From d24f5dc33ce053c34f880a6777c4180637db8589 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 23 Sep 2026 02:14:40 +0200 Subject: [PATCH 001/121] Adopt the canonical golangci-lint config (closes #90) The lint config is now the canonical file from `prompts`, which replaces the deprecated `gomodguard` with `gomodguard_v2`, so lint prints no deprecation warnings. It also turns on the `depguard` `test-support` rule. The one difference from canonical is that the deny list names vaultik's own test-only package `internal/storage/faultstore`, so shipped code cannot import it. The new config found nothing to fix in the source. Issues and PRs that pin the old `.golangci.yml` sha256 as an untouched-file check need the new one: `7122fcf0dd0ea57441374f98ebd98bb3da23decb67f9209fee5175170838fbd1`. Model: opus-5-5 --- .golangci.yml | 72 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 70 insertions(+), 2 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 26b1610..d8179d9 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,14 +10,20 @@ run: linters: default: all + enable: + # Successor to the deprecated gomodguard. Named explicitly, rather than + # left to `default: all`, because it carries the module policy below. + - gomodguard_v2 disable: # Genuinely incompatible with project patterns - exhaustruct # Requires all struct fields - - depguard # Dependency allow/block lists - godot # Requires comments to end with periods - - wsl # Deprecated, replaced by wsl_v5 - wrapcheck # Too verbose for internal packages - varnamelen # Short names like db, id are idiomatic Go + # Deprecated: the warning is attached to the old name, so it is + # silenced by disabling that name, not by enabling the successor. + - wsl # Deprecated, replaced by wsl_v5 + - gomodguard # Deprecated, replaced by gomodguard_v2 settings: lll: line-length: 88 @@ -28,6 +34,68 @@ linters: max-complexity: 15 dupl: threshold: 100 + depguard: + # Test-support code must not be compiled into the shipped binary. A + # test-support package exists to hand a test privileges the program + # itself must never have, so a file that is not a test must not import + # one. Test files, and the files inside a package whose directory name + # ends in `test`, are where that code belongs, and are exempt. + # + # The deny list below is the one part of this file a repository is + # expected to extend, and the only part it may. depguard matches an + # import path against a list of prefixes, so it cannot be told "any path + # whose last segment ends in test"; a repository's own test-support + # packages have to be named here one at a time, by full import path, + # under a module path that differs from repository to repository. Add + # them; change nothing else. + rules: + test-support: + list-mode: lax + files: + - "$all" + - "!$test" + - "!**/*test/**" + deny: + - pkg: net/http/httptest + desc: >- + Test-support code belongs in test files and in packages whose + directory name ends in test, not in the shipped binary. + - pkg: sneak.berlin/go/vaultik/internal/storage/faultstore + desc: >- + Test-support code belongs in test files and in packages whose + directory name ends in test, not in the shipped binary. + # Only decisions already recorded in the Go package defaults are + # listed here. Every entry matches the module path exactly. + gomodguard_v2: + blocked: + - module: github.com/rs/zerolog + recommendations: + - log/slog + reason: "Structured logging is stdlib log/slog." + # One entry per pre-fork module path, because the later releases + # are separate paths. A prefix match would be shorter but would + # also reach github.com/go-redis/redismock, the test double for + # the successor these entries recommend. + - module: github.com/go-redis/redis + recommendations: + - github.com/redis/go-redis/v9 + reason: "Pre-fork module; use the maintained go-redis v9." + - module: github.com/go-redis/redis/v7 + recommendations: + - github.com/redis/go-redis/v9 + reason: "Pre-fork module; use the maintained go-redis v9." + - module: github.com/go-redis/redis/v8 + recommendations: + - github.com/redis/go-redis/v9 + reason: "Pre-fork module; use the maintained go-redis v9." + - module: github.com/sergi/go-diff + recommendations: + - github.com/aymanbagabas/go-udiff + reason: "No unified diff output; use go-udiff." + - module: github.com/hexops/gotextdiff + recommendations: + - github.com/aymanbagabas/go-udiff + reason: "Unmaintained fork; use go-udiff." issues: max-issues-per-linter: 0 From 6e1f499048652d5ba61351a9272c1504dc36f136 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Mon, 28 Sep 2026 20:21:38 +0200 Subject: [PATCH 002/121] Document that migrations are supported and none are added before 1.0 (closes #68) The docs now say vaultik supports migrations. The numbered files in `internal/database/schema/` are migrations: `schema_migrations` records which have run, and opening a database applies any that have not. None are added before 1.0 because nothing is installed anywhere yet, so a schema change edits `001.sql` directly. After 1.0 each change is a new numbered file, and an existing local database is migrated when vaultik is updated. `docs/DATAMODEL.md` owns the explanation. The README caveat and roadmap entry and `AGENTS.md` policy 13 link to it. This replaces the wording from https://git.eeqj.de/sneak/vaultik/pulls/146, which said there was no upgrade path. Disclosure: `CLAUDE.md` line 33, the owner's file, changes from "do not need to support migrations" to "do not add migrations before 1.0". Model: opus-5-5 --- AGENTS.md | 18 ++++++++---------- CLAUDE.md | 2 +- README.md | 25 ++++++++++++------------- docs/DATAMODEL.md | 41 ++++++++++++++++++----------------------- 4 files changed, 39 insertions(+), 47 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 66b9c69..2f93504 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,14 +102,12 @@ Version: 2025-06-08 build files are acceptable in the root, but source code and other files should be organized in appropriate subdirectories. -13. Pre-1.0: NEVER write database migrations. There are no live databases - anywhere — every user's local index can be rebuilt from a fresh full - backup. To change the schema, edit `internal/database/schema/001.sql` - (and any code that touches the affected tables) directly; do not add new - numbered schema files. Those numbered files and the `schema_migrations` - table they populate only bootstrap a fresh database — they are not an - upgrade path. The local index is disposable until 1.0 ships and is - tagged; once 1.0 is tagged that clause expires and the question of - upgrading existing indexes returns. See [`docs/DATAMODEL.md`](docs/DATAMODEL.md) - for the full explanation. +13. Pre-1.0: NEVER add a database migration. Migrations are supported, but + nothing is installed anywhere yet, so there is nothing to migrate. To + change the schema, edit `internal/database/schema/001.sql` (and any + code that touches the affected tables) directly. After 1.0, each schema + change is a new numbered file in that directory and a released file is + never edited; an existing local database is then migrated when vaultik + is updated. See + [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations). diff --git a/CLAUDE.md b/CLAUDE.md index cec4213..7b5788e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,7 +30,7 @@ Read the rules in AGENTS.md and follow them. done provided to you in the initial instruction. Don't do part or most of the work, do all of the work until the criteria for done are met. -* We do not need to support migrations; schema upgrades can be handled by +* We do not add migrations before 1.0; schema upgrades can be handled by deleting the local state file and doing a full backup to re-create it. * When testing on a 2.5Gbit/s ethernet to an s3 server backed by 2000MB/sec SSD, diff --git a/README.md b/README.md index 9e8f862..6fb2d9c 100644 --- a/README.md +++ b/README.md @@ -559,13 +559,13 @@ complete annotated example also lives in sequentially. Restore speed is bound by single-stream throughput. * **Device nodes, named pipes, and sockets are silently skipped.** Only regular files, directories, and symlinks are backed up. -* **No upgrade path between versions.** There is no supported way to carry - an existing local index across a schema change; if the local SQLite - schema changes between versions, delete the local database (`vaultik - database delete`) and run a full backup. Remote storage is unaffected. - (The binary does embed numbered schema files and a `schema_migrations` - table to bootstrap a fresh database — see [`docs/DATAMODEL.md`](docs/DATAMODEL.md) - — but that is not an upgrade path.) +* **Before 1.0, an update can make the local index unusable.** Vaultik + supports schema migrations, but none are added before 1.0 because + there is no installed base yet. If an update leaves your local index + unusable, run `vaultik database delete` and then a full backup; remote + storage is unaffected. After 1.0, the local index is migrated when + vaultik is updated. See + [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations). * **Files that change during backup may be inconsistent.** There is no filesystem snapshot or freeze. If a file is modified between the scan and chunk phases, the backed-up copy may reflect a partial write. @@ -631,12 +631,11 @@ priority. ### infrastructure -* **Cross-version schema upgrades.** There is no upgrade path between - released versions — pre-1.0 schema changes are handled by `vaultik - database delete` plus a full re-scan (see - [`docs/DATAMODEL.md`](docs/DATAMODEL.md)). Post-1.0 we'll need a - migration story to keep existing index databases usable across - upgrades. +* **Schema migrations after 1.0.** Migrations are supported, but none + are added before 1.0 because there is no installed base yet. After + 1.0, each schema change is a new migration, so an existing local + index is migrated when vaultik is updated (see + [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations)). * **Storage backend coverage tests.** S3, file://, and rclone:// all share the Storer interface but the rclone path is the least exercised in CI. diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index fdb86cf..7338c0d 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -6,33 +6,28 @@ Vaultik uses a local SQLite database to track file metadata, chunk mappings, and **Important Notes:** -This section is the authoritative explanation of the schema/migration story; -other documents (the README and `AGENTS.md`) link here. - -- **No upgrade path between versions (pre-1.0)**: Vaultik has no supported way to - carry an existing local index across a schema change. The index is disposable - — if the on-disk schema changes between versions, delete the local SQLite - database (`vaultik database delete`) and run a full backup. Remote storage is - unaffected; the new index re-deduplicates against existing remote blobs. This - is the standing project policy, and it is separate from the schema bootstrap - described next. -- **Schema bootstrap**: a fresh database is populated from numbered SQL files - embedded in the binary under `internal/database/schema/`. `000.sql` creates the - `schema_migrations` table; `001.sql` creates the application tables. On opening - a database the code applies each numbered file that has not yet run and records - its version in `schema_migrations`. This bootstraps a new database; it does not - upgrade an existing one between released versions. -- **Changing the schema (pre-1.0)**: edit `internal/database/schema/001.sql` (and - the code that touches the affected tables) directly. Do not add new numbered - files — there is no installed base to migrate. -- **Disposability expires at 1.0**: the index is treated as disposable only until - 1.0 ships and is tagged. Once 1.0 is tagged that clause expires and the - question of upgrading existing indexes returns. It is deliberately left open - here. - **Version Compatibility**: In rare cases, you may need to use the same version of Vaultik to restore a backup as was used to create it. This ensures compatibility with the metadata format stored in S3. +## Schema Migrations + +Vaultik supports schema migrations. They are the numbered SQL files in +`internal/database/schema/`, embedded in the binary: `000.sql` creates the +`schema_migrations` table, which records each migration that has run, and +`001.sql` creates the application tables. `database.New` opens a database and +applies, in order, every migration that database has not yet recorded. + +**Before 1.0** no migrations are added, because nothing is installed anywhere +yet. A schema change edits `001.sql` (and the code that uses the affected +tables) directly. A local database created before the change has already +recorded `001.sql` as run, so it keeps the old schema and can become unusable; +`vaultik database delete` followed by a full backup rebuilds it. + +**After 1.0** each schema change is a new numbered file, so an existing local +database is migrated the first time an updated vaultik opens it. A file that +has shipped in a release is never edited. + ## Database Tables ### 1. `files` From b30e79ee45a9b63be242c65bad4e49cd07b6dd85 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 1 Oct 2026 20:24:30 +0200 Subject: [PATCH 003/121] Run the disk-full restore test again (closes #207) TestRestoreReportsDiskFull was skipped pending https://git.eeqj.de/sneak/vaultik/issues/163, which is closed. The skip and its "skipped until" wording are removed. Restore is unchanged. With the skip removed the test failed because restore succeeded: its simulated full disk capped only Create, but restore now opens each file with OpenFile, so nothing was capped. It now caps OpenFile, and only for files under the restore target: restore also writes the decrypted metadata database under $TMPDIR through the same filesystem, and capping that would fail the restore before any file reached the target. Judgement call: the test was corrected, not restore; both assertions are unchanged. Model: opus-5-5 --- internal/vaultik/fault_injection_test.go | 39 +++++++++++------------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/internal/vaultik/fault_injection_test.go b/internal/vaultik/fault_injection_test.go index dd02574..055fcfd 100644 --- a/internal/vaultik/fault_injection_test.go +++ b/internal/vaultik/fault_injection_test.go @@ -680,18 +680,10 @@ func faultScannerFactory( // Scenario 5: the restore target runs out of space mid-file. Restore // must fail with an out-of-space error, and must not leave a truncated -// file at the target path presenting as a complete restore. Restore -// today writes each file straight to its final path and does not remove -// it when a write fails, so the truncated file survives; deleting it is -// tracked by https://git.eeqj.de/sneak/vaultik/issues/163. Skipped until -// that lands, so the destination assertion below is recorded rather than -// dropped. +// file at the target path presenting as a complete restore. // //nolint:paralleltest // installs the global logger via log.Initialize func TestRestoreReportsDiskFull(t *testing.T) { - t.Skip("blocked on https://git.eeqj.de/sneak/vaultik/issues/163: " + - "a disk-full write leaves a truncated file at the target path " + - "instead of removing it") log.Initialize(log.Config{}) osFS := afero.NewOsFs() @@ -717,10 +709,10 @@ func TestRestoreReportsDiskFull(t *testing.T) { id := fullFaultBackup(ctx, t, osFS, inner, cfg, repos, dataDir, dbPath, "diskfull") require.NoError(t, db.Close()) - // Restore onto a filesystem that allows only a few bytes of file - // content: enough to create files, far too little to hold them. + // Restore onto a target that allows only a few bytes of file content: + // enough to create files, far too little to hold them. budget := int64(8) - quota := "aFS{Fs: osFS, remaining: &budget} + quota := "aFS{Fs: osFS, dir: restoreDir, remaining: &budget} v := newReaderVaultik(ctx, cfg, inner, nil, quota) err = v.Restore(&vaultik.RestoreOptions{SnapshotID: id, TargetDir: restoreDir}) @@ -754,21 +746,26 @@ func assertRestoredTree( // budget is exhausted, mirroring a real ENOSPC. var errNoSpace = errors.New("no space left on device") -// quotaFS is an afero.Fs whose files may write only a fixed total number -// of content bytes before failing, simulating a full restore target. It -// wraps the interface so every method except Create delegates to the -// real filesystem; only file writes are capped. +// quotaFS is an afero.Fs on which files opened under dir may write only +// a fixed total number of content bytes before failing, simulating a full +// restore target. Every other method, and every file outside dir, goes +// straight to the real filesystem: restore also writes the decrypted +// metadata database under $TMPDIR through this filesystem, and capping +// that would fail the restore before it wrote anything to the target. type quotaFS struct { afero.Fs + dir string remaining *int64 } -//nolint:ireturn // afero.Fs.Create's signature requires returning afero.File. -func (q *quotaFS) Create(name string) (afero.File, error) { - f, err := q.Fs.Create(name) - if err != nil { - return nil, err +//nolint:ireturn // afero.Fs.OpenFile's signature requires returning afero.File. +func (q *quotaFS) OpenFile( + name string, flag int, perm os.FileMode, +) (afero.File, error) { + f, err := q.Fs.OpenFile(name, flag, perm) + if err != nil || !strings.HasPrefix(name, q.dir) { + return f, err } return "aFile{File: f, remaining: q.remaining}, nil From 584444b6198098976445b1c41c95ef176293d997 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 1 Oct 2026 21:41:41 +0200 Subject: [PATCH 004/121] List only after-1.0 work in the README roadmap (closes #208) The README roadmap and the TODO.md Next Step still described finished 1.0 work as remaining. The roadmap now lists only work planned after 1.0. Its security item says the code was reviewed before 1.0, every bug found was fixed, and the accepted risks are listed; an outside audit stays as after-1.0 work. The error-condition item is gone because every failure case it listed has a fault-injection test. Daemon mode is added. TODO.md says the 1.0 work is complete on next and that merging and tagging are the owner's. Judgement call: dropped the human-readable size flags item; no command flag takes a raw-integer size. Model: opus-5-5 --- README.md | 28 +++++++++++++--------------- TODO.md | 16 +++++++--------- 2 files changed, 20 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 6fb2d9c..8006bd1 100644 --- a/README.md +++ b/README.md @@ -577,22 +577,18 @@ complete annotated example also lives in ## roadmap -Items still to do before / shortly after 1.0. Loosely ordered by -priority. +Work planned after 1.0. Loosely ordered by priority. ### correctness and operability -* **Security audit of the encryption implementation.** Pre-1.0 - blocker if we're advertising "secure" at the top of this README. - age + zstd + content-defined chunking is mostly off-the-shelf - pieces, but the seams (key handling, recipient parsing, manifest - trust boundary, restore-time identity validation) need an outside - read. -* **Error-condition tests.** Today's coverage is the happy path - plus a few specific regressions. Need fault-injection coverage: - network failures mid-blob, disk-full during restore, corrupted / - truncated / missing blobs, partial uploads, kill -9 between - manifest and db.zst.age writes. +* **Outside security audit.** Before 1.0 the encryption and + blob-generation code was reviewed: every bug the review found was + fixed, and the risks it accepted are listed in + [Accepted Risks](docs/REPOSTRUCTURE.md#accepted-risks). No outside + audit has been done. age + zstd + content-defined chunking + is mostly off-the-shelf pieces, but the seams (key handling, + recipient parsing, manifest trust boundary, restore-time identity + validation) need an outside read. * **Verify restored content end-to-end in CI.** The current integration test does this for a small synthetic snapshot but not at scale. A nightly job against a multi-GB representative @@ -615,13 +611,15 @@ priority. doesn't resume from where it stopped or skip already-present files. A `--resume` mode that checks targets before fetching blobs would matter for very large restores. +* **Daemon mode.** A long-running mode that watches for file + changes so frequent backups, such as hourly, skip the full scan. + It adds little for the usual runs from cron every 12 to 36 hours. + See [issue #204](https://git.eeqj.de/sneak/vaultik/issues/204). ### usability * **Man pages and richer `--help` examples.** Cobra generates basic help; man pages would be a separate target. -* **`--bwlimit` style human-readable size flags** across the - command surface where they're currently raw integers. * **`vaultik snapshot diff `** — show which files changed between two snapshots without restoring either. * **Status reporting hook for `--cron`.** When a backup fails diff --git a/TODO.md b/TODO.md index feb0f2a..c490f04 100644 --- a/TODO.md +++ b/TODO.md @@ -14,14 +14,11 @@ pre-1.0 # Next Step -Define the remaining scope for the first tagged release under the 1.0.0 -milestone, then cut that tag. The mechanism to cut it now exists and is -exercised; what is left is the scope decision, which is the owner's. -This step deliberately names one version number: it previously said -"cut v0.1.0" while the `Makefile` baked in `1.0.0-rc.1` and the issue -milestone said 1.0.0, and three different answers to "what is the next -release" is exactly the contradiction -[issue #65](https://git.eeqj.de/sneak/vaultik/issues/65) was filed over. +The 1.0 work is complete on `next`: the scope settled on +[issue #125](https://git.eeqj.de/sneak/vaultik/issues/125) was the work +already planned for 1.0, and all of it has landed. The mechanism to cut +the tag exists and is exercised; what is left is merging `next` to +`main` and tagging, both the owner's. # Completed Steps @@ -693,4 +690,5 @@ release" is exactly the contradiction # Future Steps -None queued; the release-scoping item is now the Next Step. +Work planned after 1.0 is listed in the README +[roadmap](README.md#roadmap). From 070090124a419546fed33812fdb09ee624821b49 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Fri, 2 Oct 2026 10:04:14 +0200 Subject: [PATCH 005/121] Stamp the tag or short commit in a plain docker build (closes #211) A plain `docker build .` stamped `dev`: `.dockerignore` left out `.git` and the Dockerfile defaulted VERSION to `dev`. `.dockerignore` now sends `.git` without `.git/config`. Given no build arguments, the builder stamps `git describe --tags --always` and the commit and date from git, and fails if `.git` is present but yields no version. The empty CHECK_EPOCH refusal is gone so the plain build succeeds. `script/version` now prints `git describe --tags --always --dirty`, so make, the scripts and a plain build agree. `vaultik version` treats the short commit, tag-N-gHASH forms and any version ending in `-dirty` as development builds, so they keep the development-build notice. Model: opus-5-5 --- .dockerignore | 64 +++++++++++++++++++++++++- .goreleaser.yaml | 4 +- Dockerfile | 58 +++++++++++------------ Makefile | 4 +- README.md | 66 ++++++++++++++++----------- cmd/vaultik/dockerversion_test.go | 59 +++++++++++++----------- cmd/vaultik/lintdocker_test.go | 15 +++--- internal/globals/globals.go | 28 ++++++++---- internal/globals/globals_test.go | 22 ++++++--- script/cibuild | 18 ++++---- script/docker | 23 ++++------ script/version | 76 +++++++------------------------ 12 files changed, 241 insertions(+), 196 deletions(-) diff --git a/.dockerignore b/.dockerignore index fc84c76..0228778 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,65 @@ -.git +# .dockerignore does NOT use .gitignore semantics. Docker matches with +# moby/patternmatcher: filepath.Match plus `**`, so `*` does not cross +# `/` and an unprefixed pattern is anchored at the context root. Every +# depth-independent pattern therefore needs `**/`, or `config/.env` and +# `certs/server.key` still ship while this file reads as solved. Only +# genuinely root-anchored entries go unprefixed. Never transplant these +# into .gitignore, where `**/` is wrong. +# +# Matching is case-sensitive, so secrets use character ranges rather +# than an ALL-CAPS twin, which would still miss `Server.Key`. +# +# Extend with this repo's own host-built artifacts, written anchored: +# `/myapp`, never `**/myapp`, which also matches `cmd/myapp/` and +# deletes the package directory from the context. + +# .git is sent without its config. Without a VERSION build argument the +# stage that compiles runs `git describe --tags --always` on .git, which +# does not need .git/config; that file can hold a credential, such as a +# password in a remote URL or the token the CI checkout step stores there. +.git/config + +# Agent scratch: one full checkout of the repo per in-flight agent. +# Anchored because it occurs once where agents run at the repo root. +# KNOWN GAP: a repo running agents in subdirectories still ships +# `services/api/.claude/` and must add its own anchored entry. +.claude + +# Environment files. `*.env` covers bare `.env` and the `prod.env` +# convention. Re-include a committed template with a negation if the +# build needs one: `!docs/example.env`. +**/*.[eE][nN][vV] +**/.[eE][nN][vV].* +**/.[eE][nN][vV][rR][cC] + +# Private keys and the bundles carrying them. Public certificates +# (*.crt, *.cer) are deliberately absent: they are legitimate inputs. +**/*.[pP][eE][mM] +**/*.[kK][eE][yY] +**/*.[pP]12 +**/*.[pP][fF][xX] +**/[iI][dD]_[rR][sS][aA] +**/[iI][dD]_[dD][sS][aA] +**/[iI][dD]_[eE][cC][dD][sS][aA] +**/[iI][dD]_[eE][dD]25519 + +# Dependencies: restored inside the image, never copied in. +**/node_modules + +# OS metadata. +**/.DS_Store +**/Thumbs.db + +# Editor state: never a build input, and it churns COPY. +**/*.swp +**/*.swo +**/*~ +**/*.bak +**/.idea +**/.vscode +**/*.sublime-* + +# This repo's own entries. .gitea *.md LICENSE @@ -7,4 +68,3 @@ dist .tool coverage.out coverage.html -.DS_Store diff --git a/.goreleaser.yaml b/.goreleaser.yaml index d316d84..7f168b9 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -47,9 +47,7 @@ checksum: # A snapshot is not a release and must not name itself like one. The # previous `{{ incpatch .Version }}-next` derived a plausible-looking # release number from the last tag -- and with no tags in the repo at -# all, from goreleaser's fabricated v0.0.0. This produces the same -# string script/version produces for an untagged build, so a snapshot -# binary and a `make vaultik` binary of the same clean commit agree. +# all, from goreleaser's fabricated v0.0.0. snapshot: version_template: "dev-{{ slice .FullCommit 0 12 }}" diff --git a/Dockerfile b/Dockerfile index 1dcc46a..6d4eb31 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,10 +20,10 @@ # golang:1.26.1-alpine, 2026-03-17 FROM golang:1.26.1-alpine@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 AS builder -# Build tooling: make, plus a C toolchain because `go test -race` needs cgo. -# The sqlite driver is pure Go (modernc.org/sqlite), so no sqlite library or -# CLI is required. -RUN apk add --no-cache make build-base +# Build tooling: make, plus a C toolchain because `go test -race` needs cgo, +# and git, which derives the version below. The sqlite driver is pure Go +# (modernc.org/sqlite), so no sqlite library or CLI is required. +RUN apk add --no-cache make build-base git WORKDIR /src @@ -47,48 +47,44 @@ COPY . . # unreferenced-ARG handling staying as it is. It also puts the epoch in # the build log, where a reader can see the layer was keyed fresh. # -# The guard is what makes a build that omits --build-arg fail instead of -# lie. An unset ARG is an empty string, and an empty string is a -# perfectly stable cache key: without the guard the first such build -# runs the checks and every one after it on an unchanged tree replays -# these layers from cache, executes nothing, and still exits 0. Failed -# steps are never cached, so the guard fails on EVERY invocation rather -# than once -- a bare `docker build .` is a loud error, not a quiet -# green. Do not give CHECK_EPOCH a default value; a default would -# satisfy the guard with a constant and restore the hole. +# A build that passes no CHECK_EPOCH, such as a plain `docker build .`, +# keys these layers on the empty string, so rebuilding an unchanged +# checkout replays them from cache and runs nothing. Only the scripts' +# builds mean the checks executed. # # Everything above this line (apk, go.mod, `go mod download`) is # deliberately outside the busted range and keeps caching. ARG CHECK_EPOCH -RUN [ -n "$CHECK_EPOCH" ] || exit 1 RUN echo "check epoch: ${CHECK_EPOCH}" && make fmt-check RUN echo "check epoch: ${CHECK_EPOCH}" && make test -# Version, commit and build date are computed on the host by -# script/docker and script/cibuild (where .git exists) and passed in as -# build args. The build context excludes .git (see .dockerignore), so -# the build cannot derive them itself: it used to try, with `git -# rev-parse` inside this stage, and always got "unknown". VERSION comes -# from script/version, the source of truth shared with the Makefile, so -# it carries the same tag / dev- / -dirty rules and a Docker image -# reports the same string a local build of the same tree would. -# -# The defaults are the fallback for a bare `docker build .` that passes -# none of them: an unset arg would otherwise stamp an empty string and -# produce an image that cannot report its own version, commit or date. -# They match what an out-of-git build reports elsewhere. +# Version, commit and build date: the build args when given (script/docker +# and script/cibuild pass the ones they compute on the host), otherwise +# derived from the .git in the build context. The version is then `git +# describe --tags --always`: the tag on a tagged commit, tag-N-gHASH after +# one, the short commit when no tag is reachable. A context that carries +# .git and still yields no version fails the build; one without .git, as +# from a source tarball, stamps "dev" and an "unknown" commit and date. # # These ARGs sit here, after the checks, rather than at the top of the # stage: every commit changes their values, and a value change # invalidates all layers below the ARG. Declared up top they would bust # `go mod download`; here they only rekey this build layer, which the # COPY of the sources above already rebuilds on any change anyway. -ARG VERSION=dev -ARG COMMIT=unknown -ARG COMMIT_DATE=unknown +ARG VERSION +ARG COMMIT +ARG COMMIT_DATE # Build (pure Go, no CGO required since we use modernc.org/sqlite) -RUN CGO_ENABLED=0 go build -ldflags "-X 'sneak.berlin/go/vaultik/internal/globals.Version=${VERSION}' -X 'sneak.berlin/go/vaultik/internal/globals.Commit=${COMMIT}' -X 'sneak.berlin/go/vaultik/internal/globals.CommitDate=${COMMIT_DATE}'" -o /vaultik ./cmd/vaultik +RUN version="${VERSION:-$(git describe --tags --always || echo dev)}"; \ + if [ -e .git ] && { [ -z "$version" ] || [ "$version" = dev ] || \ + [ "$version" = unknown ]; }; then \ + echo "the build context carries .git but yields no version" >&2; \ + exit 1; \ + fi; \ + commit="${COMMIT:-$(git rev-parse HEAD || echo unknown)}"; \ + commit_date="${COMMIT_DATE:-$(git show -s --format=%cs HEAD || echo unknown)}"; \ + CGO_ENABLED=0 go build -ldflags "-X 'sneak.berlin/go/vaultik/internal/globals.Version=${version}' -X 'sneak.berlin/go/vaultik/internal/globals.Commit=${commit}' -X 'sneak.berlin/go/vaultik/internal/globals.CommitDate=${commit_date}'" -o /vaultik ./cmd/vaultik # Runtime stage # alpine:3.21, 2026-02-25 diff --git a/Makefile b/Makefile index 17f714a..d0e60c2 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ .PHONY: all bootstrap setup check test lint lint-fix fmt fmt-check build clean deps test-coverage local install release release-snapshot docker hooks -# Version number, derived from git by script/version -- the tag when -# HEAD is on one, otherwise dev-. This used to be a hardcoded +# Version number, derived from git by script/version (`git describe +# --tags --always --dirty`). This used to be a hardcoded # constant, which meant every local build claimed to be a release that # had never been tagged. VERSION := $(shell script/version) diff --git a/README.md b/README.md index 8006bd1..0bab63c 100644 --- a/README.md +++ b/README.md @@ -770,8 +770,9 @@ them. We provide: * `script/projectname` — print the project name (used for the Docker image tag) * `script/version` — print the version string to bake into the binary. - The `Makefile`'s `LDFLAGS` call this; it is the single source of truth - for the version. See [releasing](#releasing) for the rules. + The `Makefile`'s `LDFLAGS` call this, and `script/docker` and + `script/cibuild` pass its output to the image build. See + [releasing](#releasing) for the rules. * `script/install-goreleaser` — install the pinned `goreleaser` into `.tool/bin` from a sha256-verified release archive. Idempotent, and called by `script/bootstrap`; the release workflow calls it directly @@ -863,16 +864,18 @@ them. We provide: module layers sit above the `ARG` and still cache, so a build is not cold. - A build that supplies no `CHECK_EPOCH` — a bare `docker build .` or - `docker build -f Dockerfile.lint .` — fails rather than lying. An - unset `ARG` is an empty string and an empty string is a stable cache - key, so without a guard such a build would serve every check layer - from cache, execute nothing, and still exit 0. Each file therefore - asserts the value is non-empty before running anything, and because - failed steps are never cached that assertion fires on every - invocation rather than once. Use `script/lint`, `script/docker` or - `script/cibuild`, which pass the arg; a bare `docker build` is a loud - error. + A `docker build -f Dockerfile.lint .` that supplies no `CHECK_EPOCH` + fails rather than lying. An unset `ARG` is an empty string and an + empty string is a stable cache key, so without a guard such a build + would serve the lint layer from cache, execute nothing, and still exit + 0. `Dockerfile.lint` therefore asserts the value is non-empty before + running anything, and because failed steps are never cached that + assertion fires on every invocation rather than once. The product + `Dockerfile` has no such guard, because a plain `docker build .` must + succeed: without `CHECK_EPOCH`, rebuilding an unchanged checkout + replays its check layers from cache. Use `script/lint`, + `script/docker` or `script/cibuild`, which pass the arg, when the + checks must run. * `script/precommit` — pre-commit gate: `go mod tidy` + `go fmt` (must not change files), then `script/check` * `script/install-precommit` — install the git pre-commit hook that @@ -883,24 +886,33 @@ them. We provide: ### version numbers The version a binary reports comes from git, not from a constant in a -file. `script/version` decides it, and everything that stamps a binary -agrees with it: +file. It is `git describe --tags --always --dirty`, which +`script/version` runs for the `Makefile`, `script/docker` and +`script/cibuild`: -* `HEAD` is exactly on a tag → that tag with a leading `v` stripped, so - the tag `v1.0.0` produces `vaultik 1.0.0`, matching the archive name - `vaultik_1.0.0_linux_amd64.tar.gz`. `goreleaser` strips the prefix the - same way. -* anything else → `dev-<12 chars of the commit sha>`. -* either, with uncommitted changes to tracked files → a `-dirty` +* `HEAD` is exactly on a tag → that tag, such as `v1.0.0`. +* a commit after a tag → `--g`. +* no tag reachable → the short commit sha. +* any of these, with uncommitted changes to tracked files → a `-dirty` suffix, because a modified checkout of a tag is not that tag. -A build that is not a release never names itself like one. `vaultik -version` says so in as many words on a development build, and -`goreleaser --snapshot` stamps the same `dev-` string rather than -inventing the next patch number. If `script/version` cannot be run at -all, `make` stops with an error instead of building an unversioned -binary, and a binary that somehow carries an empty version string still -reports itself as a development build. +A `docker build .` of a clone, with no build arguments, runs the same +`git describe` (without `--dirty`) on the `.git` in its build context, +so it stamps the same value for a clean commit; the build fails if the +context carries `.git` and no version comes out. A binary built without +git metadata reports `dev`. + +`goreleaser` stamps a release binary with the tag minus its leading +`v`, so the tag `v1.0.0` produces `vaultik 1.0.0`, matching the archive +name `vaultik_1.0.0_linux_amd64.tar.gz`. `goreleaser --snapshot` stamps +`dev-<12 chars of the commit sha>` rather than inventing the next patch +number. `vaultik version` calls a build a development build when its +version is `dev`, `dev-`, the short commit sha or +`--g`, with or without `-dirty`; only a plain tag, +such as `v1.0.0` or `1.0.0`, is a release. If `script/version` cannot +be run at all, `make` stops with an error instead of building an +unversioned binary, and a binary that somehow carries an empty version +string still reports itself as a development build. ### cutting a release diff --git a/cmd/vaultik/dockerversion_test.go b/cmd/vaultik/dockerversion_test.go index f77d274..d1ee2df 100644 --- a/cmd/vaultik/dockerversion_test.go +++ b/cmd/vaultik/dockerversion_test.go @@ -11,9 +11,10 @@ import ( // This file guards the version stamping of the product image (issue // #75). The failure it protects against is silent: the image still // builds and runs, but `vaultik version` inside it reports "commit: -// unknown", so an operator cannot tell which source produced a given -// backup. .dockerignore excludes .git, so the build cannot derive the -// commit itself; the values must be computed on the host and passed in. +// unknown" or a version of "dev", so an operator cannot tell which +// source produced a given backup. The build takes the values as build +// args, which script/docker computes on the host, and otherwise derives +// them from the .git in its context. // // These are parses of the committed files, for the same reason the lint // guards next door are: shelling out to docker would nest a build @@ -32,35 +33,41 @@ func versionArgs() []string { } // TestProductDockerfileTakesVersionAsBuildArgs fails unless the build -// declares each version arg and stamps it into the binary by ldflag -// reference, rather than computing it in the container. +// declares each version arg, with no default, and stamps it into the +// binary whenever it is given, ahead of the value derived in the +// container. func TestProductDockerfileTakesVersionAsBuildArgs(t *testing.T) { t.Parallel() found := instructions(t, productDockerfile) for _, arg := range versionArgs() { - require.GreaterOrEqual(t, indexOf(found, "ARG "+arg), 0, - "%s must declare `ARG %s` so the host can pass it in", - productDockerfile, arg) + require.Contains(t, found, "ARG "+arg, + "%s must declare `ARG %s`, with no default, so the host can"+ + " pass it in", productDockerfile, arg) assertLdflagReferences(t, found, arg) } } -// TestProductDockerfileDoesNotDeriveVersionItself is the anti-regression -// for the original defect: the container ran `git rev-parse`, but .git -// is not in the build context, so it always resolved to "unknown". No -// git command may reach into a build that cannot see the history. -func TestProductDockerfileDoesNotDeriveVersionItself(t *testing.T) { +// TestProductDockerfileDerivesVersionFromGit fails unless a build given +// no VERSION, such as a plain `docker build .` of a clone, takes it from +// `git describe` of the .git in its context, and fails rather than +// stamp "dev" when that .git yields no version. +func TestProductDockerfileDerivesVersionFromGit(t *testing.T) { t.Parallel() - text := instructionText(readRepoFile(t, productDockerfile)) + found := instructions(t, productDockerfile) - assert.NotContains(t, text, "git ", - "%s must not run git: .git is excluded from the build context, so"+ - " any value it derives is wrong. Pass version, commit and date"+ - " in as build args instead.", productDockerfile) + buildAt := indexContaining(found, "go build") + require.GreaterOrEqual(t, buildAt, 0, "%s must build", productDockerfile) + + assert.Contains(t, found[buildAt], "git describe --tags --always", + "%s must derive the version from git when no VERSION is given", + productDockerfile) + assert.Contains(t, found[buildAt], "[ -e .git ]", + "%s must fail when the context carries .git but yields no version", + productDockerfile) } // TestDockerScriptComputesVersionOnTheHost fails unless script/docker @@ -78,25 +85,25 @@ func TestDockerScriptComputesVersionOnTheHost(t *testing.T) { } assert.Contains(t, script, "/version", - "%s must take VERSION from script/version, the source of truth"+ - " shared with the Makefile", dockerScript) + "%s must take VERSION from script/version, as the Makefile does", + dockerScript) } -// assertLdflagReferences fails unless some build instruction stamps the -// named variable from the ARG (a ${arg} reference), not from a value -// computed inside the container. +// assertLdflagReferences fails unless the build instruction uses the +// named ARG whenever it is given (a ${arg:- reference), so a value +// passed in is not overridden by one derived inside the container. func assertLdflagReferences(t *testing.T, found []string, arg string) { t.Helper() for _, instruction := range found { if strings.HasPrefix(instruction, "RUN ") && strings.Contains(instruction, "go build") && - strings.Contains(instruction, "${"+arg+"}") { + strings.Contains(instruction, "${"+arg+":-") { return } } assert.Fail(t, "version arg is declared but never stamped", - "the go build in %s must reference ${%s} in its ldflags, or the"+ - " arg is passed and discarded", productDockerfile, arg) + "the go build in %s must use ${%s:-...}, or the arg is passed and"+ + " discarded", productDockerfile, arg) } diff --git a/cmd/vaultik/lintdocker_test.go b/cmd/vaultik/lintdocker_test.go index 07e8452..fa620ce 100644 --- a/cmd/vaultik/lintdocker_test.go +++ b/cmd/vaultik/lintdocker_test.go @@ -152,20 +152,21 @@ func TestLintDockerfileVerifiesTheLinterConfig(t *testing.T) { assertEpochExpandedInto(t, found, verify) } -// TestProductDockerfileCannotBeCachedGreen holds the same line for the -// checks that remain in the product image build. -func TestProductDockerfileCannotBeCachedGreen(t *testing.T) { +// TestProductDockerfileKeysChecksOnTheEpoch holds the same line for the +// checks that remain in the product image build, but without the guard: +// a plain `docker build .` with no build arguments must succeed. +func TestProductDockerfileKeysChecksOnTheEpoch(t *testing.T) { t.Parallel() found := instructions(t, productDockerfile) argAt := indexOf(found, checkEpochARG) require.GreaterOrEqual(t, argAt, 0, - "%s must declare `%s` with no default value", - productDockerfile, checkEpochARG) + "%s must declare `%s`", productDockerfile, checkEpochARG) - assert.GreaterOrEqual(t, indexOf(found, checkEpochGuard), argAt, - "%s must guard against an empty CHECK_EPOCH", productDockerfile) + assert.Equal(t, -1, indexOf(found, checkEpochGuard), + "%s must not refuse an empty CHECK_EPOCH: a plain `docker build .`"+ + " must succeed", productDockerfile) assertEpochExpandedInto(t, found[argAt:], "make fmt-check") assertEpochExpandedInto(t, found[argAt:], "make test") diff --git a/internal/globals/globals.go b/internal/globals/globals.go index 09233f9..fd00834 100644 --- a/internal/globals/globals.go +++ b/internal/globals/globals.go @@ -3,6 +3,7 @@ package globals import ( + "regexp" "strings" "time" ) @@ -10,12 +11,11 @@ import ( // Appname is the application name, populated from main(). var Appname = "vaultik" //nolint:gochecknoglobals // set via -ldflags at build time -// DevVersion is the version a binary reports when it was not built -// from a tagged commit. script/version emits either this exact string -// (outside a git checkout) or this string followed by "-" and the -// commit it was built from, and goreleaser's snapshot template matches -// that shape. It is deliberately not a number: a build that is not a -// release must not name itself like one. +// DevVersion is the version a binary reports when it was built without +// git metadata: script/version emits it outside a git checkout, and an +// unstamped `go build` keeps it. goreleaser's snapshot template stamps +// it followed by "-" and the commit it was built from. It is +// deliberately not a number. const DevVersion = "dev" // Version is the application version, populated from main(). @@ -60,9 +60,12 @@ func New() (*Globals, error) { } // IsDevVersion reports whether v names a development build rather than -// a release. Both "dev" and "dev-" (and its "-dirty" variant) -// count: a caller that compares against "dev" exactly would treat every -// commit-stamped development build as a release. +// a release. "dev" and goreleaser's snapshot "dev-" count, and so +// does what `git describe --tags --always --dirty` gives a make or +// docker build of an untagged commit: the bare short commit, or +// tag-N-gHASH on a commit after a tag. Any version ending in "-dirty" +// counts, a modified checkout of a tag ("v1.0.0-dirty") included. +// A plain tag such as "v1.0.0" or "1.0.0" is a release. // // The empty string counts too. Nothing that knows its version reports // no version, so an empty Version means the stamping failed, and the @@ -71,7 +74,12 @@ func New() (*Globals, error) { // case; this is the second line of defence, for a binary linked by // something other than the Makefile. func IsDevVersion(v string) bool { - return v == "" || v == DevVersion || strings.HasPrefix(v, DevVersion+"-") + if v == "" || v == DevVersion || strings.HasPrefix(v, DevVersion+"-") || + strings.HasSuffix(v, "-dirty") { + return true + } + + return regexp.MustCompile(`^(.+-[0-9]+-g)?[0-9a-f]+$`).MatchString(v) } // shortCommitLen is the number of commit-hash characters ShortCommit keeps. diff --git a/internal/globals/globals_test.go b/internal/globals/globals_test.go index e0b7c2e..7012e60 100644 --- a/internal/globals/globals_test.go +++ b/internal/globals/globals_test.go @@ -34,10 +34,11 @@ func TestGlobalsNew(t *testing.T) { } // TestIsDevVersion covers the boundary that matters: everything -// script/version and goreleaser's snapshot template can emit for an -// untagged build must be recognised as a development build, and a real -// tag must not be. A plain equality check against "dev" used to decide -// this, which classified every commit-stamped dev build as a release. +// script/version, a plain docker build and goreleaser's snapshot +// template can emit for an untagged build must be recognised as a +// development build, and a real tag must not be. A plain equality check +// against "dev" used to decide this, which classified every +// commit-stamped dev build as a release. func TestIsDevVersion(t *testing.T) { t.Parallel() @@ -49,8 +50,17 @@ func TestIsDevVersion(t *testing.T) { {"dev", true}, {"dev-b6e4a218a39e", true}, {"dev-b6e4a218a39e-dirty", true}, - // What a tagged build produces (script/version strips the - // leading "v", matching goreleaser's .Version). + // What `git describe --tags --always --dirty` produces with no + // tag reachable, and on a commit after a tag. + {"877eb2f", true}, + {"877eb2f-dirty", true}, + {"v1.0.0-3-g877eb2f", true}, + {"v1.0.0-3-g877eb2f-dirty", true}, + {"1.0.0-rc.1-12-g877eb2f", true}, + // A tagged commit with uncommitted changes is not that tag. + {"v1.0.0-dirty", true}, + // What a tagged build produces (goreleaser's .Version strips + // the leading "v"; script/version keeps it). {"1.0.0", false}, {"0.1.0", false}, {"1.0.0-rc.1", false}, diff --git a/script/cibuild b/script/cibuild index 339ee49..032fae6 100755 --- a/script/cibuild +++ b/script/cibuild @@ -24,9 +24,11 @@ main() { # value is what forces those layers to re-run: without it an # unchanged tree replays them from cache, the checks never execute, # and the build still exits 0. Each ARG sits immediately above the - # check RUNs, so dependency and module layers still cache. Both - # Dockerfiles also refuse to build at all when CHECK_EPOCH is empty, - # so a missing value fails loudly here rather than passing quietly. + # check RUNs, so dependency and module layers still cache. + # Dockerfile.lint also refuses to build at all when CHECK_EPOCH is + # empty, so a missing value fails its build loudly rather than passing + # quietly; the product Dockerfile does not, because a plain `docker + # build .` must succeed. # # The value must be unique per invocation, not per second. `date +%s` # is second-granular, so two concurrent invocations in the same @@ -57,12 +59,10 @@ main() { --build-arg CHECK_EPOCH="$epoch" -f Dockerfile.lint . # Version, commit and build date are computed here on the host, the - # same way script/docker does, and passed into the product build so - # the CI-built image reports its real source. The build context - # excludes .git (see .dockerignore), so the build cannot derive them - # itself; without these it would stamp the Dockerfile's dev/unknown - # fallbacks. VERSION comes from script/version, the source of truth - # shared with the Makefile. + # same way script/docker does, and passed into the product build, + # where they take precedence over what the build would derive from + # the .git in its context. VERSION comes from script/version, as in + # the Makefile. version="$("$ROOT/script/version")" commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" commit_date="$(git show -s --format=%cs HEAD 2>/dev/null || echo unknown)" diff --git a/script/docker b/script/docker index b7f29bd..d685746 100755 --- a/script/docker +++ b/script/docker @@ -1,7 +1,8 @@ #!/bin/sh # script/docker: build the Docker image tagged with the project name. -# Identical in all repos; the tag comes from script/projectname. -# Generic: needs no adaptation. +# The tag comes from script/projectname. Unlike the canonical copy in +# sneak/prompts, it passes a fresh CHECK_EPOCH instead of --no-cache, and +# COMMIT and COMMIT_DATE as well as VERSION. # # This builds the PRODUCT image only, and the product Dockerfile has no # lint stage: linting lives in Dockerfile.lint and is run by @@ -21,19 +22,15 @@ main() { # comments there. This script is not the CI gate, but a local build # is almost always warm, so without this it would report a green the # tree had not earned and the two entrypoints would disagree about - # whether the tree is clean. The Dockerfile now refuses to build - # without a non-empty value, so this is required, not optional. + # whether the tree is clean. epoch="$(date +%s%N)$$" - # Version, commit and build date are computed here on the host, - # where .git exists, and passed into the build. The build context - # excludes .git (see .dockerignore), so the container cannot derive - # them itself -- it used to try and always got "unknown", giving - # every image a "commit: unknown" it could not be traced from. - # VERSION comes from script/version, the source of truth shared with - # the Makefile, so a Docker build reports the same string (tag, - # dev-, or a -dirty variant) that a local build of the same - # tree would. + # Version, commit and build date are computed here on the host and + # passed into the build, where they take precedence over what the + # build would derive from the .git in its context. VERSION comes + # from script/version, as in the Makefile, so the image reports the + # same string, -dirty included, that a local build of the same tree + # would. version="$("$SCRIPT_DIR/version")" commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" commit_date="$(git show -s --format=%cs HEAD 2>/dev/null || echo unknown)" diff --git a/script/version b/script/version index 0df9b42..7ba6ad0 100755 --- a/script/version +++ b/script/version @@ -1,73 +1,29 @@ #!/bin/sh # script/version: output the version string to bake into the binary. -# Our own extension to scripts-to-rule-them-all, and the single source -# of truth for the version: the Makefile's LDFLAGS call this rather -# than carrying a hardcoded constant, which is what used to make every -# local build claim to be 1.0.0-rc.1 regardless of git state. +# Our own extension to scripts-to-rule-them-all. The Makefile's LDFLAGS +# call this rather than carrying a hardcoded constant, which is what used +# to make every local build claim to be 1.0.0-rc.1 regardless of git +# state. script/docker and script/cibuild pass its output to the image +# build; given no version, the image build runs `git describe --tags +# --always` itself, without `--dirty`. # -# The rules, in order: +# The version is `git describe --tags --always --dirty`: the tag on a +# tagged commit, tag-N-gHASH on a commit after one, the short commit +# when no tag is reachable, each with a "-dirty" suffix when tracked +# files have uncommitted changes. Untracked files are ignored: a stray +# scratch file does not change what was compiled. Outside a git checkout +# (release tarball, `go install`), or in one with no commits, it is +# "dev". # -# HEAD is exactly on an annotated or lightweight tag -# -> that tag, with a leading "v" stripped -# anything else -# -> "dev-<12 chars of HEAD>" -# not a git checkout at all (release tarball, `go install`) -# -> "dev" -# -# Either of the first two gains a "-dirty" suffix when tracked files -# have uncommitted changes, because a modified checkout of v1.0.0 is -# not v1.0.0. Untracked files are ignored, matching `git describe -# --dirty`: a stray scratch file does not change what was compiled. -# -# The "v" is stripped so that a `make` build and a goreleaser build of -# the same tagged commit report the *same* string: goreleaser's -# {{ .Version }} is the tag without the prefix, and the release archive -# names are built from it. A tag named `v1.0.0` therefore produces -# `vaultik 1.0.0`, matching `vaultik_1.0.0_linux_amd64.tar.gz`. -# -# Nothing here ever invents a version number. An untagged build says so -# and names the commit it was built from; it does not round up to the -# nearest plausible release. +# Nothing here ever invents a version number. set -eu ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" -# Length of the commit prefix in a dev version. Matches -# globals.ShortCommit, so `vaultik version` shows the same 12 chars in -# its version line and its commit line. -SHORT_LEN=12 - main() { cd "$ROOT" - - if ! git rev-parse --git-dir >/dev/null 2>&1; then - echo "dev" - return 0 - fi - - dirty="" - if [ -n "$(git status --porcelain --untracked-files=no 2>/dev/null)" ]; then - dirty="-dirty" - fi - - # --exact-match so a *descendant* of a tag is not reported as that - # tag. Plain `git describe --tags` would call a commit 40 patches - # past v1.0.0 "v1.0.0-40-gabc1234", and the leading token of that is - # a released version the build is not. - tag="$(git describe --tags --exact-match HEAD 2>/dev/null || true)" - if [ -n "$tag" ]; then - echo "${tag#v}${dirty}" - return 0 - fi - - sha="$(git rev-parse "--short=$SHORT_LEN" HEAD 2>/dev/null || true)" - if [ -z "$sha" ]; then - # A repo with no commits at all. - echo "dev" - return 0 - fi - - echo "dev-${sha}${dirty}" + version="$(git describe --tags --always --dirty 2>/dev/null || true)" + echo "${version:-dev}" } main "$@" From 35cf985c18a57edc5e4652a646e482900351fd81 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 04:46:16 +0200 Subject: [PATCH 006/121] Re-chunk a known file whose chunks no uploaded blob holds (closes #214) File rows are shared by every snapshot and updated in place, while a blob row is deleted once no snapshot references it. Removing the newest snapshot, or the prune after an interrupted run, could drop the only blob holding a changed file's current chunks while an older snapshot kept the file row. The next backup compared metadata only, skipped the file, and completed a snapshot that could not restore it. The scanner now loads the IDs of known files that list a chunk no uploaded blob holds and re-chunks them even when their metadata is unchanged. The tests append to a file, so the file keeps its first chunk in a blob the first snapshot still references. Each backup run gets its own snapshot name, so the second-precision snapshot IDs differ without sleeping. Model: opus-5-5 --- ARCHITECTURE.md | 2 +- README.md | 8 +- TODO.md | 9 + docs/DATAMODEL.md | 1 + internal/database/files.go | 50 ++++ internal/snapshot/scanner.go | 43 ++++ internal/vaultik/changed_file_restore_test.go | 234 ++++++++++++++++++ 7 files changed, 343 insertions(+), 4 deletions(-) create mode 100644 internal/vaultik/changed_file_restore_test.go diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 6428d8f..309186f 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -353,7 +353,7 @@ CreateSnapshot(opts) ## Deduplication Strategy -1. **File-level**: Files unchanged since last backup are skipped (metadata comparison: size, mtime, mode, uid, gid) +1. **File-level**: Files unchanged since last backup are skipped (metadata comparison: size, mtime, mode, uid, gid), unless the file lists a chunk that no uploaded blob holds; such a file is re-chunked 2. **Chunk-level**: Chunks are content-addressed by SHA256 hash. If a chunk hash already exists in the database, the chunk data is not re-uploaded. diff --git a/README.md b/README.md index 0bab63c..ecd7622 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,8 @@ Features: * modern encryption ([age](https://age-encryption.org/), X25519 + ChaCha20-Poly1305) * content-defined chunking with deduplication (FastCDC) -* incremental backups (only changed files are re-chunked) +* incremental backups (a file is re-chunked only when it changed or a + chunk it lists is held by no uploaded blob) * multithreaded zstd compression at configurable levels * content-addressed immutable storage * local state tracking in SQLite (enables write-only incremental backups) @@ -499,8 +500,9 @@ format does and does not protect. * Content-defined chunking using the FastCDC algorithm * Average chunk size: configurable (default 10MB) -* Deduplication at file level (unchanged files skipped) and chunk level - (identical chunks across files stored once) +* Deduplication at file level (unchanged files skipped, unless a chunk + the file lists is held by no uploaded blob) and chunk level (identical + chunks across files stored once) * Multiple chunks packed into blobs to reduce object count ### encryption diff --git a/TODO.md b/TODO.md index c490f04..fef4869 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,15 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made a backup re-chunk a known file that lists a chunk no + uploaded blob holds + ([issue #214](https://git.eeqj.de/sneak/vaultik/issues/214)). File + rows are shared by every snapshot and updated in place, so removing or + pruning the only snapshot that referenced a changed file's current + blob left an older snapshot keeping a row that matched the disk while + no blob held its chunks. The next backup skipped the file and + completed a snapshot that could not restore it. + - 2026-09-22: Routed the last direct-to-stdout command output through `internal/ui` ([issue #149](https://git.eeqj.de/sneak/vaultik/issues/149)). The diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index 7338c0d..37e128e 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -195,6 +195,7 @@ Tracks blob upload metrics. 1. **Change Detection** - `SELECT * FROM files WHERE path = ?` - Get previous file metadata - Compare mtime, size, mode to detect changes + - Re-chunk a file that lists a chunk no uploaded blob holds, even when its metadata is unchanged - Skip unchanged files but still add to `snapshot_files` 2. **Chunk Reuse** diff --git a/internal/database/files.go b/internal/database/files.go index 8fd69e7..f9d8022 100644 --- a/internal/database/files.go +++ b/internal/database/files.go @@ -266,6 +266,56 @@ func (r *FileRepository) ListByPrefix( return files, rows.Err() } +// ListIDsWithChunksNotInUploadedBlobs returns the IDs of the files whose +// path starts with prefix and that list at least one chunk held by no +// blob whose upload has completed (uploaded_ts set). A new snapshot +// cannot reference such a chunk, so a backup must not treat the file as +// unchanged even when its metadata matches the file on disk. +func (r *FileRepository) ListIDsWithChunksNotInUploadedBlobs( + ctx context.Context, prefix string, +) ([]types.FileID, error) { + query := ` + SELECT DISTINCT f.id + FROM files f + JOIN file_chunks fc ON fc.file_id = f.id + WHERE f.path LIKE ? || '%' + AND NOT EXISTS ( + SELECT 1 + FROM blob_chunks bc + JOIN blobs b ON bc.blob_id = b.id + WHERE bc.chunk_hash = fc.chunk_hash + AND b.uploaded_ts IS NOT NULL + ) + ` + + rows, err := r.db.conn.QueryContext(ctx, query, prefix) + if err != nil { + return nil, fmt.Errorf("querying files: %w", err) + } + + defer func() { + err := rows.Close() + if err != nil { + Fatalf("failed to close rows: %v", err) + } + }() + + var ids []types.FileID + + for rows.Next() { + var id types.FileID + + err := rows.Scan(&id) + if err != nil { + return nil, fmt.Errorf("scanning file ID: %w", err) + } + + ids = append(ids, id) + } + + return ids, rows.Err() +} + // ListAll returns all files in the database func (r *FileRepository) ListAll(ctx context.Context) ([]*File, error) { query := ` diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index a0f6a9b..71f8fd8 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -73,6 +73,11 @@ type Scanner struct { knownChunks map[string]struct{} knownChunksMu sync.RWMutex + // filesToRechunk holds the IDs of known files that list a chunk no + // uploaded blob holds; they are re-chunked even when their metadata + // is unchanged. + filesToRechunk map[types.FileID]struct{} + // Pending chunk hashes - chunks that have been added to packer but not // yet committed to DB. When a blob finalizes, the committed chunks are // removed from this set. @@ -325,9 +330,42 @@ func (s *Scanner) loadDatabaseState( s.ui.Completef("Loaded %s known chunks from local index database.", s.ui.Count(len(s.knownChunks))) + err = s.loadFilesToRechunk(ctx, path) + if err != nil { + return nil, fmt.Errorf("loading files to re-chunk: %w", err) + } + return knownFiles, nil } +// loadFilesToRechunk loads the IDs of known files under path that list a +// chunk no uploaded blob holds. A file row is shared by every snapshot +// that lists the file and is updated in place when the file changes, +// while a blob row is deleted once no snapshot references it. Removing +// the only snapshot that references a changed file's current blob +// therefore leaves an older snapshot keeping a file row whose metadata +// matches the disk while no blob the local index records as uploaded +// holds its chunks, so a new snapshot cannot reference them. The dropped +// blob can still be in remote storage until prune removes it. +func (s *Scanner) loadFilesToRechunk(ctx context.Context, path string) error { + ids, err := s.repos.Files.ListIDsWithChunksNotInUploadedBlobs(ctx, path) + if err != nil { + return fmt.Errorf("listing files: %w", err) + } + + s.filesToRechunk = make(map[types.FileID]struct{}, len(ids)) + for _, id := range ids { + s.filesToRechunk[id] = struct{}{} + } + + if len(ids) > 0 { + log.Info("Re-chunking known files whose chunks are not all "+ + "in uploaded blobs", "files", len(ids)) + } + + return nil +} + // repairInterruptedBlobs discards blob rows left by a previous run whose // upload never completed. Such a blob has its chunks, blob_chunks, and // blobs rows committed to the local index before the upload is attempted, @@ -1208,6 +1246,11 @@ func (s *Scanner) checkFileInMemory( return file, true } + // No uploaded blob holds one of its chunks (see loadFilesToRechunk) + if _, rechunk := s.filesToRechunk[fileID]; rechunk { + return file, true + } + // Check if file has changed if existingFile.Size != file.Size || existingFile.MTime.Unix() != file.MTime.Unix() || diff --git a/internal/vaultik/changed_file_restore_test.go b/internal/vaultik/changed_file_restore_test.go new file mode 100644 index 0000000..de61170 --- /dev/null +++ b/internal/vaultik/changed_file_restore_test.go @@ -0,0 +1,234 @@ +package vaultik_test + +import ( + "context" + "crypto/rand" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/chunker" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/214: once +// the only snapshot referencing a changed file's current blob is +// dropped, an older snapshot still keeps the file's row, and the next +// backup must re-chunk the file instead of treating it as unchanged. +// +// Each backup run uses its own snapshot name over the same source +// directory, so the snapshot IDs differ without waiting for their +// one-second timestamps to tick over. File rows are keyed by path, so +// the runs share them exactly as runs of one snapshot name would. + +// changedFileConfig returns a full-backup config with the snapshot names +// "first", "second" and "third", all backing up dataDir. +func changedFileConfig(dataDir, dbPath string) *config.Config { + source := config.SnapshotConfig{Paths: []string{dataDir}} + + cfg := faultTestConfig() + cfg.IndexPath = dbPath + cfg.ChunkSize = config.Size(faultChunkSize) + cfg.Snapshots = map[string]config.SnapshotConfig{ + "first": source, + "second": source, + "third": source, + } + + return cfg +} + +// backUp runs a full backup of the named snapshot. +func backUp(v *vaultik.Vaultik, name string) error { + return v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Cron: true, + Snapshots: []string{name}, + }) +} + +// appendedFileSize is the size of the file before the tests append to it. +// It is twice the largest chunk the chunker cuts, so the file's first +// chunk ends before the appended bytes and stays in a blob the first +// snapshot still references, while its new chunks are only in the blob +// that gets dropped. +const appendedFileSize = 2 * chunker.ChunkSizeSpread * faultChunkSize + +// appendRandomBytes appends n random bytes to the file at path, creating +// the file if it does not exist, and records the new content in files. +// Random content gives the chunker real cut points. +func appendRandomBytes( + t *testing.T, fs afero.Fs, files map[string][]byte, path string, n int64, +) { + t.Helper() + + added := make([]byte, n) + _, err := rand.Read(added) + require.NoError(t, err) + + content := slices.Concat(files[path], added) + require.NoError(t, afero.WriteFile(fs, path, content, 0o644)) + + files[path] = content +} + +// localSnapshotID returns the ID of the one snapshot in the local index +// that was backed up under name. +func localSnapshotID( + ctx context.Context, t *testing.T, + repos *database.Repositories, name string, +) string { + t.Helper() + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + + var ids []string + + for _, s := range snapshots { + if strings.Contains(s.ID.String(), "_"+name+"_") { + ids = append(ids, s.ID.String()) + } + } + + require.Lenf(t, ids, 1, "expected one local snapshot named %q", name) + + return ids[0] +} + +// assertThirdSnapshotRestores closes the local index, then restores the +// snapshot named "third" from store alone and byte-compares every file +// against files. +func assertThirdSnapshotRestores( + ctx context.Context, t *testing.T, cfg *config.Config, + store storage.Storer, repos *database.Repositories, db *database.DB, + fs afero.Fs, restoreDir string, files map[string][]byte, +) { + t.Helper() + + id := localSnapshotID(ctx, t, repos, "third") + require.NoError(t, db.Close()) + + reader := newReaderVaultik(ctx, cfg, store, nil, fs) + require.NoError(t, reader.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Verify: true, + }), "the backup after the drop must restore the changed file") + + assertRestoredTree(t, fs, restoreDir, files) +} + +// Trigger 1: bytes are appended to the file, a second snapshot backs it +// up, and that snapshot is removed. The first snapshot keeps the file row, +// which now lists the appended content's chunks, while removal drops the +// blob that held them. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestBackupAfterRemovingNewestSnapshotRestoresChangedFile(t *testing.T) { + log.Initialize(log.Config{}) + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := filepath.Join(tempDir, "remote") + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + changedPath := filepath.Join(dataDir, "appended.bin") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, dataDir) + cfg := changedFileConfig(dataDir, dbPath) + + appendRandomBytes(t, fs, files, changedPath, appendedFileSize) + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, "first")) + + appendRandomBytes(t, fs, files, changedPath, faultChunkSize) + require.NoError(t, backUp(v, "second")) + + _, err = v.RemoveSnapshot(localSnapshotID(ctx, t, repos, "second"), + &vaultik.RemoveOptions{Force: true}) + require.NoError(t, err) + + require.NoError(t, backUp(v, "third")) + + assertThirdSnapshotRestores( + ctx, t, cfg, store, repos, db, fs, restoreDir, files) +} + +// Trigger 2: bytes are appended to the file and the run that backs it up +// is interrupted at the manifest upload, after its blobs were uploaded. +// The next run's prune drops that incomplete snapshot and its blob, while +// the first snapshot keeps the file row, which now lists the appended +// content's chunks. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestBackupAfterInterruptedRunRestoresChangedFile(t *testing.T) { + log.Initialize(log.Config{}) + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := filepath.Join(tempDir, "remote") + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + changedPath := filepath.Join(dataDir, "appended.bin") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, dataDir) + cfg := changedFileConfig(dataDir, dbPath) + + appendRandomBytes(t, fs, files, changedPath, appendedFileSize) + + inner, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + failManifest := false + store := faultstore.New(inner) + store.OnPut = func(key string) faultstore.PutAction { + if failManifest && strings.HasSuffix(key, "manifest.json.zst") { + return faultstore.PutFail + } + + return faultstore.PutNormal + } + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, "first")) + + appendRandomBytes(t, fs, files, changedPath, faultChunkSize) + + failManifest = true + + require.Error(t, backUp(v, "second"), + "the run must fail when its manifest upload fails") + + failManifest = false + + require.NoError(t, backUp(v, "third")) + + assertThirdSnapshotRestores( + ctx, t, cfg, inner, repos, db, fs, restoreDir, files) +} From 713be502bdb4038332e95959e8e32f2b52424cb1 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 06:12:07 +0200 Subject: [PATCH 007/121] Reject a duration with characters outside its parts (closes #215) parseDuration fell back to an unanchored search for number-and-unit pieces when time.ParseDuration failed, and skipped everything in between. 1.0y became 0, so `snapshot create --prune --keep-newer-than 1.0y` deleted every snapshot of the backed-up names, the new one included. 2.1w became one week and 1,5y five years. The fallback now requires the whole input to be whole-number-and-unit parts with nothing between them. A bare number is rejected before time.ParseDuration sees it, since Go reads 0 and +0 as zero with no unit. Judgement call: a space between number and unit (`30 days`) was accepted and is now an error, matching Go's own units. Model: opus-5-5 --- TODO.md | 9 +++++++++ internal/vaultik/helpers.go | 20 +++++++++++++++----- internal/vaultik/helpers_test.go | 11 +++++++++++ 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/TODO.md b/TODO.md index fef4869..dbf60b3 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,15 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made `--older-than` and `--keep-newer-than` reject a + duration with characters outside its number-and-unit parts + ([issue #215](https://git.eeqj.de/sneak/vaultik/issues/215)). The + parser picked out the parts it recognised and skipped the rest, so + `1.0y` became zero and `--prune --keep-newer-than 1.0y` deleted every + snapshot of the backed-up names, the new one included. `1.0y`, + `1,5y`, `30 days`, `x7d` and a bare `0` are now errors; decimals still + work in Go units such as `1.5h`. + - 2026-10-06: Made a backup re-chunk a known file that lists a chunk no uploaded blob holds ([issue #214](https://git.eeqj.de/sneak/vaultik/issues/214)). File diff --git a/internal/vaultik/helpers.go b/internal/vaultik/helpers.go index 64a1d85..9ca5045 100644 --- a/internal/vaultik/helpers.go +++ b/internal/vaultik/helpers.go @@ -140,24 +140,34 @@ func parseSnapshotName(snapshotID string) string { // parseDuration parses a duration string with support for human-friendly units: // d/day/days, w/week/weeks, mo/month/months, y/year/years, plus standard Go // duration units. Following Go, m is minutes and mo is months. A bare number, -// an unknown unit, and a negative value are all rejected. +// an unknown unit, and a negative value are all rejected. Outside the Go +// units the input must be whole numbers each followed directly by a unit +// (2w3d), so 1.0y and 30 days are errors; decimals work only in Go units +// (1.5h). func parseDuration(s string) (time.Duration, error) { if strings.HasPrefix(strings.TrimSpace(s), "-") { return 0, errNegativeDuration } + // A bare number has no unit, but time.ParseDuration accepts 0, which + // would put the cutoff at now and select every snapshot. + _, err := strconv.ParseFloat(s, 64) + if err == nil { + return 0, fmt.Errorf("%w: %q", errInvalidDuration, s) + } + d, err := time.ParseDuration(s) if err == nil { return d, nil } - re := regexp.MustCompile(`(\d+)\s*([a-zA-Z]+)`) - - matches := re.FindAllStringSubmatch(s, -1) - if len(matches) == 0 { + if !regexp.MustCompile(`^(\d+[a-zA-Z]+)+$`).MatchString(s) { return 0, fmt.Errorf("%w: %q", errInvalidDuration, s) } + re := regexp.MustCompile(`(\d+)([a-zA-Z]+)`) + matches := re.FindAllStringSubmatch(s, -1) + var total time.Duration for _, match := range matches { diff --git a/internal/vaultik/helpers_test.go b/internal/vaultik/helpers_test.go index eb58781..b77b51d 100644 --- a/internal/vaultik/helpers_test.go +++ b/internal/vaultik/helpers_test.go @@ -59,6 +59,7 @@ func TestParseDuration(t *testing.T) { {"30s", 30 * time.Second, false}, {"6m", 6 * time.Minute, false}, {"1h", time.Hour, false}, + {"1.5h", 90 * time.Minute, false}, // Extended calendar units. {"30d", 30 * 24 * time.Hour, false}, {"3days", 3 * 24 * time.Hour, false}, @@ -73,11 +74,21 @@ func TestParseDuration(t *testing.T) { {"1y6mo", 365*24*time.Hour + 180*24*time.Hour, false}, // Rejected inputs. {"6", 0, true}, // bare number, no unit + {"0", 0, true}, // bare number; time.ParseDuration accepts it + {"+0", 0, true}, // bare number; time.ParseDuration accepts it {"5x", 0, true}, // unknown unit {"-5d", 0, true}, // negative, extended unit {"-5h", 0, true}, // negative, Go unit {"", 0, true}, // empty {"garbage", 0, true}, + // Characters outside the number-and-unit parts must not be + // skipped: 1.0y read as 0y would select every snapshot. + {"1.0y", 0, true}, + {"2.1w", 0, true}, + {"1,5y", 0, true}, + {"30 days", 0, true}, + {"30 days ago", 0, true}, + {"x7d", 0, true}, } for _, tt := range tests { From ea726979922ec3ef34793805212451a4fcd41b48 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 08:46:17 +0200 Subject: [PATCH 008/121] List a missing file:// destination directory as an error (closes #220) The file backend listed a destination directory that does not exist as an empty store. With the volume unplugged, snapshot list reported every local snapshot as missing from the store, snapshot remove said it had removed metadata it never reached, and prune dropped every local snapshot record. List and ListStream now fail when the destination directory is missing, so those commands take their existing path for a store that cannot be listed. A missing prefix under an existing directory is still an empty listing, and a first backup still creates the directory. Three tests listed a file:// destination nothing had created; they now create it. Model: opus-5-5 --- TODO.md | 10 ++ internal/cli/entry_banner_test.go | 15 +- internal/cli/entry_prune_json_test.go | 15 +- internal/storage/file.go | 31 +++- internal/storage/file_backend_test.go | 35 +++++ internal/vaultik/fault_injection_test.go | 4 + internal/vaultik/missing_destination_test.go | 155 +++++++++++++++++++ 7 files changed, 246 insertions(+), 19 deletions(-) create mode 100644 internal/vaultik/missing_destination_test.go diff --git a/TODO.md b/TODO.md index dbf60b3..d8432df 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,16 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made a `file://` destination whose directory is missing + count as one that cannot be listed + ([issue #220](https://git.eeqj.de/sneak/vaultik/issues/220)). The file + backend listed a missing directory as an empty store, so with the + quickstart's USB stick unplugged `snapshot list` reported every local + snapshot as missing from the store, `snapshot remove` claimed to have + removed metadata it never reached, and `prune` dropped every local + snapshot record. Listing a missing destination directory is now an + error; a first backup still creates the directory. + - 2026-10-06: Made `--older-than` and `--keep-newer-than` reject a duration with characters outside its number-and-unit parts ([issue #215](https://git.eeqj.de/sneak/vaultik/issues/215)). The diff --git a/internal/cli/entry_banner_test.go b/internal/cli/entry_banner_test.go index cbb51e3..df7321b 100644 --- a/internal/cli/entry_banner_test.go +++ b/internal/cli/entry_banner_test.go @@ -172,9 +172,9 @@ func TestBannerSuppressedInArgs(t *testing.T) { // hermeticConfig is a complete, valid config that needs no network and // no credentials: file:// storage is exempt from the S3 credential -// checks, and FileStorer over a directory that does not exist lists -// zero objects without erroring. Chunk, blob and compression settings -// are filled in by config.Load. +// checks. A test that lists the destination must create its directory +// first, because listing a directory that does not exist is an error. +// Chunk, blob and compression settings are filled in by config.Load. const hermeticConfig = `age_recipients: - age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj snapshots: @@ -196,22 +196,25 @@ hostname: test-host // `snapshot list` is the command chosen because it is the only --json // command that reaches its document without a populated destination // store: it reads the local index, streams `metadata/` (empty here), -// and treats a barren destination as an empty list rather than a -// failure. +// and treats an empty destination directory as an empty list rather +// than a failure. // // Not parallel: it replaces os.Args, os.Stdout and the xdg globals. func TestEntryJSONStdoutIsExactlyOneDocument(t *testing.T) { dir := t.TempDir() configPath := filepath.Join(dir, "config.yml") + storeDir := filepath.Join(dir, "store") contents := fmt.Sprintf(hermeticConfig, filepath.Join(dir, "source"), - filepath.Join(dir, "store"), + storeDir, filepath.Join(dir, "index.sqlite")) require.NoError(t, os.WriteFile(configPath, []byte(contents), configFileMode)) + require.NoError(t, os.Mkdir(storeDir, 0o750)) + // The PID lock lives under xdg.DataHome, which xdg resolves at // package init; point it at the temp dir so the test neither // touches nor collides with the real one. diff --git a/internal/cli/entry_prune_json_test.go b/internal/cli/entry_prune_json_test.go index 7f4d6e9..b220df4 100644 --- a/internal/cli/entry_prune_json_test.go +++ b/internal/cli/entry_prune_json_test.go @@ -98,25 +98,30 @@ func TestEntryPruneJSONStdoutIsExactlyOneDocument(t *testing.T) { } } -// writeHermeticPruneConfig builds a config over a temp directory and, if -// seedStale is set, creates the index database up front with one -// snapshot record that has no counterpart on the destination store. -// Returns the config path. +// writeHermeticPruneConfig builds a config over a temp directory with an +// empty destination directory and, if seedStale is set, creates the +// index database up front with one snapshot record that has no +// counterpart on the destination store. Returns the config path. func writeHermeticPruneConfig(t *testing.T, seedStale bool) string { t.Helper() dir := t.TempDir() configPath := filepath.Join(dir, "config.yml") indexPath := filepath.Join(dir, "index.sqlite") + storeDir := filepath.Join(dir, "store") contents := fmt.Sprintf(hermeticConfig, filepath.Join(dir, "source"), - filepath.Join(dir, "store"), + storeDir, indexPath) require.NoError(t, os.WriteFile(configPath, []byte(contents), configFileMode)) + // prune fails on a destination directory that does not exist, so the + // empty store is created here rather than left to a first backup. + require.NoError(t, os.Mkdir(storeDir, 0o750)) + // The PID lock lives under xdg.DataHome, which xdg resolves at // package init; point it at the temp dir so the test neither // touches nor collides with the real one. diff --git a/internal/storage/file.go b/internal/storage/file.go index 5c31898..bcf2c3d 100644 --- a/internal/storage/file.go +++ b/internal/storage/file.go @@ -22,11 +22,11 @@ type FileStorer struct { // // Construction is intentionally cheap and does not touch the filesystem. // The basePath is recorded; the directory is created lazily on first -// write. Reads (Get/Stat/List) tolerate a missing basePath — a missing -// or unmounted destination during `snapshot list` should NOT block the -// command, it should degrade to "no remote snapshots reachable" with a -// warning. Write operations (Put/PutWithProgress) call MkdirAll for the +// write. Write operations (Put/PutWithProgress) call MkdirAll for the // per-blob parent directory, which also covers basePath on first use. +// Get and Stat report a key under a missing basePath as ErrNotFound. +// List and ListStream fail on a missing basePath, because listing it as +// an empty store would make `prune` drop every local snapshot record. // // Uses the real OS filesystem by default; call SetFilesystem to // override for testing. @@ -119,13 +119,20 @@ func (f *FileStorer) Delete(_ context.Context, key string) error { return nil } -// List returns all keys with the given prefix. +// List returns all keys with the given prefix. It fails when the +// destination directory is missing; a missing prefix under it is an +// empty listing. func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error) { var keys []string + _, err := f.fs.Stat(f.basePath) + if err != nil { + return nil, fmt.Errorf("checking destination directory: %w", err) + } + basePath := f.fullPath(prefix) - // Check if base path exists + // Check if the prefix exists exists, err := afero.Exists(f.fs, basePath) if err != nil { return nil, fmt.Errorf("checking path: %w", err) @@ -167,16 +174,24 @@ func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error) return keys, nil } -// ListStream returns a channel of ObjectInfo for large result sets. +// ListStream returns a channel of ObjectInfo for large result sets. Like +// List, it sends an error when the destination directory is missing. func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan ObjectInfo { ch := make(chan ObjectInfo) go func() { defer close(ch) + _, err := f.fs.Stat(f.basePath) + if err != nil { + ch <- ObjectInfo{Err: fmt.Errorf("checking destination directory: %w", err)} + + return + } + basePath := f.fullPath(prefix) - // Check if base path exists + // Check if the prefix exists exists, err := afero.Exists(f.fs, basePath) if err != nil { ch <- ObjectInfo{Err: fmt.Errorf("checking path: %w", err)} diff --git a/internal/storage/file_backend_test.go b/internal/storage/file_backend_test.go index de5ef31..f92331e 100644 --- a/internal/storage/file_backend_test.go +++ b/internal/storage/file_backend_test.go @@ -1,6 +1,10 @@ package storage_test import ( + "context" + "errors" + "io/fs" + "path/filepath" "testing" "sneak.berlin/go/vaultik/internal/storage" @@ -25,3 +29,34 @@ func TestFileStorer(t *testing.T) { t.Parallel() runStorerConformance(t, newFileStorer) } + +// TestFileStorerListMissingDestination checks that List and ListStream +// fail when the destination directory does not exist, instead of +// reporting an empty store. +func TestFileStorerListMissingDestination(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + s, err := storage.NewFileStorer(filepath.Join(t.TempDir(), "unmounted")) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + keys, err := s.List(ctx, "metadata/") + if !errors.Is(err, fs.ErrNotExist) { + t.Errorf("List = %v, %v; want a not-exist error", keys, err) + } + + var streamErr error + + for object := range s.ListStream(ctx, "metadata/") { + if object.Err != nil { + streamErr = object.Err + } + } + + if !errors.Is(streamErr, fs.ErrNotExist) { + t.Errorf("ListStream error = %v, want a not-exist error", streamErr) + } +} diff --git a/internal/vaultik/fault_injection_test.go b/internal/vaultik/fault_injection_test.go index 055fcfd..594c284 100644 --- a/internal/vaultik/fault_injection_test.go +++ b/internal/vaultik/fault_injection_test.go @@ -301,6 +301,10 @@ func TestInterruptedBlobUploadRecordsNoUploadedBlob(t *testing.T) { writeFaultSourceTree(t, fs, dataDir) + // No upload succeeds, so nothing creates the destination directory. + // It must exist for the listing below to show that no blob survived. + require.NoError(t, os.Mkdir(storeDir, 0o750)) + inner, err := storage.NewFileStorer(storeDir) require.NoError(t, err) diff --git a/internal/vaultik/missing_destination_test.go b/internal/vaultik/missing_destination_test.go new file mode 100644 index 0000000..3869bc7 --- /dev/null +++ b/internal/vaultik/missing_destination_test.go @@ -0,0 +1,155 @@ +package vaultik_test + +import ( + "bytes" + "context" + "io/fs" + "os" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/220: a +// file:// destination whose directory is missing, such as a USB stick +// that is not plugged in, cannot be listed. It is not an empty store, so +// no command may conclude from it that the local snapshots are gone. + +// backUpToFileDestination backs up the snapshot named "first" to a +// file:// destination at storeDir, which need not exist yet. Everything +// the returned Vaultik prints after the backup goes to the returned +// buffer. +func backUpToFileDestination( + ctx context.Context, t *testing.T, storeDir string, +) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer) { + t.Helper() + + osFs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + dbPath := filepath.Join(tempDir, "index.sqlite") + + writeFaultSourceTree(t, osFs, dataDir) + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + cfg := changedFileConfig(dataDir, dbPath) + v := newBackupVaultik(ctx, cfg, store, repos, db, osFs) + + require.NoError(t, backUp(v, "first")) + + out := &bytes.Buffer{} + v.Stdout = out + v.UI = ui.NewWithColor(out, false) + + return v, repos, out +} + +// backUpThenUnplug backs up to a file:// destination, then moves the +// destination directory away, as unplugging the volume it lives on would. +func backUpThenUnplug( + ctx context.Context, t *testing.T, +) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer) { + t.Helper() + + storeDir := filepath.Join(t.TempDir(), "usbstick") + v, repos, out := backUpToFileDestination(ctx, t, storeDir) + + require.NoError(t, os.Rename(storeDir, storeDir+"-unplugged")) + + return v, repos, out +} + +// TestFirstBackupCreatesDestinationDirectory checks that a first backup +// to a destination directory that does not exist yet creates it, and +// that the destination can be listed afterwards. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestFirstBackupCreatesDestinationDirectory(t *testing.T) { + log.Initialize(log.Config{}) + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "volume", "backup") + v, _, out := backUpToFileDestination(ctx, t, storeDir) + + require.NoError(t, v.ListSnapshots(false)) + + assert.NotContains(t, out.String(), "Could not list backup destination store") + assert.NotContains(t, out.String(), "not found in backup destination store") +} + +// TestListSnapshotsWarnsWhenDestinationMissing checks that snapshot list +// warns and shows the local index alone, without reporting the local +// snapshot as missing from the destination. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestListSnapshotsWarnsWhenDestinationMissing(t *testing.T) { + log.Initialize(log.Config{}) + + ctx := context.Background() + v, repos, out := backUpThenUnplug(ctx, t) + id := localSnapshotID(ctx, t, repos, "first") + + require.NoError(t, v.ListSnapshots(false)) + + assert.Contains(t, out.String(), "Could not list backup destination store") + assert.Contains(t, out.String(), "Showing snapshots from the local index only.") + assert.Contains(t, out.String(), id) + assert.NotContains(t, out.String(), "not found in backup destination store") +} + +// TestRemoveSnapshotWarnsWhenDestinationMissing checks that snapshot +// remove warns that the metadata could not be removed from the +// destination, instead of reporting that it was. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestRemoveSnapshotWarnsWhenDestinationMissing(t *testing.T) { + log.Initialize(log.Config{}) + + ctx := context.Background() + v, repos, out := backUpThenUnplug(ctx, t) + + result, err := v.RemoveSnapshot(localSnapshotID(ctx, t, repos, "first"), + &vaultik.RemoveOptions{Force: true}) + require.NoError(t, err) + + assert.False(t, result.RemoteRemoved) + assert.Contains(t, out.String(), + "Could not remove snapshot metadata from remote") + assert.NotContains(t, out.String(), + "Removed snapshot metadata from remote storage") +} + +// TestPruneKeepsLocalRecordsWhenDestinationMissing checks that prune +// fails on a destination it cannot list and deletes no local snapshot +// record. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestPruneKeepsLocalRecordsWhenDestinationMissing(t *testing.T) { + log.Initialize(log.Config{}) + + ctx := context.Background() + v, repos, _ := backUpThenUnplug(ctx, t) + + err := v.Prune(&vaultik.PruneOptions{Force: true}) + require.ErrorIs(t, err, fs.ErrNotExist) + require.ErrorContains(t, err, "listing remote snapshots") + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "prune must delete no local snapshot record") +} From 4a167e153aebb2294f5e21ca559f8748c36d0a2e Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 09:46:16 +0200 Subject: [PATCH 009/121] Record the real uid and gid of backed-up files (closes #216) The scanner read uid and gid by asserting the stat result to an interface with Uid() and Gid() methods. *syscall.Stat_t has Uid and Gid fields, not methods, so the assertion never matched and every file, directory and symlink was stored as 0:0; a restore as root then gave everything to root. The scanner now reads the fields of *syscall.Stat_t. The first backup after this change re-reads every file not owned by root, because its stored uid and gid no longer match the disk. When the tests run as root, as in the Docker build, the new test compares 0 with 0 and cannot catch the defect; a non-root run does. Model: opus-5-5 --- TODO.md | 8 ++++ internal/snapshot/scanner.go | 31 ++++--------- internal/snapshot/scanner_test.go | 77 +++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 21 deletions(-) diff --git a/TODO.md b/TODO.md index d8432df..c4059a0 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,14 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made a backup record the real uid and gid of files, + directories and symlinks + ([issue #216](https://git.eeqj.de/sneak/vaultik/issues/216)). The + scanner asked the stat result for `Uid()` and `Gid()` methods, which + `*syscall.Stat_t` does not have, so every entry was stored as `0:0` + and a restore as root gave every file to root. It now reads the + `Uid` and `Gid` fields of `*syscall.Stat_t`. + - 2026-10-06: Made a `file://` destination whose directory is missing count as one that cannot be listed ([issue #220](https://git.eeqj.de/sneak/vaultik/issues/220)). The file diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 71f8fd8..850b1b8 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -11,6 +11,7 @@ import ( "runtime" "strings" "sync" + "syscall" "time" "github.com/dustin/go-humanize" @@ -1142,12 +1143,9 @@ func (s *Scanner) buildSymlinkEntry(path string, info os.FileInfo) *database.Fil } var uid, gid uint32 - if stat, ok := info.Sys().(interface { - Uid() uint32 - Gid() uint32 - }); ok { - uid = stat.Uid() - gid = stat.Gid() + if stat, ok := info.Sys().(*syscall.Stat_t); ok { + uid = stat.Uid + gid = stat.Gid } return &database.File{ @@ -1166,12 +1164,9 @@ func (s *Scanner) buildSymlinkEntry(path string, info os.FileInfo) *database.Fil // buildDirectoryEntry creates a File record for a directory. func (s *Scanner) buildDirectoryEntry(path string, info os.FileInfo) *database.File { var uid, gid uint32 - if stat, ok := info.Sys().(interface { - Uid() uint32 - Gid() uint32 - }); ok { - uid = stat.Uid() - gid = stat.Gid() + if stat, ok := info.Sys().(*syscall.Stat_t); ok { + uid = stat.Uid + gid = stat.Gid } return &database.File{ @@ -1204,16 +1199,10 @@ func (s *Scanner) recordNonRegularFile(ctx context.Context, ftp *FileToProcess) func (s *Scanner) checkFileInMemory( path string, info os.FileInfo, knownFiles map[string]*database.File, ) (*database.File, bool) { - // Get file stats - stat, ok := info.Sys().(interface { - Uid() uint32 - Gid() uint32 - }) - var uid, gid uint32 - if ok { - uid = stat.Uid() - gid = stat.Gid() + if stat, ok := info.Sys().(*syscall.Stat_t); ok { + uid = stat.Uid + gid = stat.Gid } // Check against in-memory map first to get existing ID if available diff --git a/internal/snapshot/scanner_test.go b/internal/snapshot/scanner_test.go index dfac28e..a28b58c 100644 --- a/internal/snapshot/scanner_test.go +++ b/internal/snapshot/scanner_test.go @@ -307,3 +307,80 @@ func TestScannerLargeFile(t *testing.T) { } } } + +// TestScannerRecordsOwnership backs up real files on disk and checks that +// the uid and gid of a file, a directory and a symlink are recorded. +// When the tests run as root both sides are 0, so only a run as another +// user can catch ownership recorded as 0. +func TestScannerRecordsOwnership(t *testing.T) { + t.Parallel() + + sourceDir := t.TempDir() + filePath := filepath.Join(sourceDir, "file.txt") + dirPath := filepath.Join(sourceDir, "subdir") + linkPath := filepath.Join(sourceDir, "link") + + err := os.WriteFile(filePath, []byte("owned"), 0o600) + if err != nil { + t.Fatal(err) + } + + err = os.Mkdir(dirPath, 0o700) + if err != nil { + t.Fatal(err) + } + + err = os.Symlink("file.txt", linkPath) + if err != nil { + t.Fatal(err) + } + + db, err := database.NewTestDB() + if err != nil { + t.Fatalf("failed to create test database: %v", err) + } + + defer func() { + err := db.Close() + if err != nil { + t.Errorf("failed to close database: %v", err) + } + }() + + repos := database.NewRepositories(db) + + scanner := snapshot.NewScanner(snapshot.ScannerConfig{ + FS: afero.NewOsFs(), + ChunkSize: int64(1024 * 16), + Repositories: repos, + MaxBlobSize: int64(1024 * 1024), + CompressionLevel: 3, + AgeRecipients: []string{testAgePublicKey}, + }) + + ctx := context.Background() + snapshotID := "test-snapshot-ownership" + + createTestSnapshotRecord(ctx, t, repos, snapshotID) + + _, err = scanner.Scan(ctx, sourceDir, snapshotID) + if err != nil { + t.Fatalf("scan failed: %v", err) + } + + for _, path := range []string{filePath, dirPath, linkPath} { + file, err := repos.Files.GetByPath(ctx, path) + if err != nil { + t.Fatalf("failed to get %s: %v", path, err) + } + + if file == nil { + t.Fatalf("%s was not recorded", path) + } + + if int(file.UID) != os.Getuid() || int(file.GID) != os.Getgid() { + t.Errorf("%s recorded as uid %d gid %d, want uid %d gid %d", + path, file.UID, file.GID, os.Getuid(), os.Getgid()) + } + } +} From c4adb72d807da98153969f0d4ab885963a33f733 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 11:29:18 +0200 Subject: [PATCH 010/121] Run the local index in WAL mode with a busy timeout (closes #217) The connection settings were passed as `_journal_mode=`-style parameters, which the SQLite driver drops without an error, so the index ran in rollback-journal mode with no busy timeout. `snapshot list` or `info` reading during a backup could make the backup's next write fail with "database is locked". Both open paths now pass `_pragma=` parameters; foreign keys moved there too. With WAL on, rows committed to the open index can still be in the -wal file, which a copy of the main file misses. The metadata export now copies the index with VACUUM INTO, into an empty 0600 file. The retry after a failed open no longer claims a TRUNCATE recovery; it retries with the same settings. Model: opus-5-5 --- TODO.md | 9 +++ docs/DATAMODEL.md | 2 +- internal/database/database.go | 83 +++++++++++++-------------- internal/database/database_test.go | 83 +++++++++++++++++++++++++++ internal/snapshot/export_perm_test.go | 24 +++++--- internal/snapshot/snapshot.go | 71 +++++++++++------------ internal/snapshot/snapshot_test.go | 71 +++++++++++++++++++++++ 7 files changed, 252 insertions(+), 91 deletions(-) diff --git a/TODO.md b/TODO.md index c4059a0..2336169 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,15 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made the local index actually run in WAL mode with a busy + timeout ([issue #217](https://git.eeqj.de/sneak/vaultik/issues/217)). + The connection settings were written in a form the SQLite driver + ignores, so the index ran without either and `snapshot list` or `info` + during a backup could make the backup's next write fail with + `database is locked`. They are now `_pragma=` parameters, and the + metadata export copies the open index with `VACUUM INTO`, because a + copy of the file alone misses rows still in the `-wal` file. + - 2026-10-06: Made a backup record the real uid and gid of files, directories and symlinks ([issue #216](https://git.eeqj.de/sneak/vaultik/issues/216)). The diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index 37e128e..4fe62a5 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -280,7 +280,7 @@ This ensures consistency, especially important for operations like: 3. **Batch Operations**: Where possible, operations are batched within transactions -4. **Write-Ahead Logging**: SQLite WAL mode is enabled for better concurrency +4. **Write-Ahead Logging**: The local index runs in SQLite WAL mode with a 10-second busy timeout, so a read-only command such as `snapshot list` can read it while a backup writes to it. Committed rows can sit in the `-wal` file beside the index until a checkpoint, so the metadata export copies the index through SQLite (`VACUUM INTO`), not as a file ## Data Integrity diff --git a/internal/database/database.go b/internal/database/database.go index b41945b..5e680c5 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -42,6 +42,10 @@ var schemaFS embed.FS // table itself. It is applied before the normal migration loop. const bootstrapVersion = 0 +// busyTimeoutMs is how long a connection to the index waits for another +// connection's lock before failing with "database is locked". +const busyTimeoutMs = 10000 + // DB represents the Vaultik local index database connection. // It uses SQLite to track file metadata, content-defined chunks, and blob associations. // The database enables incremental backups by detecting changed files and @@ -94,10 +98,27 @@ func ParseMigrationVersion(filename string) (int, error) { return version, nil } +// indexDSN returns the driver DSN that opens the database at path. The +// driver runs each _pragma parameter on every connection it opens and drops +// any parameter it does not know without an error, so a setting written in +// another form silently does nothing. In WAL mode one connection can write +// while others read; the busy timeout makes a connection wait for a lock +// instead of failing at once. +func indexDSN(path string) string { + return fmt.Sprintf( + "%s?_pragma=busy_timeout(%d)&_pragma=journal_mode(WAL)"+ + "&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(1)", + path, busyTimeoutMs) +} + // New creates a new database connection at the specified path. -// It creates the schema if needed and configures SQLite with WAL mode for -// better concurrency. SQLite handles crash recovery automatically when -// opening a database with journal/WAL files present. +// It creates the schema if needed. Every connection runs in WAL mode with +// a busy timeout and foreign keys on (see indexDSN), so a read-only command +// can read the index while a backup writes to it. Committed rows can sit in +// the -wal file beside the database until a checkpoint, so a copy of the +// database file alone may miss them. +// SQLite handles crash recovery automatically when opening a database with +// journal/WAL files present. // The path parameter can be a file path for persistent storage or ":memory:" // for an in-memory database (useful for testing). func New(ctx context.Context, path string) (*DB, error) { @@ -110,11 +131,7 @@ func New(ctx context.Context, path string) (*DB, error) { // First attempt with standard WAL mode log.Debug("Attempting to open database with WAL mode", "path", path) - conn, err := sql.Open( - "sqlite", - path+"?_journal_mode=WAL&_synchronous=NORMAL&_busy_timeout=10000"+ - "&_locking_mode=NORMAL&_foreign_keys=ON", - ) + conn, err := sql.Open("sqlite", indexDSN(path)) if err == nil { configureConnPool(conn) @@ -134,8 +151,8 @@ func New(ctx context.Context, path string) (*DB, error) { _ = conn.Close() } - // If first attempt failed, try with TRUNCATE mode to clear any locks - return openWithRecovery(ctx, path) + // If the first attempt failed, try once more + return retryOpen(ctx, path) } // configureConnPool serializes all database access through one connection. @@ -147,18 +164,12 @@ func configureConnPool(conn *sql.DB) { conn.SetMaxIdleConns(1) } -// finishOpen enables foreign keys, wraps the connection, and applies any -// pending migrations. On migration failure the connection is closed. +// finishOpen wraps the connection and applies any pending migrations. On +// migration failure the connection is closed. func finishOpen(ctx context.Context, conn *sql.DB, path string) (*DB, error) { - // Enable foreign keys explicitly - _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys = ON") - if err != nil { - log.Warn("Failed to enable foreign keys", "path", path, "error", err) - } - db := &DB{conn: conn, path: path} - err = applyMigrations(ctx, conn) + err := applyMigrations(ctx, conn) if err != nil { _ = conn.Close() @@ -168,21 +179,15 @@ func finishOpen(ctx context.Context, conn *sql.DB, path string) (*DB, error) { return db, nil } -// openWithRecovery retries opening the database in TRUNCATE journal mode to -// clear stale locks, then switches back to WAL mode. -func openWithRecovery(ctx context.Context, path string) (*DB, error) { - log.Info( - "Database appears locked, attempting recovery with TRUNCATE mode", - "path", path, - ) +// retryOpen makes a second attempt to open the database, with the same +// settings, after the first attempt failed, for example because another +// process held a lock for longer than the busy timeout. +func retryOpen(ctx context.Context, path string) (*DB, error) { + log.Info("Database appears locked, retrying open", "path", path) - conn, err := sql.Open( - "sqlite", - path+"?_journal_mode=TRUNCATE&_synchronous=NORMAL&_busy_timeout=10000"+ - "&_foreign_keys=ON", - ) + conn, err := sql.Open("sqlite", indexDSN(path)) if err != nil { - return nil, fmt.Errorf("opening database in recovery mode: %w", err) + return nil, fmt.Errorf("opening database on retry: %w", err) } configureConnPool(conn) @@ -190,28 +195,18 @@ func openWithRecovery(ctx context.Context, path string) (*DB, error) { err = conn.PingContext(ctx) if err != nil { log.Debug( - "Failed to ping database in recovery mode, closing", + "Failed to ping database on retry, closing", "path", path, "error", err, ) _ = conn.Close() return nil, fmt.Errorf( - "database still locked after recovery attempt: %w", + "database still locked on retry: %w", err, ) } - log.Debug("Database opened in TRUNCATE mode", "path", path) - - // Switch back to WAL mode - log.Debug("Switching database back to WAL mode", "path", path) - - _, err = conn.ExecContext(ctx, "PRAGMA journal_mode=WAL") - if err != nil { - log.Warn("Failed to switch back to WAL mode", "path", path, "error", err) - } - db, err := finishOpen(ctx, conn, path) if err != nil { return nil, err diff --git a/internal/database/database_test.go b/internal/database/database_test.go index 24cf416..b2fb822 100644 --- a/internal/database/database_test.go +++ b/internal/database/database_test.go @@ -120,6 +120,89 @@ func TestDatabaseConcurrentAccess(t *testing.T) { } } +// TestNewSetsJournalModeAndBusyTimeout checks that the connection settings +// New passes reach SQLite. The driver drops a setting it does not recognise +// without an error, so only reading the value back shows it took effect. +func TestNewSetsJournalModeAndBusyTimeout(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + db, err := New(ctx, filepath.Join(t.TempDir(), "index.db")) + if err != nil { + t.Fatalf("failed to create database: %v", err) + } + + defer func() { _ = db.Close() }() + + var journalMode string + + err = db.conn.QueryRowContext(ctx, "PRAGMA journal_mode").Scan(&journalMode) + if err != nil { + t.Fatalf("reading journal_mode: %v", err) + } + + if journalMode != "wal" { + t.Errorf("journal_mode = %q, want %q", journalMode, "wal") + } + + var busyTimeout int + + err = db.conn.QueryRowContext(ctx, "PRAGMA busy_timeout").Scan(&busyTimeout) + if err != nil { + t.Fatalf("reading busy_timeout: %v", err) + } + + if busyTimeout != busyTimeoutMs { + t.Errorf("busy_timeout = %d, want %d", busyTimeout, busyTimeoutMs) + } +} + +// TestNewWriteSucceedsWhileAnotherHandleReads opens the same index twice, +// as a read-only command does while a backup runs, and checks that a write +// on one handle commits while the other is in the middle of a read. +func TestNewWriteSucceedsWhileAnotherHandleReads(t *testing.T) { + t.Parallel() + + ctx := context.Background() + dbPath := filepath.Join(t.TempDir(), "index.db") + + reader, err := New(ctx, dbPath) + if err != nil { + t.Fatalf("failed to open reading handle: %v", err) + } + + defer func() { _ = reader.Close() }() + + writer, err := New(ctx, dbPath) + if err != nil { + t.Fatalf("failed to open writing handle: %v", err) + } + + defer func() { _ = writer.Close() }() + + // The read lock taken by the SELECT is held until the transaction ends. + readTx, err := reader.BeginTx(ctx, nil) + if err != nil { + t.Fatalf("beginning read transaction: %v", err) + } + + defer func() { _ = readTx.Rollback() }() + + var count int + + err = readTx.QueryRowContext(ctx, "SELECT COUNT(*) FROM chunks").Scan(&count) + if err != nil { + t.Fatalf("reading chunks: %v", err) + } + + _, err = writer.ExecWithLog(ctx, + "INSERT INTO chunks (chunk_hash, size) VALUES (?, ?)", "hash", 1024) + if err != nil { + t.Fatalf("write while another handle reads: %v", err) + } +} + func TestParseMigrationVersion(t *testing.T) { t.Parallel() diff --git a/internal/snapshot/export_perm_test.go b/internal/snapshot/export_perm_test.go index 84e407a..12d79e9 100644 --- a/internal/snapshot/export_perm_test.go +++ b/internal/snapshot/export_perm_test.go @@ -1,40 +1,48 @@ -//nolint:testpackage // exercises the unexported copyFile helper +//nolint:testpackage // exercises the unexported copyDatabase helper package snapshot import ( + "context" "os" "path/filepath" "syscall" "testing" "github.com/spf13/afero" + "sneak.berlin/go/vaultik/internal/database" ) -// TestCopyFileExportCopyMode verifies that the exported snapshot database -// copy is created owner-only (0600), even under a lenient 022 umask that -// would otherwise leave a fresh file world-readable. +// TestCopyDatabaseExportCopyMode verifies that the exported snapshot +// database copy is created owner-only (0600), even under a lenient 022 +// umask that would otherwise leave a fresh file world-readable. // //nolint:paralleltest // syscall.Umask is process-global; parallel tests would clash -func TestCopyFileExportCopyMode(t *testing.T) { +func TestCopyDatabaseExportCopyMode(t *testing.T) { restore := syscall.Umask(0o022) defer syscall.Umask(restore) + ctx := context.Background() dir := t.TempDir() src := filepath.Join(dir, "index.sqlite") - err := os.WriteFile(src, []byte("index data"), 0o600) + db, err := database.New(ctx, src) if err != nil { t.Fatalf("creating source index: %v", err) } + err = db.Close() + if err != nil { + t.Fatalf("closing source index: %v", err) + } + dst := filepath.Join(dir, "snapshot.db") sm := &SnapshotManager{fs: afero.NewOsFs()} - err = sm.copyFile(src, dst) + err = sm.copyDatabase(ctx, src, dst) if err != nil { - t.Fatalf("copyFile: %v", err) + t.Fatalf("copyDatabase: %v", err) } info, err := os.Stat(dst) diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 2fac581..82a12a7 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -386,12 +386,12 @@ func (sm *SnapshotManager) prepareExportDB( ctx context.Context, dbPath, snapshotID, tempDir string, ) ([]byte, string, error) { // Step 1: Copy database to temp file - // The main database should be closed at this point + // The main database is still open here, so it is copied through SQLite tempDBPath := filepath.Join(tempDir, "snapshot.db") log.Debug("Copying database to temporary location", "source", dbPath, "destination", tempDBPath) - err := sm.copyFile(dbPath, tempDBPath) + err := sm.copyDatabase(ctx, dbPath, tempDBPath) if err != nil { return nil, "", fmt.Errorf("copying database: %w", err) } @@ -648,9 +648,10 @@ func (sm *SnapshotManager) collectCleanupStats( // // VACUUM runs through the modernc.org/sqlite driver, on a freshly opened // connection with no transaction in flight (VACUUM cannot run inside one). -// The database opens in WAL mode, so VACUUM's rewrite lands in the WAL; the -// checkpoint on Close flushes it into the main file, which is the file we -// then compress and upload. +// database.New opens the file in WAL mode, so VACUUM's rewrite lands in the +// -wal file. This is the only connection to the file, so closing it +// checkpoints the rewrite into the main file and removes the -wal file; the +// main file is the one compressFile then compresses and uploads. func (sm *SnapshotManager) vacuumDatabase(ctx context.Context, dbPath string) error { log.Debug("Running VACUUM on database", "path", dbPath) @@ -744,26 +745,15 @@ func (sm *SnapshotManager) compressFile(inputPath, outputPath string) error { // user; it holds the same private index data as the local index file. const exportCopyPerm = 0o600 -// copyFile copies a file from src to dst. The destination is the exported -// snapshot database, so it is created owner-only rather than with the -// umask-dependent default. -func (sm *SnapshotManager) copyFile(src, dst string) error { - log.Debug("Opening source file for copy", "path", src) - - sourceFile, err := sm.fs.Open(src) - if err != nil { - return err - } - - defer func() { - log.Debug("Closing source file", "path", src) - - err := sourceFile.Close() - if err != nil { - log.Debug("Failed to close source file", "path", src, "error", err) - } - }() - +// copyDatabase copies the database at src to dst with VACUUM INTO. It reads +// through SQLite, so the copy holds rows committed to src that are still in +// its -wal file, which a copy of the file alone would miss. The destination +// is the exported snapshot database, so it is created empty and owner-only +// first rather than with the umask-dependent default: VACUUM INTO writes +// into an existing empty file and keeps its mode. +func (sm *SnapshotManager) copyDatabase( + ctx context.Context, src, dst string, +) error { log.Debug("Creating destination file", "path", dst) destFile, err := sm.fs.OpenFile( @@ -773,23 +763,28 @@ func (sm *SnapshotManager) copyFile(src, dst string) error { return err } - defer func() { - log.Debug("Closing destination file", "path", dst) - - err := destFile.Close() - if err != nil { - log.Debug("Failed to close destination file", "path", dst, "error", err) - } - }() - - log.Debug("Copying file data") - - n, err := io.Copy(destFile, sourceFile) + err = destFile.Close() if err != nil { return err } - log.Debug("File copy complete", "bytes_copied", n) + db, err := database.New(ctx, src) + if err != nil { + return fmt.Errorf("opening database to copy: %w", err) + } + + defer func() { + cerr := db.Close() + if cerr != nil { + log.Debug("Failed to close database after copy", + "path", src, "error", cerr) + } + }() + + _, err = db.ExecWithLog(ctx, "VACUUM INTO ?", dst) + if err != nil { + return fmt.Errorf("running VACUUM INTO: %w", err) + } return nil } diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go index 42061a2..a0b31bc 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -188,6 +188,77 @@ func TestVacuumDatabaseRemovesDeletedData(t *testing.T) { } } +// TestPrepareExportDBKeepsRowsCommittedToOpenIndex exports from an index +// that is still open, as a backup does. A row committed there can still be +// in the index's -wal file, and the export must hold it all the same. +func TestPrepareExportDBKeepsRowsCommittedToOpenIndex(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + fs := afero.NewOsFs() + + dbPath := filepath.Join(t.TempDir(), "index.sqlite") + + db, err := database.New(ctx, dbPath) + if err != nil { + t.Fatalf("failed to create database: %v", err) + } + + defer func() { _ = db.Close() }() + + repos := database.NewRepositories(db) + + snapshot := &database.Snapshot{ID: "open-index-snapshot", Hostname: "test-host"} + + err = repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + return repos.Snapshots.Create(ctx, tx, snapshot) + }) + if err != nil { + t.Fatalf("failed to create snapshot: %v", err) + } + + sm := &SnapshotManager{ + config: &config.Config{ + CompressionLevel: 3, + AgeRecipients: []string{testAgeRecipient}, + }, + fs: fs, + } + + _, tempDBPath, err := sm.prepareExportDB( + ctx, dbPath, snapshot.ID.String(), t.TempDir()) + if err != nil { + t.Fatalf("prepareExportDB failed: %v", err) + } + + // Only the main database file is compressed and uploaded, so open a + // copy of that file alone. + uploadedPath := filepath.Join(t.TempDir(), "uploaded.db") + + err = copyFile(fs, tempDBPath, uploadedPath) + if err != nil { + t.Fatalf("failed to copy exported database: %v", err) + } + + exported, err := database.OpenReadOnly(ctx, uploadedPath) + if err != nil { + t.Fatalf("failed to open exported database: %v", err) + } + + defer func() { _ = exported.Close() }() + + got, err := database.NewRepositories(exported).Snapshots.GetByID( + ctx, snapshot.ID.String()) + if err != nil { + t.Fatalf("failed to read snapshot from export: %v", err) + } + + if got == nil { + t.Fatal("exported database is missing the snapshot row") + } +} + func TestCleanSnapshotDBEmptySnapshot(t *testing.T) { // Initialize logger log.Initialize(log.Config{}) From 81f83b29f67a1dca5e9b91457548762dea090e79 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 12:46:13 +0200 Subject: [PATCH 011/121] Re-vendor the canonical files from sneak/prompts at dd4027b (closes #213) Linting and testing become the lint and test phases of the Dockerfile, and the build stage depends on both. Dockerfile.lint, CHECK_EPOCH and the tests that checked them are removed. Every docker build in script/ passes --no-cache, and script/cibuild runs script/bootstrap first. A host without Go gets the go.mod version from script/install-go in .tool/go, which bootstrap, the Makefile, fmt, fmt-check, precommit and release add to PATH; fmt-check skips .tool. The image takes its version from the VERSION build arg or git describe, dev without .git. This repo's own entries follow the canonical content in .gitignore and .editorconfig. The golangci-lint v2.14.0 findings are fixed. The rules in CLAUDE.md move into AGENTS.md. IsDevVersion counts "unknown". Model: opus-5-5 --- .dockerignore | 29 +- .editorconfig | 3 + .gitea/workflows/check.yml | 19 +- .gitea/workflows/release.yml | 11 +- .gitignore | 80 ++++-- .golangci.yml | 1 + AGENTS.md | 19 +- CLAUDE.md | 44 --- Dockerfile | 144 +++++----- Dockerfile.lint | 104 ------- Makefile | 26 +- README.md | 167 +++++------ REPO_POLICIES.md | 443 ++++++++++++++++++++++++------ TODO.md | 9 + cmd/vaultik/dockerversion_test.go | 128 ++++++--- cmd/vaultik/lintdocker_test.go | 368 ------------------------- cmd/vaultik/makefile_test.go | 40 ++- internal/config/size.go | 2 - internal/database/chunk_files.go | 2 +- internal/database/chunks.go | 2 +- internal/database/file_chunks.go | 2 +- internal/database/files.go | 2 +- internal/database/snapshots.go | 2 +- internal/globals/globals.go | 15 +- internal/globals/globals_test.go | 3 + internal/snapshot/scanner.go | 3 +- internal/storage/url.go | 3 +- script/bootstrap | 47 ++-- script/check | 5 +- script/cibuild | 86 ++---- script/docker | 41 +-- script/fmt | 2 + script/fmt-check | 9 +- script/install-go | 41 +-- script/lint | 111 +------- script/lint-fix | 17 +- script/precommit | 2 + script/release | 2 + script/test | 70 +---- script/version | 5 +- 40 files changed, 892 insertions(+), 1217 deletions(-) delete mode 100644 CLAUDE.md delete mode 100644 Dockerfile.lint delete mode 100644 cmd/vaultik/lintdocker_test.go diff --git a/.dockerignore b/.dockerignore index 0228778..6b49f01 100644 --- a/.dockerignore +++ b/.dockerignore @@ -17,7 +17,17 @@ # stage that compiles runs `git describe --tags --always` on .git, which # does not need .git/config; that file can hold a credential, such as a # password in a remote URL or the token the CI checkout step stores there. -.git/config +# Each submodule keeps a config with the same exposure in its git directory +# under .git/modules/, nested again for a submodule's own submodules, or in +# its own .git directory when it keeps one. +# KNOWN GAP: a submodule whose name has a `config` segment (`config`, +# `deploy/config`, `config/lib`) loses its whole git directory, because +# `**/.git/modules/**/config` also matches that segment's directory +# under .git/modules/. Go's version stamping then fails the build; +# nothing leaks. Name such a submodule without that segment: +# `git submodule add --name`. +**/.git/config +**/.git/modules/**/config # Agent scratch: one full checkout of the repo per in-flight agent. # Anchored because it occurs once where agents run at the repo root. @@ -41,7 +51,9 @@ **/[iI][dD]_[rR][sS][aA] **/[iI][dD]_[dD][sS][aA] **/[iI][dD]_[eE][cC][dD][sS][aA] +**/[iI][dD]_[eE][cC][dD][sS][aA]_[sS][kK] **/[iI][dD]_[eE][dD]25519 +**/[iI][dD]_[eE][dD]25519_[sS][kK] # Dependencies: restored inside the image, never copied in. **/node_modules @@ -59,12 +71,9 @@ **/.vscode **/*.sublime-* -# This repo's own entries. -.gitea -*.md -LICENSE -vaultik -dist -.tool -coverage.out -coverage.html +# This repo's own host-built artifacts. +/vaultik +/dist +/.tool +/coverage.out +/coverage.html diff --git a/.editorconfig b/.editorconfig index 2fe0ce0..92ec261 100644 --- a/.editorconfig +++ b/.editorconfig @@ -10,3 +10,6 @@ insert_final_newline = true [Makefile] indent_style = tab + +[*.go] +indent_style = tab diff --git a/.gitea/workflows/check.yml b/.gitea/workflows/check.yml index b4e58dc..ee73864 100644 --- a/.gitea/workflows/check.yml +++ b/.gitea/workflows/check.yml @@ -1,14 +1,9 @@ name: check -on: - push: - branches: [main, next] - pull_request: - branches: [main, next] +on: [push] jobs: - check: - runs-on: ubuntu-latest - steps: - # actions/checkout v4, 2024-09-16 - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 - - name: Build and check - run: script/cibuild + check: + runs-on: ubuntu-latest + steps: + # actions/checkout v4.2.2, 2026-02-22 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - run: script/cibuild diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index b083588..9d30f41 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -16,11 +16,12 @@ jobs: fetch-depth: 0 # goreleaser is not a compiler: it shells out to `go` for the # `before:` hook and for every one of the four cross-compiles. - # Nothing else in this repo puts a Go toolchain on the runner -- - # check.yml runs script/cibuild, which does all of its work inside - # the digest-pinned Dockerfile images -- so without this step the - # release either fails at the before-hook or, worse, ships binaries - # built by whatever Go the runner happens to carry. + # Without this step the release either fails at the before-hook or, + # worse, ships binaries built by whatever Go the runner happens to + # carry. check.yml's runner gets the same Go through + # script/bootstrap, which calls script/install-go, and uses it only + # for `go mod download` and gofmt; it compiles inside the + # digest-pinned Dockerfile images. # # actions/setup-go would pin the action by commit sha, but the Go # tarball it downloads at runtime is verified against no value in diff --git a/.gitignore b/.gitignore index df0dea6..fe7bf4a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,28 +1,62 @@ -# Binary -/vaultik - -# goreleaser output -/dist/ - -# Locally installed pinned tools (script/install-goreleaser) -/.tool/ - -# Test artifacts -*.out -*.test -coverage.html -coverage.out - -# IDE -.vscode/ -.idea/ -*.swp -*.swo - # OS .DS_Store Thumbs.db -# Local config for development +# Editors +*.swp +*.swo +*~ +*.bak +.idea/ +.vscode/ +*.sublime-* + +# Agent scratch (worktrees of this repo, created and destroyed by +# in-flight tooling). Unanchored: .gitignore patterns already match at +# every depth, so no prefix is wanted here. This is not a .dockerignore +# entry and must not be given a `**/` prefix on the way into one. +.claude/ + +# Node +node_modules/ + +# Secrets. Unanchored like every entry above, so each matches at every +# depth. Matching is case-sensitive on Linux, so names use character +# ranges rather than a lowercase form that misses `Server.Key`. + +# Environment files. `*.env` covers bare `.env` and the `prod.env` +# convention. Only the templates `example.env` and `sample.env` are +# re-included below. A repository that commits any other template adds +# its own negation after these lines, for example `!.env.example`. +*.[eE][nN][vV] +.[eE][nN][vV].* +.[eE][nN][vV][rR][cC] +!example.env +!sample.env + +# Private keys and the bundles carrying them. +*.[pP][eE][mM] +*.[kK][eE][yY] +*.[pP]12 +*.[pP][fF][xX] +[iI][dD]_[rR][sS][aA] +[iI][dD]_[dD][sS][aA] +[iI][dD]_[eE][cC][dD][sS][aA] +[iI][dD]_[eE][cC][dD][sS][aA]_[sS][kK] +[iI][dD]_[eE][dD]25519 +[iI][dD]_[eE][dD]25519_[sS][kK] + +# Go build and test output. +*.log +*.out +*.test +coverage.html + +# This repo's own host-built artifacts. +/vaultik +/dist/ +/.tool/ + +# Local configs for development; they hold storage credentials. local-config.yaml -dev-config.yaml \ No newline at end of file +dev-config.yaml diff --git a/.golangci.yml b/.golangci.yml index d8179d9..39d54d2 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -17,6 +17,7 @@ linters: disable: # Genuinely incompatible with project patterns - exhaustruct # Requires all struct fields + - exhaustruct_v5 # Requires all struct fields (successor to exhaustruct) - godot # Requires comments to end with periods - wrapcheck # Too verbose for internal packages - varnamelen # Short names like db, id are idiomatic Go diff --git a/AGENTS.md b/AGENTS.md index 2f93504..2f253ae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -108,6 +108,23 @@ Version: 2025-06-08 code that touches the affected tables) directly. After 1.0, each schema change is a new numbered file in that directory and a released file is never edited; an existing local database is then migrated when vaultik - is updated. See + is updated. Before 1.0, a local database left on an older schema is + deleted and re-created by a full backup. See [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations). +14. Never use `git add -A`. Stage only the files you intentionally + changed. + +15. Commit messages carry no attribution or advertising trailers for the + tool that helped write the code, or for its vendor: the owner is the + sole author of code written with a tool. + +16. Run the whole test suite with `make test` every time, and read its full + output. Never run `go test`, a single test or a single package, and + never grep the output. + +17. Do not stop working on a task until the definition of done given in the + initial instruction is met: all of the work, not part or most of it. + +18. For estimates: backing up over 2.5Gbit/s ethernet to an S3 server + backed by 2000MB/sec SSD takes about 4 seconds per gigabyte. diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 7b5788e..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,44 +0,0 @@ -# Rules - -Read the rules in AGENTS.md and follow them. - -# Memory - -* Claude is an inanimate tool. The spam that Claude attempts to insert into - commit messages (which it erroneously refers to as "attribution") is not - attribution, as I am the sole author of code created using Claude. It is - corporate advertising for Anthropic and is therefore completely - unacceptable in commit messages. - -* NEVER use `git add -A`. Always add only the files you intentionally - changed. - -* Tests should always be run before committing code. No commits should be - made that do not pass tests. - -* Code should always be formatted before committing. Do not commit - unformatted code. - -* Code should always be linted before committing. Do not commit - unlinted code. - -* The test suite is fast and local. When running tests, don't run - individual parts of the test suite, always run the whole thing by running - "make test". - -* Do not stop working on a task until you have reached the definition of - done provided to you in the initial instruction. Don't do part or most of - the work, do all of the work until the criteria for done are met. - -* We do not add migrations before 1.0; schema upgrades can be handled by - deleting the local state file and doing a full backup to re-create it. - -* When testing on a 2.5Gbit/s ethernet to an s3 server backed by 2000MB/sec SSD, - estimate about 4 seconds per gigabyte of backup time. - -* When running tests, don't run individual tests, or grep the output. run - the entire test suite every time and read the full output. - -* When running tests, don't run individual tests, or try to grep the output. - never run "go test". only ever run "make test" to run the full test - suite, and examine the full output. diff --git a/Dockerfile b/Dockerfile index 6d4eb31..b769346 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,92 +1,76 @@ -# This file has no lint stage, deliberately. -# -# Linting lives in Dockerfile.lint, built by script/lint, and -# script/cibuild builds both. A lint stage here would have to either -# shell out to `make lint` -- which is now `docker build`, so -# docker-in-docker inside a BuildKit step with no daemon -- or call -# golangci-lint directly, which would mean a second, independently -# bumpable digest pin for the linter alongside the one in -# Dockerfile.lint. Two pins for one tool is the drift that -# https://git.eeqj.de/sneak/vaultik/issues/78 was filed over. See -# https://git.eeqj.de/sneak/vaultik/issues/113 for the ruling. -# -# Consequence, stated rather than left to be discovered: script/docker -# builds this file only and therefore does not lint. `make fmt-check` -# and `make test` still run here, so what a green build of this file -# means is "formatted, tested, and it compiles" -- the lint verdict -# comes from script/lint or script/cibuild. - -# Build stage -# golang:1.26.1-alpine, 2026-03-17 -FROM golang:1.26.1-alpine@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 AS builder - -# Build tooling: make, plus a C toolchain because `go test -race` needs cgo, -# and git, which derives the version below. The sqlite driver is pure Go -# (modernc.org/sqlite), so no sqlite library or CLI is required. -RUN apk add --no-cache make build-base git - +# Lint phase. The linter is invoked directly rather than through `make +# lint` or `script/lint`, which are themselves a docker build and would +# recurse into a daemon that does not exist in a build step. +# golangci/golangci-lint:v2.14.0, 2026-10-05 +FROM golangci/golangci-lint:v2.14.0@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f AS lint WORKDIR /src - -# Copy go mod files first for better layer caching COPY go.mod go.sum ./ RUN go mod download +COPY . . +# `golangci-lint run` silently ignores an unknown top-level key in +# .golangci.yml, such as a misspelt `linters:`; `config verify` fails on it. +RUN golangci-lint config verify --config .golangci.yml +RUN golangci-lint run --config .golangci.yml ./... -# Copy source code +# Test phase. -race needs cgo and so a C compiler, which the Debian Go +# image ships and the alpine one does not. +# golang:1.26.1 (Debian trixie), 2026-10-05 +FROM golang:1.26.1@sha256:cd78d88e00afadbedd272f977d375a6247455f3a4b1178f8ae8bbcb201743a8a AS test +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN go test -timeout 90s -race -cover ./... || \ + { echo "--- Rerunning with -v for details ---"; \ + go test -timeout 90s -race -v ./...; exit 1; } + +# Build stage. Nothing is wanted from either phase above; the copies +# are what make BuildKit build them first, so this stage cannot run +# unless lint and test passed. +# golang:1.26.1-alpine, 2026-03-17 +FROM golang:1.26.1-alpine@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 AS builder +COPY --from=lint /src/go.sum /dev/null +COPY --from=test /src/go.sum /dev/null +RUN apk add --no-cache git +# A tar-stream context keeps the sender's file owners, which git refuses. +RUN git config --system --add safe.directory /src +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download COPY . . -# Run the format check and the tests. -# -# CHECK_EPOCH must stay immediately above these RUNs. These layers are -# keyed on its value, so they are cache-eligible only for a value -# already built against this same tree. script/cibuild and script/docker -# each pass a fresh value on every invocation, which is what makes their -# green mean the checks really executed. -# -# The value is expanded into each check command rather than left to a -# bare declaration, so the cache miss does not depend on BuildKit's -# unreferenced-ARG handling staying as it is. It also puts the epoch in -# the build log, where a reader can see the layer was keyed fresh. -# -# A build that passes no CHECK_EPOCH, such as a plain `docker build .`, -# keys these layers on the empty string, so rebuilding an unchanged -# checkout replays them from cache and runs nothing. Only the scripts' -# builds mean the checks executed. -# -# Everything above this line (apk, go.mod, `go mod download`) is -# deliberately outside the busted range and keeps caching. -ARG CHECK_EPOCH -RUN echo "check epoch: ${CHECK_EPOCH}" && make fmt-check -RUN echo "check epoch: ${CHECK_EPOCH}" && make test - -# Version, commit and build date: the build args when given (script/docker -# and script/cibuild pass the ones they compute on the host), otherwise -# derived from the .git in the build context. The version is then `git -# describe --tags --always`: the tag on a tagged commit, tag-N-gHASH after -# one, the short commit when no tag is reachable. A context that carries -# .git and still yields no version fails the build; one without .git, as -# from a source tarball, stamps "dev" and an "unknown" commit and date. -# -# These ARGs sit here, after the checks, rather than at the top of the -# stage: every commit changes their values, and a value change -# invalidates all layers below the ARG. Declared up top they would bust -# `go mod download`; here they only rekey this build layer, which the -# COPY of the sources above already rebuilds on any change anyway. +# The VERSION build arg when one is given, otherwise +# `git describe --tags --always` on the .git in the build context. The +# commit and its date always come from that .git. With .git present, a +# version that is still empty, dev or unknown, or a commit or date that +# is unknown, fails the build: git is missing or could not read the +# checkout, as when .git is a file pointing outside the context. A +# context without .git, such as a source export, stamps "dev" and an +# "unknown" commit and date. ARG VERSION -ARG COMMIT -ARG COMMIT_DATE - -# Build (pure Go, no CGO required since we use modernc.org/sqlite) -RUN version="${VERSION:-$(git describe --tags --always || echo dev)}"; \ - if [ -e .git ] && { [ -z "$version" ] || [ "$version" = dev ] || \ - [ "$version" = unknown ]; }; then \ - echo "the build context carries .git but yields no version" >&2; \ - exit 1; \ +RUN VERSION="${VERSION:-$(git describe --tags --always || echo dev)}"; \ + commit="$(git rev-parse HEAD || echo unknown)"; \ + commit_date="$(git show -s --format=%cs HEAD || echo unknown)"; \ + if [ -e .git ]; then \ + case "$VERSION" in ""|dev|unknown) \ + echo "version is '$VERSION' although .git is present" >&2; \ + exit 1 ;; \ + esac; \ + if [ "$commit" = unknown ] || [ "$commit_date" = unknown ]; then \ + echo "commit is '$commit' and its date '$commit_date'" \ + "although .git is present" >&2; \ + exit 1; \ + fi; \ fi; \ - commit="${COMMIT:-$(git rev-parse HEAD || echo unknown)}"; \ - commit_date="${COMMIT_DATE:-$(git show -s --format=%cs HEAD || echo unknown)}"; \ - CGO_ENABLED=0 go build -ldflags "-X 'sneak.berlin/go/vaultik/internal/globals.Version=${version}' -X 'sneak.berlin/go/vaultik/internal/globals.Commit=${commit}' -X 'sneak.berlin/go/vaultik/internal/globals.CommitDate=${commit_date}'" -o /vaultik ./cmd/vaultik + globals=sneak.berlin/go/vaultik/internal/globals; \ + CGO_ENABLED=0 go build -trimpath \ + -ldflags="-s -w -X ${globals}.Version=${VERSION} \ + -X ${globals}.Commit=${commit} \ + -X ${globals}.CommitDate=${commit_date}" \ + -o /vaultik ./cmd/vaultik -# Runtime stage +# Runtime stage, and the last one: a plain `docker build .` builds this +# stage's chain and nothing else. # alpine:3.21, 2026-02-25 FROM alpine:3.21@sha256:c3f8e73fdb79deaebaa2037150150191b9dcbfba68b4a46d70103204c53f4709 diff --git a/Dockerfile.lint b/Dockerfile.lint deleted file mode 100644 index 4e39700..0000000 --- a/Dockerfile.lint +++ /dev/null @@ -1,104 +0,0 @@ -# Lint image. -# -# Every lint run in this repo happens inside this image, invoked through -# script/lint, and linting is a BUILD STEP rather than a container -# command: a successful build of this file IS a clean lint. That shape -# also works where the docker daemon is remote and bind mounts are -# impossible, which `docker run` against a mounted worktree does not. -# -# This FROM line is the single source of truth for the linter version in -# this repo. Nothing else pins golangci-lint: the product Dockerfile has -# no lint stage, deliberately, so there is no second digest to bump and -# no pair of pins that can drift apart. Bump the tag AND the digest here -# and nowhere else. -# -# Note for readers coming from REPO_POLICIES.md: that document still -# describes the older pattern, a lint stage inside the product -# Dockerfile wired up with `COPY --from=lint /src/go.sum /dev/null`. -# That pattern is superseded here by the owner's ruling recorded in -# https://git.eeqj.de/sneak/vaultik/issues/113 -- lint runs in its own -# image, per run, with its own cache and its own lock, which is what -# makes concurrent runs on one host safe. The policy text is org-wide -# and is being amended separately; this file is what this repo does. -# -# golangci/golangci-lint:v2.12.2, 2026-08-10 -FROM golangci/golangci-lint:v2.12.2@sha256:5cceeef04e53efe1470638d4b4b4f5ceefd574955ab3941b2d9a68a8c9ad5240 - -WORKDIR /src - -# Copy the dependency manifests first so the module download layer stays -# cached until they change. Everything above the ARG below is cacheable -# on purpose; a cold module download on every lint would make the inner -# loop unusable and buys nothing, because it is not what the gate is -# asserting. -COPY go.mod go.sum ./ -RUN go mod download - -COPY . . - -# Force the check layers to execute on every invocation. -# -# CHECK_EPOCH must stay immediately above the RUNs below. Those layers -# are keyed on its value, so they are cache-eligible only for a value -# already built against this same tree; script/lint and script/cibuild -# each pass a fresh value on every invocation, which is what makes their -# green mean the linter really ran. Without it, `docker build -f -# Dockerfile.lint .` on an unchanged tree exits 0 in well under a second -# having linted nothing. -# -# The value is expanded into each check command itself rather than left -# to a bare declaration, so the cache miss does not depend on BuildKit's -# unreferenced-ARG handling staying as it is. It also puts the epoch in -# the build log, where a reader can see the layer was keyed fresh. -# -# The guard is what makes a build that omits --build-arg fail instead of -# lie. An unset ARG is an empty string, and an empty string is a -# perfectly stable cache key: without the guard the first such build -# lints and every one after it on an unchanged tree replays this layer, -# executes nothing, and still exits 0. Failed steps are never cached, so -# the guard fails on EVERY invocation rather than once. Do not give -# CHECK_EPOCH a default value; a default would satisfy the guard with a -# constant and restore the hole. -ARG CHECK_EPOCH -RUN [ -n "$CHECK_EPOCH" ] || exit 1 - -# Validate .golangci.yml before linting with it. -# -# This is not belt-and-braces; it closes a hole that `golangci-lint run` -# leaves wide open. `run` rejects YAML it cannot PARSE, but it silently -# IGNORES an unknown top-level KEY. Renaming `linters:` to `linterz:` -- -# one character -- discards `default: all`, the whole disable list and -# every threshold, leaves only golangci-lint's small default linter set -# running, and exits 0 reporting `0 issues.` on a tree the real config -# fails. Demonstrated on this repo at this pin, recorded on -# https://git.eeqj.de/sneak/vaultik/pulls/114: with a planted -# over-length line, `script/lint` exits 1 naming the `revive` finding -# with `linters:` and exits 0 with `linterz:`. A set-but-ineffective -# config quietly falling back to defaults is precisely the false-green -# class this gate exists to eliminate, so it must not sit in the gate's -# own configuration. -# -# `config verify` catches it, and it does so OFFLINE at this pinned -# version -- verified, not assumed. Under `docker run --network none` -# against the pinned digest it exits 0 on this repo's config and exits 3 -# on the `linterz:` variant with `additional properties 'linterz' not -# allowed`. An earlier revision of this file asserted the opposite, that -# the schema is fetched over live HTTPS from an unpinned URL, and used -# that to justify omitting this line. That claim was false at v2.12.2; -# the schema is embedded. If a future bump reintroduces a network fetch -# the failure is loud and this comment is where to record it. -# -# It is keyed on CHECK_EPOCH, like the lint run below, so it executes on -# every invocation. Content-addressing alone would arguably be enough -- -# .golangci.yml arrives through `COPY . .`, so a cache hit here implies -# a byte-identical config was validated when the layer really ran. That -# argument is exactly the one that would also excuse caching the lint -# layer, and this repo has ruled it insufficient: a cached check layer -# checks nothing, and the cost of being wrong is silent. Forcing it costs -# milliseconds and puts the epoch in the log, where a reader can see that -# this validation ran rather than being replayed. -RUN echo "check epoch: ${CHECK_EPOCH}" && \ - golangci-lint config verify --config .golangci.yml - -RUN echo "check epoch: ${CHECK_EPOCH}" && \ - golangci-lint run --config .golangci.yml ./... diff --git a/Makefile b/Makefile index d0e60c2..f694dd5 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,8 @@ .PHONY: all bootstrap setup check test lint lint-fix fmt fmt-check build clean deps test-coverage local install release release-snapshot docker hooks +# Where script/bootstrap installs Go when the host has none. +export PATH := $(PATH):$(CURDIR)/.tool/go/bin + # Version number, derived from git by script/version (`git describe # --tags --always --dirty`). This used to be a hardcoded # constant, which meant every local build claimed to be a release that @@ -40,9 +43,10 @@ setup: check: @script/check -# Run tests only. This runs the ENTIRE suite -- there is no separate -# integration target and no build-tagged subset held back. In -# particular internal/vaultik/integration_test.go, which does full +# Run tests only, by building the test phase of the Dockerfile. This +# runs the ENTIRE suite -- there is no separate integration target and +# no build-tagged subset held back. In particular +# internal/vaultik/integration_test.go, which does full # chunk -> pack -> encrypt -> upload -> restore round-trips, runs here. # A `test-integration` target used to exist and was removed: no file in # the repo carried a build tag, so `-tags=integration` selected nothing @@ -87,17 +91,17 @@ clean: go clean # Install dependencies. The linter is deliberately not installed here: -# script/lint lints by building Dockerfile.lint, whose FROM line is the -# single source of truth for the linter version. A second, separately -# pinned copy on PATH could drift from it and make a local `make lint` -# disagree with CI. +# script/lint lints by building the lint phase of the Dockerfile, whose +# FROM line is the single source of truth for the linter version. A +# second, separately pinned copy on PATH could drift from it and make a +# local `make lint` disagree with CI. deps: go mod download -# Run tests with coverage. -count=1 for the same reason script/test -# uses it: without it an unchanged package is served from Go's test -# result cache, and a coverage profile assembled from cached results -# describes a run that did not happen. +# Run tests with coverage, on the host. -count=1 because without it an +# unchanged package is served from Go's test result cache, and a +# coverage profile assembled from cached results describes a run that +# did not happen. test-coverage: go test -v -count=1 -coverprofile=coverage.out ./... go tool cover -html=coverage.out -o coverage.html diff --git a/README.md b/README.md index ecd7622..71011d1 100644 --- a/README.md +++ b/README.md @@ -728,12 +728,11 @@ regardless of color setting (emoji are not color). ## requirements * Go 1.26 or later -* Docker, with a reachable daemon, to lint, check, or commit: - `script/lint` lints by building `Dockerfile.lint`, which runs the - digest-pinned `golangci-lint` image as a build step, and `make check` - and the pre-commit hook both run it. A `golangci-lint` installed on - `PATH` is not a substitute and is never used on a host, whatever its - version. +* Docker, with a reachable daemon, to test, lint, check, or commit: + `script/test` and `script/lint` build the `test` and `lint` phases of + the `Dockerfile`, and `make check` and the pre-commit hook both run + them. A `golangci-lint` installed on `PATH` is not a substitute and is + never used on a host, whatever its version. * S3-compatible object storage (or local filesystem, or rclone remote) ## development workflow @@ -764,17 +763,20 @@ standard: normalized scripts in `script/` are the entrypoints for the development workflow, and the Makefile targets are thin shims that call them. We provide: -* `script/bootstrap` — install all development dependencies (go, Go - module download). It deliberately does not install `golangci-lint`; - see `script/lint` below. +* `script/bootstrap` — install all development dependencies (Go, Go + module download). A host without Go gets the `go.mod` version through + `script/install-go`, in `.tool/go`, which `script/bootstrap` itself, + the `Makefile`, `script/fmt`, `script/fmt-check`, `script/precommit` + and `script/release` add to their `PATH`. It + deliberately does not install `golangci-lint`; see `script/lint` + below. * `script/setup` — make a fresh clone ready for development: runs `script/bootstrap`, then `script/install-precommit` * `script/projectname` — print the project name (used for the Docker image tag) * `script/version` — print the version string to bake into the binary. - The `Makefile`'s `LDFLAGS` call this, and `script/docker` and - `script/cibuild` pass its output to the image build. See - [releasing](#releasing) for the rules. + The `Makefile`'s `LDFLAGS` call this. See [releasing](#releasing) for + the rules. * `script/install-goreleaser` — install the pinned `goreleaser` into `.tool/bin` from a sha256-verified release archive. Idempotent, and called by `script/bootstrap`; the release workflow calls it directly @@ -782,102 +784,59 @@ them. We provide: `script/bootstrap` insists on. * `script/install-go` — install the Go toolchain named by `go.mod`'s `go` directive into `.tool/go` from a sha256-verified `go.dev` - archive, and put it on `PATH`. Idempotent. Called only by the release - workflow, which needs a host Go for `goreleaser` to shell out to; - nothing else on the release runner does. `actions/setup-go` is not - used because it verifies the downloaded toolchain against no value in - this repo. Bumping Go edits `go.mod`, the checksum in this script, and - the `Dockerfile` `golang` digest together. + archive, for Linux or macOS on amd64 or arm64. Idempotent. On a CI + runner it also puts `.tool/go/bin` on `PATH` for the steps that + follow. Called by the release workflow, which needs a host Go for + `goreleaser` to shell out to, and by `script/bootstrap` on a host + without Go. `actions/setup-go` is not used because it verifies the + downloaded toolchain against no value in this repo. Bumping Go edits + `go.mod`, the checksums in this script, and the two `golang` digests + in the `Dockerfile` together. * `script/release` — cross-compile and publish the release artifacts with the pinned `goreleaser`. Refuses a `goreleaser` on `PATH` whose version is not the pinned one, on the same reasoning as `script/lint`. * `script/release-snapshot` — the same build with no publishing and no tagging, into `./dist` -* `script/test` — run the test suite (verbose rerun on failure). This - runs *everything*: there is no separate integration target and no - build-tagged subset held back, so the full round-trip tests in - `internal/vaultik/integration_test.go` run on every invocation. It - passes `-count=1`, which disables Go's test result cache. That is - deliberate and it is not free: on this repo's suite it costs about 11 - seconds on every repeat run (measured, back to back: 0.4s cached - versus 11.6s with `-count=1`). That is the price of the run meaning - anything, because without it an unchanged package prints - `ok (cached)`, which is indistinguishable from a package that - really ran, so the whole suite can report a full set of `ok` lines in - under half a second having executed nothing. The `-timeout` is a hang - backstop rather than a performance budget — it applies per test binary - to test execution only, not to compilation — and is set well above the - slowest package's measured runtime. Its 120s value deliberately - diverges from the 30s `REPO_POLICIES.md` mandates; the reasoning is in - the comment in the script, and issue #101 proposes amending the policy - text. -* `script/lint` — lint by building `Dockerfile.lint`, which runs - `golangci-lint run --config .golangci.yml ./...` as a build step - inside the digest-pinned `golangci-lint` image, so a successful build - *is* a clean lint. Nothing lints on the host, at any version, ever; - the script requires Docker and fails loudly rather than falling back - to a `golangci-lint` on `PATH`. That `FROM` line is the single source - of truth for the linter version — bump it there and nowhere else. - - It takes no arguments, because a build step has no command line to - pass flags to, and it passes a fresh `--build-arg CHECK_EPOCH` on - every invocation so the lint layer cannot be replayed from cache (see - `script/cibuild` below for what that mechanism defends against). To - watch the linter execute, run it as - `BUILDKIT_PROGRESS=plain script/lint` and check that the lint layer - says `RUN … golangci-lint` rather than `CACHED`. - - One container per run means one lint cache and one `golangci-lint` - lock per run, both private to it and discarded with it, so concurrent - runs on one host cannot contaminate or block each other. +* `script/test` — run the test suite by building the `test` phase of + the `Dockerfile` (verbose rerun on failure). This runs *everything*: + there is no separate integration target and no build-tagged subset + held back, so the full round-trip tests in + `internal/vaultik/integration_test.go` run on every invocation. The + 90s `-timeout` is a hang backstop rather than a performance budget; it + applies per test binary, to test execution only. +* `script/lint` — lint by building the `lint` phase of the + `Dockerfile`, which runs `golangci-lint config verify` and then + `golangci-lint run --config .golangci.yml ./...` as build steps in + the digest-pinned `golangci-lint` image. Nothing lints on the host. + That `FROM` line is the only pin of the linter version, and it changes + in the same commit as a re-vendored `.golangci.yml`. * `script/lint-fix` — apply the linter's autofixes (rewrites files), - using the same pinned image, parsed out of `Dockerfile.lint`. It - cannot be a build step, because fixes have to land in the worktree, so - it bind-mounts the tree into a `docker run` and therefore needs a - *local* daemon. It is a developer convenience and never a gate: no - gate reads its exit status. Run `make lint` afterwards to find out - whether the tree is clean. + using the same pinned image, parsed out of the `lint` phase's `FROM` + line. It cannot be a build step, because fixes have to land in the + worktree, so it bind-mounts the tree into a `docker run` and therefore + needs a *local* daemon. It is a developer convenience and never a + gate: no gate reads its exit status. Run `make lint` afterwards to + find out whether the tree is clean. * `script/fmt` — format all code (writes) -* `script/fmt-check` — check formatting (read-only) +* `script/fmt-check` — check formatting (read-only). It runs `gofmt` on + the host, over every Go file outside `.tool`. * `script/check` — run `script/test`, `script/lint`, and - `script/fmt-check`. This is authoritative *because* `script/lint` - builds `Dockerfile.lint`: a local `make check` and CI cannot disagree - about lint findings. + `script/fmt-check`. * `script/docker` — build the Docker image tagged via - `script/projectname`. Passes a fresh `--build-arg CHECK_EPOCH` for the - same reason `script/cibuild` does, so a local image build cannot be - green on checks it replayed from cache. It builds the *product* image - only, and the product `Dockerfile` has no lint stage, so it does not - lint: a green here means formatted, tested, and it compiles. -* `script/cibuild` — CI entrypoint, and the full gate. Two builds, in - order: `Dockerfile.lint` (the linter, as a build step) and then - `Dockerfile` (`make fmt-check` and `make test` in its builder stage, - then the product image). Either failing fails the script. It runs the - checks in the same containers CI does, from a clean copy of the tree, - so it also catches anything that depends on host state. - `.gitea/workflows/check.yml` runs it on every push to `main` and - `next` and on every pull request against either. + `script/projectname`, stamped with the version + `git describe --tags --always --dirty` gives on the host, or `unknown` + outside a git checkout. The image's build stage depends on the `lint` + and `test` phases, so this lints and tests too. +* `script/cibuild` — CI entrypoint: runs `script/bootstrap`, + `script/check`, and then the same image build as `script/docker`. + `.gitea/workflows/check.yml` runs it on every push. - It passes a fresh `--build-arg CHECK_EPOCH` to each build, unique per - invocation, which both files declare immediately above their check - `RUN`s and expand into each check command. Those layers are keyed on - that value, so a new value re-runs them even on a byte-identical tree, - and a green from this script means the checks executed. Dependency and - module layers sit above the `ARG` and still cache, so a build is not - cold. - - A `docker build -f Dockerfile.lint .` that supplies no `CHECK_EPOCH` - fails rather than lying. An unset `ARG` is an empty string and an - empty string is a stable cache key, so without a guard such a build - would serve the lint layer from cache, execute nothing, and still exit - 0. `Dockerfile.lint` therefore asserts the value is non-empty before - running anything, and because failed steps are never cached that - assertion fires on every invocation rather than once. The product - `Dockerfile` has no such guard, because a plain `docker build .` must - succeed: without `CHECK_EPOCH`, rebuilding an unchanged checkout - replays its check layers from cache. Use `script/lint`, - `script/docker` or `script/cibuild`, which pass the arg, when the - checks must run. + Every `docker build` in these scripts passes `--no-cache`, because on + an unchanged tree a cached check layer is replayed without running and + the build still exits 0. A plain `docker build .` is therefore no + evidence that the checks ran. The cost is that `script/cibuild` runs + the `lint` and `test` phases twice: once in `script/check` and again + in the image build. * `script/precommit` — pre-commit gate: `go mod tidy` + `go fmt` (must not change files), then `script/check` * `script/install-precommit` — install the git pre-commit hook that @@ -889,8 +848,8 @@ them. We provide: The version a binary reports comes from git, not from a constant in a file. It is `git describe --tags --always --dirty`, which -`script/version` runs for the `Makefile`, `script/docker` and -`script/cibuild`: +`script/version` runs for the `Makefile`, and `script/docker` and +`script/cibuild` run themselves: * `HEAD` is exactly on a tag → that tag, such as `v1.0.0`. * a commit after a tag → `--g`. @@ -901,15 +860,17 @@ file. It is `git describe --tags --always --dirty`, which A `docker build .` of a clone, with no build arguments, runs the same `git describe` (without `--dirty`) on the `.git` in its build context, so it stamps the same value for a clean commit; the build fails if the -context carries `.git` and no version comes out. A binary built without -git metadata reports `dev`. +context carries `.git` and no version, commit or commit date comes out. +A binary built without +git metadata reports `dev`, or `unknown` when `script/docker` or +`script/cibuild` built it outside a git checkout. `goreleaser` stamps a release binary with the tag minus its leading `v`, so the tag `v1.0.0` produces `vaultik 1.0.0`, matching the archive name `vaultik_1.0.0_linux_amd64.tar.gz`. `goreleaser --snapshot` stamps `dev-<12 chars of the commit sha>` rather than inventing the next patch number. `vaultik version` calls a build a development build when its -version is `dev`, `dev-`, the short commit sha or +version is `dev`, `unknown`, `dev-`, the short commit sha or `--g`, with or without `-dirty`; only a plain tag, such as `v1.0.0` or `1.0.0`, is a release. If `script/version` cannot be run at all, `make` stops with an error instead of building an diff --git a/REPO_POLICIES.md b/REPO_POLICIES.md index bc2f161..20382d1 100644 --- a/REPO_POLICIES.md +++ b/REPO_POLICIES.md @@ -1,6 +1,6 @@ --- title: Repository Policies -last_modified: 2026-07-06 +last_modified: 2026-10-04 --- This document covers repository structure, tooling, and workflow standards. Code @@ -60,17 +60,28 @@ style conventions are in separate documents: prerequisite since nvm requires bash. yarn is then pinned via `corepack prepare yarn@ --activate`. Never install "latest" or "lts"; always exact versions. `script/cibuild` runs the CI build: it changes to the - repo root and runs `docker build .`; the Gitea workflow calls it. Four further - scripts are our own extensions to the standard: `script/check` runs - `script/test`, `script/lint`, and `script/fmt-check`; `script/precommit` is - what the git pre-commit hook runs, and it calls `script/check`; - `script/install-precommit` installs the git pre-commit hook (the `make hooks` - target shims to it); and `script/projectname` (literally that filename) simply - outputs the project's name. Scripts that need the name call - `script/projectname` — e.g. `script/docker` assembles its image tag from it — - so those scripts stay byte-identical across all repos. Repo-type-specific - pre-commit extras (e.g. `go mod tidy` verification in Go repos) belong in - `script/precommit`, not in the hook itself. Model scripts are at + repo root, runs `script/bootstrap`, runs `script/check`, and builds the image + with the version; the Gitea workflow calls it. **`script/cibuild` runs + `script/bootstrap` first**, because the workflow checks out the repo and runs + nothing else, while `script/fmt-check` runs the formatter on the host: on a + pristine checkout with nothing installed the run dies there, after the + containerised gates have passed. **The bootstrap alone is not enough**: + `script/bootstrap` installs node and yarn under nvm and leaves neither on the + `PATH` of the shell that called it, so a bare `yarn` still exits 127. The host + entrypoints that need yarn — `script/fmt` and `script/fmt-check` — therefore + source nvm for the pinned node version before invoking it, exactly as + `script/bootstrap`'s own install step does. A runner carrying nothing but + docker and git then gets through `script/check`. Four further scripts are our + own extensions to the standard: `script/check` runs `script/test`, + `script/lint` and `script/fmt-check`; `script/precommit` is what the git + pre-commit hook runs, and it calls `script/check`; `script/install-precommit` + installs the git pre-commit hook (the `make hooks` target shims to it); and + `script/projectname` (literally that filename) simply outputs the project's + name. Scripts that need the name call `script/projectname` — e.g. + `script/docker` assembles its image tag from it — so those scripts stay + byte-identical across all repos. Repo-type-specific pre-commit extras (e.g. + `go mod tidy` verification in Go repos) belong in `script/precommit`, not in + the hook itself. Model scripts are at `https://git.eeqj.de/sneak/prompts/raw/branch/main/script/`. The README must document the provided scripts in an **Entrypoints** section (see the README requirements below). @@ -89,87 +100,198 @@ style conventions are in separate documents: contributor should be able to understand the entire development workflow by reading the Makefile. -- Every repo should have a `Dockerfile`. All Dockerfiles must run `make check` - as a build step so the build fails if the branch is not green. For non-server - repos, the Dockerfile should bring up a development environment and run - `make check`. For server repos, `make check` should run as an early build - stage before the final image is assembled. Dockerfiles install development - prerequisites by running `script/bootstrap` rather than duplicating installs - inline; COPY `script/` and the dependency manifests (`package.json` + - `yarn.lock`, `go.mod` + `go.sum`, etc.) before running it so the bootstrap - layer stays cached until dependencies change. +- Every repo should have a `Dockerfile`, and it carries the repo's gates: a + `lint` phase and a `test` phase, with the final stage depending on both so the + image cannot be built unless they pass. For non-server repos the final stage + brings up a development environment; for server repos it is the runtime image. + The gate phases and the build stage start from their pinned base images and + install what those images lack either inline, as the canonical Go `Dockerfile` + below does for `git`, or by running `script/bootstrap`, as the `prompts` + repo's own `Dockerfile` does for its yarn packages. The development + environment stage installs development prerequisites by running + `script/bootstrap` rather than duplicating its installs inline. A stage that + runs `script/bootstrap` COPYs `script/` and the dependency manifests + (`package.json` + `yarn.lock`, `go.mod` + `go.sum`, etc.) before running it. -- **Dockerfiles must use a separate lint stage for fail-fast feedback.** Go - repos use a multistage build where linting runs in an independent stage based - on the `golangci/golangci-lint` image (pinned by hash). This stage runs - `make fmt-check` and `make lint` before the full build begins. The build stage - then declares an explicit dependency on the lint stage via - `COPY --from=lint /src/go.sum /dev/null`, which forces BuildKit to complete - linting before proceeding to compilation and tests. This ensures lint failures - surface in seconds rather than minutes, without blocking on dependency - download or compilation in the build stage. +- **Linting and testing run in Docker, as phases of the `Dockerfile`.** There is + no separate lint file. `script/lint` and `script/test` each build one phase + and nothing else: - The standard pattern for a Go repo Dockerfile is: + ```sh + docker build --no-cache --target lint -t "$(script/projectname)-lint" . + docker build --no-cache --target test -t "$(script/projectname)-test" . + ``` + + **A stage that is not the last one in the file is built only when the final + stage's chain depends on it, or when `--target` names it.** That is why the + two gates are always invoked by name here, and why the final stage carries a + `COPY --from=` of a harmless file from each of them: without that edge a + plain `docker build .` builds the last stage alone and exits 0 having linted + and tested nothing. + + **Every `docker build` in `script/` is tagged**, here and in + `script/cibuild` and `script/docker`. An untagged build leaves a dangling + image behind on every invocation, on every developer host and every CI + runner; a tagged one replaces the previous image. + + Inside a phase the tool is invoked directly — `golangci-lint`, `go test`, + `eslint`, `prettier` — never through `make lint` or `script/test`, which are + themselves a `docker build` and would recurse into a daemon that does not + exist in a build step. Formatting is the exception and stays on the host: + `script/fmt` writes the working tree, and `script/fmt-check` is its + read-only twin. + + **No lint verdict may come from a host invocation of the linter.** On a + shared host golangci-lint reads a result cache keyed on file content rather + than location, so a second checkout of the same content is served the first + one's findings, and a host-global lock in `$TMPDIR` makes concurrent runs + exit non-zero with `parallel golangci-lint is running` — a status a caller + cannot tell from real findings. Both have produced wrong verdicts in this + org, in both directions. A container has its own cache, its own `TMPDIR` and + a digest-pinned binary, so neither is reachable. + +- **Any build that runs checks is built with `--no-cache`.** Docker invalidates + a `COPY` layer only when the copied content changes, so on an unchanged tree + the check `RUN` is served from cache, nothing executes, and the build still + exits 0. Every `docker build` in `script/` therefore passes `--no-cache`: + `script/lint`, `script/test`, `script/cibuild` and `script/docker` are the + four, and there is no fifth — `script/check` runs the two gate phases and + `script/fmt-check`, and builds no image of its own. A bare `docker build .` is + not evidence that anything ran: a sub-second build reporting success is a + cache hit, not a result. Never invalidate by pruning — `docker builder prune` + and friends destroy a build cache shared with every other build on the host. + When a check is added or changed, prove it works by planting a defect it must + catch and watching the run fail on it, then revert the defect. A green run + alone shows neither that the check ran nor that it covers what it should. + +- **The gate phases are separate stages, and the build stage depends on both.** + The lint phase is based on the `golangci/golangci-lint` image (pinned by + hash), so lint failures surface in seconds rather than after a full compile, + and the test phase is based on the Debian Go image. The canonical Go repo + `Dockerfile`: ```dockerfile - # Lint stage — fast feedback on formatting and lint issues + # Lint phase # golangci/golangci-lint:v2.x.x, YYYY-MM-DD FROM golangci/golangci-lint@sha256:... AS lint WORKDIR /src COPY go.mod go.sum ./ RUN go mod download COPY . . - RUN make fmt-check - RUN make lint + RUN golangci-lint run --config .golangci.yml ./... - # Build stage - # golang:1.x-alpine, YYYY-MM-DD - FROM golang@sha256:... AS builder + # Test phase. -race needs cgo and so a C compiler, which the Debian Go + # image ships and the alpine one does not. + # golang:1.x, YYYY-MM-DD + FROM golang@sha256:... AS test WORKDIR /src - - # Force BuildKit to run the lint stage before proceeding - COPY --from=lint /src/go.sum /dev/null - COPY go.mod go.sum ./ RUN go mod download COPY . . - RUN make test + RUN go test -timeout 90s -race -cover ./... || \ + { echo "--- Rerunning with -v for details ---"; \ + go test -timeout 90s -race -v ./...; exit 1; } - ARG VERSION=dev - RUN CGO_ENABLED=0 go build -trimpath \ - -ldflags="-s -w -X main.Version=${VERSION}" \ - -o /app ./cmd/app/ + # Build stage. Nothing is wanted from either phase above; the copies + # are what make BuildKit build them first, so this stage cannot run + # unless lint and test passed. + # golang:1.x-alpine, YYYY-MM-DD + FROM golang@sha256:... AS builder + COPY --from=lint /src/go.sum /dev/null + COPY --from=test /src/go.sum /dev/null + RUN apk add --no-cache git + # A tar-stream context keeps the sender's file owners, which git refuses. + RUN git config --system --add safe.directory /src + WORKDIR /src + COPY go.mod go.sum ./ + RUN go mod download + COPY . . - # Runtime stage + # The VERSION build arg when one is given, otherwise + # `git describe --tags --always` on the .git in the build context. With + # .git present, a version that is still empty, dev or unknown fails the + # build: git is missing or could not read the checkout. + ARG VERSION + RUN VERSION="${VERSION:-$(git describe --tags --always)}"; \ + if [ -e .git ]; then \ + case "$VERSION" in ""|dev|unknown) \ + echo "version is '$VERSION' although .git is present" >&2; \ + exit 1 ;; \ + esac; \ + fi; \ + CGO_ENABLED=0 go build -trimpath \ + -ldflags="-s -w -X main.Version=${VERSION}" \ + -o /app ./cmd/app/ + + # Runtime stage, and the last one FROM alpine@sha256:... COPY --from=builder /app /usr/local/bin/app ENTRYPOINT ["app"] ``` Key points: - - The lint stage uses the `golangci/golangci-lint` image directly (it - includes both Go and the linter), so there is no need to install the - linter separately. - - `COPY --from=lint /src/go.sum /dev/null` is a no-op file copy that creates - a stage dependency. BuildKit runs stages in parallel by default; without - this line, the build stage would not wait for lint to finish and a lint - failure might not fail the overall build. + - The lint phase uses the `golangci/golangci-lint` image directly (it has + both Go and the linter), so nothing needs installing. + - `COPY --from= /src/go.sum /dev/null` is a no-op copy whose only + purpose is the ordering edge. BuildKit runs stages in parallel by default, + and a stage nothing depends on is not built at all, so without these two + lines a red gate would not fail the build. + - Keep the runtime stage last, and if you add a stage after it, give it the + same two copies. A plain `docker build .` builds the last stage's chain + and nothing else. - If the project uses `//go:embed` directives that reference build artifacts - (e.g. a web frontend compiled in a separate stage), the lint stage must + (e.g. a web frontend compiled in a separate stage), the lint phase must create placeholder files so the embed directives resolve. Example: `RUN mkdir -p web/dist && touch web/dist/index.html web/dist/style.css`. - The lint stage should not depend on the actual build output — it exists to - fail fast. - - If the project requires CGO or system libraries for linting (e.g. - `vips-dev`), install them in the lint stage with `apk add`. - - The build stage runs `make test` after compilation setup. Tests run in the - build stage, not the lint stage, because they may require compiled - artifacts or heavier dependencies. + - If the project requires CGO or system libraries for linting, install them + in the lint phase. The `golangci/golangci-lint` image is Debian-based and + has no `apk`, so install with `apt-get` under the Debian package name + (`libvips-dev`, where alpine says `vips-dev`), and delete the package + lists in the same `RUN`, so the layer does not keep them: + + ```dockerfile + RUN apt-get update \ + && apt-get install -y --no-install-recommends libvips-dev \ + && rm -rf /var/lib/apt/lists/* + ``` + + - `.dockerignore` lets `.git` into the build context. It keeps out every git + `config` at any depth (`**/.git/config`, `**/.git/modules/**/config`): the + repository's own, each submodule's under `.git/modules/`, and that of a + submodule keeping its own `.git` directory. `git describe` does not need + them, and each can hold a credential: a password in a remote URL, or the + token the CI checkout step stores there. A submodule whose name has a + `config` segment (`config`, `deploy/config`, `config/lib`) loses its whole + git directory to `**/.git/modules/**/config`, and Go's version stamping + then fails the build: give it a name without that segment + (`git submodule add --name`). The stage that compiles has `git` (the + Debian Go image has it; an alpine one needs `apk add --no-cache git`) and + takes the version from the `VERSION` build argument when one is given, + otherwise from `git describe --tags --always`. That gives the tag on a + tagged commit; on a later commit, the tag, the number of commits since it + and the short commit (`v1.2.3-4-gabc1234`); and the short commit when no + tag is reachable. The stage that compiles also marks its working directory + safe for git (`git config --system --add safe.directory /src`): a context + sent as a tar stream keeps the sender's file owners, and git refuses a + checkout owned by another user, so the version would come out empty. + `ARG VERSION` has no default, and the build fails if the context carries + `.git` and the version still comes out empty, `dev` or `unknown`. A plain + `docker build .` with no build arguments must succeed; a Dockerfile that + refuses an empty build argument drops that refusal and keeps the argument. - Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that - runs `script/cibuild` (which runs `docker build .`) on push. Since the - Dockerfile already runs `make check`, a successful build implies all checks - pass. + runs `script/cibuild` on push, and checks out the repo as its only other step. + That script bootstraps, runs the gate phases, and then builds the image, so a + successful run means every check passed; a bare `docker build .` does not + carry the same guarantee, because its gate phases may come from the cache. The + image build is uncached and so runs the gate phases a second time. That is the + price of the rule above, and it is worth paying: the image that ships is built + from a run of its own gates rather than from a cache entry. A separate + workflow limited to `main` by a `branches` list under `on: push` cannot be + checked by review: to try a change to it, add the feature branch to that list + and push, then remove the branch from the list again before merging. Keep any + job in it that publishes behind `if: github.ref_name == 'main'`, so the run + from the feature branch publishes nothing. - Use platform-standard formatters: `black` for Python, `prettier` for JS/CSS/Markdown/HTML, `go fmt` for Go. Always use default configuration with @@ -189,14 +311,21 @@ style conventions are in separate documents: module under test to verify it compiles/parses. There is no excuse for `make test` to be a no-op. -- `make test` must complete in under 20 seconds. Add a 30-second timeout in the - Makefile. +- `make test` must complete in under 60 seconds. That is the hard cap, and a + suite that exceeds it fails. Under 20 seconds is the target. A suite between + 20 and 60 seconds is still green, but the overage must be filed as an + improvement bug against that repo. Add a 90-second timeout to the test + invocation (`go test -timeout 90s`). The backstop deliberately sits above the + hard cap so that it catches a genuinely hung test rather than a merely slow + one. -- **`make test` should use the conditional verbose rerun pattern.** Run tests - without `-v` (verbose) first. If tests fail, automatically rerun with `-v` to - show full output. This keeps CI logs and `docker build` output clean on - success (just package/suite summaries) while providing full diagnostic detail - on failure (every test case, every assertion). The general shell pattern: +- **The test command should use the conditional verbose rerun pattern.** Run + tests without `-v` (verbose) first. If tests fail, automatically rerun with + `-v` to show full output. This keeps CI logs and `docker build` output clean + on success (just package/suite summaries) while providing full diagnostic + detail on failure (every test case, every assertion). The command lives in the + `test` phase of the `Dockerfile`, since `script/test` builds that phase; the + Makefile form below is the same pattern for any repo-local invocation: ```makefile test: @@ -209,11 +338,26 @@ style conventions are in separate documents: ```makefile test: - @go test -timeout 30s -race -cover ./... || \ + @go test -count=1 -timeout 90s -race -cover ./... || \ { echo "--- Rerunning with -v for details ---"; \ - go test -timeout 30s -race -v ./...; exit 1; } + go test -count=1 -timeout 90s -race -v ./...; exit 1; } ``` + `-count=1` is required on both invocations: it defeats Go's test _result_ + cache, so neither run can report a stored pass in place of running the + tests. It leaves the build cache alone, so it costs the runtime of the suite + and no recompilation. + + That cache is Go's own, separate from Docker's layer cache. Go stores a + passing result in its cache directory (`GOCACHE`), and when the same tests + run again on unchanged code it prints that result, marked `(cached)`, + without running them. That matters on a developer's machine, where this + target runs and the directory lasts from one run to the next. The `test` + phase of the `Dockerfile` needs no `-count=1`: its base image holds no + result for this repo's tests and nothing before its `go test` step runs a + test, so there is nothing to replay. `--no-cache` (above) is what makes that + step run on an unchanged tree. + Python example: ```makefile @@ -239,10 +383,84 @@ style conventions are in separate documents: must be in `.gitignore`. No exceptions. - `.gitignore` should be comprehensive from the start: OS files (`.DS_Store`), - editor files (`.swp`, `*~`), language build artifacts, and `node_modules/`. - Fetch the standard `.gitignore` from - `https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when setting up - a new repo. + editor files (`.swp`, `*~`), in-repo agent scratch directories (`.claude/`), + language build artifacts, and `node_modules/`. Fetch the standard `.gitignore` + from `https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when + setting up a new repo. These patterns are written to `.gitignore`'s own + semantics, in which an unanchored pattern already matches at every depth; they + are not a `.dockerignore` and must not be transplanted into one unmodified. + +- **`.dockerignore` does not use `.gitignore` semantics, and copying patterns + across unmodified leaves secrets in the build context.** Docker matches with + `moby/patternmatcher`: `filepath.Match` semantics plus a `**` extension, so + `*` does not cross `/` and a pattern without a leading `**/` is anchored at + the build-context root. A `.dockerignore` listing `.env`, `*.pem` and `*.key` + therefore excludes only the copies at the repository root, while `config/.env` + and `certs/server.key` still reach the context and can land in an image layer + — which is more dangerous than a short file with no secret patterns at all, + because it reads as solved and stops anyone looking. Give every + depth-independent pattern the `**/` prefix and leave only genuinely + root-anchored entries unprefixed: `.claude`, and the repo's own host-built + binary, written `/myapp` and never `**/myapp`, which would also match + `cmd/myapp/` and delete the package directory from the context. Matching is + case-sensitive, and an ALL-CAPS twin per pattern still misses `Server.Key`, so + secret names use character ranges — `**/*.[kK][eE][yY]`, `**/*.[pP][eE][mM]`, + and likewise for `.envrc` and the extensionless SSH keys. Where such a pattern + also catches something the build needs, re-include it with a negation + (`!docs/example.env`); deleting the pattern reopens the exposure for every + other file it covers. Fetch the standard `.dockerignore` from + `https://git.eeqj.de/sneak/prompts/raw/branch/main/.dockerignore` and extend + it with the repo's own artifacts. + +- **In-repo agent scratch belongs in both files, written to each file's own + semantics.** `.claude/` holds one worktree per in-flight agent — an entire + additional checkout of the repo — so under `COPY . .` the build context + inflates by a multiple of the repo and another session's unreviewed work can + be copied into an image layer. In `.gitignore` the entry is `.claude/`, + unanchored. In `.dockerignore` it is `.claude`, anchored and with **no** `**/` + prefix, because the prefixed form would also delete any nested directory of + that name from the build. Anchoring carries a known gap that the canonical + `.dockerignore` states in its own comment, since consuming repos receive the + file and not the tracker: the directory is created in the agent's working + directory, so a repo running agents in subdirectories still ships + `services/api/.claude/` and must add its own anchored entry there. + +- **A plain `docker build .` of a clone stamps the version that + `git describe --tags --always` gives**, derived from the `.git` in the build + context as the canonical `Dockerfile` above shows. Without its failure check, + a missing `git` or an unreadable checkout would leave `-X main.Version=` empty + and the build would still exit 0. `script/docker` and `script/cibuild` pass + the version they compute on the host; it takes precedence. They do this + byte-identically across repos: + + ```sh + # Own line: a failing command substitution inside an argument does not + # trip `set -e`, so the inline form degrades to an empty constant. + version="$(git describe --tags --always --dirty 2>/dev/null || true)" + [ -n "$version" ] || version="unknown" + docker build --no-cache \ + --build-arg VERSION="$version" \ + -t "$(script/projectname)" . + ``` + + `--always` makes an untagged repo yield an abbreviated commit hash rather + than failing, and the `[ -n "$version" ]` line is the single place the + fallback is applied — a live check that fires on a build from an export with + no `.git` and on a repository with no commits yet. Do not fold it into the + substitution as `|| echo unknown`, which makes the guard unreachable. The + Dockerfile's side is `ARG VERSION` in the stage that compiles, declared + there because `ARG` is stage-scoped; passing `VERSION` to a repo whose + Dockerfile declares no such `ARG` is ignored and costs nothing, which is why + the scripts stay byte-identical. One consequence for CI: the standard + checkout action clones shallow and fetches no tags, so a repo that embeds a + tag-derived version must set `fetch-depth: 0` on its checkout step. + +- **Verify `.dockerignore` by enumerating the image, not by reading the + patterns.** Plant files at the root _and_ at least two directories deep, build + a probe image that does `COPY . .`, and list what actually landed + (`docker run --rm --entrypoint find IMAGE /app`). The `transferring context` + size is not a substitute: a nested secret is a few bytes, and BuildKit + transfers only the delta from the previous build. - **No build artifacts in version control.** Code-derived data (compiled bundles, minified output, generated assets) must never be committed to the @@ -258,9 +476,56 @@ style conventions are in separate documents: - Make all changes on a feature branch. You can do whatever you want on a feature branch. -- `.golangci.yml` is standardized and must _NEVER_ be modified by an agent, only - manually by the user. Fetch from - `https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml`. +- `.golangci.yml` is standardized. The vendored copy in a consuming repo must + _NEVER_ be modified by an agent: fetch it from + `https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml` and keep it + byte-identical, so that no repo can quietly loosen its own linting. Linter + configuration changes are made to the canonical copy in the `prompts` repo and + reach consuming repos by re-vendoring; an agent may open a PR against + canonical, which only the user merges. One list is exempt from byte-identity, + because it cannot be written once for every repo: the `deny` list of the + `test-support` depguard rule, where a repo names its own test-support packages + by full import path. A repo adds entries there and changes nothing else, and a + re-vendor carries its entries forward. The canonical golangci-lint version is + v2.14.0 (released 2026-09-24), pinned as the digest of the lint phase's base + image + (`golangci/golangci-lint@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f`, + which reports `2.14.0 built with go1.27.0 from 114493f9`). A module's `go` + directive must not name a newer Go minor version than the one golangci-lint + was built with, or golangci-lint refuses to lint it: this release lints + `go 1.27.1` but not `go 1.28`. That digest is the only pin, since no repo + installs golangci-lint on the host. A repo sets the lint phase digest to the + one named here and re-vendors `.golangci.yml` in the same commit, whichever of + the two prompted the change: the canonical copy can name linters that an older + golangci-lint rejects, and a newer golangci-lint can add linters that + `default: all` switches on until the canonical copy disables them. + +- **`script/bootstrap` installs a pinned tool by comparing versions, never by + testing presence.** An `if ! command -v ; then install; fi` guard tests + `PATH` only, so on an already-provisioned machine the pin is inert and a + version bump is a silent no-op — while the Dockerfile, installing into a clean + image, gets the pinned version, so a local `make check` and `make docker` can + disagree about what the tool even is. The canonical form: + - compares the installed version against the pin over the **whole** version + token; a parser that stops at the first `-` reports `2.12.2` for a host + running `2.12.2-rc1` and skips the install; + - treats absent, non-zero, empty or unrecognised `--version` output as a + mismatch, so the failure direction is a redundant install and never a + skipped one; + - after installing, re-resolves the binary the way callers do — `hash -r`, + then through `PATH`, not through the directory the installer wrote to — + and fails naming the resolved path, since an install that a shadowing + binary hides succeeds while changing nothing any caller sees; + - is actually called, and prints the version on both success paths: a + function defined and never invoked has the same exit status and the same + empty output as one that worked. + + Keep it POSIX sh: no arrays, no `[[`, no `grep -P`. + + A Go tool a repo needs on the host is installed with `go install` pinned to + a commit hash (`go install @`). It is never tracked as + a `go.mod` tool dependency or through a `tools.go` file, either of which + pulls the tool's own dependencies into the repo's `go.mod` and `go.sum`. - When pinning images or packages by hash, add a comment above the reference with the version and date (YYYY-MM-DD). @@ -374,12 +639,14 @@ style conventions are in separate documents: settings. - Avoid putting files in the repo root unless necessary. Root should contain - only project-level config files (`README.md`, `Makefile`, `Dockerfile`, - `LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`, and - language-specific config). Everything else goes in a subdirectory. Canonical - subdirectory names: + only project-level config files (`README.md`, `AGENTS.md`, `Makefile`, + `Dockerfile`, `LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`, + and language-specific config). Everything else goes in a subdirectory. + Canonical subdirectory names: - `bin/` — executable scripts and tools - - `cmd/` — Go command entrypoints + - `cmd/` — Go command entrypoints; thin only: one `main.go` per binary whose + body is a single call into `internal/` or `pkg/`, no project logic in + `cmd/` - `configs/` — configuration templates and examples - `deploy/` — deployment manifests (k8s, compose, terraform) - `docs/` — documentation and markdown (README.md stays in root) @@ -406,3 +673,7 @@ style conventions are in separate documents: - Go: `go.mod`, `go.sum`, `.golangci.yml` - JS: `package.json`, `yarn.lock`, `.prettierrc`, `.prettierignore` - Python: `pyproject.toml` + +- Guidance for coding agents lives in one `AGENTS.md` at the repository root. It + is never committed under a file or directory named after one agent tool, such + as `CLAUDE.md` or `.claude/`, and never split into separate memory files. diff --git a/TODO.md b/TODO.md index 2336169..f6eaa18 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,15 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Re-vendored the canonical files from `sneak/prompts` at + `dd4027b` ([issue #213](https://git.eeqj.de/sneak/vaultik/issues/213)). + Linting and testing are now the `lint` and `test` phases of the + `Dockerfile`, and the build stage depends on both. `Dockerfile.lint`, + `CHECK_EPOCH` and the tests that checked them are gone; every + `docker build` in `script/` passes `--no-cache` instead. golangci-lint + is v2.14.0, with its new findings fixed in the code, and the rules in + `CLAUDE.md` now live in `AGENTS.md`. + - 2026-10-06: Made the local index actually run in WAL mode with a busy timeout ([issue #217](https://git.eeqj.de/sneak/vaultik/issues/217)). The connection settings were written in a form the SQLite driver diff --git a/cmd/vaultik/dockerversion_test.go b/cmd/vaultik/dockerversion_test.go index d1ee2df..6ae7b92 100644 --- a/cmd/vaultik/dockerversion_test.go +++ b/cmd/vaultik/dockerversion_test.go @@ -12,48 +12,44 @@ import ( // #75). The failure it protects against is silent: the image still // builds and runs, but `vaultik version` inside it reports "commit: // unknown" or a version of "dev", so an operator cannot tell which -// source produced a given backup. The build takes the values as build -// args, which script/docker computes on the host, and otherwise derives -// them from the .git in its context. +// source produced a given backup. The build takes the version as a +// build arg, which script/docker computes on the host, and otherwise +// derives it from the .git in its context; the commit and its date +// always come from that .git. // -// These are parses of the committed files, for the same reason the lint -// guards next door are: shelling out to docker would nest a build -// inside `make test`. That `vaultik version` in the built image really -// prints the host's version is verified by hand and recorded on the -// pull request. +// These are parses of the committed files, because shelling out to +// docker would nest a build inside `make test`. That `vaultik version` +// in the built image really prints the host's version is verified by +// hand. -// dockerScript is script/docker, relative to the repository root. -const dockerScript = "script/docker" +// The files under guard, relative to the repository root. +const ( + productDockerfile = "Dockerfile" + dockerScript = "script/docker" +) -// versionArgs are the ldflag targets the build stamps and, matching -// them, the build args the host must supply. The names line up so the -// same list checks both files. -func versionArgs() []string { - return []string{"VERSION", "COMMIT", "COMMIT_DATE"} -} - -// TestProductDockerfileTakesVersionAsBuildArgs fails unless the build -// declares each version arg, with no default, and stamps it into the -// binary whenever it is given, ahead of the value derived in the -// container. -func TestProductDockerfileTakesVersionAsBuildArgs(t *testing.T) { +// TestProductDockerfileTakesVersionAsBuildArg fails unless the build +// declares ARG VERSION, with no default, and stamps it into the binary +// whenever it is given, ahead of the value derived in the container. +func TestProductDockerfileTakesVersionAsBuildArg(t *testing.T) { t.Parallel() found := instructions(t, productDockerfile) - for _, arg := range versionArgs() { - require.Contains(t, found, "ARG "+arg, - "%s must declare `ARG %s`, with no default, so the host can"+ - " pass it in", productDockerfile, arg) + require.Contains(t, found, "ARG VERSION", + "%s must declare `ARG VERSION`, with no default, so the host can"+ + " pass it in", productDockerfile) - assertLdflagReferences(t, found, arg) - } + assertLdflagReferences(t, found, "VERSION") } // TestProductDockerfileDerivesVersionFromGit fails unless a build given // no VERSION, such as a plain `docker build .` of a clone, takes it from -// `git describe` of the .git in its context, and fails rather than -// stamp "dev" when that .git yields no version. +// `git describe` of the .git in its context, stamps "dev" when the +// context has no .git, and fails rather than stamp "dev" when that .git +// yields no version. The commit and its date come from the same .git, +// and the build fails rather than stamp them "unknown" when it is +// present. func TestProductDockerfileDerivesVersionFromGit(t *testing.T) { t.Parallel() @@ -62,31 +58,31 @@ func TestProductDockerfileDerivesVersionFromGit(t *testing.T) { buildAt := indexContaining(found, "go build") require.GreaterOrEqual(t, buildAt, 0, "%s must build", productDockerfile) - assert.Contains(t, found[buildAt], "git describe --tags --always", - "%s must derive the version from git when no VERSION is given", - productDockerfile) + assert.Contains(t, found[buildAt], "git describe --tags --always || echo dev", + "%s must derive the version from git when no VERSION is given,"+ + " and stamp dev when the context has no .git", productDockerfile) assert.Contains(t, found[buildAt], "[ -e .git ]", "%s must fail when the context carries .git but yields no version", productDockerfile) + assert.Contains(t, found[buildAt], "git rev-parse HEAD", + "%s must stamp the commit from git", productDockerfile) + assert.Contains(t, found[buildAt], "git show -s --format=%cs HEAD", + "%s must stamp the commit date from git", productDockerfile) + assert.Contains(t, found[buildAt], + `[ "$commit" = unknown ] || [ "$commit_date" = unknown ]`, + "%s must fail when the context carries .git but yields no commit"+ + " or date", productDockerfile) } // TestDockerScriptComputesVersionOnTheHost fails unless script/docker -// derives each value where .git exists and passes it as a build arg, -// with VERSION coming from script/version so a Docker build reports the -// same string a local build of the same tree would. +// passes the version it derives where .git exists as a build arg. func TestDockerScriptComputesVersionOnTheHost(t *testing.T) { t.Parallel() script := readRepoFile(t, dockerScript) - for _, arg := range versionArgs() { - assert.Contains(t, script, "--build-arg "+arg+"=", - "%s must pass --build-arg %s to the build", dockerScript, arg) - } - - assert.Contains(t, script, "/version", - "%s must take VERSION from script/version, as the Makefile does", - dockerScript) + assert.Contains(t, script, "--build-arg VERSION=", + "%s must pass --build-arg VERSION to the build", dockerScript) } // assertLdflagReferences fails unless the build instruction uses the @@ -107,3 +103,47 @@ func assertLdflagReferences(t *testing.T, found []string, arg string) { "the go build in %s must use ${%s:-...}, or the arg is passed and"+ " discarded", productDockerfile, arg) } + +// instructions returns the Dockerfile's instructions, one per element, +// with comments and blank lines dropped and continuation lines joined, +// so a multi-line RUN is one string. +func instructions(t *testing.T, name string) []string { + t.Helper() + + var ( + out []string + continued string + isContinued bool + ) + + for line := range strings.SplitSeq(readRepoFile(t, name), "\n") { + trimmed := strings.TrimSpace(line) + if !isContinued && (trimmed == "" || strings.HasPrefix(trimmed, "#")) { + continue + } + + isContinued = strings.HasSuffix(trimmed, `\`) + continued += strings.TrimSuffix(trimmed, `\`) + + if isContinued { + continue + } + + out = append(out, strings.Join(strings.Fields(continued), " ")) + continued = "" + } + + return out +} + +// indexContaining returns the position of the first instruction +// containing want; -1 if there is none. +func indexContaining(found []string, want string) int { + for i, instruction := range found { + if strings.Contains(instruction, want) { + return i + } + } + + return -1 +} diff --git a/cmd/vaultik/lintdocker_test.go b/cmd/vaultik/lintdocker_test.go deleted file mode 100644 index fa620ce..0000000 --- a/cmd/vaultik/lintdocker_test.go +++ /dev/null @@ -1,368 +0,0 @@ -package main_test - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// This file guards the shape of the lint gate. Every property asserted -// here is one whose loss is SILENT: the build still exits 0, the gate -// still looks green, and nothing was linted or tested. -// -// The gate is a build step. script/lint builds Dockerfile.lint, which -// runs golangci-lint as a RUN instruction, so a successful build is a -// clean lint. BuildKit will happily replay that RUN from cache on an -// unchanged tree in well under a second, which is why the check layers -// are keyed on a CHECK_EPOCH build arg that the calling script -// regenerates per invocation, and why an empty value is a hard error -// rather than a stable cache key. -// -// These are parses rather than invocations. Shelling out to docker from -// the test suite would nest a build inside `make test`, which itself -// runs inside a build in CI. The one property a parse cannot establish -// -- that a real finding actually fails the build -- is verified by -// hand against a deliberately broken tree, recorded on the pull -// request. -// -// One property is deliberately NOT tested here: that no script runs the -// linter on the host. script/lint is the only lint entry point, and it -// runs golangci-lint only inside the container; keeping it that way is a -// review matter, not something a test in this file establishes. - -// The files under guard, relative to the repository root. -const ( - lintDockerfile = "Dockerfile.lint" - productDockerfile = "Dockerfile" - lintScript = "script/lint" - cibuildScript = "script/cibuild" -) - -// linterBinary is the linter's command name, used to locate the -// config-verify and lint steps in Dockerfile.lint. -const linterBinary = "golangci-lint" - -// checkEpochARG is the declaration, with no default value. A default -// would satisfy the non-empty guard with a constant, and a constant is -// a stable cache key: the checks would be replayed from cache forever -// after the first build. -const checkEpochARG = "ARG CHECK_EPOCH" - -// checkEpochGuard is what turns a build that omits --build-arg into a -// loud failure instead of a quiet green. Failed steps are never cached, -// so it fires on every such invocation rather than once. -const checkEpochGuard = `RUN [ -n "$CHECK_EPOCH" ] || exit 1` - -// freshEpoch is the epoch computation the calling scripts must use, as -// a bare assignment on its own line. Inline in an argument, a failing -// `date` would not abort under `set -eu`; CHECK_EPOCH would become the -// empty string, and the guard above would be the only thing standing -// between that and a permanently cached green. `$$` is required because -// `date +%s` is second-granular and busybox silently drops `%N`, so -// without the pid two concurrent runs in one second can collide. -const freshEpoch = `epoch="$(date +%s%N)$$"` - -// TestLintDockerfilePinsTheLinterByDigest fails if the lint image stops -// being pinned. An unpinned tag makes the gate's verdict depend on -// whatever the registry currently serves under that name. -func TestLintDockerfilePinsTheLinterByDigest(t *testing.T) { - t.Parallel() - - from := "" - - for _, instruction := range instructions(t, lintDockerfile) { - if strings.HasPrefix(instruction, "FROM ") { - from = instruction - - break - } - } - - require.NotEmpty(t, from, "%s declares no FROM", lintDockerfile) - assert.Contains(t, from, "golangci/golangci-lint", - "the lint image must be the golangci-lint image") - assert.Contains(t, from, "@sha256:", - "the lint image must be pinned by digest, not by tag alone") -} - -// TestLintDockerfileCannotBeCachedGreen pins the whole cache-busting -// mechanism in the file that lints: the declaration with no default, -// the non-empty guard, and the value expanded into the lint command -// itself rather than merely declared. -func TestLintDockerfileCannotBeCachedGreen(t *testing.T) { - t.Parallel() - - found := instructions(t, lintDockerfile) - - argAt := indexOf(found, checkEpochARG) - require.GreaterOrEqual(t, argAt, 0, - "%s must declare `%s` with no default value", - lintDockerfile, checkEpochARG) - - assert.GreaterOrEqual(t, indexOf(found, checkEpochGuard), argAt, - "%s must guard against an empty CHECK_EPOCH with `%s`", - lintDockerfile, checkEpochGuard) - - assertEpochExpandedInto(t, found[argAt:], "golangci-lint run") - - // Dependency layers must stay above the ARG, or every lint run - // re-downloads the module cache and the inner loop becomes - // unusable. - download := indexOf(found, "RUN go mod download") - require.GreaterOrEqual(t, download, 0, - "%s must download modules in their own layer", lintDockerfile) - assert.Less(t, download, argAt, - "`%s` must come after `go mod download` so dependency layers"+ - " still cache", checkEpochARG) -} - -// TestLintDockerfileVerifiesTheLinterConfig guards the validation of -// .golangci.yml itself. `golangci-lint run` rejects a config it cannot -// parse but silently IGNORES an unknown top-level key, so renaming -// `linters:` to `linterz:` discards `default: all` and every threshold -// and still exits 0 reporting no issues. `config verify` is what turns -// that into a failure, and it has to run BEFORE the lint, or the lint -// spends a minute reporting a verdict from a config already known to be -// wrong. -func TestLintDockerfileVerifiesTheLinterConfig(t *testing.T) { - t.Parallel() - - found := instructions(t, lintDockerfile) - verify := linterBinary + " config verify" - - verifyAt := indexContaining(found, verify) - require.GreaterOrEqual(t, verifyAt, 0, - "%s must run `%s --config .golangci.yml`: without it a typo'd"+ - " top-level key in .golangci.yml is silently ignored and the"+ - " gate passes with only the default linter set", lintDockerfile, - verify) - - runAt := indexContaining(found, linterBinary+" run") - require.GreaterOrEqual(t, runAt, 0, "%s must lint", lintDockerfile) - assert.Less(t, verifyAt, runAt, - "%s must verify the config before linting with it", lintDockerfile) - - // Keyed on the epoch like every other check layer, so it executes - // per invocation rather than being replayed. A cached validation - // validates nothing. - assertEpochExpandedInto(t, found, verify) -} - -// TestProductDockerfileKeysChecksOnTheEpoch holds the same line for the -// checks that remain in the product image build, but without the guard: -// a plain `docker build .` with no build arguments must succeed. -func TestProductDockerfileKeysChecksOnTheEpoch(t *testing.T) { - t.Parallel() - - found := instructions(t, productDockerfile) - - argAt := indexOf(found, checkEpochARG) - require.GreaterOrEqual(t, argAt, 0, - "%s must declare `%s`", productDockerfile, checkEpochARG) - - assert.Equal(t, -1, indexOf(found, checkEpochGuard), - "%s must not refuse an empty CHECK_EPOCH: a plain `docker build .`"+ - " must succeed", productDockerfile) - - assertEpochExpandedInto(t, found[argAt:], "make fmt-check") - assertEpochExpandedInto(t, found[argAt:], "make test") -} - -// TestProductDockerfileDoesNotLint records the split deliberately: the -// linter lives in Dockerfile.lint and nowhere else, so there is exactly -// one digest pinning it. A lint stage reintroduced here would either be -// docker-in-docker (`make lint` is now `docker build`) or a second, -// independently bumpable pin. -func TestProductDockerfileDoesNotLint(t *testing.T) { - t.Parallel() - - contents := readRepoFile(t, productDockerfile) - - for _, forbidden := range []string{"golangci", "make lint"} { - assert.NotContains(t, instructionText(contents), forbidden, - "%s must not lint: the linter is pinned once, in %s", - productDockerfile, lintDockerfile) - } -} - -// TestLintScriptBuildsTheLintDockerfileWithAFreshEpoch is the other -// half of the mechanism. The Dockerfile's guard only rejects an EMPTY -// epoch; a constant non-empty one would satisfy it and still be served -// from cache forever. -func TestLintScriptBuildsTheLintDockerfileWithAFreshEpoch(t *testing.T) { - t.Parallel() - - script := readRepoFile(t, lintScript) - - assertBareEpochAssignment(t, script, lintScript) - assert.Contains(t, script, `--build-arg CHECK_EPOCH="$epoch"`, - "%s must pass the fresh epoch to the build", lintScript) - assert.Contains(t, script, lintDockerfile, - "%s must build %s", lintScript, lintDockerfile) -} - -// TestCibuildBuildsBothDockerfilesWithFreshEpochs guards the CI gate: -// dropping either build silently removes a whole class of check from -// CI while leaving it green. -func TestCibuildBuildsBothDockerfilesWithFreshEpochs(t *testing.T) { - t.Parallel() - - script := readRepoFile(t, cibuildScript) - - assertBareEpochAssignment(t, script, cibuildScript) - assert.Equal(t, 2, strings.Count(script, freshEpoch), - "%s must compute a fresh epoch for each of its two builds", - cibuildScript) - assert.Equal(t, 2, - strings.Count(script, `--build-arg CHECK_EPOCH="$epoch"`), - "%s must pass a fresh epoch to both builds", cibuildScript) - assert.Contains(t, script, "-f Dockerfile.lint", - "%s must build %s", cibuildScript, lintDockerfile) -} - -// assertEpochExpandedInto fails unless some instruction runs the named -// command with the epoch expanded into it. Expansion, not mere -// declaration: an ARG that no instruction references is not guaranteed -// to key the layer, and the expansion also puts the value in the build -// log where a reader can see the layer was keyed fresh. -func assertEpochExpandedInto(t *testing.T, found []string, command string) { - t.Helper() - - for _, instruction := range found { - if !strings.HasPrefix(instruction, "RUN ") { - continue - } - - if strings.Contains(instruction, command) && - strings.Contains(instruction, "${CHECK_EPOCH}") { - return - } - } - - assert.Fail(t, "no epoch-keyed layer runs the command", - "`%s` must run in a layer that expands ${CHECK_EPOCH}, or it"+ - " will be replayed from cache without executing", command) -} - -// assertBareEpochAssignment fails unless the script computes the epoch -// as a bare assignment on its own line. -func assertBareEpochAssignment(t *testing.T, script, name string) { - t.Helper() - - for line := range strings.SplitSeq(script, "\n") { - if strings.TrimSpace(line) == freshEpoch { - return - } - } - - assert.Fail(t, "no bare epoch assignment", - "%s must compute `%s` as a bare assignment on its own line, so"+ - " `set -e` catches a failing date instead of quietly"+ - " building with an empty epoch", name, freshEpoch) -} - -// instructions returns the Dockerfile's instructions, one per element, -// with comments and blank lines dropped and continuation lines joined, -// so a multi-line RUN is one string. -func instructions(t *testing.T, name string) []string { - t.Helper() - - return strings.Split(instructionText(readRepoFile(t, name)), "\n") -} - -// instructionText is instructions' parse, before splitting: it is also -// what a "must not contain" assertion should look at, so that a word -// appearing only in a comment is not mistaken for behaviour. -func instructionText(contents string) string { - var ( - out []string - continued string - isContinued bool - ) - - for line := range strings.SplitSeq(contents, "\n") { - trimmed := strings.TrimSpace(line) - if !isContinued && (trimmed == "" || strings.HasPrefix(trimmed, "#")) { - continue - } - - isContinued = strings.HasSuffix(trimmed, `\`) - continued += strings.TrimSuffix(trimmed, `\`) - - if isContinued { - continue - } - - out = append(out, strings.Join(strings.Fields(continued), " ")) - continued = "" - } - - return strings.Join(out, "\n") -} - -// indexOf returns the position of the first instruction equal to, or -// beginning with, want; -1 if there is none. An `ARG NAME=default` -// counts as beginning with `ARG NAME`, so a declared arg is found -// whether or not it carries a default. -func indexOf(found []string, want string) int { - for i, instruction := range found { - if instruction == want || - strings.HasPrefix(instruction, want+" ") || - strings.HasPrefix(instruction, want+"=") { - return i - } - } - - return -1 -} - -// indexContaining returns the position of the first instruction -// containing want; -1 if there is none. -func indexContaining(found []string, want string) int { - for i, instruction := range found { - if strings.Contains(instruction, want) { - return i - } - } - - return -1 -} - -// readRepoFile reads a file by its path relative to the repository -// root. -func readRepoFile(t *testing.T, name string) string { - t.Helper() - - //nolint:gosec // G304: the path is a constant relative to this repo - contents, err := os.ReadFile(filepath.Join(repoRoot(t), name)) - require.NoError(t, err) - - return string(contents) -} - -// repoRoot returns the repository root. The test binary runs with its -// package directory as the working directory, so the root is found by -// walking up until the module file appears. -func repoRoot(t *testing.T) string { - t.Helper() - - dir, err := os.Getwd() - require.NoError(t, err) - - for { - _, err = os.Stat(filepath.Join(dir, "go.mod")) - if err == nil { - return dir - } - - parent := filepath.Dir(dir) - require.NotEqual(t, dir, parent, - "walked to the filesystem root without finding a go.mod") - - dir = parent - } -} diff --git a/cmd/vaultik/makefile_test.go b/cmd/vaultik/makefile_test.go index b937f15..8b527be 100644 --- a/cmd/vaultik/makefile_test.go +++ b/cmd/vaultik/makefile_test.go @@ -1,6 +1,8 @@ package main_test import ( + "os" + "path/filepath" "regexp" "slices" "strings" @@ -84,14 +86,48 @@ func TestBuildTargetBuildsTheBinary(t *testing.T) { "`make build` must depend on the rule that builds the binary") } -// readMakefile returns the contents of the repository's Makefile. The -// root is located by the shared walk in lintdocker_test.go. +// readMakefile returns the contents of the repository's Makefile. func readMakefile(t *testing.T) string { t.Helper() return readRepoFile(t, "Makefile") } +// readRepoFile reads a file by its path relative to the repository +// root. +func readRepoFile(t *testing.T, name string) string { + t.Helper() + + //nolint:gosec // G304: the path is a constant relative to this repo + contents, err := os.ReadFile(filepath.Join(repoRoot(t), name)) + require.NoError(t, err) + + return string(contents) +} + +// repoRoot returns the repository root. The test binary runs with its +// package directory as the working directory, so the root is found by +// walking up until the module file appears. +func repoRoot(t *testing.T) string { + t.Helper() + + dir, err := os.Getwd() + require.NoError(t, err) + + for { + _, err = os.Stat(filepath.Join(dir, "go.mod")) + if err == nil { + return dir + } + + parent := filepath.Dir(dir) + require.NotEqual(t, dir, parent, + "walked to the filesystem root without finding a go.mod") + + dir = parent + } +} + // phonyTargets returns every name declared phony, across all .PHONY // lines. func phonyTargets(makefile string) []string { diff --git a/internal/config/size.go b/internal/config/size.go index 8f21a87..23b77b6 100644 --- a/internal/config/size.go +++ b/internal/config/size.go @@ -16,8 +16,6 @@ var ( // Size represents a byte size that can be specified in configuration files. // It can unmarshal from both numeric values (interpreted as bytes) and // human-readable strings like "10MB", "2.5GB", or "1TB". -// -//nolint:recvcheck // UnmarshalYAML requires a pointer; String/Int64 are value reads type Size int64 // UnmarshalYAML implements yaml.Unmarshaler for Size, allowing it to be diff --git a/internal/database/chunk_files.go b/internal/database/chunk_files.go index 308af59..0ce345a 100644 --- a/internal/database/chunk_files.go +++ b/internal/database/chunk_files.go @@ -220,7 +220,7 @@ func (r *ChunkFileRepository) CreateBatch( cf.ChunkHash.String(), cf.FileID.String(), cf.FileOffset, cf.Length) } - query += querySb183.String() //nolint:gosec // G202: appends "?" placeholders only + query += querySb183.String() query += " ON CONFLICT(chunk_hash, file_id) DO NOTHING" diff --git a/internal/database/chunks.go b/internal/database/chunks.go index 833c1aa..51e95d1 100644 --- a/internal/database/chunks.go +++ b/internal/database/chunks.go @@ -98,7 +98,7 @@ func (r *ChunkRepository) GetByHashes( args[i] = hash } - query += querySb75.String() //nolint:gosec // G202: appends "?" placeholders only + query += querySb75.String() query += ") ORDER BY chunk_hash" diff --git a/internal/database/file_chunks.go b/internal/database/file_chunks.go index 04388d7..0803de2 100644 --- a/internal/database/file_chunks.go +++ b/internal/database/file_chunks.go @@ -253,7 +253,7 @@ func (r *FileChunkRepository) CreateBatch( args = append(args, fc.FileID.String(), fc.Idx, fc.ChunkHash.String()) } - query += querySb211.String() //nolint:gosec // G202: appends "?" placeholders only + query += querySb211.String() query += " ON CONFLICT(file_id, idx) DO NOTHING" diff --git a/internal/database/files.go b/internal/database/files.go index f9d8022..c30c07e 100644 --- a/internal/database/files.go +++ b/internal/database/files.go @@ -391,7 +391,7 @@ func (r *FileRepository) CreateBatch( f.LinkTarget.String()) } - query += querySb325.String() //nolint:gosec // G202: appends "?" placeholders only + query += querySb325.String() query += ` ON CONFLICT(path) DO UPDATE SET source_path = excluded.source_path, diff --git a/internal/database/snapshots.go b/internal/database/snapshots.go index 07c8242..4479985 100644 --- a/internal/database/snapshots.go +++ b/internal/database/snapshots.go @@ -395,7 +395,7 @@ func (r *SnapshotRepository) AddFilesByIDBatch( args = append(args, snapshotID, fileID.String()) } - query += querySb312.String() //nolint:gosec // G202: appends "?" placeholders only + query += querySb312.String() var err error if tx != nil { diff --git a/internal/globals/globals.go b/internal/globals/globals.go index fd00834..984b8a0 100644 --- a/internal/globals/globals.go +++ b/internal/globals/globals.go @@ -18,14 +18,19 @@ var Appname = "vaultik" //nolint:gochecknoglobals // set via -ldflags at build t // deliberately not a number. const DevVersion = "dev" +// Unknown is what Commit and CommitDate hold when the build did not +// stamp them, and the version script/docker and script/cibuild stamp +// when the host has no git checkout. +const Unknown = "unknown" + // Version is the application version, populated from main(). var Version = DevVersion //nolint:gochecknoglobals // set via -ldflags at build time // Commit is the git commit hash, populated from main(). -var Commit = "unknown" //nolint:gochecknoglobals // set via -ldflags at build time +var Commit = Unknown //nolint:gochecknoglobals // set via -ldflags at build time // CommitDate is the ISO-8601 date of the commit, populated from main(). -var CommitDate = "unknown" //nolint:gochecknoglobals // set via -ldflags at build time +var CommitDate = Unknown //nolint:gochecknoglobals // set via -ldflags at build time // Author identifies the upstream author of vaultik. const Author = "Jeffrey Paul " @@ -72,9 +77,11 @@ func New() (*Globals, error) { // safe reading of "we could not establish that this is a release" is // that it is not one. The Makefile refuses to build at all in that // case; this is the second line of defence, for a binary linked by -// something other than the Makefile. +// something other than the Makefile. Unknown counts for the same +// reason. func IsDevVersion(v string) bool { - if v == "" || v == DevVersion || strings.HasPrefix(v, DevVersion+"-") || + if v == "" || v == Unknown || v == DevVersion || + strings.HasPrefix(v, DevVersion+"-") || strings.HasSuffix(v, "-dirty") { return true } diff --git a/internal/globals/globals_test.go b/internal/globals/globals_test.go index 7012e60..fd05e4a 100644 --- a/internal/globals/globals_test.go +++ b/internal/globals/globals_test.go @@ -74,6 +74,9 @@ func TestIsDevVersion(t *testing.T) { // as one. The Makefile refuses to build when script/version // yields nothing; this covers a binary linked some other way. {"", true}, + // What script/docker and script/cibuild stamp when the host + // has no git checkout. + {"unknown", true}, } for _, tc := range cases { diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 850b1b8..f7eb40e 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -1377,8 +1377,7 @@ func (s *Scanner) processFileWithErrorHandling( // record a file whose chunk is in no blob and cannot be restored, so // abort the run even under --skip-errors. Only open and read errors // are skipped below. - var pErr *packerError - if errors.As(err, &pErr) { + if _, ok := errors.AsType[*packerError](err); ok { return false, fmt.Errorf("processing file %s: %w", fileToProcess.Path, err) } // Handle files that were deleted between scan and process phases diff --git a/internal/storage/url.go b/internal/storage/url.go index 24ea329..8da6eca 100644 --- a/internal/storage/url.go +++ b/internal/storage/url.go @@ -161,8 +161,7 @@ func rejectUnknownParams(query url.Values, allowed ...string) error { // *url.Error that url.Parse returns embeds the raw URL in its message, so // wrapping it directly would echo a credential-bearing URL into logs. func wrapParseError(err error) error { - var uerr *url.Error - if errors.As(err, &uerr) { + if uerr, ok := errors.AsType[*url.Error](err); ok { return fmt.Errorf("invalid URL: %w", uerr.Err) } diff --git a/script/bootstrap b/script/bootstrap index 21862fe..c1024a0 100755 --- a/script/bootstrap +++ b/script/bootstrap @@ -48,12 +48,12 @@ missing() { ! command -v "$1" >/dev/null 2>&1 } -# Docker is a hard requirement, not a nice-to-have: script/lint lints by -# building Dockerfile.lint, whose digest-pinned golangci-lint image is -# the only place the linter runs, and script/check and script/precommit -# both run script/lint. A bootstrap that prints "bootstrap complete" on a -# machine where `make check` cannot run is a false success, so this fails -# instead. +# Docker is a hard requirement, not a nice-to-have: script/lint and +# script/test build the lint and test phases of the Dockerfile, the only +# place the linter and the tests run, and script/check and +# script/precommit both run them. A bootstrap that prints "bootstrap +# complete" on a machine where `make check` cannot run is a false +# success, so this fails instead. # # Installing docker from here was considered and rejected: it needs root, # a running daemon, and on macOS a GUI cask, so an attempt would itself @@ -80,15 +80,15 @@ bootstrap: FAILED - $reason. Docker is required to develop this repo. Without it these do not work: - script/lint builds Dockerfile.lint, which runs the linter as a - build step in a digest-pinned golangci-lint image. - That FROM line is the single source of truth for the - linter version - script/check runs script/lint + script/lint builds the lint phase of the Dockerfile, which runs + the linter as a build step in a digest-pinned + golangci-lint image + script/test builds the test phase of the Dockerfile + script/check runs script/test and script/lint script/precommit runs script/check, so commits are blocked by the pre-commit hook installed by script/setup - script/cibuild builds Dockerfile.lint and Dockerfile, which is what - CI runs + script/cibuild runs script/check and builds the image, which is + what CI runs Install docker (and start the daemon, checking DOCKER_HOST and your group membership), then re-run script/bootstrap. golangci-lint on PATH @@ -104,15 +104,22 @@ main() { if missing git; then pkg_install git git git git; fi if missing make; then pkg_install gnumake make make make; fi - # Go toolchain - if missing go; then pkg_install go golang go go; fi + # Go toolchain: the host's own, or else the version go.mod names, + # hash-verified, in .tool/go. That directory is not on the caller's + # PATH; this script, the Makefile, script/fmt, script/fmt-check, + # script/precommit and script/release add it to theirs. + if missing go; then + "$ROOT/script/install-go" + PATH="$PATH:$ROOT/.tool/go/bin" + fi # golangci-lint is deliberately NOT installed: script/lint lints by - # building Dockerfile.lint, whose digest-pinned image is the only - # place the linter runs, so whatever a package manager happens to - # ship would only be a shadow of the pinned version that could drift - # from CI. Nothing on the host is ever used as a linter, at any - # version, so installing one here would buy nothing. + # building the lint phase of the Dockerfile, whose digest-pinned + # image is the only place the linter runs, so whatever a package + # manager happens to ship would only be a shadow of the pinned + # version that could drift from CI. Nothing on the host is ever used + # as a linter, at any version, so installing one here would buy + # nothing. # goreleaser, at the version pinned by script/install-goreleaser and # verified against a hardcoded sha256. Package managers are not used diff --git a/script/check b/script/check index cc046f7..92875f7 100755 --- a/script/check +++ b/script/check @@ -1,7 +1,8 @@ #!/bin/sh # script/check: run all checks (test, lint, fmt-check). Our own -# extension to scripts-to-rule-them-all. Must not modify any files. -# Generic: usually needs no adaptation. +# extension to scripts-to-rule-them-all. test and lint are Docker +# phases; fmt-check is native, because a formatter writes the working +# tree. Must not modify any files. set -eu SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" diff --git a/script/cibuild b/script/cibuild index 032fae6..d8d3200 100755 --- a/script/cibuild +++ b/script/cibuild @@ -1,78 +1,28 @@ #!/bin/sh -# script/cibuild: run the CI build. This is the full gate, and it is two -# builds, in this order: -# -# Dockerfile.lint the linter, as a build step (a clean build IS a -# clean lint) -# Dockerfile `make fmt-check` and `make test` in the builder -# stage, then the product image -# -# Either one failing fails this script. Note what follows from the -# split: script/docker builds only the product image and so no longer -# lints -- this script and script/check (which runs script/lint) are the -# things that decide whether the tree is clean. -# -# Generic apart from the two Dockerfiles: the Gitea workflow runs this -# on push. +# script/cibuild: run the CI build. It bootstraps first: a CI runner +# checks out and runs this and nothing else, and script/fmt-check runs +# the formatter on the host, which a pristine checkout cannot do. +# --no-cache for the same reason as script/docker: the gate phases the +# final stage depends on are RUN steps, and a cached one is a check that +# did not run. set -eu -ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" +ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)" main() { cd "$ROOT" - # Both Dockerfiles key their check layers on CHECK_EPOCH, so a fresh - # value is what forces those layers to re-run: without it an - # unchanged tree replays them from cache, the checks never execute, - # and the build still exits 0. Each ARG sits immediately above the - # check RUNs, so dependency and module layers still cache. - # Dockerfile.lint also refuses to build at all when CHECK_EPOCH is - # empty, so a missing value fails its build loudly rather than passing - # quietly; the product Dockerfile does not, because a plain `docker - # build .` must succeed. - # - # The value must be unique per invocation, not per second. `date +%s` - # is second-granular, so two concurrent invocations in the same - # second get identical epochs and the later one can be served from - # cache -- the original defect in miniature. `%N` alone does not fix - # it: busybox silently drops %N, exits 0, and hands back second - # granularity with no warning. `$$` is what makes this correct - # regardless, since concurrent invocations have different pids. - # - # Assign the epoch on its own line rather than inline in the - # argument. Under `set -eu` a command substitution that fails - # inside an argument does NOT abort the script: CHECK_EPOCH would - # become an empty string, an empty string is a constant, and a - # constant CHECK_EPOCH is exactly the cached-check false green this - # script exists to prevent -- so the guard would disarm itself and - # still exit 0. As a bare assignment, `set -e` catches a failing - # `date` and no build starts. - # - # A separate value per build, because they are separate builds: one - # `date` shared between them would still be fresh, but reusing it - # invites the two to be collapsed into a single value that is - # computed somewhere else and passed in. - epoch="$(date +%s%N)$$" - # cacheonly for the lint build: its verdict is the exit status and - # the image is never run, so exporting it is pure cost. See - # script/lint. - docker build --output=type=cacheonly \ - --build-arg CHECK_EPOCH="$epoch" -f Dockerfile.lint . - - # Version, commit and build date are computed here on the host, the - # same way script/docker does, and passed into the product build, - # where they take precedence over what the build would derive from - # the .git in its context. VERSION comes from script/version, as in - # the Makefile. - version="$("$ROOT/script/version")" - commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" - commit_date="$(git show -s --format=%cs HEAD 2>/dev/null || echo unknown)" - - epoch="$(date +%s%N)$$" - docker build --build-arg CHECK_EPOCH="$epoch" \ + "$SCRIPT_DIR/bootstrap" + "$SCRIPT_DIR/check" + # Own line: a failing command substitution inside an argument does + # not trip `set -e`, so the inline form degrades silently to an + # empty constant. The VERSION build argument takes precedence over + # the version a build stage derives from the .git in the context. + version="$(git describe --tags --always --dirty 2>/dev/null || true)" + [ -n "$version" ] || version="unknown" + docker build --no-cache \ --build-arg VERSION="$version" \ - --build-arg COMMIT="$commit" \ - --build-arg COMMIT_DATE="$commit_date" \ - . + -t "$("$SCRIPT_DIR/projectname")" . } main "$@" diff --git a/script/docker b/script/docker index d685746..07b626c 100755 --- a/script/docker +++ b/script/docker @@ -1,15 +1,8 @@ #!/bin/sh # script/docker: build the Docker image tagged with the project name. -# The tag comes from script/projectname. Unlike the canonical copy in -# sneak/prompts, it passes a fresh CHECK_EPOCH instead of --no-cache, and -# COMMIT and COMMIT_DATE as well as VERSION. -# -# This builds the PRODUCT image only, and the product Dockerfile has no -# lint stage: linting lives in Dockerfile.lint and is run by -# script/lint. So a green here means `make fmt-check` and `make test` -# passed and the image built -- it says nothing about lint. The gates -# are script/check (which runs script/lint) and script/cibuild (which -# builds both files). +# Identical in all repos; the tag comes from script/projectname. +# --no-cache because the gate phases the final stage depends on are RUN +# steps, and a cached one is a check that did not run. set -eu SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" @@ -17,28 +10,14 @@ ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)" main() { cd "$ROOT" - # Same CHECK_EPOCH contract as script/cibuild, for the same reason - # and with the same bare-assignment and `$$` requirements -- see the - # comments there. This script is not the CI gate, but a local build - # is almost always warm, so without this it would report a green the - # tree had not earned and the two entrypoints would disagree about - # whether the tree is clean. - epoch="$(date +%s%N)$$" - - # Version, commit and build date are computed here on the host and - # passed into the build, where they take precedence over what the - # build would derive from the .git in its context. VERSION comes - # from script/version, as in the Makefile, so the image reports the - # same string, -dirty included, that a local build of the same tree - # would. - version="$("$SCRIPT_DIR/version")" - commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" - commit_date="$(git show -s --format=%cs HEAD 2>/dev/null || echo unknown)" - - docker build --build-arg CHECK_EPOCH="$epoch" \ + # Own line: a failing command substitution inside an argument does + # not trip `set -e`, so the inline form degrades silently to an + # empty constant. The VERSION build argument takes precedence over + # the version a build stage derives from the .git in the context. + version="$(git describe --tags --always --dirty 2>/dev/null || true)" + [ -n "$version" ] || version="unknown" + docker build --no-cache \ --build-arg VERSION="$version" \ - --build-arg COMMIT="$commit" \ - --build-arg COMMIT_DATE="$commit_date" \ -t "$("$SCRIPT_DIR/projectname")" . } diff --git a/script/fmt b/script/fmt index e95d111..f4876e1 100755 --- a/script/fmt +++ b/script/fmt @@ -6,6 +6,8 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" main() { cd "$ROOT" + # Where script/bootstrap installs Go when the host has none. + PATH="$PATH:$ROOT/.tool/go/bin" go fmt ./... } diff --git a/script/fmt-check b/script/fmt-check index 57e8e5c..84c23df 100755 --- a/script/fmt-check +++ b/script/fmt-check @@ -7,7 +7,14 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" main() { cd "$ROOT" - unformatted="$(gofmt -l .)" + # Where script/bootstrap installs Go when the host has none. + PATH="$PATH:$ROOT/.tool/go/bin" + # .tool/go holds that toolchain's own sources, which are not ours. + if ! unformatted="$(find . -path ./.tool -prune -o -name '*.go' -type f \ + -exec gofmt -l {} +)"; then + echo "fmt-check: gofmt failed" >&2 + exit 1 + fi if [ -n "$unformatted" ]; then echo "Files not formatted:" >&2 echo "$unformatted" >&2 diff --git a/script/install-go b/script/install-go index 38056dc..3442421 100755 --- a/script/install-go +++ b/script/install-go @@ -4,12 +4,13 @@ # own extension to scripts-to-rule-them-all. Idempotent: exits at once # when the pinned toolchain is already installed. # -# Only .gitea/workflows/release.yml calls this. goreleaser is not a +# .gitea/workflows/release.yml calls this, and so does script/bootstrap +# when the host has no Go, as on the check runner. goreleaser is not a # compiler: it shells out to `go` for the `before:` hook and for every # one of the four cross-compiles, so the release runner needs a Go -# toolchain on PATH. check.yml never does -- it builds inside the -# digest-pinned Dockerfile images -- so this is the release path's only -# host Go, and per REPO_POLICIES.md it must be pinned by hash. +# toolchain on PATH. The check runner compiles nothing on the host; it +# uses this Go only for bootstrap's `go mod download` and for gofmt in +# script/fmt-check. Per REPO_POLICIES.md a host Go is pinned by hash. # actions/setup-go exposes no checksum input, so Go is installed the way # script/install-goreleaser installs goreleaser: download the exact # archive from go.dev and refuse it unless its sha256 matches the value @@ -18,11 +19,11 @@ # The version is go.mod's `go` directive, the single source of truth for # the toolchain. GO_VERSION below MUST equal it, and this script fails # when they disagree -- so bumping Go is one reviewed change touching -# go.mod, the checksum here, and the Dockerfile golang digest together. +# go.mod, the checksums here, and the Dockerfile's two golang digests +# together. # -# Linux only, because that is what the release runner is. A darwin dev -# building a snapshot uses their own Go; supporting an OS means adding -# its checksums. +# Linux and macOS, each on amd64 and arm64: the four archives whose +# checksums are committed below. set -eu ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" @@ -33,6 +34,8 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" GO_VERSION="1.26.1" SHA256_LINUX_AMD64="031f088e5d955bab8657ede27ad4e3bc5b7c1ba281f05f245bcc304f327c987a" SHA256_LINUX_ARM64="a290581cfe4fe28ddd737dde3095f3dbeb7f2e4065cab4eae44dfc53b760c2f7" +SHA256_DARWIN_AMD64="65773dab2f8cc4cd23d93ba6d0a805de150ca0b78378879292be0b903b8cdd08" +SHA256_DARWIN_ARM64="353df43a7811ce284c8938b5f3c7df40b7bfb6f56cb165b150bc40b5e2dd541f" GOROOT_DIR="$ROOT/.tool/go" GOCMD="$GOROOT_DIR/bin/go" @@ -101,26 +104,28 @@ main() { arch="$(uname -m)" case "$os" in Linux) os="linux" ;; + Darwin) os="darwin" ;; *) - echo "install-go: unsupported OS $os (release runner is Linux)" >&2 + echo "install-go: unsupported OS $os" >&2 exit 1 ;; esac case "$arch" in - x86_64 | amd64) - arch="amd64" - sum="$SHA256_LINUX_AMD64" - ;; - arm64 | aarch64) - arch="arm64" - sum="$SHA256_LINUX_ARM64" - ;; + x86_64 | amd64) arch="amd64" ;; + arm64 | aarch64) arch="arm64" ;; *) - echo "install-go: no pinned checksum for architecture $arch" >&2 + echo "install-go: unsupported architecture $arch" >&2 exit 1 ;; esac + case "${os}-${arch}" in + linux-amd64) sum="$SHA256_LINUX_AMD64" ;; + linux-arm64) sum="$SHA256_LINUX_ARM64" ;; + darwin-amd64) sum="$SHA256_DARWIN_AMD64" ;; + darwin-arm64) sum="$SHA256_DARWIN_ARM64" ;; + esac + archive="go${GO_VERSION}.${os}-${arch}.tar.gz" url="https://go.dev/dl/${archive}" diff --git a/script/lint b/script/lint index 5499014..2d8b075 100755 --- a/script/lint +++ b/script/lint @@ -1,108 +1,23 @@ #!/bin/sh -# script/lint: run the linter. +# script/lint: run the linter. Linting is a phase of the Dockerfile and +# this builds that phase alone; the linter is never installed or run on +# a developer host, where a shared result cache and a host-global lock +# make its answer untrustworthy. # -# The linter runs inside the image built by Dockerfile.lint, and it runs -# there as a BUILD STEP: a successful build of that file IS a clean -# lint. Nothing lints on the host, at any version, ever. That FROM line -# is the single source of truth for the linter version in this repo, so -# a local run and a CI run of the same tree cannot disagree. -# -# One container per run means one lint cache and one golangci-lint lock -# per run, both private to that run and thrown away with it. That is -# what makes concurrent runs on a shared host safe, and it is why this -# script no longer carries per-worktree cache directories, a lock-retry -# loop, or an output audit: there is no shared state left for them to -# defend (issue https://git.eeqj.de/sneak/vaultik/issues/113). -# -# To watch the linter execute, set BUILDKIT_PROGRESS=plain, which docker -# honours directly: -# -# BUILDKIT_PROGRESS=plain script/lint -# -# The check layers -- `golangci-lint config verify` and then -# `golangci-lint run` -- must appear as executing rather than CACHED on -# every run; see the CHECK_EPOCH comment in Dockerfile.lint. +# The phase is not the last stage in the file, so it is built only when +# --target names it. --no-cache because a cached lint layer is a lint +# that did not run. The tag makes each build replace the previous image +# instead of leaving a dangling one behind. set -eu -ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" -DOCKERFILE="$ROOT/Dockerfile.lint" - -require_docker() { - if ! command -v docker >/dev/null 2>&1; then - cat >&2 </dev/null 2>&1; then - cat >&2 <&2 <&2 + echo "lint-fix: no FROM ... AS lint line found in $DOCKERFILE" >&2 exit 1 fi diff --git a/script/precommit b/script/precommit index 50f02ae..e55afea 100755 --- a/script/precommit +++ b/script/precommit @@ -9,6 +9,8 @@ ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)" main() { cd "$ROOT" + # Where script/bootstrap installs Go when the host has none. + PATH="$PATH:$ROOT/.tool/go/bin" go mod tidy go fmt ./... git diff --exit-code -- go.mod go.sum || { diff --git a/script/release b/script/release index a9e2056..05ec0ae 100755 --- a/script/release +++ b/script/release @@ -44,6 +44,8 @@ resolve_goreleaser() { main() { cd "$ROOT" + # Where script/bootstrap installs Go when the host has none. + PATH="$PATH:$ROOT/.tool/go/bin" if ! bin="$(resolve_goreleaser)"; then cat >&2 < (cached)`, and that line is -# indistinguishable -- to every check this repo performs -- from a -# package that actually ran. The whole suite reports its full set of -# `ok` lines in under half a second having executed nothing. That -# matters beyond the local inner loop: the Dockerfile's `RUN make test` -# is forced to re-execute by CHECK_EPOCH, but a GOCACHE baked into an -# earlier image layer survives into the re-executed step, so the step -# can re-run and still do no work. It is applied unconditionally rather -# than only in the containerised path because the pre-commit hook runs -# this same script; a gate that is honest only in CI is dishonest -# exactly where people lean on it most. -# -# -timeout is a hang backstop, not a performance budget: its job is to -# turn a deadlocked test into a stack dump instead of a wedged CI job, -# so it wants to sit far above the slowest legitimate runtime, not just -# above it. It is per test binary and covers test execution only -- the -# clock starts inside testing.M.Run, after compilation and linking, so -# build time is not charged against it. (Measured: a containerised run -# with an empty GOCACHE reports per-package durations within noise of a -# warm host run. A shell `timeout 30 go test ./...` would include -# compilation, but that is a different mechanism from this flag.) -# -# The 120s value DELIBERATELY DIVERGES from REPO_POLICIES.md:192, which -# mandates "Add a 30-second timeout", and from that file's canonical Go -# recipe at :212-214, which uses -timeout 30s. REPO_POLICIES.md is -# org-canonical and cannot be amended from this repo, so the divergence -# is recorded here instead, and issue #101 proposes amending the policy -# text upstream. Do not revert this to 30s without reading #101 first. -# -# Why it diverges: the slowest packages are internal/database and -# internal/vaultik, observed under -race at about 6.4s warm, 8.1s in a -# cold containerised run on a contended host, and 10.2s in an -# independent cold run on this same host. The worst case is not tightly -# characterised -- each fresh measurement has come in above the last -- -# which is itself an argument for generous headroom. Against the 10.2s -# observation, 30s is only 2.9x: not a safety margin but a flake -# waiting for a slow day, whose failure mode is a timeout that looks -# like a real defect. 120s leaves about 12x while still bounding a hung -# package -- including the verbose rerun below -- to a few minutes. The -# cost of that choice, also recorded on #101: because of the rerun, a -# hung package pays the timeout twice. -run_tests() { - go test -race -timeout 120s -count=1 "$@" ./... -} +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" +ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)" main() { cd "$ROOT" - run_tests || { - echo "--- Rerunning with -v for details ---" - run_tests -v - exit 1 - } + docker build --no-cache \ + --target test \ + -t "$("$SCRIPT_DIR/projectname")-test" . } main "$@" diff --git a/script/version b/script/version index 7ba6ad0..4006043 100755 --- a/script/version +++ b/script/version @@ -3,9 +3,8 @@ # Our own extension to scripts-to-rule-them-all. The Makefile's LDFLAGS # call this rather than carrying a hardcoded constant, which is what used # to make every local build claim to be 1.0.0-rc.1 regardless of git -# state. script/docker and script/cibuild pass its output to the image -# build; given no version, the image build runs `git describe --tags -# --always` itself, without `--dirty`. +# state. script/docker and script/cibuild run the same `git describe` +# themselves, and fall back to "unknown" rather than "dev". # # The version is `git describe --tags --always --dirty`: the tag on a # tagged commit, tag-N-gHASH on a commit after one, the short commit From 66c80a70e30ea4f3c8b40240b7e54e03acd98a27 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 14:46:05 +0200 Subject: [PATCH 012/121] Skip files of an unreadable blob under restore --skip-errors (closes #218) A blob that failed to download ended `snapshot restore` even with --skip-errors, after restoring whichever files came first. The download error now goes through the same per-file handling as any other restore error, once for every pending file that references the blob. With --skip-errors those files are reported as failed, the rest are restored, and the command still exits non-zero. Without the flag the restore still aborts; the error now also names one affected file and suggests --skip-errors. A cancelled restore still ends at once. The --skip-errors help text and README now limit the packing and storage caveat to snapshot creation. Model: opus-5-5 --- README.md | 2 +- TODO.md | 8 + internal/cli/root.go | 3 +- internal/vaultik/restore.go | 30 ++- internal/vaultik/restore_interrupt_test.go | 50 +++++ internal/vaultik/restore_plan.go | 14 ++ internal/vaultik/restore_skip_errors_test.go | 194 +++++++++++++++++++ 7 files changed, 296 insertions(+), 5 deletions(-) create mode 100644 internal/vaultik/restore_skip_errors_test.go diff --git a/README.md b/README.md index 71011d1..6592d9f 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ vaultik version * `--verbose`, `-v`: Enable verbose output (on stderr — see below) * `--debug`: Enable debug output (on stderr — see below) * `--quiet`, `-q`: Suppress non-error output (also suppresses startup banner) -* `--skip-errors`: Skip files that cannot be read when creating a snapshot, or that cannot be restored when restoring, instead of aborting. Packing and storage errors (which would leave a chunk recorded but not stored) still abort the run. +* `--skip-errors`: Skip files that cannot be read when creating a snapshot, or that cannot be restored when restoring, instead of aborting. Packing and storage errors while creating a snapshot (which would leave a chunk recorded but not stored) still abort the run. ### locking diff --git a/TODO.md b/TODO.md index f6eaa18..a59deca 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,14 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made `snapshot restore --skip-errors` skip the files that + need a blob it cannot download + ([issue #218](https://git.eeqj.de/sneak/vaultik/issues/218)). A missing + or damaged blob ended the restore even with the flag, after restoring + whichever files happened to come first. Every file that needs such a + blob is now reported as failed, the rest are restored, and the command + still exits non-zero. Without the flag the blob error still aborts. + - 2026-10-06: Re-vendored the canonical files from `sneak/prompts` at `dd4027b` ([issue #213](https://git.eeqj.de/sneak/vaultik/issues/213)). Linting and testing are now the `lint` and `test` phases of the diff --git a/internal/cli/root.go b/internal/cli/root.go index 7f24423..463eb1d 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -60,7 +60,8 @@ on the source system.`, cmd.PersistentFlags().BoolVar(&rootFlags.SkipErrors, "skip-errors", false, "Skip files that cannot be read when creating a snapshot, or "+ "that cannot be restored when restoring, instead of aborting "+ - "(packing and storage errors still abort)") + "(packing and storage errors while creating a snapshot still "+ + "abort)") // Add subcommands cmd.AddCommand( diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index 118a68b..f8372d6 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -355,7 +355,7 @@ func (v *Vaultik) runRestoreLoop( fileID, ready := plan.popReady() if !ready { - downloaded, err := session.downloadNextBlobSet(plan) + downloaded, err := session.downloadNextBlobSet(plan, filesByID) if err != nil { return err } @@ -411,7 +411,13 @@ func (v *Vaultik) runRestoreLoop( // blob set and downloads its blobs; after each blob lands, the plan // moves any pending file whose set just emptied onto the ready queue. // Returns false when nothing is pending download (the caller stops). -func (s *restoreSession) downloadNextBlobSet(plan *restorePlan) (bool, error) { +// +// A blob that cannot be downloaded is reported through +// handleRestoreFileError for every pending file that references it, so +// it aborts the restore unless --skip-errors is set. +func (s *restoreSession) downloadNextBlobSet( + plan *restorePlan, filesByID map[types.FileID]*database.File, +) (bool, error) { s.sweeper.sweep() next, ok := plan.pickNextDownload() @@ -433,7 +439,25 @@ func (s *restoreSession) downloadNextBlobSet(plan *restorePlan) (bool, error) { err := s.downloadBlobToCache(hash, blob.CompressedSize, blob.UncompressedSize) if err != nil { - return false, fmt.Errorf("downloading blob %s: %w", shortHash(hash), err) + err = fmt.Errorf("downloading blob %s: %w", shortHash(hash), err) + + // On cancel the error says nothing about the blob, so it ends + // the restore instead of failing the files that need it. + if s.ctx.Err() != nil { + return false, err + } + + for _, fileID := range plan.filesReferencingBlob(hash) { + fileErr := s.v.handleRestoreFileError( + plan, s.opts, s.result, filesByID[fileID], fileID, err) + if fileErr != nil { + return false, fileErr + } + } + + // next is among the failed files, so the rest of its blob set + // is left for any other file that still needs it. + return true, nil } s.result.BlobsDownloaded++ diff --git a/internal/vaultik/restore_interrupt_test.go b/internal/vaultik/restore_interrupt_test.go index ccf07a5..e8816c5 100644 --- a/internal/vaultik/restore_interrupt_test.go +++ b/internal/vaultik/restore_interrupt_test.go @@ -1,6 +1,7 @@ package vaultik //nolint:testpackage // sets ctx/cancel and inspects scratch files import ( + "bytes" "context" "io" "path/filepath" @@ -11,6 +12,7 @@ import ( "time" "github.com/spf13/afero" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/storage" @@ -157,3 +159,51 @@ func scratchEntries(t *testing.T, dir string) []string { return matches } + +// TestRestoreSkipErrorsCancelDuringBlobDownload cancels a SkipErrors +// restore while a blob download is in progress. The download fails only +// because of the cancel, so Restore must return context.Canceled without +// reporting the file that needs the blob as failed. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestRestoreSkipErrorsCancelDuringBlobDownload(t *testing.T) { + log.Initialize(log.Config{}) + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + cfg, storer, snapshotID, srcPath := backupOneFile(context.Background(), + t, fs, tempDir, "a.txt", []byte("hello vaultik"), 0o644) + + gate := newBlockingBlobStorer(storer) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var out bytes.Buffer + + v := newRestoreVaultik(ctx, cfg, gate, fs) + v.UI = ui.NewWithColor(&out, false) + + restoreErr := make(chan error, 1) + + go func() { + restoreErr <- v.Restore(&RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: filepath.Join(tempDir, "restored"), + SkipErrors: true, + }) + }() + + select { + case <-gate.entered: + case <-time.After(30 * time.Second): + t.Fatal("restore never reached the blob-download phase") + } + + cancel() + + require.ErrorIs(t, <-restoreErr, context.Canceled) + assert.NotContains(t, out.String(), srcPath, + "the cancel was reported as a failed file") +} diff --git a/internal/vaultik/restore_plan.go b/internal/vaultik/restore_plan.go index 8ec0f1f..d9805fa 100644 --- a/internal/vaultik/restore_plan.go +++ b/internal/vaultik/restore_plan.go @@ -214,6 +214,20 @@ func (p *restorePlan) blobsNeeded(fileID types.FileID) []string { return out } +// filesReferencingBlob returns the pending files that reference the +// named blob, in any order. The result is a copy, so the caller may +// finishFile each of them while ranging over it. +func (p *restorePlan) filesReferencingBlob(blobHash string) []types.FileID { + files := p.blobFiles[blobHash] + + out := make([]types.FileID, 0, len(files)) + for id := range files { + out = append(out, id) + } + + return out +} + // hasPending reports whether any unfinished files remain. func (p *restorePlan) hasPending() bool { return len(p.fileBlobs) > 0 diff --git a/internal/vaultik/restore_skip_errors_test.go b/internal/vaultik/restore_skip_errors_test.go new file mode 100644 index 0000000..bb19ff4 --- /dev/null +++ b/internal/vaultik/restore_skip_errors_test.go @@ -0,0 +1,194 @@ +package vaultik_test + +import ( + "bytes" + "context" + "fmt" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// A file no larger than the chunker's minimum chunk size (a quarter of +// faultChunkSize) is stored as one chunk, so it lives in exactly one blob. +// More of them than fit in faultMaxBlobSize make the snapshot span two +// blobs. +const ( + missingBlobFileBytes = int(faultChunkSize / 4) + missingBlobFileCount = 20 +) + +// missingBlobBackup is a snapshot of single-chunk files spread over two +// blobs, with one of those blobs deleted from the store. +type missingBlobBackup struct { + fs afero.Fs + cfg *config.Config + storer storage.Storer + snapshotID string + restoreDir string + // files holds the original content by source path. + files map[string][]byte + // lost holds the source paths whose chunk is in the deleted blob. + lost map[string]bool +} + +// TestRestoreSkipErrorsSkipsFilesOfMissingBlob restores with SkipErrors +// after one blob of a two-blob snapshot was deleted. Every file stored in +// that blob must be reported as failed and left absent, every other file +// must be restored intact, and Restore must still return an error. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestRestoreSkipErrorsSkipsFilesOfMissingBlob(t *testing.T) { + ctx := context.Background() + backup := backupThenDeleteOneBlob(ctx, t) + + var out bytes.Buffer + + v := newReaderVaultik(ctx, backup.cfg, backup.storer, nil, backup.fs) + v.UI = ui.NewWithColor(&out, false) + + err := v.Restore(&vaultik.RestoreOptions{ + SnapshotID: backup.snapshotID, + TargetDir: backup.restoreDir, + SkipErrors: true, + }) + + require.Error(t, err, "restore must fail when files were skipped") + assert.Contains(t, err.Error(), + fmt.Sprintf("%d file(s) failed to restore", len(backup.lost))) + + for path, content := range backup.files { + restored := filepath.Join(backup.restoreDir, path) + + if backup.lost[path] { + assert.Containsf(t, out.String(), path, + "%s needs the deleted blob and must be reported", path) + assert.NoFileExists(t, restored) + + continue + } + + got, err := afero.ReadFile(backup.fs, restored) + require.NoErrorf(t, err, "%s does not need the deleted blob", path) + assert.Equalf(t, content, got, "%s restored with wrong content", path) + } +} + +// TestRestoreMissingBlobAbortsWithoutSkipErrors checks that a deleted blob +// still ends the restore with an error when SkipErrors is not set. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestRestoreMissingBlobAbortsWithoutSkipErrors(t *testing.T) { + ctx := context.Background() + backup := backupThenDeleteOneBlob(ctx, t) + + v := newReaderVaultik(ctx, backup.cfg, backup.storer, nil, backup.fs) + + err := v.Restore(&vaultik.RestoreOptions{ + SnapshotID: backup.snapshotID, + TargetDir: backup.restoreDir, + }) + + require.ErrorIs(t, err, storage.ErrNotFound) +} + +// backupThenDeleteOneBlob backs up missingBlobFileCount single-chunk +// files, then deletes from the store the blob holding the first of them. +func backupThenDeleteOneBlob( + ctx context.Context, t *testing.T, +) *missingBlobBackup { + t.Helper() + log.Initialize(log.Config{}) + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + dbPath := filepath.Join(tempDir, "index.sqlite") + cfg := faultTestConfig() + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + + files := make(map[string][]byte, missingBlobFileCount) + + for i := range missingBlobFileCount { + path := filepath.Join(dataDir, fmt.Sprintf("file-%02d.bin", i)) + files[path] = bytesPattern( + fmt.Sprintf("file-%02d-", i), missingBlobFileBytes) + require.NoError(t, afero.WriteFile(fs, path, files[path], 0o644)) + } + + storer, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + + id := fullFaultBackup( + ctx, t, fs, storer, cfg, repos, dataDir, dbPath, "missingblob") + + blobOfFile := make(map[string]string, len(files)) + for path := range files { + blobOfFile[path] = blobHashOfSingleChunkFile(ctx, t, repos, path) + } + + require.NoError(t, db.Close()) + + deleted := blobOfFile[filepath.Join(dataDir, "file-00.bin")] + require.NoError(t, storer.Delete(ctx, fmt.Sprintf( + "blobs/%s/%s/%s", deleted[:2], deleted[2:4], deleted))) + + lost := make(map[string]bool) + + for path, hash := range blobOfFile { + if hash == deleted { + lost[path] = true + } + } + + require.Less(t, len(lost), len(files), + "the snapshot must span more than one blob") + + return &missingBlobBackup{ + fs: fs, + cfg: cfg, + storer: storer, + snapshotID: id, + restoreDir: filepath.Join(tempDir, "restored"), + files: files, + lost: lost, + } +} + +// blobHashOfSingleChunkFile returns the hash of the blob holding the one +// chunk of the file at path, as recorded in the local index. +func blobHashOfSingleChunkFile( + ctx context.Context, t *testing.T, + repos *database.Repositories, path string, +) string { + t.Helper() + + chunks, err := repos.FileChunks.GetByPath(ctx, path) + require.NoError(t, err) + require.Lenf(t, chunks, 1, "%s must be a single chunk", path) + + blobChunk, err := repos.BlobChunks.GetByChunkHash( + ctx, chunks[0].ChunkHash.String()) + require.NoError(t, err) + require.NotNilf(t, blobChunk, "chunk of %s is in no blob", path) + + blob, err := repos.Blobs.GetByID(ctx, blobChunk.BlobID.String()) + require.NoError(t, err) + + return blob.Hash.String() +} From 14fc4c9893e37b25fba4622f613c1f19f830d49e Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 15:46:13 +0200 Subject: [PATCH 013/121] Load a config that has no age recipient (closes #221) The README's steps for restoring on another machine failed at the first command: `config init` wrote a placeholder recipient, and `config.Load` rejects any recipient that does not parse. `config init` now writes an empty `age_recipients` list, `config.Load` accepts an empty list, and `snapshot create` refuses to start without a recipient. A malformed recipient is still rejected at load. The recovery-host test now builds its config with `config init` and `config set` and reads it through `config.Load`, so it imports `internal/cli`. On a fresh file, `config set age_recipients.0` writes the list in flow style (`[age1...]`). Model: opus-5-5 --- README.md | 2 +- TODO.md | 8 +++ config.example.yml | 3 +- internal/cli/config.go | 11 ++-- internal/cli/config_test.go | 43 +++++++++++++- internal/config/config.go | 15 ++--- internal/config/config_test.go | 10 +++- .../vaultik/restore_another_machine_test.go | 57 +++++++++++++++---- internal/vaultik/snapshot.go | 9 +++ 9 files changed, 126 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 6592d9f..425d569 100644 --- a/README.md +++ b/README.md @@ -530,7 +530,7 @@ complete annotated example also lives in | Field | Default | Description | |-------|---------|-------------| -| `age_recipients` | (required) | Age public keys for encryption | +| `age_recipients` | (required by `snapshot create`) | Age public keys for encryption. Other commands run without one, so a machine that only restores can leave it empty | | `age_secret_key` | (unset) | Age private key for decryption (`snapshot restore`, `snapshot verify --deep`). Setting it in the config file places the private key on the backed-up host, defeating the public-key-only design (see "why" above). Prefer the `VAULTIK_AGE_SECRET_KEY` environment variable, supplied only on the machine you restore from. | | `snapshots` | (required) | Named snapshot definitions with paths and excludes | | `storage_url` | | Storage backend URL (`s3://`, `file://`, `rclone://`) | diff --git a/TODO.md b/TODO.md index a59deca..b7958a5 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,14 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made the README's steps for restoring on another machine + work ([issue #221](https://git.eeqj.de/sneak/vaultik/issues/221)). + `config init` wrote a placeholder recipient that `config.Load` + rejects, so every command on the new machine failed before reaching + the store. The file now has an empty `age_recipients` list, + `config.Load` accepts an empty list, and `snapshot create` refuses to + run without a recipient. + - 2026-10-06: Made `snapshot restore --skip-errors` skip the files that need a blob it cannot download ([issue #218](https://git.eeqj.de/sneak/vaultik/issues/218)). A missing diff --git a/config.example.yml b/config.example.yml index 199c3d1..6dc50de 100644 --- a/config.example.yml +++ b/config.example.yml @@ -3,7 +3,8 @@ # Copy this file and uncomment/modify the values you need # Age recipient public keys for encryption -# This is REQUIRED - backups are encrypted to these public keys +# Backups are encrypted to these public keys. snapshot create needs at least +# one; listing, verifying and restoring do not # Generate with: age-keygen | grep "public key" age_recipients: - age1cj2k2addawy294f6k2gr2mf9gps9r3syplryxca3nvxj3daqm96qfp84tz diff --git a/internal/cli/config.go b/internal/cli/config.go index ae8aad9..a7444f8 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -45,16 +45,19 @@ const defaultConfigTemplate = `# vaultik configuration # ─── REQUIRED ──────────────────────────────────────────────────────────────── -# Age recipient public keys for encryption. +# Age recipient public keys for encryption. snapshot create needs at least +# one; listing, verifying and restoring do not, so a machine that only +# restores can leave this empty. # Backups are encrypted to ALL listed recipients; any one of the corresponding # private keys can decrypt. Adding a recipient later does not re-encrypt data # already stored: deduplicated chunks and existing blobs stay encrypted to the # earlier recipients, so a newly added key cannot restore them on its own (see -# docs/REPOSTRUCTURE.md, Accepted Risks). Generate a keypair with: +# docs/REPOSTRUCTURE.md, Accepted Risks). Generate a keypair and add its +# public key with: # age-keygen -o vaultik_backup_private_key.txt # grep 'public key' vaultik_backup_private_key.txt -age_recipients: - - age1REPLACE_WITH_YOUR_PUBLIC_KEY +# vaultik config set age_recipients.0 age1... +age_recipients: [] # Named snapshots. Each snapshot backs up one or more paths and can have its # own exclude patterns in addition to the global excludes below. diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go index b537946..4e3f7e2 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -24,8 +24,10 @@ func TestDefaultConfigTemplateParses(t *testing.T) { t.Fatalf("default config template is not valid YAML: %v", err) } - if len(cfg.AgeRecipients) != 1 { - t.Errorf("expected 1 placeholder age recipient, got %d", len(cfg.AgeRecipients)) + // A placeholder recipient would fail config.Load, so the template + // leaves the list empty. + if len(cfg.AgeRecipients) != 0 { + t.Errorf("expected no age recipients, got %d", len(cfg.AgeRecipients)) } home, ok := cfg.Snapshots["home"] @@ -55,6 +57,43 @@ func TestDefaultConfigTemplateParses(t *testing.T) { } } +// TestConfigSetRecipientOnFreshConfig follows the README quickstart: on the +// file `config init` writes, `config set age_recipients.0` and +// `config set storage_url` give a config that loads with that recipient. +func TestConfigSetRecipientOnFreshConfig(t *testing.T) { + t.Parallel() + + const recipient = "age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj" + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(defaultConfigTemplate), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + out := ui.NewWithColor(&bytes.Buffer{}, false) + + err = writeConfigSet(out, path, "age_recipients.0", recipient) + if err != nil { + t.Fatalf("config set age_recipients.0: %v", err) + } + + err = writeConfigSet(out, path, "storage_url", "file:///mnt/backups") + if err != nil { + t.Fatalf("config set storage_url: %v", err) + } + + cfg, err := config.Load(path) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + + if len(cfg.AgeRecipients) != 1 || cfg.AgeRecipients[0] != recipient { + t.Errorf("age_recipients = %v, want [%s]", cfg.AgeRecipients, recipient) + } +} + const testYAML = `# top comment compression_level: 3 age_recipients: diff --git a/internal/config/config.go b/internal/config/config.go index 2608d9d..1448a32 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -42,9 +42,7 @@ const ( // Sentinel validation errors. var ( - errNoConfigPath = errors.New("config path not provided") - errNoAgeRecipients = errors.New( - "at least one age_recipient is required (generate with: age-keygen)") + errNoConfigPath = errors.New("config path not provided") errRecipientIsSecretKey = errors.New( "an age secret key was given where a public key (age1...) belongs") errRecipientNotX25519 = errors.New( @@ -323,9 +321,10 @@ func Load(path string) (*Config, error) { // Validate checks if the configuration is valid and complete. // It ensures all required fields are present and have valid values: -// - At least one age recipient must be specified, and every recipient must -// parse as an X25519 age1... public key (so a bad entry fails at load, not -// mid-backup); errors name the position, never the value +// - Every age recipient must parse as an X25519 age1... public key (so a +// bad entry fails at load, not mid-backup); errors name the position, +// never the value. An empty list is accepted, because only snapshot +// create needs a recipient and it checks for one itself // - At least one snapshot must be configured with at least one path // - Storage must be configured (either storage_url or s3.* fields) // - Chunk size must be at least 1MB @@ -336,10 +335,6 @@ func Load(path string) (*Config, error) { // // Returns an error describing the first validation failure encountered. func (c *Config) Validate() error { - if len(c.AgeRecipients) == 0 { - return errNoAgeRecipients - } - for i, recipient := range c.AgeRecipients { err := validateAgeRecipient(recipient) if err != nil { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 44e9fe6..52b46ad 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -223,7 +223,8 @@ func TestValidateBlobSizeLimit(t *testing.T) { // TestValidateAgeRecipients checks that recipients are parsed at config load // (a bad entry fails immediately, not mid-backup) and that no invalid entry — -// least of all a pasted secret key — is echoed in the error. +// least of all a pasted secret key — is echoed in the error. An empty list +// loads, because only snapshot create needs a recipient. func TestValidateAgeRecipients(t *testing.T) { t.Parallel() @@ -244,7 +245,12 @@ func TestValidateAgeRecipients(t *testing.T) { wantErr bool }{ { - name: "config init placeholder is rejected", + name: "no recipients is accepted", + recipients: nil, + wantErr: false, + }, + { + name: "placeholder recipient is rejected", recipients: []string{"age1REPLACE_WITH_YOUR_PUBLIC_KEY"}, wantErr: true, }, diff --git a/internal/vaultik/restore_another_machine_test.go b/internal/vaultik/restore_another_machine_test.go index 59268a4..3f53202 100644 --- a/internal/vaultik/restore_another_machine_test.go +++ b/internal/vaultik/restore_another_machine_test.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/cli" "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" @@ -27,10 +28,12 @@ import ( // // The backup half writes a snapshot with one index and hostname. The // restore half throws that index away entirely: a fresh, empty index and -// a config that shares nothing with the original but the storage location -// and the secret key. If restore or verify needed the original local -// index — or the human snapshot ID that only that index holds — this test -// could not run, because the recovery host can know neither. +// a config written by `config init` and `config set storage_url`, as in +// the README's steps for restoring on another machine, which shares +// nothing with the original but the storage location and the secret key. +// If restore or verify needed the original local index — or +// the human snapshot ID that only that index holds — this test could not +// run, because the recovery host can know neither. func TestRestoreOnAnotherMachine(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -58,7 +61,12 @@ func TestRestoreOnAnotherMachine(t *testing.T) { // Recovery host: a fresh empty index, a different hostname, and no // age_recipients — only the secret key and the same storage location. - recovery, stdout := newRecoveryHost(ctx, t, fs, storer) + configPath := filepath.Join(tempDir, "config.yml") + runVaultikCommand(t, "--config", configPath, "config", "init") + runVaultikCommand(t, "--config", configPath, + "config", "set", "storage_url", "file://"+storeDir) + + recovery, stdout := newRecoveryHost(ctx, t, fs, storer, configPath) // The recovery index really is empty. This is the assertion that makes // the test a guard against restore quietly depending on the original @@ -93,6 +101,10 @@ func TestRestoreOnAnotherMachine(t *testing.T) { remote.RemoteKey, &vaultik.VerifyOptions{Deep: true})) assertRestoredTreeMatches(t, fs, restoreDir, sourceFiles) + + // With no public key configured, a backup must refuse to start. + err = recovery.CreateSnapshot(&vaultik.SnapshotCreateOptions{Cron: true}) + require.ErrorContains(t, err, "age_recipients") } // writeRecoverySourceTree writes a small source tree spanning several @@ -118,14 +130,24 @@ func writeRecoverySourceTree( } // newRecoveryHost builds the Vaultik a replacement machine would run: an -// empty in-memory index, a hostname different from the backup host, no -// age_recipients, and only the secret key plus the shared storer. It -// returns the instance and the buffer its stdout is wired to. +// empty in-memory index, a hostname different from the backup host, and +// only the secret key plus the shared storer. Its config is read from +// configPath by config.Load, as every command reads it. It returns the +// instance and the buffer its stdout is wired to. func newRecoveryHost( ctx context.Context, t *testing.T, fs afero.Fs, storer storage.Storer, + configPath string, ) (*vaultik.Vaultik, *bytes.Buffer) { t.Helper() + cfg, err := config.Load(configPath) + require.NoError(t, err) + + // Set directly rather than through VAULTIK_AGE_SECRET_KEY, which a + // parallel test cannot change. + cfg.AgeSecretKey = testAgeSecretKey + cfg.Hostname = "recovery-host" + recoveryDB, err := database.New(ctx, ":memory:") require.NoError(t, err) t.Cleanup(func() { _ = recoveryDB.Close() }) @@ -133,10 +155,7 @@ func newRecoveryHost( stdout := &bytes.Buffer{} recovery := &vaultik.Vaultik{ - Config: &config.Config{ - AgeSecretKey: testAgeSecretKey, - Hostname: "recovery-host", - }, + Config: cfg, Storage: storer, Fs: fs, Repositories: database.NewRepositories(recoveryDB), @@ -150,6 +169,20 @@ func newRecoveryHost( return recovery, stdout } +// runVaultikCommand runs one vaultik command line in-process and fails the +// test if it returns an error. The command writes the cli package's global +// flag variables, so it must not be called from two tests that run at the +// same time. +func runVaultikCommand(t *testing.T, args ...string) { + t.Helper() + + cmd := cli.NewRootCommand() + cmd.SetArgs(args) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + require.NoError(t, cmd.Execute()) +} + // assertRestoredTreeMatches byte-compares every restored file against its // source content. func assertRestoredTreeMatches( diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 9f76fdf..cb61ba5 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -23,6 +23,9 @@ var ( errSnapshotVerifyFailed = errors.New("verification failed") errRemoveAllNeedsForce = errors.New("--all requires --force") errInvalidTableName = errors.New("invalid table name") + errNoAgeRecipients = errors.New( + "creating a snapshot needs at least one public key in " + + "age_recipients (generate a keypair with: age-keygen)") ) // listRecentLimit caps how many snapshot rows are fetched from the @@ -42,6 +45,12 @@ type SnapshotCreateOptions struct { // CreateSnapshot executes the snapshot creation operation func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { + // config.Load accepts an empty list, since listing, verifying and + // restoring need no public key. + if len(v.Config.AgeRecipients) == 0 { + return errNoAgeRecipients + } + overallStartTime := time.Now() log.Info("Starting snapshot creation", From 315b6483b877d730996a7d63d42b43b8e4aaced5 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 16:59:26 +0200 Subject: [PATCH 014/121] Mark github.com/spf13/pflag as a direct dependency in go.mod (closes #246) internal/cli/snapshot_restore_test.go imports github.com/spf13/pflag directly, but go.mod still marked it // indirect. script/precommit runs go mod tidy and fails when that changes go.mod, so the pre-commit hook stopped every commit. This is the go mod tidy output: pflag moves to the direct require block, and go.sum does not change. script/cibuild does not run the tidy, which is why the gate stayed green. Model: opus-5-5 --- TODO.md | 8 ++++++++ go.mod | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index b7958a5..a0c35be 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,14 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made `go.mod` what `go mod tidy` writes, so the + pre-commit hook no longer stops every commit + ([issue #246](https://git.eeqj.de/sneak/vaultik/issues/246)). A test + in `internal/cli` imports `github.com/spf13/pflag` directly, but + `go.mod` still marked it `// indirect`, and `script/precommit` fails + whenever the tidy changes `go.mod`. It is now in the direct `require` + block. + - 2026-10-06: Made the README's steps for restoring on another machine work ([issue #221](https://git.eeqj.de/sneak/vaultik/issues/221)). `config init` wrote a placeholder recipient that `config.Load` diff --git a/go.mod b/go.mod index 23e63f2..e8d6235 100644 --- a/go.mod +++ b/go.mod @@ -20,6 +20,7 @@ require ( github.com/rclone/rclone v1.72.1 github.com/spf13/afero v1.15.0 github.com/spf13/cobra v1.10.1 + github.com/spf13/pflag v1.0.10 github.com/stretchr/testify v1.11.1 go.uber.org/fx v1.24.0 golang.org/x/sync v0.18.0 @@ -225,7 +226,6 @@ require ( github.com/smarty/assertions v1.16.0 // indirect github.com/sony/gobreaker v1.0.0 // indirect github.com/spacemonkeygo/monkit/v3 v3.0.25-0.20251022131615-eb24eb109368 // indirect - github.com/spf13/pflag v1.0.10 // indirect github.com/t3rm1n4l/go-mega v0.0.0-20251031123324-a804aaa87491 // indirect github.com/tidwall/gjson v1.18.0 // indirect github.com/tidwall/match v1.1.1 // indirect From 5aa5ba5544a4a02d56e403e3c0ee60a2d8503212 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 18:29:09 +0200 Subject: [PATCH 015/121] Apply restored owners, modes and times in an order that keeps them (closes #219) A directory got its stored mode and mtime before its contents were written, so a read-only directory came back without its files and a non-empty one carried the time of the restore. Directories are now created owner-only (0700) and get their stored owner, mode and mtime after the restore loop, each before its parent, skipping any whose place a symlink has since taken. A file's mode is now applied after its chown, which on Linux clears setuid and setgid. A symlink gets its stored owner (as root) and mtime on the link itself, through golang.org/x/sys/unix, now a direct dependency. An interrupted restore leaves its directories at 0700. Model: opus-5-5 --- TODO.md | 11 + go.mod | 2 +- internal/vaultik/restore.go | 102 ++++++- internal/vaultik/restore_metadata_test.go | 349 ++++++++++++++++++++++ 4 files changed, 447 insertions(+), 17 deletions(-) create mode 100644 internal/vaultik/restore_metadata_test.go diff --git a/TODO.md b/TODO.md index a0c35be..c129340 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,17 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made restore apply owners, modes and times in an order + that keeps them + ([issue #219](https://git.eeqj.de/sneak/vaultik/issues/219)). A + directory got its stored mode and mtime before its contents were + written, so a read-only directory came back without its files and a + non-empty one carried the time of the restore. Directories are now + created owner-only and get their stored owner, mode and mtime once the + restore loop is done, each before its parent. A file's mode is applied + after its chown, which on Linux clears setuid and setgid, and a + symlink gets its stored owner (as root) and mtime on the link itself. + - 2026-10-06: Made `go.mod` what `go mod tidy` writes, so the pre-commit hook no longer stops every commit ([issue #246](https://git.eeqj.de/sneak/vaultik/issues/246)). A test diff --git a/go.mod b/go.mod index e8d6235..d00f7f3 100644 --- a/go.mod +++ b/go.mod @@ -24,6 +24,7 @@ require ( github.com/stretchr/testify v1.11.1 go.uber.org/fx v1.24.0 golang.org/x/sync v0.18.0 + golang.org/x/sys v0.38.0 golang.org/x/term v0.37.0 gopkg.in/yaml.v3 v3.0.1 modernc.org/sqlite v1.38.0 @@ -263,7 +264,6 @@ require ( golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect golang.org/x/net v0.47.0 // indirect golang.org/x/oauth2 v0.33.0 // indirect - golang.org/x/sys v0.38.0 // indirect golang.org/x/text v0.31.0 // indirect golang.org/x/time v0.14.0 // indirect golang.org/x/tools v0.38.0 // indirect diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index f8372d6..a1ec97d 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -10,11 +10,13 @@ import ( "math" "os" "path/filepath" + "slices" "strings" "time" "filippo.io/age" "github.com/spf13/afero" + "golang.org/x/sys/unix" "sneak.berlin/go/vaultik/internal/blobgen" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" @@ -63,6 +65,12 @@ const snapshotDBFilename = "snapshot.db" // directories themselves get their stored mode). const restoreDirMode = 0o755 +// restoreDirCreateMode is the owner-only mode a directory from the +// snapshot is created with during restore, so its contents can be written +// whatever its stored mode. The stored mode is applied after the restore +// loop, by applyDirectoryMetadata. +const restoreDirCreateMode = 0o700 + // restoreFileMode is the restrictive mode a regular file is created with // during restore. Content is written while the file holds this mode; the // stored mode is applied only after the file is fully written and closed, @@ -332,6 +340,8 @@ func (v *Vaultik) restoreAllFiles( return nil, err } + session.applyDirectoryMetadata() + return result, nil } @@ -901,6 +911,9 @@ type restoreSession struct { // the call entirely as non-root and emit one warning at the end // of the restore explaining that ownership was not preserved. runningAsRoot bool + // directories holds every restored directory, for + // applyDirectoryMetadata to finish after the restore loop. + directories []*database.File } // containedRestorePath resolves rel — a path read from the snapshot @@ -1007,6 +1020,8 @@ func (s *restoreSession) restoreSymlink(file *database.File, targetPath string) if err != nil { return fmt.Errorf("creating symlink: %w", err) } + + s.applySymlinkMetadata(file, targetPath) } else { log.Debug("Symlink creation not supported on this filesystem", "path", file.Path, "target", file.LinkTarget) @@ -1019,35 +1034,90 @@ func (s *restoreSession) restoreSymlink(file *database.File, targetPath string) return nil } -// restoreDirectory restores a directory with its permissions, mtime, -// and (on real filesystems, with sufficient privileges) ownership. +// restoreDirectory creates a directory with restoreDirCreateMode. Its +// stored mode, owner and mtime are applied after the restore loop by +// applyDirectoryMetadata: a read-only stored mode would block writing +// its contents, and writing them changes its mtime. func (s *restoreSession) restoreDirectory( file *database.File, targetPath string, ) error { - err := s.v.Fs.MkdirAll(targetPath, os.FileMode(file.Mode)) + err := s.v.Fs.MkdirAll(targetPath, restoreDirCreateMode) if err != nil { return fmt.Errorf("creating directory: %w", err) } - // MkdirAll applies the process umask, so chmod to the exact stored - // mode. A failure here is non-fatal. - err = s.v.Fs.Chmod(targetPath, os.FileMode(file.Mode)) - if err != nil { - log.Debug("Failed to set permissions", "path", targetPath, "error", err) - } - - s.applyFileMetadata(file, targetPath) + s.directories = append(s.directories, file) s.result.FilesRestored++ return nil } +// applyDirectoryMetadata applies the stored owner, mtime and mode to every +// restored directory, each before its parent, so a parent whose stored +// mode denies search does not block its children. Failures are logged at +// debug level and do not abort the restore. +func (s *restoreSession) applyDirectoryMetadata() { + // A path sorts after its parent's, so reverse order puts every + // directory before its parent. + slices.SortFunc(s.directories, func(a, b *database.File) int { + return strings.Compare(b.Path.String(), a.Path.String()) + }) + + for _, dir := range s.directories { + targetPath, err := containedRestorePath( + s.v.Fs, s.opts.TargetDir, dir.Path.String()) + if err != nil { + log.Debug("Failed to set directory metadata", + "path", dir.Path, "error", err) + + continue + } + + // A later entry can have put a symlink in the directory's place, + // for example one stored as "/d/" next to the directory "/d". The + // calls below follow symlinks, so they would change its target. + info, err := lstatIfPossible(s.v.Fs, targetPath) + if err != nil || !info.IsDir() { + log.Debug("Not setting directory metadata: no longer a directory", + "path", targetPath, "error", err) + + continue + } + + s.applyFileMetadata(dir, targetPath) + + err = s.v.Fs.Chmod(targetPath, os.FileMode(dir.Mode)) + if err != nil { + log.Debug("Failed to set permissions", "path", targetPath, "error", err) + } + } +} + +// applySymlinkMetadata applies ownership (when running as root) and mtime +// to a restored symlink itself; os.Chown and Chtimes would follow it. +// Failures are logged at debug level and do not abort the restore. +func (s *restoreSession) applySymlinkMetadata(file *database.File, targetPath string) { + if s.runningAsRoot { + err := os.Lchown(targetPath, int(file.UID), int(file.GID)) + if err != nil { + log.Debug("Failed to set ownership", "path", targetPath, "error", err) + } + } + + mtime := unix.NsecToTimeval(file.MTime.UnixNano()) + + err := unix.Lutimes(targetPath, []unix.Timeval{mtime, mtime}) + if err != nil { + log.Debug("Failed to set mtime", "path", targetPath, "error", err) + } +} + // applyFileMetadata applies ownership (when running as root on a real -// filesystem) and mtime to a restored path. Permission mode is applied -// separately by each caller, with different failure handling, so it is -// not touched here. Failures are logged at debug level and do not abort -// the restore. +// filesystem) and mtime to a restored path. The caller applies the mode +// afterwards: on Linux a chown clears the setuid and setgid bits of a +// regular file. Failures are logged at debug level and do not abort the +// restore. func (s *restoreSession) applyFileMetadata(file *database.File, targetPath string) { if s.runningAsRoot { if _, ok := s.v.Fs.(*afero.OsFs); ok { @@ -1138,8 +1208,8 @@ func (s *restoreSession) restoreRegularFile( return fmt.Errorf("closing output file: %w", err) } - s.applyRestoredFileMode(file, targetPath) s.applyFileMetadata(file, targetPath) + s.applyRestoredFileMode(file, targetPath) s.result.FilesRestored++ s.result.BytesRestored += bytesWritten diff --git a/internal/vaultik/restore_metadata_test.go b/internal/vaultik/restore_metadata_test.go new file mode 100644 index 0000000..3264e52 --- /dev/null +++ b/internal/vaultik/restore_metadata_test.go @@ -0,0 +1,349 @@ +package vaultik //nolint:testpackage // drives unexported restore internals + +import ( + "context" + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/types" +) + +// These tests check that restore applies each entry's owner, mode and +// mtime in an order that keeps them. + +const ( + readOnlyDirMode = uint32(os.ModeDir | 0o555) + unsearchableMode = uint32(os.ModeDir | 0o600) + plainDirMode = uint32(os.ModeDir | 0o755) + plainFileMode = uint32(0o644) + setuidFileMode = uint32(os.ModeSetuid | 0o755) + otherOwnerID = uint32(4321) + writableTestMode = 0o755 + symlinkTargetPath = "/nonexistent/target" + memTargetDir = "/restore" + + // Owner bits a normal user needs on a directory to create an entry + // in it, and to change an entry in it. + ownerWriteAndSearch = os.FileMode(0o300) + ownerSearch = os.FileMode(0o100) +) + +// normalUserFs refuses what the kernel refuses a normal user. make test +// runs as root, which a read-only or unsearchable directory does not +// stop, so without it the tests below could not fail there. Creating an +// entry needs owner write and search on the directory holding it; +// changing an entry's mode or times needs owner search. Only that one +// directory is checked, not every ancestor. +type normalUserFs struct { + afero.Fs +} + +//nolint:ireturn // afero.Fs.OpenFile is defined to return the interface +func (fs normalUserFs) OpenFile( + name string, flag int, perm os.FileMode, +) (afero.File, error) { + if flag&os.O_CREATE != 0 { + err := fs.checkParent(name, ownerWriteAndSearch) + if err != nil { + return nil, err + } + } + + return fs.Fs.OpenFile(name, flag, perm) +} + +func (fs normalUserFs) MkdirAll(path string, perm os.FileMode) error { + _, err := fs.Stat(path) + if err != nil { + err = fs.checkParent(path, ownerWriteAndSearch) + if err != nil { + return err + } + } + + return fs.Fs.MkdirAll(path, perm) +} + +func (fs normalUserFs) Chmod(name string, mode os.FileMode) error { + err := fs.checkParent(name, ownerSearch) + if err != nil { + return err + } + + return fs.Fs.Chmod(name, mode) +} + +func (fs normalUserFs) Chtimes(name string, atime, mtime time.Time) error { + err := fs.checkParent(name, ownerSearch) + if err != nil { + return err + } + + return fs.Fs.Chtimes(name, atime, mtime) +} + +// checkParent returns a permission error when the directory holding name +// exists and its owner bits lack any of need. +func (fs normalUserFs) checkParent(name string, need os.FileMode) error { + info, err := fs.Stat(filepath.Dir(name)) + if err == nil && info.Mode().Perm()&need != need { + return &os.PathError{Op: "access", Path: name, Err: os.ErrPermission} + } + + return nil +} + +// TestRestoreFillsReadOnlyDirectory checks that a read-only directory +// still receives the entries inside it, and ends with its stored mode. +func TestRestoreFillsReadOnlyDirectory(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + + rows, repos := makeFiles(ctx, t, []*database.File{ + {Path: "/ro", Mode: readOnlyDirMode}, + {Path: "/ro/file", Mode: plainFileMode}, + {Path: "/ro/sub", Mode: readOnlyDirMode}, + {Path: "/ro/sub/file", Mode: plainFileMode}, + }) + + fs := afero.NewMemMapFs() + v := newContainmentVaultik(ctx, normalUserFs{Fs: fs}) + _, err := v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: memTargetDir}, nil, nil) + require.NoError(t, err) + + for _, path := range []string{"/ro/file", "/ro/sub/file"} { + _, err := fs.Stat(filepath.Join(memTargetDir, path)) + require.NoErrorf(t, err, "file inside a read-only directory: %s", path) + } + + for _, dir := range []string{"/ro", "/ro/sub"} { + info, err := fs.Stat(filepath.Join(memTargetDir, dir)) + require.NoError(t, err) + assert.Equalf(t, os.FileMode(0o555), info.Mode().Perm(), "mode of %s", dir) + } +} + +// TestRestoreKeepsNonEmptyDirectoryMTime checks that a directory keeps +// its stored mtime although entries were written into it. It runs on the +// real filesystem, where writing an entry changes its directory's mtime. +func TestRestoreKeepsNonEmptyDirectoryMTime(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + targetDir := t.TempDir() + mtime := time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC) + + rows, repos := makeFiles(ctx, t, []*database.File{ + {Path: "/dir", Mode: plainDirMode, MTime: mtime}, + {Path: "/dir/file", Mode: plainFileMode, MTime: mtime}, + }) + + v := newContainmentVaultik(ctx, afero.NewOsFs()) + _, err := v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: targetDir}, nil, nil) + require.NoError(t, err) + + info, err := os.Stat(filepath.Join(targetDir, "dir")) + require.NoError(t, err) + assert.Truef(t, info.ModTime().Equal(mtime), + "directory mtime is %s, stored %s", info.ModTime(), mtime) +} + +// TestRestoreFinishesChildBeforeUnsearchableParent checks that a +// directory inside one whose stored mode denies search still gets its +// own stored mode and mtime. +func TestRestoreFinishesChildBeforeUnsearchableParent(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + mtime := time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC) + + rows, repos := makeFiles(ctx, t, []*database.File{ + {Path: "/locked", Mode: unsearchableMode, MTime: mtime}, + {Path: "/locked/sub", Mode: plainDirMode, MTime: mtime}, + }) + + fs := afero.NewMemMapFs() + v := newContainmentVaultik(ctx, normalUserFs{Fs: fs}) + _, err := v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: memTargetDir}, nil, nil) + require.NoError(t, err) + + info, err := fs.Stat(filepath.Join(memTargetDir, "locked")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + + info, err = fs.Stat(filepath.Join(memTargetDir, "locked", "sub")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o755), info.Mode().Perm()) + assert.Truef(t, info.ModTime().Equal(mtime), + "mtime of sub is %s, stored %s", info.ModTime(), mtime) +} + +// TestRestoreLeavesSymlinkedDirectoryTargetAlone checks that a directory +// whose place a later entry takes with a symlink does not hand its stored +// owner, mode and mtime to whatever the symlink points at. "/d" and "/d/" +// are different stored paths for the same place on disk. +func TestRestoreLeavesSymlinkedDirectoryTargetAlone(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + tempDir := t.TempDir() + targetDir := filepath.Join(tempDir, "target") + outsideDir := filepath.Join(tempDir, "outside") + require.NoError(t, os.Mkdir(outsideDir, writableTestMode)) + + before, err := os.Stat(outsideDir) + require.NoError(t, err) + + mtime := time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC) + + rows, repos := makeFiles(ctx, t, []*database.File{ + { + Path: "/d", + Mode: readOnlyDirMode, + UID: otherOwnerID, + GID: otherOwnerID, + MTime: mtime, + }, + {Path: "/d/", LinkTarget: types.FilePath(outsideDir), MTime: mtime}, + }) + + v := newContainmentVaultik(ctx, afero.NewOsFs()) + _, err = v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: targetDir}, nil, nil) + require.NoError(t, err) + + after, err := os.Stat(outsideDir) + require.NoError(t, err) + assert.Equal(t, before.Mode(), after.Mode()) + assert.Truef(t, after.ModTime().Equal(before.ModTime()), + "mtime changed from %s to %s", before.ModTime(), after.ModTime()) + + beforeOwner, ok := before.Sys().(*syscall.Stat_t) + require.True(t, ok) + + afterOwner, ok := after.Sys().(*syscall.Stat_t) + require.True(t, ok) + assert.Equal(t, beforeOwner.Uid, afterOwner.Uid) + assert.Equal(t, beforeOwner.Gid, afterOwner.Gid) +} + +// TestRestoreKeepsSetuidThroughChown checks that a setuid file keeps the +// bit when restore changes its owner. Linux clears setuid on any chown of +// a regular file, even one to its current owner, so the file is recorded +// with the current user as owner and the session is told it runs as +// root: the chown then needs no privilege. +func TestRestoreKeepsSetuidThroughChown(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + targetDir := t.TempDir() + + info, err := os.Stat(targetDir) + require.NoError(t, err) + + owner, ok := info.Sys().(*syscall.Stat_t) + require.True(t, ok) + + rows, repos := makeFiles(ctx, t, []*database.File{{ + Path: "/suid", + Mode: setuidFileMode, + UID: owner.Uid, + GID: owner.Gid, + MTime: time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC), + }}) + + session := &restoreSession{ + v: newContainmentVaultik(ctx, afero.NewOsFs()), + ctx: ctx, + repos: repos, + opts: &RestoreOptions{TargetDir: targetDir}, + result: &RestoreResult{}, + runningAsRoot: true, + } + require.NoError(t, session.restoreFile(rows[0])) + + info, err = os.Stat(filepath.Join(targetDir, "suid")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(setuidFileMode), + info.Mode()&(os.ModeSetuid|os.ModePerm)) +} + +// TestRestoreSetsSymlinkMTime checks that a restored symlink gets its +// stored mtime on the link itself. The link dangles, so a call that +// follows it would fail. +func TestRestoreSetsSymlinkMTime(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + targetDir := t.TempDir() + mtime := time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC) + + rows, repos := makeFiles(ctx, t, []*database.File{{ + Path: "/link", + LinkTarget: types.FilePath(symlinkTargetPath), + MTime: mtime, + }}) + + v := newContainmentVaultik(ctx, afero.NewOsFs()) + _, err := v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: targetDir}, nil, nil) + require.NoError(t, err) + + info, err := os.Lstat(filepath.Join(targetDir, "link")) + require.NoError(t, err) + assert.Truef(t, info.ModTime().Equal(mtime), + "symlink mtime is %s, stored %s", info.ModTime(), mtime) +} + +// TestRestoreSetsSymlinkOwnerAsRoot checks that a symlink restored as +// root gets its stored owner on the link itself. +func TestRestoreSetsSymlinkOwnerAsRoot(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + if os.Geteuid() != 0 { + t.Skip("giving a file to another user needs root") + } + + ctx := context.Background() + targetDir := t.TempDir() + + rows, repos := makeFiles(ctx, t, []*database.File{{ + Path: "/link", + LinkTarget: types.FilePath(symlinkTargetPath), + UID: otherOwnerID, + GID: otherOwnerID, + MTime: time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC), + }}) + + v := newContainmentVaultik(ctx, afero.NewOsFs()) + _, err := v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: targetDir}, nil, nil) + require.NoError(t, err) + + info, err := os.Lstat(filepath.Join(targetDir, "link")) + require.NoError(t, err) + + owner, ok := info.Sys().(*syscall.Stat_t) + require.True(t, ok) + assert.Equal(t, otherOwnerID, owner.Uid) + assert.Equal(t, otherOwnerID, owner.Gid) +} From d276d891da1420fdc04055d54d8c0b1ab69b9ad1 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 19:46:09 +0200 Subject: [PATCH 016/121] Join the S3 prefix to every key with one slash (closes #222) The S3 client built each key as prefix + key, and the URL parser keeps the prefix as written, so s3://bucket/p stored p + "blobs/..." with no slash while s3://bucket/p/ stored p/blobs/.... A recovery host that wrote the URL the other way found no snapshots. NewClient now strips trailing slashes from the prefix and adds one back when anything is left, giving the README layout for both URL forms; an empty prefix stays at the bucket root. The s3.prefix config setting goes through the same client and gets the same join. A new test writes through each URL shape against an in-process S3 server, checks the key in the bucket, and lists through both List and ListStream, which every snapshot listing uses. Model: opus-5-5 --- TODO.md | 8 +++ internal/s3/client.go | 12 +++- internal/storage/s3_test.go | 109 ++++++++++++++++++++++++++++++++++++ 3 files changed, 128 insertions(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index c129340..c957a88 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,14 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made `s3://bucket/prefix` and `s3://bucket/prefix/` the same + destination ([issue #222](https://git.eeqj.de/sneak/vaultik/issues/222)). + The S3 client put the prefix directly in front of each key, so a prefix + without a trailing slash stored `prefixblobs/...`. A non-empty prefix is + now joined to every key with one `/`, giving the README's + `//blobs/...` layout. The `s3.prefix` config setting goes + through the same client and gets the same join. + - 2026-10-06: Made restore apply owners, modes and times in an order that keeps them ([issue #219](https://git.eeqj.de/sneak/vaultik/issues/219)). A diff --git a/internal/s3/client.go b/internal/s3/client.go index b54d3f4..43f8725 100644 --- a/internal/s3/client.go +++ b/internal/s3/client.go @@ -6,6 +6,7 @@ import ( "context" "errors" "io" + "strings" "sync/atomic" "github.com/aws/aws-sdk-go-v2/aws" @@ -30,6 +31,8 @@ type Client struct { // Config contains S3 client configuration. // All fields are required except Prefix, which defaults to an empty string. +// A non-empty Prefix is joined to every key with one "/", whether or not +// it ends with one. // The Endpoint field should include the protocol (http:// or https://). type Config struct { Endpoint string @@ -75,10 +78,17 @@ func NewClient(ctx context.Context, cfg Config) (*Client, error) { s3Client := s3.NewFromConfig(awsCfg, s3Opts) + // Every method below builds a key as prefix + key, so the prefix + // must carry its own trailing "/". + prefix := strings.TrimRight(cfg.Prefix, "/") + if prefix != "" { + prefix += "/" + } + return &Client{ s3Client: s3Client, bucket: cfg.Bucket, - prefix: cfg.Prefix, + prefix: prefix, endpoint: cfg.Endpoint, }, nil } diff --git a/internal/storage/s3_test.go b/internal/storage/s3_test.go index 966d5c6..2d581f7 100644 --- a/internal/storage/s3_test.go +++ b/internal/storage/s3_test.go @@ -4,11 +4,14 @@ import ( "context" "errors" "net/http/httptest" + "slices" + "strings" "testing" "github.com/johannesboyne/gofakes3" "github.com/johannesboyne/gofakes3/backend/s3mem" + "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/s3" "sneak.berlin/go/vaultik/internal/storage" ) @@ -79,3 +82,109 @@ func TestS3StorerMissingKeyMapsToErrNotFound(t *testing.T) { t.Errorf("Stat on missing key: got %v, want ErrNotFound", err) } } + +// TestS3URLPrefixKeyLayout pins the bucket keys an s3:// URL reads and +// writes: the README's remote storage layout, with the prefix joined to +// each key by one "/". s3://b/p and s3://b/p/ must be the same +// destination, or a host that writes the URL the other way finds no +// snapshots. The listed object is put straight into the bucket, as +// another host would have written it. Both List and ListStream are +// checked: ListStream is what every snapshot listing goes through. +func TestS3URLPrefixKeyLayout(t *testing.T) { + t.Parallel() + + const ( + blobKey = "blobs/aa/bb/aabbccdd" + listPrefix = "metadata/" + manifestKey = listPrefix + "snap/manifest.json.zst" + manifestBody = "manifest" + ) + + cases := []struct { + urlPath string // URL path after the bucket name + keyPrefix string // what every key in the bucket must start with + }{ + {urlPath: "/p", keyPrefix: "p/"}, + {urlPath: "/p/", keyPrefix: "p/"}, + {urlPath: "", keyPrefix: ""}, + } + + for _, tc := range cases { + storageURL := "s3://" + s3TestBucket + tc.urlPath + + t.Run(storageURL, func(t *testing.T) { + t.Parallel() + + backend := s3mem.New() + + err := backend.CreateBucket(s3TestBucket) + if err != nil { + t.Fatalf("create bucket: %v", err) + } + + srv := httptest.NewServer(gofakes3.New(backend).Server()) + t.Cleanup(srv.Close) + + storer, err := storage.NewStorer(&config.Config{ + StorageURL: storageURL + "?endpoint=" + srv.URL, + S3: config.S3Config{ + AccessKeyID: "key", + SecretAccessKey: "secret", + }, + }) + if err != nil { + t.Fatalf("NewStorer: %v", err) + } + + ctx := context.Background() + + err = storer.Put(ctx, blobKey, strings.NewReader("blob")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + _, err = backend.HeadObject(s3TestBucket, tc.keyPrefix+blobKey) + if err != nil { + t.Errorf("blob not stored at %q: %v", tc.keyPrefix+blobKey, err) + } + + _, err = backend.PutObject(s3TestBucket, tc.keyPrefix+manifestKey, + nil, strings.NewReader(manifestBody), int64(len(manifestBody))) + if err != nil { + t.Fatalf("seed manifest: %v", err) + } + + keys, err := storer.List(ctx, listPrefix) + if err != nil { + t.Fatalf("List: %v", err) + } + + if !slices.Equal(keys, []string{manifestKey}) { + t.Errorf("List(%q) = %q, want [%q]", listPrefix, keys, manifestKey) + } + + streamed := listStreamKeys(t, storer, listPrefix) + if !slices.Equal(streamed, []string{manifestKey}) { + t.Errorf("ListStream(%q) = %q, want [%q]", listPrefix, streamed, manifestKey) + } + }) + } +} + +// listStreamKeys returns the keys ListStream yields under a prefix, and +// fails the test on a listing error. +func listStreamKeys(t *testing.T, s storage.Storer, prefix string) []string { + t.Helper() + + var keys []string + + for obj := range s.ListStream(context.Background(), prefix) { + if obj.Err != nil { + t.Fatalf("ListStream %q: %v", prefix, obj.Err) + } + + keys = append(keys, obj.Key) + } + + return keys +} From f59086c0e5a410c1815ccbd4f3a00e379f43bd57 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 21:16:28 +0200 Subject: [PATCH 017/121] Return an error, not a panic, on a malformed snapshot database (closes #231) Restore cut chunk hashes from the snapshot database to 16 characters for its error messages, so a shorter hash panicked. Those messages now use shortHash. Under --verify, a file_chunks row with no chunks row was dereferenced, and the chunk size from the database was allocated in one piece, so a negative or huge size panicked. A missing row is now an error, a negative size is rejected, and each chunk is hashed by streaming it from the restored file. A restored file shorter than its chunks now fails verify as a short read instead of an unexpected EOF. Model: opus-5-5 --- TODO.md | 9 + internal/vaultik/restore.go | 42 ++-- internal/vaultik/restore_malformed_db_test.go | 221 ++++++++++++++++++ internal/vaultik/restore_plan.go | 2 +- 4 files changed, 258 insertions(+), 16 deletions(-) create mode 100644 internal/vaultik/restore_malformed_db_test.go diff --git a/TODO.md b/TODO.md index c957a88..62d1aee 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,15 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made restore return an error instead of panicking on a + malformed snapshot database + ([issue #231](https://git.eeqj.de/sneak/vaultik/issues/231)). A chunk + hash shorter than 16 characters crashed the error message naming it, + and `--verify` dereferenced a missing `chunks` row and allocated + whatever chunk size the database gave. Those messages now go through + `shortHash`, a missing row is an error, and `--verify` rejects a + negative size and hashes each chunk as a stream. + - 2026-10-06: Made `s3://bucket/prefix` and `s3://bucket/prefix/` the same destination ([issue #222](https://git.eeqj.de/sneak/vaultik/issues/222)). The S3 client put the prefix directly in front of each key, so a prefix diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index a1ec97d..03129a5 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -42,6 +42,7 @@ var ( errChunkNotInAnyBlob = errors.New("chunk not found in any blob") errBlobIDNotInHashIndex = errors.New("blob id missing from hash index") errShortChunkRead = errors.New("short read") + errChunkRowMissing = errors.New("chunk has no row in the chunks table") errRestorePathEscapesTarget = errors.New( "refusing to restore path outside the target directory") errTrailingRestoreData = errors.New( @@ -1267,7 +1268,7 @@ func (s *restoreSession) writeFileChunks( blobChunk, ok := s.chunkToBlobMap[chunkHashStr] if !ok { return bytesWritten, timings, fmt.Errorf( - "%w: %s", errChunkNotInAnyBlob, chunkHashStr[:16]) + "%w: %s", errChunkNotInAnyBlob, shortHash(chunkHashStr)) } blobHash, ok := s.blobIDToHash[blobChunk.BlobID.String()] @@ -1284,7 +1285,7 @@ func (s *restoreSession) writeFileChunks( if err != nil { return bytesWritten, timings, fmt.Errorf( "reading chunk %s from cached blob %s: %w", - fc.ChunkHash[:16], blobHash[:16], err) + shortHash(chunkHashStr), shortHash(blobHash), err) } t0 = time.Now() @@ -1482,33 +1483,44 @@ func (v *Vaultik) verifyFile( chunk, err := repos.Chunks.GetByHash(ctx, fc.ChunkHash.String()) if err != nil { return bytesVerified, fmt.Errorf("getting chunk %s: %w", - fc.ChunkHash.String()[:16], err) + shortHash(fc.ChunkHash.String()), err) } - // Read chunk data from file - chunkData := make([]byte, chunk.Size) - - n, err := io.ReadFull(f, chunkData) - if err != nil { - return bytesVerified, fmt.Errorf("reading chunk data: %w", err) + if chunk == nil { + return bytesVerified, fmt.Errorf("%w: %s", + errChunkRowMissing, shortHash(fc.ChunkHash.String())) } - if int64(n) != chunk.Size { + // chunk.Size comes from the snapshot database, which is not + // trusted: reject a negative size, and hash the chunk by + // streaming it rather than allocating that many bytes. + if chunk.Size < 0 { + return bytesVerified, fmt.Errorf("%w: chunk %d size %d", + errNegativeChunkLength, fc.Idx, chunk.Size) + } + + hasher := sha256.New() + + n, err := io.CopyN(hasher, f, chunk.Size) + if errors.Is(err, io.EOF) { return bytesVerified, fmt.Errorf("%w: expected %d bytes, got %d", errShortChunkRead, chunk.Size, n) } - // Calculate hash and compare - hash := sha256.Sum256(chunkData) - actualHash := hex.EncodeToString(hash[:]) + if err != nil { + return bytesVerified, fmt.Errorf("reading chunk data: %w", err) + } + + actualHash := hex.EncodeToString(hasher.Sum(nil)) expectedHash := fc.ChunkHash.String() if actualHash != expectedHash { return bytesVerified, fmt.Errorf("%w: chunk %d: expected %s, got %s", - errChunkHashMismatch, fc.Idx, expectedHash[:16], actualHash[:16]) + errChunkHashMismatch, fc.Idx, + shortHash(expectedHash), shortHash(actualHash)) } - bytesVerified += int64(n) + bytesVerified += n } // The stored chunks account for the whole file, so the reader must diff --git a/internal/vaultik/restore_malformed_db_test.go b/internal/vaultik/restore_malformed_db_test.go new file mode 100644 index 0000000..b6c884d --- /dev/null +++ b/internal/vaultik/restore_malformed_db_test.go @@ -0,0 +1,221 @@ +package vaultik //nolint:testpackage // drives unexported restore and verify steps + +import ( + "context" + "math" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/types" +) + +// These tests feed restore and --verify a snapshot database written by +// hand, as a damaged or hostile store could serve one. Each malformed row +// must end in an error, not a panic. + +// shortChunkHash is shorter than the hash prefix that error messages print. +const shortChunkHash = "abc" + +// restoredFileContent is the content of the restored file under verify. +const restoredFileContent = "xyz" + +// craftedSnapshotDB opens an empty snapshot database in a temp directory. +func craftedSnapshotDB(t *testing.T) (*database.DB, *database.Repositories) { + t.Helper() + + db, err := database.New(context.Background(), + filepath.Join(t.TempDir(), "snapshot.db")) + require.NoError(t, err) + + t.Cleanup(func() { _ = db.Close() }) + + return db, database.NewRepositories(db) +} + +// craftedFile adds a regular file whose only chunk has the given hash. +// Adding the chunks row, if any, is left to the caller. +func craftedFile( + t *testing.T, repos *database.Repositories, chunkHash string, +) *database.File { + t.Helper() + + ctx := context.Background() + file := &database.File{ + Path: "/src/f", + MTime: time.Now().UTC(), + Size: int64(len(restoredFileContent)), + Mode: 0o644, + } + require.NoError(t, repos.Files.Create(ctx, nil, file)) + require.NoError(t, repos.FileChunks.Create(ctx, nil, &database.FileChunk{ + FileID: file.ID, + ChunkHash: types.ChunkHash(chunkHash), + })) + + return file +} + +// TestRestoreShortChunkHashInNoBlob proves a file whose short chunk hash +// has no blob_chunks row fails restore planning and the chunk write with +// an error. +func TestRestoreShortChunkHashInNoBlob(t *testing.T) { + t.Parallel() + + ctx := context.Background() + _, repos := craftedSnapshotDB(t) + require.NoError(t, repos.Chunks.Create(ctx, nil, + &database.Chunk{ChunkHash: shortChunkHash, Size: 3})) + file := craftedFile(t, repos, shortChunkHash) + + v := NewForTesting(nil) + + chunkToBlobMap, err := v.buildChunkToBlobMap(ctx, repos) + require.NoError(t, err) + + _, err = newRestorePlan(ctx, repos, []*database.File{file}, + chunkToBlobMap, map[string]string{}) + require.ErrorIs(t, err, errPlanChunkMissing) + + fileChunks, err := repos.FileChunks.GetByFileID(ctx, file.ID) + require.NoError(t, err) + + out, err := afero.NewMemMapFs().Create("out") + require.NoError(t, err) + + session := &restoreSession{ + v: v.Vaultik, ctx: ctx, chunkToBlobMap: chunkToBlobMap, + } + + _, _, err = session.writeFileChunks(out, fileChunks) + require.ErrorIs(t, err, errChunkNotInAnyBlob) +} + +// TestRestoreShortChunkHashReadPastBlobEnd proves a short chunk hash +// whose blob_chunks row reads past the end of its blob fails the chunk +// write with an error. +func TestRestoreShortChunkHashReadPastBlobEnd(t *testing.T) { + t.Parallel() + + ctx := context.Background() + _, repos := craftedSnapshotDB(t) + + blobHash := strings.Repeat("b", blobHashHexLen) + blob := &database.Blob{ + ID: types.NewBlobID(), + Hash: types.BlobHash(blobHash), + CreatedTS: time.Now().UTC(), + } + require.NoError(t, repos.Blobs.Create(ctx, nil, blob)) + require.NoError(t, repos.Chunks.Create(ctx, nil, + &database.Chunk{ChunkHash: shortChunkHash, Size: 3})) + require.NoError(t, repos.BlobChunks.Create(ctx, nil, &database.BlobChunk{ + BlobID: blob.ID, + ChunkHash: shortChunkHash, + Length: 100, + })) + file := craftedFile(t, repos, shortChunkHash) + + cache, err := newBlobDiskCache(1 << 20) + require.NoError(t, err) + + t.Cleanup(func() { _ = cache.Close() }) + + require.NoError(t, cache.Put(blobHash, []byte("abc"))) + + v := NewForTesting(nil) + + chunkToBlobMap, err := v.buildChunkToBlobMap(ctx, repos) + require.NoError(t, err) + + _, blobIDToHash, err := v.buildBlobIndexes(repos) + require.NoError(t, err) + + fileChunks, err := repos.FileChunks.GetByFileID(ctx, file.ID) + require.NoError(t, err) + + out, err := afero.NewMemMapFs().Create("out") + require.NoError(t, err) + + session := &restoreSession{ + v: v.Vaultik, + ctx: ctx, + chunkToBlobMap: chunkToBlobMap, + blobIDToHash: blobIDToHash, + blobCache: cache, + } + + _, _, err = session.writeFileChunks(out, fileChunks) + require.ErrorIs(t, err, errCacheReadBeyondBlob) +} + +// TestVerifyFileMalformedChunkRow proves --verify returns an error for a +// chunk with no chunks row, a short chunk hash, and a chunk size from the +// database that is negative or larger than the restored file. +func TestVerifyFileMalformedChunkRow(t *testing.T) { + t.Parallel() + + fullHash := types.ChunkHash(strings.Repeat("c", blobHashHexLen)) + + tests := []struct { + name string + hash types.ChunkHash + chunk *database.Chunk // nil adds no chunks row + want error + }{ + { + name: "missing chunk row", + hash: fullHash, + want: errChunkRowMissing, + }, + { + name: "short hash", + hash: shortChunkHash, + chunk: &database.Chunk{ChunkHash: shortChunkHash, Size: 3}, + want: errChunkHashMismatch, + }, + { + name: "size larger than the file", + hash: fullHash, + chunk: &database.Chunk{ChunkHash: fullHash, Size: math.MaxInt64}, + want: errShortChunkRead, + }, + { + name: "negative size", + hash: fullHash, + chunk: &database.Chunk{ChunkHash: fullHash, Size: -1}, + want: errNegativeChunkLength, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + db, repos := craftedSnapshotDB(t) + + if tt.chunk == nil { + // A crafted database need not satisfy its foreign keys. + _, err := db.Conn().ExecContext(ctx, "PRAGMA foreign_keys = OFF") + require.NoError(t, err) + } else { + require.NoError(t, repos.Chunks.Create(ctx, nil, tt.chunk)) + } + + file := craftedFile(t, repos, tt.hash.String()) + + v := NewForTesting(nil) + v.Fs = afero.NewMemMapFs() + require.NoError(t, afero.WriteFile(v.Fs, "/restore/f", + []byte(restoredFileContent), 0o600)) + + _, err := v.verifyFile(ctx, repos, file, "/restore/f") + require.ErrorIs(t, err, tt.want) + }) + } +} diff --git a/internal/vaultik/restore_plan.go b/internal/vaultik/restore_plan.go index d9805fa..c018b79 100644 --- a/internal/vaultik/restore_plan.go +++ b/internal/vaultik/restore_plan.go @@ -75,7 +75,7 @@ func newRestorePlan( bc, ok := chunkToBlobMap[fc.ChunkHash.String()] if !ok { return nil, fmt.Errorf("planning %s: %w: %s", - f.Path, errPlanChunkMissing, fc.ChunkHash.String()[:16]) + f.Path, errPlanChunkMissing, shortHash(fc.ChunkHash.String())) } hash, ok := blobIDToHash[bc.BlobID.String()] From 5d685f03cee4d3d8c3bdca921db78841d3a37897 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 6 Oct 2026 22:12:16 +0200 Subject: [PATCH 018/121] List the files under a path by path, not by string prefix (closes #223) FileRepository.ListByPrefix matched with SQL LIKE: a plain string prefix that ignores ASCII case and treats _ and % as wildcards. Restoring /home/u/doc also restored doc2, DOC and doc.txt.bak, and a backup counted the files of a longer sibling path as deleted. It is now ListUnderPath, which returns the file at the path and every file whose path starts with the path plus a slash, compared exactly. A trailing slash is ignored, so "/" still lists every file. Three tests relied on string-prefix matching and now name a full path or call ListAll. ListIDsWithChunksNotInUploadedBlobs keeps its LIKE: it only adds file IDs the scan never looks up. Model: opus-5-5 --- TODO.md | 11 +++ internal/database/files.go | 17 ++-- internal/database/files_test.go | 78 +++++++++++++++++++ .../database/repository_comprehensive_test.go | 4 +- internal/database/repository_debug_test.go | 2 +- .../database/repository_edge_cases_test.go | 8 +- internal/snapshot/backup_test.go | 2 +- internal/snapshot/scanner.go | 10 ++- internal/snapshot/scanner_test.go | 2 +- internal/vaultik/integration_test.go | 2 +- internal/vaultik/restore.go | 5 +- 11 files changed, 118 insertions(+), 23 deletions(-) diff --git a/TODO.md b/TODO.md index 62d1aee..b5307d3 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,17 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made a restore path argument select only that path and + what is beneath it + ([issue #223](https://git.eeqj.de/sneak/vaultik/issues/223)). The + lookup matched with SQL `LIKE`, so `/home/u/doc` also restored + `doc2`, `DOC` and `doc.txt.bak`, and a `_` or `%` in the path acted + as a wildcard. A backup used the same lookup to load the known files + of each configured path, so files of a longer sibling path were + counted as deleted. `FileRepository.ListUnderPath`, which replaces + `ListByPrefix`, returns the file at the path and every file whose + path starts with the path plus `/`, compared case-sensitively. + - 2026-10-06: Made restore return an error instead of panicking on a malformed snapshot database ([issue #231](https://git.eeqj.de/sneak/vaultik/issues/231)). A chunk diff --git a/internal/database/files.go b/internal/database/files.go index c30c07e..02bd26c 100644 --- a/internal/database/files.go +++ b/internal/database/files.go @@ -228,19 +228,24 @@ func (r *FileRepository) DeleteByID( return nil } -// ListByPrefix returns all files whose path starts with prefix, ordered by -// path. -func (r *FileRepository) ListByPrefix( - ctx context.Context, prefix string, +// ListUnderPath returns the file at path and every file beneath it, +// ordered by path. Paths are compared case-sensitively, and a trailing +// slash on path is ignored, so "/" lists every file. +func (r *FileRepository) ListUnderPath( + ctx context.Context, path string, ) ([]*File, error) { + path = strings.TrimRight(path, "/") + dirPrefix := path + "/" + + // LIKE would ignore ASCII case and treat _ and % in path as wildcards. query := ` SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target FROM files - WHERE path LIKE ? || '%' + WHERE path = ? OR substr(path, 1, length(?)) = ? ORDER BY path ` - rows, err := r.db.conn.QueryContext(ctx, query, prefix) + rows, err := r.db.conn.QueryContext(ctx, query, path, dirPrefix, dirPrefix) if err != nil { return nil, fmt.Errorf("querying files: %w", err) } diff --git a/internal/database/files_test.go b/internal/database/files_test.go index 2d4823b..23f33b1 100644 --- a/internal/database/files_test.go +++ b/internal/database/files_test.go @@ -5,10 +5,12 @@ import ( "database/sql" "errors" "os" + "slices" "testing" "time" "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/types" ) // errTestRollback is the sentinel returned from transaction bodies to @@ -134,6 +136,82 @@ func TestFileRepositoryListDelete(t *testing.T) { } } +func TestFileRepositoryListUnderPath(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repo := database.NewFileRepository(db) + + const ( + docDir = "/home/u/doc" + docFile = "/home/u/doc/a.txt" + ) + + // In path order, so the root case can expect all of them as listed. + paths := []string{ + "/home/u/50%/x.txt", + "/home/u/50percent/y.txt", + "/home/u/DOC/c.txt", + "/home/u/a_b/x.txt", + "/home/u/axb/y.txt", + docDir, + "/home/u/doc.txt.bak", + docFile, + "/home/u/doc/sub/b.txt", + "/home/u/doc2/b.txt", + } + + for _, path := range paths { + err := repo.Create(ctx, nil, &database.File{ + Path: types.FilePath(path), + MTime: time.Now().Truncate(time.Second), + Mode: 0644, + }) + if err != nil { + t.Fatalf("failed to create %s: %v", path, err) + } + } + + docTree := []string{docDir, docFile, "/home/u/doc/sub/b.txt"} + + tests := []struct { + name string + path string + want []string + }{ + {"directory", docDir, docTree}, + {"directory with trailing slash", docDir + "/", docTree}, + {"directory differing only in case", "/home/u/DOC", + []string{"/home/u/DOC/c.txt"}}, + {"file", docFile, []string{docFile}}, + {"underscore is literal", "/home/u/a_b", + []string{"/home/u/a_b/x.txt"}}, + {"percent is literal", "/home/u/50%", + []string{"/home/u/50%/x.txt"}}, + {"root", "/", paths}, + } + + for _, tt := range tests { + files, err := repo.ListUnderPath(ctx, tt.path) + if err != nil { + t.Fatalf("%s: failed to list files: %v", tt.name, err) + } + + got := make([]string, 0, len(files)) + for _, f := range files { + got = append(got, f.Path.String()) + } + + if !slices.Equal(got, tt.want) { + t.Errorf("%s: listing %q got %q, want %q", + tt.name, tt.path, got, tt.want) + } + } +} + func TestFileRepositorySymlink(t *testing.T) { t.Parallel() diff --git a/internal/database/repository_comprehensive_test.go b/internal/database/repository_comprehensive_test.go index 4799458..53c5372 100644 --- a/internal/database/repository_comprehensive_test.go +++ b/internal/database/repository_comprehensive_test.go @@ -824,7 +824,7 @@ func TestTransactionIsolation(t *testing.T) { } // Verify the file was not created (transaction rolled back) - files, err := repos.Files.ListByPrefix(ctx, "/tx-test") + files, err := repos.Files.ListUnderPath(ctx, "/tx-test.txt") if err != nil { t.Fatal(err) } @@ -916,7 +916,7 @@ func TestConcurrentOrphanedCleanup(t *testing.T) { } // Verify correct files were deleted - files, err := repos.Files.ListByPrefix(ctx, "/concurrent-") + files, err := repos.Files.ListAll(ctx) if err != nil { t.Fatal(err) } diff --git a/internal/database/repository_debug_test.go b/internal/database/repository_debug_test.go index 4a4e2aa..9c9ec02 100644 --- a/internal/database/repository_debug_test.go +++ b/internal/database/repository_debug_test.go @@ -147,7 +147,7 @@ func TestOrphanedFileCleanupDebug(t *testing.T) { t.Logf("Files count after cleanup: %d", count) // List remaining files - files, err := repos.Files.ListByPrefix(ctx, "/") + files, err := repos.Files.ListUnderPath(ctx, "/") if err != nil { t.Fatal(err) } diff --git a/internal/database/repository_edge_cases_test.go b/internal/database/repository_edge_cases_test.go index 3e8cfb2..a4cf9f7 100644 --- a/internal/database/repository_edge_cases_test.go +++ b/internal/database/repository_edge_cases_test.go @@ -442,12 +442,12 @@ func TestLargeDatasets(t *testing.T) { createLargeDatasetFiles(t, repos, snapshot.ID.String(), fileCount) }) - // Test ListByPrefix performance + // Test ListUnderPath performance //nolint:paralleltest // phases share one database and are order-dependent - t.Run("list by prefix performance", func(t *testing.T) { + t.Run("list under path performance", func(t *testing.T) { start := time.Now() - files, err := repos.Files.ListByPrefix(ctx, "/large/") + files, err := repos.Files.ListUnderPath(ctx, "/large/") if err != nil { t.Fatal(err) } @@ -472,7 +472,7 @@ func TestLargeDatasets(t *testing.T) { t.Logf("Cleaned up orphaned files in %v", time.Since(start)) // Verify correct number remain - files, err := repos.Files.ListByPrefix(ctx, "/large/") + files, err := repos.Files.ListUnderPath(ctx, "/large/") if err != nil { t.Fatal(err) } diff --git a/internal/snapshot/backup_test.go b/internal/snapshot/backup_test.go index 80e0b38..f970cfb 100644 --- a/internal/snapshot/backup_test.go +++ b/internal/snapshot/backup_test.go @@ -71,7 +71,7 @@ func verifyBackupFiles( ) { t.Helper() - files, err := repos.Files.ListByPrefix(ctx, "") + files, err := repos.Files.ListAll(ctx) if err != nil { t.Fatalf("Failed to list files: %v", err) } diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index f7eb40e..7800891 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -456,14 +456,16 @@ func (s *Scanner) finalizeScanResult(ctx context.Context, result *ScanResult) { result.EndTime = time.Now().UTC() } -// loadKnownFiles loads all known files from the database into a map for fast lookup -// This avoids per-file database queries during the scan phase +// loadKnownFiles loads the known files at and beneath path from the +// database into a map for fast lookup. Every loaded file the scan does +// not find is counted as deleted. This avoids per-file database queries +// during the scan phase. func (s *Scanner) loadKnownFiles( ctx context.Context, path string, ) (map[string]*database.File, error) { - files, err := s.repos.Files.ListByPrefix(ctx, path) + files, err := s.repos.Files.ListUnderPath(ctx, path) if err != nil { - return nil, fmt.Errorf("listing files by prefix: %w", err) + return nil, fmt.Errorf("listing files under %s: %w", path, err) } result := make(map[string]*database.File, len(files)) diff --git a/internal/snapshot/scanner_test.go b/internal/snapshot/scanner_test.go index a28b58c..632d045 100644 --- a/internal/snapshot/scanner_test.go +++ b/internal/snapshot/scanner_test.go @@ -71,7 +71,7 @@ func verifySimpleScanDatabase( t.Helper() // Verify files in database - includes regular files and directories - files, err := repos.Files.ListByPrefix(ctx, "/source") + files, err := repos.Files.ListUnderPath(ctx, "/source") if err != nil { t.Fatalf("failed to list files: %v", err) } diff --git a/internal/vaultik/integration_test.go b/internal/vaultik/integration_test.go index bf74e60..5bb5483 100644 --- a/internal/vaultik/integration_test.go +++ b/internal/vaultik/integration_test.go @@ -249,7 +249,7 @@ func verifyEndToEndBackupState( assert.Positive(t, blobUploads, "Should upload at least one blob") // Verify files in database - files, err := repos.Files.ListByPrefix(ctx, "/home/user") + files, err := repos.Files.ListUnderPath(ctx, "/home/user") require.NoError(t, err) // Count only regular files (not directories) regularFiles := 0 diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index 03129a5..c5843e8 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -830,10 +830,9 @@ func (v *Vaultik) getFilesToRestore( // Normalize the filter path filter = filepath.Clean(filter) - // Get files with this prefix - files, err := repos.Files.ListByPrefix(ctx, filter) + files, err := repos.Files.ListUnderPath(ctx, filter) if err != nil { - return nil, fmt.Errorf("listing files with prefix %s: %w", filter, err) + return nil, fmt.Errorf("listing files under %s: %w", filter, err) } for _, file := range files { From b06f9921525a699d953b406740cfcc451c15aff0 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 00:12:10 +0200 Subject: [PATCH 019/121] Start the progress reporter once per snapshot, not once per path (closes #253) A backup without --cron of a snapshot with two or more paths panicked with "close of closed channel". Scan runs once per path, and it started the progress reporter and deferred its Stop each time; Stop closes the reporter's signal channel, so the second path's Stop panicked. scanAllDirectories now starts the reporter before the first path and stops it after the last, and Scan no longer starts or stops it. A new test backs up a two-path snapshot with the reporter on and restores both paths. Model: opus-5-5 --- TODO.md | 8 +++ internal/snapshot/scanner.go | 10 +-- internal/vaultik/snapshot.go | 5 ++ internal/vaultik/two_path_snapshot_test.go | 71 ++++++++++++++++++++++ 4 files changed, 87 insertions(+), 7 deletions(-) create mode 100644 internal/vaultik/two_path_snapshot_test.go diff --git a/TODO.md b/TODO.md index b5307d3..3ed2e9b 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,14 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made a backup without `--cron` of a snapshot with two or + more `paths` complete instead of panicking with `close of closed + channel` ([issue #253](https://git.eeqj.de/sneak/vaultik/issues/253)). + `Scan` runs once per path and started and stopped the progress + reporter each time, and a second stop panics. The reporter is now + started and stopped once per snapshot, around the scans of all its + paths. + - 2026-10-06: Made a restore path argument select only that path and what is beneath it ([issue #223](https://git.eeqj.de/sneak/vaultik/issues/223)). The diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 7800891..e74921a 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -224,12 +224,6 @@ func (s *Scanner) Scan( log.Debug("No storage configured, blobs will not be uploaded") } - // Start progress reporting if enabled - if s.progress != nil { - s.progress.Start() - defer s.progress.Stop() - } - // Phase 0: Repair any state left by an interrupted previous run, then // load known files and chunks from the database into memory for fast // lookup. @@ -300,7 +294,9 @@ func (s *Scanner) Scan( return result, nil } -// GetProgress returns the progress reporter for this scanner +// GetProgress returns the progress reporter for this scanner, or nil when +// progress is off. Scan neither starts nor stops it: the caller does, +// once for all the paths it scans, because a second Stop panics. func (s *Scanner) GetProgress() *ProgressReporter { return s.progress } diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index cb61ba5..a292607 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -281,6 +281,11 @@ func (v *Vaultik) resolveSnapshotPaths(snapName string) ([]string, error) { func (v *Vaultik) scanAllDirectories( scanner *snapshot.Scanner, resolvedDirs []string, snapshotID string, ) (*snapshotStats, error) { + if progress := scanner.GetProgress(); progress != nil { + progress.Start() + defer progress.Stop() + } + stats := &snapshotStats{} for i, dir := range resolvedDirs { diff --git a/internal/vaultik/two_path_snapshot_test.go b/internal/vaultik/two_path_snapshot_test.go new file mode 100644 index 0000000..f20ae4b --- /dev/null +++ b/internal/vaultik/two_path_snapshot_test.go @@ -0,0 +1,71 @@ +package vaultik_test + +import ( + "context" + "maps" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// A backup without --cron runs the progress reporter while one scanner +// scans each path of the snapshot in turn. See +// https://git.eeqj.de/sneak/vaultik/issues/253. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestBackupWithoutCronOfTwoPathSnapshotRestoresBothPaths(t *testing.T) { + log.Initialize(log.Config{}) + + const snapshotName = "data" + + fs := afero.NewOsFs() + tempDir := t.TempDir() + firstDir := filepath.Join(tempDir, "first") + secondDir := filepath.Join(tempDir, "second") + storeDir := filepath.Join(tempDir, "remote") + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, firstDir) + maps.Copy(files, writeFaultSourceTree(t, fs, secondDir)) + + cfg := faultTestConfig() + cfg.IndexPath = dbPath + cfg.ChunkSize = config.Size(faultChunkSize) + cfg.Snapshots = map[string]config.SnapshotConfig{ + snapshotName: {Paths: []string{firstDir, secondDir}}, + } + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Snapshots: []string{snapshotName}, + })) + + id := localSnapshotID(ctx, t, repos, snapshotName) + require.NoError(t, db.Close()) + + reader := newReaderVaultik(ctx, cfg, store, nil, fs) + require.NoError(t, reader.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Verify: true, + })) + + assertRestoredTree(t, fs, restoreDir, files) +} From 85d4ef118db470649bfbd7c808d81b52e1059aee Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 01:12:15 +0200 Subject: [PATCH 020/121] Keep command output to the README's stdout and stderr rules (closes #224) The startup banner moves from stdout to stderr, so a `completion` script, a `config get` value and the hidden `__complete` command print only their own output. `--quiet`, `--cron` and `--json` still suppress it. A failing `remote info`, `prune` or `snapshot remove` under `--json` now reports its error on stderr. Their reporters returned early under `--json`, so the failure reached neither stream. `snapshot verify --quiet` writes no report. A failure is still returned and printed on stderr, with the same exit status. Judgement call: the banner's stream, posted on the issue for the owner. Model: opus-5-5 --- README.md | 36 +++--- TODO.md | 9 ++ internal/cli/app.go | 31 ++--- internal/cli/entry.go | 19 +-- internal/cli/entry_banner_test.go | 59 +++------ internal/cli/entry_status_test.go | 6 +- internal/cli/entry_stdout_stderr_test.go | 152 +++++++++++++++++++++++ internal/cli/prune.go | 4 - internal/cli/remote.go | 6 +- internal/cli/snapshot.go | 6 +- internal/vaultik/snapshot.go | 28 +++-- internal/vaultik/verify.go | 27 ++-- internal/vaultik/verify_quiet_test.go | 102 +++++++++++++++ 13 files changed, 365 insertions(+), 120 deletions(-) create mode 100644 internal/cli/entry_stdout_stderr_test.go create mode 100644 internal/vaultik/verify_quiet_test.go diff --git a/README.md b/README.md index 425d569..70f5eb4 100644 --- a/README.md +++ b/README.md @@ -200,8 +200,10 @@ local index or the destination store. `config`, `database delete`, ### stdout and stderr Log output — everything from `--verbose` and `--debug`, and every -warning and error the logger emits — goes to **stderr**. stdout carries -the output you asked for: tables, and the documents produced by `--json`. +warning and error the logger emits — goes to **stderr**, and so does the +startup banner. stdout carries the output you asked for: tables, the +documents produced by `--json`, `config get` values, and completion +scripts. This means `vaultik snapshot list --verbose > out.txt` captures the listing and leaves the diagnostics on your terminal. To capture both, @@ -645,8 +647,8 @@ Work planned after 1.0. Loosely ordered by priority. ## output style Every command's user-facing output is governed by `internal/ui`, in one -of two ways. Color is enabled when stdout is a TTY and the `NO_COLOR` -environment variable is unset (https://no-color.org/). +of two ways. Color is enabled when the stream written to is a TTY and +the `NO_COLOR` environment variable is unset (https://no-color.org/). * **Status, progress, warnings, and errors** go through the `internal/ui` message methods below: marker-prefixed, colored on a TTY, and — except @@ -656,24 +658,26 @@ environment variable is unset (https://no-color.org/). `config init`, `config set`, and `database delete`. * **The data a command exists to produce** is written plain, with no marker and no color, because a marker would corrupt a table or a - parsed document. This covers the `version`, `info`, and `remote info` - reports, the `snapshot list` table, `config get` values, and every - `--json` document. `--quiet` silences the human reports and tables - (`version`, `info`, `remote info`, `snapshot list`) but never the - machine-consumed `config get` value or the `--json` documents, which a - script depends on. The `database delete` confirmation prompt is also - written this way and always shown: it is an interactive exchange the - operator must see. + parsed document. This covers the `version`, `info`, `remote info` and + `snapshot verify` reports, the `snapshot list` table, `config get` + values, and every `--json` document. `--quiet` silences the human + reports and tables (`version`, `info`, `remote info`, `snapshot + verify`, `snapshot list`) but never the machine-consumed `config get` + value or the `--json` documents, which a script depends on. The + `database delete` confirmation prompt is also written this way and + always shown: it is an interactive exchange the operator must see. -`internal/ui` writes to stdout; it is the output the user asked for. -Structured log records are a different thing and go through -`internal/log`, which writes to stderr (see "stdout and stderr" above). +`internal/ui` writes to stdout; it is the output the user asked for. The +exceptions are the startup banner and the error a failed command ends +with, which go to stderr. Structured log records are a different thing +and go through `internal/log`, which writes to stderr (see "stdout and +stderr" above). Message classes: | Class | Marker | Alignment | Use for | |-------|--------|-----------|---------| -| Banner | none | column 0 | The startup line printed once per invocation | +| Banner | none | column 0 | The startup line printed once per invocation, on stderr | | Begin | `》` (white) | column 0 | An operation is about to start (present-continuous verb) | | Complete | `》` (green) | column 0 | An operation just finished (past-tense verb) | | Info | `》` (white) | column 0 | Neutral status update | diff --git a/TODO.md b/TODO.md index 3ed2e9b..b2e6cb7 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,15 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made command output follow the README's stdout and stderr + rules ([issue #224](https://git.eeqj.de/sneak/vaultik/issues/224)). The + startup banner went to stdout, so a `completion` script or a + `config get` value started with it; the banner now goes to stderr. A + failing `remote info`, `prune` or `snapshot remove` under `--json` + printed nothing on either stream, and now reports its error on stderr. + `snapshot verify --quiet` printed its whole report; it now prints + none, and a failure still reaches stderr with the same exit status. + - 2026-10-06: Made a backup without `--cron` of a snapshot with two or more `paths` complete instead of panicking with `close of closed channel` ([issue #253](https://git.eeqj.de/sneak/vaultik/issues/253)). diff --git a/internal/cli/app.go b/internal/cli/app.go index dc305b3..76ba625 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -200,10 +200,10 @@ func RunApp(ctx context.Context, app *fx.App) error { } // errReported marks a failure the operation has already shown the user -// (and deliberately withheld under --json). Entry turns it into a -// non-zero exit status without printing anything further, so the error -// line is not doubled. It flows up from RunOperation through cobra to -// Entry. +// (or, under `snapshot verify --json`, put in its document). Entry +// turns it into a non-zero exit status without printing anything +// further, so the error line is not doubled. It flows up from +// RunOperation through cobra to Entry. var errReported = errors.New("operation failed") // RunOperation runs op against the Vaultik instance inside the fx app @@ -220,10 +220,10 @@ var errReported = errors.New("operation failed") // interrupt OnStop cancels op and waits for the goroutine to return, so // op's cleanup (removing decrypted scratch files) runs before the // process exits; the wait is bounded by shutdownTimeout. report is -// called with a non-canceled failure so the caller can log it (and -// suppress it under --json) before it becomes errReported. A context -// cancellation is the interrupt path, not a failure: it is neither -// reported nor counted as one. +// called with a non-canceled failure so the caller can show it to the +// user before it becomes errReported. A context cancellation is the +// interrupt path, not a failure: it is neither reported nor counted as +// one. func RunOperation( ctx context.Context, opts AppOptions, op func(v *vaultik.Vaultik) error, report func(err error), @@ -293,13 +293,12 @@ func RunOperation( // runVaultikApp runs the standard single-operation command lifecycle // shared by the snapshot list/purge/remove and remote nuke subcommands: // resolve the config, then run op against the Vaultik instance through -// RunOperation, reporting a failure prefixed with failMsg (suppressed -// while suppressErrors is true, e.g. under --json). mode says whether the -// command takes the PID lock. jsonOutput marks a command whose stdout is a -// JSON document: it quiets the UI but, unlike Quiet, leaves the stderr log -// level alone. +// RunOperation, reporting a failure prefixed with failMsg on stderr. mode +// says whether the command takes the PID lock. jsonOutput marks a command +// whose stdout is a JSON document: it quiets the UI but, unlike Quiet, +// leaves the stderr log level alone. func runVaultikApp( - cmd *cobra.Command, mode lockMode, jsonOutput, suppressErrors bool, + cmd *cobra.Command, mode lockMode, jsonOutput bool, failMsg string, op func(v *vaultik.Vaultik) error, ) error { configPath, err := ResolveConfigPath() @@ -319,10 +318,6 @@ func runVaultikApp( }, Mode: mode, }, op, func(err error) { - if suppressErrors { - return - } - log.Error(failMsg, "error", err) ReportErrorf("%s: %v", failMsg, err) }) diff --git a/internal/cli/entry.go b/internal/cli/entry.go index 917e6e7..5736c40 100644 --- a/internal/cli/entry.go +++ b/internal/cli/entry.go @@ -16,16 +16,18 @@ import ( const shortCommitLen = 12 // Entry is the main entry point for the CLI application. -// It prints the startup banner to stdout (unless a banner-suppressing +// It prints the startup banner to stderr (unless a banner-suppressing // flag is present in os.Args — see bannerSuppressedInArgs), executes the // root cobra command, and routes any returned error through the // ui.Writer so the user sees a properly formatted "🛑 ERROR:" line. +// The banner goes to stderr because stdout carries only the output the +// user asked for, such as a completion script or a `config get` value. // // It returns the process exit code (0 on success, 1 on error) rather // than calling os.Exit, so that main's deferred profile writers run // before the process ends. See run in cmd/vaultik/main.go. func Entry() int { - emitStartupBanner(os.Args[1:], os.Stdout) + emitStartupBanner(os.Args[1:], os.Stderr) rootCmd := NewRootCommand() rootCmd.SilenceErrors = true @@ -33,8 +35,9 @@ func Entry() int { err := rootCmd.Execute() if err != nil { // An operation that ran inside the fx app has already reported - // its own failure (and suppressed it under --json); errReported - // says so. Printing it again here would double the error line. + // its own failure (`snapshot verify --json` puts it in the + // document instead); errReported says so. Printing it again + // here would double the error line. // Every other error — bad arguments, a config that would not // load — reaches Entry unreported, so it is shown here. if !errors.Is(err, errReported) { @@ -49,9 +52,8 @@ func Entry() int { // emitStartupBanner writes the startup banner to w unless args (the // argument vector with the program name already stripped) contains a -// flag that suppresses it. Split out of Entry so that the decision — the -// only thing standing between a --json invocation and a parseable -// stdout — is reachable from a test without running the whole CLI. +// flag that suppresses it. Split out of Entry so that the decision is +// reachable from a test without running the whole CLI. func emitStartupBanner(args []string, w io.Writer) { if bannerSuppressedInArgs(args) { return @@ -86,8 +88,7 @@ func ReportErrorf(format string, args ...any) { // --json is a subcommand flag rather than a persistent one, but so is // --cron (it exists only on `snapshot create`), so this adds no new // class of imprecision. The only cost of a false positive is a missing -// decorative banner; the cost of a false negative is a corrupt document -// on stdout, so the scan errs deliberately in that direction. +// decorative banner. func bannerSuppressedInArgs(args []string) bool { for _, a := range args { if a == "--" { diff --git a/internal/cli/entry_banner_test.go b/internal/cli/entry_banner_test.go index df7321b..26015d5 100644 --- a/internal/cli/entry_banner_test.go +++ b/internal/cli/entry_banner_test.go @@ -36,23 +36,14 @@ const ( // strips it before scanning, so it has to be present. programName = "vaultik" - // someSnapshotID is any snapshot identifier: these tests never run - // the command, so it only has to occupy the positional argument. + // someSnapshotID only fills the positional argument; no test needs + // the snapshot to exist. someSnapshotID = "host_2026-01-01T00:00:00Z" ) -// placeholderJSONDocument stands in for whatever document a --json -// command writes to stdout. `snapshot list --json` with no snapshots -// prints exactly this; the other --json commands print an object rather -// than an array, but this test is not about their shape. It is about -// what is on stdout *before* them, which is the same for all of them -// because Entry prints the banner before cobra has parsed anything and -// therefore before it can know which command is running. -const placeholderJSONDocument = "[]\n" - // jsonArgumentVectors are the argument vectors of every --json // invocation the CLI accepts, with the program name stripped exactly as -// Entry strips it. Each one must leave stdout untouched by the banner. +// Entry strips it. Each one must suppress the banner. // //nolint:gochecknoglobals // read-only test fixture shared by two tests var jsonArgumentVectors = map[string][]string{ @@ -74,39 +65,23 @@ var jsonArgumentVectors = map[string][]string{ }, } -// TestJSONInvocationStdoutIsExactlyOneDocument is the CLI-layer -// regression guard for issue #106: `vaultik snapshot list --json | jq` -// must work with no other flags. -// -// internal/vaultik's TestListSnapshots_JSONStdoutIsOnlyTheDocument -// guards the same contract one layer down, but it calls the library -// function directly and so cannot see Entry, which is where the -// contamination was: the startup banner is written to stdout before -// cobra parses anything, and the suppression scan did not know about -// --json. The two banner lines and the blank line landed ahead of the -// document and `jq` refused the result. -// -// The document is a constant here because this test is about the -// argument vectors, one per --json command; the one that runs a real -// command end to end is TestEntryJSONStdoutIsExactlyOneDocument below. -func TestJSONInvocationStdoutIsExactlyOneDocument(t *testing.T) { +// TestJSONInvocationSuppressesBanner checks that every --json +// invocation suppresses the startup banner, as the README says --json +// does along with --quiet and --cron. The scan is over the raw argument +// vector, so each position and spelling of --json is listed. +func TestJSONInvocationSuppressesBanner(t *testing.T) { t.Parallel() for name, argv := range jsonArgumentVectors { t.Run(name, func(t *testing.T) { t.Parallel() - var stdout bytes.Buffer + var banner bytes.Buffer - emitStartupBanner(argv, &stdout) + emitStartupBanner(argv, &banner) - require.Empty(t, stdout.String(), - "nothing may reach stdout ahead of a --json document") - - _, err := stdout.WriteString(placeholderJSONDocument) - require.NoError(t, err) - - requireExactlyOneJSONDocument(t, stdout.String()) + assert.Empty(t, banner.String(), + "--json suppresses the banner") }) } } @@ -127,11 +102,11 @@ func TestBannerStillPrintedWithoutSuppressingFlag(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - var stdout bytes.Buffer + var banner bytes.Buffer - emitStartupBanner(argv, &stdout) + emitStartupBanner(argv, &banner) - assert.Contains(t, stdout.String(), "starting up at", + assert.Contains(t, banner.String(), "starting up at", "the banner belongs on invocations that did not opt out") }) } @@ -247,9 +222,7 @@ func TestEntryJSONStdoutIsExactlyOneDocument(t *testing.T) { // captureProcessStdout redirects the process's own stdout to a pipe for // the duration of fn and returns what was written to it. The redirection // has to be at the file-descriptor level rather than through an injected -// writer, because the banner and the JSON encoder reach os.Stdout -// independently and the point of the test is that both land in the same -// place. +// writer, because the commands Entry runs reach os.Stdout directly. // // Not parallel-safe: os.Stdout is process-global. func captureProcessStdout(t *testing.T, fn func()) string { diff --git a/internal/cli/entry_status_test.go b/internal/cli/entry_status_test.go index 9042bce..2bd7bd6 100644 --- a/internal/cli/entry_status_test.go +++ b/internal/cli/entry_status_test.go @@ -15,8 +15,8 @@ import ( // run, so a failing command must come back with a non-zero code rather // than ending the process here. // -// Stdout is captured only to keep the banner and command output off the -// test log; the assertion is on the returned code. +// Stdout and stderr are captured only to keep the banner and command +// output off the test log; the assertion is on the returned code. // //nolint:paralleltest // replaces os.Args and rootFlags func TestEntryReturnsStatusCode(t *testing.T) { @@ -50,7 +50,7 @@ func TestEntryReturnsStatusCode(t *testing.T) { var code int - _ = captureProcessStdout(t, func() { code = Entry() }) + _, _ = captureProcessStdoutAndStderr(t, func() { code = Entry() }) assert.Equal(t, testCase.want, code) }) diff --git a/internal/cli/entry_stdout_stderr_test.go b/internal/cli/entry_stdout_stderr_test.go new file mode 100644 index 0000000..43a6e42 --- /dev/null +++ b/internal/cli/entry_stdout_stderr_test.go @@ -0,0 +1,152 @@ +package cli //nolint:testpackage // shares hermeticConfig and the capture helpers + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/adrg/xdg" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" +) + +// TestEntryCompletionStdoutIsTheScript runs `vaultik completion bash`, +// whose stdout the README tells the user to source. The script has to +// start on the first line. +// +//nolint:paralleltest // replaces os.Args, os.Stdout and os.Stderr +func TestEntryCompletionStdoutIsTheScript(t *testing.T) { + code, stdout, _ := runEntry(t, "completion", "bash") + + require.Equal(t, 0, code) + + firstLine, _, _ := strings.Cut(stdout, "\n") + assert.True(t, strings.HasPrefix(firstLine, "# bash completion"), + "the first line of stdout must be the script's, got %q", firstLine) +} + +// TestEntryConfigGetStdoutIsTheValue runs `vaultik config get`, whose +// stdout a script reads as the value and nothing else. +// +//nolint:paralleltest // replaces os.Args, os.Stdout and os.Stderr +func TestEntryConfigGetStdoutIsTheValue(t *testing.T) { + configPath := filepath.Join(t.TempDir(), "config.yml") + require.NoError(t, os.WriteFile(configPath, + []byte("hostname: test-host\n"), configFileMode)) + + code, stdout, _ := runEntry(t, + flagConfig, configPath, "config", "get", "hostname") + + require.Equal(t, 0, code) + assert.Equal(t, "test-host\n", stdout) +} + +// TestEntryJSONFailureIsReportedOnStderr runs each --json command that +// writes no document when it fails, against a destination it cannot +// use. The error must reach stderr, and stdout must stay empty. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntryJSONFailureIsReportedOnStderr(t *testing.T) { + for _, testCase := range []struct { + name string + args []string + wantOnStderr string + }{ + { + name: "remote info", + args: []string{cmdRemote, cmdInfo, flagJSON}, + wantOnStderr: "Failed to get remote info", + }, + { + name: "prune", + args: []string{cmdPrune, flagJSON}, + wantOnStderr: "Prune failed", + }, + { + name: "snapshot remove", + args: []string{cmdSnapshot, cmdRemove, someSnapshotID, flagJSON}, + wantOnStderr: "Failed to remove snapshot", + }, + } { + t.Run(testCase.name, func(t *testing.T) { + configPath := writeUnusableDestinationConfig(t) + + code, stdout, stderr := runEntry(t, + append([]string{flagConfig, configPath}, testCase.args...)...) + + assert.Equal(t, 1, code) + assert.Empty(t, stdout, + "a failed --json command has no document to write") + assert.Contains(t, stderr, testCase.wantOnStderr, + "the failure must be reported on stderr") + }) + } +} + +// writeUnusableDestinationConfig builds a config whose destination +// directory does not exist, which fails `remote info`, and whose local +// index is bound to another destination, which fails `prune` and +// `snapshot remove` (a missing destination alone only makes `snapshot +// remove` warn). Returns the config path. +func writeUnusableDestinationConfig(t *testing.T) string { + t.Helper() + + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yml") + indexPath := filepath.Join(dir, "index.sqlite") + + contents := fmt.Sprintf(hermeticConfig, + filepath.Join(dir, "source"), + filepath.Join(dir, "missing-store"), + indexPath) + + require.NoError(t, + os.WriteFile(configPath, []byte(contents), configFileMode)) + + // The PID lock lives under xdg.DataHome, which xdg resolves at + // package init; point it at the temp dir so the test neither + // touches nor collides with the real one. + t.Setenv("XDG_DATA_HOME", filepath.Join(dir, "data")) + xdg.Reload() + t.Cleanup(xdg.Reload) + + ctx := context.Background() + + db, err := database.New(ctx, indexPath) + require.NoError(t, err) + + defer func() { require.NoError(t, db.Close()) }() + + require.NoError(t, database.NewRepositories(db).LocalMeta.Set(ctx, + database.LocalMetaKeyStorageURL, "file://"+filepath.Join(dir, "other"))) + + return configPath +} + +// runEntry runs Entry with args after the program name and returns its +// exit code and what it wrote to stdout and stderr. +// +// Not parallel-safe: it replaces os.Args, os.Stdout and os.Stderr. +func runEntry(t *testing.T, args ...string) (int, string, string) { + t.Helper() + + previousArgs := os.Args + + t.Cleanup(func() { + os.Args = previousArgs + rootFlags = RootFlags{} + }) + + os.Args = append([]string{programName}, args...) + + var code int + + stdout, stderr := captureProcessStdoutAndStderr(t, + func() { code = Entry() }) + + return code, stdout, stderr +} diff --git a/internal/cli/prune.go b/internal/cli/prune.go index b3b6040..ef3cef6 100644 --- a/internal/cli/prune.go +++ b/internal/cli/prune.go @@ -48,10 +48,6 @@ work (e.g. after a crashed backup or to reclaim storage).`, }, func(v *vaultik.Vaultik) error { return v.Prune(opts) }, func(err error) { - if opts.JSON { - return - } - log.Error("Prune operation failed", "error", err) ReportErrorf("Prune failed: %v", err) }) diff --git a/internal/cli/remote.go b/internal/cli/remote.go index e561298..dd72e9f 100644 --- a/internal/cli/remote.go +++ b/internal/cli/remote.go @@ -45,7 +45,7 @@ This is destructive and irreversible. Requires --force.`, return errNukeNeedsForce } - return runVaultikApp(cmd, mutating, false, false, "Remote nuke failed", + return runVaultikApp(cmd, mutating, false, "Remote nuke failed", func(v *vaultik.Vaultik) error { return v.NukeRemote(true) }) @@ -92,10 +92,6 @@ func newRemoteInfoCommand() *cobra.Command { }, func(v *vaultik.Vaultik) error { return v.RemoteInfo(jsonOutput) }, func(err error) { - if jsonOutput { - return - } - log.Error("Failed to get remote info", "error", err) ReportErrorf("Failed to get remote info: %v", err) }) diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index cee6594..4a0e095 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -126,7 +126,7 @@ func newSnapshotListCommand() *cobra.Command { Long: "Lists all snapshots with their ID, timestamp, and compressed size", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - return runVaultikApp(cmd, readOnly, false, false, + return runVaultikApp(cmd, readOnly, false, "Failed to list snapshots", func(v *vaultik.Vaultik) error { return v.ListSnapshots(jsonOutput) @@ -162,7 +162,7 @@ restrict the operation to specific snapshot names.`, return errPurgeCriteriaBoth } - return runVaultikApp(cmd, mutating, false, false, + return runVaultikApp(cmd, mutating, false, "Failed to purge snapshots", func(v *vaultik.Vaultik) error { return v.PurgeSnapshotsWithOptions(opts) @@ -265,7 +265,7 @@ To wipe the entire destination store and start over, use 'vaultik remote nuke --force' — it is the single supported entry point for that.`, Args: requireSnapshotIDArg, RunE: func(cmd *cobra.Command, args []string) error { - return runVaultikApp(cmd, mutating, opts.JSON, opts.JSON, + return runVaultikApp(cmd, mutating, opts.JSON, "Failed to remove snapshot", func(v *vaultik.Vaultik) error { _, err := v.RemoveSnapshot(args[0], opts) diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index a292607..7c948f7 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -732,7 +732,7 @@ func (v *Vaultik) VerifySnapshotWithOptions( result.BlobCount = manifest.BlobCount result.TotalSize = manifest.TotalCompressedSize - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Snapshot information:\n") v.stdoutf(" Blob count: %d\n", manifest.BlobCount) v.stdoutf(" Total size: %s\n", ubytes(manifest.TotalCompressedSize)) @@ -787,7 +787,7 @@ func (v *Vaultik) printVerifyHeader(snapshotID string, opts *VerifyOptions) { snapshotTime = t } - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Verifying snapshot %s\n", snapshotID) if !snapshotTime.IsZero() { @@ -827,7 +827,7 @@ func (v *Vaultik) verifyManifestBlobs( stat, err := v.Storage.Stat(v.ctx, blobPath) switch { case err != nil: - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf(" Missing: %s (%s)\n", blob.Hash, ubytes(blob.CompressedSize)) } @@ -835,7 +835,7 @@ func (v *Vaultik) verifyManifestBlobs( missing++ missingSize += blob.CompressedSize case stat.Size != blob.CompressedSize: - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf(" Wrong size: %s (store has %s, manifest lists %s)\n", blob.Hash, ubytes(stat.Size), ubytes(blob.CompressedSize)) } @@ -867,6 +867,22 @@ func (v *Vaultik) formatVerifyResult( return v.outputVerifyJSON(result) } + // Under --quiet a failure is still returned, and the cli layer + // prints it on stderr. + if !v.UI.Quiet() { + v.printVerifySummary(result, failure) + } + + if failure != "" { + return fmt.Errorf("%w: %s", errSnapshotVerifyFailed, failure) + } + + return nil +} + +// printVerifySummary prints the counts and the status line that end the +// human-readable shallow verify report. failure is empty when it passed. +func (v *Vaultik) printVerifySummary(result *VerifyResult, failure string) { v.stdoutf("\nVerification complete:\n") v.stdoutf(" Present with listed size: %d blobs\n", result.Verified) @@ -888,14 +904,12 @@ func (v *Vaultik) formatVerifyResult( if failure != "" { v.stdoutf("FAILED - %s\n", failure) - return fmt.Errorf("%w: %s", errSnapshotVerifyFailed, failure) + return } // Report only what was actually checked: presence and size, not contents. v.stdoutf("OK - all %d blobs listed in the manifest are present with the "+ "listed size; contents not checked (use --deep)\n", result.Verified) - - return nil } // shallowVerifyFailure returns a human-readable description of everything diff --git a/internal/vaultik/verify.go b/internal/vaultik/verify.go index cf43c62..070c47b 100644 --- a/internal/vaultik/verify.go +++ b/internal/vaultik/verify.go @@ -103,7 +103,7 @@ func (v *Vaultik) RunDeepVerify(snapshotID string, opts *VerifyOptions) error { log.Info("Starting snapshot verification", "snapshot_id", snapshotID, "mode", "deep") - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Deep verification of snapshot: %s\n\n", snapshotID) } @@ -143,10 +143,13 @@ func (v *Vaultik) RunDeepVerify(snapshotID string, opts *VerifyOptions) error { log.Info("✓ Verification completed successfully", "snapshot_id", snapshotID, "mode", "deep", "blobs_verified", len(dbBlobs)) - v.stdoutf("\n✓ Verification completed successfully\n") - v.stdoutf(" Snapshot: %s\n", snapshotID) - v.stdoutf(" Blobs verified: %d\n", len(dbBlobs)) - v.stdoutf(" Total size: %s\n", ubytes(totalSize)) + + if !v.UI.Quiet() { + v.stdoutf("\n✓ Verification completed successfully\n") + v.stdoutf(" Snapshot: %s\n", snapshotID) + v.stdoutf(" Blobs verified: %d\n", len(dbBlobs)) + v.stdoutf(" Total size: %s\n", ubytes(totalSize)) + } return nil } @@ -170,7 +173,7 @@ func (v *Vaultik) loadVerificationData( // remote manifests; see its doc comment. log.Info("Downloading manifest", "remote_key", remoteKey) - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Downloading manifest...\n") } @@ -185,7 +188,7 @@ func (v *Vaultik) loadVerificationData( "manifest_blob_count", manifest.BlobCount, "manifest_total_size", ubytes(manifest.TotalCompressedSize)) - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Manifest loaded: %d blobs (%s)\n", manifest.BlobCount, ubytes(manifest.TotalCompressedSize)) v.stdoutf("Downloading and decrypting database...\n") @@ -215,7 +218,7 @@ func (v *Vaultik) loadVerificationData( "db_blob_count", len(dbBlobs), "db_total_size", ubytes(dbTotalSize)) - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Database loaded: %d blobs (%s)\n", len(dbBlobs), ubytes(dbTotalSize)) } @@ -273,7 +276,7 @@ func (v *Vaultik) runVerificationSteps( totalSize int64, identities []age.Identity, ) error { - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Verifying manifest against database...\n") } @@ -282,7 +285,7 @@ func (v *Vaultik) runVerificationSteps( return v.deepVerifyFailure(result, opts, err.Error(), err) } - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Manifest verified.\n") v.stdoutf("Checking blob existence in remote storage...\n") } @@ -292,7 +295,7 @@ func (v *Vaultik) runVerificationSteps( return v.deepVerifyFailure(result, opts, err.Error(), err) } - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("All blobs exist.\n") v.stdoutf("Downloading and verifying blob contents (%d blobs, %s)...\n", len(dbBlobs), ubytes(totalSize)) @@ -748,7 +751,7 @@ func (v *Vaultik) performDeepVerificationFromDB( "eta", eta.Round(time.Second), ) - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf(" Verified %d/%d blobs (%d remaining) - %s/%s - elapsed %s, eta %s\n", i+1, len(blobs), remaining, ubytes(bytesProcessed), diff --git a/internal/vaultik/verify_quiet_test.go b/internal/vaultik/verify_quiet_test.go new file mode 100644 index 0000000..b4350db --- /dev/null +++ b/internal/vaultik/verify_quiet_test.go @@ -0,0 +1,102 @@ +package vaultik_test + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestVerify_QuietSuppressesReport is the --quiet contract for +// `snapshot verify`: neither shallow nor deep verify writes its report, +// a failed verify still returns its error (which the cli layer prints +// on stderr), and the --json document still emits. +func TestVerify_QuietSuppressesReport(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + storeDir := filepath.Join(tempDir, "remote") + dbPath := filepath.Join(tempDir, "index.sqlite") + + chunkSize := int64(32 * 1024) + maxBlobSize := int64(128 * 1024) + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, "data.bin"), + bytesPattern("quiet-", int(maxBlobSize*2)), 0o644)) + + ctx := context.Background() + + cfg, storer, snapshotID := runFileStorageBackup( + ctx, t, fs, dataDir, storeDir, dbPath, chunkSize, maxBlobSize) + + // The UI writes to the same buffer as Stdout, as both write to the + // process's stdout in production. + var stdout bytes.Buffer + + newQuietVerifier := func() *vaultik.Vaultik { + v := &vaultik.Vaultik{ + Config: cfg, + Storage: storer, + Fs: fs, + Stdout: &stdout, + Stderr: io.Discard, + UI: ui.NewWithColor(&stdout, false), + } + v.SetContext(ctx) + v.UI.SetQuiet(true) + + return v + } + + require.NoError(t, newQuietVerifier().VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{})) + require.Empty(t, stdout.String(), + "shallow verify must write no report under --quiet") + + require.NoError(t, newQuietVerifier().VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{Deep: true})) + require.Empty(t, stdout.String(), + "deep verify must write no report under --quiet") + + require.NoError(t, newQuietVerifier().VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{JSON: true})) + require.Equal(t, "ok", decodeVerifyResult(t, stdout.Bytes()).Status, + "the --json document must still emit under --quiet") + + // A snapshot without its encrypted database fails shallow verify. A + // failed report also lists each missing blob and each blob of the + // wrong size, so remove one blob and grow another. + require.NoError(t, os.Remove(filepath.Join(storeDir, "metadata", + snapshot.RemoteSnapshotKey(snapshotID), "db.zst.age"))) + + blobFiles, err := filepath.Glob( + filepath.Join(storeDir, "blobs", "*", "*", "*")) + require.NoError(t, err) + require.GreaterOrEqual(t, len(blobFiles), 2, + "the snapshot must span two blobs, one to remove and one to grow") + require.NoError(t, os.Remove(blobFiles[0])) + growOneBlob(t, fs, filepath.Join(storeDir, "blobs")) + + stdout.Reset() + + require.Error(t, newQuietVerifier().VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{}), + "--quiet must not change the outcome of a failed verify") + require.Empty(t, stdout.String(), + "a failed verify must write no report under --quiet") +} From 49eed7a3e5e4d04acf65f7d42298ec803b7edbe3 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 02:59:27 +0200 Subject: [PATCH 021/121] Count each file, byte and upload once in backup statistics (closes #225) The scanner added a changed file's bytes again for each new chunk and counted a file as unchanged for each chunk already stored. It now counts files and bytes once, in the scan phase, and counts its own uploads, so a --cron run, which has no progress reporter, records them. The blob count no longer adds earlier paths' blobs again. The snapshots row now stores the size of all files in total_size and the referenced blobs' sizes in blob_size, blob_uncompressed_size and compression_ratio, as docs/DATAMODEL.md says. Those sizes come from one query, and a failed query fails the snapshot. DATAMODEL.md now says chunk_count and blob_count count what the run added. Removed UpdateSnapshotStats and GetCountBySnapshot, which nothing calls any more. Model: opus-5-5 --- ARCHITECTURE.md | 4 +- TODO.md | 13 + docs/DATAMODEL.md | 6 +- internal/database/models.go | 4 +- internal/database/snapshots.go | 31 ++- internal/database/snapshots_test.go | 59 +++++ internal/database/uploads.go | 16 -- internal/snapshot/progress.go | 4 - internal/snapshot/scanner.go | 110 ++++----- internal/snapshot/snapshot.go | 28 +-- internal/vaultik/snapshot.go | 83 +++---- internal/vaultik/snapshot_summary_test.go | 285 ++++++++++++++++++++++ 12 files changed, 471 insertions(+), 172 deletions(-) create mode 100644 internal/vaultik/snapshot_summary_test.go diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 309186f..0541199 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -335,10 +335,10 @@ CreateSnapshot(opts) │ │ │ └─► Accumulate statistics │ - ├─► SnapshotManager.UpdateSnapshotStatsExtended() - │ ├─► SnapshotManager.PopulateSnapshotBlobs() // record referenced blobs │ + ├─► SnapshotManager.UpdateSnapshotStatsExtended() + │ ├─► SnapshotManager.ExportSnapshotMetadata() │ │ │ ├─► Copy database to temp file diff --git a/TODO.md b/TODO.md index b2e6cb7..ec17c26 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,19 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made the backup summary and the `snapshots` row count each + file, byte and upload once + ([issue #225](https://git.eeqj.de/sneak/vaultik/issues/225)). The + scanner added a file's bytes again for each new chunk and counted a + file as unchanged for each chunk already stored, so a first backup + reported twice its size and "backed up" could go negative. Upload + figures came from the progress reporter, which `--cron` turns off, and + `blob_count` counted earlier paths' blobs again for each later path. + The scanner now counts uploads itself; `blob_size`, + `blob_uncompressed_size` and `compression_ratio` describe the blobs + the snapshot references, and `docs/DATAMODEL.md` now says + `chunk_count` and `blob_count` count what the run added. + - 2026-10-06: Made command output follow the README's stdout and stderr rules ([issue #224](https://git.eeqj.de/sneak/vaultik/issues/224)). The startup banner went to stdout, so a `completion` script or a diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index 4fe62a5..a1967a3 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -117,10 +117,10 @@ Tracks backup snapshots. - `started_at` (INTEGER) - Start timestamp - `completed_at` (INTEGER) - Completion timestamp (NULL if in progress) - `file_count` (INTEGER) - Number of files in snapshot -- `chunk_count` (INTEGER) - Number of unique chunks -- `blob_count` (INTEGER) - Number of blobs referenced +- `chunk_count` (INTEGER) - Number of chunks this snapshot stored that were not stored before +- `blob_count` (INTEGER) - Number of blobs this snapshot created - `total_size` (INTEGER) - Total size of all files -- `blob_size` (INTEGER) - Total size of all blobs (compressed) +- `blob_size` (INTEGER) - Total compressed size of all referenced blobs - `blob_uncompressed_size` (INTEGER) - Total uncompressed size of all referenced blobs - `compression_ratio` (REAL) - Compression ratio achieved - `compression_level` (INTEGER) - Compression level used for this snapshot diff --git a/internal/database/models.go b/internal/database/models.go index ed27a8c..9c23c59 100644 --- a/internal/database/models.go +++ b/internal/database/models.go @@ -99,8 +99,8 @@ type Snapshot struct { StartedAt time.Time CompletedAt *time.Time // nil if still in progress FileCount int64 - ChunkCount int64 - BlobCount int64 + ChunkCount int64 // Chunks this snapshot stored that were not stored before + BlobCount int64 // Blobs this snapshot created TotalSize int64 // Total size of all referenced files // BlobSize is the total size of all referenced blobs (compressed and diff --git a/internal/database/snapshots.go b/internal/database/snapshots.go index 4479985..09d3b3a 100644 --- a/internal/database/snapshots.go +++ b/internal/database/snapshots.go @@ -127,6 +127,7 @@ func (r *SnapshotRepository) UpdateExtendedStats( snapshotID string, blobUncompressedSize int64, compressionLevel int, + uploadBytes int64, uploadDurationMs int64, ) error { compressionRatio, err := r.extendedCompressionRatio( @@ -141,7 +142,7 @@ func (r *SnapshotRepository) UpdateExtendedStats( SET blob_uncompressed_size = ?, compression_ratio = ?, compression_level = ?, - upload_bytes = blob_size, + upload_bytes = ?, upload_duration_ms = ? WHERE id = ? ` @@ -149,11 +150,11 @@ func (r *SnapshotRepository) UpdateExtendedStats( if tx != nil { _, err = tx.ExecContext(ctx, query, blobUncompressedSize, compressionRatio, compressionLevel, - uploadDurationMs, snapshotID) + uploadBytes, uploadDurationMs, snapshotID) } else { _, err = r.db.ExecWithLog(ctx, query, blobUncompressedSize, compressionRatio, compressionLevel, - uploadDurationMs, snapshotID) + uploadBytes, uploadDurationMs, snapshotID) } if err != nil { @@ -543,6 +544,30 @@ func (r *SnapshotRepository) GetSnapshotTotalCompressedSize( return totalSize, nil } +// GetSnapshotBlobSizes returns the total compressed and uncompressed sizes +// of all blobs referenced by a snapshot. +func (r *SnapshotRepository) GetSnapshotBlobSizes( + ctx context.Context, snapshotID string, +) (int64, int64, error) { + query := ` + SELECT COALESCE(SUM(b.compressed_size), 0), + COALESCE(SUM(b.uncompressed_size), 0) + FROM snapshot_blobs sb + JOIN blobs b ON sb.blob_hash = b.blob_hash + WHERE sb.snapshot_id = ? + ` + + var compressed, uncompressed int64 + + err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan( + &compressed, &uncompressed) + if err != nil { + return 0, 0, fmt.Errorf("querying snapshot blob sizes: %w", err) + } + + return compressed, uncompressed, nil +} + // GetSnapshotUncompressedChunkSize returns the sum of plaintext sizes of all unique // chunks referenced by a snapshot (via snapshot_files → file_chunks → chunks). func (r *SnapshotRepository) GetSnapshotUncompressedChunkSize( diff --git a/internal/database/snapshots_test.go b/internal/database/snapshots_test.go index 9d07c8e..5ddbd14 100644 --- a/internal/database/snapshots_test.go +++ b/internal/database/snapshots_test.go @@ -145,6 +145,65 @@ func TestSnapshotRepositoryUpdateCounts(t *testing.T) { } } +// GetSnapshotBlobSizes totals the blobs the snapshot references, and only +// those. +func TestSnapshotRepositoryGetSnapshotBlobSizes(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repos := database.NewRepositories(db) + + snapshot := &database.Snapshot{ + ID: "2024-01-03T12:00:00Z", + Hostname: testHostname, + VaultikVersion: testVersion, + StartedAt: time.Now().Truncate(time.Second), + } + + err := repos.Snapshots.Create(ctx, nil, snapshot) + if err != nil { + t.Fatalf("failed to create snapshot: %v", err) + } + + blobs := []*database.Blob{ + {Hash: "referenced-1", CompressedSize: 10, UncompressedSize: 100}, + {Hash: "referenced-2", CompressedSize: 20, UncompressedSize: 200}, + {Hash: "unreferenced", CompressedSize: 40, UncompressedSize: 400}, + } + + for _, blob := range blobs { + blob.ID = types.NewBlobID() + blob.CreatedTS = time.Now().Truncate(time.Second) + + err = repos.Blobs.Create(ctx, nil, blob) + if err != nil { + t.Fatalf("failed to create blob %s: %v", blob.Hash, err) + } + } + + for _, blob := range blobs[:2] { + err = repos.Snapshots.AddBlob(ctx, nil, snapshot.ID.String(), + blob.ID, blob.Hash) + if err != nil { + t.Fatalf("failed to add blob %s to snapshot: %v", blob.Hash, err) + } + } + + compressed, uncompressed, err := repos.Snapshots.GetSnapshotBlobSizes( + ctx, snapshot.ID.String()) + if err != nil { + t.Fatalf("failed to get snapshot blob sizes: %v", err) + } + + if compressed != 30 || uncompressed != 300 { + t.Errorf("blob sizes: got %d and %d, want 30 and 300", + compressed, uncompressed) + } +} + func TestSnapshotRepositoryListRecent(t *testing.T) { t.Parallel() diff --git a/internal/database/uploads.go b/internal/database/uploads.go index 312373e..7939089 100644 --- a/internal/database/uploads.go +++ b/internal/database/uploads.go @@ -158,19 +158,3 @@ type UploadStats struct { MinDurationMs int64 MaxDurationMs int64 } - -// GetCountBySnapshot returns the count of uploads for a specific snapshot -func (r *UploadRepository) GetCountBySnapshot( - ctx context.Context, snapshotID string, -) (int64, error) { - query := `SELECT COUNT(*) FROM uploads WHERE snapshot_id = ?` - - var count int64 - - err := r.conn.QueryRowContext(ctx, query, snapshotID).Scan(&count) - if err != nil { - return 0, err - } - - return count, nil -} diff --git a/internal/snapshot/progress.go b/internal/snapshot/progress.go index 5cd151a..9aba0f5 100644 --- a/internal/snapshot/progress.go +++ b/internal/snapshot/progress.go @@ -66,7 +66,6 @@ type ProgressStats struct { BlobsCreated atomic.Int64 BlobsUploaded atomic.Int64 BytesUploaded atomic.Int64 - UploadDurationMs atomic.Int64 // Total milliseconds spent uploading CurrentFile atomic.Value // stores string TotalSize atomic.Int64 // Total size to process (set after scan phase) TotalFiles atomic.Int64 // Total files to process in phase 2 @@ -231,9 +230,6 @@ func (pr *ProgressReporter) ReportUploadComplete( // Clear current upload pr.stats.CurrentUpload.Store((*UploadInfo)(nil)) - // Add to total upload duration - pr.stats.UploadDurationMs.Add(duration.Milliseconds()) - // Calculate speed if duration < time.Millisecond { duration = time.Millisecond diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index e74921a..6676f6e 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -92,9 +92,6 @@ type Scanner struct { // Mutex for coordinating blob creation packerMu sync.Mutex // Blocks chunk production during blob creation - - // Context for cancellation - scanCtx context.Context //nolint:containedctx // set per-Scan for packer callbacks } // Periodic status output intervals and thresholds for the scan and @@ -134,18 +131,23 @@ type ScannerConfig struct { SkipErrors bool } -// ScanResult contains the results of a scan operation +// ScanResult contains the results of a scan operation. Files and bytes +// are counted per file: BytesScanned is the size of the new and changed +// files, BytesSkipped that of the unchanged ones. type ScanResult struct { - FilesScanned int - FilesSkipped int - FilesDeleted int - BytesScanned int64 - BytesSkipped int64 - BytesDeleted int64 - ChunksCreated int - BlobsCreated int - StartTime time.Time - EndTime time.Time + FilesScanned int + FilesSkipped int + FilesDeleted int + BytesScanned int64 + BytesSkipped int64 + BytesDeleted int64 + ChunksCreated int + BlobsCreated int + BlobsUploaded int + BytesUploaded int64 + UploadDuration time.Duration + StartTime time.Time + EndTime time.Time } // NewScanner creates a new scanner instance @@ -211,7 +213,6 @@ func (s *Scanner) Scan( s.snapshotID = snapshotID // Store source path for file records (used during restore) s.currentSourcePath = path - s.scanCtx = ctx result := &ScanResult{ StartTime: time.Now().UTC(), } @@ -219,7 +220,9 @@ func (s *Scanner) Scan( // Set blob handler for concurrent upload if s.storage != nil { log.Debug("Setting blob handler for storage uploads") - s.packer.SetBlobHandler(s.handleBlobReady) + s.packer.SetBlobHandler(func(blobWithReader *blob.WithReader) error { + return s.handleBlobReady(ctx, blobWithReader, result) + }) } else { log.Debug("No storage configured, blobs will not be uploaded") } @@ -288,8 +291,7 @@ func (s *Scanner) Scan( log.Info("Phase 2/3: Skipping (no files need processing, metadata-only snapshot)") } - // Finalize result with blob statistics - s.finalizeScanResult(ctx, result) + result.EndTime = time.Now().UTC() return result, nil } @@ -431,27 +433,6 @@ func (s *Scanner) summarizeScanPhase( s.ui.Completef("%s.", msg) } -// finalizeScanResult populates final blob statistics in the scan result -// by querying the packer and database for blob/upload counts -func (s *Scanner) finalizeScanResult(ctx context.Context, result *ScanResult) { - blobs := s.packer.GetFinishedBlobs() - result.BlobsCreated += len(blobs) - - // Query database for actual blob count created during this snapshot - // The database is authoritative, especially for concurrent blob uploads - // We count uploads rather than all snapshot_blobs to get only NEW blobs - if s.snapshotID != "" { - uploadCount, err := s.repos.Uploads.GetCountBySnapshot(ctx, s.snapshotID) - if err != nil { - log.Warn("Failed to query upload count from database", "error", err) - } else { - result.BlobsCreated = int(uploadCount) - } - } - - result.EndTime = time.Now().UTC() -} - // loadKnownFiles loads the known files at and beneath path from the // database into a map for fast lookup. Every loaded file the scan does // not find is counted as deleted. This avoids per-file database queries @@ -1511,24 +1492,24 @@ func (s *Scanner) finalizeProcessPhase(ctx context.Context, result *ScanResult) } // handleBlobReady is called by the packer when a blob is finalized -func (s *Scanner) handleBlobReady(blobWithReader *blob.WithReader) error { +func (s *Scanner) handleBlobReady( + ctx context.Context, blobWithReader *blob.WithReader, result *ScanResult, +) error { startTime := time.Now().UTC() finishedBlob := blobWithReader.FinishedBlob + result.BlobsCreated++ + if s.progress != nil { s.progress.ReportUploadStart(finishedBlob.Hash, finishedBlob.Compressed) s.progress.GetStats().BlobsCreated.Add(1) } - ctx := s.scanCtx - if ctx == nil { - ctx = context.Background() - } - blobPath := fmt.Sprintf("blobs/%s/%s/%s", finishedBlob.Hash[:2], finishedBlob.Hash[2:4], finishedBlob.Hash) - blobExists, err := s.uploadBlobIfNeeded(ctx, blobPath, blobWithReader, startTime) + blobExists, err := s.uploadBlobIfNeeded( + ctx, blobPath, blobWithReader, startTime, result) if err != nil { s.cleanupBlobTempFile(blobWithReader) @@ -1563,6 +1544,7 @@ func (s *Scanner) uploadBlobIfNeeded( blobPath string, blobWithReader *blob.WithReader, startTime time.Time, + result *ScanResult, ) (bool, error) { finishedBlob := blobWithReader.FinishedBlob @@ -1598,6 +1580,10 @@ func (s *Scanner) uploadBlobIfNeeded( uploadDuration := time.Since(startTime) uploadSpeedBps := float64(finishedBlob.Compressed) / uploadDuration.Seconds() + result.BlobsUploaded++ + result.BytesUploaded += finishedBlob.Compressed + result.UploadDuration += uploadDuration + s.ui.Completef("Uploaded blob %s (%s) in %s at %s.", s.ui.Hex(finishedBlob.Hash), s.ui.Size(finishedBlob.Compressed), @@ -1813,9 +1799,9 @@ func (s *Scanner) processFileStreaming( size: chunk.Size, }) - s.updateChunkStats(chunkExists, chunk.Size, result) - if !chunkExists { + s.updateChunkStats(chunk.Size, result) + err := s.addChunkToPacker(ctx, chunk) if err != nil { // Mark as a packer error so --skip-errors cannot swallow it: @@ -1843,26 +1829,16 @@ func (s *Scanner) processFileStreaming( return nil } -// updateChunkStats updates scan result and progress stats for a processed chunk -func (s *Scanner) updateChunkStats( - chunkExists bool, chunkSize int64, result *ScanResult, -) { - if chunkExists { - result.FilesSkipped++ +// updateChunkStats counts a chunk that was not already stored. The scan +// result's file counts, BytesScanned and BytesSkipped are not touched +// here: the scan phase counts each file once. +func (s *Scanner) updateChunkStats(chunkSize int64, result *ScanResult) { + result.ChunksCreated++ - result.BytesSkipped += chunkSize - if s.progress != nil { - s.progress.GetStats().BytesSkipped.Add(chunkSize) - } - } else { - result.ChunksCreated++ - result.BytesScanned += chunkSize - - if s.progress != nil { - s.progress.GetStats().ChunksCreated.Add(1) - s.progress.GetStats().BytesProcessed.Add(chunkSize) - s.progress.UpdateChunkingActivity() - } + if s.progress != nil { + s.progress.GetStats().ChunksCreated.Add(1) + s.progress.GetStats().BytesProcessed.Add(chunkSize) + s.progress.UpdateChunkingActivity() } } diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 82a12a7..2848864 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -154,26 +154,6 @@ func (sm *SnapshotManager) CreateSnapshotWithName( return snapshotID, nil } -// UpdateSnapshotStats updates the statistics for a snapshot during backup -func (sm *SnapshotManager) UpdateSnapshotStats( - ctx context.Context, snapshotID string, stats BackupStats, -) error { - err := sm.repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { - return sm.repos.Snapshots.UpdateCounts(ctx, tx, snapshotID, - int64(stats.FilesScanned), - int64(stats.ChunksCreated), - int64(stats.BlobsCreated), - stats.BytesScanned, - stats.BytesUploaded, - ) - }) - if err != nil { - return fmt.Errorf("updating snapshot stats: %w", err) - } - - return nil -} - // UpdateSnapshotStatsExtended updates snapshot statistics with extended metrics. // This includes compression level, uncompressed blob size, and upload duration. func (sm *SnapshotManager) UpdateSnapshotStatsExtended( @@ -185,8 +165,8 @@ func (sm *SnapshotManager) UpdateSnapshotStatsExtended( int64(stats.FilesScanned), int64(stats.ChunksCreated), int64(stats.BlobsCreated), - stats.BytesScanned, - stats.BytesUploaded, + stats.TotalSize, + stats.BlobSize, ) if err != nil { return err @@ -196,6 +176,7 @@ func (sm *SnapshotManager) UpdateSnapshotStatsExtended( return sm.repos.Snapshots.UpdateExtendedStats(ctx, tx, snapshotID, stats.BlobUncompressedSize, stats.CompressionLevel, + stats.BytesUploaded, stats.UploadDurationMs, ) }) @@ -890,7 +871,7 @@ func (sm *SnapshotManager) getFileSize(path string) int64 { // BackupStats contains statistics from a backup operation type BackupStats struct { FilesScanned int - BytesScanned int64 + TotalSize int64 // Total size of all files examined ChunksCreated int BlobsCreated int BytesUploaded int64 @@ -900,6 +881,7 @@ type BackupStats struct { type ExtendedBackupStats struct { BackupStats + BlobSize int64 // Total compressed size of all referenced blobs BlobUncompressedSize int64 // Total uncompressed size of all referenced blobs CompressionLevel int // Compression level used for this snapshot UploadDurationMs int64 // Total milliseconds spent uploading to S3 diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 7c948f7..82a116e 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -189,6 +189,11 @@ type snapshotStats struct { totalBytesUploaded int64 totalBlobsUploaded int uploadDuration time.Duration + + // The sizes of all blobs the snapshot references, set by + // finalizeSnapshotMetadata once snapshot_blobs is populated. + blobSize int64 + blobUncompressedSize int64 } // createNamedSnapshot creates a single named snapshot @@ -228,8 +233,6 @@ func (v *Vaultik) createNamedSnapshot( return err } - v.collectUploadStats(scanner, stats) - err = v.finalizeSnapshotMetadata(snapshotID, stats) if err != nil { return err @@ -314,6 +317,9 @@ func (v *Vaultik) scanAllDirectories( stats.totalBytesSkipped += result.BytesSkipped stats.totalFilesDeleted += result.FilesDeleted stats.totalBytesDeleted += result.BytesDeleted + stats.totalBlobsUploaded += result.BlobsUploaded + stats.totalBytesUploaded += result.BytesUploaded + stats.uploadDuration += result.UploadDuration log.Info("Directory scan complete", "path", dir, @@ -329,18 +335,6 @@ func (v *Vaultik) scanAllDirectories( return stats, nil } -// collectUploadStats gathers upload statistics from the scanner's -// progress reporter. -func (v *Vaultik) collectUploadStats(scanner *snapshot.Scanner, stats *snapshotStats) { - if s := scanner.GetProgress(); s != nil { - progressStats := s.GetStats() - stats.totalBytesUploaded = progressStats.BytesUploaded.Load() - stats.totalBlobsUploaded = int(progressStats.BlobsUploaded.Load()) - stats.uploadDuration = time.Duration( - progressStats.UploadDurationMs.Load()) * time.Millisecond - } -} - // finalizeSnapshotMetadata updates stats, exports metadata, and only then // marks the snapshot complete. Recording completion last is deliberate: an // export interrupted by a crash leaves the snapshot incomplete rather than @@ -350,31 +344,39 @@ func (v *Vaultik) collectUploadStats(scanner *snapshot.Scanner, stats *snapshotS func (v *Vaultik) finalizeSnapshotMetadata( snapshotID string, stats *snapshotStats, ) error { + // snapshot_blobs must be populated before the blob sizes below, which + // total the snapshot's blobs, and before the export, which builds the + // manifest and the trimmed metadata database from it. + err := v.SnapshotManager.PopulateSnapshotBlobs(v.ctx, snapshotID) + if err != nil { + return fmt.Errorf("populating snapshot blobs: %w", err) + } + + stats.blobSize, stats.blobUncompressedSize, err = + v.Repositories.Snapshots.GetSnapshotBlobSizes(v.ctx, snapshotID) + if err != nil { + return fmt.Errorf("getting snapshot blob sizes: %w", err) + } + extStats := snapshot.ExtendedBackupStats{ BackupStats: snapshot.BackupStats{ FilesScanned: stats.totalFiles, - BytesScanned: stats.totalBytes, + TotalSize: stats.totalBytes + stats.totalBytesSkipped, ChunksCreated: stats.totalChunks, BlobsCreated: stats.totalBlobs, BytesUploaded: stats.totalBytesUploaded, }, - BlobUncompressedSize: 0, + BlobSize: stats.blobSize, + BlobUncompressedSize: stats.blobUncompressedSize, CompressionLevel: v.Config.CompressionLevel, UploadDurationMs: stats.uploadDuration.Milliseconds(), } - err := v.SnapshotManager.UpdateSnapshotStatsExtended(v.ctx, snapshotID, extStats) + err = v.SnapshotManager.UpdateSnapshotStatsExtended(v.ctx, snapshotID, extStats) if err != nil { return fmt.Errorf("updating snapshot stats: %w", err) } - // snapshot_blobs must be populated before the export, which builds the - // manifest and the trimmed metadata database from it. - err = v.SnapshotManager.PopulateSnapshotBlobs(v.ctx, snapshotID) - if err != nil { - return fmt.Errorf("populating snapshot blobs: %w", err) - } - err = v.SnapshotManager.ExportSnapshotMetadata( v.ctx, v.Config.IndexPath, snapshotID) if err != nil { @@ -409,12 +411,10 @@ func (v *Vaultik) printSnapshotSummary( totalFilesChanged := stats.totalFiles - stats.totalFilesSkipped totalBytesAll := stats.totalBytes + stats.totalBytesSkipped - // Get total blob sizes from database - compressedSize, uncompressedSize := v.getSnapshotBlobSizes(snapshotID) - var compressionRatio float64 - if uncompressedSize > 0 { - compressionRatio = float64(compressedSize) / float64(uncompressedSize) + if stats.blobUncompressedSize > 0 { + compressionRatio = float64(stats.blobSize) / + float64(stats.blobUncompressedSize) } else { compressionRatio = 1.0 } @@ -442,8 +442,8 @@ func (v *Vaultik) printSnapshotSummary( if stats.totalBlobsUploaded > 0 { v.UI.Detailf("Storage: %s compressed from %s (%.2fx ratio).", - v.UI.Size(compressedSize), - v.UI.Size(uncompressedSize), + v.UI.Size(stats.blobSize), + v.UI.Size(stats.blobUncompressedSize), compressionRatio) v.UI.Detailf("Upload: %d blobs, %s in %s (%s).", stats.totalBlobsUploaded, @@ -455,27 +455,6 @@ func (v *Vaultik) printSnapshotSummary( v.UI.Detailf("Snapshot create duration: %s.", v.UI.Duration(snapshotDuration)) } -// getSnapshotBlobSizes returns total compressed and uncompressed blob -// sizes for a snapshot. -func (v *Vaultik) getSnapshotBlobSizes(snapshotID string) (int64, int64) { - var compressed, uncompressed int64 - - blobHashes, err := v.Repositories.Snapshots.GetBlobHashes(v.ctx, snapshotID) - if err != nil { - return 0, 0 - } - - for _, hash := range blobHashes { - blob, err := v.Repositories.Blobs.GetByHash(v.ctx, hash) - if err == nil && blob != nil { - compressed += blob.CompressedSize - uncompressed += blob.UncompressedSize - } - } - - return compressed, uncompressed -} - // SnapshotPurgeOptions contains options for the snapshot purge command. type SnapshotPurgeOptions struct { KeepLatest bool // Keep only the most recent snapshot per name diff --git a/internal/vaultik/snapshot_summary_test.go b/internal/vaultik/snapshot_summary_test.go new file mode 100644 index 0000000..a3562f3 --- /dev/null +++ b/internal/vaultik/snapshot_summary_test.go @@ -0,0 +1,285 @@ +package vaultik_test + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/225: the +// summary printed after a backup, and the statistics stored in the +// snapshots table, count each file, byte and upload once, and a --cron +// run records its uploads. + +// summaryUploadDelay slows every blob upload, so a run's upload time is +// at least this long per blob even on a local store. +const summaryUploadDelay = 20 * time.Millisecond + +// summaryEnv is a backup setup whose user-facing output is kept in out. +type summaryEnv struct { + v *vaultik.Vaultik + db *database.DB + repos *database.Repositories + out *bytes.Buffer + + // aPath is a.bin, whose content copy.bin repeats; aSize is its size + // and totalSize the size of all three source files. + aPath string + aSize int64 + totalSize int64 +} + +// newSummaryEnv writes src/one/a.bin, src/one/small.txt and +// src/two/copy.bin, a copy of a.bin. Every chunk of copy.bin is therefore +// already stored by the time the backup reaches it. +// +// The snapshot names "first" and "second" back up src; "split" backs up +// src/one and src/two as two paths. +func newSummaryEnv(t *testing.T) *summaryEnv { + t.Helper() + + log.Initialize(log.Config{}) + + fs := afero.NewOsFs() + tempDir := t.TempDir() + srcDir := filepath.Join(tempDir, "src") + dirOne := filepath.Join(srcDir, "one") + dirTwo := filepath.Join(srcDir, "two") + dbPath := filepath.Join(tempDir, "index.sqlite") + ctx := context.Background() + + aContent := bytesPattern("a-", int(3*faultChunkSize)) + smallContent := []byte("hello vaultik") + files := map[string][]byte{ + filepath.Join(dirOne, "a.bin"): aContent, + filepath.Join(dirOne, "small.txt"): smallContent, + filepath.Join(dirTwo, "copy.bin"): aContent, + } + + for path, content := range files { + require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, afero.WriteFile(fs, path, content, 0o644)) + } + + cfg := faultTestConfig() + cfg.IndexPath = dbPath + cfg.ChunkSize = config.Size(faultChunkSize) + cfg.Snapshots = map[string]config.SnapshotConfig{ + "first": {Paths: []string{srcDir}}, + "second": {Paths: []string{srcDir}}, + "split": {Paths: []string{dirOne, dirTwo}}, + } + + inner, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + require.NoError(t, err) + + store := faultstore.New(inner) + store.OnPut = func(key string) faultstore.PutAction { + if strings.HasPrefix(key, "blobs/") { + time.Sleep(summaryUploadDelay) + } + + return faultstore.PutNormal + } + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + out := &bytes.Buffer{} + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + v.UI = ui.NewWithColor(out, false) + + return &summaryEnv{ + v: v, + db: db, + repos: repos, + out: out, + aPath: filepath.Join(dirOne, "a.bin"), + aSize: int64(len(aContent)), + totalSize: int64(2*len(aContent) + len(smallContent)), + } +} + +// backUp runs a backup of the named snapshot and returns its output. +func (e *summaryEnv) backUp(t *testing.T, name string, cron bool) string { + t.Helper() + + e.out.Reset() + require.NoError(t, e.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Cron: cron, + Snapshots: []string{name}, + })) + + return e.out.String() +} + +// snapshot returns the local snapshots row of the snapshot named name. +func (e *summaryEnv) snapshot(t *testing.T, name string) *database.Snapshot { + t.Helper() + + ctx := context.Background() + snap, err := e.repos.Snapshots.GetByID(ctx, + localSnapshotID(ctx, t, e.repos, name)) + require.NoError(t, err) + require.NotNil(t, snap) + + return snap +} + +// uploads returns how many blobs the snapshot uploaded and their +// total size, as recorded in the uploads table. +func (e *summaryEnv) uploads(t *testing.T, snapshotID string) (int64, int64) { + t.Helper() + + var count, size int64 + + err := e.db.Conn().QueryRowContext(context.Background(), ` + SELECT COUNT(*), COALESCE(SUM(size), 0) + FROM uploads WHERE snapshot_id = ?`, snapshotID).Scan(&count, &size) + require.NoError(t, err) + + return count, size +} + +// referencedBlobSizes returns the compressed and uncompressed sizes of +// all blobs the snapshot references. +func (e *summaryEnv) referencedBlobSizes( + t *testing.T, snapshotID string, +) (int64, int64) { + t.Helper() + + var compressed, uncompressed int64 + + err := e.db.Conn().QueryRowContext(context.Background(), ` + SELECT COALESCE(SUM(b.compressed_size), 0), + COALESCE(SUM(b.uncompressed_size), 0) + FROM snapshot_blobs sb JOIN blobs b ON b.blob_hash = sb.blob_hash + WHERE sb.snapshot_id = ?`, snapshotID).Scan(&compressed, &uncompressed) + require.NoError(t, err) + + return compressed, uncompressed +} + +// filesLine returns the summary's line of file counts. +func filesLine(examined, backedUp, unchanged int) string { + return fmt.Sprintf("Files: %d examined, %d backed up, %d unchanged.", + examined, backedUp, unchanged) +} + +// dataLine returns the summary's line of byte counts. +func (e *summaryEnv) dataLine(total, backedUp int64) string { + return fmt.Sprintf("Data: %s total (%s backed up).", + e.v.UI.Size(total), e.v.UI.Size(backedUp)) +} + +// A first backup stores copy.bin's chunks while backing up a.bin, so +// copy.bin's chunks are deduplicated within the run. Each file and byte +// is still counted once. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestSnapshotSummaryFirstRun(t *testing.T) { + env := newSummaryEnv(t) + + summary := env.backUp(t, "first", false) + + assert.Contains(t, summary, filesLine(3, 3, 0)) + assert.Contains(t, summary, env.dataLine(env.totalSize, env.totalSize)) + + snap := env.snapshot(t, "first") + uploadCount, uploadBytes := env.uploads(t, snap.ID.String()) + require.Positive(t, uploadCount) + + assert.Contains(t, summary, fmt.Sprintf("Upload: %d blobs, %s in ", + uploadCount, env.v.UI.Size(uploadBytes))) + + assert.Equal(t, int64(3), snap.FileCount) + assert.Equal(t, env.totalSize, snap.TotalSize) + assert.Equal(t, uploadCount, snap.BlobCount) + assert.Equal(t, uploadBytes, snap.UploadBytes) +} + +// An incremental backup where a.bin's mtime changed but its content did +// not: a.bin is backed up again and every one of its chunks is already +// stored. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestSnapshotSummaryIncrementalRunWithDeduplicatedChunks(t *testing.T) { + env := newSummaryEnv(t) + + env.backUp(t, "first", false) + + later := time.Now().Add(time.Hour) + require.NoError(t, os.Chtimes(env.aPath, later, later)) + + summary := env.backUp(t, "second", false) + + assert.Contains(t, summary, filesLine(3, 1, 2)) + assert.Contains(t, summary, env.dataLine(env.totalSize, env.aSize)) + assert.NotContains(t, summary, "Upload:") + + snap := env.snapshot(t, "second") + compressed, uncompressed := env.referencedBlobSizes(t, snap.ID.String()) + require.Positive(t, compressed) + + assert.Equal(t, env.totalSize, snap.TotalSize) + assert.Zero(t, snap.ChunkCount) + assert.Zero(t, snap.BlobCount) + assert.Zero(t, snap.UploadBytes) + assert.Equal(t, compressed, snap.BlobSize, + "blob_size must total the blobs the snapshot references") + assert.Equal(t, uncompressed, snap.BlobUncompressedSize) +} + +// Under --cron the progress reporter is off; the upload figures must +// still reach the summary and the snapshots row. The snapshot has two +// paths, each backed up by its own scan. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestSnapshotSummaryCronRunRecordsUploads(t *testing.T) { + env := newSummaryEnv(t) + + summary := env.backUp(t, "split", true) + + snap := env.snapshot(t, "split") + uploadCount, uploadBytes := env.uploads(t, snap.ID.String()) + require.Positive(t, uploadCount) + + assert.Contains(t, summary, filesLine(3, 3, 0)) + assert.Contains(t, summary, env.dataLine(env.totalSize, env.totalSize)) + assert.Contains(t, summary, fmt.Sprintf("Upload: %d blobs, %s in ", + uploadCount, env.v.UI.Size(uploadBytes))) + + assert.Equal(t, env.totalSize, snap.TotalSize) + assert.Equal(t, uploadCount, snap.BlobCount, + "blob_count must count each blob once, however many paths the "+ + "snapshot has") + assert.Equal(t, uploadBytes, snap.UploadBytes) + assert.GreaterOrEqual(t, snap.UploadDurationMs, + uploadCount*summaryUploadDelay.Milliseconds()) + + compressed, uncompressed := env.referencedBlobSizes(t, snap.ID.String()) + require.Positive(t, uncompressed) + + assert.Equal(t, compressed, snap.BlobSize) + assert.Equal(t, uncompressed, snap.BlobUncompressedSize) + assert.InDelta(t, float64(compressed)/float64(uncompressed), + snap.CompressionRatio, 1e-9) +} From cdc60c4dfa9d36966fb68955f54d8f116dadba94 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 04:46:13 +0200 Subject: [PATCH 022/121] Write only the document to stdout from snapshot remove --json (closes #251) When the destination store cannot be reached, `snapshot remove` still removes the snapshot from the local index and warns. The warning went through the UI, which writes to stdout, so under `--json` it landed ahead of the document and `| jq` failed on a command that exited 0. Under `--json` the UI warning is now skipped; the logger's warning on stderr carries the follow-up, with the snapshot ID as a field. The follow-up, in the warning, the README and the command's help, said `vaultik prune` would finish the cleanup, but `prune` never removes snapshot metadata. They now say to run `vaultik snapshot remove` for the snapshot again once the destination store is reachable. Model: opus-5-5 --- README.md | 5 +- TODO.md | 11 +++++ internal/cli/entry_stdout_stderr_test.go | 62 +++++++++++++++++++++--- internal/cli/snapshot.go | 5 +- internal/vaultik/snapshot.go | 30 ++++++++---- 5 files changed, 93 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 70f5eb4..72097c3 100644 --- a/README.md +++ b/README.md @@ -352,8 +352,9 @@ may hold snapshots this host doesn't know about), which is what prune` invocation to run as a follow-up. Local row cleanup (files, chunks, blobs the snapshot was the last referrer for) runs automatically. If the destination store is unreachable, the local-DB -removal still completes and a warning is emitted; rerun `vaultik prune` -once the store is reachable to finish remote cleanup. To wipe everything +removal still completes and a warning is emitted; run `vaultik snapshot +remove ` again once the store is reachable to remove the +snapshot's metadata from it (`vaultik prune` does not). To wipe everything on the destination in one go, use `vaultik remote nuke --force`. * `--local-only`: Skip remote cleanup; only touch the local index * `--dry-run`: Show what would be deleted without deleting diff --git a/TODO.md b/TODO.md index ec17c26..f280f3d 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,17 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-06: Made `snapshot remove --json` write only its document to + stdout when the destination store cannot be reached + ([issue #251](https://git.eeqj.de/sneak/vaultik/issues/251)). Its + warning that the snapshot's metadata was left on the destination store + went to stdout ahead of the document, breaking `| jq` on a command that + exited 0. Under `--json` the warning now reaches stderr only, through + the logger. The warning, the README and the command's help said + `vaultik prune` would finish the cleanup, but `prune` never removes + snapshot metadata; they now say to run `vaultik snapshot remove` for the + snapshot again once the destination store is reachable. + - 2026-10-06: Made the backup summary and the `snapshots` row count each file, byte and upload once ([issue #225](https://git.eeqj.de/sneak/vaultik/issues/225)). The diff --git a/internal/cli/entry_stdout_stderr_test.go b/internal/cli/entry_stdout_stderr_test.go index 43a6e42..1eda0d4 100644 --- a/internal/cli/entry_stdout_stderr_test.go +++ b/internal/cli/entry_stdout_stderr_test.go @@ -2,7 +2,9 @@ package cli //nolint:testpackage // shares hermeticConfig and the capture helper import ( "context" + "encoding/json" "fmt" + "log/slog" "os" "path/filepath" "strings" @@ -87,12 +89,45 @@ func TestEntryJSONFailureIsReportedOnStderr(t *testing.T) { } } -// writeUnusableDestinationConfig builds a config whose destination -// directory does not exist, which fails `remote info`, and whose local -// index is bound to another destination, which fails `prune` and -// `snapshot remove` (a missing destination alone only makes `snapshot -// remove` warn). Returns the config path. -func writeUnusableDestinationConfig(t *testing.T) string { +// TestEntrySnapshotRemoveJSONWarningIsOnStderr runs `snapshot remove +// --json` on a snapshot in the local index, against a destination +// directory that does not exist. The command removes the snapshot from +// the local index and still exits 0. Its stdout must hold the document +// alone, with the warning about the destination store on stderr: the +// command to run again once it is reachable, and the snapshot's ID in +// the record's snapshot_id field. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotRemoveJSONWarningIsOnStderr(t *testing.T) { + configPath, indexPath := writeMissingDestinationConfig(t) + seedStaleSnapshotRecord(t, indexPath) + + code, stdout, stderr := runEntry(t, flagConfig, configPath, + cmdSnapshot, cmdRemove, stalePruneSnapshotID, flagJSON) + + require.Equal(t, 0, code) + requireExactlyOneJSONDocument(t, stdout) + + // stderr is a pipe here, so the logger writes one JSON record a line. + var warning map[string]any + + for line := range strings.Lines(stderr) { + if strings.Contains(line, + "Could not remove snapshot metadata from remote storage") { + require.NoError(t, json.Unmarshal([]byte(line), &warning)) + } + } + + require.NotNil(t, warning, "the warning must reach stderr") + assert.Contains(t, warning[slog.MessageKey], + "run 'vaultik snapshot remove' with the snapshot's ID again") + assert.Equal(t, stalePruneSnapshotID, warning["snapshot_id"]) +} + +// writeMissingDestinationConfig builds a config whose destination +// directory does not exist. Returns the config path and the path of +// its local index, which is not created here. +func writeMissingDestinationConfig(t *testing.T) (string, string) { t.Helper() dir := t.TempDir() @@ -114,6 +149,19 @@ func writeUnusableDestinationConfig(t *testing.T) string { xdg.Reload() t.Cleanup(xdg.Reload) + return configPath, indexPath +} + +// writeUnusableDestinationConfig builds a config whose destination +// directory does not exist, which fails `remote info`, and whose local +// index is bound to another destination, which fails `prune` and +// `snapshot remove` (a missing destination alone only makes `snapshot +// remove` warn). Returns the config path. +func writeUnusableDestinationConfig(t *testing.T) string { + t.Helper() + + configPath, indexPath := writeMissingDestinationConfig(t) + ctx := context.Background() db, err := database.New(ctx, indexPath) @@ -122,7 +170,7 @@ func writeUnusableDestinationConfig(t *testing.T) string { defer func() { require.NoError(t, db.Close()) }() require.NoError(t, database.NewRepositories(db).LocalMeta.Set(ctx, - database.LocalMetaKeyStorageURL, "file://"+filepath.Join(dir, "other"))) + database.LocalMetaKeyStorageURL, "file://"+t.TempDir())) return configPath } diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 4a0e095..fb2dc4d 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -258,8 +258,9 @@ Use --local-only to skip the remote half (e.g. when you want to forget a snapshot locally without touching the destination store). If the remote is unreachable, the local-database removal still completes -and a warning is emitted; rerun 'vaultik prune' once the destination store -is reachable to finish remote cleanup. +and a warning is emitted; run 'vaultik snapshot remove ' again +once the destination store is reachable to remove the snapshot's metadata +from it ('vaultik prune' does not). To wipe the entire destination store and start over, use 'vaultik remote nuke --force' — it is the single supported entry point for that.`, diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 82a116e..7071bd4 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -1110,6 +1110,12 @@ type RemoveResult struct { // just-removed snapshot left behind on the destination store. const pruneCommandHint = "vaultik prune" +// snapshotRemoveCommandHint is the command suggested, with the +// snapshot's ID, when a remove could not reach the destination store: +// running it again removes the snapshot's metadata there, which +// `vaultik prune` never does. +const snapshotRemoveCommandHint = "vaultik snapshot remove" + // RemoveSnapshot removes a snapshot from the local index database and, // unless LocalOnly is set, also strips the snapshot's metadata from the // destination store. Blobs are NOT touched: removing a snapshot's @@ -1146,7 +1152,7 @@ func (v *Vaultik) RemoveSnapshot( } if !opts.LocalOnly { - result.RemoteRemoved = v.removeSnapshotRemote(snapshotID) + result.RemoteRemoved = v.removeSnapshotRemote(snapshotID, opts) } if v.SnapshotManager != nil { @@ -1229,9 +1235,11 @@ func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) // removeSnapshotRemote strips the snapshot's metadata from the // destination store, warning and proceeding on failure: the local-DB // removal has already happened, so the user is told the remote half -// didn't finish and can retry with `vaultik prune` once the destination -// store is reachable. Returns true when the remote removal succeeded. -func (v *Vaultik) removeSnapshotRemote(snapshotID string) bool { +// didn't finish and to run `vaultik snapshot remove` for the snapshot +// again once the destination store is reachable (`vaultik prune` never +// removes snapshot metadata). Returns true when the remote removal +// succeeded. +func (v *Vaultik) removeSnapshotRemote(snapshotID string, opts *RemoveOptions) bool { log.Info("Removing snapshot metadata from remote storage", "snapshot_id", snapshotID) @@ -1239,13 +1247,17 @@ func (v *Vaultik) removeSnapshotRemote(snapshotID string) bool { err := v.deleteRemoteSnapshotByKey(remoteKey) if err != nil { - log.Warn("Could not remove snapshot metadata from remote storage", - "error", err) + log.Warn("Could not remove snapshot metadata from remote storage; "+ + "run '"+snapshotRemoveCommandHint+"' with the snapshot's ID "+ + "again once the remote is reachable", + "snapshot_id", snapshotID, "error", err) - if v.UI != nil { + // The UI writes to stdout, which under --json holds only the + // document; the log record above is the warning on stderr. + if v.UI != nil && !opts.JSON { v.UI.Warningf("Could not remove snapshot metadata from remote: "+ - "%v. Run '%s' once the remote is reachable to finish cleanup.", - err, pruneCommandHint) + "%v. Run '%s %s' again once the remote is reachable.", + err, snapshotRemoveCommandHint, snapshotID) } return false From 8496404d8bb8340aa80e5b45ca5bde7b62dfb9db Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 06:12:10 +0200 Subject: [PATCH 023/121] Make the process-wide lock atomic with flock (closes #227) Acquire read vaultik.pid, checked whether that PID was alive, then wrote its own, so two writers started together could both pass the check and both run. The lock is now an flock on vaultik.pid, held while the file stays open; the kernel drops it when the process exits, so the stale-PID check is gone. Release empties the file instead of deleting it. Deleting it would let a process that opened the old file a moment earlier lock it while another creates and locks a new one. The new concurrent test fails against the old code only when the race is hit, not on every run; against the fix it cannot admit two callers. Model: opus-5-5 --- TODO.md | 10 +++ internal/pidlock/pidlock.go | 119 +++++++++++++++++-------------- internal/pidlock/pidlock_test.go | 66 ++++++++++++++++- 3 files changed, 140 insertions(+), 55 deletions(-) diff --git a/TODO.md b/TODO.md index f280f3d..3801fd1 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,16 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Made taking the process-wide lock atomic + ([issue #227](https://git.eeqj.de/sneak/vaultik/issues/227)). The lock + read `vaultik.pid`, checked whether that PID was alive and then wrote + its own, so two writers started together could both pass the check and + both run. It is now an `flock` on `vaultik.pid`, held until the run + ends; the kernel drops it when the process exits, so a crash leaves no + lock behind. A clean exit now empties the file instead of deleting it, + because deleting it would let two later runs each lock a different + file. + - 2026-10-06: Made `snapshot remove --json` write only its document to stdout when the destination store cannot be reached ([issue #251](https://git.eeqj.de/sneak/vaultik/issues/251)). Its diff --git a/internal/pidlock/pidlock.go b/internal/pidlock/pidlock.go index ea15e77..279b233 100644 --- a/internal/pidlock/pidlock.go +++ b/internal/pidlock/pidlock.go @@ -10,15 +10,18 @@ import ( "path/filepath" "strconv" "strings" - "syscall" + + "golang.org/x/sys/unix" ) // ErrAlreadyRunning indicates another vaultik instance is running. var ErrAlreadyRunning = errors.New("another vaultik instance is already running") -// Lock represents an acquired PID lock. +// Lock represents an acquired PID lock: an flock(2) on the PID file, +// held while the file stays open. The kernel drops it when the process +// exits, however it exits, so a crashed run never leaves the lock held. type Lock struct { - path string + file *os.File } const ( @@ -29,10 +32,9 @@ const ( ) // Acquire attempts to acquire a PID lock in the specified directory. -// If the lock file exists and the process is still running, it returns -// ErrAlreadyRunning with details about the existing process. -// On success, it writes the current PID to the lock file and returns -// a Lock that must be released with Release(). +// If another process holds the lock, it returns ErrAlreadyRunning with +// that process's PID. On success, it writes the current PID to the lock +// file and returns a Lock that must be released with Release(). func Acquire(lockDir string) (*Lock, error) { // Ensure lock directory exists err := os.MkdirAll(lockDir, lockDirPerm) @@ -42,56 +44,82 @@ func Acquire(lockDir string) (*Lock, error) { lockPath := filepath.Join(lockDir, "vaultik.pid") - // Check for existing lock - existingPID, err := readPIDFile(lockPath) - if err == nil { - // Lock file exists, check if process is running - if isProcessRunning(existingPID) { - return nil, fmt.Errorf("%w (PID %d)", ErrAlreadyRunning, existingPID) - } - // Process is not running, stale lock file - we can take over - } - - // Write our PID - pid := os.Getpid() - - err = os.WriteFile(lockPath, []byte(strconv.Itoa(pid)), pidFilePerm) + // No O_TRUNC: the file may hold the PID of the process that has the + // lock, which the error below reports. + file, err := os.OpenFile( //nolint:gosec // G304: path is our own lock file + lockPath, os.O_RDWR|os.O_CREATE, pidFilePerm) if err != nil { - return nil, fmt.Errorf("writing PID file: %w", err) + return nil, fmt.Errorf("opening PID file: %w", err) } - return &Lock{path: lockPath}, nil + err = unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB) + if err != nil { + _ = file.Close() + + if errors.Is(err, unix.EWOULDBLOCK) { + return nil, alreadyRunningError(lockPath) + } + + return nil, fmt.Errorf("locking PID file: %w", err) + } + + err = writePID(file) + if err != nil { + _ = file.Close() + + return nil, err + } + + return &Lock{file: file}, nil } -// Release removes the PID lock file. +// Release empties the PID file and closes it, which drops the lock. // It is safe to call Release multiple times. func (l *Lock) Release() error { - if l == nil || l.path == "" { + if l == nil || l.file == nil { return nil } - // Verify we still own the lock (our PID is in the file) - existingPID, err := readPIDFile(l.path) + file := l.file + l.file = nil + + // Do not remove the file here. A process that opened it a moment + // earlier could then lock the removed file while another creates and + // locks a new one, and both would run. + truncateErr := file.Truncate(0) + closeErr := file.Close() + + return errors.Join(truncateErr, closeErr) +} + +// writePID replaces the contents of the locked PID file with the current +// PID. +func writePID(file *os.File) error { + err := file.Truncate(0) if err != nil { - // File already gone or unreadable - that's fine - return nil //nolint:nilerr // unreadable lock file means nothing to release + return fmt.Errorf("truncating PID file: %w", err) } - if existingPID != os.Getpid() { - // Someone else wrote to our lock file - don't remove it - return nil + _, err = file.WriteAt([]byte(strconv.Itoa(os.Getpid())), 0) + if err != nil { + return fmt.Errorf("writing PID file: %w", err) } - err = os.Remove(l.path) - if err != nil && !os.IsNotExist(err) { - return fmt.Errorf("removing PID file: %w", err) - } - - l.path = "" // Prevent double-release - return nil } +// alreadyRunningError reports that another process holds the lock, +// naming its PID when the file holds one. The holder writes its PID just +// after it locks, so the file can briefly be empty. +func alreadyRunningError(lockPath string) error { + pid, err := readPIDFile(lockPath) + if err != nil { + return ErrAlreadyRunning + } + + return fmt.Errorf("%w (PID %d)", ErrAlreadyRunning, pid) +} + // readPIDFile reads and parses the PID from a lock file. func readPIDFile(path string) (int, error) { data, err := os.ReadFile(path) //nolint:gosec // G304: path is our own lock file @@ -106,16 +134,3 @@ func readPIDFile(path string) (int, error) { return pid, nil } - -// isProcessRunning checks if a process with the given PID is running. -func isProcessRunning(pid int) bool { - process, err := os.FindProcess(pid) - if err != nil { - return false - } - - // On Unix, FindProcess always succeeds. We need to send signal 0 to check. - err = process.Signal(syscall.Signal(0)) - - return err == nil -} diff --git a/internal/pidlock/pidlock_test.go b/internal/pidlock/pidlock_test.go index 1f49372..25d67b1 100644 --- a/internal/pidlock/pidlock_test.go +++ b/internal/pidlock/pidlock_test.go @@ -4,6 +4,7 @@ import ( "os" "path/filepath" "strconv" + "sync" "testing" "github.com/stretchr/testify/assert" @@ -33,9 +34,10 @@ func TestAcquireAndRelease(t *testing.T) { err = lock.Release() require.NoError(t, err) - // Verify PID file is gone - _, err = os.Stat(pidPath) - assert.True(t, os.IsNotExist(err)) + // Verify PID file is empty + data, err = os.ReadFile(pidPath) //nolint:gosec // G304: test's own temp file + require.NoError(t, err) + assert.Empty(t, data) } func TestAcquireBlocksSecondInstance(t *testing.T) { @@ -55,6 +57,64 @@ func TestAcquireBlocksSecondInstance(t *testing.T) { lock2, err := pidlock.Acquire(tmpDir) require.ErrorIs(t, err, pidlock.ErrAlreadyRunning) assert.Nil(t, lock2) + + // Once the first lock is released, the next Acquire succeeds + require.NoError(t, lock1.Release()) + + lock3, err := pidlock.Acquire(tmpDir) + require.NoError(t, err) + require.NoError(t, lock3.Release()) +} + +// TestConcurrentAcquireAdmitsOne starts many Acquire calls at the same +// moment, as two cron entries firing together would, and checks that +// exactly one of them gets the lock. +func TestConcurrentAcquireAdmitsOne(t *testing.T) { + t.Parallel() + + const callers = 50 + + tmpDir := t.TempDir() + start := make(chan struct{}) + + var ( + mu sync.Mutex + acquired []*pidlock.Lock + failures []error + wg sync.WaitGroup + ) + + for range callers { + wg.Go(func() { + <-start + + lock, err := pidlock.Acquire(tmpDir) + + mu.Lock() + defer mu.Unlock() + + if err != nil { + failures = append(failures, err) + + return + } + + acquired = append(acquired, lock) + }) + } + + close(start) + wg.Wait() + + for _, lock := range acquired { + require.NoError(t, lock.Release()) + } + + assert.Len(t, acquired, 1, "exactly one caller should hold the lock") + + for _, err := range failures { + require.ErrorIs(t, err, pidlock.ErrAlreadyRunning) + } } func TestAcquireWithStaleLock(t *testing.T) { From b57ce2277d6b3ed74f4f51bc6520a20b6020501e Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 07:12:12 +0200 Subject: [PATCH 024/121] Store and compare file mtimes to the nanosecond (closes #226) The files table held mtime in whole seconds and the scanner compared whole seconds. A file rewritten with its size unchanged and a new mtime in the same second as the indexed one was treated as unchanged, and every later snapshot restored the old content. A new mtime_nsec column now holds the nanoseconds within the second that mtime holds, and the scanner compares the full mtime. A local index created before this change lacks the column and is rebuilt with `vaultik database delete` and a full backup. A snapshot made before it cannot be restored by this version. Model: opus-5-5 --- TODO.md | 10 ++ docs/DATAMODEL.md | 3 +- internal/database/files.go | 47 +++++--- internal/database/files_test.go | 109 ++++++++++++++++++ .../database/repository_edge_cases_test.go | 3 +- internal/database/schema/001.sql | 3 +- internal/snapshot/scanner.go | 2 +- internal/vaultik/same_second_rewrite_test.go | 73 ++++++++++++ 8 files changed, 226 insertions(+), 24 deletions(-) create mode 100644 internal/vaultik/same_second_rewrite_test.go diff --git a/TODO.md b/TODO.md index 3801fd1..3383609 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,16 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Made a backup notice a file rewritten with its size + unchanged and a new mtime in the same second as the one in the index + ([issue #226](https://git.eeqj.de/sneak/vaultik/issues/226)). The + `files` table held mtime in whole seconds and the scanner compared + whole seconds, so every later snapshot kept the old content. A new + `mtime_nsec` column holds the nanoseconds within the second that + `mtime` holds, and the scanner compares the full mtime. A local index + created before the change lacks the column and is rebuilt with + `vaultik database delete` and a full backup. + - 2026-10-07: Made taking the process-wide lock atomic ([issue #227](https://git.eeqj.de/sneak/vaultik/issues/227)). The lock read `vaultik.pid`, checked whether that PID was alive and then wrote diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index a1967a3..285c52e 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -36,7 +36,8 @@ Stores metadata about files in the filesystem being backed up. **Columns:** - `id` (TEXT PRIMARY KEY) - UUID for the file record - `path` (TEXT NOT NULL UNIQUE) - Absolute file path -- `mtime` (INTEGER NOT NULL) - Modification time as Unix timestamp +- `mtime` (INTEGER NOT NULL) - Modification time, whole seconds since the Unix epoch +- `mtime_nsec` (INTEGER NOT NULL) - Nanoseconds within that second, 0 to 999999999 - `size` (INTEGER NOT NULL) - File size in bytes - `mode` (INTEGER NOT NULL) - Unix file permissions and type - `uid` (INTEGER NOT NULL) - User ID of file owner diff --git a/internal/database/files.go b/internal/database/files.go index 02bd26c..bce0a3b 100644 --- a/internal/database/files.go +++ b/internal/database/files.go @@ -33,11 +33,13 @@ func (r *FileRepository) Create(ctx context.Context, tx *sql.Tx, file *File) err } query := ` - INSERT INTO files (id, path, source_path, mtime, size, mode, uid, gid, link_target) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + INSERT INTO files + (id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET source_path = excluded.source_path, mtime = excluded.mtime, + mtime_nsec = excluded.mtime_nsec, size = excluded.size, mode = excluded.mode, uid = excluded.uid, @@ -54,16 +56,19 @@ func (r *FileRepository) Create(ctx context.Context, tx *sql.Tx, file *File) err if tx != nil { LogSQL("Execute", query, file.ID.String(), file.Path.String(), file.SourcePath.String(), - file.MTime.Unix(), file.Size, file.Mode, file.UID, file.GID, + file.MTime.Unix(), file.MTime.Nanosecond(), + file.Size, file.Mode, file.UID, file.GID, file.LinkTarget.String()) err = tx.QueryRowContext(ctx, query, file.ID.String(), file.Path.String(), file.SourcePath.String(), - file.MTime.Unix(), file.Size, file.Mode, file.UID, file.GID, + file.MTime.Unix(), file.MTime.Nanosecond(), + file.Size, file.Mode, file.UID, file.GID, file.LinkTarget.String()).Scan(&idStr) } else { err = r.db.QueryRowWithLog(ctx, query, file.ID.String(), file.Path.String(), file.SourcePath.String(), - file.MTime.Unix(), file.Size, file.Mode, file.UID, file.GID, + file.MTime.Unix(), file.MTime.Nanosecond(), + file.Size, file.Mode, file.UID, file.GID, file.LinkTarget.String()).Scan(&idStr) } @@ -84,7 +89,7 @@ func (r *FileRepository) Create(ctx context.Context, tx *sql.Tx, file *File) err // in the index. func (r *FileRepository) GetByPath(ctx context.Context, path string) (*File, error) { query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files WHERE path = ? ` @@ -104,7 +109,7 @@ func (r *FileRepository) GetByPath(ctx context.Context, path string) (*File, err // GetByID retrieves a file by its UUID func (r *FileRepository) GetByID(ctx context.Context, id types.FileID) (*File, error) { query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files WHERE id = ? ` @@ -127,7 +132,7 @@ func (r *FileRepository) GetByPathTx( ctx context.Context, tx *sql.Tx, path string, ) (*File, error) { query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files WHERE path = ? ` @@ -158,13 +163,14 @@ func (r *FileRepository) ListModifiedSince( ctx context.Context, since time.Time, ) ([]*File, error) { query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files - WHERE mtime >= ? + WHERE (mtime, mtime_nsec) >= (?, ?) ORDER BY path ` - rows, err := r.db.conn.QueryContext(ctx, query, since.Unix()) + rows, err := r.db.conn.QueryContext(ctx, query, + since.Unix(), since.Nanosecond()) if err != nil { return nil, fmt.Errorf("querying files: %w", err) } @@ -239,7 +245,7 @@ func (r *FileRepository) ListUnderPath( // LIKE would ignore ASCII case and treat _ and % in path as wildcards. query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files WHERE path = ? OR substr(path, 1, length(?)) = ? ORDER BY path @@ -324,7 +330,7 @@ func (r *FileRepository) ListIDsWithChunksNotInUploadedBlobs( // ListAll returns all files in the database func (r *FileRepository) ListAll(ctx context.Context) ([]*File, error) { query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files ORDER BY path ` @@ -365,7 +371,7 @@ func (r *FileRepository) CreateBatch( } // Each files row binds this many SQL variables. - const fileCols = 9 + const fileCols = 10 // Batch at 100 rows to be safe with SQLite's variable limit. const batchSize = 100 @@ -376,7 +382,7 @@ func (r *FileRepository) CreateBatch( batch := files[i:end] query := `INSERT INTO files - (id, path, source_path, mtime, size, mode, uid, gid, link_target) + (id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target) VALUES ` args := make([]any, 0, len(batch)*fileCols) @@ -388,11 +394,12 @@ func (r *FileRepository) CreateBatch( querySb325.WriteString(", ") } - querySb325.WriteString("(?, ?, ?, ?, ?, ?, ?, ?, ?)") + querySb325.WriteString("(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") args = append(args, f.ID.String(), f.Path.String(), f.SourcePath.String(), - f.MTime.Unix(), f.Size, f.Mode, f.UID, f.GID, + f.MTime.Unix(), f.MTime.Nanosecond(), + f.Size, f.Mode, f.UID, f.GID, f.LinkTarget.String()) } @@ -401,6 +408,7 @@ func (r *FileRepository) CreateBatch( query += ` ON CONFLICT(path) DO UPDATE SET source_path = excluded.source_path, mtime = excluded.mtime, + mtime_nsec = excluded.mtime_nsec, size = excluded.size, mode = excluded.mode, uid = excluded.uid, @@ -460,7 +468,7 @@ func (r *FileRepository) scanFileFrom(row fileRowScanner) (*File, error) { var ( file File idStr, pathStr, sourcePathStr string - mtimeUnix int64 + mtimeUnix, mtimeNsec int64 linkTarget sql.NullString ) @@ -469,6 +477,7 @@ func (r *FileRepository) scanFileFrom(row fileRowScanner) (*File, error) { &pathStr, &sourcePathStr, &mtimeUnix, + &mtimeNsec, &file.Size, &file.Mode, &file.UID, @@ -487,7 +496,7 @@ func (r *FileRepository) scanFileFrom(row fileRowScanner) (*File, error) { file.Path = types.FilePath(pathStr) file.SourcePath = types.SourcePath(sourcePathStr) - file.MTime = time.Unix(mtimeUnix, 0).UTC() + file.MTime = time.Unix(mtimeUnix, mtimeNsec).UTC() if linkTarget.Valid { file.LinkTarget = types.FilePath(linkTarget.String) } diff --git a/internal/database/files_test.go b/internal/database/files_test.go index 23f33b1..8153766 100644 --- a/internal/database/files_test.go +++ b/internal/database/files_test.go @@ -252,6 +252,115 @@ func TestFileRepositorySymlink(t *testing.T) { } } +// An mtime after 2262 or before 1678 does not fit in int64 nanoseconds +// since the epoch, and must still come back from the database unchanged. +func TestFileRepositoryMTimeOutsideInt64NanosecondRange(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repo := database.NewFileRepository(db) + + mtimes := []time.Time{ + time.Date(2300, time.January, 1, 0, 0, 0, 123456789, time.UTC), + time.Date(1601, time.January, 1, 0, 0, 0, 987654321, time.UTC), + } + + for _, mtime := range mtimes { + created := &database.File{ + Path: types.FilePath("/created-" + mtime.Format(time.RFC3339Nano)), + MTime: mtime, + } + + err := repo.Create(ctx, nil, created) + if err != nil { + t.Fatalf("failed to create file: %v", err) + } + + batched := &database.File{ + ID: types.NewFileID(), + Path: types.FilePath("/batched-" + mtime.Format(time.RFC3339Nano)), + MTime: mtime, + } + + err = repo.CreateBatch(ctx, nil, []*database.File{batched}) + if err != nil { + t.Fatalf("failed to batch create file: %v", err) + } + + for _, path := range []types.FilePath{created.Path, batched.Path} { + retrieved, err := repo.GetByPath(ctx, path.String()) + if err != nil { + t.Fatalf("failed to get file: %v", err) + } + + if !retrieved.MTime.Equal(mtime) { + t.Errorf("%s: mtime got %v, want %v", + path, retrieved.MTime, mtime) + } + } + } +} + +// A file already in the index and rewritten within the same second must get +// its new nanoseconds stored, through both Create and CreateBatch. +func TestFileRepositoryUpsertMTimeInSameSecond(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repo := database.NewFileRepository(db) + + indexed := time.Date(2026, time.October, 7, 12, 0, 0, 100000000, time.UTC) + rewritten := indexed.Add(800 * time.Millisecond) + + tests := []struct { + name string + upsert func(file *database.File) error + }{ + {"Create", func(file *database.File) error { + return repo.Create(ctx, nil, file) + }}, + {"CreateBatch", func(file *database.File) error { + return repo.CreateBatch(ctx, nil, []*database.File{file}) + }}, + } + + for _, tt := range tests { + file := &database.File{ + ID: types.NewFileID(), + Path: types.FilePath("/" + tt.name), + MTime: indexed, + } + + err := tt.upsert(file) + if err != nil { + t.Fatalf("%s: failed to create file: %v", tt.name, err) + } + + file.MTime = rewritten + + err = tt.upsert(file) + if err != nil { + t.Fatalf("%s: failed to update file: %v", tt.name, err) + } + + retrieved, err := repo.GetByPath(ctx, file.Path.String()) + if err != nil { + t.Fatalf("%s: failed to get file: %v", tt.name, err) + } + + if !retrieved.MTime.Equal(rewritten) { + t.Errorf("%s: mtime got %v, want %v", + tt.name, retrieved.MTime, rewritten) + } + } +} + func TestFileRepositoryTransaction(t *testing.T) { t.Parallel() diff --git a/internal/database/repository_edge_cases_test.go b/internal/database/repository_edge_cases_test.go index a4cf9f7..59f85ca 100644 --- a/internal/database/repository_edge_cases_test.go +++ b/internal/database/repository_edge_cases_test.go @@ -606,8 +606,7 @@ func TestTimezoneHandling(t *testing.T) { t.Skip("timezone not available") } - // Use Truncate to remove sub-second precision since we store as Unix timestamps - nyTime := time.Now().In(loc).Truncate(time.Second) + nyTime := time.Now().In(loc) file := &File{ Path: "/timezone-test.txt", MTime: nyTime, diff --git a/internal/database/schema/001.sql b/internal/database/schema/001.sql index 944c3a6..243c0f8 100644 --- a/internal/database/schema/001.sql +++ b/internal/database/schema/001.sql @@ -6,7 +6,8 @@ CREATE TABLE IF NOT EXISTS files ( id TEXT PRIMARY KEY, -- UUID path TEXT NOT NULL UNIQUE, source_path TEXT NOT NULL DEFAULT '', -- The source directory this file came from (for restore path stripping) - mtime INTEGER NOT NULL, + mtime INTEGER NOT NULL, -- whole seconds since the Unix epoch + mtime_nsec INTEGER NOT NULL, -- nanoseconds within that second, 0 to 999999999 size INTEGER NOT NULL, mode INTEGER NOT NULL, uid INTEGER NOT NULL, diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 6676f6e..24fcaa7 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -1221,7 +1221,7 @@ func (s *Scanner) checkFileInMemory( // Check if file has changed if existingFile.Size != file.Size || - existingFile.MTime.Unix() != file.MTime.Unix() || + !existingFile.MTime.Equal(file.MTime) || existingFile.Mode != file.Mode || existingFile.UID != file.UID || existingFile.GID != file.GID { diff --git a/internal/vaultik/same_second_rewrite_test.go b/internal/vaultik/same_second_rewrite_test.go new file mode 100644 index 0000000..71ca958 --- /dev/null +++ b/internal/vaultik/same_second_rewrite_test.go @@ -0,0 +1,73 @@ +package vaultik_test + +import ( + "bytes" + "context" + "path/filepath" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// A file rewritten with its size unchanged and a new mtime in the same +// second as the mtime the index holds must still be backed up. See +// https://git.eeqj.de/sneak/vaultik/issues/226. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestBackupOfSameSecondRewriteRestoresNewContent(t *testing.T) { + log.Initialize(log.Config{}) + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := filepath.Join(tempDir, "remote") + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + rewrittenPath := filepath.Join(dataDir, "small.txt") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, dataDir) + cfg := changedFileConfig(dataDir, dbPath) + + firstMTime := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC). + Add(100 * time.Millisecond) + secondMTime := firstMTime.Add(800 * time.Millisecond) + + require.NoError(t, fs.Chtimes(rewrittenPath, firstMTime, firstMTime)) + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, "first")) + + // Upper-casing ASCII text keeps its size. + files[rewrittenPath] = bytes.ToUpper(files[rewrittenPath]) + require.NoError(t, afero.WriteFile(fs, rewrittenPath, files[rewrittenPath], 0o644)) + require.NoError(t, fs.Chtimes(rewrittenPath, secondMTime, secondMTime)) + + require.NoError(t, backUp(v, "second")) + + id := localSnapshotID(ctx, t, repos, "second") + require.NoError(t, db.Close()) + + reader := newReaderVaultik(ctx, cfg, store, nil, fs) + require.NoError(t, reader.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Verify: true, + })) + + assertRestoredTree(t, fs, restoreDir, files) +} From 5d1118d143f77821ff2744b1b02c70031cf5968a Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 09:29:19 +0200 Subject: [PATCH 025/121] Quote a string setting that YAML would read as a number (closes #229) config set wrote every value as an unquoted YAML scalar, and config.Load reads the file through untyped YAML, so an access key 00112233 loaded as 38043 and a hostname 007 as 7. config set now looks the key up in config.Config by the fields' yaml tags. A string setting is tagged !!str, which the encoder quotes wherever YAML would read a number or a boolean. Other settings stay unquoted, so compression_level 9 is still a number. A value that is not valid UTF-8 stays untagged and is written as !!binary, which loads back unchanged. Judgement call: the type comes from reflection over config.Config. Model: opus-5-5 --- TODO.md | 8 +++ internal/cli/config.go | 55 +++++++++++++++++++ internal/cli/config_test.go | 105 ++++++++++++++++++++++++++++++++++++ 3 files changed, 168 insertions(+) diff --git a/TODO.md b/TODO.md index 3383609..1e1fdaa 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,14 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Made `config set` keep a string that looks like a number + ([issue #229](https://git.eeqj.de/sneak/vaultik/issues/229)). It wrote + every value unquoted, and `config.Load` reads the file through untyped + YAML, so an access key `00112233` loaded as `38043` and a hostname `007` + as `7`. A value for a string setting in `config.Config` is now tagged as + a YAML string, which the file quotes wherever YAML would read a number or + a boolean; other settings are still written unquoted. + - 2026-10-07: Made a backup notice a file rewritten with its size unchanged and a new mtime in the same second as the one in the index ([issue #226](https://git.eeqj.de/sneak/vaultik/issues/226)). The diff --git a/internal/cli/config.go b/internal/cli/config.go index a7444f8..b00a602 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -7,11 +7,14 @@ import ( "os" "os/exec" "path/filepath" + "reflect" "strconv" "strings" + "unicode/utf8" "github.com/spf13/cobra" "gopkg.in/yaml.v3" + "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/ui" ) @@ -31,6 +34,9 @@ const configDirMode = 0o755 // yaml.Marshal's 4-space default. const configYAMLIndent = 2 +// yamlStringTag is YAML's tag for a string scalar. +const yamlStringTag = "!!str" + var ( errConfigExists = errors.New("config file already exists") errEmptyConfig = errors.New("empty config file") @@ -583,9 +589,58 @@ func yamlPathSet(root *yaml.Node, keys []string, value string) error { } } + // config.Load reads the file through untyped YAML, which turns an + // unquoted 00112233 into the number 38043 and 1e5 into 100000. Tagging + // a string setting as a string makes the encoder quote such a value. + // Other settings stay unquoted, so compression_level 9 is a number. + // The encoder refuses to write a value that is not valid UTF-8 as a + // string. Left untagged, such a value is written as base64 !!binary and + // loads back unchanged. + if configKeyIsString(keys) && utf8.ValidString(value) { + node.Tag = yamlStringTag + } + return nil } +// configKeyIsString reports whether the dotted key names a string in +// config.Config, following the fields' yaml tags, as s3.access_key_id and +// snapshots.home.exclude.0 do. +func configKeyIsString(keys []string) bool { + typ := reflect.TypeFor[config.Config]() + + for _, key := range keys { + switch { + case typ.Kind() == reflect.Map || typ.Kind() == reflect.Slice: + // The key is a snapshot name or a list index. + typ = typ.Elem() + case typ.Kind() == reflect.Struct: + field, ok := yamlField(typ, key) + if !ok { + return false + } + + typ = field.Type + default: + return false + } + } + + return typ.Kind() == reflect.String +} + +// yamlField returns the field of struct type typ whose yaml tag names key. +func yamlField(typ reflect.Type, key string) (reflect.StructField, bool) { + for field := range typ.Fields() { + name, _, _ := strings.Cut(field.Tag.Get("yaml"), ",") + if name == key { + return field, true + } + } + + return reflect.StructField{}, false +} + // yamlSetInMapping resolves (creating if needed) the value node for key // within a mapping node, setting it to value when it is the final path // element, and returns the node to descend into. diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go index 4e3f7e2..f7b9eb2 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -4,6 +4,7 @@ import ( "bytes" "os" "path/filepath" + "strconv" "strings" "testing" @@ -94,6 +95,110 @@ func TestConfigSetRecipientOnFreshConfig(t *testing.T) { } } +// TestConfigSetStringLooksLikeNumber sets string settings to values that +// YAML reads as numbers or booleans when they are unquoted, and checks that +// config.Load returns each one unchanged. +func TestConfigSetStringLooksLikeNumber(t *testing.T) { + t.Parallel() + + tests := []struct { + key string + value string + field func(cfg *config.Config) string + }{ + {"s3.access_key_id", "00112233", + func(cfg *config.Config) string { return cfg.S3.AccessKeyID }}, + {"s3.secret_access_key", "12345678901234567890123456789012", + func(cfg *config.Config) string { return cfg.S3.SecretAccessKey }}, + {"hostname", "007", + func(cfg *config.Config) string { return cfg.Hostname }}, + {"s3.prefix", "1e5", + func(cfg *config.Config) string { return cfg.S3.Prefix }}, + {"s3.bucket", "true", + func(cfg *config.Config) string { return cfg.S3.Bucket }}, + {"s3.region", "FALSE", + func(cfg *config.Config) string { return cfg.S3.Region }}, + {"snapshots.home.exclude.0", "1.10", + func(cfg *config.Config) string { return cfg.Snapshots["home"].Exclude[0] }}, + } + + for _, tt := range tests { + t.Run(tt.key+"="+tt.value, func(t *testing.T) { + t.Parallel() + + cfg := loadAfterConfigSet(t, tt.key, tt.value) + + got := tt.field(cfg) + if got != tt.value { + t.Errorf("%s = %q after config set %q", tt.key, got, tt.value) + } + }) + } +} + +// TestConfigSetNonUTF8Path checks that config set still accepts a value that +// is not valid UTF-8, such as a path with a Latin-1 file name, and that +// config.Load returns it unchanged. +func TestConfigSetNonUTF8Path(t *testing.T) { + t.Parallel() + + const dir = "/srv/caf\xe9" + + cfg := loadAfterConfigSet(t, "snapshots.home.paths.0", dir) + + got := cfg.Snapshots["home"].Paths[0] + if got != dir { + t.Errorf("snapshots.home.paths.0 = %q, want %q", got, dir) + } +} + +// TestConfigSetNumberStaysNumber checks that a number set for an integer +// setting is still read as a number, not as a quoted string. +func TestConfigSetNumberStaysNumber(t *testing.T) { + t.Parallel() + + const level = 9 + + cfg := loadAfterConfigSet(t, "compression_level", strconv.Itoa(level)) + + if cfg.CompressionLevel != level { + t.Errorf("compression_level = %d, want %d", cfg.CompressionLevel, level) + } +} + +// loadAfterConfigSet writes the file `config init` writes, sets storage_url +// to a local directory so that the file passes validation, applies +// `config set key value` and returns what config.Load reads back. +func loadAfterConfigSet(t *testing.T, key, value string) *config.Config { + t.Helper() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(defaultConfigTemplate), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + out := ui.NewWithColor(&bytes.Buffer{}, false) + + err = writeConfigSet(out, path, "storage_url", "file:///mnt/backups") + if err != nil { + t.Fatalf("config set storage_url: %v", err) + } + + err = writeConfigSet(out, path, key, value) + if err != nil { + t.Fatalf("config set %s: %v", key, err) + } + + cfg, err := config.Load(path) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + + return cfg +} + const testYAML = `# top comment compression_level: 3 age_recipients: From 7696f832589c48edb1b9e1a5830f82b0df2c11ea Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 10:59:26 +0200 Subject: [PATCH 026/121] Leave remote info orphan figures unknown when a manifest is unreadable (closes #228) When a manifest could not be read, remote info skipped it, counted that snapshot's blobs as orphaned and advised running prune. The orphan figures are now unknown in that case, with no prune advice; --json gives them as null and lists the unreadable remote keys in unreadable_manifests. Only a listed manifest.json.zst is read, so a directory without one, as an interrupted backup leaves, keeps the figures known. Names under metadata/ were used unchecked and printed raw. A name that is not a remote key is now skipped with a warning. A manifest under it is not read either, so it also leaves the figures unknown; --json counts such manifests in skipped_manifest_count. Model: opus-5-5 --- README.md | 8 +- TODO.md | 16 +++ internal/vaultik/info.go | 134 +++++++++++++++++----- internal/vaultik/remote_info_test.go | 159 +++++++++++++++++++++++++++ 4 files changed, 291 insertions(+), 26 deletions(-) create mode 100644 internal/vaultik/remote_info_test.go diff --git a/README.md b/README.md index 72097c3..cf9e39d 100644 --- a/README.md +++ b/README.md @@ -390,7 +390,13 @@ recipients, and local database statistics. **`remote info`**: Show storage backend type and location plus detailed remote storage inventory: per-snapshot metadata sizes, blob counts, and -orphaned blob detection. +orphaned blob detection. A name under `metadata/` that is not a remote +key is skipped with a warning and is not printed. If a listed +`manifest.json.zst` cannot be read, or sits under a skipped name, the +orphaned blob figures are reported as unknown; `--json` gives them as +`null`, lists the remote key of each unreadable manifest in +`unreadable_manifests` and counts the manifests under skipped names in +`skipped_manifest_count`. * `--json`: Output as JSON **`remote nuke`**: Delete every snapshot's metadata and every blob from the diff --git a/TODO.md b/TODO.md index 1e1fdaa..0964f46 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,22 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Made `remote info` stop reporting a snapshot's blobs as + orphaned when its manifest cannot be read, and stop printing raw + names from under `metadata/` + ([issue #228](https://git.eeqj.de/sneak/vaultik/issues/228)). A + manifest it failed to read was skipped, so that snapshot's blobs were + counted as orphaned and the report advised running `vaultik prune`. + The orphan figures are now unknown in that case, with no prune + advice, and `--json` gives them as `null` with the unreadable remote + keys in `unreadable_manifests`. A name under `metadata/` that is not + 64 lowercase hex characters is now skipped with a warning instead of + being printed, control characters included. A manifest under a + skipped name is then not read either, so it also leaves the orphan + figures unknown, and `--json` counts such manifests in + `skipped_manifest_count`. A directory with no manifest in it, as left + by an interrupted backup, leaves the figures known. + - 2026-10-07: Made `config set` keep a string that looks like a number ([issue #229](https://git.eeqj.de/sneak/vaultik/issues/229)). It wrote every value unquoted, and `config.Load` reads the file through untyped diff --git a/internal/vaultik/info.go b/internal/vaultik/info.go index 53e6d44..a39659d 100644 --- a/internal/vaultik/info.go +++ b/internal/vaultik/info.go @@ -183,6 +183,11 @@ type SnapshotMetadataInfo struct { TotalSize int64 `json:"total_size"` BlobCount int `json:"blob_count"` BlobsSize int64 `json:"blobs_size"` + + // Set when the listing holds this snapshot's manifest.json.zst. A + // backup interrupted before its manifest upload leaves a directory + // without one, which prune does not treat as a snapshot. + hasManifest bool } // RemoteInfoResult contains all remote storage information @@ -206,9 +211,20 @@ type RemoteInfoResult struct { ReferencedBlobCount int `json:"referenced_blob_count"` ReferencedBlobSize int64 `json:"referenced_blob_size"` - // Orphaned blobs - OrphanedBlobCount int `json:"orphaned_blob_count"` - OrphanedBlobSize int64 `json:"orphaned_blob_size"` + // Orphaned blobs. Both stay nil (null in the JSON) when a manifest + // was listed but not read, since that snapshot's blobs would be + // counted as orphaned. + OrphanedBlobCount *int `json:"orphaned_blob_count"` + OrphanedBlobSize *int64 `json:"orphaned_blob_size"` + + // Remote key of each snapshot whose manifest could not be read + UnreadableManifests []string `json:"unreadable_manifests,omitempty"` + + // Number of manifests not read because the name above them under + // metadata/ is not a remote key. The names themselves are not + // reported: they come from the destination store and may hold + // control characters. + SkippedManifestCount int `json:"skipped_manifest_count,omitempty"` } // RemoteInfo displays information about remote storage @@ -234,16 +250,28 @@ func (v *Vaultik) RemoteInfo(jsonOutput bool) error { v.stdoutf("Scanning snapshot metadata...\n") } - snapshotMetadata, snapshotIDs, err := v.collectSnapshotMetadata() + snapshotMetadata, snapshotIDs, skippedManifestCount, err := v.collectSnapshotMetadata() if err != nil { return err } + result.SkippedManifestCount = skippedManifestCount + if showText { - v.stdoutf("Downloading %d manifest(s)...\n", len(snapshotIDs)) + manifestCount := 0 + + for _, info := range snapshotMetadata { + if info.hasManifest { + manifestCount++ + } + } + + v.stdoutf("Downloading %d manifest(s)...\n", manifestCount) } - referencedBlobs := v.collectReferencedBlobsFromManifests(snapshotIDs, snapshotMetadata) + referencedBlobs, unreadableManifests := v.collectReferencedBlobsFromManifests( + snapshotIDs, snapshotMetadata) + result.UnreadableManifests = unreadableManifests v.populateRemoteInfoResult(result, snapshotMetadata, snapshotIDs, referencedBlobs) @@ -256,7 +284,7 @@ func (v *Vaultik) RemoteInfo(jsonOutput bool) error { "snapshots", result.TotalMetadataCount, "total_blobs", result.TotalBlobCount, "referenced_blobs", result.ReferencedBlobCount, - "orphaned_blobs", result.OrphanedBlobCount) + "unreadable_manifests", len(result.UnreadableManifests)) if jsonOutput { enc := json.NewEncoder(v.Stdout) @@ -273,16 +301,18 @@ func (v *Vaultik) RemoteInfo(jsonOutput bool) error { } // collectSnapshotMetadata scans remote metadata and returns -// per-snapshot info and sorted IDs. +// per-snapshot info, sorted IDs and the number of manifests it skipped +// because the name above them is not a remote key. func (v *Vaultik) collectSnapshotMetadata() ( - map[string]*SnapshotMetadataInfo, []string, error, + map[string]*SnapshotMetadataInfo, []string, int, error, ) { snapshotMetadata := make(map[string]*SnapshotMetadataInfo) + skippedManifestCount := 0 metadataCh := v.Storage.ListStream(v.ctx, "metadata/") for obj := range metadataCh { if obj.Err != nil { - return nil, nil, fmt.Errorf("listing metadata: %w", obj.Err) + return nil, nil, 0, fmt.Errorf("listing metadata: %w", obj.Err) } parts := strings.Split(obj.Key, "/") @@ -291,6 +321,22 @@ func (v *Vaultik) collectSnapshotMetadata() ( } snapshotID := parts[1] + filename := parts[2] + isManifest := filename == "manifest.json.zst" + + // The name comes from the destination store, which is not + // trusted, and is printed in the report. Accept it only in the + // form of a remote key. + if !isBlobHash(snapshotID) { + log.Warn("Skipping non-conforming key under metadata/", + "key", obj.Key) + + if isManifest { + skippedManifestCount++ + } + + continue + } if _, exists := snapshotMetadata[snapshotID]; !exists { snapshotMetadata[snapshotID] = &SnapshotMetadataInfo{SnapshotID: snapshotID} @@ -298,7 +344,10 @@ func (v *Vaultik) collectSnapshotMetadata() ( info := snapshotMetadata[snapshotID] - filename := parts[2] + if isManifest { + info.hasManifest = true + } + if strings.HasPrefix(filename, "manifest") { info.ManifestSize = obj.Size } else if strings.HasPrefix(filename, "db") { @@ -315,17 +364,25 @@ func (v *Vaultik) collectSnapshotMetadata() ( sort.Strings(snapshotIDs) - return snapshotMetadata, snapshotIDs, nil + return snapshotMetadata, snapshotIDs, skippedManifestCount, nil } -// collectReferencedBlobsFromManifests downloads manifests and returns -// referenced blob hashes with sizes. +// collectReferencedBlobsFromManifests downloads the listed manifests +// and returns referenced blob hashes with sizes, and the remote keys +// of the manifests it could not read. func (v *Vaultik) collectReferencedBlobsFromManifests( snapshotIDs []string, snapshotMetadata map[string]*SnapshotMetadataInfo, -) map[string]int64 { +) (map[string]int64, []string) { referencedBlobs := make(map[string]int64) + var unreadable []string + for _, snapshotID := range snapshotIDs { + info := snapshotMetadata[snapshotID] + if !info.hasManifest { + continue + } + // snapshotIDs here are remote keys, taken straight from the // metadata/ listing. downloadManifestByKey is the single reader // for remote manifests; see its doc comment. @@ -333,10 +390,11 @@ func (v *Vaultik) collectReferencedBlobsFromManifests( if err != nil { log.Warn("Failed to read manifest", "snapshot", snapshotID, "error", err) + unreadable = append(unreadable, snapshotID) + continue } - info := snapshotMetadata[snapshotID] info.BlobCount = manifest.BlobCount var blobsSize int64 @@ -349,7 +407,7 @@ func (v *Vaultik) collectReferencedBlobsFromManifests( info.BlobsSize = blobsSize } - return referencedBlobs + return referencedBlobs, unreadable } // populateRemoteInfoResult fills in the result's snapshot and @@ -378,8 +436,9 @@ func (v *Vaultik) populateRemoteInfoResult( } // scanRemoteBlobStorage lists all blobs on remote and computes orphan -// stats. showText is true only when the human report is being printed -// (not --json, not --quiet), gating the progress line. +// stats when every listed manifest was read. showText is true only +// when the human report is being printed (not --json, not --quiet), +// gating the progress line. func (v *Vaultik) scanRemoteBlobStorage( result *RemoteInfoResult, referencedBlobs map[string]int64, showText bool, ) error { @@ -406,13 +465,28 @@ func (v *Vaultik) scanRemoteBlobStorage( result.TotalBlobSize += obj.Size } + // A blob named only by a manifest that could not be read, or by one + // under a skipped name, would be counted as orphaned, so the orphan + // figures stay unknown. + if len(result.UnreadableManifests) > 0 || result.SkippedManifestCount > 0 { + return nil + } + + var ( + orphanedCount int + orphanedSize int64 + ) + for hash, size := range allBlobs { if _, referenced := referencedBlobs[hash]; !referenced { - result.OrphanedBlobCount++ - result.OrphanedBlobSize += size + orphanedCount++ + orphanedSize += size } } + result.OrphanedBlobCount = &orphanedCount + result.OrphanedBlobSize = &orphanedSize + return nil } @@ -465,11 +539,21 @@ func (v *Vaultik) printRemoteInfoTable(result *RemoteInfoResult) { v.stdoutf("Referenced by snapshots: %s (%s)\n", humanize.Comma(int64(result.ReferencedBlobCount)), ubytes(result.ReferencedBlobSize)) - v.stdoutf("Orphaned (unreferenced): %s (%s)\n", - humanize.Comma(int64(result.OrphanedBlobCount)), - ubytes(result.OrphanedBlobSize)) - if result.OrphanedBlobCount > 0 { + if result.OrphanedBlobCount == nil { + v.stdoutf("Orphaned (unreferenced): unknown "+ + "(%d manifest(s) could not be read, "+ + "%d manifest(s) under a non-conforming name skipped)\n", + len(result.UnreadableManifests), result.SkippedManifestCount) + + return + } + + v.stdoutf("Orphaned (unreferenced): %s (%s)\n", + humanize.Comma(int64(*result.OrphanedBlobCount)), + ubytes(*result.OrphanedBlobSize)) + + if *result.OrphanedBlobCount > 0 { v.stdoutf("\nRun 'vaultik prune' to remove orphaned blobs.\n") } } diff --git a/internal/vaultik/remote_info_test.go b/internal/vaultik/remote_info_test.go new file mode 100644 index 0000000..2c6c8da --- /dev/null +++ b/internal/vaultik/remote_info_test.go @@ -0,0 +1,159 @@ +package vaultik_test + +import ( + "bytes" + "context" + "encoding/json" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" +) + +// testBlobHashB is a blob that the manifest written by addRemote does +// not reference. +const testBlobHashB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + +// TestRemoteInfo_UnreadableManifestLeavesOrphansUnknown checks that a +// manifest remote info cannot read makes the orphan figures unknown. A +// blob referenced only by that snapshot would otherwise be counted as +// orphaned, and the report would advise running prune. +func TestRemoteInfo_UnreadableManifestLeavesOrphansUnknown(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + // The readable manifest references blob A only. + env.addRemote(t, listRemoteID, time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + addBlob(t, env.store.testStorer, testBlobHashA) + addBlob(t, env.store.testStorer, testBlobHashB) + + // With every manifest readable, blob B is orphaned. + require.NoError(t, env.v.RemoteInfo(true)) + + var doc map[string]any + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &doc)) + assert.InDelta(t, 1, doc["orphaned_blob_count"], 0) + + // A second snapshot whose manifest cannot be decoded. Blob B may be + // one of its blobs. + unreadableKey := snapshot.RemoteSnapshotKey(listLocalID) + require.NoError(t, env.store.Put(context.Background(), + "metadata/"+unreadableKey+"/manifest.json.zst", + bytes.NewReader([]byte("not a valid manifest")))) + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(false)) + + text := env.stdout.String() + assert.Contains(t, text, "Orphaned (unreferenced): unknown "+ + "(1 manifest(s) could not be read, "+ + "0 manifest(s) under a non-conforming name skipped)") + assert.NotContains(t, text, "vaultik prune") + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(true)) + + doc = nil + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &doc)) + assert.Contains(t, doc, "orphaned_blob_count") + assert.Nil(t, doc["orphaned_blob_count"]) + assert.Contains(t, doc, "orphaned_blob_size") + assert.Nil(t, doc["orphaned_blob_size"]) + assert.Equal(t, []any{unreadableKey}, doc["unreadable_manifests"]) +} + +// TestRemoteInfo_SkipsNonConformingMetadataName checks that a directory +// under metadata/ whose name is not a remote key is left out of the +// report, and that the orphan figures are unknown when it holds a +// manifest. The name comes from the destination store; printed raw, its +// control characters would reach the terminal. Its manifest is not +// read, so a blob only it references would otherwise be counted as +// orphaned. +func TestRemoteInfo_SkipsNonConformingMetadataName(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + env.addRemote(t, listRemoteID, time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + addBlob(t, env.store.testStorer, testBlobHashA) + addBlob(t, env.store.testStorer, testBlobHashB) + require.NoError(t, env.store.Put(context.Background(), + "metadata/\x1b[31mred/manifest.json.zst", + bytes.NewReader([]byte("not a valid manifest")))) + + require.NoError(t, env.v.RemoteInfo(false)) + + text := env.stdout.String() + assert.NotContains(t, text, "\x1b") + assert.NotContains(t, text, "31mred") + assert.Contains(t, text, "Total (1 snapshots)") + assert.Contains(t, text, "Orphaned (unreferenced): unknown "+ + "(0 manifest(s) could not be read, "+ + "1 manifest(s) under a non-conforming name skipped)") + assert.NotContains(t, text, "vaultik prune") + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(true)) + + out := env.stdout.String() + assert.NotContains(t, out, "31mred") + + var doc map[string]any + + require.NoError(t, json.Unmarshal([]byte(out), &doc)) + assert.Contains(t, doc, "orphaned_blob_count") + assert.Nil(t, doc["orphaned_blob_count"]) + assert.Contains(t, doc, "orphaned_blob_size") + assert.Nil(t, doc["orphaned_blob_size"]) + assert.InDelta(t, 1, doc["skipped_manifest_count"], 0) + assert.NotContains(t, doc, "unreadable_manifests") +} + +// TestRemoteInfo_DirectoryWithoutManifestLeavesOrphansKnown checks that +// a directory under metadata/ holding no manifest.json.zst, such as one +// left by a backup interrupted before its manifest upload, leaves the +// orphan figures known. prune does not treat such a directory as a +// snapshot and deletes the blobs the report lists as orphaned. +func TestRemoteInfo_DirectoryWithoutManifestLeavesOrphansKnown(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + env.addRemote(t, listRemoteID, time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + addBlob(t, env.store.testStorer, testBlobHashA) + addBlob(t, env.store.testStorer, testBlobHashB) + + // One directory under a remote key and one under a non-conforming + // name, each holding only a database. + names := []string{snapshot.RemoteSnapshotKey(listLocalID), "\x1b[31mred"} + for _, name := range names { + require.NoError(t, env.store.Put(context.Background(), + "metadata/"+name+"/db.zst.age", + bytes.NewReader([]byte("not a valid database")))) + } + + require.NoError(t, env.v.RemoteInfo(false)) + + text := env.stdout.String() + assert.NotContains(t, text, "\x1b") + assert.Contains(t, text, "Downloading 1 manifest(s)...") + assert.Contains(t, text, "Orphaned (unreferenced): 1 (") + assert.Contains(t, text, "Run 'vaultik prune' to remove orphaned blobs.") + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(true)) + + var doc map[string]any + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &doc)) + assert.InDelta(t, 1, doc["orphaned_blob_count"], 0) + assert.NotContains(t, doc, "unreadable_manifests") + assert.NotContains(t, doc, "skipped_manifest_count") +} From 3fc8a8f2f49a982e986bd3cad410c00e089fab3b Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 12:12:08 +0200 Subject: [PATCH 027/121] Read the snapshot name using the stored hostname (closes #230) A snapshot ID is hostname_name_timestamp, and purge took the name to be everything between the first and the last underscore. With a hostname such as my_host the name home came out as host_home, so `snapshot purge --keep-latest --snapshot home` found nothing to delete and `snapshot create --prune` purged nothing without a message. The name is now read by removing the hostname stored with the snapshot, in the short form the ID uses, so both may contain underscores. This was chosen over rejecting underscores in `hostname` when the config loads, which would also stop restores on such a host. The purge consistency test stored a hostname that did not match its snapshot IDs; it now matches, as it always does in production. Model: opus-5-5 --- TODO.md | 11 ++++ internal/snapshot/snapshot.go | 14 +++-- internal/vaultik/helpers.go | 41 +++++++------- internal/vaultik/helpers_test.go | 28 ++++++++-- .../purge_local_remote_consistency_test.go | 2 +- internal/vaultik/purge_per_name_test.go | 54 ++++++++++++++----- internal/vaultik/snapshot.go | 19 ++++--- 7 files changed, 124 insertions(+), 45 deletions(-) diff --git a/TODO.md b/TODO.md index 0964f46..e8dd4f6 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,17 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Made per-name retention work when the hostname contains `_` + ([issue #230](https://git.eeqj.de/sneak/vaultik/issues/230)). A + snapshot ID is `hostname_name_timestamp`, and the name was read as + everything between the first and the last `_`, so with + `hostname: my_host` the name `home` came out as `host_home`. + `snapshot purge --keep-latest --snapshot home` then printed "No + snapshots to delete", and `snapshot create --prune` purged nothing + without a message. The name is now read using the hostname the + `snapshots` table stores with each snapshot, cut at its first `.` as it + is in the ID. + - 2026-10-07: Made `remote info` stop reporting a snapshot's blobs as orphaned when its manifest cannot be read, and stop printing raw names from under `metadata/` diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 2848864..4e59092 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -105,17 +105,21 @@ func (sm *SnapshotManager) CreateSnapshot( return sm.CreateSnapshotWithName(ctx, hostname, "", version, gitRevision) } +// ShortHostname returns hostname up to its first dot. A snapshot ID starts +// with this form, while the snapshots table stores the full hostname. +func ShortHostname(hostname string) string { + short, _, _ := strings.Cut(hostname, ".") + + return short +} + // CreateSnapshotWithName creates a new snapshot record with an optional // snapshot name. The snapshot ID format is: hostname_name_timestamp or // hostname_timestamp if name is empty. func (sm *SnapshotManager) CreateSnapshotWithName( ctx context.Context, hostname, name, version, gitRevision string, ) (string, error) { - // Use short hostname (strip domain if present) - shortHostname := hostname - if before, _, ok := strings.Cut(hostname, "."); ok { - shortHostname = before - } + shortHostname := ShortHostname(hostname) // Build snapshot ID with optional name timestamp := time.Now().UTC().Format("2006-01-02T15:04:05Z") diff --git a/internal/vaultik/helpers.go b/internal/vaultik/helpers.go index 9ca5045..ff5fe19 100644 --- a/internal/vaultik/helpers.go +++ b/internal/vaultik/helpers.go @@ -9,6 +9,7 @@ import ( "time" "github.com/dustin/go-humanize" + "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/types" ) @@ -46,12 +47,9 @@ const ( year = 365 * day ) -// Snapshot IDs split on "_" into hostname, optional name parts, and a -// trailing timestamp. -const ( - minSnapshotIDParts = 2 - minSnapshotIDNameParts = 3 -) +// A snapshot ID split on "_" has at least a hostname and a trailing +// timestamp. +const minSnapshotIDParts = 2 // SnapshotInfo contains information about a snapshot. // @@ -121,20 +119,27 @@ func parseSnapshotTimestamp(snapshotID string) (time.Time, error) { return timestamp.UTC(), nil } -// parseSnapshotName extracts the snapshot name from a snapshot ID. -// Format: hostname_snapshotname_timestamp — the middle part(s) between hostname -// and the RFC3339 timestamp are the snapshot name (may contain underscores). -// Returns the snapshot name, or empty string if the ID is malformed. -func parseSnapshotName(snapshotID string) string { - parts := strings.Split(snapshotID, "_") - if len(parts) < minSnapshotIDNameParts { - // Format: hostname_timestamp — no snapshot name +// parseSnapshotName extracts the snapshot name from a snapshot ID of the +// form hostname_name_timestamp, given the hostname stored with that +// snapshot. The hostname and the name may both contain underscores, so the +// name is what is left after removing the short hostname and its "_" from +// the front and the last "_" and the timestamp from the end. Returns "" for +// an ID with no name (hostname_timestamp), and for an ID that does not start +// with that hostname, which CreateSnapshotWithName never writes. +func parseSnapshotName(snapshotID, hostname string) string { + prefix := snapshot.ShortHostname(hostname) + "_" + + rest, ok := strings.CutPrefix(snapshotID, prefix) + if !ok { return "" } - // Format: hostname_name_timestamp — middle parts are the name. - // The last part is the RFC3339 timestamp, the first part is the hostname, - // everything in between is the snapshot name (which may itself contain underscores). - return strings.Join(parts[1:len(parts)-1], "_") + + end := strings.LastIndex(rest, "_") + if end < 0 { + return "" + } + + return rest[:end] } // parseDuration parses a duration string with support for human-friendly units: diff --git a/internal/vaultik/helpers_test.go b/internal/vaultik/helpers_test.go index b77b51d..e279319 100644 --- a/internal/vaultik/helpers_test.go +++ b/internal/vaultik/helpers_test.go @@ -11,33 +11,55 @@ func TestParseSnapshotName(t *testing.T) { tests := []struct { name string snapshotID string + hostname string want string }{ { name: "standard format with name", snapshotID: "myhost_home_2026-01-12T14:41:15Z", + hostname: "myhost", want: "home", }, { name: "standard format with different name", snapshotID: "server1_system_2026-02-15T09:30:00Z", + hostname: "server1", want: "system", }, { name: "name with underscores", snapshotID: "myhost_my_special_backup_2026-03-01T00:00:00Z", + hostname: "myhost", want: "my_special_backup", }, + { + name: "hostname with underscores", + snapshotID: "my_host_docs_2026-03-01T00:00:00Z", + hostname: "my_host", + want: "docs", + }, + { + name: "stored hostname with domain", + snapshotID: "my_host_mail_2026-03-01T00:00:00Z", + hostname: "my_host.example.com", + want: "mail", + }, + { + name: "no name", + snapshotID: "my_host_2026-03-01T00:00:00Z", + hostname: "my_host", + want: "", + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - got := parseSnapshotName(tt.snapshotID) + got := parseSnapshotName(tt.snapshotID, tt.hostname) if got != tt.want { - t.Errorf("parseSnapshotName(%q) = %q, want %q", - tt.snapshotID, got, tt.want) + t.Errorf("parseSnapshotName(%q, %q) = %q, want %q", + tt.snapshotID, tt.hostname, got, tt.want) } }) } diff --git a/internal/vaultik/purge_local_remote_consistency_test.go b/internal/vaultik/purge_local_remote_consistency_test.go index bf52b45..f170d2f 100644 --- a/internal/vaultik/purge_local_remote_consistency_test.go +++ b/internal/vaultik/purge_local_remote_consistency_test.go @@ -42,7 +42,7 @@ func setupConsistencyTest( completedAt := startedAt.Add(5 * time.Minute) snap := &database.Snapshot{ ID: types.SnapshotID(id), - Hostname: testHostname, + Hostname: snapHostname, VaultikVersion: testLabel, StartedAt: startedAt, CompletedAt: &completedAt, diff --git a/internal/vaultik/purge_per_name_test.go b/internal/vaultik/purge_per_name_test.go index cfc343b..800480c 100644 --- a/internal/vaultik/purge_per_name_test.go +++ b/internal/vaultik/purge_per_name_test.go @@ -17,8 +17,10 @@ import ( "sneak.berlin/go/vaultik/internal/vaultik" ) -// Snapshot IDs reused across the purge tests. +// Snapshot IDs reused across the purge tests, and the hostname they were +// taken on. const ( + snapHostname = "testhost" snapSystemT0 = "testhost_system_2026-01-01T00:00:00Z" snapHomeT0 = "testhost_home_2026-01-01T00:00:00Z" snapHomeT1 = "testhost_home_2026-01-01T01:00:00Z" @@ -26,9 +28,12 @@ const ( ) // setupPurgeTest creates a Vaultik instance with an in-memory database and mock -// storage pre-populated with the given snapshot IDs. Each snapshot is marked as -// completed. Remote metadata stubs are created so syncWithRemote keeps them. -func setupPurgeTest(t *testing.T, snapshotIDs []string) *vaultik.Vaultik { +// storage pre-populated with the given snapshot IDs, all taken on hostname. +// Each snapshot is marked as completed. Remote metadata stubs are created so +// syncWithRemote keeps them. +func setupPurgeTest( + t *testing.T, hostname string, snapshotIDs []string, +) *vaultik.Vaultik { t.Helper() ctx := context.Background() @@ -51,7 +56,7 @@ func setupPurgeTest(t *testing.T, snapshotIDs []string) *vaultik.Vaultik { completedAt := startedAt.Add(5 * time.Minute) snap := &database.Snapshot{ ID: types.SnapshotID(id), - Hostname: "testhost", + Hostname: types.Hostname(hostname), VaultikVersion: testLabel, StartedAt: startedAt, CompletedAt: &completedAt, @@ -120,7 +125,7 @@ func TestPurgeKeepLatest_PerName(t *testing.T) { "testhost_system_2026-01-01T04:00:00Z", } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -148,7 +153,7 @@ func TestPurgeKeepLatest_SingleName(t *testing.T) { "testhost_home_2026-01-01T02:00:00Z", } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -176,7 +181,7 @@ func TestPurgeKeepLatest_WithNameFilter(t *testing.T) { "testhost_home_2026-01-01T04:00:00Z", } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -198,7 +203,7 @@ func TestPurgeKeepLatest_NoSnapshots(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() - v := setupPurgeTest(t, nil) + v := setupPurgeTest(t, snapHostname, nil) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -216,7 +221,7 @@ func TestPurgeKeepLatest_NameFilterNoMatch(t *testing.T) { "testhost_system_2026-01-01T01:00:00Z", } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -243,7 +248,7 @@ func TestPurgeOlderThan_WithNameFilter(t *testing.T) { snapHomeT0, } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) // Purge only "home" snapshots older than 365 days err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ @@ -277,7 +282,7 @@ func TestPurgeKeepLatest_ThreeNames(t *testing.T) { "testhost_home_2026-01-01T06:00:00Z", } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -291,3 +296,28 @@ func TestPurgeKeepLatest_ThreeNames(t *testing.T) { assert.Contains(t, remaining, "testhost_system_2026-01-01T04:00:00Z") assert.Contains(t, remaining, "testhost_media_2026-01-01T05:00:00Z") } + +// A hostname may contain underscores, so the snapshot name cannot be found +// by splitting the ID at them. A purge by name must still select "docs". +func TestPurgeKeepLatest_HostnameWithUnderscore(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const ( + system = "my_host_system_2026-01-01T00:00:00Z" + docsT1 = "my_host_docs_2026-01-01T01:00:00Z" + docsT2 = "my_host_docs_2026-01-01T02:00:00Z" + ) + + v := setupPurgeTest(t, "my_host", []string{system, docsT1, docsT2}) + + err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + KeepLatest: true, + Force: true, + Names: []string{"docs"}, + }) + require.NoError(t, err) + + assert.ElementsMatch(t, []string{system, docsT2}, + listRemainingSnapshots(t, v)) +} diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 7071bd4..2707516 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -14,6 +14,7 @@ import ( "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/types" ) // Sentinel errors for snapshot management. @@ -495,19 +496,23 @@ func (v *Vaultik) PurgeSnapshotsWithOptions(opts *SnapshotPurgeOptions) error { nameFilter[n] = struct{}{} } - // Collect completed snapshots, applying the name filter. + // Collect completed snapshots and their names, applying the name filter. snapshots := make([]SnapshotInfo, 0, len(dbSnapshots)) + names := make(map[types.SnapshotID]string, len(dbSnapshots)) + for _, s := range dbSnapshots { if s.CompletedAt == nil { continue } + name := parseSnapshotName(s.ID.String(), s.Hostname.String()) if len(nameFilter) > 0 { - if _, ok := nameFilter[parseSnapshotName(s.ID.String())]; !ok { + if _, ok := nameFilter[name]; !ok { continue } } + names[s.ID] = name snapshots = append(snapshots, SnapshotInfo{ ID: s.ID, Timestamp: s.StartedAt, @@ -520,7 +525,7 @@ func (v *Vaultik) PurgeSnapshotsWithOptions(opts *SnapshotPurgeOptions) error { return snapshots[i].Timestamp.After(snapshots[j].Timestamp) }) - toDelete, err := selectSnapshotsToPurge(snapshots, opts) + toDelete, err := selectSnapshotsToPurge(snapshots, names, opts) if err != nil { return err } @@ -538,9 +543,11 @@ func (v *Vaultik) PurgeSnapshotsWithOptions(opts *SnapshotPurgeOptions) error { // selectSnapshotsToPurge applies the purge retention criteria to the // newest-first sorted snapshot list and returns the deletion -// candidates. +// candidates. names maps each snapshot's ID to its snapshot name. func selectSnapshotsToPurge( - snapshots []SnapshotInfo, opts *SnapshotPurgeOptions, + snapshots []SnapshotInfo, + names map[types.SnapshotID]string, + opts *SnapshotPurgeOptions, ) ([]SnapshotInfo, error) { var toDelete []SnapshotInfo @@ -551,7 +558,7 @@ func selectSnapshotsToPurge( seen := make(map[string]bool) for _, snap := range snapshots { - name := parseSnapshotName(snap.ID.String()) + name := names[snap.ID] if seen[name] { toDelete = append(toDelete, snap) From 8b22ae8d42e8daae70428356408c2148fdbc9b1f Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 14:29:10 +0200 Subject: [PATCH 028/121] Pass s3.part_size to the multipart uploader (closes #232) s3.part_size was loaded and defaulted but never reached the S3 client, whose uploader used a fixed 10MiB part. The client now takes the part size from the config, for storage_url and for the s3.* fields, and config load rejects a value below 5MiB or above 5GiB, an explicit 0 included. A blob too large for S3's limit of 10,000 parts at that size is uploaded in larger parts, since the uploader cannot learn the size of the reader it is given. The docs gave the default as 5MB, which the config file reads as 5,000,000 bytes, below the minimum; they now say 5MiB. Judgement call: the 5GiB maximum is enforced along with the 5MiB minimum the issue names. Model: opus-5-5 --- TODO.md | 10 +++ config.example.yml | 9 ++- internal/cli/config.go | 2 +- internal/config/config.go | 17 ++-- internal/config/config_test.go | 116 ++++++++++++++++++++++++++++ internal/s3/client.go | 28 +++++-- internal/s3/client_internal_test.go | 55 +++++++++++++ internal/s3/module.go | 1 + internal/storage/module.go | 2 + internal/storage/s3_test.go | 98 ++++++++++++++++++++++- test/config.yaml | 2 +- 11 files changed, 322 insertions(+), 18 deletions(-) create mode 100644 internal/s3/client_internal_test.go diff --git a/TODO.md b/TODO.md index e8dd4f6..1a1b960 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,16 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Made `s3.part_size` set the multipart upload part size + ([issue #232](https://git.eeqj.de/sneak/vaultik/issues/232)). It was + loaded and defaulted but never passed to the S3 client, whose uploader + used a fixed 10MiB part. It now reaches the uploader for `storage_url` + and for the `s3.*` fields, and a part size S3 refuses, below 5MiB or + above 5GiB, `0` included, fails at config load. A blob too large for + S3's limit of 10,000 parts at the configured size is uploaded in larger + parts. The docs gave the default as `5MB`, which the config file reads + as 5,000,000 bytes, below the minimum; they now say `5MiB`. + - 2026-10-07: Made per-name retention work when the hostname contains `_` ([issue #230](https://git.eeqj.de/sneak/vaultik/issues/230)). A snapshot ID is `hostname_name_timestamp`, and the name was read as diff --git a/config.example.yml b/config.example.yml index 6dc50de..3ad5870 100644 --- a/config.example.yml +++ b/config.example.yml @@ -287,10 +287,11 @@ storage_url: "rclone://myremote/path/to/backups" # #use_ssl: true # # # Part size for multipart uploads -# # Minimum 5MB, affects memory usage during upload -# # Supports: 5MB, 10M, 100MiB, etc. -# # Default: 5MB -# #part_size: 5MB +# # Minimum 5MiB, maximum 5GiB; affects memory usage during upload +# # A blob too large for 10,000 parts of this size gets larger parts +# # Supports: 10MB, 16MiB, 100MiB, etc. (5MB is below the minimum) +# # Default: 5MiB +# #part_size: 5MiB # Path to local SQLite index database # This database tracks file state for incremental backups diff --git a/internal/cli/config.go b/internal/cli/config.go index b00a602..545f81a 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -205,7 +205,7 @@ storage_url: "" # access_key_id: YOUR_ACCESS_KEY # secret_access_key: YOUR_SECRET_KEY # # region: us-east-1 # Default: us-east-1 -# # part_size: 5MB # Multipart upload part size. Default: 5MB +# # part_size: 5MiB # Upload part size, 5MiB to 5GiB. Default: 5MiB # # For the s3:// form, disable TLS with ?ssl=false in the URL, not use_ssl. # ─── OPTIONAL ──────────────────────────────────────────────────────────────── diff --git a/internal/config/config.go b/internal/config/config.go index 1448a32..e5192b0 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -33,11 +33,14 @@ const secretKeyPrefix = "AGE-SECRET-KEY-" const ( defaultBlobSizeLimit = Size(10 * 1024 * 1024 * 1024) // 10GB defaultChunkSize = Size(10 * 1024 * 1024) // 10MB - defaultS3PartSize = Size(5 * 1024 * 1024) // 5MB + defaultS3PartSize = Size(5 * 1024 * 1024) // 5MiB defaultCompressionLevel = 3 minChunkSize = 1024 * 1024 // 1MB minCompressionLevel = 1 maxCompressionLevel = 19 + // S3 accepts a multipart upload part from 5MiB to 5GiB. + minS3PartSize = 5 * 1024 * 1024 + maxS3PartSize = 5 * 1024 * 1024 * 1024 ) // Sentinel validation errors. @@ -55,6 +58,7 @@ var ( "blob_size_limit must be at least the largest chunk the chunker can " + "emit (chunk_size times the FastCDC size spread)") errBadCompression = errors.New("compression_level must be between 1 and 19") + errBadS3PartSize = errors.New("s3.part_size must be between 5MiB and 5GiB") errBadStorageScheme = errors.New( "storage_url must start with s3://, file://, or rclone://") errStorageNotConfigured = errors.New( @@ -244,6 +248,7 @@ func Load(path string) (*Config, error) { ChunkSize: defaultChunkSize, IndexPath: filepath.Join(xdg.DataHome, appName, "index.sqlite"), CompressionLevel: defaultCompressionLevel, + S3: S3Config{PartSize: defaultS3PartSize}, } // Convert smartconfig data to YAML then unmarshal @@ -294,10 +299,6 @@ func Load(path string) (*Config, error) { cfg.S3.Region = "us-east-1" } - if cfg.S3.PartSize == 0 { - cfg.S3.PartSize = defaultS3PartSize - } - // Check config file permissions (warn if world or group readable) //nolint:gosec // G703: config path is operator-supplied by design info, statErr := os.Stat(path) @@ -332,6 +333,7 @@ func Load(path string) (*Config, error) { // (chunk_size times chunker.ChunkSizeSpread), so a single-chunk blob never // exceeds the configured limit // - Compression level must be between 1 and 19 +// - S3 part size must be between 5MiB and 5GiB, the part sizes S3 accepts // // Returns an error describing the first validation failure encountered. func (c *Config) Validate() error { @@ -376,6 +378,11 @@ func (c *Config) Validate() error { return errBadCompression } + if c.S3.PartSize.Int64() < minS3PartSize || + c.S3.PartSize.Int64() > maxS3PartSize { + return errBadS3PartSize + } + return nil } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 52b46ad..c9bb10d 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -166,6 +166,7 @@ func TestValidateBlobSizeLimit(t *testing.T) { ChunkSize: chunkSize, BlobSizeLimit: blobLimit, CompressionLevel: 3, + S3: S3Config{PartSize: defaultS3PartSize}, } } @@ -221,6 +222,120 @@ func TestValidateBlobSizeLimit(t *testing.T) { } } +// TestValidateS3PartSize checks that s3.part_size is held to the part sizes +// S3 accepts, 5MiB to 5GiB, by changing only the part size of the test +// config. "5MB" in the config file is 5,000,000 bytes, below the minimum. +func TestValidateS3PartSize(t *testing.T) { + t.Parallel() + + base, err := Load(os.Getenv("VAULTIK_CONFIG")) + if err != nil { + t.Fatalf("Failed to load config: %v", err) + } + + tests := []struct { + name string + partSize Size + wantErr bool + }{ + { + name: "5MB is rejected", + partSize: 5_000_000, + wantErr: true, + }, + { + name: "one byte below 5MiB is rejected", + partSize: minS3PartSize - 1, + wantErr: true, + }, + { + name: "5MiB is accepted", + partSize: minS3PartSize, + wantErr: false, + }, + { + name: "5GiB is accepted", + partSize: maxS3PartSize, + wantErr: false, + }, + { + name: "one byte above 5GiB is rejected", + partSize: maxS3PartSize + 1, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + cfg := *base + cfg.S3.PartSize = tt.partSize + + err := cfg.Validate() + if tt.wantErr { + if !errors.Is(err, errBadS3PartSize) { + t.Fatalf("Validate() error = %v, want errBadS3PartSize", err) + } + + return + } + + if err != nil { + t.Fatalf("Validate() unexpected error: %v", err) + } + }) + } +} + +// TestLoadS3PartSize checks that a config file without s3.part_size loads +// with the 5MiB default, and that an explicit 0 fails at load like any other +// part size S3 refuses. +func TestLoadS3PartSize(t *testing.T) { + t.Parallel() + + const withoutPartSize = "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file:///tmp/vaultik-test-storage\n" + + writeConfig := func(t *testing.T, text string) string { + t.Helper() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(text), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) + } + + return path + } + + t.Run("absent loads as 5MiB", func(t *testing.T) { + t.Parallel() + + cfg, err := Load(writeConfig(t, withoutPartSize)) + if err != nil { + t.Fatalf("Load() unexpected error: %v", err) + } + + if cfg.S3.PartSize != defaultS3PartSize { + t.Errorf("s3.part_size = %d, want %d", + cfg.S3.PartSize, defaultS3PartSize) + } + }) + + t.Run("0 is rejected", func(t *testing.T) { + t.Parallel() + + _, err := Load(writeConfig(t, withoutPartSize+"s3:\n part_size: 0\n")) + if !errors.Is(err, errBadS3PartSize) { + t.Fatalf("Load() error = %v, want errBadS3PartSize", err) + } + }) +} + // TestValidateAgeRecipients checks that recipients are parsed at config load // (a bad entry fails immediately, not mid-backup) and that no invalid entry — // least of all a pasted secret key — is echoed in the error. An empty list @@ -236,6 +351,7 @@ func TestValidateAgeRecipients(t *testing.T) { ChunkSize: Size(10 * 1024 * 1024), BlobSizeLimit: Size(10 * 1024 * 1024 * 1024), CompressionLevel: 3, + S3: S3Config{PartSize: defaultS3PartSize}, } } diff --git a/internal/s3/client.go b/internal/s3/client.go index 43f8725..f5fc91c 100644 --- a/internal/s3/client.go +++ b/internal/s3/client.go @@ -27,10 +27,12 @@ type Client struct { bucket string prefix string endpoint string + partSize int64 } // Config contains S3 client configuration. -// All fields are required except Prefix, which defaults to an empty string. +// All fields are required except Prefix, which defaults to an empty string, +// and PartSize, where zero means the SDK default of 5 MiB. // A non-empty Prefix is joined to every key with one "/", whether or not // it ends with one. // The Endpoint field should include the protocol (http:// or https://). @@ -41,6 +43,9 @@ type Config struct { AccessKeyID string SecretAccessKey string Region string + // PartSize is the size in bytes of each part of a multipart upload. + // An upload too large for S3's limit of 10,000 parts gets larger parts. + PartSize int64 } // nopLogger is a logger that discards all output. @@ -90,6 +95,7 @@ func NewClient(ctx context.Context, cfg Config) (*Client, error) { bucket: cfg.Bucket, prefix: prefix, endpoint: cfg.Endpoint, + partSize: cfg.PartSize, }, nil } @@ -123,12 +129,9 @@ func (c *Client) PutObjectWithProgress( ) error { fullKey := c.prefix + key - // uploadPartSize is 10MB for better progress granularity. - const uploadPartSize = 10 * 1024 * 1024 - // Create an uploader with the S3 client uploader := manager.NewUploader(c.s3Client, func(u *manager.Uploader) { - u.PartSize = uploadPartSize + u.PartSize = uploadPartSize(c.partSize, size) }) // Create a progress reader that tracks upload progress @@ -149,6 +152,21 @@ func (c *Client) PutObjectWithProgress( return err } +// uploadPartSize returns the part size for an upload of size bytes: the +// configured part size (the SDK default when zero), raised where needed so +// the upload fits in S3's limit of 10,000 parts. The uploader cannot raise +// it itself, because it cannot seek the progress reader to learn its size. +func uploadPartSize(configured, size int64) int64 { + if configured == 0 { + configured = manager.DefaultUploadPartSize + } + + maxParts := int64(manager.MaxUploadParts) + smallestThatFits := (size + maxParts - 1) / maxParts // rounded up + + return max(configured, smallestThatFits) +} + // GetObject downloads an object from S3 with the specified key. // The key is automatically prefixed with the configured prefix. // Returns a ReadCloser containing the object data. The caller must diff --git a/internal/s3/client_internal_test.go b/internal/s3/client_internal_test.go new file mode 100644 index 0000000..552059d --- /dev/null +++ b/internal/s3/client_internal_test.go @@ -0,0 +1,55 @@ +package s3 + +import "testing" + +// TestUploadPartSize checks that an upload too large for 10,000 parts of the +// configured size gets parts just large enough to fit in 10,000. +func TestUploadPartSize(t *testing.T) { + t.Parallel() + + const mib = 1024 * 1024 + + tests := []struct { + name string + configured int64 + size int64 + want int64 + }{ + { + name: "an upload that fits keeps the configured size", + configured: 5 * mib, + size: 10 * 1024 * mib, + want: 5 * mib, + }, + { + name: "exactly 10,000 parts keeps the configured size", + configured: 6 * mib, + size: 10_000 * 6 * mib, + want: 6 * mib, + }, + { + name: "one byte more than 10,000 parts adds a byte to each", + configured: 6 * mib, + size: 10_000*6*mib + 1, + want: 6*mib + 1, + }, + { + name: "zero means the SDK default of 5MiB", + configured: 0, + size: 1, + want: 5 * mib, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got := uploadPartSize(tt.configured, tt.size) + if got != tt.want { + t.Errorf("uploadPartSize(%d, %d) = %d, want %d", + tt.configured, tt.size, got, tt.want) + } + }) + } +} diff --git a/internal/s3/module.go b/internal/s3/module.go index 33b24ba..71f1b88 100644 --- a/internal/s3/module.go +++ b/internal/s3/module.go @@ -28,6 +28,7 @@ func provideClient(lc fx.Lifecycle, cfg *config.Config) (*Client, error) { AccessKeyID: cfg.S3.AccessKeyID, SecretAccessKey: cfg.S3.SecretAccessKey, Region: cfg.S3.Region, + PartSize: cfg.S3.PartSize.Int64(), }) if err != nil { return nil, err diff --git a/internal/storage/module.go b/internal/storage/module.go index 0e400fd..8d00ea1 100644 --- a/internal/storage/module.go +++ b/internal/storage/module.go @@ -99,6 +99,7 @@ func storerFromParsedS3URL(parsed *URL, cfg *config.Config) (Storer, error) { AccessKeyID: cfg.S3.AccessKeyID, SecretAccessKey: cfg.S3.SecretAccessKey, Region: region, + PartSize: cfg.S3.PartSize.Int64(), }) if err != nil { return nil, fmt.Errorf("creating S3 client: %w", err) @@ -134,6 +135,7 @@ func storerFromLegacyS3Config(cfg *config.Config) (Storer, error) { AccessKeyID: cfg.S3.AccessKeyID, SecretAccessKey: cfg.S3.SecretAccessKey, Region: region, + PartSize: cfg.S3.PartSize.Int64(), }) if err != nil { return nil, fmt.Errorf("creating S3 client: %w", err) diff --git a/internal/storage/s3_test.go b/internal/storage/s3_test.go index 2d581f7..2434eb5 100644 --- a/internal/storage/s3_test.go +++ b/internal/storage/s3_test.go @@ -1,11 +1,14 @@ package storage_test import ( + "bytes" "context" "errors" + "net/http" "net/http/httptest" "slices" "strings" + "sync/atomic" "testing" "github.com/johannesboyne/gofakes3" @@ -19,6 +22,13 @@ import ( // s3TestBucket is the bucket created for each in-process S3 server. const s3TestBucket = "test-bucket" +// Credentials for the tests that build a storer from a config.Config. The +// in-process S3 server accepts any. +const ( + s3TestAccessKeyID = "key" + s3TestSecretAccessKey = "secret" +) + // newS3Storer builds an s3:// backend backed by a fresh in-process // S3 server. It reuses the same in-memory S3 harness (gofakes3 + s3mem // over httptest) that internal/s3 and the not-found regression test use, @@ -128,8 +138,8 @@ func TestS3URLPrefixKeyLayout(t *testing.T) { storer, err := storage.NewStorer(&config.Config{ StorageURL: storageURL + "?endpoint=" + srv.URL, S3: config.S3Config{ - AccessKeyID: "key", - SecretAccessKey: "secret", + AccessKeyID: s3TestAccessKeyID, + SecretAccessKey: s3TestSecretAccessKey, }, }) if err != nil { @@ -171,6 +181,90 @@ func TestS3URLPrefixKeyLayout(t *testing.T) { } } +// TestS3UploadUsesConfiguredPartSize checks that s3.part_size reaches the +// multipart uploader, through storage_url and through the s3.* fields. An +// object three parts long must arrive as three parts; at the SDK's default +// of 5 MiB it would arrive as four. +func TestS3UploadUsesConfiguredPartSize(t *testing.T) { + t.Parallel() + + const ( + partSize = 6 * 1024 * 1024 + wantParts = 3 + ) + + backend := s3mem.New() + + err := backend.CreateBucket(s3TestBucket) + if err != nil { + t.Fatalf("create bucket: %v", err) + } + + // Every part of a multipart upload is one request with a partNumber. + var parts atomic.Int32 + + fake := gofakes3.New(backend).Server() + srv := httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Has("partNumber") { + parts.Add(1) + } + + fake.ServeHTTP(w, r) + })) + t.Cleanup(srv.Close) + + cases := []struct { + name string + cfg *config.Config + }{ + { + name: "storage_url", + cfg: &config.Config{ + StorageURL: "s3://" + s3TestBucket + "?endpoint=" + srv.URL, + S3: config.S3Config{ + AccessKeyID: s3TestAccessKeyID, + SecretAccessKey: s3TestSecretAccessKey, + PartSize: partSize, + }, + }, + }, + { + name: "s3.endpoint", + cfg: &config.Config{ + S3: config.S3Config{ + Endpoint: srv.URL, + Bucket: s3TestBucket, + AccessKeyID: s3TestAccessKeyID, + SecretAccessKey: s3TestSecretAccessKey, + PartSize: partSize, + }, + }, + }, + } + + for _, tc := range cases { + parts.Store(0) + + storer, err := storage.NewStorer(tc.cfg) + if err != nil { + t.Fatalf("%s: NewStorer: %v", tc.name, err) + } + + data := bytes.NewReader(make([]byte, wantParts*partSize)) + + err = storer.PutWithProgress( + context.Background(), "blob", data, data.Size(), nil) + if err != nil { + t.Fatalf("%s: PutWithProgress: %v", tc.name, err) + } + + if got := parts.Load(); got != wantParts { + t.Errorf("%s: uploaded in %d parts, want %d", tc.name, got, wantParts) + } + } +} + // listStreamKeys returns the keys ListStream yields under a prefix, and // fails the test on a listing error. func listStreamKeys(t *testing.T, s storage.Storer, prefix string) []string { diff --git a/test/config.yaml b/test/config.yaml index f67577f..cd0e303 100644 --- a/test/config.yaml +++ b/test/config.yaml @@ -19,7 +19,7 @@ s3: secret_access_key: test-secret-key region: us-east-1 use_ssl: true - part_size: 5242880 # 5MB + part_size: 5242880 # 5MiB index_path: /tmp/vaultik-test.sqlite chunk_size: 10MB blob_size_limit: 10GB From d53202eb869c52cd3daceddaad8c62b59822fbb1 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 15:29:07 +0200 Subject: [PATCH 029/121] Fix two misleading messages (closes #240) The warning for a config file that others can read always said the file contained S3 credentials, so a file:// config with none got a false claim. When s3.access_key_id or s3.secret_access_key is set it now says the file may contain them, because Load sees the values only after smartconfig has replaced any ${...} reference, so a set credential need not be in the file. Otherwise it says the file is readable by others. snapshot purge wrapped the listing error, which already starts with "listing remote snapshots:", in that prefix a second time. syncWithRemote now returns it unwrapped, as CleanupLocalSnapshots does. Model: opus-5-5 --- TODO.md | 11 ++ internal/config/config.go | 14 ++- internal/config/config_test.go | 123 +++++++++++++++++++ internal/vaultik/missing_destination_test.go | 21 ++++ internal/vaultik/snapshot.go | 2 +- 5 files changed, 169 insertions(+), 2 deletions(-) diff --git a/TODO.md b/TODO.md index 1a1b960..2f33a00 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,17 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Made two messages say only what is true + ([issue #240](https://git.eeqj.de/sneak/vaultik/issues/240)). A config + file that others can read was warned about as containing S3 + credentials even when it set none, as a `file://` config does. The + warning now says the file may contain S3 credentials only when + `s3.access_key_id` or `s3.secret_access_key` is set, since either may + come from a `${...}` reference rather than the file, and otherwise + says the file is readable by others. `snapshot purge` against a + destination store it could not list gave an error with + `listing remote snapshots:` in it twice; the prefix now appears once. + - 2026-10-07: Made `s3.part_size` set the multipart upload part size ([issue #232](https://git.eeqj.de/sneak/vaultik/issues/232)). It was loaded and defaulted but never passed to the S3 client, whose uploader diff --git a/internal/config/config.go b/internal/config/config.go index e5192b0..e8527d7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -305,7 +305,7 @@ func Load(path string) (*Config, error) { if statErr == nil { mode := info.Mode().Perm() if mode&0044 != 0 { // group or world readable - log.Warn("Config file has insecure permissions (contains S3 credentials)", + log.Warn(cfg.readableByOthersWarning(), "path", path, "mode", fmt.Sprintf("%04o", mode), "recommendation", "chmod 600 "+path) @@ -418,6 +418,18 @@ func (c *Config) setAgeSecretKey() { } } +// readableByOthersWarning is the warning Load logs when others can read +// the config file. It says "may contain" because the S3 credentials are +// seen only after smartconfig has replaced any ${...} reference in the +// file with its value, so a set credential need not be in the file. +func (c *Config) readableByOthersWarning() string { + if c.S3.AccessKeyID != "" || c.S3.SecretAccessKey != "" { + return "Config file is readable by others and may contain S3 credentials" + } + + return "Config file is readable by others" +} + // validateStorage validates storage configuration. // If StorageURL is set, it takes precedence. S3 URLs require credentials. // File URLs don't require any S3 configuration. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index c9bb10d..18d0b20 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -8,6 +8,7 @@ import ( "testing" "sneak.berlin/go/vaultik/internal/chunker" + "sneak.berlin/go/vaultik/internal/log" ) const ( @@ -459,3 +460,125 @@ func TestAgeSecretKeySourceName(t *testing.T) { }) } } + +// loadReadableConfig writes configYAML to a file that others can read, +// loads it, and returns what the logger wrote to stderr meanwhile. The +// logger writes to the os.Stderr it finds when it is initialized, so +// os.Stderr is pointed at a file first. Not parallel-safe: os.Stderr and +// the logger are process-global. +func loadReadableConfig(t *testing.T, configYAML string) string { + t.Helper() + + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yml") + stderrPath := filepath.Join(dir, "stderr") + + err := os.WriteFile(configPath, []byte(configYAML), 0o600) + if err != nil { + t.Fatalf("writing config: %v", err) + } + + //nolint:gosec // G302: the test needs a config file others can read + err = os.Chmod(configPath, 0o644) + if err != nil { + t.Fatalf("chmod config: %v", err) + } + + stderrFile, err := os.Create(stderrPath) //nolint:gosec // G304: test temp path + if err != nil { + t.Fatalf("creating stderr file: %v", err) + } + + previous := os.Stderr + os.Stderr = stderrFile + + log.Initialize(log.Config{}) + + _, loadErr := Load(configPath) + + os.Stderr = previous + + log.Initialize(log.Config{}) + + _ = stderrFile.Close() + + if loadErr != nil { + t.Fatalf("Load() error = %v", loadErr) + } + + captured, err := os.ReadFile(stderrPath) //nolint:gosec // G304: test temp path + if err != nil { + t.Fatalf("reading stderr file: %v", err) + } + + return string(captured) +} + +// TestLoadWarnsReadableConfigWithoutS3Credentials checks that a config +// file others can read, holding no S3 credentials, is warned about +// without a claim that it holds them. +// +//nolint:paralleltest // loadReadableConfig replaces os.Stderr +func TestLoadWarnsReadableConfigWithoutS3Credentials(t *testing.T) { + stderr := loadReadableConfig(t, ` +storage_url: file:///var/backups/vaultik +snapshots: + home: + paths: + - /home +`) + + if !strings.Contains(stderr, "Config file is readable by others") { + t.Errorf("expected a warning that the file is readable by others, got %q", + stderr) + } + + if strings.Contains(stderr, "S3 credentials") { + t.Errorf("warning names S3 credentials the file does not set: %q", stderr) + } +} + +// TestLoadWarnsReadableConfigWithS3Credentials checks that a config file +// others can read and that sets S3 credentials, as values or as ${ENV:...} +// references, is warned about as one that may contain them. +// +//nolint:paralleltest // loadReadableConfig replaces os.Stderr +func TestLoadWarnsReadableConfigWithS3Credentials(t *testing.T) { + t.Setenv("VAULTIK_TEST_ACCESS_KEY_ID", "test-access-key") + t.Setenv("VAULTIK_TEST_SECRET_ACCESS_KEY", "test-secret-key") + + configs := map[string]string{ + "values": ` +storage_url: s3://bucket/prefix?endpoint=s3.example.com +s3: + access_key_id: test-access-key + secret_access_key: test-secret-key +snapshots: + home: + paths: + - /home +`, + "references": ` +storage_url: s3://bucket/prefix?endpoint=s3.example.com +s3: + access_key_id: ${ENV:VAULTIK_TEST_ACCESS_KEY_ID} + secret_access_key: ${ENV:VAULTIK_TEST_SECRET_ACCESS_KEY} +snapshots: + home: + paths: + - /home +`, + } + + for name, configYAML := range configs { + t.Run(name, func(t *testing.T) { + stderr := loadReadableConfig(t, configYAML) + + if !strings.Contains(stderr, + "Config file is readable by others and may contain S3 credentials") { + t.Errorf("expected a warning naming the S3 credentials, got %q", + stderr) + } + }) + } +} diff --git a/internal/vaultik/missing_destination_test.go b/internal/vaultik/missing_destination_test.go index 3869bc7..cc3affa 100644 --- a/internal/vaultik/missing_destination_test.go +++ b/internal/vaultik/missing_destination_test.go @@ -6,6 +6,7 @@ import ( "io/fs" "os" "path/filepath" + "strings" "testing" "github.com/spf13/afero" @@ -153,3 +154,23 @@ func TestPruneKeepsLocalRecordsWhenDestinationMissing(t *testing.T) { require.NoError(t, err) assert.Len(t, snapshots, 1, "prune must delete no local snapshot record") } + +// TestPurgeSaysListingFailedOnceWhenDestinationMissing checks that +// snapshot purge fails on a destination it cannot list, with an error +// that says "listing remote snapshots" once. +// +//nolint:paralleltest // installs the global logger via log.Initialize +func TestPurgeSaysListingFailedOnceWhenDestinationMissing(t *testing.T) { + log.Initialize(log.Config{}) + + ctx := context.Background() + v, _, _ := backUpThenUnplug(ctx, t) + + err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + KeepLatest: true, + Force: true, + }) + require.ErrorIs(t, err, fs.ErrNotExist) + assert.Equal(t, 1, strings.Count(err.Error(), "listing remote snapshots"), + err.Error()) +} diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 2707516..43ab3e1 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -1052,7 +1052,7 @@ func (v *Vaultik) syncWithRemote() error { // every local snapshot record (issue #160). remoteKeys, err := v.listAllRemoteSnapshotKeys() if err != nil { - return fmt.Errorf("listing remote snapshots: %w", err) + return err } remoteKeySet := make(map[string]bool, len(remoteKeys)) From e161343eacc3368bbfb08afcb0ba9376a52f715e Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 17:12:07 +0200 Subject: [PATCH 030/121] Speed up the vaultik and database package tests (closes #235) In the Dockerfile test phase, internal/vaultik spent 23.6s of 31.9s in 36 tests run one at a time. 24 of them were serial only because they call log.Initialize; they now call it before t.Parallel(), so the logger is replaced before any parallel test runs. The 12 still serial change the umask, TMPDIR, os.Stderr or time.Local. TestLargeDatasets took 8.4s of the 9.8s internal/database run by committing each of its 1,500 inserts on its own; it now makes them in one transaction. TestDedupOnlySnapshotRestores gives its second backup its own snapshot name instead of sleeping 1.1s for a new snapshot ID. Model: opus-5-5 --- TODO.md | 10 ++++ .../database/repository_edge_cases_test.go | 50 +++++++++++-------- internal/vaultik/changed_file_restore_test.go | 6 +-- internal/vaultik/fault_injection_test.go | 37 ++++++-------- internal/vaultik/integration_test.go | 21 ++++---- internal/vaultik/missing_destination_test.go | 15 ++---- internal/vaultik/prune_count_test.go | 3 +- internal/vaultik/restore_interrupt_test.go | 3 +- internal/vaultik/restore_skip_errors_test.go | 11 ++-- internal/vaultik/same_second_rewrite_test.go | 3 +- internal/vaultik/snapshot_summary_test.go | 17 ++++--- internal/vaultik/two_path_snapshot_test.go | 3 +- 12 files changed, 90 insertions(+), 89 deletions(-) diff --git a/TODO.md b/TODO.md index 2f33a00..c6b96b1 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,16 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Cut the time the `internal/vaultik` and `internal/database` + tests take ([issue #235](https://git.eeqj.de/sneak/vaultik/issues/235)). + Most of the `internal/vaultik` time went to 24 tests that ran one at a + time only because they call `log.Initialize`; they now call it before + `t.Parallel()`, as the package's other tests do. `TestLargeDatasets` + committed each of its 1,500 inserts on its own and now makes them in + one transaction. `TestDedupOnlySnapshotRestores` gives its second + backup its own snapshot name instead of sleeping past the one-second + timestamp in the snapshot ID. + - 2026-10-07: Made two messages say only what is true ([issue #240](https://git.eeqj.de/sneak/vaultik/issues/240)). A config file that others can read was warned about as containing S3 diff --git a/internal/database/repository_edge_cases_test.go b/internal/database/repository_edge_cases_test.go index 59f85ca..59b54ac 100644 --- a/internal/database/repository_edge_cases_test.go +++ b/internal/database/repository_edge_cases_test.go @@ -3,6 +3,7 @@ package database import ( "context" + "database/sql" "fmt" "strings" "testing" @@ -367,7 +368,7 @@ func verifyBlobNullUploadTS( } // createLargeDatasetFiles creates fileCount files and adds every other -// one to the snapshot. +// one to the snapshot, in one transaction as a backup writes them. func createLargeDatasetFiles( t *testing.T, repos *Repositories, @@ -376,31 +377,38 @@ func createLargeDatasetFiles( ) { t.Helper() - ctx := context.Background() start := time.Now() - for i := range fileCount { - file := &File{ - Path: types.FilePath(fmt.Sprintf("/large/file%05d.txt", i)), - MTime: time.Now(), - Size: int64(i * 1024), - Mode: 0644, - UID: uint32(1000 + (i % 10)), - GID: uint32(1000 + (i % 10)), - } + err := repos.WithTx(context.Background(), + func(ctx context.Context, tx *sql.Tx) error { + for i := range fileCount { + file := &File{ + Path: types.FilePath(fmt.Sprintf("/large/file%05d.txt", i)), + MTime: time.Now(), + Size: int64(i * 1024), + Mode: 0644, + UID: uint32(1000 + (i % 10)), + GID: uint32(1000 + (i % 10)), + } - err := repos.Files.Create(ctx, nil, file) - if err != nil { - t.Fatalf("failed to create file %d: %v", i, err) - } + err := repos.Files.Create(ctx, tx, file) + if err != nil { + return fmt.Errorf("creating file %d: %w", i, err) + } - // Add half to snapshot - if i%2 == 0 { - err = repos.Snapshots.AddFileByID(ctx, nil, snapshotID, file.ID) - if err != nil { - t.Fatal(err) + // Add half to snapshot + if i%2 == 0 { + err = repos.Snapshots.AddFileByID(ctx, tx, snapshotID, file.ID) + if err != nil { + return err + } + } } - } + + return nil + }) + if err != nil { + t.Fatal(err) } t.Logf("Created %d files in %v", fileCount, time.Since(start)) diff --git a/internal/vaultik/changed_file_restore_test.go b/internal/vaultik/changed_file_restore_test.go index de61170..01ed0ec 100644 --- a/internal/vaultik/changed_file_restore_test.go +++ b/internal/vaultik/changed_file_restore_test.go @@ -130,10 +130,9 @@ func assertThirdSnapshotRestores( // up, and that snapshot is removed. The first snapshot keeps the file row, // which now lists the appended content's chunks, while removal drops the // blob that held them. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestBackupAfterRemovingNewestSnapshotRestoresChangedFile(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() @@ -178,10 +177,9 @@ func TestBackupAfterRemovingNewestSnapshotRestoresChangedFile(t *testing.T) { // The next run's prune drops that incomplete snapshot and its blob, while // the first snapshot keeps the file row, which now lists the appended // content's chunks. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestBackupAfterInterruptedRunRestoresChangedFile(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() diff --git a/internal/vaultik/fault_injection_test.go b/internal/vaultik/fault_injection_test.go index 594c284..1595151 100644 --- a/internal/vaultik/fault_injection_test.go +++ b/internal/vaultik/fault_injection_test.go @@ -38,11 +38,9 @@ import ( // (https://git.eeqj.de/sneak/vaultik/issues/130) and is not re-tested // here; these tests target the layers above the backend. // -// The tests run serially, not with t.Parallel: each calls -// log.Initialize, which replaces the package-global logger, and a -// backup or restore running concurrently reads that same logger. Under -// -race the two collide. Running one at a time is the same choice -// prune_count_test.go already makes for the same reason. +// log.Initialize replaces the package-global logger that a running +// backup or restore reads, so each test calls it before t.Parallel, +// while no parallel test is running yet. const ( faultChunkSize = int64(64 * 1024) @@ -165,17 +163,19 @@ func newReaderVaultik( // Scenario 3: a stored blob's bytes are flipped before restore reads // them. Restore must fail loudly, and no file must be left on the // restore target holding corrupt content. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestRestoreRejectsCorruptBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + assertRestoreRejectsDamagedBlob(t, faultstore.GetCorrupt, "corrupt") } // Scenario 4: a stored blob is truncated before restore reads it. Same // contract as the corrupt case. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestRestoreRejectsTruncatedBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + assertRestoreRejectsDamagedBlob(t, faultstore.GetTruncate, "truncated") } @@ -188,7 +188,6 @@ func assertRestoreRejectsDamagedBlob( t *testing.T, fault faultstore.GetFault, name string, ) { t.Helper() - log.Initialize(log.Config{}) fs := afero.NewOsFs() tempDir := t.TempDir() @@ -232,10 +231,9 @@ func assertRestoreRejectsDamagedBlob( // Scenario 6: the backend accepts blob uploads and reports success but // stores nothing. verify --deep must catch it. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestDeepVerifyCatchesLyingBackend(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() @@ -285,10 +283,9 @@ func TestDeepVerifyCatchesLyingBackend(t *testing.T) { // Scenario 1a: a blob upload fails partway through. The interrupted run // must not record the blob as uploaded, must not reference it from the // snapshot, and must leave no blob object at the destination. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestInterruptedBlobUploadRecordsNoUploadedBlob(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() @@ -361,10 +358,9 @@ func TestInterruptedBlobUploadRecordsNoUploadedBlob(t *testing.T) { // chunks in a blob that was actually uploaded, so the retry re-chunks and // re-uploads the affected data instead of silently referencing data that // never reached storage. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestBackupRetryAfterInterruptedUploadIsRestorable(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() @@ -426,10 +422,9 @@ func TestBackupRetryAfterInterruptedUploadIsRestorable(t *testing.T) { // covered by TestBackupCompletesOnlyAfterMetadataExport // (https://git.eeqj.de/sneak/vaultik/issues/177); this test exercises the // lower-level export path in isolation. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestBackupSurvivesMetadataExportInterruption(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() @@ -509,10 +504,9 @@ func TestBackupSurvivesMetadataExportInterruption(t *testing.T) { // destination. Rerunning the backup must then prune the incomplete // snapshot, produce a snapshot whose destination metadata and local index // agree, and restore. See https://git.eeqj.de/sneak/vaultik/issues/177. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestBackupCompletesOnlyAfterMetadataExport(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() @@ -685,10 +679,9 @@ func faultScannerFactory( // Scenario 5: the restore target runs out of space mid-file. Restore // must fail with an out-of-space error, and must not leave a truncated // file at the target path presenting as a complete restore. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestRestoreReportsDiskFull(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() osFS := afero.NewOsFs() tempDir := t.TempDir() diff --git a/internal/vaultik/integration_test.go b/internal/vaultik/integration_test.go index 5bb5483..ded2e7e 100644 --- a/internal/vaultik/integration_test.go +++ b/internal/vaultik/integration_test.go @@ -928,17 +928,17 @@ func setupDedupBackupEnv( } } -// runDedupSnapshot creates a "dedup" snapshot, scans dataDir into it, -// completes it, and exports its metadata, returning the snapshot ID and -// scan result. +// runDedupSnapshot creates a snapshot with the given name, scans dataDir +// into it, completes it, and exports its metadata, returning the snapshot +// ID and scan result. func runDedupSnapshot( ctx context.Context, t *testing.T, sm *snapshot.SnapshotManager, scanner *snapshot.Scanner, - hostname, dataDir, dbPath string, + hostname, name, dataDir, dbPath string, ) (string, *snapshot.ScanResult) { t.Helper() - id, err := sm.CreateSnapshotWithName(ctx, hostname, "dedup", "v", "g") + id, err := sm.CreateSnapshotWithName(ctx, hostname, name, "v", "g") require.NoError(t, err) result, err := scanner.Scan(ctx, dataDir, id) @@ -980,16 +980,15 @@ func TestDedupOnlySnapshotRestores(t *testing.T) { // First snapshot — uploads all blobs. _, r1 := runDedupSnapshot(ctx, t, sm, makeScanner(), - cfg.Hostname, dataDir, dbPath) + cfg.Hostname, "first", dataDir, dbPath) require.Positive(t, r1.BlobsCreated, "first snapshot should upload at least one blob") - // Second snapshot — same data, every chunk dedups. Sleep past the - // second-precision timestamp so the snapshot IDs differ. - time.Sleep(1100 * time.Millisecond) - + // Second snapshot — same data, every chunk dedups. Its own name gives + // it a different snapshot ID without waiting for the one-second + // timestamp in the ID to tick over. id2, r2 := runDedupSnapshot(ctx, t, sm, makeScanner(), - cfg.Hostname, dataDir, dbPath) + cfg.Hostname, "second", dataDir, dbPath) require.Equal(t, 0, r2.BlobsCreated, "second snapshot should upload zero new blobs (fully dedup'd)") diff --git a/internal/vaultik/missing_destination_test.go b/internal/vaultik/missing_destination_test.go index cc3affa..e3d3561 100644 --- a/internal/vaultik/missing_destination_test.go +++ b/internal/vaultik/missing_destination_test.go @@ -78,10 +78,9 @@ func backUpThenUnplug( // TestFirstBackupCreatesDestinationDirectory checks that a first backup // to a destination directory that does not exist yet creates it, and // that the destination can be listed afterwards. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestFirstBackupCreatesDestinationDirectory(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() ctx := context.Background() storeDir := filepath.Join(t.TempDir(), "volume", "backup") @@ -96,10 +95,9 @@ func TestFirstBackupCreatesDestinationDirectory(t *testing.T) { // TestListSnapshotsWarnsWhenDestinationMissing checks that snapshot list // warns and shows the local index alone, without reporting the local // snapshot as missing from the destination. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestListSnapshotsWarnsWhenDestinationMissing(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() ctx := context.Background() v, repos, out := backUpThenUnplug(ctx, t) @@ -116,10 +114,9 @@ func TestListSnapshotsWarnsWhenDestinationMissing(t *testing.T) { // TestRemoveSnapshotWarnsWhenDestinationMissing checks that snapshot // remove warns that the metadata could not be removed from the // destination, instead of reporting that it was. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestRemoveSnapshotWarnsWhenDestinationMissing(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() ctx := context.Background() v, repos, out := backUpThenUnplug(ctx, t) @@ -138,10 +135,9 @@ func TestRemoveSnapshotWarnsWhenDestinationMissing(t *testing.T) { // TestPruneKeepsLocalRecordsWhenDestinationMissing checks that prune // fails on a destination it cannot list and deletes no local snapshot // record. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestPruneKeepsLocalRecordsWhenDestinationMissing(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() ctx := context.Background() v, repos, _ := backUpThenUnplug(ctx, t) @@ -158,10 +154,9 @@ func TestPruneKeepsLocalRecordsWhenDestinationMissing(t *testing.T) { // TestPurgeSaysListingFailedOnceWhenDestinationMissing checks that // snapshot purge fails on a destination it cannot list, with an error // that says "listing remote snapshots" once. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestPurgeSaysListingFailedOnceWhenDestinationMissing(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() ctx := context.Background() v, _, _ := backUpThenUnplug(ctx, t) diff --git a/internal/vaultik/prune_count_test.go b/internal/vaultik/prune_count_test.go index fbc3e5d..ab9268f 100644 --- a/internal/vaultik/prune_count_test.go +++ b/internal/vaultik/prune_count_test.go @@ -14,10 +14,9 @@ import ( // the discarded-error bug: getTableCount for a table its query cannot // resolve must not silently become 0. A count that could not be read is // reported as unknown, which a reader can tell apart from an empty table. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestTableCountForReportSurfacesReadFailure(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() ctx := context.Background() diff --git a/internal/vaultik/restore_interrupt_test.go b/internal/vaultik/restore_interrupt_test.go index e8816c5..0625ccb 100644 --- a/internal/vaultik/restore_interrupt_test.go +++ b/internal/vaultik/restore_interrupt_test.go @@ -164,10 +164,9 @@ func scratchEntries(t *testing.T, dir string) []string { // restore while a blob download is in progress. The download fails only // because of the cancel, so Restore must return context.Canceled without // reporting the file that needs the blob as failed. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestRestoreSkipErrorsCancelDuringBlobDownload(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() diff --git a/internal/vaultik/restore_skip_errors_test.go b/internal/vaultik/restore_skip_errors_test.go index bb19ff4..7cbfeff 100644 --- a/internal/vaultik/restore_skip_errors_test.go +++ b/internal/vaultik/restore_skip_errors_test.go @@ -45,9 +45,10 @@ type missingBlobBackup struct { // after one blob of a two-blob snapshot was deleted. Every file stored in // that blob must be reported as failed and left absent, every other file // must be restored intact, and Restore must still return an error. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestRestoreSkipErrorsSkipsFilesOfMissingBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + ctx := context.Background() backup := backupThenDeleteOneBlob(ctx, t) @@ -85,9 +86,10 @@ func TestRestoreSkipErrorsSkipsFilesOfMissingBlob(t *testing.T) { // TestRestoreMissingBlobAbortsWithoutSkipErrors checks that a deleted blob // still ends the restore with an error when SkipErrors is not set. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestRestoreMissingBlobAbortsWithoutSkipErrors(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + ctx := context.Background() backup := backupThenDeleteOneBlob(ctx, t) @@ -107,7 +109,6 @@ func backupThenDeleteOneBlob( ctx context.Context, t *testing.T, ) *missingBlobBackup { t.Helper() - log.Initialize(log.Config{}) fs := afero.NewOsFs() tempDir := t.TempDir() diff --git a/internal/vaultik/same_second_rewrite_test.go b/internal/vaultik/same_second_rewrite_test.go index 71ca958..998330b 100644 --- a/internal/vaultik/same_second_rewrite_test.go +++ b/internal/vaultik/same_second_rewrite_test.go @@ -18,10 +18,9 @@ import ( // A file rewritten with its size unchanged and a new mtime in the same // second as the mtime the index holds must still be backed up. See // https://git.eeqj.de/sneak/vaultik/issues/226. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestBackupOfSameSecondRewriteRestoresNewContent(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() diff --git a/internal/vaultik/snapshot_summary_test.go b/internal/vaultik/snapshot_summary_test.go index a3562f3..3e180b6 100644 --- a/internal/vaultik/snapshot_summary_test.go +++ b/internal/vaultik/snapshot_summary_test.go @@ -54,8 +54,6 @@ type summaryEnv struct { func newSummaryEnv(t *testing.T) *summaryEnv { t.Helper() - log.Initialize(log.Config{}) - fs := afero.NewOsFs() tempDir := t.TempDir() srcDir := filepath.Join(tempDir, "src") @@ -193,9 +191,10 @@ func (e *summaryEnv) dataLine(total, backedUp int64) string { // A first backup stores copy.bin's chunks while backing up a.bin, so // copy.bin's chunks are deduplicated within the run. Each file and byte // is still counted once. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestSnapshotSummaryFirstRun(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + env := newSummaryEnv(t) summary := env.backUp(t, "first", false) @@ -219,9 +218,10 @@ func TestSnapshotSummaryFirstRun(t *testing.T) { // An incremental backup where a.bin's mtime changed but its content did // not: a.bin is backed up again and every one of its chunks is already // stored. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestSnapshotSummaryIncrementalRunWithDeduplicatedChunks(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + env := newSummaryEnv(t) env.backUp(t, "first", false) @@ -251,9 +251,10 @@ func TestSnapshotSummaryIncrementalRunWithDeduplicatedChunks(t *testing.T) { // Under --cron the progress reporter is off; the upload figures must // still reach the summary and the snapshots row. The snapshot has two // paths, each backed up by its own scan. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestSnapshotSummaryCronRunRecordsUploads(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + env := newSummaryEnv(t) summary := env.backUp(t, "split", true) diff --git a/internal/vaultik/two_path_snapshot_test.go b/internal/vaultik/two_path_snapshot_test.go index f20ae4b..06c2fed 100644 --- a/internal/vaultik/two_path_snapshot_test.go +++ b/internal/vaultik/two_path_snapshot_test.go @@ -18,10 +18,9 @@ import ( // A backup without --cron runs the progress reporter while one scanner // scans each path of the snapshot in turn. See // https://git.eeqj.de/sneak/vaultik/issues/253. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestBackupWithoutCronOfTwoPathSnapshotRestoresBothPaths(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() const snapshotName = "data" From d87202fb70757c17c6fda95432f97a46a2139e05 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 17:59:27 +0200 Subject: [PATCH 031/121] Correct doc and help sentences that are false about the code (closes #233) A blob is written whole to a temporary file and uploaded once finished, not streamed to storage. The README, ARCHITECTURE.md and config.example.yml now say a backup needs free temporary space for each blob (twice that for an rclone destination that cannot stream uploads) and for the metadata export's copies of the local index, in $TMPDIR, or partly in /var/tmp when TMPDIR is unset. Also corrected: the snapshot ID format, what restore reads and how incomplete snapshots are removed in docs/DATAMODEL.md, what source_path holds, the index_path default, the config search order in the snapshot create help, what snapshot remove cleans up in the prune help, how the release installs Go, and the script/release and script/fmt-check comments. Model: opus-5-5 --- ARCHITECTURE.md | 10 +++++++--- README.md | 17 +++++++++-------- TODO.md | 16 ++++++++++++++++ config.example.yml | 12 ++++++++++-- docs/DATAMODEL.md | 11 +++++------ internal/cli/prune.go | 8 +++++--- internal/cli/snapshot.go | 5 +++-- internal/database/models.go | 3 +-- internal/database/schema/001.sql | 2 +- internal/snapshot/scanner.go | 10 ++++------ internal/types/types.go | 4 ++-- script/fmt-check | 7 +++++-- script/release | 7 +++---- 13 files changed, 71 insertions(+), 41 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 0541199..b791882 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -54,10 +54,12 @@ The database tracks five primary entities and their relationships: #### File (`database.File`) Represents a file, directory, or symlink in the backup system. Stores metadata needed for restoration: -- Path, source_path (for restore path stripping), mtime +- Path, mtime - Size, mode, ownership (uid, gid) - Symlink target (if applicable) +It also stores `source_path`, the source directory the scan found it under, made absolute and with symlinks resolved. Restore does not read it. + #### Chunk (`database.Chunk`) A content-addressed unit of data. Files are split into variable-size chunks using the FastCDC algorithm: - `ChunkHash`: SHA256 hash of chunk content (primary key) @@ -82,9 +84,11 @@ The final storage unit uploaded to S3. Contains many compressed and encrypted ch Blob creation process: 1. Chunks are accumulated (up to MaxBlobSize, typically 10GB) 2. As each chunk is added, its uncompressed bytes are fed to a running SHA-256 -3. Concurrently, the same bytes are compressed with zstd, then encrypted with age (recipients configured in config), and streamed to storage +3. Concurrently, the same bytes are compressed with zstd, then encrypted with age (recipients configured in config), and written to a temporary file 4. On finalize, the blob's name is the double SHA-256 of the uncompressed contents — `hex(SHA256(SHA256(...)))` — not a hash of the compressed, encrypted bytes -5. Uploaded to `blobs/{hash[0:2]}/{hash[2:4]}/{hash}` +5. The finished file is uploaded to `blobs/{hash[0:2]}/{hash[2:4]}/{hash}` and then deleted + +A backup needs free temporary space, because each blob is written whole to a temporary file before it is uploaded (up to about `blob_size_limit`; an rclone destination that cannot stream uploads needs about twice that) and the metadata export writes copies of the local index. Temporary files go to `$TMPDIR` (default `/tmp`); with `TMPDIR` unset, SQLite writes one of those copies to `/var/tmp`. #### BlobChunk (`database.BlobChunk`) Maps chunks to their position within blobs: diff --git a/README.md b/README.md index cf9e39d..529ebd1 100644 --- a/README.md +++ b/README.md @@ -546,7 +546,7 @@ complete annotated example also lives in | `s3.*` | | Legacy S3 configuration (endpoint, bucket, credentials) | | `exclude` | | Global exclude patterns (applied to all snapshots) | | `chunk_size` | `10MB` | Average chunk size for content-defined chunking | -| `blob_size_limit` | `10GB` | Maximum blob size before splitting. Must be at least four times `chunk_size` (the largest chunk the chunker can emit), otherwise a single-chunk blob could exceed the limit | +| `blob_size_limit` | `10GB` | Maximum blob size before splitting. Must be at least four times `chunk_size` (the largest chunk the chunker can emit), otherwise a single-chunk blob could exceed the limit. A backup needs free temporary space, because each blob is written whole to a temporary file before it is uploaded (up to about `blob_size_limit`; an rclone destination that cannot stream uploads needs about twice that) and the metadata export writes copies of the local index. Temporary files go to `$TMPDIR` (default `/tmp`); with `TMPDIR` unset, SQLite writes one of those copies to `/var/tmp` | | `compression_level` | `3` | zstd compression level (1-19) | | `hostname` | system hostname | Hostname used in snapshot IDs | | `index_path` | platform data dir | Local SQLite index path | @@ -805,7 +805,8 @@ them. We provide: in the `Dockerfile` together. * `script/release` — cross-compile and publish the release artifacts with the pinned `goreleaser`. Refuses a `goreleaser` on `PATH` whose - version is not the pinned one, on the same reasoning as `script/lint`. + version is not the pinned one, because a different version would build + a different release from the same tag. * `script/release-snapshot` — the same build with no publishing and no tagging, into `./dist` * `script/test` — run the test suite by building the `test` phase of @@ -915,14 +916,14 @@ It is passed to `goreleaser` as `GITEA_TOKEN`. The runner's automatic token is deliberately not used: it is not guaranteed to carry release write access. -The Go toolchain that compiles the released binaries comes from an -`actions/setup-go` step pinned by commit sha, reading its version from -`go.mod` (currently `1.26.1`, the same version the `Dockerfile` builder -stage pins by digest). `goreleaser` shells out to `go` for every +The Go toolchain that compiles the released binaries is installed by +`script/install-go`, which downloads the version named by `go.mod` +(currently `1.26.1`, the same version the `Dockerfile` builder stage +pins by digest) and refuses the archive unless its sha256 matches the +value committed in the script. `goreleaser` shells out to `go` for every cross-compile, so without that step the release would either fail outright or ship binaries built by whatever unpinned toolchain the -runner happened to carry — the one unpinned thing in an otherwise -hash-pinned release path. +runner happened to carry. To rehearse the whole build without publishing or tagging anything: diff --git a/TODO.md b/TODO.md index c6b96b1..076aae6 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,22 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Corrected documentation, help text and comments that were + false about the code + ([issue #233](https://git.eeqj.de/sneak/vaultik/issues/233)). A blob + is not streamed to storage. The README, `ARCHITECTURE.md` and + `config.example.yml` now say a backup needs free temporary space, + because each blob is written whole to a temporary file before it is + uploaded (up to about `blob_size_limit`; an rclone destination that + cannot stream uploads needs about twice that) and the metadata export + writes copies of the local index. Temporary files go to `$TMPDIR` + (default `/tmp`); with `TMPDIR` unset, SQLite writes one of those + copies to `/var/tmp`. Also corrected: the snapshot ID format, what restore + reads and how incomplete snapshots are removed in `docs/DATAMODEL.md`, + what `source_path` holds, the `index_path` and config file defaults, + what `snapshot remove` cleans up, how the release gets its Go + toolchain, and the `script/release` and `script/fmt-check` comments. + - 2026-10-07: Cut the time the `internal/vaultik` and `internal/database` tests take ([issue #235](https://git.eeqj.de/sneak/vaultik/issues/235)). Most of the `internal/vaultik` time went to 24 tests that ran one at a diff --git a/config.example.yml b/config.example.yml index 3ad5870..fd76d48 100644 --- a/config.example.yml +++ b/config.example.yml @@ -295,8 +295,10 @@ storage_url: "rclone://myremote/path/to/backups" # Path to local SQLite index database # This database tracks file state for incremental backups -# Default: /var/lib/vaultik/index.sqlite -#index_path: /var/lib/vaultik/index.sqlite +# Default: the platform data directory, e.g. +# macOS: ~/Library/Application Support/vaultik/index.sqlite +# Linux: ~/.local/share/vaultik/index.sqlite +#index_path: /path/to/index.sqlite # Average chunk size for content-defined chunking # Smaller chunks = better deduplication but more metadata @@ -311,6 +313,12 @@ storage_url: "rclone://myremote/path/to/backups" # Chunking uses no secret (the FastCDC parameters are fixed and public). At a # large limit a blob holds hundreds of chunks, so individual chunk lengths are # not visible in its size; lowering the limit toward chunk_size exposes them. +# A backup needs free temporary space, because each blob is written whole to +# a temporary file before it is uploaded (up to about blob_size_limit; an +# rclone destination that cannot stream uploads needs about twice that) and +# the metadata export writes copies of the local index. Temporary files go to +# $TMPDIR (default /tmp); with TMPDIR unset, SQLite writes one of those copies +# to /var/tmp. # Supports: 1GB, 10G, 500MB, 1GiB, etc. # Default: 10GB #blob_size_limit: 10GB diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index 285c52e..bcb9d1c 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -111,7 +111,7 @@ Maps chunks to the blobs that contain them. Tracks backup snapshots. **Columns:** -- `id` (TEXT PRIMARY KEY) - Snapshot ID (format: hostname-YYYYMMDD-HHMMSSZ) +- `id` (TEXT PRIMARY KEY) - Snapshot ID (format: `hostname_name_timestamp`, e.g. `server1_home_2025-06-01T12:00:00Z`: the hostname up to its first `.`, the snapshot name, and an RFC 3339 UTC timestamp) - `hostname` (TEXT) - Hostname where backup was created - `vaultik_version` (TEXT) - Version of Vaultik used - `vaultik_git_revision` (TEXT) - Git revision of Vaultik used @@ -218,8 +218,8 @@ The `{remote-key}` directory name is a one-way hash of the human snapshot ID, so ### 4. Restore Process The restore process doesn't use the local database. Instead: -1. Downloads snapshot metadata from S3 -2. Downloads required blobs based on manifest +1. Downloads and decrypts the snapshot's metadata database (`db.zst.age`) from S3 +2. Downloads the blobs holding the chunks of the files being restored, found through that database's `blob_chunks` table; the manifest is not read 3. Reconstructs files from decrypted and decompressed chunks ### 5. Pruning @@ -232,9 +232,8 @@ The restore process doesn't use the local database. Instead: Before each backup: 1. Query incomplete snapshots (where `completed_at IS NULL`) -2. Check if metadata exists in S3 -3. If no metadata, delete snapshot and all associations -4. Clean up orphaned files, chunks, and blobs +2. Delete each one and all its associations, without checking S3 for its metadata +3. Clean up orphaned files, chunks, and blobs ## Repository Pattern diff --git a/internal/cli/prune.go b/internal/cli/prune.go index ef3cef6..e73d45d 100644 --- a/internal/cli/prune.go +++ b/internal/cli/prune.go @@ -22,9 +22,11 @@ scans every snapshot manifest in the destination store, builds the set of still-referenced blob hashes, and deletes any blob not in that set. -Snapshot create --prune and snapshot remove run the same cleanup -automatically; this command is the manual entry point for the same -work (e.g. after a crashed backup or to reclaim storage).`, +Snapshot create --prune runs the same cleanup automatically; this +command is the manual entry point for the same work (e.g. after a +crashed backup or to reclaim storage). Snapshot remove leaves blobs in +place; run this command afterwards to delete the ones no longer +referenced.`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { // Use unified config resolution diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index fb2dc4d..a9c6e5a 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -66,8 +66,9 @@ func newSnapshotCreateCommand() *cobra.Command { If snapshot names are provided, only those snapshots are created. If no names are provided, all configured snapshots are created. -Config is located at /etc/vaultik/config.yml by default, but can be overridden by -specifying a path using --config or by setting VAULTIK_CONFIG to a path.`, +The config is read from the path given by --config or VAULTIK_CONFIG; +otherwise from the platform config directory (~/.config/vaultik/config.yml +on Linux), then /etc/vaultik/config.yml.`, Args: cobra.ArbitraryArgs, RunE: func(cmd *cobra.Command, args []string) error { // Pass snapshot names from args diff --git a/internal/database/models.go b/internal/database/models.go index 9c23c59..c71b1cd 100644 --- a/internal/database/models.go +++ b/internal/database/models.go @@ -14,8 +14,7 @@ type File struct { ID types.FileID // UUID primary key Path types.FilePath // Absolute path of the file - // SourcePath is the source directory this file came from (used for - // restore path stripping). + // SourcePath is the source directory this file came from. SourcePath types.SourcePath MTime time.Time Size int64 diff --git a/internal/database/schema/001.sql b/internal/database/schema/001.sql index 243c0f8..c07d978 100644 --- a/internal/database/schema/001.sql +++ b/internal/database/schema/001.sql @@ -5,7 +5,7 @@ CREATE TABLE IF NOT EXISTS files ( id TEXT PRIMARY KEY, -- UUID path TEXT NOT NULL UNIQUE, - source_path TEXT NOT NULL DEFAULT '', -- The source directory this file came from (for restore path stripping) + source_path TEXT NOT NULL DEFAULT '', -- The source directory this file came from mtime INTEGER NOT NULL, -- whole seconds since the Unix epoch mtime_nsec INTEGER NOT NULL, -- nanoseconds within that second, 0 to 999999999 size INTEGER NOT NULL, diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 24fcaa7..b611857 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -58,8 +58,8 @@ type Scanner struct { compressionLevel int ageRecipient string snapshotID string // Current snapshot being processed - // currentSourcePath is the source directory being scanned (used for - // restore path stripping). + // currentSourcePath is the source directory being scanned, stored with + // each file record. currentSourcePath string exclude []string // Glob patterns for files/directories to exclude compiledExclude []compiledPattern // Compiled glob patterns @@ -211,7 +211,6 @@ func (s *Scanner) Scan( ctx context.Context, path string, snapshotID string, ) (*ScanResult, error) { s.snapshotID = snapshotID - // Store source path for file records (used during restore) s.currentSourcePath = path result := &ScanResult{ StartTime: time.Now().UTC(), @@ -1198,9 +1197,8 @@ func (s *Scanner) checkFileInMemory( } file := &database.File{ - ID: fileID, - Path: types.FilePath(path), - // Store source directory for restore path stripping + ID: fileID, + Path: types.FilePath(path), SourcePath: types.SourcePath(s.currentSourcePath), MTime: info.ModTime(), Size: info.Size(), diff --git a/internal/types/types.go b/internal/types/types.go index d4dc997..e9fdd72 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -155,8 +155,8 @@ type BlobHash string // FilePath represents an absolute path to a file or directory. type FilePath string -// SourcePath represents the root directory from which files are backed up. -// Used during restore to strip the source prefix from paths. +// SourcePath is the source directory a scan found a file under, made +// absolute and with symlinks resolved. type SourcePath string // Hostname identifies a host machine. diff --git a/script/fmt-check b/script/fmt-check index 84c23df..9a9a333 100755 --- a/script/fmt-check +++ b/script/fmt-check @@ -1,6 +1,9 @@ #!/bin/sh -# script/fmt-check: check formatting (read-only). Same scope as -# script/fmt, but fails instead of writing. +# script/fmt-check: check formatting (read-only). Fails instead of +# writing. It checks every Go file outside .tool, which is more than +# script/fmt formats: `go fmt ./...` skips `testdata` directories and +# files and directories whose names start with `.` or `_`. Fix a file +# only this reports with `gofmt -w`. set -eu ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" diff --git a/script/release b/script/release index 05ec0ae..cdc1b1c 100755 --- a/script/release +++ b/script/release @@ -21,10 +21,9 @@ goreleaser_version() { head -n 1 } -# Resolve the goreleaser to run, on the same rule script/lint uses for -# golangci-lint: a binary on PATH is accepted only when it is exactly -# the pinned version, because a differently versioned tool would -# produce a differently built release from the same tag. Anything else +# Resolve the goreleaser to run. A binary on PATH is accepted only when +# it is exactly the pinned version, because a differently versioned tool +# would produce a differently built release from the same tag. Anything else # comes from .tool/bin, and a missing one is a loud failure naming the # script that installs it rather than a silent fallback. resolve_goreleaser() { From b5389a62b5baf715d5411076a377848197b87868 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 21:59:27 +0200 Subject: [PATCH 032/121] Exit 130 and say so when a command is interrupted (closes #267) Ctrl-C or SIGTERM during snapshot create, restore or verify exited 0 with no error line (1, also silent, under snapshot verify --json), so an unfinished --cron backup looked like a success. RunOperation now records whether op returned while the Vaultik context was still live; a run where it had not by the time RunWithApp returned is interrupted, whatever op returned. It used to look for context.Canceled in op's error, which verify --json does not return. Entry prints "interrupted before the command finished" on stderr for it and returns 130, under --cron and --json too. SIGTERM also gives 130, as the issue asks, not 143. The test does not cover an op still running when the 30s shutdown timeout ends. Model: opus-5-5 --- TODO.md | 9 ++ internal/cli/app.go | 53 +++++-- internal/cli/entry.go | 19 ++- internal/cli/entry_interrupt_test.go | 203 +++++++++++++++++++++++++++ 4 files changed, 266 insertions(+), 18 deletions(-) create mode 100644 internal/cli/entry_interrupt_test.go diff --git a/TODO.md b/TODO.md index 076aae6..4320581 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,15 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Made an interrupted command exit 130 and say so + ([issue #267](https://git.eeqj.de/sneak/vaultik/issues/267)). Ctrl-C + or SIGTERM during `snapshot create`, `snapshot restore` or `snapshot + verify` exited 0 with no error line (`snapshot verify --json` exited + 1, also without one), so a `--cron` run that never finished looked + like a success. A command stopped by either signal now exits 130 and + prints `interrupted before the command finished` on stderr, under + `--cron` and `--json` too. + - 2026-10-07: Corrected documentation, help text and comments that were false about the code ([issue #233](https://git.eeqj.de/sneak/vaultik/issues/233)). A blob diff --git a/internal/cli/app.go b/internal/cli/app.go index 76ba625..889327f 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -206,6 +206,10 @@ func RunApp(ctx context.Context, app *fx.App) error { // RunOperation through cobra to Entry. var errReported = errors.New("operation failed") +// errInterrupted marks an operation that SIGINT or SIGTERM stopped +// before it finished. Entry shows it and returns exitCodeInterrupted. +var errInterrupted = errors.New("interrupted before the command finished") + // RunOperation runs op against the Vaultik instance inside the fx app // and turns a failure into a returned error rather than an os.Exit from // within the goroutine. An os.Exit there skipped main's deferred @@ -220,17 +224,21 @@ var errReported = errors.New("operation failed") // interrupt OnStop cancels op and waits for the goroutine to return, so // op's cleanup (removing decrypted scratch files) runs before the // process exits; the wait is bounded by shutdownTimeout. report is -// called with a non-canceled failure so the caller can show it to the -// user before it becomes errReported. A context cancellation is the -// interrupt path, not a failure: it is neither reported nor counted as -// one. +// called with a failure so the caller can show it to the user before +// it becomes errReported. +// +// The run counts as interrupted unless op returned, without an +// interrupt having cancelled it, before RunWithApp returned. An +// interrupted op is not reported, whatever it returned; RunOperation +// returns errInterrupted instead. func RunOperation( ctx context.Context, opts AppOptions, op func(v *vaultik.Vaultik) error, report func(err error), ) error { var ( - mu sync.Mutex - failed bool + mu sync.Mutex + finished bool // op returned before any interrupt cancelled it + failed bool // op finished with an error ) opts.Invokes = append(opts.Invokes, @@ -241,11 +249,21 @@ func RunOperation( OnStart: func(_ context.Context) error { stop = v.StartOperation(func() { err := op(v) - if err != nil && !errors.Is(err, context.Canceled) { - report(err) + + // Only stop, called from OnStop below, cancels the + // Vaultik context, so a live context means no + // interrupt cancelled op. Check the context, not + // err: an interrupted op need not return + // context.Canceled (`snapshot verify --json` + // returns a verification failure). + if v.Context().Err() == nil { + if err != nil { + report(err) + } mu.Lock() - failed = true + finished = true + failed = err != nil mu.Unlock() } @@ -278,16 +296,23 @@ func RunOperation( return err } - // The goroutine sets failed before triggering the shutdown that lets - // RunWithApp return, so the write is in place by the time we read it. + // RunWithApp returns only after the app was asked to stop, either by + // an interrupt or by the goroutine's Shutdown call. When op finished + // without being cancelled, the goroutine set finished before that + // call. So if finished is unset here, an interrupt stopped the app, + // and op either returned after it was cancelled or is still running + // because the shutdown timed out. mu.Lock() defer mu.Unlock() - if failed { + switch { + case !finished: + return errInterrupted + case failed: return errReported + default: + return nil } - - return nil } // runVaultikApp runs the standard single-operation command lifecycle diff --git a/internal/cli/entry.go b/internal/cli/entry.go index 5736c40..e9d3a6c 100644 --- a/internal/cli/entry.go +++ b/internal/cli/entry.go @@ -15,6 +15,11 @@ import ( // the startup banner. const shortCommitLen = 12 +// exitCodeInterrupted is the exit status of a command that SIGINT or +// SIGTERM stopped. It is 128 plus SIGINT's number, 2, which is what a +// shell reports for a command stopped by Ctrl-C. +const exitCodeInterrupted = 130 + // Entry is the main entry point for the CLI application. // It prints the startup banner to stderr (unless a banner-suppressing // flag is present in os.Args — see bannerSuppressedInArgs), executes the @@ -23,9 +28,10 @@ const shortCommitLen = 12 // The banner goes to stderr because stdout carries only the output the // user asked for, such as a completion script or a `config get` value. // -// It returns the process exit code (0 on success, 1 on error) rather -// than calling os.Exit, so that main's deferred profile writers run -// before the process ends. See run in cmd/vaultik/main.go. +// It returns the process exit code (0 on success, 130 when interrupted, +// 1 on any other error) rather than calling os.Exit, so that main's +// deferred profile writers run before the process ends. See run in +// cmd/vaultik/main.go. func Entry() int { emitStartupBanner(os.Args[1:], os.Stderr) @@ -39,11 +45,16 @@ func Entry() int { // document instead); errReported says so. Printing it again // here would double the error line. // Every other error — bad arguments, a config that would not - // load — reaches Entry unreported, so it is shown here. + // load, an interrupt — reaches Entry unreported, so it is shown + // here. if !errors.Is(err, errReported) { ReportErrorf("%s", err.Error()) } + if errors.Is(err, errInterrupted) { + return exitCodeInterrupted + } + return 1 } diff --git a/internal/cli/entry_interrupt_test.go b/internal/cli/entry_interrupt_test.go new file mode 100644 index 0000000..b11c24b --- /dev/null +++ b/internal/cli/entry_interrupt_test.go @@ -0,0 +1,203 @@ +package cli //nolint:testpackage // shares runEntry and the argument constants + +import ( + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/signal" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/adrg/xdg" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// stalledStoreConfig is hermeticConfig with an s3:// destination store +// in place of the file:// one. The server behind it accepts any +// credentials. +const stalledStoreConfig = `age_recipients: + - age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj +snapshots: + test: + paths: + - %s +storage_url: s3://bucket?endpoint=%s&ssl=false +s3: + access_key_id: key + secret_access_key: secret +index_path: %s +hostname: test-host +` + +// interruptRepeat is how often interruptOnFirstRequest sends SIGINT. +const interruptRepeat = 50 * time.Millisecond + +// TestEntryInterruptedRun sends SIGINT to the test process while a +// command waits on the destination store, and checks that Entry returns +// 130 and prints one line on stderr saying the run was interrupted. The +// store is a local HTTP server that holds every request open, so the +// command is always mid-operation when the signal arrives. The two +// cases cover --cron and --json, which silence other output. +// +// Not parallel: it signals the process and replaces os.Args, os.Stdout, +// os.Stderr and the xdg globals. +// +//nolint:paralleltest // signals the process and replaces process globals +func TestEntryInterruptedRun(t *testing.T) { + for _, testCase := range []struct { + name string + args []string + }{ + { + name: "snapshot create --cron", + args: []string{cmdSnapshot, cmdCreate, "--cron"}, + }, + { + name: "snapshot verify --json", + args: []string{cmdSnapshot, cmdVerify, someSnapshotID, flagJSON}, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + endpoint, requestArrived := startStalledStore(t) + configPath := writeStalledStoreConfig(t, endpoint) + interruptOnFirstRequest(t, requestArrived) + + code, _, stderr := runEntry(t, + append([]string{flagConfig, configPath}, testCase.args...)...) + + assert.Equal(t, 130, code) + assert.Equal(t, 1, + strings.Count(stderr, errInterrupted.Error()), stderr) + }) + } +} + +// interruptOnFirstRequest sends SIGINT to the test process every +// interruptRepeat, from the first request to the destination store until +// the test ends. One signal is not enough: the command can reach the +// store before fx has started catching signals. The test catches SIGINT +// too, so that a signal fx is not catching does not kill the test +// binary. +func interruptOnFirstRequest(t *testing.T, requestArrived <-chan struct{}) { + t.Helper() + + self, err := os.FindProcess(os.Getpid()) + require.NoError(t, err) + + caught := make(chan os.Signal, 1) + signal.Notify(caught, os.Interrupt) + + testEnded := make(chan struct{}) + senderDone := make(chan struct{}) + + // Stop catching SIGINT only after the sender has returned. The sender + // waits for each SIGINT it sends to arrive on caught; one still on + // its way after signal.Stop would kill the test binary. + t.Cleanup(func() { + close(testEnded) + <-senderDone + signal.Stop(caught) + }) + + go func() { + defer close(senderDone) + + select { + case <-requestArrived: + case <-testEnded: + return + } + + ticker := time.NewTicker(interruptRepeat) + defer ticker.Stop() + + for { + // Empty caught, so that the receive below waits for this + // SIGINT rather than an earlier one. + select { + case <-caught: + default: + } + + sendErr := self.Signal(os.Interrupt) + if sendErr != nil { + t.Errorf("sending SIGINT: %v", sendErr) + + return + } + + <-caught + + select { + case <-testEnded: + return + case <-ticker.C: + } + } + }() +} + +// startStalledStore starts an HTTP server that never answers: each +// request is held until the client gives up on it or the test ends. +// It returns the server's host:port and a channel that receives a value +// when the first request arrives. +func startStalledStore(t *testing.T) (string, <-chan struct{}) { + t.Helper() + + requestArrived := make(chan struct{}, 1) + release := make(chan struct{}) + + server := httptest.NewServer(http.HandlerFunc( + func(_ http.ResponseWriter, r *http.Request) { + select { + case requestArrived <- struct{}{}: + default: + } + + select { + case <-r.Context().Done(): + case <-release: + } + })) + + // Cleanups run last-registered first, so release lets any held + // request return before Close waits for it. + t.Cleanup(server.Close) + t.Cleanup(func() { close(release) }) + + return server.Listener.Addr().String(), requestArrived +} + +// writeStalledStoreConfig writes a config whose destination store is the +// server at endpoint and whose snapshot source holds one small file, so +// that `snapshot create` has a blob to upload. Returns the config path. +func writeStalledStoreConfig(t *testing.T, endpoint string) string { + t.Helper() + + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yml") + sourceDir := filepath.Join(dir, "source") + + require.NoError(t, os.Mkdir(sourceDir, 0o750)) + require.NoError(t, os.WriteFile(filepath.Join(sourceDir, "file.txt"), + []byte("contents"), 0o600)) + + contents := fmt.Sprintf(stalledStoreConfig, + sourceDir, endpoint, filepath.Join(dir, "index.sqlite")) + + require.NoError(t, + os.WriteFile(configPath, []byte(contents), configFileMode)) + + // The PID lock lives under xdg.DataHome, which xdg resolves at + // package init; point it at the temp dir so the test neither + // touches nor collides with the real one. + t.Setenv("XDG_DATA_HOME", filepath.Join(dir, "data")) + xdg.Reload() + t.Cleanup(xdg.Reload) + + return configPath +} From 32c4a46b49c68cee35f928107ff69943b9dd7e30 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 7 Oct 2026 22:59:26 +0200 Subject: [PATCH 033/121] Write rclone uploads under a temporary name and move them into place (closes #266) The rclone backend wrote each object straight to its key, so killing an upload to a local or sftp remote left a truncated object there that the next backup trusted. On every remote with a server-side move, an object is now written under a name ending in `.partial` and moved onto its key with rclone's operations.Move, which removes an object already at the key first; drive, dropbox and others will not move onto one. Listings skip `.partial` names. Rclone's own copy also requires the PartialUploads flag; this does not, because hdfs shows a file while it is written without setting it. Remotes without a move are written in place. Model: opus-5-5 --- README.md | 10 + TODO.md | 11 + internal/storage/conformance_test.go | 5 +- internal/storage/file.go | 7 +- internal/storage/file_atomic_test.go | 7 +- internal/storage/rclone.go | 79 +++++-- internal/storage/rclone_test.go | 321 +++++++++++++++++++++++++-- 7 files changed, 404 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 529ebd1..78eaea7 100644 --- a/README.md +++ b/README.md @@ -428,6 +428,16 @@ a local or mounted filesystem. Useful for testing or backing up to a NAS. **Rclone** (`rclone://remote/path`): Uses rclone's 70+ supported cloud providers. Requires rclone to be configured separately (`rclone config`). +An upload cut off part-way leaves nothing under the object's name on S3, which +shows an object only once its upload has completed, and on the local filesystem +backend, which writes a temporary file and renames it into place. Rclone +remotes with a server-side move (local and sftp among them) are written under a +temporary name ending in `.partial` and moved into place. Rclone remotes without +one are written in place: where such a remote shows a file while it is still +being written, a killed upload can leave a truncated object under its name, +which a later backup takes for complete. A leftover `.partial` file is ignored +and can be deleted. + Legacy S3 configuration via `s3.*` fields (endpoint, bucket, prefix, etc.) is still supported for backward compatibility. `storage_url` takes precedence if both are set. diff --git a/TODO.md b/TODO.md index 4320581..fe962f5 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,17 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Stopped a killed rclone upload from leaving a truncated + object under its key + ([issue #266](https://git.eeqj.de/sneak/vaultik/issues/266)). The + rclone backend wrote each object straight to its key, so killing an + upload to a local or sftp remote left a truncated object there; the + next backup found the key with `Stat`, skipped the upload and recorded + a snapshot that could not be restored. On a remote with a server-side + move, an object is now written under a temporary name ending in + `.partial` and moved into place, and listings skip such names. Remotes + without one are still written in place. + - 2026-10-07: Made an interrupted command exit 130 and say so ([issue #267](https://git.eeqj.de/sneak/vaultik/issues/267)). Ctrl-C or SIGTERM during `snapshot create`, `snapshot restore` or `snapshot diff --git a/internal/storage/conformance_test.go b/internal/storage/conformance_test.go index 7282341..e5c35f9 100644 --- a/internal/storage/conformance_test.go +++ b/internal/storage/conformance_test.go @@ -14,8 +14,9 @@ import ( // runStorerConformance is the shared Storer contract. Every backend that // can run in-process is expected to pass it: TestFileStorer runs it against -// file://, TestS3Storer against s3://. A new backend inherits this coverage -// by passing its own constructor, so the contract is defined once. +// file://, TestS3Storer against s3://, TestRcloneStorer against rclone's +// local backend. A new backend inherits this coverage by passing its own +// constructor, so the contract is defined once. // // It exercises the public Storer interface: round-trip, stat, list with // prefix filtering, overwrite, delete, delete-of-missing, and not-found on diff --git a/internal/storage/file.go b/internal/storage/file.go index bcf2c3d..7cb5653 100644 --- a/internal/storage/file.go +++ b/internal/storage/file.go @@ -50,9 +50,10 @@ const storageDirPerm = 0o755 // temp file carrying this suffix and only renames it onto the real key once // the whole object is on disk, so an interrupted write can never leave a // truncated object at the key a later run would Stat and trust as a complete -// blob. List and ListStream skip these files, so a leftover from an -// interrupted write is never listed or trusted as a blob; it is otherwise -// harmless and is overwritten when the same key is written again. +// blob. The rclone backend's upload does the same on remotes with a +// server-side move. List and ListStream skip these files, so a leftover from +// an interrupted write is never listed or trusted as a blob; it is otherwise +// harmless. const tempSuffix = ".partial" // Put stores data at the specified key. diff --git a/internal/storage/file_atomic_test.go b/internal/storage/file_atomic_test.go index 9006695..b9be4e6 100644 --- a/internal/storage/file_atomic_test.go +++ b/internal/storage/file_atomic_test.go @@ -14,6 +14,9 @@ import ( // errStreamInterrupted stands in for an upload cut off mid-stream. var errStreamInterrupted = errors.New("connection reset mid-upload") +// testBlobKey is a key laid out as a blob's key is. +const testBlobKey = "blobs/aa/bb/aabbccddeeff" + // failingReader yields its data once, then fails. type failingReader struct { data []byte @@ -43,7 +46,7 @@ func TestFileStorer_InterruptedWriteLeavesNoTrustedObject(t *testing.T) { } ctx := context.Background() - key := "blobs/aa/bb/aabbccddeeff" + key := testBlobKey err = f.PutWithProgress(ctx, key, &failingReader{data: []byte("partial")}, 4096, nil) if err == nil { @@ -79,7 +82,7 @@ func TestFileStorer_ListSkipsPartialFiles(t *testing.T) { } ctx := context.Background() - realKey := "blobs/aa/bb/aabbccddeeff" + realKey := testBlobKey err = f.Put(ctx, realKey, strings.NewReader("blob-bytes")) if err != nil { diff --git a/internal/storage/rclone.go b/internal/storage/rclone.go index c3a3433..dfc8e1f 100644 --- a/internal/storage/rclone.go +++ b/internal/storage/rclone.go @@ -3,6 +3,7 @@ package storage import ( "bytes" "context" + "crypto/rand" "errors" "fmt" "io" @@ -68,14 +69,7 @@ func (r *RcloneStorer) Put(ctx context.Context, key string, data io.Reader) erro return fmt.Errorf("reading data: %w", err) } - // Upload the object - _, err = operations.Rcat(ctx, r.fsys, key, - io.NopCloser(bytes.NewReader(buf)), time.Now(), nil) - if err != nil { - return fmt.Errorf("uploading object: %w", err) - } - - return nil + return r.upload(ctx, key, bytes.NewReader(buf)) } // PutWithProgress stores data with progress reporting. @@ -89,13 +83,7 @@ func (r *RcloneStorer) PutWithProgress( callback: progress, } - // Upload the object - _, err := operations.Rcat(ctx, r.fsys, key, io.NopCloser(pr), time.Now(), nil) - if err != nil { - return fmt.Errorf("uploading object: %w", err) - } - - return nil + return r.upload(ctx, key, pr) } // Get retrieves data from the specified key. @@ -173,6 +161,10 @@ func (r *RcloneStorer) List(ctx context.Context, prefix string) ([]string, error err := operations.ListFn(ctx, r.fsys, func(obj fs.Object) { key := obj.Remote() + if strings.HasSuffix(key, tempSuffix) { + return + } + if prefix == "" || strings.HasPrefix(key, prefix) { keys = append(keys, key) } @@ -202,6 +194,10 @@ func (r *RcloneStorer) ListStream( } key := obj.Remote() + if strings.HasSuffix(key, tempSuffix) { + return + } + if prefix == "" || strings.HasPrefix(key, prefix) { ch <- ObjectInfo{ Key: key, @@ -230,6 +226,59 @@ func (r *RcloneStorer) Info() Info { } } +// upload writes data to key. Where the remote has a server-side move, it +// writes under a temporary name ending in tempSuffix and moves the object +// onto key once it is complete, so a killed upload cannot leave a truncated +// object at key; a remote without one is written in place. List and +// ListStream skip a temporary object left behind. +// +// rclone's own copy does this only where the remote also sets +// PartialUploads. That flag is not checked here: hdfs, for one, shows a +// file while it is written without setting it. +func (r *RcloneStorer) upload(ctx context.Context, key string, data io.Reader) error { + if r.fsys.Features().Move == nil { + _, err := operations.Rcat(ctx, r.fsys, key, io.NopCloser(data), time.Now(), nil) + if err != nil { + return fmt.Errorf("uploading object: %w", err) + } + + return nil + } + + tempKey := key + "-" + rand.Text() + tempSuffix + + obj, err := operations.Rcat(ctx, r.fsys, tempKey, io.NopCloser(data), time.Now(), nil) + if err != nil { + // Rcat returns the object it wrote when the written data fails its check. + if obj != nil { + _ = obj.Remove(ctx) + } + + return fmt.Errorf("uploading object: %w", err) + } + + // On drive, dropbox, onedrive and others the remote's own move does not + // replace an object already at key. operations.Move removes the object + // it is given first, and copies where the remote refuses the move. + existing, err := r.fsys.NewObject(ctx, key) + if errors.Is(err, fs.ErrorObjectNotFound) { + existing = nil + } else if err != nil { + _ = obj.Remove(ctx) + + return fmt.Errorf("looking up existing object: %w", err) + } + + _, err = operations.Move(ctx, r.fsys, existing, key, obj) + if err != nil { + _ = obj.Remove(ctx) + + return fmt.Errorf("moving object into place: %w", err) + } + + return nil +} + // progressReader wraps an io.Reader to track read progress. type progressReader struct { reader io.Reader diff --git a/internal/storage/rclone_test.go b/internal/storage/rclone_test.go index e941497..8179e8d 100644 --- a/internal/storage/rclone_test.go +++ b/internal/storage/rclone_test.go @@ -1,28 +1,47 @@ package storage_test import ( + "bytes" "context" "errors" + "io" + "os" + "path/filepath" + "strings" "testing" + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/config/configmap" "sneak.berlin/go/vaultik/internal/storage" ) -// The rclone backend is a thin adapter over the rclone library: it turns a -// (remote, path) pair into rclone's "remote:path" string, hands it to -// rclone, and maps rclone's own results back to the Storer interface. What -// can be tested in-process, without a configured remote or network, is that -// adapter layer — how the arguments are shaped and how construction errors -// are reported. The data-plane operations (Put/Get/List/Delete) are rclone's -// own, exercised against a real provider (drive, s3-via-rclone, ...), which -// needs a configured remote with credentials and network access and so is -// out of reach of a unit test. The shared Storer conformance suite therefore -// runs against the in-process file and s3 backends; the rclone backend -// inherits that contract once a remote is configured. -// // These tests use rclone's ":local:" on-the-fly backend, which addresses the -// local filesystem directly without any configured remote, so construction -// runs entirely in-process. +// local filesystem directly without any configured remote, so they run +// entirely in-process. A remote that needs credentials and network access +// (drive, s3 via rclone, ...) is out of reach of a unit test. + +// newRcloneStorer builds an rclone backend on rclone's local backend, +// rooted at a fresh temp directory. +// +//nolint:ireturn // conformance runs against the Storer interface by design +func newRcloneStorer(t *testing.T) storage.Storer { + t.Helper() + + s, err := storage.NewRcloneStorer(context.Background(), ":local", t.TempDir()) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + return s +} + +// TestRcloneStorer runs the shared Storer contract against the rclone +// backend. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorer(t *testing.T) { + runStorerConformance(t, newRcloneStorer) +} // TestNewRcloneStorerConstruction checks that a valid remote constructs a // backend and that Info() reports the shaped "remote:path" location. @@ -44,6 +63,280 @@ func TestNewRcloneStorerConstruction(t *testing.T) { } } +// unbufferedUploadContext returns a context in which rclone neither reads +// ahead of the write nor holds a small upload in memory. Without it, a +// progress callback runs before anything is written to the remote. +func unbufferedUploadContext() context.Context { + ctx, ci := fs.AddConfig(context.Background()) + ci.BufferSize = 0 + ci.StreamingUploadCutoff = 0 + + return ctx +} + +// objectAtKeyDuringUpload uploads data to testBlobKey and reports whether +// an object was at the key before the upload finished. It fails the test +// unless the key then reads back as the uploaded data. +func objectAtKeyDuringUpload( + ctx context.Context, t *testing.T, s *storage.RcloneStorer, +) bool { + t.Helper() + + data := bytes.Repeat([]byte("blob-bytes"), 1000) + seen := false + + err := s.PutWithProgress(ctx, testBlobKey, bytes.NewReader(data), + int64(len(data)), func(int64) error { + _, statErr := s.Stat(ctx, testBlobKey) + if statErr == nil { + seen = true + } + + return nil + }) + if err != nil { + t.Fatalf("PutWithProgress: %v", err) + } + + got := readObject(ctx, t, s, testBlobKey) + if !bytes.Equal(got, data) { + t.Errorf("object read back as %d bytes, want the %d uploaded", + len(got), len(data)) + } + + return seen +} + +// readObject returns the contents of the object at key. +func readObject( + ctx context.Context, t *testing.T, s *storage.RcloneStorer, key string, +) []byte { + t.Helper() + + rc, err := s.Get(ctx, key) + if err != nil { + t.Fatalf("Get: %v", err) + } + + defer func() { _ = rc.Close() }() + + got, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("reading object: %v", err) + } + + return got +} + +// TestRcloneStorerObjectAppearsOnlyWhenComplete checks that on a remote +// with a server-side move, such as local, nothing is at the key until the +// upload has finished, so a killed upload cannot leave a truncated object +// there. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerObjectAppearsOnlyWhenComplete(t *testing.T) { + ctx := unbufferedUploadContext() + + s, err := storage.NewRcloneStorer(ctx, ":local", t.TempDir()) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + if objectAtKeyDuringUpload(ctx, t, s) { + t.Error("object was at its key before the upload finished") + } +} + +// TestRcloneStorerListSkipsPartialFiles checks that a temporary file left +// by a killed upload is never listed as a key. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerListSkipsPartialFiles(t *testing.T) { + dir := t.TempDir() + ctx := context.Background() + + s, err := storage.NewRcloneStorer(ctx, ":local", dir) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + realKey := testBlobKey + + err = s.Put(ctx, realKey, strings.NewReader("blob-bytes")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + leftover := filepath.Join(dir, realKey+"-123456.partial") + + err = os.WriteFile(leftover, []byte("half"), 0o600) + if err != nil { + t.Fatalf("writing leftover temp file: %v", err) + } + + keys, err := s.List(ctx, "blobs/") + if err != nil { + t.Fatalf("List: %v", err) + } + + if len(keys) != 1 || keys[0] != realKey { + t.Fatalf("List should return only the real key, got %v", keys) + } + + var streamed []string + + for obj := range s.ListStream(ctx, "blobs/") { + if obj.Err != nil { + t.Fatalf("ListStream: %v", obj.Err) + } + + streamed = append(streamed, obj.Key) + } + + if len(streamed) != 1 || streamed[0] != realKey { + t.Fatalf("ListStream should return only the real key, got %v", streamed) + } +} + +// newRcloneStorerOnWrappedLocal registers name as rclone's local backend +// wrapped by wrap, and builds an rclone backend on it rooted at a fresh +// temp directory. wrap changes the features the local backend reports, so +// that it behaves like a remote a unit test cannot reach. +func newRcloneStorerOnWrappedLocal( + ctx context.Context, t *testing.T, name string, wrap func(fs.Fs) fs.Fs, +) *storage.RcloneStorer { + t.Helper() + + fs.Register(&fs.RegInfo{ + Name: name, + NewFs: func( + ctx context.Context, _, root string, _ configmap.Mapper, + ) (fs.Fs, error) { + local, err := fs.NewFs(ctx, ":local:"+root) + if err != nil { + return nil, err + } + + return wrap(local), nil + }, + }) + + s, err := storage.NewRcloneStorer(ctx, ":"+name, t.TempDir()) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + return s +} + +// withoutPartialUploads is rclone's local backend with the PartialUploads +// flag cleared. Like hdfs, it then has a server-side move and shows a file +// while it is written, without setting that flag. +type withoutPartialUploads struct { + fs.Fs +} + +func (f *withoutPartialUploads) Features() *fs.Features { + features := *f.Fs.Features() + features.PartialUploads = false + + return &features +} + +// TestRcloneStorerMovesIntoPlaceWithoutPartialUploads checks that on a +// remote with a server-side move nothing is at the key until the upload has +// finished, even when rclone does not mark the remote as showing partial +// uploads. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerMovesIntoPlaceWithoutPartialUploads(t *testing.T) { + ctx := unbufferedUploadContext() + s := newRcloneStorerOnWrappedLocal(ctx, t, "withoutpartialuploads", + func(local fs.Fs) fs.Fs { return &withoutPartialUploads{Fs: local} }) + + if objectAtKeyDuringUpload(ctx, t, s) { + t.Error("object was at its key before the upload finished") + } +} + +// withoutMove is rclone's local backend reporting no server-side move. +type withoutMove struct { + fs.Fs +} + +func (f *withoutMove) Features() *fs.Features { + features := *f.Fs.Features() + features.Move = nil + + return &features +} + +// TestRcloneStorerWritesInPlaceWithoutMove checks that on a remote with no +// server-side move an object is written straight to its key and reads back +// from there. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerWritesInPlaceWithoutMove(t *testing.T) { + ctx := unbufferedUploadContext() + s := newRcloneStorerOnWrappedLocal(ctx, t, "withoutmove", + func(local fs.Fs) fs.Fs { return &withoutMove{Fs: local} }) + + if !objectAtKeyDuringUpload(ctx, t, s) { + t.Error("object was not at its key while it was uploaded") + } +} + +var errNameConflict = errors.New("an object with this name already exists") + +// moveRefusesExisting is rclone's local backend with a server-side move +// that, like dropbox's or onedrive's, refuses to move onto an existing +// object. +type moveRefusesExisting struct { + fs.Fs +} + +func (f *moveRefusesExisting) Features() *fs.Features { + features := *f.Fs.Features() + features.Move = f.move + + return &features +} + +//nolint:ireturn // the signature is rclone's +func (f *moveRefusesExisting) move( + ctx context.Context, src fs.Object, remote string, +) (fs.Object, error) { + _, err := f.NewObject(ctx, remote) + if err == nil { + return nil, errNameConflict + } + + return f.Fs.Features().Move(ctx, src, remote) +} + +// TestRcloneStorerOverwritesWhereMoveRefusesExisting checks that writing a +// key twice replaces the object on a remote whose server-side move will not +// replace an existing object. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerOverwritesWhereMoveRefusesExisting(t *testing.T) { + ctx := context.Background() + s := newRcloneStorerOnWrappedLocal(ctx, t, "moverefusesexisting", + func(local fs.Fs) fs.Fs { return &moveRefusesExisting{Fs: local} }) + + for _, content := range []string{"first", "second"} { + err := s.Put(ctx, testBlobKey, strings.NewReader(content)) + if err != nil { + t.Fatalf("Put %q: %v", content, err) + } + } + + got := readObject(ctx, t, s, testBlobKey) + if string(got) != "second" { + t.Errorf("object = %q, want %q", got, "second") + } +} + // TestNewRcloneStorerUnknownRemote checks that a remote that is not in the // rclone config fails construction with the ErrRemoteNotFound sentinel, // rather than silently returning a backend pointed nowhere. From e459a66099e52932410d204c0b9cd675652f5be4 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 8 Oct 2026 00:12:13 +0200 Subject: [PATCH 034/121] Stop a backup on a symlink whose target cannot be read (closes #269) When readlink failed, the scanner logged at debug level and left the symlink out of the snapshot, and the run reported success even without --skip-errors. The error now goes through the same handling as any other entry the walk cannot read: the run aborts, or with --skip-errors the symlink is skipped with the usual "Failed to access" error line. A symlink removed between the walk's lstat and the readlink also aborts the run, as an entry that vanishes during the walk already does. Model: opus-5-5 --- TODO.md | 7 ++ internal/snapshot/scanner.go | 41 ++++++----- internal/snapshot/skip_errors_test.go | 102 ++++++++++++++++++++++++-- 3 files changed, 124 insertions(+), 26 deletions(-) diff --git a/TODO.md b/TODO.md index fe962f5..52719c6 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,13 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-07: Made a symlink whose target cannot be read stop the backup + ([issue #269](https://git.eeqj.de/sneak/vaultik/issues/269)). It was + left out of the snapshot with only a debug log line, even without + `--skip-errors`. It now aborts the run, or with `--skip-errors` is + skipped with the `Failed to access` error line that any other entry + the scan cannot read gets. + - 2026-10-07: Stopped a killed rclone upload from leaving a truncated object under its key ([issue #266](https://git.eeqj.de/sneak/vaultik/issues/266)). The diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index b611857..46765b2 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -889,9 +889,10 @@ func (s *Scanner) scanPhase( } // Handle symlinks and directories - if handled := s.recordSpecialEntry( - filePath, info, existingFiles, collector, result); handled { - return nil + handled, err := s.recordSpecialEntry( + filePath, info, existingFiles, collector, result) + if handled { + return err } // Skip other non-regular files (devices, sockets, etc.) @@ -933,22 +934,25 @@ func (s *Scanner) scanPhase( } // recordSpecialEntry records symlinks and directories (which have no -// data to chunk) and reports whether it handled the entry. +// data to chunk) and reports whether it handled the entry. For a symlink +// whose target cannot be read it returns handleWalkError's result. func (s *Scanner) recordSpecialEntry( filePath string, info os.FileInfo, existingFiles map[string]struct{}, collector *scanCollector, result *ScanResult, -) bool { +) (bool, error) { // Handle symlinks if info.Mode()&os.ModeSymlink != 0 { - file := s.buildSymlinkEntry(filePath, info) - if file != nil { - existingFiles[filePath] = struct{}{} - collector.addToProcess(filePath, info, file) - s.updateScanEntryStats(result, true, info) + file, err := s.buildSymlinkEntry(filePath, info) + if err != nil { + return true, s.handleWalkError(filePath, err) } - return true + existingFiles[filePath] = struct{}{} + collector.addToProcess(filePath, info, file) + s.updateScanEntryStats(result, true, info) + + return true, nil } // Handle directories (record for permission/ownership preservation @@ -958,10 +962,10 @@ func (s *Scanner) recordSpecialEntry( existingFiles[filePath] = struct{}{} collector.addToProcess(filePath, info, file) - return true + return true, nil } - return false + return false, nil } // handleWalkError deals with a filesystem error surfaced by the walk: @@ -1111,13 +1115,12 @@ func (s *Scanner) printScanProgressLine( } // buildSymlinkEntry creates a File record for a symlink. -// Returns nil if the link target cannot be read. -func (s *Scanner) buildSymlinkEntry(path string, info os.FileInfo) *database.File { +func (s *Scanner) buildSymlinkEntry( + path string, info os.FileInfo, +) (*database.File, error) { target, err := os.Readlink(path) if err != nil { - log.Debug("Cannot read symlink target", "path", path, "error", err) - - return nil + return nil, err } var uid, gid uint32 @@ -1136,7 +1139,7 @@ func (s *Scanner) buildSymlinkEntry(path string, info os.FileInfo) *database.Fil UID: uid, GID: gid, LinkTarget: types.FilePath(target), - } + }, nil } // buildDirectoryEntry creates a File record for a directory. diff --git a/internal/snapshot/skip_errors_test.go b/internal/snapshot/skip_errors_test.go index 9ae128a..8325372 100644 --- a/internal/snapshot/skip_errors_test.go +++ b/internal/snapshot/skip_errors_test.go @@ -3,6 +3,7 @@ package snapshot_test import ( "context" "errors" + "io" "os" "path/filepath" "strings" @@ -13,6 +14,7 @@ import ( "github.com/spf13/afero" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/ui" ) // errSimTempFail is the one-time temp-file creation failure blobTempFailFs @@ -80,6 +82,30 @@ func (f *readFailFs) Open(name string) (afero.File, error) { return file, nil } +// linkRemovedAfterLstatFs is the real filesystem, except that the symlink at +// target is removed right after the walk lstats it, as happens when a link is +// deleted during a backup. The scanner's readlink of it then fails. +type linkRemovedAfterLstatFs struct { + afero.OsFs + + t *testing.T + target string +} + +func (f *linkRemovedAfterLstatFs) LstatIfPossible( + name string, +) (os.FileInfo, bool, error) { + info, lstatCalled, err := f.OsFs.LstatIfPossible(name) + if err == nil && name == f.target { + rmErr := os.Remove(name) + if rmErr != nil { + f.t.Errorf("removing %s: %v", name, rmErr) + } + } + + return info, lstatCalled, err +} + // writeSkipErrorTestFile writes one file into fs with a fixed mtime. func writeSkipErrorTestFile(t *testing.T, fs afero.Fs, path, content string) { t.Helper() @@ -102,10 +128,11 @@ func writeSkipErrorTestFile(t *testing.T, fs afero.Fs, path, content string) { } } -// runSkipErrorScan scans /source on fs with the given skip-errors setting and -// returns the repositories (for inspection) and the scan error. +// runSkipErrorScan scans source on fs with the given skip-errors setting, +// printing user-facing messages to uiw (nil discards them), and returns the +// repositories (for inspection) and the scan error. func runSkipErrorScan( - t *testing.T, fs afero.Fs, skipErrors bool, + t *testing.T, fs afero.Fs, source string, skipErrors bool, uiw *ui.Writer, ) (*database.Repositories, error) { t.Helper() @@ -130,6 +157,7 @@ func runSkipErrorScan( MaxBlobSize: int64(1024 * 1024), CompressionLevel: 3, AgeRecipients: []string{testAgePublicKey}, + UI: uiw, SkipErrors: skipErrors, }) @@ -137,7 +165,7 @@ func runSkipErrorScan( snapshotID := "test-snapshot-skip-errors" createTestSnapshotRecord(ctx, t, repos, snapshotID) - _, err = scanner.Scan(ctx, "/source", snapshotID) + _, err = scanner.Scan(ctx, source, snapshotID) return repos, err } @@ -157,7 +185,7 @@ func TestScannerPackingFailureAbortsUnderSkipErrors(t *testing.T) { writeSkipErrorTestFile(t, fs, "/source/file1.txt", "first file content") writeSkipErrorTestFile(t, fs, "/source/file2.txt", "second file content") - repos, err := runSkipErrorScan(t, fs, true) + repos, err := runSkipErrorScan(t, fs, "/source", true, nil) if err == nil { t.Fatal("expected scan to abort on the packer error, got nil") } @@ -184,7 +212,7 @@ func TestScannerReadErrorAbortsWithoutSkipErrors(t *testing.T) { fs := &readFailFs{Fs: afero.NewMemMapFs(), target: target} writeSkipErrorTestFile(t, fs, target, "content that cannot be read") - _, err := runSkipErrorScan(t, fs, false) + _, err := runSkipErrorScan(t, fs, "/source", false, nil) if err == nil { t.Fatal("expected scan to fail on the read error, got nil") } @@ -200,7 +228,7 @@ func TestScannerReadErrorSkippedWithSkipErrors(t *testing.T) { fs := &readFailFs{Fs: afero.NewMemMapFs(), target: target} writeSkipErrorTestFile(t, fs, target, "content that cannot be read") - repos, err := runSkipErrorScan(t, fs, true) + repos, err := runSkipErrorScan(t, fs, "/source", true, nil) if err != nil { t.Fatalf("expected scan to complete with --skip-errors, got %v", err) } @@ -214,3 +242,63 @@ func TestScannerReadErrorSkippedWithSkipErrors(t *testing.T) { t.Fatalf("expected unreadable file skipped, got %d chunks", len(chunks)) } } + +// writeSymlinkSource creates a source directory on disk holding one symlink +// and returns the directory and the symlink's path. +func writeSymlinkSource(t *testing.T) (string, string) { + t.Helper() + + sourceDir := t.TempDir() + linkPath := filepath.Join(sourceDir, "link") + + err := os.Symlink("target.txt", linkPath) + if err != nil { + t.Fatalf("creating symlink: %v", err) + } + + return sourceDir, linkPath +} + +// TestScannerUnreadableSymlinkAbortsWithoutSkipErrors checks that a symlink +// whose target cannot be read aborts the run when --skip-errors is not set. +func TestScannerUnreadableSymlinkAbortsWithoutSkipErrors(t *testing.T) { + t.Parallel() + + sourceDir, linkPath := writeSymlinkSource(t) + fs := &linkRemovedAfterLstatFs{t: t, target: linkPath} + + _, err := runSkipErrorScan(t, fs, sourceDir, false, nil) + if !errors.Is(err, os.ErrNotExist) { + t.Fatalf("expected scan to fail on the removed symlink, got %v", err) + } +} + +// TestScannerUnreadableSymlinkSkippedWithSkipErrors checks that a symlink +// whose target cannot be read is skipped with an error line, and the run +// completes, when --skip-errors is set. +func TestScannerUnreadableSymlinkSkippedWithSkipErrors(t *testing.T) { + t.Parallel() + + sourceDir, linkPath := writeSymlinkSource(t) + fs := &linkRemovedAfterLstatFs{t: t, target: linkPath} + uiw := ui.NewWithColor(io.Discard, false) + + repos, err := runSkipErrorScan(t, fs, sourceDir, true, uiw) + if err != nil { + t.Fatalf("expected scan to complete with --skip-errors, got %v", err) + } + + if uiw.ErrorCount() != 1 { + t.Fatalf("expected one error line for the symlink, got %d", + uiw.ErrorCount()) + } + + file, err := repos.Files.GetByPath(context.Background(), linkPath) + if err != nil { + t.Fatalf("getting %s: %v", linkPath, err) + } + + if file != nil { + t.Fatalf("expected %s not to be recorded", linkPath) + } +} From fce253fa39d4e313e7d2472006a701edb3c9760f Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 8 Oct 2026 03:29:07 +0200 Subject: [PATCH 035/121] Give a second snapshot create in the same second its own ID (closes #270) The timestamp in a snapshot ID is in whole seconds, so a `snapshot create` that started in the same second as the previous run of that snapshot name got the same ID, and inserting its row failed with `UNIQUE constraint failed: snapshots.id`. CreateSnapshotWithName now looks the ID up in the local index first and, if it is taken, waits a second and takes a new timestamp. The ID format is unchanged. Only the local index is checked. That is where the insert fails, and the process lock serializes runs, so nothing takes the ID between the lookup and the insert. Model: opus-5-5 --- TODO.md | 8 ++++++++ internal/snapshot/snapshot.go | 33 ++++++++++++++++++++++-------- internal/snapshot/snapshot_test.go | 33 ++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 8 deletions(-) diff --git a/TODO.md b/TODO.md index 52719c6..9d6ca17 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,14 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-08: Made a second `snapshot create` of one name succeed when + it starts in the same second as the first + ([issue #270](https://git.eeqj.de/sneak/vaultik/issues/270)). The + timestamp in a snapshot ID is in whole seconds, so the second run got + the first run's ID and failed with `UNIQUE constraint failed: + snapshots.id`. When the local index already has a snapshot with the + ID, the create now waits a second and takes a new timestamp. + - 2026-10-07: Made a symlink whose target cannot be read stop the backup ([issue #269](https://git.eeqj.de/sneak/vaultik/issues/269)). It was left out of the snapshot with only a debug log line, even without diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 4e59092..05e1ac1 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -115,20 +115,37 @@ func ShortHostname(hostname string) string { // CreateSnapshotWithName creates a new snapshot record with an optional // snapshot name. The snapshot ID format is: hostname_name_timestamp or -// hostname_timestamp if name is empty. +// hostname_timestamp if name is empty. The timestamp is in whole seconds. +// If the local index already has a snapshot with that ID, from a run of the +// same name that started in the same second, it waits a second and takes a +// new timestamp. func (sm *SnapshotManager) CreateSnapshotWithName( ctx context.Context, hostname, name, version, gitRevision string, ) (string, error) { shortHostname := ShortHostname(hostname) - // Build snapshot ID with optional name - timestamp := time.Now().UTC().Format("2006-01-02T15:04:05Z") - var snapshotID string - if name != "" { - snapshotID = fmt.Sprintf("%s_%s_%s", shortHostname, name, timestamp) - } else { - snapshotID = fmt.Sprintf("%s_%s", shortHostname, timestamp) + + for { + // Build snapshot ID with optional name + timestamp := time.Now().UTC().Format("2006-01-02T15:04:05Z") + + if name != "" { + snapshotID = fmt.Sprintf("%s_%s_%s", shortHostname, name, timestamp) + } else { + snapshotID = fmt.Sprintf("%s_%s", shortHostname, timestamp) + } + + existing, err := sm.repos.Snapshots.GetByID(ctx, snapshotID) + if err != nil { + return "", fmt.Errorf("looking up snapshot %s: %w", snapshotID, err) + } + + if existing == nil { + break + } + + time.Sleep(time.Second) } snapshot := &database.Snapshot{ diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go index a0b31bc..38e38d8 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -386,3 +386,36 @@ func TestCleanSnapshotDBNonExistentSnapshot(t *testing.T) { t.Fatalf("unexpected error: %v", err) } } + +// Two creates of one snapshot name back to back start within one second, +// the resolution of the timestamp in a snapshot ID. See +// https://git.eeqj.de/sneak/vaultik/issues/270. +func TestCreateSnapshotWithNameTwiceBackToBack(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + + db, err := database.New(ctx, filepath.Join(t.TempDir(), "index.sqlite")) + if err != nil { + t.Fatalf("failed to create database: %v", err) + } + + defer func() { _ = db.Close() }() + + sm := &SnapshotManager{repos: database.NewRepositories(db)} + + first, err := sm.CreateSnapshotWithName(ctx, "test-host", "data", "v", "g") + if err != nil { + t.Fatalf("first create failed: %v", err) + } + + second, err := sm.CreateSnapshotWithName(ctx, "test-host", "data", "v", "g") + if err != nil { + t.Fatalf("second create failed: %v", err) + } + + if first == second { + t.Fatalf("both creates returned snapshot ID %s", first) + } +} From 70f008a21a7aea368371b40422a98600228148b8 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 8 Oct 2026 04:59:30 +0200 Subject: [PATCH 036/121] Document that --json skips the confirmation prompt (closes #268) snapshot remove and prune delete without asking under --json, because a prompt on stdout would break the JSON document. Their --json help and README entries named only --force as skipping the prompt. Both now say --json skips it too. One test checks the --json help of both commands; another runs prune with --json, no --force and empty stdin, and checks that the unreferenced blob is deleted and stdout holds only the JSON document. Model: opus-5-5 --- README.md | 6 +++-- TODO.md | 8 ++++++ internal/cli/json_help_test.go | 24 +++++++++++++++++ internal/cli/prune.go | 3 ++- internal/cli/snapshot.go | 3 ++- internal/vaultik/prune_json_test.go | 40 +++++++++++++++++++++++++++++ 6 files changed, 80 insertions(+), 4 deletions(-) create mode 100644 internal/cli/json_help_test.go create mode 100644 internal/vaultik/prune_json_test.go diff --git a/README.md b/README.md index 78eaea7..5d2188b 100644 --- a/README.md +++ b/README.md @@ -359,7 +359,8 @@ on the destination in one go, use `vaultik remote nuke --force`. * `--local-only`: Skip remote cleanup; only touch the local index * `--dry-run`: Show what would be deleted without deleting * `--force`: Skip confirmation prompt -* `--json`: Output result as JSON +* `--json`: Output result as JSON. Also skips the confirmation prompt, as + `--force` does. **`snapshot restore`**: Restore files from a backup snapshot. * Requires `VAULTIK_AGE_SECRET_KEY` environment variable @@ -383,7 +384,8 @@ manifests — network cost scales with the number of snapshots. `snapshot create --prune` runs the same cleanup automatically; this is the manual entry point for the same work. * `--force`: Skip confirmation prompt -* `--json`: Output stats as JSON +* `--json`: Output stats as JSON. Also skips the confirmation prompt, as + `--force` does. **`info`**: Display system configuration, storage settings, encryption recipients, and local database statistics. diff --git a/TODO.md b/TODO.md index 9d6ca17..906798c 100644 --- a/TODO.md +++ b/TODO.md @@ -30,6 +30,14 @@ the tag exists and is exercised; what is left is merging `next` to snapshots.id`. When the local index already has a snapshot with the ID, the create now waits a second and takes a new timestamp. +- 2026-10-07: Documented that `--json` skips the confirmation prompt of + `snapshot remove` and `prune` + ([issue #268](https://git.eeqj.de/sneak/vaultik/issues/268)). Both + commands delete without asking under `--json`, since a prompt on stdout + would break the JSON document, but the help and the README described + only `--force` as skipping it. The `--json` help of both commands and + their README entries now say so. + - 2026-10-07: Made a symlink whose target cannot be read stop the backup ([issue #269](https://git.eeqj.de/sneak/vaultik/issues/269)). It was left out of the snapshot with only a debug log line, even without diff --git a/internal/cli/json_help_test.go b/internal/cli/json_help_test.go new file mode 100644 index 0000000..3d25048 --- /dev/null +++ b/internal/cli/json_help_test.go @@ -0,0 +1,24 @@ +package cli //nolint:testpackage // exercises the unexported command constructor + +import ( + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" +) + +// TestJSONHelpSaysConfirmationPromptIsSkipped checks that the --json help +// of `snapshot remove` and `prune` says the flag skips the confirmation +// prompt. Both delete without asking under --json, since a prompt on +// stdout would break the JSON document. +func TestJSONHelpSaysConfirmationPromptIsSkipped(t *testing.T) { + t.Parallel() + + for _, cmd := range []*cobra.Command{ + newSnapshotRemoveCommand(), + NewPruneCommand(), + } { + assert.Contains(t, cmd.Flags().Lookup("json").Usage, + "skips the confirmation prompt", cmd.Name()) + } +} diff --git a/internal/cli/prune.go b/internal/cli/prune.go index e73d45d..707617b 100644 --- a/internal/cli/prune.go +++ b/internal/cli/prune.go @@ -57,7 +57,8 @@ referenced.`, } cmd.Flags().BoolVar(&opts.Force, "force", false, "Skip confirmation prompt") - cmd.Flags().BoolVar(&opts.JSON, "json", false, "Output pruning stats as JSON") + cmd.Flags().BoolVar(&opts.JSON, "json", false, + "Output pruning stats as JSON; skips the confirmation prompt, as --force does") return cmd } diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index a9c6e5a..58b32db 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -280,7 +280,8 @@ nuke --force' — it is the single supported entry point for that.`, cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "Skip confirmation prompt") cmd.Flags().BoolVar(&opts.DryRun, "dry-run", false, "Show what would be removed without removing") - cmd.Flags().BoolVar(&opts.JSON, "json", false, "Output result as JSON") + cmd.Flags().BoolVar(&opts.JSON, "json", false, + "Output result as JSON; skips the confirmation prompt, as --force does") cmd.Flags().BoolVar(&opts.LocalOnly, "local-only", false, "Skip remote cleanup; only touch the local index") diff --git a/internal/vaultik/prune_json_test.go b/internal/vaultik/prune_json_test.go new file mode 100644 index 0000000..96f6d01 --- /dev/null +++ b/internal/vaultik/prune_json_test.go @@ -0,0 +1,40 @@ +package vaultik_test + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestPruneBlobs_JSONDeletesWithoutAsking checks that prune with --json +// and without --force deletes an unreferenced blob without the +// confirmation prompt. Stdin is empty, so a prompt would read no answer +// and cancel, and its text would come before the JSON document. +func TestPruneBlobs_JSONDeletesWithoutAsking(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + // The store holds no manifest, so nothing references this blob. + addBlob(t, env.store.testStorer, testBlobHashA) + + err := env.v.PruneBlobs(&vaultik.PruneOptions{JSON: true}) + require.NoError(t, err) + + blobKey := "blobs/" + testBlobHashA[:2] + "/" + testBlobHashA[2:4] + + "/" + testBlobHashA + assert.False(t, env.store.hasKey(blobKey), + "the unreferenced blob must be deleted") + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &result), + "stdout must hold only the JSON document, got:\n%s", + env.stdout.String()) + assert.Equal(t, 1, result.BlobsDeleted) +} From c06c4d201b67d83a07ff5a2b067cf7c016e1a9b0 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 8 Oct 2026 07:29:11 +0200 Subject: [PATCH 037/121] Keep the progress line of a multi-path snapshot within 100% (closes #271) One progress reporter spans every path of a snapshot. Its counts of files and bytes processed run across all the paths, while the totals they were divided by were reset to each path's own, so a second path smaller than the first showed more than 100% and an ETA of `unknown`. The totals now add up over the paths scanned so far. The rate behind the ETA restarts when each path's scan phase ends, so that phase does not lower the rate while the path is processed; until then the rate is the previous path's. SetTotalSize is renamed AddTotalSize because it now adds. The issue says the ETA went negative; it was computed negative and printed as `unknown`. Model: opus-5-5 --- TODO.md | 11 +++ internal/snapshot/progress.go | 122 ++++++++++++++---------- internal/snapshot/progress_rate_test.go | 54 +++++++++++ internal/snapshot/progress_test.go | 94 ++++++++++++++++++ internal/snapshot/scanner.go | 4 +- 5 files changed, 230 insertions(+), 55 deletions(-) create mode 100644 internal/snapshot/progress_rate_test.go create mode 100644 internal/snapshot/progress_test.go diff --git a/TODO.md b/TODO.md index 906798c..4e052b4 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,17 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-08: Kept the progress line of a snapshot with more than one + path within 100% + ([issue #271](https://git.eeqj.de/sneak/vaultik/issues/271)). The + bytes and files processed counted every path, but the totals they + were divided by held only the current path's, so a second path + smaller than the first showed more than 100% and an ETA of `unknown`. + The totals now add up over the paths scanned so far. The rate behind + the ETA restarts when each path's scan phase ends, so that phase does + not lower the rate while the path is processed; until then the rate + is the previous path's. + - 2026-10-08: Made a second `snapshot create` of one name succeed when it starts in the same second as the first ([issue #270](https://git.eeqj.de/sneak/vaultik/issues/270)). The diff --git a/internal/snapshot/progress.go b/internal/snapshot/progress.go index 9aba0f5..d58a339 100644 --- a/internal/snapshot/progress.go +++ b/internal/snapshot/progress.go @@ -56,23 +56,27 @@ const ( // ProgressStats holds atomic counters for progress tracking type ProgressStats struct { - FilesScanned atomic.Int64 // Total files seen during scan (includes skipped) - FilesProcessed atomic.Int64 // Files actually processed in phase 2 - FilesSkipped atomic.Int64 // Files skipped due to no changes - BytesScanned atomic.Int64 // Bytes from new/changed files only - BytesSkipped atomic.Int64 // Bytes from unchanged files - BytesProcessed atomic.Int64 // Actual bytes processed (for ETA calculation) - ChunksCreated atomic.Int64 - BlobsCreated atomic.Int64 - BlobsUploaded atomic.Int64 - BytesUploaded atomic.Int64 - CurrentFile atomic.Value // stores string - TotalSize atomic.Int64 // Total size to process (set after scan phase) - TotalFiles atomic.Int64 // Total files to process in phase 2 - ProcessStartTime atomic.Value // stores time.Time when processing starts - StartTime time.Time - mu sync.RWMutex - lastDetailTime time.Time + FilesScanned atomic.Int64 // Total files seen during scan (includes skipped) + FilesProcessed atomic.Int64 // Files actually processed in phase 2 + FilesSkipped atomic.Int64 // Files skipped due to no changes + BytesScanned atomic.Int64 // Bytes from new/changed files only + BytesSkipped atomic.Int64 // Bytes from unchanged files + BytesProcessed atomic.Int64 // Actual bytes processed (for ETA calculation) + ChunksCreated atomic.Int64 + BlobsCreated atomic.Int64 + BlobsUploaded atomic.Int64 + BytesUploaded atomic.Int64 + CurrentFile atomic.Value // stores string + TotalSize atomic.Int64 // Size to process in the paths scanned so far + TotalFiles atomic.Int64 // Files to process in the paths scanned so far + StartTime time.Time + mu sync.RWMutex + lastDetailTime time.Time + + // Guarded by mu: when the last scan phase ended, and + // BytesProcessed at that moment. + processStartTime time.Time + processStartBytes int64 // Upload tracking CurrentUpload atomic.Value // stores *UploadInfo @@ -148,10 +152,36 @@ func (pr *ProgressReporter) GetStats() *ProgressStats { return pr.stats } -// SetTotalSize sets the total size to process (after scan phase) -func (pr *ProgressReporter) SetTotalSize(size int64) { - pr.stats.TotalSize.Store(size) - pr.stats.ProcessStartTime.Store(time.Now().UTC()) +// AddTotalSize adds the size one path of the snapshot has to process to +// the total, once that path's scan phase is done, and starts measuring +// the processing rate again. The processed counts run across every path, +// so the total does too. Restarting the rate keeps a path's scan phase, +// which processes nothing, out of the rate while that path is processed. +// During a later path's scan phase the rate is still the previous +// path's, and falls as that scan goes on. +func (pr *ProgressReporter) AddTotalSize(size int64) { + pr.stats.TotalSize.Add(size) + + pr.stats.mu.Lock() + defer pr.stats.mu.Unlock() + + pr.stats.processStartTime = time.Now().UTC() + pr.stats.processStartBytes = pr.stats.BytesProcessed.Load() +} + +// processRate returns the bytes processed per second since the last scan +// phase ended, or 0 before the first path's scan phase is done. +func (s *ProgressStats) processRate() float64 { + s.mu.RLock() + defer s.mu.RUnlock() + + if s.processStartTime.IsZero() { + return 0 + } + + processed := s.BytesProcessed.Load() - s.processStartBytes + + return float64(processed) / time.Since(s.processStartTime).Seconds() } // Helper functions @@ -357,19 +387,12 @@ func (pr *ProgressReporter) printSummaryStatus() { // Calculate ETA if we have total size and are processing etaStr := "" - if totalSize > 0 && bytesProcessed > 0 { - processStart, ok := pr.stats.ProcessStartTime.Load().(time.Time) - if ok && !processStart.IsZero() { - processElapsed := time.Since(processStart) - - rate := float64(bytesProcessed) / processElapsed.Seconds() - if rate > 0 { - remainingBytes := totalSize - bytesProcessed - remainingSeconds := float64(remainingBytes) / rate - eta := time.Duration(remainingSeconds * float64(time.Second)) - etaStr = " | ETA: " + formatDuration(eta) - } - } + processRate := pr.stats.processRate() + if totalSize > 0 && processRate > 0 { + remainingBytes := totalSize - bytesProcessed + remainingSeconds := float64(remainingBytes) / processRate + eta := time.Duration(remainingSeconds * float64(time.Second)) + etaStr = " | ETA: " + formatDuration(eta) } rate := float64(bytesScanned+bytesSkipped) / elapsed.Seconds() @@ -421,25 +444,18 @@ func (pr *ProgressReporter) printDetailedStatus() { log.Info("Elapsed time", "duration", formatDuration(elapsed)) // Calculate and show ETA if we have data - if totalSize > 0 && bytesProcessed > 0 { - processStart, ok := pr.stats.ProcessStartTime.Load().(time.Time) - if ok && !processStart.IsZero() { - processElapsed := time.Since(processStart) - - processRate := float64(bytesProcessed) / processElapsed.Seconds() - if processRate > 0 { - remainingBytes := totalSize - bytesProcessed - remainingSeconds := float64(remainingBytes) / processRate - eta := time.Duration(remainingSeconds * float64(time.Second)) - percentComplete := float64(bytesProcessed) / float64(totalSize) * percentScale - log.Info("Overall progress", - "percent", fmt.Sprintf("%.1f%%", percentComplete), - "processed", humanize.Bytes(safeUint64(bytesProcessed)), - "total", humanize.Bytes(safeUint64(totalSize)), - "rate", humanize.Bytes(uint64(processRate))+"/s", - "eta", formatDuration(eta)) - } - } + processRate := pr.stats.processRate() + if totalSize > 0 && processRate > 0 { + remainingBytes := totalSize - bytesProcessed + remainingSeconds := float64(remainingBytes) / processRate + eta := time.Duration(remainingSeconds * float64(time.Second)) + percentComplete := float64(bytesProcessed) / float64(totalSize) * percentScale + log.Info("Overall progress", + "percent", fmt.Sprintf("%.1f%%", percentComplete), + "processed", humanize.Bytes(safeUint64(bytesProcessed)), + "total", humanize.Bytes(safeUint64(totalSize)), + "rate", humanize.Bytes(uint64(processRate))+"/s", + "eta", formatDuration(eta)) } log.Info("Files processed", diff --git a/internal/snapshot/progress_rate_test.go b/internal/snapshot/progress_rate_test.go new file mode 100644 index 0000000..69d0689 --- /dev/null +++ b/internal/snapshot/progress_rate_test.go @@ -0,0 +1,54 @@ +//nolint:testpackage // exercises the unexported processRate helper +package snapshot + +import ( + "testing" + "time" +) + +// TestProcessRateNotLoweredByLaterScanPhase feeds the reporter two paths +// that each take 10 seconds to process, the second after a 30-second scan +// phase. That scan phase processes nothing, so the rate while the second +// path is processed must be that path's own. +func TestProcessRateNotLoweredByLaterScanPhase(t *testing.T) { + t.Parallel() + + const ( + pathSize = 1000 + processingTime = 10 * time.Second + scanTime = 30 * time.Second + ) + + // Never started, but Stop releases its tickers and signal handler. + progress := NewProgressReporter() + defer progress.Stop() + + stats := progress.GetStats() + + // Moves the processing start time back instead of sleeping. + elapse := func(d time.Duration) { + stats.mu.Lock() + defer stats.mu.Unlock() + + stats.processStartTime = stats.processStartTime.Add(-d) + } + + progress.AddTotalSize(pathSize) + stats.BytesProcessed.Add(pathSize) + elapse(processingTime) + + elapse(scanTime) + progress.AddTotalSize(pathSize) + stats.BytesProcessed.Add(pathSize) + elapse(processingTime) + + want := pathSize / processingTime.Seconds() + got := stats.processRate() + + // The test's own run time adds to the elapsed time, so got is a hair + // under want. + if got > want || got < want*0.99 { + t.Errorf("rate while the second path is processed is %.1f bytes/s, "+ + "want %.1f", got, want) + } +} diff --git a/internal/snapshot/progress_test.go b/internal/snapshot/progress_test.go new file mode 100644 index 0000000..ed63c91 --- /dev/null +++ b/internal/snapshot/progress_test.go @@ -0,0 +1,94 @@ +package snapshot_test + +import ( + "context" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/afero" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/snapshot" +) + +// TestProgressPercentWithSecondPathSmaller backs up two paths with one +// scanner, as a snapshot with two paths does, the second path smaller +// than the first. The progress line divides the bytes processed by the +// total size, so both must count both paths to stay within 100%. +func TestProgressPercentWithSecondPathSmaller(t *testing.T) { + t.Parallel() + + fs := afero.NewMemMapFs() + files := map[string]string{ + "/large/one.txt": strings.Repeat("1", 4000), + "/large/two.txt": strings.Repeat("2", 4000), + "/small/three.txt": strings.Repeat("3", 1000), + } + + for path, content := range files { + err := fs.MkdirAll(filepath.Dir(path), 0755) + if err != nil { + t.Fatalf("mkdir: %v", err) + } + + err = afero.WriteFile(fs, path, []byte(content), 0644) + if err != nil { + t.Fatalf("write %s: %v", path, err) + } + } + + db, err := database.NewTestDB() + if err != nil { + t.Fatalf("create test db: %v", err) + } + + t.Cleanup(func() { + cerr := db.Close() + if cerr != nil { + t.Errorf("close db: %v", cerr) + } + }) + + repos := database.NewRepositories(db) + + scanner := snapshot.NewScanner(snapshot.ScannerConfig{ + FS: fs, + ChunkSize: int64(1024 * 16), + Repositories: repos, + MaxBlobSize: int64(1024 * 1024), + CompressionLevel: 3, + AgeRecipients: []string{testAgePublicKey}, + EnableProgress: true, + }) + + // Never started, but Stop releases its tickers and signal handler. + progress := scanner.GetProgress() + defer progress.Stop() + + ctx := context.Background() + snapshotID := "test-snapshot-progress" + createTestSnapshotRecord(ctx, t, repos, snapshotID) + + for _, path := range []string{"/large", "/small"} { + _, err := scanner.Scan(ctx, path, snapshotID) + if err != nil { + t.Fatalf("scanning %s: %v", path, err) + } + } + + stats := progress.GetStats() + + // Directories count toward the total size but produce no chunks, so + // the percentage ends just under 100%. + percent := float64(stats.BytesProcessed.Load()) / + float64(stats.TotalSize.Load()) * 100 + if percent > 100 { + t.Errorf("progress after both paths is %.1f%%, want at most 100%%", + percent) + } + + if stats.FilesProcessed.Load() != stats.TotalFiles.Load() { + t.Errorf("progress after both paths is %d of %d files, want all", + stats.FilesProcessed.Load(), stats.TotalFiles.Load()) + } +} diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 46765b2..79d7e33 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -407,8 +407,8 @@ func (s *Scanner) summarizeScanPhase( } if s.progress != nil { - s.progress.SetTotalSize(totalSizeToProcess) - s.progress.GetStats().TotalFiles.Store(int64(len(filesToProcess))) + s.progress.AddTotalSize(totalSizeToProcess) + s.progress.GetStats().TotalFiles.Add(int64(len(filesToProcess))) } log.Info("Phase 1 complete", From 0d0368df811ab1d96e9060193c23deff20241b7d Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 8 Oct 2026 08:46:11 +0200 Subject: [PATCH 038/121] Report unknown blob figures for a snapshot whose manifest cannot be read (closes #272) When remote info could not read a snapshot's manifest, the orphan figures were unknown but the snapshot's row still gave 0 blobs and 0 B, in the table and in --json. The row's blob count and blob size are now unknown, and null in --json. A directory with no manifest, as an interrupted backup leaves, still shows 0: the orphan figures count its blobs as orphaned, so it references none. The constant holding the "unknown" text is renamed from countUnknown to unknownText, since it now also stands for a size. Model: opus-5-5 --- README.md | 3 +- TODO.md | 9 ++++ internal/vaultik/info.go | 30 +++++++++--- internal/vaultik/prune_count_test.go | 4 +- internal/vaultik/remote_info_test.go | 69 ++++++++++++++++++++++++++++ internal/vaultik/snapshot.go | 8 ++-- 6 files changed, 110 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 5d2188b..5c58a8f 100644 --- a/README.md +++ b/README.md @@ -398,7 +398,8 @@ key is skipped with a warning and is not printed. If a listed orphaned blob figures are reported as unknown; `--json` gives them as `null`, lists the remote key of each unreadable manifest in `unreadable_manifests` and counts the manifests under skipped names in -`skipped_manifest_count`. +`skipped_manifest_count`. An unreadable manifest also leaves its +snapshot's blob count and blob size unknown, `null` in `--json`. * `--json`: Output as JSON **`remote nuke`**: Delete every snapshot's metadata and every blob from the diff --git a/TODO.md b/TODO.md index 4e052b4..97be9f1 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,15 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-08: Made `remote info` report a snapshot's blob count and + blob size as unknown when its manifest cannot be read + ([issue #272](https://git.eeqj.de/sneak/vaultik/issues/272)). The + orphan figures were already unknown in that case, but the snapshot's + row still gave 0 blobs and 0 B, in the table and in `--json`. The row + now reads `unknown` and `--json` gives `null`. A directory with no + manifest still shows 0, since the orphan figures count its blobs as + orphaned. + - 2026-10-08: Kept the progress line of a snapshot with more than one path within 100% ([issue #271](https://git.eeqj.de/sneak/vaultik/issues/271)). The diff --git a/internal/vaultik/info.go b/internal/vaultik/info.go index a39659d..e587e27 100644 --- a/internal/vaultik/info.go +++ b/internal/vaultik/info.go @@ -181,8 +181,11 @@ type SnapshotMetadataInfo struct { ManifestSize int64 `json:"manifest_size"` DatabaseSize int64 `json:"database_size"` TotalSize int64 `json:"total_size"` - BlobCount int `json:"blob_count"` - BlobsSize int64 `json:"blobs_size"` + + // Both stay nil (null in the JSON) when the snapshot's manifest was + // listed but could not be read. + BlobCount *int `json:"blob_count"` + BlobsSize *int64 `json:"blobs_size"` // Set when the listing holds this snapshot's manifest.json.zst. A // backup interrupted before its manifest upload leaves a directory @@ -380,6 +383,10 @@ func (v *Vaultik) collectReferencedBlobsFromManifests( for _, snapshotID := range snapshotIDs { info := snapshotMetadata[snapshotID] if !info.hasManifest { + // The orphan figures count this directory's blobs as + // orphaned, so it references none. + info.BlobCount, info.BlobsSize = new(int), new(int64) + continue } @@ -395,7 +402,7 @@ func (v *Vaultik) collectReferencedBlobsFromManifests( continue } - info.BlobCount = manifest.BlobCount + blobCount := manifest.BlobCount var blobsSize int64 @@ -404,7 +411,8 @@ func (v *Vaultik) collectReferencedBlobsFromManifests( blobsSize += blob.CompressedSize } - info.BlobsSize = blobsSize + info.BlobCount = &blobCount + info.BlobsSize = &blobsSize } return referencedBlobs, unreadable @@ -516,13 +524,23 @@ func (v *Vaultik) printRemoteInfoTable(result *RemoteInfoResult) { v.stdoutf("%s", separator) for _, info := range result.Snapshots { + blobCount := unknownText + if info.BlobCount != nil { + blobCount = humanize.Comma(int64(*info.BlobCount)) + } + + blobsSize := unknownText + if info.BlobsSize != nil { + blobsSize = ubytes(*info.BlobsSize) + } + v.stdoutf(rowFormat, truncateString(info.SnapshotID, snapshotIDColWidth), ubytes(info.ManifestSize), ubytes(info.DatabaseSize), ubytes(info.TotalSize), - humanize.Comma(int64(info.BlobCount)), - ubytes(info.BlobsSize), + blobCount, + blobsSize, ) } diff --git a/internal/vaultik/prune_count_test.go b/internal/vaultik/prune_count_test.go index ab9268f..11401c6 100644 --- a/internal/vaultik/prune_count_test.go +++ b/internal/vaultik/prune_count_test.go @@ -42,7 +42,7 @@ func TestTableCountForReportSurfacesReadFailure(t *testing.T) { assert.Nil(t, missing, "a failed read is unknown, not a count") // The rendered count for a failed read must say unknown, never 0. - assert.Equal(t, countUnknown, countText(missing)) + assert.Equal(t, unknownText, countText(missing)) assert.NotEqual(t, "0", countText(missing)) } @@ -57,7 +57,7 @@ func TestCountTextDistinguishesEmptyFromUnknown(t *testing.T) { assert.Equal(t, "0", countText(&zero)) assert.Equal(t, "7", countText(&seven)) - assert.Equal(t, countUnknown, countText(nil)) + assert.Equal(t, unknownText, countText(nil)) } // TestCountDiffUnknownWhenEitherSideUnknown checks that a delta computed diff --git a/internal/vaultik/remote_info_test.go b/internal/vaultik/remote_info_test.go index 2c6c8da..ceb5f11 100644 --- a/internal/vaultik/remote_info_test.go +++ b/internal/vaultik/remote_info_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "strings" "testing" "time" @@ -69,6 +70,74 @@ func TestRemoteInfo_UnreadableManifestLeavesOrphansUnknown(t *testing.T) { assert.Equal(t, []any{unreadableKey}, doc["unreadable_manifests"]) } +// TestRemoteInfo_UnreadableManifestLeavesSnapshotBlobsUnknown checks +// that the row of a snapshot whose manifest cannot be read gives its +// blob count and blob size as unknown in the table and as null in +// --json, not as 0. A directory without a manifest still shows 0: the +// orphan figures count its blobs as orphaned, so it references none. +func TestRemoteInfo_UnreadableManifestLeavesSnapshotBlobsUnknown(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + readableKey := env.addRemote(t, listRemoteID, + time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + + unreadableKey := snapshot.RemoteSnapshotKey(listLocalID) + require.NoError(t, env.store.Put(context.Background(), + "metadata/"+unreadableKey+"/manifest.json.zst", + bytes.NewReader([]byte("not a valid manifest")))) + + noManifestKey := snapshot.RemoteSnapshotKey("testhost_home_2026-03-03T10:00:00Z") + require.NoError(t, env.store.Put(context.Background(), + "metadata/"+noManifestKey+"/db.zst.age", + bytes.NewReader([]byte("not a valid database")))) + + require.NoError(t, env.v.RemoteInfo(false)) + + // The table truncates the remote key, so a row is found by a prefix. + wantUnknown := map[string]int{readableKey: 0, unreadableKey: 2, noManifestKey: 0} + for key, want := range wantUnknown { + var row string + + for line := range strings.SplitSeq(env.stdout.String(), "\n") { + if strings.HasPrefix(line, key[:16]) { + row = line + } + } + + require.NotEmpty(t, row, "no table row for %s", key) + assert.Equal(t, want, strings.Count(row, "unknown"), "row: %q", row) + } + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(true)) + + var doc struct { + Snapshots []map[string]any `json:"snapshots"` + } + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &doc)) + require.Len(t, doc.Snapshots, len(wantUnknown)) + + for _, entry := range doc.Snapshots { + switch entry["snapshot_id"] { + case readableKey: + assert.InDelta(t, 1, entry["blob_count"], 0) + assert.InDelta(t, fiveMegabytes, entry["blobs_size"], 0) + case noManifestKey: + assert.InDelta(t, 0, entry["blob_count"], 0) + assert.InDelta(t, 0, entry["blobs_size"], 0) + default: + assert.Equal(t, unreadableKey, entry["snapshot_id"]) + assert.Contains(t, entry, "blob_count") + assert.Nil(t, entry["blob_count"]) + assert.Contains(t, entry, "blobs_size") + assert.Nil(t, entry["blobs_size"]) + } + } +} + // TestRemoteInfo_SkipsNonConformingMetadataName checks that a directory // under metadata/ whose name is not a remote key is left out of the // report, and that the orphan figures are unknown when it holds a diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 43ab3e1..0b14640 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -1756,9 +1756,9 @@ func (v *Vaultik) PruneDatabase() (*PruneResult, error) { return result, nil } -// countUnknown is what a count reads as when its query could not be run, -// distinct from "0", which means the table really was empty. -const countUnknown = "unknown" +// unknownText is what a count or size reads as when it could not be +// determined, distinct from "0", which is a real zero. +const unknownText = "unknown" // tableCountForReport returns the row count of a table for the prune // summary, or nil if the count could not be read. A read failure is @@ -1795,7 +1795,7 @@ func countDiff(before, after *int64) *int64 { // one that could not be queried. func countText(count *int64) string { if count == nil { - return countUnknown + return unknownText } return strconv.FormatInt(*count, 10) From 79a73fa122fce43fa42153a54b0d0f9cffe46dc1 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 8 Oct 2026 10:12:10 +0200 Subject: [PATCH 039/121] Count a file a backup could not store as failed (closes #280) A file that phase 1 of a backup counted and phase 2 could not open, because it was unreadable under --skip-errors or removed in between, was added to the unchanged count while its size stayed in BytesScanned. The summary showed it as unchanged with its bytes backed up, and the snapshots row's file_count and total_size included it. The scanner now counts such a file in FilesFailed and takes its size out of BytesScanned. The summary's files line adds "N failed", and file_count leaves the file out. A directory phase 2 cannot record is not counted as failed, since phase 1 counts no directories; that case has no test. Model: opus-5-5 --- TODO.md | 9 ++ internal/snapshot/scanner.go | 21 ++- internal/snapshot/snapshot.go | 2 +- internal/vaultik/snapshot.go | 14 +- internal/vaultik/snapshot_failed_file_test.go | 123 ++++++++++++++++++ 5 files changed, 163 insertions(+), 6 deletions(-) create mode 100644 internal/vaultik/snapshot_failed_file_test.go diff --git a/TODO.md b/TODO.md index 97be9f1..2c8fffe 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,15 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-08: Counted a file that a backup could not store as failed + ([issue #280](https://git.eeqj.de/sneak/vaultik/issues/280)). A file + that phase 1 counted and phase 2 could not open, because it was + unreadable under `--skip-errors` or removed in between, was reported + in the summary as unchanged with its bytes as backed up, and the + `snapshots` row's `file_count` and `total_size` included it. The + summary now counts it as failed, and its data total and the row leave + it out. + - 2026-10-08: Made `remote info` report a snapshot's blob count and blob size as unknown when its manifest cannot be read ([issue #272](https://git.eeqj.de/sneak/vaultik/issues/272)). The diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 79d7e33..70641c0 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -133,10 +133,13 @@ type ScannerConfig struct { // ScanResult contains the results of a scan operation. Files and bytes // are counted per file: BytesScanned is the size of the new and changed -// files, BytesSkipped that of the unchanged ones. +// files, BytesSkipped that of the unchanged ones. FilesFailed counts the +// new and changed files that phase 2 could not store; FilesScanned +// includes them and BytesScanned does not. type ScanResult struct { FilesScanned int FilesSkipped int + FilesFailed int FilesDeleted int BytesScanned int64 BytesSkipped int64 @@ -1365,7 +1368,7 @@ func (s *Scanner) processFileWithErrorHandling( log.Warn("File was deleted during backup, skipping", "path", fileToProcess.Path) - result.FilesSkipped++ + countFailedFile(fileToProcess, result) return true, nil } @@ -1376,7 +1379,7 @@ func (s *Scanner) processFileWithErrorHandling( s.ui.Errorf("Failed to process %s: %v. Skipping (--skip-errors).", s.ui.Path(fileToProcess.Path), err) - result.FilesSkipped++ + countFailedFile(fileToProcess, result) return true, nil } @@ -1387,6 +1390,18 @@ func (s *Scanner) processFileWithErrorHandling( return false, nil } +// countFailedFile counts a file that phase 2 could not store as failed +// and takes its size back out of BytesScanned, where phase 1 put it. +// Phase 1 counts no directories, so a directory is not counted here. +func countFailedFile(fileToProcess *FileToProcess, result *ScanResult) { + if fileToProcess.FileInfo.IsDir() { + return + } + + result.FilesFailed++ + result.BytesScanned -= fileToProcess.FileInfo.Size() +} + // printProcessingProgress prints a periodic progress line during the process phase, // showing files processed, bytes transferred, throughput, and ETA func (s *Scanner) printProcessingProgress( diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 05e1ac1..cdf641e 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -892,7 +892,7 @@ func (sm *SnapshotManager) getFileSize(path string) int64 { // BackupStats contains statistics from a backup operation type BackupStats struct { FilesScanned int - TotalSize int64 // Total size of all files examined + TotalSize int64 // Total size of the files in the snapshot ChunksCreated int BlobsCreated int BytesUploaded int64 diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 0b14640..97ecfdb 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -185,6 +185,7 @@ type snapshotStats struct { totalBlobs int totalBytesSkipped int64 totalFilesSkipped int + totalFilesFailed int totalFilesDeleted int totalBytesDeleted int64 totalBytesUploaded int64 @@ -315,6 +316,7 @@ func (v *Vaultik) scanAllDirectories( stats.totalChunks += result.ChunksCreated stats.totalBlobs += result.BlobsCreated stats.totalFilesSkipped += result.FilesSkipped + stats.totalFilesFailed += result.FilesFailed stats.totalBytesSkipped += result.BytesSkipped stats.totalFilesDeleted += result.FilesDeleted stats.totalBytesDeleted += result.BytesDeleted @@ -326,6 +328,7 @@ func (v *Vaultik) scanAllDirectories( "path", dir, "files", result.FilesScanned, "files_skipped", result.FilesSkipped, + "files_failed", result.FilesFailed, "bytes", result.BytesScanned, "bytes_skipped", result.BytesSkipped, "chunks", result.ChunksCreated, @@ -359,9 +362,11 @@ func (v *Vaultik) finalizeSnapshotMetadata( return fmt.Errorf("getting snapshot blob sizes: %w", err) } + // file_count and total_size leave out the files that could not be + // stored; stats.totalBytes already does. extStats := snapshot.ExtendedBackupStats{ BackupStats: snapshot.BackupStats{ - FilesScanned: stats.totalFiles, + FilesScanned: stats.totalFiles - stats.totalFilesFailed, TotalSize: stats.totalBytes + stats.totalBytesSkipped, ChunksCreated: stats.totalChunks, BlobsCreated: stats.totalBlobs, @@ -409,7 +414,8 @@ func (v *Vaultik) printSnapshotSummary( snapshotID string, startTime time.Time, stats *snapshotStats, ) { snapshotDuration := time.Since(startTime) - totalFilesChanged := stats.totalFiles - stats.totalFilesSkipped + totalFilesChanged := stats.totalFiles - stats.totalFilesSkipped - + stats.totalFilesFailed totalBytesAll := stats.totalBytes + stats.totalBytesSkipped var compressionRatio float64 @@ -426,6 +432,10 @@ func (v *Vaultik) printSnapshotSummary( v.UI.Count(stats.totalFiles), v.UI.Count(totalFilesChanged), v.UI.Count(stats.totalFilesSkipped)) + if stats.totalFilesFailed > 0 { + filesMsg += fmt.Sprintf(", %s failed", v.UI.Count(stats.totalFilesFailed)) + } + if stats.totalFilesDeleted > 0 { filesMsg += fmt.Sprintf(", %s deleted", v.UI.Count(stats.totalFilesDeleted)) } diff --git a/internal/vaultik/snapshot_failed_file_test.go b/internal/vaultik/snapshot_failed_file_test.go new file mode 100644 index 0000000..a5f8bc4 --- /dev/null +++ b/internal/vaultik/snapshot_failed_file_test.go @@ -0,0 +1,123 @@ +package vaultik_test + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// openFailFs is the real filesystem, except that opening path fails +// with err. Phase 1 of a backup only lstats a file, so it still counts +// path; phase 2 is the first to open it. +type openFailFs struct { + afero.OsFs + + path string + err error +} + +//nolint:ireturn // afero.Fs.Open is defined to return the interface. +func (f *openFailFs) Open(name string) (afero.File, error) { + if name == f.path { + return nil, &os.PathError{Op: "open", Path: name, Err: f.err} + } + + return f.OsFs.Open(name) +} + +// A file that phase 2 cannot open is reported as failed, not as +// unchanged, and neither the summary's data total nor the snapshots row +// counts it. See https://git.eeqj.de/sneak/vaultik/issues/280. +func TestSnapshotSummaryCountsFileNotStoredAsFailed(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + tests := []struct { + name string + openErr error + skipErrors bool + }{ + // What a normal user gets opening a file with mode 000. + {name: "unopenable under skip-errors", + openErr: os.ErrPermission, skipErrors: true}, + // What opening a file removed after phase 1 gives. + {name: "removed between the phases", + openErr: os.ErrNotExist, skipErrors: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + // The scan walks the source path with symlinks resolved, so + // failedPath must be spelled the same way to match. + tempDir, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + + srcDir := filepath.Join(tempDir, "src") + failedPath := filepath.Join(srcDir, "failed.txt") + storedContent := []byte("this file is backed up") + storedSize := int64(len(storedContent)) + + fs := &openFailFs{path: failedPath, err: tt.openErr} + require.NoError(t, fs.MkdirAll(srcDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(srcDir, "stored.txt"), storedContent, 0o644)) + require.NoError(t, afero.WriteFile(fs, + failedPath, []byte("this file cannot be opened"), 0o644)) + + cfg := faultTestConfig() + cfg.IndexPath = filepath.Join(tempDir, "index.sqlite") + cfg.Snapshots = map[string]config.SnapshotConfig{ + "src": {Paths: []string{srcDir}}, + } + + store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + require.NoError(t, err) + + db, err := database.New(ctx, cfg.IndexPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + out := &bytes.Buffer{} + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + v.UI = ui.NewWithColor(out, false) + + require.NoError(t, v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: tt.skipErrors, + Snapshots: []string{"src"}, + })) + + summary := out.String() + assert.Contains(t, summary, + "Files: 2 examined, 1 backed up, 0 unchanged, 1 failed.") + assert.Contains(t, summary, + fmt.Sprintf("Data: %s total (%s backed up).", + v.UI.Size(storedSize), v.UI.Size(storedSize))) + + snap, err := repos.Snapshots.GetByID(ctx, + localSnapshotID(ctx, t, repos, "src")) + require.NoError(t, err) + require.NotNil(t, snap) + + assert.Equal(t, int64(1), snap.FileCount) + assert.Equal(t, storedSize, snap.TotalSize) + }) + } +} From 05bf73c48a20d224284d92fd77bbf1801cd38b2b Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 8 Oct 2026 12:59:26 +0200 Subject: [PATCH 040/121] Never skip a local index error for a directory or symlink (closes #284) Under --skip-errors, an error recording a directory or symlink in the local index was skipped like an unreadable file. The snapshot completed without the entry, and a restore did not recreate it. processFileWithErrorHandling now records a directory or symlink itself and returns any error, which stops the backup with or without the flag. The skip sees only a regular file's errors, so countFailedFile no longer checks for a directory. The test injects the error with a SQLite trigger that refuses the directory's files row. Model: opus-5-5 --- TODO.md | 9 +++ internal/snapshot/scanner.go | 32 ++++---- internal/vaultik/snapshot_skip_errors_test.go | 75 +++++++++++++++++++ 3 files changed, 102 insertions(+), 14 deletions(-) create mode 100644 internal/vaultik/snapshot_skip_errors_test.go diff --git a/TODO.md b/TODO.md index 2c8fffe..930a1ae 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,15 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-08: Made a local index error while recording a directory or + symlink stop a backup under `--skip-errors` + ([issue #284](https://git.eeqj.de/sneak/vaultik/issues/284)). Phase 2 + only records such an entry in the local index, since it has no data + to open or read, but an error doing so was skipped like an unreadable + file. The snapshot then completed without the entry, and a restore + did not recreate it. The error now stops the backup, as it does + without the flag. + - 2026-10-08: Counted a file that a backup could not store as failed ([issue #280](https://git.eeqj.de/sneak/vaultik/issues/280)). A file that phase 1 counted and phase 2 could not open, because it was diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 70641c0..4527f69 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -1348,11 +1348,25 @@ func (s *Scanner) processPhase( return s.finalizeProcessPhase(ctx, result) } -// processFileWithErrorHandling wraps processFileStreaming with error recovery for -// deleted files and skip-errors mode. Returns (skipped, error). +// processFileWithErrorHandling records a directory or symlink, or wraps +// processFileStreaming for a regular file with error recovery for deleted +// files and skip-errors mode. Returns (skipped, error). func (s *Scanner) processFileWithErrorHandling( ctx context.Context, fileToProcess *FileToProcess, result *ScanResult, ) (bool, error) { + // A directory or symlink has no data to open or read; it is only + // recorded in the local index. An error recording it stops the run + // even under --skip-errors, or the snapshot would complete without it. + mode := os.FileMode(fileToProcess.File.Mode) + if mode&os.ModeSymlink != 0 || mode.IsDir() { + err := s.recordNonRegularFile(ctx, fileToProcess) + if err != nil { + return false, fmt.Errorf("processing file %s: %w", fileToProcess.Path, err) + } + + return false, nil + } + err := s.processFileStreaming(ctx, fileToProcess, result) if err != nil { // A packer/database/encryption/upload failure means the chunk's data @@ -1392,12 +1406,7 @@ func (s *Scanner) processFileWithErrorHandling( // countFailedFile counts a file that phase 2 could not store as failed // and takes its size back out of BytesScanned, where phase 1 put it. -// Phase 1 counts no directories, so a directory is not counted here. func countFailedFile(fileToProcess *FileToProcess, result *ScanResult) { - if fileToProcess.FileInfo.IsDir() { - return - } - result.FilesFailed++ result.BytesScanned -= fileToProcess.FileInfo.Size() } @@ -1770,16 +1779,11 @@ func (e *packerError) Error() string { return e.err.Error() } func (e *packerError) Unwrap() error { return e.err } -// processFileStreaming processes a file by streaming chunks directly to the packer +// processFileStreaming processes a regular file by streaming chunks directly +// to the packer func (s *Scanner) processFileStreaming( ctx context.Context, fileToProcess *FileToProcess, result *ScanResult, ) error { - // Symlinks and directories have no data to chunk — just record them in the DB. - mode := os.FileMode(fileToProcess.File.Mode) - if mode&os.ModeSymlink != 0 || mode.IsDir() { - return s.recordNonRegularFile(ctx, fileToProcess) - } - file, err := s.fs.Open(fileToProcess.Path) if err != nil { return fmt.Errorf("opening file: %w", wrapPermissionError(fileToProcess.Path, err)) diff --git a/internal/vaultik/snapshot_skip_errors_test.go b/internal/vaultik/snapshot_skip_errors_test.go new file mode 100644 index 0000000..0f88515 --- /dev/null +++ b/internal/vaultik/snapshot_skip_errors_test.go @@ -0,0 +1,75 @@ +package vaultik_test + +import ( + "context" + "fmt" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// --skip-errors skips only a file that cannot be opened or read. A local +// index error while a directory is recorded stops the backup, and the +// snapshot is not recorded as complete. See +// https://git.eeqj.de/sneak/vaultik/issues/284. +func TestSkipErrorsBackupStopsOnIndexErrorRecordingDirectory(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + + // The scan walks the source path with symlinks resolved, so dirPath + // must be spelled the same way to match the row the scan inserts. + tempDir, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + + srcDir := filepath.Join(tempDir, "src") + dirPath := filepath.Join(srcDir, "dir") + + fs := afero.NewOsFs() + require.NoError(t, fs.MkdirAll(dirPath, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dirPath, "file.txt"), []byte("file content"), 0o644)) + + cfg := faultTestConfig() + cfg.IndexPath = filepath.Join(tempDir, "index.sqlite") + cfg.Snapshots = map[string]config.SnapshotConfig{ + "tree": {Paths: []string{srcDir}}, + } + + store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + require.NoError(t, err) + + db, err := database.New(ctx, cfg.IndexPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + // The local index refuses the directory's files row. + _, err = db.Conn().ExecContext(ctx, fmt.Sprintf(` + CREATE TRIGGER refuse_directory BEFORE INSERT ON files + WHEN NEW.path = '%s' + BEGIN SELECT RAISE(ABORT, 'simulated index error'); END`, dirPath)) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + err = v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: true, + Snapshots: []string{"tree"}, + }) + require.ErrorContains(t, err, "simulated index error") + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1) + assert.Nil(t, snapshots[0].CompletedAt) +} From 34f61fb408efbb93e7a1e78f071fef61b9d36cb1 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 8 Oct 2026 14:17:20 +0200 Subject: [PATCH 041/121] Make remote nuke delete leftover .partial uploads (closes #281) The file and rclone listings skip an object whose name ends in `.partial`, the temporary name a `file://` or rclone upload writes before moving the object into place. `remote nuke` deletes only what the listings return, so it left the `.partial` objects killed uploads leave behind and still reported the destination store empty. Storer gains DeletePartialUploads. The file and rclone backends remove every `.partial` object under the prefix; S3 has none to remove, since it shows an object only once its upload completes. `remote nuke` calls it for `metadata/` and `blobs/` as its last step. Empty directories under a `file://` destination are still left behind. Model: opus-5-5 --- TODO.md | 7 ++ internal/storage/faultstore/faultstore.go | 5 ++ internal/storage/file.go | 36 +++++++++++ internal/storage/file_atomic_test.go | 42 ++++++++++++ internal/storage/rclone.go | 25 ++++++++ internal/storage/rclone_test.go | 41 ++++++++++++ internal/storage/s3.go | 6 ++ internal/storage/storer.go | 6 ++ .../vaultik/destination_validation_test.go | 4 ++ internal/vaultik/integration_test.go | 6 ++ internal/vaultik/nuke_remote_test.go | 64 +++++++++++++++++++ internal/vaultik/prune.go | 14 +++- internal/vaultik/remove_snapshot_test.go | 6 ++ 13 files changed, 260 insertions(+), 2 deletions(-) create mode 100644 internal/vaultik/nuke_remote_test.go diff --git a/TODO.md b/TODO.md index 930a1ae..46585b4 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,13 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-08: Made `remote nuke` delete the `.partial` files that + uploads cut off part-way leave on the destination store + ([issue #281](https://git.eeqj.de/sneak/vaultik/issues/281)). The + file and rclone listings skip such a file, so the command left it in + place and still reported the store empty. It now removes them under + `metadata/` and `blobs/` as its last step. + - 2026-10-08: Made a local index error while recording a directory or symlink stop a backup under `--skip-errors` ([issue #284](https://git.eeqj.de/sneak/vaultik/issues/284)). Phase 2 diff --git a/internal/storage/faultstore/faultstore.go b/internal/storage/faultstore/faultstore.go index 3aad29a..ae5d889 100644 --- a/internal/storage/faultstore/faultstore.go +++ b/internal/storage/faultstore/faultstore.go @@ -171,6 +171,11 @@ func (f *Storer) ListStream( return f.inner.ListStream(ctx, prefix) } +// DeletePartialUploads delegates unchanged. +func (f *Storer) DeletePartialUploads(ctx context.Context, prefix string) error { + return f.inner.DeletePartialUploads(ctx, prefix) +} + // Info delegates unchanged. func (f *Storer) Info() storage.Info { return f.inner.Info() diff --git a/internal/storage/file.go b/internal/storage/file.go index 7cb5653..7bb74d1 100644 --- a/internal/storage/file.go +++ b/internal/storage/file.go @@ -242,6 +242,42 @@ func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan Objec return ch } +// DeletePartialUploads removes every file under prefix whose name ends in +// tempSuffix. A missing prefix has none to remove. +func (f *FileStorer) DeletePartialUploads(ctx context.Context, prefix string) error { + basePath := f.fullPath(prefix) + + exists, err := afero.Exists(f.fs, basePath) + if err != nil { + return fmt.Errorf("checking path: %w", err) + } + + if !exists { + return nil + } + + err = afero.Walk(f.fs, basePath, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + if ctx.Err() != nil { + return ctx.Err() + } + + if info.IsDir() || !strings.HasSuffix(info.Name(), tempSuffix) { + return nil + } + + return f.fs.Remove(path) + }) + if err != nil { + return fmt.Errorf("walking directory: %w", err) + } + + return nil +} + // Info returns human-readable storage location information. func (f *FileStorer) Info() Info { return Info{ diff --git a/internal/storage/file_atomic_test.go b/internal/storage/file_atomic_test.go index b9be4e6..6030ea2 100644 --- a/internal/storage/file_atomic_test.go +++ b/internal/storage/file_atomic_test.go @@ -120,3 +120,45 @@ func TestFileStorer_ListSkipsPartialFiles(t *testing.T) { t.Fatalf("ListStream should return only the real key, got %v", streamed) } } + +// TestFileStorer_DeletePartialUploads checks that a leftover temp file is +// removed and the object at the real key is kept. +func TestFileStorer_DeletePartialUploads(t *testing.T) { + t.Parallel() + + base := t.TempDir() + + f, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + ctx := context.Background() + + err = f.Put(ctx, testBlobKey, strings.NewReader("blob-bytes")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + leftover := filepath.Join(base, testBlobKey+"-123456.partial") + + err = os.WriteFile(leftover, []byte("half"), 0o600) + if err != nil { + t.Fatalf("writing leftover temp file: %v", err) + } + + err = f.DeletePartialUploads(ctx, "blobs/") + if err != nil { + t.Fatalf("DeletePartialUploads: %v", err) + } + + _, err = os.Stat(leftover) + if !os.IsNotExist(err) { + t.Errorf("leftover temp file was not removed: %v", err) + } + + _, err = f.Stat(ctx, testBlobKey) + if err != nil { + t.Errorf("Stat of the real key: %v", err) + } +} diff --git a/internal/storage/rclone.go b/internal/storage/rclone.go index dfc8e1f..43ac7ba 100644 --- a/internal/storage/rclone.go +++ b/internal/storage/rclone.go @@ -213,6 +213,31 @@ func (r *RcloneStorer) ListStream( return ch } +// DeletePartialUploads removes every object under prefix whose name ends +// in tempSuffix. +func (r *RcloneStorer) DeletePartialUploads(ctx context.Context, prefix string) error { + var partial []fs.Object + + err := operations.ListFn(ctx, r.fsys, func(obj fs.Object) { + key := obj.Remote() + if strings.HasPrefix(key, prefix) && strings.HasSuffix(key, tempSuffix) { + partial = append(partial, obj) + } + }) + if err != nil { + return fmt.Errorf("listing objects: %w", err) + } + + for _, obj := range partial { + err = obj.Remove(ctx) + if err != nil { + return fmt.Errorf("removing object: %w", err) + } + } + + return nil +} + // Info returns human-readable storage location information. func (r *RcloneStorer) Info() Info { location := r.remote diff --git a/internal/storage/rclone_test.go b/internal/storage/rclone_test.go index 8179e8d..c666a64 100644 --- a/internal/storage/rclone_test.go +++ b/internal/storage/rclone_test.go @@ -198,6 +198,47 @@ func TestRcloneStorerListSkipsPartialFiles(t *testing.T) { } } +// TestRcloneStorerDeletePartialUploads checks that a temporary file left +// by a killed upload is removed and the object at the real key is kept. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerDeletePartialUploads(t *testing.T) { + dir := t.TempDir() + ctx := context.Background() + + s, err := storage.NewRcloneStorer(ctx, ":local", dir) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + err = s.Put(ctx, testBlobKey, strings.NewReader("blob-bytes")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + leftover := filepath.Join(dir, testBlobKey+"-123456.partial") + + err = os.WriteFile(leftover, []byte("half"), 0o600) + if err != nil { + t.Fatalf("writing leftover temp file: %v", err) + } + + err = s.DeletePartialUploads(ctx, "blobs/") + if err != nil { + t.Fatalf("DeletePartialUploads: %v", err) + } + + _, err = os.Stat(leftover) + if !os.IsNotExist(err) { + t.Errorf("leftover temp file was not removed: %v", err) + } + + _, err = s.Stat(ctx, testBlobKey) + if err != nil { + t.Errorf("Stat of the real key: %v", err) + } +} + // newRcloneStorerOnWrappedLocal registers name as rclone's local backend // wrapped by wrap, and builds an rclone backend on it rooted at a fresh // temp directory. wrap changes the features the local backend reports, so diff --git a/internal/storage/s3.go b/internal/storage/s3.go index 648e697..4f2b53b 100644 --- a/internal/storage/s3.go +++ b/internal/storage/s3.go @@ -99,6 +99,12 @@ func (s *S3Storer) ListStream(ctx context.Context, prefix string) <-chan ObjectI return ch } +// DeletePartialUploads has nothing to remove: S3 shows an object only once +// its upload has completed, so an upload cut off part-way leaves none. +func (s *S3Storer) DeletePartialUploads(_ context.Context, _ string) error { + return nil +} + // Info returns human-readable storage location information. func (s *S3Storer) Info() Info { return Info{ diff --git a/internal/storage/storer.go b/internal/storage/storer.go index 2334a7d..44a4861 100644 --- a/internal/storage/storer.go +++ b/internal/storage/storer.go @@ -71,6 +71,12 @@ type Storer interface { // If an error occurs during listing, the final item will have Err set. ListStream(ctx context.Context, prefix string) <-chan ObjectInfo + // DeletePartialUploads removes every object under prefix that an + // upload cut off part-way left under a temporary name ending in + // `.partial`. The file and rclone backends' List and ListStream skip + // such an object. + DeletePartialUploads(ctx context.Context, prefix string) error + // Info returns human-readable storage location information. Info() Info } diff --git a/internal/vaultik/destination_validation_test.go b/internal/vaultik/destination_validation_test.go index d154fc9..4a083bf 100644 --- a/internal/vaultik/destination_validation_test.go +++ b/internal/vaultik/destination_validation_test.go @@ -257,6 +257,10 @@ func (s *stubLister) List(_ context.Context, _ string) ([]string, error) { return nil, errStubUnused } +func (s *stubLister) DeletePartialUploads(_ context.Context, _ string) error { + return errStubUnused +} + func (s *stubLister) Info() storage.Info { return storage.Info{} } diff --git a/internal/vaultik/integration_test.go b/internal/vaultik/integration_test.go index ded2e7e..e2891ee 100644 --- a/internal/vaultik/integration_test.go +++ b/internal/vaultik/integration_test.go @@ -155,6 +155,12 @@ func (m *MockStorer) ListStream( return ch } +// DeletePartialUploads has nothing to remove: Put stores each object +// under its key at once. +func (m *MockStorer) DeletePartialUploads(_ context.Context, _ string) error { + return nil +} + func (m *MockStorer) Info() storage.Info { return storage.Info{ Type: "mock", diff --git a/internal/vaultik/nuke_remote_test.go b/internal/vaultik/nuke_remote_test.go new file mode 100644 index 0000000..6e22699 --- /dev/null +++ b/internal/vaultik/nuke_remote_test.go @@ -0,0 +1,64 @@ +package vaultik_test + +import ( + "context" + "io/fs" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" +) + +// TestNukeRemoteLeavesNoFiles checks that remote nuke leaves no file +// under a file:// destination, including the `.partial` files uploads +// killed part-way leave next to a snapshot's metadata and next to where a +// blob would have been. +func TestNukeRemoteLeavesNoFiles(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1) + + snapshotKey := snapshot.RemoteSnapshotKey(snapshots[0].ID.String()) + hash := testBlobHashA + leftovers := []string{ + filepath.Join(storeDir, "metadata", snapshotKey, + "db.zst.age-123456.partial"), + filepath.Join(storeDir, "blobs", hash[:2], hash[2:4], + hash+"-123456.partial"), + } + + for _, leftover := range leftovers { + require.NoError(t, os.MkdirAll(filepath.Dir(leftover), 0o750)) + require.NoError(t, os.WriteFile(leftover, []byte("half an upload"), 0o600)) + } + + require.NoError(t, v.NukeRemote(true)) + + var files []string + + err = filepath.WalkDir(storeDir, + func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + + if !entry.IsDir() { + files = append(files, path) + } + + return nil + }) + require.NoError(t, err) + assert.Empty(t, files) +} diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index 38bb135..6bd737a 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -24,8 +24,9 @@ var errNukeRequiresForce = errors.New( const metadataDirName = "metadata" // NukeRemote deletes every snapshot's metadata and every blob from remote -// storage. After this returns successfully the bucket prefix is empty and -// the next backup starts from scratch. +// storage, along with any object an upload cut off part-way left under a +// temporary `.partial` name. After this returns successfully the bucket +// prefix is empty and the next backup starts from scratch. // // Refuses to run unless force is true. The caller is responsible for // confirming with the user. @@ -48,6 +49,15 @@ func (v *Vaultik) NukeRemote(force bool) error { return fmt.Errorf("pruning blobs: %w", err) } + // The file and rclone listings skip `.partial` objects, so the two + // steps above never delete them. + for _, prefix := range []string{"metadata/", "blobs/"} { + err = v.Storage.DeletePartialUploads(v.ctx, prefix) + if err != nil { + return fmt.Errorf("deleting partial uploads: %w", err) + } + } + v.UI.Completef("Backup destination store is now empty.") return nil diff --git a/internal/vaultik/remove_snapshot_test.go b/internal/vaultik/remove_snapshot_test.go index bed9ace..b337c1b 100644 --- a/internal/vaultik/remove_snapshot_test.go +++ b/internal/vaultik/remove_snapshot_test.go @@ -125,6 +125,12 @@ func (s *testStorer) ListStream( return ch } +// DeletePartialUploads has nothing to remove: Put stores each object +// under its key at once. +func (s *testStorer) DeletePartialUploads(_ context.Context, _ string) error { + return nil +} + func (s *testStorer) Info() storage.Info { return storage.Info{ Type: testLabel, From fa56165fe4daf7b062105a6e5ca6cc2246ee5275 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 8 Oct 2026 15:12:07 +0200 Subject: [PATCH 042/121] Stop a cancelled backup at once under --skip-errors (closes #286) After Ctrl-C or SIGTERM, phase 2 of a --skip-errors backup treated the cancellation error from each remaining file like an unreadable file: it opened the file, printed an error line, counted it as failed and moved on to the next. The processing loop now checks for cancellation before each file, and an error from a file once the run is cancelled stops the run instead of being skipped. The loop check is what stops a run cancelled while an empty file is open, since an empty file has no chunks and nothing reads the context while it is backed up. The --skip-errors test helper now takes the scan's context. Model: opus-5-5 --- TODO.md | 8 ++ internal/snapshot/scanner.go | 12 +++ internal/snapshot/skip_errors_test.go | 101 +++++++++++++++++++++++--- 3 files changed, 110 insertions(+), 11 deletions(-) diff --git a/TODO.md b/TODO.md index 46585b4..aab8ceb 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,14 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-08: Made a backup cancelled under `--skip-errors` stop at once + ([issue #286](https://git.eeqj.de/sneak/vaultik/issues/286)). After + Ctrl-C or SIGTERM, phase 2 treated the cancellation error from each + remaining file like an unreadable file: it opened the file, printed an + error line for it, counted it as failed and went on to the next one. + The run now stops at the first file after the cancellation, and no + file is counted as failed because of it. + - 2026-10-08: Made `remote nuke` delete the `.partial` files that uploads cut off part-way leave on the destination store ([issue #281](https://git.eeqj.de/sneak/vaultik/issues/281)). The diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 4527f69..c810278 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -1312,6 +1312,13 @@ func (s *Scanner) processPhase( // Process each file for _, fileToProcess := range filesToProcess { + // Check context cancellation + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + // Update progress if s.progress != nil { s.progress.GetStats().CurrentFile.Store(fileToProcess.Path) @@ -1369,6 +1376,11 @@ func (s *Scanner) processFileWithErrorHandling( err := s.processFileStreaming(ctx, fileToProcess, result) if err != nil { + // A cancelled run stops here even under --skip-errors, rather than + // counting this file as failed and going on to the next one. + if ctx.Err() != nil { + return false, fmt.Errorf("processing file %s: %w", fileToProcess.Path, err) + } // A packer/database/encryption/upload failure means the chunk's data // may not have been stored. Skipping the file would let the snapshot // record a file whose chunk is in no blob and cannot be restored, so diff --git a/internal/snapshot/skip_errors_test.go b/internal/snapshot/skip_errors_test.go index 8325372..04ad8de 100644 --- a/internal/snapshot/skip_errors_test.go +++ b/internal/snapshot/skip_errors_test.go @@ -82,6 +82,32 @@ func (f *readFailFs) Open(name string) (afero.File, error) { return file, nil } +// cancelOnOpenFs cancels the run when the scanner opens the target file to +// back it up, as Ctrl-C partway through processing would, and records each +// file opened after that. +type cancelOnOpenFs struct { + afero.Fs + + target string + cancel context.CancelFunc + cancelled bool + openedAfterCancel []string +} + +//nolint:ireturn // afero.Fs.Open is defined to return the interface. +func (f *cancelOnOpenFs) Open(name string) (afero.File, error) { + if f.cancelled { + f.openedAfterCancel = append(f.openedAfterCancel, name) + } + + if name == f.target { + f.cancel() + f.cancelled = true + } + + return f.Fs.Open(name) +} + // linkRemovedAfterLstatFs is the real filesystem, except that the symlink at // target is removed right after the walk lstats it, as happens when a link is // deleted during a backup. The scanner's readlink of it then fails. @@ -128,15 +154,16 @@ func writeSkipErrorTestFile(t *testing.T, fs afero.Fs, path, content string) { } } -// runSkipErrorScan scans source on fs with the given skip-errors setting, -// printing user-facing messages to uiw (nil discards them), and returns the -// repositories (for inspection) and the scan error. +// runSkipErrorScan scans source on fs under ctx with the given skip-errors +// setting, printing user-facing messages to uiw (nil discards them), and +// returns the repositories (for inspection) and the scan error. func runSkipErrorScan( - t *testing.T, fs afero.Fs, source string, skipErrors bool, uiw *ui.Writer, + ctx context.Context, t *testing.T, fs afero.Fs, source string, + skipErrors bool, uiw *ui.Writer, ) (*database.Repositories, error) { t.Helper() - db, err := database.NewTestDB() + db, err := database.New(ctx, ":memory:") if err != nil { t.Fatalf("create test db: %v", err) } @@ -161,7 +188,6 @@ func runSkipErrorScan( SkipErrors: skipErrors, }) - ctx := context.Background() snapshotID := "test-snapshot-skip-errors" createTestSnapshotRecord(ctx, t, repos, snapshotID) @@ -185,7 +211,7 @@ func TestScannerPackingFailureAbortsUnderSkipErrors(t *testing.T) { writeSkipErrorTestFile(t, fs, "/source/file1.txt", "first file content") writeSkipErrorTestFile(t, fs, "/source/file2.txt", "second file content") - repos, err := runSkipErrorScan(t, fs, "/source", true, nil) + repos, err := runSkipErrorScan(context.Background(), t, fs, "/source", true, nil) if err == nil { t.Fatal("expected scan to abort on the packer error, got nil") } @@ -212,7 +238,7 @@ func TestScannerReadErrorAbortsWithoutSkipErrors(t *testing.T) { fs := &readFailFs{Fs: afero.NewMemMapFs(), target: target} writeSkipErrorTestFile(t, fs, target, "content that cannot be read") - _, err := runSkipErrorScan(t, fs, "/source", false, nil) + _, err := runSkipErrorScan(context.Background(), t, fs, "/source", false, nil) if err == nil { t.Fatal("expected scan to fail on the read error, got nil") } @@ -228,7 +254,7 @@ func TestScannerReadErrorSkippedWithSkipErrors(t *testing.T) { fs := &readFailFs{Fs: afero.NewMemMapFs(), target: target} writeSkipErrorTestFile(t, fs, target, "content that cannot be read") - repos, err := runSkipErrorScan(t, fs, "/source", true, nil) + repos, err := runSkipErrorScan(context.Background(), t, fs, "/source", true, nil) if err != nil { t.Fatalf("expected scan to complete with --skip-errors, got %v", err) } @@ -267,7 +293,7 @@ func TestScannerUnreadableSymlinkAbortsWithoutSkipErrors(t *testing.T) { sourceDir, linkPath := writeSymlinkSource(t) fs := &linkRemovedAfterLstatFs{t: t, target: linkPath} - _, err := runSkipErrorScan(t, fs, sourceDir, false, nil) + _, err := runSkipErrorScan(context.Background(), t, fs, sourceDir, false, nil) if !errors.Is(err, os.ErrNotExist) { t.Fatalf("expected scan to fail on the removed symlink, got %v", err) } @@ -283,7 +309,7 @@ func TestScannerUnreadableSymlinkSkippedWithSkipErrors(t *testing.T) { fs := &linkRemovedAfterLstatFs{t: t, target: linkPath} uiw := ui.NewWithColor(io.Discard, false) - repos, err := runSkipErrorScan(t, fs, sourceDir, true, uiw) + repos, err := runSkipErrorScan(context.Background(), t, fs, sourceDir, true, uiw) if err != nil { t.Fatalf("expected scan to complete with --skip-errors, got %v", err) } @@ -302,3 +328,56 @@ func TestScannerUnreadableSymlinkSkippedWithSkipErrors(t *testing.T) { t.Fatalf("expected %s not to be recorded", linkPath) } } + +// TestScannerCancelStopsSkipErrorsRun checks that a --skip-errors backup +// cancelled partway through processing returns the cancellation error, +// opens no further file, and reports no file as failed. +func TestScannerCancelStopsSkipErrorsRun(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + targetContent string + }{ + // The cancellation lands while the target is being read. + {name: "while reading a file", targetContent: "first file content"}, + // An empty target has no chunks, so the cancellation goes unnoticed + // until the run moves on to the next file. + {name: "between files", targetContent: ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + const target = "/source/a.txt" + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fs := &cancelOnOpenFs{ + Fs: afero.NewMemMapFs(), target: target, cancel: cancel, + } + writeSkipErrorTestFile(t, fs, target, tt.targetContent) + writeSkipErrorTestFile(t, fs, "/source/b.txt", "second file content") + writeSkipErrorTestFile(t, fs, "/source/c.txt", "third file content") + + uiw := ui.NewWithColor(io.Discard, false) + + _, err := runSkipErrorScan(ctx, t, fs, "/source", true, uiw) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected the cancellation error, got %v", err) + } + + if len(fs.openedAfterCancel) != 0 { + t.Fatalf("expected no file opened after the cancellation, got %v", + fs.openedAfterCancel) + } + + if uiw.ErrorCount() != 0 { + t.Fatalf("expected no file reported as failed, got %d error lines", + uiw.ErrorCount()) + } + }) + } +} From c9a519c233e5d2551a82456745259814b6cdc4e1 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 01:51:24 +0200 Subject: [PATCH 043/121] Reject a retention duration longer than about 292 years (closes #289) parseDuration multiplied each number by the length of its unit with no limit, so from 293y (or 15251w, 3559mo, 106752d, or a sum such as 200y200y) the result wrapped to a negative duration. The purge cutoff then lay in the future and every snapshot of the name was selected, for --older-than and --keep-newer-than alike. Each part is now checked before it is added, and a total past the largest time.Duration is rejected as an invalid duration, so nothing is deleted. Go units were already safe: time.ParseDuration rejects an overflow. With --prune the backup still runs before the duration is read; only the prune step fails. Model: opus-5-5 --- TODO.md | 10 ++++++++ internal/vaultik/helpers.go | 32 ++++++++++++++++++------- internal/vaultik/helpers_test.go | 11 +++++++++ internal/vaultik/purge_per_name_test.go | 23 ++++++++++++++++++ 4 files changed, 68 insertions(+), 8 deletions(-) diff --git a/TODO.md b/TODO.md index aab8ceb..018c80c 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,16 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-12: Rejected a retention duration longer than about 292 years + ([issue #289](https://git.eeqj.de/sneak/vaultik/issues/289)). The + number given to `--older-than` or `--keep-newer-than` was multiplied + by the length of its unit with no limit, so from `293y`, `15251w`, + `3559mo` or `106752d`, or a sum of parts such as `200y200y`, the + result wrapped to a negative duration. The cutoff then lay in the + future, every snapshot of the name was deleted, the one just made + included, and the command exited 0. Such a duration is now rejected + as invalid and nothing is deleted. + - 2026-10-08: Made a backup cancelled under `--skip-errors` stop at once ([issue #286](https://git.eeqj.de/sneak/vaultik/issues/286)). After Ctrl-C or SIGTERM, phase 2 treated the cancellation error from each diff --git a/internal/vaultik/helpers.go b/internal/vaultik/helpers.go index ff5fe19..325d8f2 100644 --- a/internal/vaultik/helpers.go +++ b/internal/vaultik/helpers.go @@ -3,6 +3,7 @@ package vaultik import ( "errors" "fmt" + "math" "regexp" "strconv" "strings" @@ -47,6 +48,10 @@ const ( year = 365 * day ) +// maxDuration is the largest value a time.Duration can hold, about 292 +// years. +const maxDuration = time.Duration(math.MaxInt64) + // A snapshot ID split on "_" has at least a hostname and a trailing // timestamp. const minSnapshotIDParts = 2 @@ -145,10 +150,10 @@ func parseSnapshotName(snapshotID, hostname string) string { // parseDuration parses a duration string with support for human-friendly units: // d/day/days, w/week/weeks, mo/month/months, y/year/years, plus standard Go // duration units. Following Go, m is minutes and mo is months. A bare number, -// an unknown unit, and a negative value are all rejected. Outside the Go -// units the input must be whole numbers each followed directly by a unit -// (2w3d), so 1.0y and 30 days are errors; decimals work only in Go units -// (1.5h). +// an unknown unit, a negative value, and a total longer than maxDuration are +// all rejected. Outside the Go units the input must be whole numbers each +// followed directly by a unit (2w3d), so 1.0y and 30 days are errors; +// decimals work only in Go units (1.5h). func parseDuration(s string) (time.Duration, error) { if strings.HasPrefix(strings.TrimSpace(s), "-") { return 0, errNegativeDuration @@ -181,19 +186,30 @@ func parseDuration(s string) (time.Duration, error) { return 0, fmt.Errorf("invalid number %q: %w", match[1], err) } + var unitLength time.Duration + unit := strings.ToLower(match[2]) switch unit { case "d", "day", "days": - total += time.Duration(n) * day + unitLength = day case "w", "week", "weeks": - total += time.Duration(n) * week + unitLength = week case "mo", "month", "months": - total += time.Duration(n) * month + unitLength = month case "y", "year", "years": - total += time.Duration(n) * year + unitLength = year default: return 0, fmt.Errorf("%w %q", errUnknownTimeUnit, unit) } + + // Past maxDuration the sum wraps to a negative value, which would + // put the purge cutoff in the future. + if time.Duration(n) > (maxDuration-total)/unitLength { + return 0, fmt.Errorf("%w: %q is longer than about 292 years", + errInvalidDuration, s) + } + + total += time.Duration(n) * unitLength } return total, nil diff --git a/internal/vaultik/helpers_test.go b/internal/vaultik/helpers_test.go index e279319..f3b2f04 100644 --- a/internal/vaultik/helpers_test.go +++ b/internal/vaultik/helpers_test.go @@ -111,6 +111,17 @@ func TestParseDuration(t *testing.T) { {"30 days", 0, true}, {"30 days ago", 0, true}, {"x7d", 0, true}, + // The largest time.Duration is about 292 years. A larger value + // must be rejected, not wrapped to a negative one, which would + // put the cutoff in the future and select every snapshot. + {"292y", 292 * 365 * 24 * time.Hour, false}, + {"293y", 0, true}, + {"3559mo", 0, true}, + {"15251w", 0, true}, + {"106752d", 0, true}, + {"2562048h", 0, true}, + {"200y200y", 0, true}, + {"292y6mo", 0, true}, } for _, tt := range tests { diff --git a/internal/vaultik/purge_per_name_test.go b/internal/vaultik/purge_per_name_test.go index 800480c..f895f61 100644 --- a/internal/vaultik/purge_per_name_test.go +++ b/internal/vaultik/purge_per_name_test.go @@ -267,6 +267,29 @@ func TestPurgeOlderThan_WithNameFilter(t *testing.T) { assert.Contains(t, remaining, snapHomeT0) } +func TestPurgeOlderThan_TooLargeDeletesNothing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + snapshotIDs := []string{snapHomeT0, snapHomeT1} + + v := setupPurgeTest(t, snapHostname, snapshotIDs) + + err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + OlderThan: "1000y", + Force: true, + }) + require.Error(t, err) + + err = v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + OlderThan: "292y", + Force: true, + }) + require.NoError(t, err) + + assert.ElementsMatch(t, snapshotIDs, listRemainingSnapshots(t, v)) +} + func TestPurgeKeepLatest_ThreeNames(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() From 07c957f84bf38145fefa50d934e7b871e88840cc Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 03:48:36 +0200 Subject: [PATCH 044/121] Bind the local index to the s3.* destination too (closes #298) The local index was bound to its destination only through storage_url. With the s3.* form nothing was checked, so after s3.bucket or s3.prefix changed the next backup treated every chunk as already stored, uploaded nothing, and completed a snapshot that could not be restored. Without storage_url, the binding now records the destination the s3.* fields name, written as an s3:// URL from s3.endpoint, s3.bucket and s3.prefix, and a change is refused with the same error and advice. The advice line now names the s3.* fields as well as storage_url. Judgement call: the fields are compared as written, so an equivalent spelling (a trailing slash on the prefix, a scheme on the endpoint) is also refused, as it already is for storage_url. Model: opus-5-5 --- README.md | 3 +- TODO.md | 9 +++++ internal/vaultik/storage_bind.go | 20 +++++------ internal/vaultik/storage_bind_test.go | 48 +++++++++++++++++++++++++++ 4 files changed, 69 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 5c58a8f..1523495 100644 --- a/README.md +++ b/README.md @@ -412,7 +412,8 @@ destination store. entirely. Remote storage is unaffected; the next backup will do a full scan and re-deduplicate against existing remote blobs, and the local index will re-bind to the currently configured storage destination. -Use this after changing `storage_url` to a different destination. +Use this after changing `storage_url`, or `s3.endpoint`, `s3.bucket` or +`s3.prefix`, to a different destination. * `--force`: Skip confirmation prompt --- diff --git a/TODO.md b/TODO.md index 018c80c..61fdbc6 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,15 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-12: Bound the local index to the destination an `s3.*` config + names ([issue #298](https://git.eeqj.de/sneak/vaultik/issues/298)). + Only `storage_url` was checked, so after `s3.bucket` or `s3.prefix` + changed, the next backup treated every chunk as already stored, + uploaded nothing, and completed a snapshot that could not be restored. + Without `storage_url`, the local index is now bound to `s3.endpoint`, + `s3.bucket` and `s3.prefix`, and a change is refused as a changed + `storage_url` is. + - 2026-10-12: Rejected a retention duration longer than about 292 years ([issue #289](https://git.eeqj.de/sneak/vaultik/issues/289)). The number given to `--older-than` or `--keep-newer-than` was multiplied diff --git a/internal/vaultik/storage_bind.go b/internal/vaultik/storage_bind.go index 2570d48..d9fe081 100644 --- a/internal/vaultik/storage_bind.go +++ b/internal/vaultik/storage_bind.go @@ -9,7 +9,7 @@ import ( ) // errStorageBindingMismatch is returned when the local index database is -// bound to a different destination than the configured storage_url. +// bound to a different destination than the configured one. var errStorageBindingMismatch = errors.New( "local index is bound to a different backup destination") @@ -24,8 +24,9 @@ var errStorageBindingMismatch = errors.New( // // Behaviour: // - On first use (empty stored value), record the configured -// storage_url and log the binding. -// - When the stored value matches the configured storage_url, do +// destination (storage_url, or the s3.* endpoint, bucket and +// prefix) and log the binding. +// - When the stored value matches the configured destination, do // nothing and return nil. // - When the two differ, refuse with an error that tells the user // how to recover (revert the config, or run `vaultik database @@ -46,12 +47,10 @@ func (v *Vaultik) EnsureStorageBinding() error { configured := v.Config.StorageURL if configured == "" { - // Some legacy configs still use the split s3.* keys instead of - // storage_url. Falling back to a synthetic URL for those would - // hide the fact that the binding is loose. Instead, treat - // unset as "nothing to bind against" — the check is - // necessarily best-effort for those configs. - return nil + // The s3.* form: bind on its endpoint, bucket and prefix, + // written the way storage_url would name the same destination. + s3 := v.Config.S3 + configured = "s3://" + s3.Bucket + "/" + s3.Prefix + "?endpoint=" + s3.Endpoint } stored, err := v.Repositories.LocalMeta.Get(v.ctx, database.LocalMetaKeyStorageURL) @@ -96,7 +95,8 @@ func buildBindingMismatchMessage(stored, configured string) string { "future snapshots referencing blobs that don't exist at the new destination.\n" + "\n" + "To proceed, either:\n" + - " - revert storage_url in your config to the bound destination, or\n" + + " - revert storage_url (or the s3.* endpoint, bucket and prefix) in your\n" + + " config to the bound destination, or\n" + " - run 'vaultik database delete' to discard the local index and rebuild it\n" + " from a fresh full backup against the new destination" } diff --git a/internal/vaultik/storage_bind_test.go b/internal/vaultik/storage_bind_test.go index a2f8272..69d97b6 100644 --- a/internal/vaultik/storage_bind_test.go +++ b/internal/vaultik/storage_bind_test.go @@ -76,3 +76,51 @@ func TestEnsureStorageBinding_MismatchRefuses(t *testing.T) { assert.Contains(t, err.Error(), "file:///mnt/backups/new") assert.Contains(t, err.Error(), "vaultik database delete") } + +// A config with no storage_url names its destination with s3.endpoint, +// s3.bucket and s3.prefix; a change to any of them must be refused just +// as a changed storage_url is. +func TestEnsureStorageBinding_S3FieldsChangeRefuses(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + bound := config.S3Config{ + Endpoint: "https://s3.example.com", + Bucket: "bucket-a", + Prefix: "backups", + } + + tests := []struct { + name string + changed config.S3Config + }{ + {"bucket", config.S3Config{ + Endpoint: bound.Endpoint, Bucket: "bucket-b", Prefix: bound.Prefix, + }}, + {"prefix", config.S3Config{ + Endpoint: bound.Endpoint, Bucket: bound.Bucket, Prefix: "other", + }}, + {"endpoint", config.S3Config{ + Endpoint: "https://s3.other.com", Bucket: bound.Bucket, Prefix: bound.Prefix, + }}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + tv, _ := buildBindTestVaultik(t, "") + + tv.Config.S3 = bound + require.NoError(t, tv.EnsureStorageBinding(), "first use binds") + require.NoError(t, tv.EnsureStorageBinding(), "same destination passes") + + tv.Config.S3 = tt.changed + err := tv.EnsureStorageBinding() + require.Error(t, err) + assert.Contains(t, err.Error(), + "local index is bound to a different backup destination") + assert.Contains(t, err.Error(), "vaultik database delete") + }) + } +} From 167c0a07466941cc81503db3a175f51c6b726543 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 05:55:22 +0200 Subject: [PATCH 045/121] Make snapshot remove fail for an unknown snapshot ID (closes #293) snapshot remove never checked that the ID existed: it deleted nothing, reported the snapshot removed from the local database and from the destination store, and exited 0, under --json, --dry-run and --local-only too. It now looks the ID up in the local index and, only when that has no row and --local-only is not set, on the destination store; finding neither is an error. The command reports a removal from the local database only when the local index had the row, and remote_removed is true only when metadata was actually deleted. Judgement call: under --local-only the destination store is not consulted, so the snapshot must be in the local index. Model: opus-5-5 --- README.md | 8 +- TODO.md | 10 ++ internal/cli/snapshot.go | 6 +- internal/vaultik/remove_snapshot_test.go | 115 +++++++++++++++++++++ internal/vaultik/snapshot.go | 123 +++++++++++++++++------ 5 files changed, 226 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 1523495..c1d87ad 100644 --- a/README.md +++ b/README.md @@ -349,9 +349,11 @@ the backup destination store. Blobs are NOT touched — deleting blobs requires reading every remaining remote manifest (the destination store may hold snapshots this host doesn't know about), which is what `vaultik prune` does. On success the command prints the exact `vaultik -prune` invocation to run as a follow-up. Local row cleanup (files, -chunks, blobs the snapshot was the last referrer for) runs -automatically. If the destination store is unreachable, the local-DB +prune` invocation to run as a follow-up. An ID that names no snapshot in +the local index or on the destination store is an error; with +`--local-only`, the snapshot must be in the local index. Local row +cleanup (files, chunks, blobs the snapshot was the last referrer for) +runs automatically. If the destination store is unreachable, the local-DB removal still completes and a warning is emitted; run `vaultik snapshot remove ` again once the store is reachable to remove the snapshot's metadata from it (`vaultik prune` does not). To wipe everything diff --git a/TODO.md b/TODO.md index 61fdbc6..e124826 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,16 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-13: Made `snapshot remove` fail for a snapshot that does not + exist ([issue #293](https://git.eeqj.de/sneak/vaultik/issues/293)). + The command never checked the ID: it reported the snapshot removed + from the local database and from the destination store and exited 0, + under `--json`, `--dry-run` and `--local-only` too. An ID that names + no snapshot in the local index or on the destination store is now an + error; with `--local-only`, the snapshot must be in the local index. + The command now reports a removal from either side only when one + happened, and `remote_removed` is true only when metadata was deleted. + - 2026-10-12: Bound the local index to the destination an `s3.*` config names ([issue #298](https://git.eeqj.de/sneak/vaultik/issues/298)). Only `storage_url` was checked, so after `s3.bucket` or `s3.prefix` diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 58b32db..1dc6811 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -255,8 +255,12 @@ manifest (the destination store may hold snapshots this host doesn't know about), which is what 'vaultik prune' does. On success the command prints the exact 'vaultik prune' invocation to run as a follow-up. +An ID that names no snapshot in the local index or on the destination +store is an error. + Use --local-only to skip the remote half (e.g. when you want to forget a -snapshot locally without touching the destination store). +snapshot locally without touching the destination store); the snapshot +must then be in the local index. If the remote is unreachable, the local-database removal still completes and a warning is emitted; run 'vaultik snapshot remove ' again diff --git a/internal/vaultik/remove_snapshot_test.go b/internal/vaultik/remove_snapshot_test.go index b337c1b..076ccdd 100644 --- a/internal/vaultik/remove_snapshot_test.go +++ b/internal/vaultik/remove_snapshot_test.go @@ -3,17 +3,21 @@ package vaultik_test import ( "bytes" "context" + "database/sql" "io" "strings" "sync" "testing" + "time" "github.com/klauspost/compress/zstd" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/types" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -214,6 +218,37 @@ func addBlob(t *testing.T, store *testStorer, hash string) { require.NoError(t, err) } +// newLocalIndex returns an in-memory local index holding a completed +// snapshot row for each of ids. +func newLocalIndex(t *testing.T, ids ...string) *database.Repositories { + t.Helper() + + ctx := context.Background() + + db, err := database.New(ctx, ":memory:") + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + + for _, id := range ids { + completedAt := time.Now().UTC() + snap := &database.Snapshot{ + ID: types.SnapshotID(id), + Hostname: snapHostname, + StartedAt: completedAt, + CompletedAt: &completedAt, + } + + err = repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + return repos.Snapshots.Create(ctx, tx, snap) + }) + require.NoError(t, err) + } + + return repos +} + // ============================================================================ // Unit Tests for RemoveSnapshot // ============================================================================ @@ -233,6 +268,7 @@ func TestRemoveSnapshot_LocalOnly_PreservesRemote(t *testing.T) { addBlob(t, store, blobA) tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001") opts := &vaultik.RemoveOptions{Force: true, LocalOnly: true} result, err := tv.RemoveSnapshot("snapshot-001", opts) @@ -268,6 +304,7 @@ func TestRemoveSnapshot_DefaultRemovesMetadataNotBlobs(t *testing.T) { addBlob(t, store, blobShared) tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001", "snapshot-002") opts := &vaultik.RemoveOptions{Force: true} result, err := tv.RemoveSnapshot("snapshot-001", opts) @@ -316,6 +353,84 @@ func TestRemoveSnapshot_DryRun(t *testing.T) { assert.Contains(t, tv.Stdout.String(), "[Dry run - no changes made]") } +// TestRemoveSnapshot_UnknownIDIsError checks that an ID naming no +// snapshot in the local index or on the destination store is an error +// under every option, and that nothing is reported as removed. +func TestRemoveSnapshot_UnknownIDIsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + for name, opts := range map[string]vaultik.RemoveOptions{ + "force": {Force: true}, + "json": {JSON: true}, + "dry-run": {Force: true, DryRun: true}, + "local-only": {Force: true, LocalOnly: true}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001") + + result, err := tv.RemoveSnapshot("snapshot-999", &opts) + + require.ErrorContains(t, err, "snapshot not found") + assert.False(t, result.RemoteRemoved) + assert.Empty(t, tv.Stdout.String()) + assert.True(t, store.hasKey(remoteKeyPath("snapshot-001"))) + }) + } +} + +// TestRemoveSnapshot_NoMetadataOnDestination checks that removing a +// snapshot whose metadata is not on the destination store does not +// report metadata removed from it. +func TestRemoveSnapshot_NoMetadataOnDestination(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + tv := vaultik.NewForTesting(newTestStorer()) + tv.Repositories = newLocalIndex(t, "snapshot-001") + + result, err := tv.RemoveSnapshot("snapshot-001", + &vaultik.RemoveOptions{Force: true}) + + require.NoError(t, err) + assert.False(t, result.RemoteRemoved) + + out := tv.Stdout.String() + assert.Contains(t, out, "Removed snapshot 'snapshot-001' from local database") + assert.NotContains(t, out, "Removed snapshot metadata from remote storage") +} + +// TestRemoveSnapshot_NotInLocalIndex checks that removing a snapshot +// only the destination store holds removes its metadata there without +// reporting a removal from the local database. +func TestRemoveSnapshot_NotInLocalIndex(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t) + + result, err := tv.RemoveSnapshot("snapshot-001", + &vaultik.RemoveOptions{Force: true}) + + require.NoError(t, err) + assert.True(t, result.RemoteRemoved) + assert.False(t, store.hasKey(remoteKeyPath("snapshot-001"))) + + out := tv.Stdout.String() + assert.NotContains(t, out, "from local database") + assert.Contains(t, out, "Removed snapshot metadata from remote storage") +} + func TestRemoveAllSnapshots_RequiresForce(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 97ecfdb..2d65a0c 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -23,6 +23,7 @@ var ( errNoSnapshotsInConfig = errors.New("no snapshots configured") errSnapshotVerifyFailed = errors.New("verification failed") errRemoveAllNeedsForce = errors.New("--all requires --force") + errSnapshotNotFound = errors.New("snapshot not found") errInvalidTableName = errors.New("invalid table name") errNoAgeRecipients = errors.New( "creating a snapshot needs at least one public key in " + @@ -643,7 +644,7 @@ func (v *Vaultik) confirmAndExecutePurge( "snapshot_id", snapshotID, "error", err) } - err = v.deleteRemoteSnapshotByKey(snapshot.RemoteSnapshotKey(snapshotID)) + _, err = v.deleteRemoteSnapshotByKey(snapshot.RemoteSnapshotKey(snapshotID)) if err != nil { return fmt.Errorf("deleting snapshot %s from remote: %w", snapshotID, err) } @@ -1153,6 +1154,11 @@ func (v *Vaultik) RemoveSnapshot( return result, err } + inLocalIndex, err := v.findSnapshotToRemove(snapshotID, opts) + if err != nil { + return result, err + } + if opts.DryRun { return v.removeSnapshotDryRun(result, snapshotID, opts) } @@ -1161,11 +1167,13 @@ func (v *Vaultik) RemoveSnapshot( return result, nil } - log.Info("Removing snapshot from local database", "snapshot_id", snapshotID) + if inLocalIndex { + log.Info("Removing snapshot from local database", "snapshot_id", snapshotID) - err = v.deleteSnapshotFromLocalDB(snapshotID) - if err != nil { - return result, fmt.Errorf("removing from local database: %w", err) + err = v.deleteSnapshotFromLocalDB(snapshotID) + if err != nil { + return result, fmt.Errorf("removing from local database: %w", err) + } } if !opts.LocalOnly { @@ -1184,9 +1192,11 @@ func (v *Vaultik) RemoveSnapshot( return result, v.outputRemoveJSON(result) } - v.stdoutf("Removed snapshot '%s' from local database\n", snapshotID) + if inLocalIndex { + v.stdoutf("Removed snapshot '%s' from local database\n", snapshotID) + } - if !opts.LocalOnly && result.RemoteRemoved { + if result.RemoteRemoved { v.printlnStdout("Removed snapshot metadata from remote storage") v.stdoutf("\nNote: The removed snapshot's blobs remain on the remote. "+ "Run '%s' to delete any blobs no longer referenced by any "+ @@ -1196,6 +1206,45 @@ func (v *Vaultik) RemoveSnapshot( return result, nil } +// findSnapshotToRemove reports whether the local index has a row for +// snapshotID, and returns errSnapshotNotFound when there is nothing to +// remove: no row and, unless LocalOnly is set, no metadata on the +// destination store either. The destination store is consulted only +// when the local index has no row, so a snapshot in the local index can +// still be removed from it while the destination store is unreachable. +func (v *Vaultik) findSnapshotToRemove( + snapshotID string, opts *RemoveOptions, +) (bool, error) { + if v.Repositories != nil { + snap, err := v.Repositories.Snapshots.GetByID(v.ctx, snapshotID) + if err != nil { + return false, fmt.Errorf("looking up snapshot in local index: %w", err) + } + + if snap != nil { + return true, nil + } + } + + if opts.LocalOnly { + return false, fmt.Errorf("%w in the local index: %s", + errSnapshotNotFound, snapshotID) + } + + objects, err := v.remoteSnapshotObjects(snapshot.RemoteSnapshotKey(snapshotID)) + if err != nil { + return false, fmt.Errorf("looking up snapshot on destination store: %w", err) + } + + if len(objects) == 0 { + return false, fmt.Errorf( + "%w in the local index or on the destination store: %s", + errSnapshotNotFound, snapshotID) + } + + return false, nil +} + // removeSnapshotDryRun reports what RemoveSnapshot would do without // making changes. func (v *Vaultik) removeSnapshotDryRun( @@ -1255,14 +1304,14 @@ func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) // didn't finish and to run `vaultik snapshot remove` for the snapshot // again once the destination store is reachable (`vaultik prune` never // removes snapshot metadata). Returns true when the remote removal -// succeeded. +// succeeded and deleted something. func (v *Vaultik) removeSnapshotRemote(snapshotID string, opts *RemoveOptions) bool { log.Info("Removing snapshot metadata from remote storage", "snapshot_id", snapshotID) remoteKey := snapshot.RemoteSnapshotKey(snapshotID) - err := v.deleteRemoteSnapshotByKey(remoteKey) + deleted, err := v.deleteRemoteSnapshotByKey(remoteKey) if err != nil { log.Warn("Could not remove snapshot metadata from remote storage; "+ "run '"+snapshotRemoveCommandHint+"' with the snapshot's ID "+ @@ -1280,7 +1329,7 @@ func (v *Vaultik) removeSnapshotRemote(snapshotID string, opts *RemoveOptions) b return false } - return true + return deleted > 0 } // RemoveAllSnapshots removes every snapshot known to the local @@ -1572,7 +1621,7 @@ func (v *Vaultik) removeAllLocalSnapshots( } if !opts.LocalOnly { - err = v.deleteRemoteSnapshotByKey( + _, err = v.deleteRemoteSnapshotByKey( snapshot.RemoteSnapshotKey(snapshotID)) if err != nil { log.Warn("Failed to remove snapshot metadata from remote", @@ -1598,7 +1647,7 @@ func (v *Vaultik) removeAllOrphanRemotes( for _, key := range orphanRemoteKeys { log.Info("Removing orphan remote snapshot", "remote_key", key) - err := v.deleteRemoteSnapshotByKey(key) + _, err := v.deleteRemoteSnapshotByKey(key) if err != nil { log.Warn("Failed to remove orphan from remote", "remote_key", key, "error", err) @@ -1645,34 +1694,44 @@ func (v *Vaultik) deleteSnapshotFromLocalDB(snapshotID string) error { } // deleteRemoteSnapshotByKey removes everything under -// metadata// on the destination store. The argument is a -// remote key (double-SHA256 derivation), not a human snapshot ID; -// callers that have a human ID must hash via snapshot.RemoteSnapshotKey -// first. -func (v *Vaultik) deleteRemoteSnapshotByKey(remoteKey string) error { - prefix := fmt.Sprintf("metadata/%s/", remoteKey) - objectCh := v.Storage.ListStream(v.ctx, prefix) - - var objectsToDelete []string - - for object := range objectCh { - if object.Err != nil { - return fmt.Errorf("listing objects: %w", object.Err) - } - - objectsToDelete = append(objectsToDelete, object.Key) +// metadata// on the destination store and returns how many +// objects it deleted. The argument is a remote key (double-SHA256 +// derivation), not a human snapshot ID; callers that have a human ID +// must hash via snapshot.RemoteSnapshotKey first. +func (v *Vaultik) deleteRemoteSnapshotByKey(remoteKey string) (int, error) { + objectsToDelete, err := v.remoteSnapshotObjects(remoteKey) + if err != nil { + return 0, err } - for _, key := range objectsToDelete { - err := v.Storage.Delete(v.ctx, key) + for i, key := range objectsToDelete { + err = v.Storage.Delete(v.ctx, key) if err != nil { - return fmt.Errorf("removing %s: %w", key, err) + return i, fmt.Errorf("removing %s: %w", key, err) } log.Debug("Deleted remote object", "key", key) } - return nil + return len(objectsToDelete), nil +} + +// remoteSnapshotObjects lists the keys of every object under +// metadata// on the destination store. +func (v *Vaultik) remoteSnapshotObjects(remoteKey string) ([]string, error) { + prefix := fmt.Sprintf("metadata/%s/", remoteKey) + + var keys []string + + for object := range v.Storage.ListStream(v.ctx, prefix) { + if object.Err != nil { + return nil, fmt.Errorf("listing objects: %w", object.Err) + } + + keys = append(keys, object.Key) + } + + return keys, nil } // outputRemoveJSON outputs the removal result as JSON From 94412d9ef34572f77728825dbe2a2990ab8e4533 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 08:33:27 +0200 Subject: [PATCH 046/121] Stop remote info counting a non-blob file under blobs/ (closes #295) remote info counted every key under blobs/ with four or more path parts as a blob, while prune skips a name that is not a blob hash. A stray file such as .DS_Store was reported as an orphaned blob, with advice to run prune, which then deleted nothing. remote info now takes its blob list from prune's listAllRemoteBlobs, so its blob and orphan figures, in the table and in --json, cover exactly what prune would consider. blobKeyParts moves to prune.go, its only remaining user. Model: opus-5-5 --- README.md | 4 +++- TODO.md | 8 +++++++ internal/vaultik/info.go | 27 +++++++---------------- internal/vaultik/prune.go | 4 ++++ internal/vaultik/remote_info_test.go | 33 ++++++++++++++++++++++++++++ 5 files changed, 56 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index c1d87ad..1451d0a 100644 --- a/README.md +++ b/README.md @@ -401,7 +401,9 @@ orphaned blob figures are reported as unknown; `--json` gives them as `null`, lists the remote key of each unreadable manifest in `unreadable_manifests` and counts the manifests under skipped names in `skipped_manifest_count`. An unreadable manifest also leaves its -snapshot's blob count and blob size unknown, `null` in `--json`. +snapshot's blob count and blob size unknown, `null` in `--json`. A file +under `blobs/` whose name is not a blob hash is not counted as a blob, +since `prune` never deletes it. * `--json`: Output as JSON **`remote nuke`**: Delete every snapshot's metadata and every blob from the diff --git a/TODO.md b/TODO.md index e124826..9160574 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,14 @@ the tag exists and is exercised; what is left is merging `next` to # Completed Steps +- 2026-10-13: Stopped `remote info` counting a file under `blobs/` that + is not a blob as an orphaned blob + ([issue #295](https://git.eeqj.de/sneak/vaultik/issues/295)). A stray + file such as `.DS_Store` was reported as an orphaned blob and the + report advised running `prune`, which skips such a file and deleted + nothing. `remote info` now takes its blob list from the same listing + `prune` uses, in the table and in `--json`. + - 2026-10-13: Made `snapshot remove` fail for a snapshot that does not exist ([issue #293](https://git.eeqj.de/sneak/vaultik/issues/293)). The command never checked the ID: it reported the snapshot removed diff --git a/internal/vaultik/info.go b/internal/vaultik/info.go index e587e27..64656d8 100644 --- a/internal/vaultik/info.go +++ b/internal/vaultik/info.go @@ -167,10 +167,6 @@ const ( // metadataKeyParts is the minimum "/"-separated segment count of a // metadata object key (metadata//). metadataKeyParts = 3 - - // blobKeyParts is the minimum "/"-separated segment count of a blob - // object key (blobs///). - blobKeyParts = 4 ) // SnapshotMetadataInfo contains information about a single snapshot's metadata @@ -454,23 +450,16 @@ func (v *Vaultik) scanRemoteBlobStorage( v.stdoutf("Scanning blobs...\n") } - blobCh := v.Storage.ListStream(v.ctx, "blobs/") - allBlobs := make(map[string]int64) + // Use prune's listing, so a file under blobs/ that prune would never + // delete is not counted as a blob, and so not as an orphaned one. + allBlobs, err := v.listAllRemoteBlobs() + if err != nil { + return err + } - for obj := range blobCh { - if obj.Err != nil { - return fmt.Errorf("listing blobs: %w", obj.Err) - } - - parts := strings.Split(obj.Key, "/") - if len(parts) < blobKeyParts { - continue - } - - hash := parts[3] - allBlobs[hash] = obj.Size + for _, size := range allBlobs { result.TotalBlobCount++ - result.TotalBlobSize += obj.Size + result.TotalBlobSize += size } // A blob named only by a manifest that could not be read, or by one diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index 6bd737a..31949c9 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -23,6 +23,10 @@ var errNukeRequiresForce = errors.New( // metadata. const metadataDirName = "metadata" +// blobKeyParts is the "/"-separated segment count of a blob object key +// (blobs///). +const blobKeyParts = 4 + // NukeRemote deletes every snapshot's metadata and every blob from remote // storage, along with any object an upload cut off part-way left under a // temporary `.partial` name. After this returns successfully the bucket diff --git a/internal/vaultik/remote_info_test.go b/internal/vaultik/remote_info_test.go index ceb5f11..76bac72 100644 --- a/internal/vaultik/remote_info_test.go +++ b/internal/vaultik/remote_info_test.go @@ -185,6 +185,39 @@ func TestRemoteInfo_SkipsNonConformingMetadataName(t *testing.T) { assert.NotContains(t, doc, "unreadable_manifests") } +// TestRemoteInfo_DoesNotCountNonBlobFileUnderBlobs checks that a file +// under blobs/ whose name is not a blob hash is not counted as a blob. +// prune never deletes such a file, so counting it as an orphaned blob +// would advise a prune that removes nothing. +func TestRemoteInfo_DoesNotCountNonBlobFileUnderBlobs(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + env.addRemote(t, listRemoteID, time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + addBlob(t, env.store.testStorer, testBlobHashA) + require.NoError(t, env.store.Put(context.Background(), + "blobs/"+testBlobHashA[:2]+"/"+testBlobHashA[2:4]+"/.DS_Store", + bytes.NewReader([]byte("junk")))) + + require.NoError(t, env.v.RemoteInfo(false)) + + text := env.stdout.String() + assert.Contains(t, text, "Total blobs on remote: 1 (") + assert.Contains(t, text, "Orphaned (unreferenced): 0 (") + assert.NotContains(t, text, "vaultik prune") + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(true)) + + var doc map[string]any + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &doc)) + assert.InDelta(t, 1, doc["total_blob_count"], 0) + assert.InDelta(t, 0, doc["orphaned_blob_count"], 0) + assert.InDelta(t, 0, doc["orphaned_blob_size"], 0) +} + // TestRemoteInfo_DirectoryWithoutManifestLeavesOrphansKnown checks that // a directory under metadata/ holding no manifest.json.zst, such as one // left by a backup interrupted before its manifest upload, leaves the From 35eed79b1a3a1afde462cf61f6d2668fd191d35b Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 09:44:44 +0200 Subject: [PATCH 047/121] Check --keep-newer-than before the backup starts (closes #307) snapshot create read --keep-newer-than only in the post-backup prune, so a value the duration parser rejects failed the run after the snapshot was uploaded: a nightly cron line added a snapshot each night, reported it as failed, and never deleted any. Without --prune the flag was ignored. The command now checks the flag before it starts and fails on an invalid duration or a missing --prune. A failed post-backup prune is now wrapped in ErrPostBackupPruneFailed and reported as "Backup completed, but post-backup prune failed: ..." rather than as a failed snapshot creation. The exit status stays 1. Model: opus-5-5 --- README.md | 4 +- .../cli/entry_snapshot_create_prune_test.go | 108 ++++++++++++++++++ internal/cli/snapshot.go | 12 ++ internal/vaultik/snapshot.go | 28 ++++- 4 files changed, 150 insertions(+), 2 deletions(-) create mode 100644 internal/cli/entry_snapshot_create_prune_test.go diff --git a/README.md b/README.md index 1451d0a..306b27d 100644 --- a/README.md +++ b/README.md @@ -286,7 +286,9 @@ needed. remove orphaned blobs from remote storage. By default keeps only the latest snapshot per name; use `--keep-newer-than` for a rolling window. * `--keep-newer-than `: With `--prune`, keep snapshots newer than - this duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`) + this duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`). + Without `--prune`, or with a value that is not a valid duration, the + command fails before the backup starts. **`snapshot list`**: Show every snapshot known to this host — the union of the local index and the backup destination store — with timestamps diff --git a/internal/cli/entry_snapshot_create_prune_test.go b/internal/cli/entry_snapshot_create_prune_test.go new file mode 100644 index 0000000..2a7b229 --- /dev/null +++ b/internal/cli/entry_snapshot_create_prune_test.go @@ -0,0 +1,108 @@ +package cli //nolint:testpackage // shares runEntry and the hermetic config helpers + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Flags of `snapshot create` used to build argument vectors below. +const ( + flagPrune = "--prune" + flagKeepNewerThan = "--keep-newer-than" +) + +// TestEntrySnapshotCreateRejectsKeepNewerThanBeforeBackup checks that a +// --keep-newer-than the post-backup prune could not use stops `snapshot +// create` before the backup: the command fails and the destination +// store stays empty. It used to be read only by the prune, after the +// snapshot was uploaded, and without --prune it was ignored. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreateRejectsKeepNewerThanBeforeBackup(t *testing.T) { + for _, testCase := range []struct { + name string + args []string + }{ + { + name: "decimal in a day count", + args: []string{flagPrune, flagKeepNewerThan, "1.5d"}, + }, + { + name: "unknown unit", + args: []string{flagPrune, flagKeepNewerThan, "4x"}, + }, + { + name: "without --prune", + args: []string{flagKeepNewerThan, "4w"}, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + configPath, storeDir := writeBackupConfig(t) + + code, _, _ := runEntry(t, append( + []string{flagConfig, configPath, cmdSnapshot, cmdCreate}, + testCase.args...)...) + + assert.Equal(t, 1, code) + + stored, err := os.ReadDir(storeDir) + require.NoError(t, err) + assert.Empty(t, stored, "nothing may be uploaded") + }) + } +} + +// TestEntrySnapshotCreateReportsPostBackupPruneFailure makes the +// post-backup prune fail after a good backup, by planting a manifest +// that cannot be decoded, and checks that the failure is reported as the +// prune's and not as a failed snapshot creation. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreateReportsPostBackupPruneFailure(t *testing.T) { + configPath, storeDir := writeBackupConfig(t) + + // A remote key is 64 lowercase hex characters. The prune reads every + // manifest on the store and fails on one it cannot decode. + plantedDir := filepath.Join(storeDir, "metadata", strings.Repeat("a", 64)) + require.NoError(t, os.MkdirAll(plantedDir, 0o750)) + require.NoError(t, os.WriteFile( + filepath.Join(plantedDir, "manifest.json.zst"), + []byte("not a valid manifest"), 0o600)) + + code, _, stderr := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate, flagPrune) + + assert.Equal(t, 1, code) + assert.Contains(t, stderr, "Backup completed, but post-backup prune failed") + assert.NotContains(t, stderr, "Snapshot creation failed") + + snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata")) + require.NoError(t, err) + assert.Len(t, snapshots, 2, + "the new snapshot is on the store beside the planted one") +} + +// writeBackupConfig builds a hermetic config with one small file in its +// source directory and an empty destination store directory. Returns the +// config path and the store directory. +func writeBackupConfig(t *testing.T) (string, string) { + t.Helper() + + configPath := writeHermeticPruneConfig(t, false) + + // writeHermeticPruneConfig puts the source and store directories + // beside the config file. + dir := filepath.Dir(configPath) + sourceDir := filepath.Join(dir, "source") + + require.NoError(t, os.Mkdir(sourceDir, 0o750)) + require.NoError(t, os.WriteFile( + filepath.Join(sourceDir, "file.txt"), []byte("hello"), 0o600)) + + return configPath, filepath.Join(dir, "store") +} diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 1dc6811..f157102 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -71,6 +71,11 @@ otherwise from the platform config directory (~/.config/vaultik/config.yml on Linux), then /etc/vaultik/config.yml.`, Args: cobra.ArbitraryArgs, RunE: func(cmd *cobra.Command, args []string) error { + err := opts.Validate() + if err != nil { + return err + } + // Pass snapshot names from args opts.Snapshots = args // --skip-errors is a global flag on the root command. @@ -97,6 +102,13 @@ on Linux), then /etc/vaultik/config.yml.`, }, func(v *vaultik.Vaultik) error { return v.CreateSnapshot(opts) }, func(err error) { + if errors.Is(err, vaultik.ErrPostBackupPruneFailed) { + log.Error("Post-backup prune failed", "error", err) + ReportErrorf("Backup completed, but %v", err) + + return + } + log.Error("Snapshot creation failed", "error", err) ReportErrorf("Snapshot creation failed: %v", err) }) diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 2d65a0c..9b767df 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -28,8 +28,14 @@ var ( errNoAgeRecipients = errors.New( "creating a snapshot needs at least one public key in " + "age_recipients (generate a keypair with: age-keygen)") + errKeepNewerThanNeedsPrune = errors.New("--keep-newer-than requires --prune") ) +// ErrPostBackupPruneFailed wraps a failure of the post-backup prune, +// which runs only after every snapshot was created and uploaded, so the +// caller can report it apart from a failed backup. +var ErrPostBackupPruneFailed = errors.New("post-backup prune failed") + // listRecentLimit caps how many snapshot rows are fetched from the // local index for listing and purge operations. const listRecentLimit = 10000 @@ -45,6 +51,26 @@ type SnapshotCreateOptions struct { Snapshots []string // Optional list of snapshot names to process (empty = all) } +// Validate fails when KeepNewerThan is set without Prune or is not a +// valid duration. Only the post-backup prune reads KeepNewerThan, after +// the backup, so the caller checks it before starting one. +func (opts *SnapshotCreateOptions) Validate() error { + if opts.KeepNewerThan == "" { + return nil + } + + if !opts.Prune { + return errKeepNewerThanNeedsPrune + } + + _, err := parseDuration(opts.KeepNewerThan) + if err != nil { + return fmt.Errorf("--keep-newer-than: %w", err) + } + + return nil +} + // CreateSnapshot executes the snapshot creation operation func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { // config.Load accepts an empty list, since listing, verifying and @@ -123,7 +149,7 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { if opts.Prune { err = v.runPostBackupPrune(snapshotNames, opts.KeepNewerThan) if err != nil { - return fmt.Errorf("post-backup prune: %w", err) + return fmt.Errorf("%w: %w", ErrPostBackupPruneFailed, err) } } From 0288735aaf451c2973d276d5ec192cf2bcee5761 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 11:14:55 +0200 Subject: [PATCH 048/121] Remove the blob temp file when a backup stops part-way (closes #302) When `snapshot create` stopped on a file error, a full temporary directory or Ctrl-C, the blob being packed was never finalized, and its `vaultik-blob-*.tmp` file (up to `blob_size_limit` of encrypted data) stayed in `$TMPDIR`. Phase 2 now calls the new `Packer.DiscardCurrentBlob` on the way out, which closes and removes that file. After a successful flush no blob is in progress, so the call then does nothing. The blob's row in the local index is left, as before, for the next run's repair of interrupted blobs to remove. Model: opus-5-5 --- internal/blob/packer.go | 11 ++++++ internal/snapshot/scanner.go | 5 +++ internal/snapshot/skip_errors_test.go | 57 +++++++++++++++++++++++++++ 3 files changed, 73 insertions(+) diff --git a/internal/blob/packer.go b/internal/blob/packer.go index 1c588cc..cee01de 100644 --- a/internal/blob/packer.go +++ b/internal/blob/packer.go @@ -245,6 +245,17 @@ func (p *Packer) Flush(ctx context.Context) error { return nil } +// DiscardCurrentBlob closes and removes the temp file of the blob being +// packed, if any, and drops that blob. A caller that stops before Flush +// must call it, or the temp file is left behind. Thread-safe. +func (p *Packer) DiscardCurrentBlob() { + p.mu.Lock() + defer p.mu.Unlock() + + p.cleanupTempFile() + p.currentBlob = nil +} + // FinalizeBlob finalizes the current blob being assembled. // This compresses the accumulated chunks, encrypts the result, and computes // the content-addressed hash. The finalized blob is either passed to the diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index c810278..dc98d4f 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -1295,6 +1295,11 @@ func (s *Scanner) batchAddFilesToSnapshot( func (s *Scanner) processPhase( ctx context.Context, filesToProcess []*FileToProcess, result *ScanResult, ) error { + // On an error or cancellation the blob being packed is never + // finalized, so its temp file must be removed here. After a + // successful flush there is no such blob and this does nothing. + defer s.packer.DiscardCurrentBlob() + // Calculate total bytes to process var totalBytes int64 for _, f := range filesToProcess { diff --git a/internal/snapshot/skip_errors_test.go b/internal/snapshot/skip_errors_test.go index 04ad8de..2a88637 100644 --- a/internal/snapshot/skip_errors_test.go +++ b/internal/snapshot/skip_errors_test.go @@ -381,3 +381,60 @@ func TestScannerCancelStopsSkipErrorsRun(t *testing.T) { }) } } + +// TestScannerRemovesBlobTempFileWhenRunStops checks that a run stopped +// part-way, by a file it cannot read or by a cancellation, removes the +// temp file of the blob it was packing. +func TestScannerRemovesBlobTempFileWhenRunStops(t *testing.T) { + t.Parallel() + + // a.txt is backed up first and starts a blob; the run stops at b.txt. + const target = "/source/b.txt" + + tests := []struct { + name string + newFs func(cancel context.CancelFunc) afero.Fs + }{ + { + name: "file cannot be read", + newFs: func(context.CancelFunc) afero.Fs { + return &readFailFs{Fs: afero.NewMemMapFs(), target: target} + }, + }, + { + name: "cancelled", + newFs: func(cancel context.CancelFunc) afero.Fs { + return &cancelOnOpenFs{ + Fs: afero.NewMemMapFs(), target: target, cancel: cancel, + } + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fs := tt.newFs(cancel) + writeSkipErrorTestFile(t, fs, "/source/a.txt", "first file content") + writeSkipErrorTestFile(t, fs, target, "second file content") + + _, err := runSkipErrorScan(ctx, t, fs, "/source", false, nil) + if err == nil { + t.Fatal("expected the scan to stop with an error, got nil") + } + + left, err := afero.Glob(fs, filepath.Join(os.TempDir(), "vaultik-blob-*")) + if err != nil { + t.Fatalf("listing blob temp files: %v", err) + } + + if len(left) != 0 { + t.Fatalf("expected no blob temp file left, got %v", left) + } + }) + } +} From 5f6455ba17e21be7b56062711f70fe9ce4bae327 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 11:27:59 +0200 Subject: [PATCH 049/121] Refuse a relative file:// storage_url and decode its escapes (closes #299) The path after file:// was used as written. file://dest resolved against the working directory, so a backup run from another directory wrote elsewhere, exited 0 and left a snapshot that could not be restored; my%20stick created a directory with that literal name. Config load now refuses a file:// storage_url whose path is not absolute. ParseStorageURL refuses it too and decodes percent-escapes; a literal space still works. The rule is written in both packages because config cannot import storage, which imports config. A % not followed by two hex digits now fails when the storage is opened, not at config load. Model: opus-5-5 --- README.md | 5 +++- internal/config/config.go | 14 +++++++++-- internal/config/config_test.go | 29 +++++++++++++++++++++++ internal/storage/url.go | 38 ++++++++++++++++++++---------- internal/storage/url_parse_test.go | 18 ++++++++++++-- 5 files changed, 87 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 306b27d..355322d 100644 --- a/README.md +++ b/README.md @@ -433,7 +433,10 @@ object store. Credentials are read from `s3.access_key_id` and `s3.secret_access_key` in the config file. **Local filesystem** (`file:///path/to/backup`): Stores blobs and metadata on -a local or mounted filesystem. Useful for testing or backing up to a NAS. +a local or mounted filesystem. Useful for testing or backing up to a NAS. The +path must be absolute; a relative one is refused when the config loads. +Percent-escapes in the path are decoded, so `my%20stick` and `my stick` name +the same directory. **Rclone** (`rclone://remote/path`): Uses rclone's 70+ supported cloud providers. Requires rclone to be configured separately (`rclone config`). diff --git a/internal/config/config.go b/internal/config/config.go index e8527d7..eb51263 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -61,6 +61,9 @@ var ( errBadS3PartSize = errors.New("s3.part_size must be between 5MiB and 5GiB") errBadStorageScheme = errors.New( "storage_url must start with s3://, file://, or rclone://") + errFileURLNotAbsolute = errors.New( + "a file:// storage_url needs an absolute path, " + + "as in file:///path/to/backup") errStorageNotConfigured = errors.New( "storage not configured; set storage_url or provide s3.endpoint + " + "s3.bucket + credentials") @@ -461,11 +464,18 @@ func (c *Config) validateStorage() error { // validateStorageURL validates URL-based storage configuration. File and // rclone URLs need no credentials; S3 URLs require the legacy s3.* -// credential fields. +// credential fields. A file URL must name an absolute path: a relative one +// would resolve against the working directory, so the destination would +// move with it. func (c *Config) validateStorageURL() error { switch { case strings.HasPrefix(c.StorageURL, "file://"): - // File storage doesn't need S3 credentials + // storage.ParseStorageURL applies the same rule, but config + // cannot import storage, which imports config. + if !strings.HasPrefix(c.StorageURL, "file:///") { + return errFileURLNotAbsolute + } + return nil case strings.HasPrefix(c.StorageURL, "rclone://"): // Rclone storage uses rclone's own config diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 18d0b20..bd7abe3 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -337,6 +337,35 @@ func TestLoadS3PartSize(t *testing.T) { }) } +// TestLoadRejectsRelativeFileURL checks that a file:// storage_url with a +// relative path fails at load. Accepted, it would resolve against the +// working directory, so a backup run from another directory would write +// to a different destination and still succeed. +func TestLoadRejectsRelativeFileURL(t *testing.T) { + t.Parallel() + + const relativeConfig = "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file://dest\n" + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(relativeConfig), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) + } + + _, err = Load(path) + if !errors.Is(err, errFileURLNotAbsolute) { + t.Fatalf("Load() error = %v, want errFileURLNotAbsolute", err) + } + + if !strings.Contains(err.Error(), "absolute path") { + t.Errorf("error %q does not say to use an absolute path", err.Error()) + } +} + // TestValidateAgeRecipients checks that recipients are parsed at config load // (a bad entry fails immediately, not mid-backup) and that no invalid entry — // least of all a pasted secret key — is echoed in the error. An empty list diff --git a/internal/storage/url.go b/internal/storage/url.go index 8da6eca..3e41198 100644 --- a/internal/storage/url.go +++ b/internal/storage/url.go @@ -17,8 +17,10 @@ const ( // Sentinel errors for storage URL parsing. var ( - ErrEmptyStorageURL = errors.New("storage URL is empty") - ErrEmptyFilePath = errors.New("file URL path is empty") + ErrEmptyStorageURL = errors.New("storage URL is empty") + ErrEmptyFilePath = errors.New("file URL path is empty") + ErrRelativeFilePath = errors.New( + "file URL needs an absolute path, as in file:///path/to/backup") ErrMissingBucket = errors.New("s3 URL missing bucket name") ErrMissingRemote = errors.New("rclone URL missing remote name") ErrUnsupportedScheme = errors.New( @@ -51,17 +53,8 @@ func ParseStorageURL(rawURL string) (*URL, error) { return nil, ErrEmptyStorageURL } - // Handle file:// URLs if after, ok := strings.CutPrefix(rawURL, "file://"); ok { - path := after - if path == "" { - return nil, ErrEmptyFilePath - } - - return &URL{ - Scheme: schemeFile, - Prefix: path, - }, nil + return parseFileURL(after) } if strings.HasPrefix(rawURL, "s3://") { @@ -75,6 +68,27 @@ func ParseStorageURL(rawURL string) (*URL, error) { return nil, ErrUnsupportedScheme } +// parseFileURL parses the path that follows file://. The path must be +// absolute: a relative one would resolve against the working directory, +// so the destination would move with it. Percent-escapes are decoded, so +// my%20stick names the directory "my stick"; a literal space is kept. +func parseFileURL(rawPath string) (*URL, error) { + if rawPath == "" { + return nil, ErrEmptyFilePath + } + + if !strings.HasPrefix(rawPath, "/") { + return nil, ErrRelativeFilePath + } + + path, err := url.PathUnescape(rawPath) + if err != nil { + return nil, fmt.Errorf("invalid file URL path: %w", err) + } + + return &URL{Scheme: schemeFile, Prefix: path}, nil +} + // parseS3URL parses an s3://bucket/prefix URL. It rejects credentials in // the userinfo and any query parameter other than endpoint, region and // ssl, so a credential-bearing URL is never stored or echoed. diff --git a/internal/storage/url_parse_test.go b/internal/storage/url_parse_test.go index ad0cce7..2151249 100644 --- a/internal/storage/url_parse_test.go +++ b/internal/storage/url_parse_test.go @@ -14,7 +14,10 @@ import ( func TestParseStorageURLValid(t *testing.T) { t.Parallel() - const bucket = "mybucket" + const ( + bucket = "mybucket" + fileScheme = "file" + ) cases := []struct { name string @@ -24,7 +27,17 @@ func TestParseStorageURLValid(t *testing.T) { { name: "file absolute path", raw: "file:///var/backups/vaultik", - want: &storage.URL{Scheme: "file", Prefix: "/var/backups/vaultik"}, + want: &storage.URL{Scheme: fileScheme, Prefix: "/var/backups/vaultik"}, + }, + { + name: "file percent-escaped path is decoded", + raw: "file:///Volumes/my%20stick/backup", + want: &storage.URL{Scheme: fileScheme, Prefix: "/Volumes/my stick/backup"}, + }, + { + name: "file path with a literal space", + raw: "file:///Volumes/my stick/backup", + want: &storage.URL{Scheme: fileScheme, Prefix: "/Volumes/my stick/backup"}, }, { name: "s3 bucket and prefix, ssl defaults on", @@ -90,6 +103,7 @@ func TestParseStorageURLErrors(t *testing.T) { }{ {"empty url", "", storage.ErrEmptyStorageURL}, {"file empty path", "file://", storage.ErrEmptyFilePath}, + {"file relative path", "file://dest", storage.ErrRelativeFilePath}, {"s3 missing bucket", "s3://", storage.ErrMissingBucket}, {"s3 missing bucket with path", "s3:///justprefix", storage.ErrMissingBucket}, {"rclone missing remote", "rclone://", storage.ErrMissingRemote}, From d1213ecb34ca8e8352f7bc19f50afe6b5ec465e6 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 13:50:11 +0200 Subject: [PATCH 050/121] Make a leading **/ in an exclude pattern match at the top level (closes #303) An unanchored exclude pattern such as **/node_modules or **/*.pyc needed a / before the name, so it excluded sub/node_modules and sub/y.pyc but backed up node_modules/ and x.pyc directly under the snapshot path. An unanchored pattern already matches at every depth, so the leading **/ is now dropped when the pattern is compiled and, as in gitignore, the pattern matches the top level too. Judgement call: an anchored /**/x is left as it was; the issue covers patterns that start with **/. Model: opus-5-5 --- internal/snapshot/exclude_test.go | 47 +++++++++++++++++++++++++++++++ internal/snapshot/scanner.go | 8 ++++++ 2 files changed, 55 insertions(+) diff --git a/internal/snapshot/exclude_test.go b/internal/snapshot/exclude_test.go index 9870018..48deb70 100644 --- a/internal/snapshot/exclude_test.go +++ b/internal/snapshot/exclude_test.go @@ -531,3 +531,50 @@ func TestExcludePatterns_UnanchoredPatternFile(t *testing.T) { require.Equal(t, 1, result.FilesScanned, "Unanchored pattern for file should match anywhere") } + +func TestExcludePatterns_DoubleStarDirectoryAtEveryDepth(t *testing.T) { + t.Parallel() + + // As in gitignore, a leading **/ also matches directly under the source dir + fs := setupAnchoredTestFS(t) + + scanner, repos, cleanup := createTestScanner(t, fs, []string{"**/projectname"}) + defer cleanup() + + ctx := context.Background() + createSnapshotRecord(ctx, t, repos, "test-snapshot") + + result, err := scanner.Scan(ctx, "/backup", "test-snapshot") + require.NoError(t, err) + + // **/projectname should exclude BOTH: + // - /backup/projectname/file.txt + // - /backup/otherproject/projectname/file.txt + // Total files: 4, excluded: 2 + require.Equal(t, 2, result.FilesScanned, + "**/ directory pattern should match at the top level and nested") +} + +func TestExcludePatterns_DoubleStarFileAtEveryDepth(t *testing.T) { + t.Parallel() + + // As in gitignore, a leading **/ also matches directly under the source dir + fs := setupAnchoredTestFS(t) + + scanner, repos, cleanup := createTestScanner(t, fs, []string{"**/*.txt"}) + defer cleanup() + + ctx := context.Background() + createSnapshotRecord(ctx, t, repos, "test-snapshot") + + result, err := scanner.Scan(ctx, "/backup", "test-snapshot") + require.NoError(t, err) + + // **/*.txt should exclude ALL .txt files: + // - /backup/file.txt + // - /backup/projectname/file.txt + // - /backup/otherproject/projectname/file.txt + // Total files: 4, excluded: 3 + require.Equal(t, 1, result.FilesScanned, + "**/ file pattern should match at the top level and nested") +} diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index dc98d4f..e54ee1a 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -2018,6 +2018,14 @@ func compileExcludePatterns(patterns []string) []compiledPattern { // Remove trailing slash if present (directory indicator) pattern = strings.TrimSuffix(pattern, "/") + // A leading "**/" demands a "/" before the name and so misses an + // entry directly under the source path. An unanchored pattern + // already matches at every depth, so drop the prefix: as in + // gitignore, "**/x" then also matches a top-level "x". + if !anchored { + pattern = strings.TrimPrefix(pattern, "**/") + } + // Compile the glob pattern // For patterns without path separators, we need to match them as components // e.g., ".git" should match ".git" anywhere in the path From 8c54e0ff7561dc3f28a7bb1afe3f6d484becc962 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 14:14:39 +0200 Subject: [PATCH 051/121] Make a mistyped subcommand under a group command an error (closes #319) snapshot, config, remote, database and completion had no Run, and cobra checks a command's arguments only when it has one, so `vaultik snapshot craete` printed the group's help and exited 0. Each group now prints its help only when given no argument; any other word fails as an unknown command with exit 1, as at the top level. cobra adds the completion command only when Execute runs, so the root command now adds it itself to give it a Run. Its scripts then go to os.Stdout as it was at that moment; a later SetOut does not redirect them. Judgement call: the error has no "Did you mean" suggestion, which the top level gives. Model: opus-5-5 --- internal/cli/config.go | 6 +++ internal/cli/database.go | 6 +++ internal/cli/entry_unknown_subcommand_test.go | 43 +++++++++++++++++++ internal/cli/remote.go | 6 +++ internal/cli/root.go | 15 +++++++ internal/cli/snapshot.go | 6 +++ 6 files changed, 82 insertions(+) create mode 100644 internal/cli/entry_unknown_subcommand_test.go diff --git a/internal/cli/config.go b/internal/cli/config.go index 545f81a..ea477bd 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -251,6 +251,12 @@ func NewConfigCommand() *cobra.Command { Use: "config", Short: "Manage the configuration file", Long: "Commands for creating, editing, and querying the vaultik config file.", + // cobra checks Args only on a command that has a Run: without + // one, a mistyped subcommand printed help and exited 0. + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, _ []string) { + _ = cmd.Help() + }, } cmd.AddCommand(newConfigInitCommand()) diff --git a/internal/cli/database.go b/internal/cli/database.go index 04605df..1ae477b 100644 --- a/internal/cli/database.go +++ b/internal/cli/database.go @@ -15,6 +15,12 @@ func NewDatabaseCommand() *cobra.Command { Use: "database", Short: "Manage the local state database", Long: `Commands for managing the local SQLite state database.`, + // cobra checks Args only on a command that has a Run: without + // one, a mistyped subcommand printed help and exited 0. + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, _ []string) { + _ = cmd.Help() + }, } cmd.AddCommand( diff --git a/internal/cli/entry_unknown_subcommand_test.go b/internal/cli/entry_unknown_subcommand_test.go new file mode 100644 index 0000000..08c9647 --- /dev/null +++ b/internal/cli/entry_unknown_subcommand_test.go @@ -0,0 +1,43 @@ +package cli //nolint:testpackage // shares runEntry and the command-word constants + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestEntryGroupRejectsUnknownSubcommand runs each group command with a +// mistyped subcommand, as a crontab line might carry one. It must fail +// with exit 1 and name the word, as `vaultik bogus` does at the top +// level, instead of printing the group's help and exiting 0 having done +// nothing. The group name alone still prints its help. +// +//nolint:paralleltest // replaces os.Args, os.Stdout and os.Stderr +func TestEntryGroupRejectsUnknownSubcommand(t *testing.T) { + for _, testCase := range []struct { + group string + mistyped string + }{ + {group: cmdSnapshot, mistyped: "craete"}, + {group: "config", mistyped: "inti"}, + {group: cmdRemote, mistyped: "ifno"}, + {group: "database", mistyped: "delte"}, + {group: "completion", mistyped: "nosuchshell"}, + } { + t.Run(testCase.group, func(t *testing.T) { + code, stdout, stderr := runEntry(t, + testCase.group, testCase.mistyped) + + assert.Equal(t, 1, code) + assert.Empty(t, stdout) + assert.Contains(t, stderr, + `unknown command "`+testCase.mistyped+`"`) + + code, stdout, _ = runEntry(t, testCase.group) + + assert.Equal(t, 0, code) + assert.Contains(t, stdout, + programName+" "+testCase.group+" [command]") + }) + } +} diff --git a/internal/cli/remote.go b/internal/cli/remote.go index dd72e9f..4bf403f 100644 --- a/internal/cli/remote.go +++ b/internal/cli/remote.go @@ -18,6 +18,12 @@ func NewRemoteCommand() *cobra.Command { Use: "remote", Short: "Remote storage management commands", Long: "Commands for inspecting and managing remote storage", + // cobra checks Args only on a command that has a Run: without + // one, a mistyped subcommand printed help and exited 0. + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, _ []string) { + _ = cmd.Help() + }, } // Add subcommands diff --git a/internal/cli/root.go b/internal/cli/root.go index 463eb1d..ba1fcbc 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -74,6 +74,21 @@ on the source system.`, NewDatabaseCommand(), ) + // cobra adds the completion command only when Execute runs, and with + // no Run, so it skipped its own cobra.NoArgs and a mistyped shell name + // printed help and exited 0. Adding it here lets it have a Run. Its + // scripts go to os.Stdout as it is now: a later SetOut does not + // redirect them. + cmd.InitDefaultCompletionCmd() + + for _, sub := range cmd.Commands() { + if sub.Name() == "completion" { + sub.Run = func(completion *cobra.Command, _ []string) { + _ = completion.Help() + } + } + } + return cmd } diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index f157102..0997140 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -41,6 +41,12 @@ func NewSnapshotCommand() *cobra.Command { Use: "snapshot", Short: "Snapshot management commands", Long: "Commands for creating, listing, and managing snapshots", + // cobra checks Args only on a command that has a Run: without + // one, a mistyped subcommand printed help and exited 0. + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, _ []string) { + _ = cmd.Help() + }, } // Add subcommands From 09a0c01c43b46a2ecf27b2cc448eb1c990db0405 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 15:48:00 +0200 Subject: [PATCH 052/121] Stop a stalled blob read when restore or deep verify is interrupted (closes #325) Restore and deep verify looked for a cancel only between blobs, and the file backend's reader ignores the context. A blob read stalled on a slow USB stick or network share outlasted the 30-second shutdown timeout, so the process exited before removing the decrypted snapshot database and blob cache from the temp directory. FetchBlob, through which both read every blob, now closes the storage reader as soon as the context is cancelled, ending a blocked read on any backend; Read then returns the context's error, not the closed reader's. Limitation: a read stuck in the kernel that closing cannot interrupt, such as one on an unresponsive hard NFS mount, still cannot be stopped. Model: opus-5-5 --- internal/vaultik/blob_fetch.go | 46 +++++++- internal/vaultik/restore_interrupt_test.go | 120 ++++++++++++++++++++- 2 files changed, 163 insertions(+), 3 deletions(-) diff --git a/internal/vaultik/blob_fetch.go b/internal/vaultik/blob_fetch.go index 714c7d1..aa00243 100644 --- a/internal/vaultik/blob_fetch.go +++ b/internal/vaultik/blob_fetch.go @@ -103,6 +103,8 @@ func (v *Vaultik) FetchAndDecryptBlob( } // FetchBlob downloads a blob and returns a reader for the encrypted data. +// The reader is closed as soon as ctx is cancelled, which ends a read +// blocked inside it. func (v *Vaultik) FetchBlob( ctx context.Context, blobHash string, ) (io.ReadCloser, error) { @@ -120,5 +122,47 @@ func (v *Vaultik) FetchBlob( return nil, fmt.Errorf("downloading blob %s: %w", shortHash(blobHash), err) } - return rc, nil + return newCloseOnCancelReader(ctx, rc), nil +} + +// closeOnCancelReader closes the reader it wraps when ctx is cancelled. +// Not every backend's reader stops on cancel by itself (the file +// backend's does not), and a read stalled on a slow or hung source would +// otherwise outlast the shutdown timeout, so the process would exit +// before restore or deep verify removed its decrypted temporary files. +type closeOnCancelReader struct { + io.ReadCloser + + ctx context.Context //nolint:containedctx // Read reports its error + stop func() bool +} + +func newCloseOnCancelReader( + ctx context.Context, rc io.ReadCloser, +) *closeOnCancelReader { + return &closeOnCancelReader{ + ReadCloser: rc, + ctx: ctx, + stop: context.AfterFunc(ctx, func() { _ = rc.Close() }), + } +} + +// Read returns the context's error, not the closed reader's, once ctx +// has been cancelled. +func (r *closeOnCancelReader) Read(p []byte) (int, error) { + n, err := r.ReadCloser.Read(p) + if err != nil && r.ctx.Err() != nil { + return n, r.ctx.Err() + } + + return n, err +} + +// Close closes the wrapped reader, unless the cancel already closed it. +func (r *closeOnCancelReader) Close() error { + if !r.stop() { + return nil + } + + return r.ReadCloser.Close() } diff --git a/internal/vaultik/restore_interrupt_test.go b/internal/vaultik/restore_interrupt_test.go index 0625ccb..2024a0d 100644 --- a/internal/vaultik/restore_interrupt_test.go +++ b/internal/vaultik/restore_interrupt_test.go @@ -142,14 +142,14 @@ func TestRestoreCleansTempDirOnInterrupt(t *testing.T) { } // scratchEntries returns the vaultik blob-cache and snapshot-database -// scratch entries currently present in dir. +// scratch entries (restore's and deep verify's) currently present in dir. func scratchEntries(t *testing.T, dir string) []string { t.Helper() var matches []string for _, pattern := range []string{ - "vaultik-blobcache-*", "vaultik-restore-*", + "vaultik-blobcache-*", "vaultik-restore-*", "vaultik-verify-*", } { found, err := filepath.Glob(filepath.Join(dir, pattern)) require.NoError(t, err) @@ -206,3 +206,119 @@ func TestRestoreSkipErrorsCancelDuringBlobDownload(t *testing.T) { assert.NotContains(t, out.String(), srcPath, "the cancel was reported as a failed file") } + +// stallingBlobStorer wraps a Storer so that every blob download hands +// over the first half of the blob and then stalls, ignoring the context, +// as a file:// blob on a hung USB stick or network share does. Only +// closing the returned reader ends the stall. +type stallingBlobStorer struct { + storage.Storer + + once sync.Once + stalled chan struct{} +} + +func newStallingBlobStorer(inner storage.Storer) *stallingBlobStorer { + return &stallingBlobStorer{Storer: inner, stalled: make(chan struct{})} +} + +func (s *stallingBlobStorer) Get( + ctx context.Context, key string, +) (io.ReadCloser, error) { + rc, err := s.Storer.Get(ctx, key) + if err != nil || !strings.HasPrefix(key, "blobs/") { + return rc, err + } + + blob, err := io.ReadAll(rc) + _ = rc.Close() + + if err != nil { + return nil, err + } + + // The writer is never closed, so once the first half has been read + // the next Read blocks until the reader is closed. + pr, pw := io.Pipe() + + go func() { + _, _ = pw.Write(blob[:len(blob)/2]) + + s.once.Do(func() { close(s.stalled) }) + }() + + return pr, nil +} + +// TestInterruptDuringStalledBlobReadCleansTempDir stops a restore and a +// deep verify while a blob read is stalled on a source that ignores the +// context. Stopping must end that read, so the operation unwinds and +// removes its decrypted scratch files well within the shutdown timeout +// (issue #325). +// +// Not parallel: it points TMPDIR at a private directory (via t.Setenv) +// so it can assert on exactly the scratch files the operation created. +func TestInterruptDuringStalledBlobReadCleansTempDir(t *testing.T) { + log.Initialize(log.Config{}) + + operations := map[string]func(v *Vaultik, snapshotID, targetDir string) error{ + "restore": func(v *Vaultik, snapshotID, targetDir string) error { + return v.Restore(&RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: targetDir, + }) + }, + "deep verify": func(v *Vaultik, snapshotID, _ string) error { + return v.RunDeepVerify(snapshotID, &VerifyOptions{Deep: true}) + }, + } + + for name, op := range operations { + t.Run(name, func(t *testing.T) { + fs := afero.NewOsFs() + root := t.TempDir() + + // Random content, so the blob stays large enough to stall + // part-way through its compressed, encrypted body. + cfg, storer, snapshotID, _ := backupOneFile(context.Background(), + t, fs, root, "a.bin", randomBytes(t, 256*1024), 0o644) + + scratch := filepath.Join(root, "scratch") + require.NoError(t, fs.MkdirAll(scratch, 0o755)) + t.Setenv("TMPDIR", scratch) + + stalling := newStallingBlobStorer(storer) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + v := newRestoreVaultik(ctx, cfg, stalling, fs) + v.cancel = cancel + + var opErr error + + stop := v.StartOperation(func() { + opErr = op(v, snapshotID, filepath.Join(root, "restored")) + }) + + select { + case <-stalling.stalled: + case <-time.After(30 * time.Second): + t.Fatal("the operation never reached a blob read") + } + + require.NotEmpty(t, scratchEntries(t, scratch), + "expected decrypted scratch files to exist mid-read") + + stopCtx, stopCancel := context.WithTimeout( + context.Background(), 10*time.Second) + defer stopCancel() + + require.True(t, stop(stopCtx), + "stop timed out; the stalled blob read was not interrupted") + require.ErrorIs(t, opErr, context.Canceled) + require.Empty(t, scratchEntries(t, scratch), + "decrypted scratch files remained after the interrupt") + }) + } +} From 005927a7fc2045de95424771326e3cdf59abd3d6 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 16:22:03 +0200 Subject: [PATCH 053/121] Print snapshot list and purge sizes like every other command (closes #312) `snapshot list`, the `snapshot purge` listing and the `bytes` value in terminal log lines divided by 1024 while labelling the result KB or MB, so 6,329,198 bytes read 6.0 MB there and 6.3 MB in every other command. All three now use humanize.Bytes, as the rest of the program does, and the 1024-based helper in internal/vaultik is removed. The size shared by the list tests is now 5,000,000 bytes, which the two ways of counting print differently. Judgement call: the log handler's copy of the formatter is changed too, since the issue asks that every command print a byte count the same way. Model: opus-5-5 --- internal/log/tty_handler.go | 17 ++++------ internal/log/tty_handler_test.go | 9 ++--- internal/vaultik/helpers.go | 16 --------- internal/vaultik/snapshot.go | 2 +- internal/vaultik/snapshot_list.go | 6 ++-- internal/vaultik/snapshot_list_test.go | 46 ++++++++++++++++++++++++-- 6 files changed, 60 insertions(+), 36 deletions(-) diff --git a/internal/log/tty_handler.go b/internal/log/tty_handler.go index 63f0dc4..fbcef68 100644 --- a/internal/log/tty_handler.go +++ b/internal/log/tty_handler.go @@ -10,6 +10,8 @@ import ( "sync" "time" "unicode" + + "github.com/dustin/go-humanize" ) // groupSeparator joins an open group path to an attribute key. This @@ -304,18 +306,13 @@ func formatDuration(d time.Duration) string { } } -// formatBytes formats bytes in a human-readable way +// formatBytes formats a byte count with humanize.Bytes, as every command +// prints one. humanize.Bytes takes no negative count, so one is printed +// as it is. func formatBytes(b int64) string { - const unit = 1024 - if b < unit { + if b < 0 { return fmt.Sprintf("%d B", b) } - div, exp := int64(unit), 0 - for n := b / unit; n >= unit; n /= unit { - div *= unit - exp++ - } - - return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "KMGTPE"[exp]) + return humanize.Bytes(uint64(b)) } diff --git a/internal/log/tty_handler_test.go b/internal/log/tty_handler_test.go index 694657f..8d0819d 100644 --- a/internal/log/tty_handler_test.go +++ b/internal/log/tty_handler_test.go @@ -200,7 +200,8 @@ func TestTTYHandlerWithGroupQualifiesKeys(t *testing.T) { func TestTTYHandlerByteFormattingSurvivesGrouping(t *testing.T) { t.Parallel() - const oneAndAHalfKiB = 1536 + // Printed as "1.0 MB", in powers of 1000 like every other byte count. + const oneMegabyte = 1_000_000 for name, testCase := range map[string]struct { derive func(*slog.Logger) *slog.Logger @@ -223,13 +224,13 @@ func TestTTYHandlerByteFormattingSurvivesGrouping(t *testing.T) { var buf bytes.Buffer logger := slog.New(log.NewTTYHandler(&buf, debugHandlerOptions())) - testCase.derive(logger).Info("uploaded", "bytes", oneAndAHalfKiB) + testCase.derive(logger).Info("uploaded", "bytes", oneMegabyte) line := ansiEscape.ReplaceAllString(buf.String(), "") - assert.Contains(t, line, testCase.key+"=1.5 KB", + assert.Contains(t, line, testCase.key+"=1.0 MB", "a byte count must be human-readable however it is qualified") - assert.NotContains(t, line, strconv.Itoa(oneAndAHalfKiB), + assert.NotContains(t, line, strconv.Itoa(oneMegabyte), "the raw number must not survive the formatting") }) } diff --git a/internal/vaultik/helpers.go b/internal/vaultik/helpers.go index 325d8f2..c891b34 100644 --- a/internal/vaultik/helpers.go +++ b/internal/vaultik/helpers.go @@ -89,22 +89,6 @@ type SnapshotInfo struct { RemotePresent *bool `json:"remote_present"` } -// formatBytes formats bytes in a human-readable format -func formatBytes(bytes int64) string { - const unit = 1024 - if bytes < unit { - return fmt.Sprintf("%d B", bytes) - } - - div, exp := int64(unit), 0 - for n := bytes / unit; n >= unit; n /= unit { - div *= unit - exp++ - } - - return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp]) -} - // parseSnapshotTimestamp extracts the timestamp from a snapshot ID // Format: hostname_snapshotname_2026-01-12T14:41:15Z func parseSnapshotTimestamp(snapshotID string) (time.Time, error) { diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 9b767df..f2aff52 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -633,7 +633,7 @@ func (v *Vaultik) confirmAndExecutePurge( v.stdoutf(" %s (%s, %s)\n", snap.ID, snap.Timestamp.Format("2006-01-02 15:04:05"), - formatBytes(snap.CompressedSize)) + ubytes(snap.CompressedSize)) } } diff --git a/internal/vaultik/snapshot_list.go b/internal/vaultik/snapshot_list.go index f3a0269..8ed7b6b 100644 --- a/internal/vaultik/snapshot_list.go +++ b/internal/vaultik/snapshot_list.go @@ -553,8 +553,8 @@ func (v *Vaultik) printSnapshotTable(snapshots []SnapshotInfo) error { if snap.LocallyTracked { id = snap.ID.String() - uncompressed = formatBytes(snap.UncompressedSize) - newChunks = formatBytes(snap.NewChunkSize) + uncompressed = ubytes(snap.UncompressedSize) + newChunks = ubytes(snap.NewChunkSize) } else { id = formatRemoteOnlyID(snap.RemoteKey) uncompressed = remoteOnlyCell @@ -564,7 +564,7 @@ func (v *Vaultik) printSnapshotTable(snapshots []SnapshotInfo) error { _, err = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", id, snap.Timestamp.Format("2006-01-02 15:04:05"), - formatBytes(snap.CompressedSize), + ubytes(snap.CompressedSize), uncompressed, newChunks) if err != nil { diff --git a/internal/vaultik/snapshot_list_test.go b/internal/vaultik/snapshot_list_test.go index 030f545..54c2d0e 100644 --- a/internal/vaultik/snapshot_list_test.go +++ b/internal/vaultik/snapshot_list_test.go @@ -212,8 +212,8 @@ const ( listConfiguredName = "home" listLocalID = "testhost_home_2026-03-01T10:00:00Z" listRemoteID = "otherhost_media_2026-03-02T11:22:33Z" - // fiveMegabytes formats as "5.0 MB" through formatBytes. - fiveMegabytes = 5 * 1024 * 1024 + // fiveMegabytes is printed as "5.0 MB" by every command. + fiveMegabytes = 5_000_000 ) // TestListSnapshots_RemoteWithoutSecretKey is the regression guard for @@ -306,6 +306,48 @@ func TestListSnapshots_RemoteOnlyRowRendering(t *testing.T) { "are not in the local index") } +// TestSnapshotListAndPurgePrintSizesLikeRemoteInfo checks that the +// `snapshot list` table and the purge listing print a byte count the way +// `remote info` does: in powers of 1000, as the MB label says. +func TestSnapshotListAndPurgePrintSizesLikeRemoteInfo(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const wantSize = "5.0 MB" // fiveMegabytes + + env := newListEnv(t) + + // A remote-only snapshot: `snapshot list` and `remote info` both take + // its size from the manifest. + remoteKey := env.addRemote(t, listRemoteID, + time.Date(2026, 3, 2, 11, 22, 33, 0, time.UTC)) + + // A locally tracked snapshot of the same size for the purge to list. + // The purge prints the snapshot's blob size, the last argument here. + start := time.Date(2026, 3, 1, 10, 0, 0, 0, time.UTC) + env.addLocal(t, listLocalID, start) + env.addRemote(t, listLocalID, start) + require.NoError(t, env.v.Repositories.Snapshots.UpdateCounts( + context.Background(), nil, listLocalID, 0, 0, 0, 0, fiveMegabytes)) + + require.NoError(t, env.v.RemoteInfo(false)) + assert.Contains(t, findTableRow(t, env.stdout.String(), remoteKey[:16]), + wantSize, "remote info") + + env.stdout.Reset() + require.NoError(t, env.v.ListSnapshots(false)) + assert.Contains(t, findTableRow(t, env.stdout.String(), + ""), wantSize, "snapshot list") + + // Without --force and with nothing on stdin the purge lists what it + // would delete, reads no confirmation, and deletes nothing. + env.stdout.Reset() + require.NoError(t, env.v.PurgeSnapshotsWithOptions( + &vaultik.SnapshotPurgeOptions{OlderThan: "1d"})) + assert.Contains(t, findTableRow(t, env.stdout.String(), listLocalID), + wantSize, "snapshot purge") +} + // findTableRow returns the single output line containing needle. func findTableRow(t *testing.T, out, needle string) string { t.Helper() From f4ab1ba5aea5ffce352a1f95e8e1c38e19f01c1e Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 16:28:59 +0200 Subject: [PATCH 054/121] Exit as interrupted when Ctrl-C lands during a local index write (closes #301) Once the run's context is cancelled, database/sql rolls an open transaction back itself, so the rollback in WithTx returned sql.ErrTxDone. WithTx treated any rollback error as fatal and called os.Exit(1): an interrupted backup printed "FATAL: failed to rollback transaction", exited 1 instead of 130 and skipped its deferred cleanup. WithTx now ignores sql.ErrTxDone from the rollback and returns the body's error alone. A rollback that really fails is returned together with the body's error instead of ending the process; on a panic it is dropped and the panic carries on. The cancel test checks that the returned error carries no sql.ErrTxDone; the other tests make the rollback really fail by running ROLLBACK inside the body. Model: opus-5-5 --- internal/database/repositories.go | 21 +++-- internal/database/repositories_test.go | 120 +++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 9 deletions(-) diff --git a/internal/database/repositories.go b/internal/database/repositories.go index 64a3f66..4db15d1 100644 --- a/internal/database/repositories.go +++ b/internal/database/repositories.go @@ -3,6 +3,7 @@ package database import ( "context" "database/sql" + "errors" "fmt" ) @@ -60,22 +61,24 @@ func (r *Repositories) WithTx(ctx context.Context, fn TxFunc) error { defer func() { if p := recover(); p != nil { - rollbackErr := tx.Rollback() - if rollbackErr != nil { - Fatalf("failed to rollback transaction: %v", rollbackErr) - } + // The panic is the failure to report, so a rollback error + // is dropped. + _ = tx.Rollback() panic(p) - } else if err != nil { - rollbackErr := tx.Rollback() - if rollbackErr != nil { - Fatalf("failed to rollback transaction: %v", rollbackErr) - } } }() err = fn(ctx, tx) if err != nil { + // Once ctx is cancelled, database/sql rolls the transaction + // back itself and Rollback returns sql.ErrTxDone. + rollbackErr := tx.Rollback() + if rollbackErr != nil && !errors.Is(rollbackErr, sql.ErrTxDone) { + return fmt.Errorf("%w; rolling back transaction: %w", + err, rollbackErr) + } + return err } diff --git a/internal/database/repositories_test.go b/internal/database/repositories_test.go index f4e2199..06e588e 100644 --- a/internal/database/repositories_test.go +++ b/internal/database/repositories_test.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "errors" + "strings" "testing" "time" @@ -235,6 +236,125 @@ func TestRepositoriesTransactionRollback(t *testing.T) { } } +// When the context is cancelled during the body, database/sql rolls the +// transaction back itself, so WithTx's own rollback finds it already +// done. WithTx must return the body's error alone, without that rollback. +func TestRepositoriesTransactionContextCancelled(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + repos := database.NewRepositories(db) + + err := repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + file := &database.File{ + Path: "/test/cancelled_file.txt", + MTime: time.Now().Truncate(time.Second), + Size: 1024, + Mode: 0644, + UID: 1000, + GID: 1000, + } + + err := repos.Files.Create(ctx, tx, file) + if err != nil { + return err + } + + cancel() + + // database/sql rolls back from a goroutine of its own; wait + // until it has, so the test does not depend on that race. + for { + _, err = tx.ExecContext(context.WithoutCancel(ctx), "SELECT 1") + if errors.Is(err, sql.ErrTxDone) { + return ctx.Err() + } + + time.Sleep(time.Millisecond) + } + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got: %v", err) + } + + if errors.Is(err, sql.ErrTxDone) { + t.Fatalf("the already-done rollback was reported: %v", err) + } + + file, err := repos.Files.GetByPath( + context.Background(), "/test/cancelled_file.txt", + ) + if err != nil { + t.Fatalf("error checking for file: %v", err) + } + + if file != nil { + t.Error("file should not exist after the cancelled transaction") + } +} + +// A body that ends the transaction itself with ROLLBACK makes WithTx's +// own rollback fail. WithTx must return that failure together with the +// body's error. +func TestRepositoriesTransactionRollbackFails(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repos := database.NewRepositories(db) + + err := repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + _, err := tx.ExecContext(ctx, "ROLLBACK") + if err != nil { + return err + } + + return errIntentionalRollback + }) + if !errors.Is(err, errIntentionalRollback) { + t.Fatalf("expected the body's error, got: %v", err) + } + + if !strings.Contains(err.Error(), "rolling back transaction") { + t.Errorf("expected the failed rollback in the error, got: %v", err) + } +} + +// When the body ends the transaction itself with ROLLBACK and then +// panics, WithTx's own rollback fails; the panic must still reach the +// caller. +func TestRepositoriesTransactionPanicRollbackFails(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repos := database.NewRepositories(db) + + defer func() { + if recover() == nil { + t.Error("expected the body's panic to reach the caller") + } + }() + + _ = repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + _, err := tx.ExecContext(ctx, "ROLLBACK") + if err != nil { + return err + } + + panic(errIntentionalRollback) + }) +} + func TestRepositoriesReadTransaction(t *testing.T) { t.Parallel() From bffd4578fc567a40eee0f51cb1618b3514163e75 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 16:44:14 +0200 Subject: [PATCH 055/121] Record each snapshot's new chunk size when its backup runs (closes #311) snapshot list worked out NEW CHUNK SIZE from the snapshot's file rows. A file's row is shared by every snapshot that lists it and rewritten when the file changes, so a snapshot whose change was a modified file showed 0 B, and older snapshots' figures moved after later backups. The scanner now totals the size of the chunks it stores that were not stored before (the chunks chunk_count counts), the backup writes that total to a new snapshots column, new_chunk_size, and snapshot list reads it. Judgement call: the figure is fixed when the backup runs, so removing an earlier snapshot no longer raises a later snapshot's figure. Model: opus-5-5 --- README.md | 8 +- docs/DATAMODEL.md | 1 + internal/database/schema/001.sql | 1 + internal/database/snapshots.go | 47 +++------ internal/snapshot/scanner.go | 12 ++- internal/snapshot/snapshot.go | 2 + internal/vaultik/new_chunk_size_test.go | 133 ++++++++++++++++++++++++ internal/vaultik/snapshot.go | 3 + internal/vaultik/snapshot_list_test.go | 1 + 9 files changed, 167 insertions(+), 41 deletions(-) create mode 100644 internal/vaultik/new_chunk_size_test.go diff --git a/README.md b/README.md index 355322d..f4c5f61 100644 --- a/README.md +++ b/README.md @@ -293,8 +293,8 @@ needed. **`snapshot list`**: Show every snapshot known to this host — the union of the local index and the backup destination store — with timestamps and three sizes per snapshot (compressed remote size; total -uncompressed chunk size; size of chunks newly referenced by that -snapshot). +uncompressed chunk size; size of the chunks that snapshot stored that +were not stored before, recorded when its backup ran). Listing the destination store does **not** require the age secret key, so it works in vaultik's intended configuration, where the backed-up @@ -307,8 +307,8 @@ only the hash, so hostname and snapshot name exist solely in the local index and in the encrypted per-snapshot database. Snapshots found only on the destination store are therefore listed as `>` and show `` in -the uncompressed and "new chunk" columns, which can only be computed -from the local index. Their timestamp and compressed size are real, +the uncompressed and "new chunk" columns, which come only from the +local index. Their timestamp and compressed size are real, read from the manifest. Snapshots in the local index with no counterpart on the destination diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index bcb9d1c..b3191ac 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -119,6 +119,7 @@ Tracks backup snapshots. - `completed_at` (INTEGER) - Completion timestamp (NULL if in progress) - `file_count` (INTEGER) - Number of files in snapshot - `chunk_count` (INTEGER) - Number of chunks this snapshot stored that were not stored before +- `new_chunk_size` (INTEGER) - Total size of those chunks before compression; `snapshot list` shows it as NEW CHUNK SIZE - `blob_count` (INTEGER) - Number of blobs this snapshot created - `total_size` (INTEGER) - Total size of all files - `blob_size` (INTEGER) - Total compressed size of all referenced blobs diff --git a/internal/database/schema/001.sql b/internal/database/schema/001.sql index c07d978..0b022c2 100644 --- a/internal/database/schema/001.sql +++ b/internal/database/schema/001.sql @@ -86,6 +86,7 @@ CREATE TABLE IF NOT EXISTS snapshots ( completed_at INTEGER, file_count INTEGER NOT NULL DEFAULT 0, chunk_count INTEGER NOT NULL DEFAULT 0, + new_chunk_size INTEGER NOT NULL DEFAULT 0, blob_count INTEGER NOT NULL DEFAULT 0, total_size INTEGER NOT NULL DEFAULT 0, blob_size INTEGER NOT NULL DEFAULT 0, diff --git a/internal/database/snapshots.go b/internal/database/snapshots.go index 09d3b3a..c9c609a 100644 --- a/internal/database/snapshots.go +++ b/internal/database/snapshots.go @@ -129,6 +129,7 @@ func (r *SnapshotRepository) UpdateExtendedStats( compressionLevel int, uploadBytes int64, uploadDurationMs int64, + newChunkSize int64, ) error { compressionRatio, err := r.extendedCompressionRatio( ctx, tx, snapshotID, blobUncompressedSize, @@ -143,18 +144,19 @@ func (r *SnapshotRepository) UpdateExtendedStats( compression_ratio = ?, compression_level = ?, upload_bytes = ?, - upload_duration_ms = ? + upload_duration_ms = ?, + new_chunk_size = ? WHERE id = ? ` if tx != nil { _, err = tx.ExecContext(ctx, query, blobUncompressedSize, compressionRatio, compressionLevel, - uploadBytes, uploadDurationMs, snapshotID) + uploadBytes, uploadDurationMs, newChunkSize, snapshotID) } else { _, err = r.db.ExecWithLog(ctx, query, blobUncompressedSize, compressionRatio, compressionLevel, - uploadBytes, uploadDurationMs, snapshotID) + uploadBytes, uploadDurationMs, newChunkSize, snapshotID) } if err != nil { @@ -594,45 +596,24 @@ func (r *SnapshotRepository) GetSnapshotUncompressedChunkSize( return totalSize, nil } -// GetSnapshotNewChunkSize returns the sum of plaintext sizes of chunks that are -// referenced by this snapshot but not by any earlier completed snapshot known to -// the local database. The result is the marginal uncompressed data this snapshot -// added to the dedup pool — i.e., the delta from prior snapshots. +// GetSnapshotNewChunkSize returns the total plaintext size of the chunks the +// snapshot's backup stored that were not stored before, as the backup +// recorded it. It is not derived from the snapshot's files: a file's row is +// shared by every snapshot that lists it and is rewritten when the file +// changes, so it shows only the file's latest chunks. func (r *SnapshotRepository) GetSnapshotNewChunkSize( ctx context.Context, snapshotID string, ) (int64, error) { - query := ` - WITH this_snap_chunks AS ( - SELECT DISTINCT fc.chunk_hash - FROM snapshot_files sf - JOIN file_chunks fc ON sf.file_id = fc.file_id - WHERE sf.snapshot_id = ? - ), - prior_chunks AS ( - SELECT DISTINCT fc.chunk_hash - FROM snapshots s - JOIN snapshot_files sf ON sf.snapshot_id = s.id - JOIN file_chunks fc ON fc.file_id = sf.file_id - WHERE s.completed_at IS NOT NULL - AND s.id != ? - AND s.started_at < (SELECT started_at FROM snapshots WHERE id = ?) - ) - SELECT COALESCE(SUM(c.size), 0) - FROM chunks c - JOIN this_snap_chunks t ON c.chunk_hash = t.chunk_hash - WHERE c.chunk_hash NOT IN (SELECT chunk_hash FROM prior_chunks) - ` + query := `SELECT new_chunk_size FROM snapshots WHERE id = ?` - var totalSize int64 + var newChunkSize int64 - err := r.db.conn.QueryRowContext( - ctx, query, snapshotID, snapshotID, snapshotID, - ).Scan(&totalSize) + err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan(&newChunkSize) if err != nil { return 0, fmt.Errorf("querying new chunk size: %w", err) } - return totalSize, nil + return newChunkSize, nil } // GetIncompleteSnapshots returns all snapshots that haven't been completed diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index e54ee1a..32441cf 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -135,7 +135,9 @@ type ScannerConfig struct { // are counted per file: BytesScanned is the size of the new and changed // files, BytesSkipped that of the unchanged ones. FilesFailed counts the // new and changed files that phase 2 could not store; FilesScanned -// includes them and BytesScanned does not. +// includes them and BytesScanned does not. ChunksCreated counts the +// chunks that were not already stored, and NewChunkSize is their total +// size. type ScanResult struct { FilesScanned int FilesSkipped int @@ -145,6 +147,7 @@ type ScanResult struct { BytesSkipped int64 BytesDeleted int64 ChunksCreated int + NewChunkSize int64 BlobsCreated int BlobsUploaded int BytesUploaded int64 @@ -1866,11 +1869,12 @@ func (s *Scanner) processFileStreaming( return nil } -// updateChunkStats counts a chunk that was not already stored. The scan -// result's file counts, BytesScanned and BytesSkipped are not touched -// here: the scan phase counts each file once. +// updateChunkStats counts a chunk that was not already stored, and its +// size. The scan result's file counts, BytesScanned and BytesSkipped are +// not touched here: the scan phase counts each file once. func (s *Scanner) updateChunkStats(chunkSize int64, result *ScanResult) { result.ChunksCreated++ + result.NewChunkSize += chunkSize if s.progress != nil { s.progress.GetStats().ChunksCreated.Add(1) diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index cdf641e..a959930 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -199,6 +199,7 @@ func (sm *SnapshotManager) UpdateSnapshotStatsExtended( stats.CompressionLevel, stats.BytesUploaded, stats.UploadDurationMs, + stats.NewChunkSize, ) }) } @@ -906,6 +907,7 @@ type ExtendedBackupStats struct { BlobUncompressedSize int64 // Total uncompressed size of all referenced blobs CompressionLevel int // Compression level used for this snapshot UploadDurationMs int64 // Total milliseconds spent uploading to S3 + NewChunkSize int64 // Total size of the chunks counted in ChunksCreated } // deleteOtherSnapshots deletes all snapshots except the current one diff --git a/internal/vaultik/new_chunk_size_test.go b/internal/vaultik/new_chunk_size_test.go new file mode 100644 index 0000000..5301334 --- /dev/null +++ b/internal/vaultik/new_chunk_size_test.go @@ -0,0 +1,133 @@ +package vaultik_test + +import ( + "bytes" + "context" + "maps" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/chunker" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestNewChunkSizeOfChangedFileStaysFixed covers +// https://git.eeqj.de/sneak/vaultik/issues/311. A backup whose only change +// is a modified file lists the size of the chunks that change added as its +// NEW CHUNK SIZE, and a later backup that changes the file again leaves +// every earlier snapshot's figure as it was. The file's row in the local +// index is shared by all three snapshots and rewritten by each backup. +func TestNewChunkSizeOfChangedFileStaysFixed(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + dbPath := filepath.Join(tempDir, "index.sqlite") + changedPath := filepath.Join(dataDir, "changed.bin") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, dataDir) + cfg := changedFileConfig(dataDir, dbPath) + + appendRandomBytes(t, fs, files, changedPath, appendedFileSize) + + store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, "first")) + + firstFiles := maps.Clone(files) + firstID := localSnapshotID(ctx, t, repos, "first") + + appendRandomBytes(t, fs, files, changedPath, faultChunkSize) + require.NoError(t, backUp(v, "second")) + + secondID := localSnapshotID(ctx, t, repos, "second") + secondAdded := sizeOfNewChunks(t, files, firstFiles) + require.Positive(t, secondAdded) + assert.Equal(t, secondAdded, listedNewChunkSizes(t, v)[secondID], + "the second snapshot must count the chunks the change added") + + appendRandomBytes(t, fs, files, changedPath, faultChunkSize) + require.NoError(t, backUp(v, "third")) + + sizes := listedNewChunkSizes(t, v) + assert.Equal(t, sizeOfNewChunks(t, firstFiles, nil), sizes[firstID], + "a later backup must not change the first snapshot's figure") + assert.Equal(t, secondAdded, sizes[secondID], + "a later backup must not change the second snapshot's figure") +} + +// sizeOfNewChunks returns the total size of the distinct chunks of the +// files in after that no file in before has, cut the way the backup cuts +// them. +func sizeOfNewChunks(t *testing.T, after, before map[string][]byte) int64 { + t.Helper() + + known := make(map[string]bool) + for _, chunk := range chunksOf(t, before) { + known[chunk.Hash] = true + } + + var total int64 + + for _, chunk := range chunksOf(t, after) { + if !known[chunk.Hash] { + known[chunk.Hash] = true + total += chunk.Size + } + } + + return total +} + +// chunksOf returns the chunks of every file in files. +func chunksOf(t *testing.T, files map[string][]byte) []chunker.Chunk { + t.Helper() + + c := chunker.NewChunker(faultChunkSize) + + var all []chunker.Chunk + + for _, content := range files { + chunks, err := c.ChunkReader(bytes.NewReader(content)) + require.NoError(t, err) + + all = append(all, chunks...) + } + + return all +} + +// listedNewChunkSizes runs `snapshot list --json` and returns each listed +// snapshot's new_chunk_size by snapshot ID. +func listedNewChunkSizes(t *testing.T, v *vaultik.Vaultik) map[string]int64 { + t.Helper() + + var out bytes.Buffer + + v.Stdout = &out + require.NoError(t, v.ListSnapshots(true)) + + sizes := make(map[string]int64) + for _, row := range decodeListJSON(t, out.String()) { + sizes[row.ID] = row.NewChunkSize + } + + return sizes +} diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index f2aff52..17bb5ea 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -209,6 +209,7 @@ type snapshotStats struct { totalFiles int totalBytes int64 totalChunks int + newChunkSize int64 totalBlobs int totalBytesSkipped int64 totalFilesSkipped int @@ -341,6 +342,7 @@ func (v *Vaultik) scanAllDirectories( stats.totalFiles += result.FilesScanned stats.totalBytes += result.BytesScanned stats.totalChunks += result.ChunksCreated + stats.newChunkSize += result.NewChunkSize stats.totalBlobs += result.BlobsCreated stats.totalFilesSkipped += result.FilesSkipped stats.totalFilesFailed += result.FilesFailed @@ -403,6 +405,7 @@ func (v *Vaultik) finalizeSnapshotMetadata( BlobUncompressedSize: stats.blobUncompressedSize, CompressionLevel: v.Config.CompressionLevel, UploadDurationMs: stats.uploadDuration.Milliseconds(), + NewChunkSize: stats.newChunkSize, } err = v.SnapshotManager.UpdateSnapshotStatsExtended(v.ctx, snapshotID, extStats) diff --git a/internal/vaultik/snapshot_list_test.go b/internal/vaultik/snapshot_list_test.go index 54c2d0e..3beb371 100644 --- a/internal/vaultik/snapshot_list_test.go +++ b/internal/vaultik/snapshot_list_test.go @@ -487,6 +487,7 @@ type listJSONRow struct { RemoteKey string `json:"remote_key"` Timestamp string `json:"timestamp"` CompressedSize int64 `json:"compressed_size"` + NewChunkSize int64 `json:"new_chunk_size"` LocallyTracked bool `json:"locally_tracked"` RemotePresent *bool `json:"remote_present"` } From e48bafccef33eba71fa2c101c45c99162f12a327 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 16:53:05 +0200 Subject: [PATCH 056/121] Restore the other files when a chunk is in no blob under --skip-errors (closes #326) Restore planning stopped at the first file needing a chunk that no blob holds, so --skip-errors never saw that file and nothing was restored. The planner now leaves such a file out of the plan and returns it with the reason, and each one goes through handleRestoreFileError like any other failed file: skipped and counted under --skip-errors, fatal without it. The fatal error now suggests --skip-errors, as other restore failures do. The skip-errors tests now share one backup helper; the new case removes a blob from the snapshot metadata and exports it again. Model: opus-5-5 --- internal/vaultik/restore.go | 13 +- internal/vaultik/restore_malformed_db_test.go | 10 +- internal/vaultik/restore_plan.go | 25 ++-- internal/vaultik/restore_skip_errors_test.go | 119 +++++++++++++++--- 4 files changed, 138 insertions(+), 29 deletions(-) diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index c5843e8..08e71c2 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -309,11 +309,22 @@ func (v *Vaultik) restoreAllFiles( return nil, err } - plan, err := newRestorePlan(v.ctx, repos, files, chunkToBlobMap, blobIDToHash) + plan, unplanned, err := newRestorePlan( + v.ctx, repos, files, chunkToBlobMap, blobIDToHash) if err != nil { return nil, fmt.Errorf("building restore plan: %w", err) } + // Ranging over files rather than the map reports them in a stable order. + for _, file := range files { + if planErr, ok := unplanned[file.ID]; ok { + err = v.handleRestoreFileError(plan, opts, result, file, file.ID, planErr) + if err != nil { + return nil, err + } + } + } + filesByID, totalBytesExpected := indexRestoreFiles(files) v.UI.Beginf("Restoring %s files (%s) to %s.", diff --git a/internal/vaultik/restore_malformed_db_test.go b/internal/vaultik/restore_malformed_db_test.go index b6c884d..661d18b 100644 --- a/internal/vaultik/restore_malformed_db_test.go +++ b/internal/vaultik/restore_malformed_db_test.go @@ -61,8 +61,8 @@ func craftedFile( } // TestRestoreShortChunkHashInNoBlob proves a file whose short chunk hash -// has no blob_chunks row fails restore planning and the chunk write with -// an error. +// has no blob_chunks row is left out of the restore plan with an error, +// and fails the chunk write with an error. func TestRestoreShortChunkHashInNoBlob(t *testing.T) { t.Parallel() @@ -77,9 +77,11 @@ func TestRestoreShortChunkHashInNoBlob(t *testing.T) { chunkToBlobMap, err := v.buildChunkToBlobMap(ctx, repos) require.NoError(t, err) - _, err = newRestorePlan(ctx, repos, []*database.File{file}, + plan, unplanned, err := newRestorePlan(ctx, repos, []*database.File{file}, chunkToBlobMap, map[string]string{}) - require.ErrorIs(t, err, errPlanChunkMissing) + require.NoError(t, err) + require.ErrorIs(t, unplanned[file.ID], errPlanChunkMissing) + require.False(t, plan.hasPending()) fileChunks, err := repos.FileChunks.GetByFileID(ctx, file.ID) require.NoError(t, err) diff --git a/internal/vaultik/restore_plan.go b/internal/vaultik/restore_plan.go index c018b79..2615c52 100644 --- a/internal/vaultik/restore_plan.go +++ b/internal/vaultik/restore_plan.go @@ -41,20 +41,25 @@ type restorePlan struct { // newRestorePlan builds the file→blob index for the given files. Files // whose chunks reference no blobs (symlinks, directories) start in the -// ready queue immediately. +// ready queue immediately. A file with a chunk that no blob holds cannot +// be restored: it is left out of the plan and returned, by ID, with the +// reason. func newRestorePlan( ctx context.Context, repos *database.Repositories, files []*database.File, chunkToBlobMap map[string]*database.BlobChunk, blobIDToHash map[string]string, -) (*restorePlan, error) { +) (*restorePlan, map[types.FileID]error, error) { p := &restorePlan{ fileBlobs: make(map[types.FileID]map[string]struct{}, len(files)), blobFiles: make(map[string]map[types.FileID]struct{}), ready: make([]types.FileID, 0, len(files)), cached: make(map[string]struct{}), } + unplanned := make(map[types.FileID]error) + +nextFile: for _, f := range files { if f.IsSymlink() || f.Mode&uint32(os.ModeDir) != 0 { // No chunks to fetch — restore can run immediately. @@ -66,7 +71,7 @@ func newRestorePlan( fileChunks, err := repos.FileChunks.GetByFileID(ctx, f.ID) if err != nil { - return nil, fmt.Errorf("planning %s: %w", f.Path, err) + return nil, nil, fmt.Errorf("planning %s: %w", f.Path, err) } blobs := make(map[string]struct{}) @@ -74,14 +79,18 @@ func newRestorePlan( for _, fc := range fileChunks { bc, ok := chunkToBlobMap[fc.ChunkHash.String()] if !ok { - return nil, fmt.Errorf("planning %s: %w: %s", - f.Path, errPlanChunkMissing, shortHash(fc.ChunkHash.String())) + unplanned[f.ID] = fmt.Errorf("%w: %s", + errPlanChunkMissing, shortHash(fc.ChunkHash.String())) + + continue nextFile } hash, ok := blobIDToHash[bc.BlobID.String()] if !ok { - return nil, fmt.Errorf("planning %s: %w: %s", - f.Path, errPlanBlobIDMissing, bc.BlobID) + unplanned[f.ID] = fmt.Errorf("%w: %s", + errPlanBlobIDMissing, bc.BlobID) + + continue nextFile } blobs[hash] = struct{}{} @@ -103,7 +112,7 @@ func newRestorePlan( } } - return p, nil + return p, unplanned, nil } // markBlobCached records that the named blob is now resident in the diff --git a/internal/vaultik/restore_skip_errors_test.go b/internal/vaultik/restore_skip_errors_test.go index 7cbfeff..c74b691 100644 --- a/internal/vaultik/restore_skip_errors_test.go +++ b/internal/vaultik/restore_skip_errors_test.go @@ -28,7 +28,8 @@ const ( ) // missingBlobBackup is a snapshot of single-chunk files spread over two -// blobs, with one of those blobs deleted from the store. +// blobs, with one of those blobs lost: deleted from the store, or missing +// from the snapshot metadata. type missingBlobBackup struct { fs afero.Fs cfg *config.Config @@ -37,20 +38,39 @@ type missingBlobBackup struct { restoreDir string // files holds the original content by source path. files map[string][]byte - // lost holds the source paths whose chunk is in the deleted blob. + // lost holds the source paths whose chunk is in the lost blob. lost map[string]bool } // TestRestoreSkipErrorsSkipsFilesOfMissingBlob restores with SkipErrors -// after one blob of a two-blob snapshot was deleted. Every file stored in -// that blob must be reported as failed and left absent, every other file -// must be restored intact, and Restore must still return an error. +// after one blob of a two-blob snapshot was deleted from the store. func TestRestoreSkipErrorsSkipsFilesOfMissingBlob(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() ctx := context.Background() - backup := backupThenDeleteOneBlob(ctx, t) + assertRestoreSkipsLostFiles(ctx, t, backupThenDeleteOneBlob(ctx, t)) +} + +// TestRestoreSkipErrorsSkipsFilesWithChunkInNoBlob restores with +// SkipErrors a snapshot whose metadata lists chunks that no blob holds, as +// earlier backup defects left behind. +func TestRestoreSkipErrorsSkipsFilesWithChunkInNoBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + assertRestoreSkipsLostFiles(ctx, t, backupThenDropOneBlobFromMetadata(ctx, t)) +} + +// assertRestoreSkipsLostFiles restores backup with SkipErrors. Every file +// stored in the lost blob must be reported as failed and left absent, +// every other file must be restored intact, and Restore must still return +// an error. +func assertRestoreSkipsLostFiles( + ctx context.Context, t *testing.T, backup *missingBlobBackup, +) { + t.Helper() var out bytes.Buffer @@ -72,14 +92,14 @@ func TestRestoreSkipErrorsSkipsFilesOfMissingBlob(t *testing.T) { if backup.lost[path] { assert.Containsf(t, out.String(), path, - "%s needs the deleted blob and must be reported", path) + "%s needs the lost blob and must be reported", path) assert.NoFileExists(t, restored) continue } got, err := afero.ReadFile(backup.fs, restored) - require.NoErrorf(t, err, "%s does not need the deleted blob", path) + require.NoErrorf(t, err, "%s does not need the lost blob", path) assert.Equalf(t, content, got, "%s restored with wrong content", path) } } @@ -103,6 +123,30 @@ func TestRestoreMissingBlobAbortsWithoutSkipErrors(t *testing.T) { require.ErrorIs(t, err, storage.ErrNotFound) } +// TestRestoreChunkInNoBlobAbortsWithoutSkipErrors checks that a chunk held +// by no blob still ends the restore, before any file is written, when +// SkipErrors is not set. +func TestRestoreChunkInNoBlobAbortsWithoutSkipErrors(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + backup := backupThenDropOneBlobFromMetadata(ctx, t) + + v := newReaderVaultik(ctx, backup.cfg, backup.storer, nil, backup.fs) + + err := v.Restore(&vaultik.RestoreOptions{ + SnapshotID: backup.snapshotID, + TargetDir: backup.restoreDir, + }) + + require.ErrorContains(t, err, "chunk missing from blob map") + + for path := range backup.files { + assert.NoFileExists(t, filepath.Join(backup.restoreDir, path)) + } +} + // backupThenDeleteOneBlob backs up missingBlobFileCount single-chunk // files, then deletes from the store the blob holding the first of them. func backupThenDeleteOneBlob( @@ -110,6 +154,54 @@ func backupThenDeleteOneBlob( ) *missingBlobBackup { t.Helper() + backup, db, lostBlob := backupSingleChunkFiles(ctx, t) + require.NoError(t, db.Close()) + + require.NoError(t, backup.storer.Delete(ctx, fmt.Sprintf( + "blobs/%s/%s/%s", lostBlob[:2], lostBlob[2:4], lostBlob))) + + return backup +} + +// backupThenDropOneBlobFromMetadata backs up missingBlobFileCount +// single-chunk files, then removes the blob holding the first of them from +// the snapshot and exports the snapshot metadata again. The exported +// metadata then lists chunks that no blob holds. +func backupThenDropOneBlobFromMetadata( + ctx context.Context, t *testing.T, +) *missingBlobBackup { + t.Helper() + + backup, db, lostBlob := backupSingleChunkFiles(ctx, t) + + // The uploads row refers to the blob row, so it would keep the export + // from deleting it. + for _, query := range []string{ + "DELETE FROM snapshot_blobs WHERE blob_hash = ?", + "DELETE FROM uploads WHERE blob_hash = ?", + } { + _, err := db.Conn().ExecContext(ctx, query, lostBlob) + require.NoError(t, err) + } + + sm := newFaultSnapshotManager( + backup.fs, backup.storer, backup.cfg, database.NewRepositories(db)) + require.NoError(t, + sm.ExportSnapshotMetadata(ctx, db.Path(), backup.snapshotID)) + require.NoError(t, db.Close()) + + return backup +} + +// backupSingleChunkFiles backs up missingBlobFileCount single-chunk files. +// It returns the backup, with lost naming the files stored in the same +// blob as the first of them, the still open local index, and the hash of +// that blob. +func backupSingleChunkFiles( + ctx context.Context, t *testing.T, +) (*missingBlobBackup, *database.DB, string) { + t.Helper() + fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") @@ -143,16 +235,11 @@ func backupThenDeleteOneBlob( blobOfFile[path] = blobHashOfSingleChunkFile(ctx, t, repos, path) } - require.NoError(t, db.Close()) - - deleted := blobOfFile[filepath.Join(dataDir, "file-00.bin")] - require.NoError(t, storer.Delete(ctx, fmt.Sprintf( - "blobs/%s/%s/%s", deleted[:2], deleted[2:4], deleted))) - + lostBlob := blobOfFile[filepath.Join(dataDir, "file-00.bin")] lost := make(map[string]bool) for path, hash := range blobOfFile { - if hash == deleted { + if hash == lostBlob { lost[path] = true } } @@ -168,7 +255,7 @@ func backupThenDeleteOneBlob( restoreDir: filepath.Join(tempDir, "restored"), files: files, lost: lost, - } + }, db, lostBlob } // blobHashOfSingleChunkFile returns the hash of the blob holding the one From 4193ced1f6148e3bce8d9b969ded8fac71855f5a Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 18:50:48 +0200 Subject: [PATCH 057/121] Report blobs shallow verify could not check apart from missing ones (closes #318) Shallow snapshot verify counted every error from checking a blob or the encrypted database as "missing" and printed the error nowhere, so a permission error or an S3 403 read as data loss. Now only a not-found answer from storage counts as missing. Any other error is reported as could not be checked, with the error storage returned, in the text report and under --json (the new unchecked list and database_check_error field), and the run fails. Under --quiet, which drops the report, each of those errors is logged as a warning on stderr. The database check moved into its own small function because the verify function was at the linter's length limit. Model: opus-5-5 --- .../vaultik/destination_validation_test.go | 3 +- internal/vaultik/shallow_verify_test.go | 223 ++++++++++++++++++ internal/vaultik/snapshot.go | 91 +++++-- internal/vaultik/verify.go | 18 +- 4 files changed, 311 insertions(+), 24 deletions(-) diff --git a/internal/vaultik/destination_validation_test.go b/internal/vaultik/destination_validation_test.go index 4a083bf..9bc7d58 100644 --- a/internal/vaultik/destination_validation_test.go +++ b/internal/vaultik/destination_validation_test.go @@ -161,13 +161,14 @@ func TestVerifyManifestBlobsRejectsShortHash(t *testing.T) { Blobs: []snapshot.BlobInfo{{Hash: "abc", CompressedSize: 1}}, } - verified, missing, mismatched, missingSize, err := + verified, missing, mismatched, missingSize, unchecked, err := v.verifyManifestBlobs(manifest, &VerifyOptions{JSON: true}) require.ErrorIs(t, err, errInvalidBlobHash) require.Zero(t, verified) require.Zero(t, missing) require.Zero(t, mismatched) require.Zero(t, missingSize) + require.Empty(t, unchecked) } // TestVerifyBlobChunksRejectsNegativeLength proves a blob_chunks row with a diff --git a/internal/vaultik/shallow_verify_test.go b/internal/vaultik/shallow_verify_test.go index e4b56fd..3633cf6 100644 --- a/internal/vaultik/shallow_verify_test.go +++ b/internal/vaultik/shallow_verify_test.go @@ -4,15 +4,20 @@ import ( "bytes" "context" "encoding/json" + "errors" + "fmt" "io" "os" + "path" "path/filepath" + "slices" "testing" "github.com/spf13/afero" "github.com/stretchr/testify/require" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/storage" "sneak.berlin/go/vaultik/internal/ui" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -151,6 +156,224 @@ func TestShallowVerifyDetectsMissingDatabase(t *testing.T) { "shallow verify must fail when db.zst.age is absent") } +// errStatDenied stands in for any storage error other than not-found: a +// permission error, an S3 403, a dropped connection. +var errStatDenied = errors.New("injected stat failure") + +// statFailingStorer fails Stat with errStatDenied for the keys in +// failKeys and passes every other call to the wrapped Storer. +type statFailingStorer struct { + storage.Storer + + failKeys []string +} + +func (s statFailingStorer) Stat( + ctx context.Context, key string, +) (*storage.ObjectInfo, error) { + if slices.Contains(s.failKeys, key) { + return nil, fmt.Errorf("stat %q: %w", key, errStatDenied) + } + + return s.Storer.Stat(ctx, key) +} + +// TestShallowVerifyReportsStatErrorsApartFromMissing backs up a real +// snapshot, deletes one blob, and makes storage fail Stat with an error +// other than not-found for a second blob and for the encrypted database. +// Only the deleted blob may be counted as missing. The second blob and +// the database must be reported as could not be checked, with the error +// storage returned, and verify must fail, in the text output and under +// --json. +func TestShallowVerifyReportsStatErrorsApartFromMissing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + storeDir := filepath.Join(tempDir, "remote") + dbPath := filepath.Join(tempDir, "index.sqlite") + + chunkSize := int64(32 * 1024) + maxBlobSize := int64(128 * 1024) + + // Random content, so the snapshot spans several blobs. + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + appendRandomBytes(t, fs, map[string][]byte{}, + filepath.Join(dataDir, "data.bin"), maxBlobSize*4) + + ctx := context.Background() + + cfg, storer, snapshotID := runFileStorageBackup( + ctx, t, fs, dataDir, storeDir, dbPath, chunkSize, maxBlobSize) + + blobKeys := storedBlobKeys(t, storeDir) + require.GreaterOrEqual(t, len(blobKeys), 2, "expected at least two blobs") + + missingKey, uncheckedKey := blobKeys[0], blobKeys[1] + missingHash, uncheckedHash := path.Base(missingKey), path.Base(uncheckedKey) + + require.NoError(t, os.Remove(filepath.Join(storeDir, missingKey))) + + dbKey := "metadata/" + snapshot.RemoteSnapshotKey(snapshotID) + "/db.zst.age" + failing := statFailingStorer{ + Storer: storer, + failKeys: []string{uncheckedKey, dbKey}, + } + + newVerifier := func(out io.Writer) *vaultik.Vaultik { + v := &vaultik.Vaultik{ + Config: cfg, + Storage: failing, + Fs: fs, + Stdout: out, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + v.SetContext(ctx) + + return v + } + + var out bytes.Buffer + + err := newVerifier(&out).VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{JSON: true}) + require.Error(t, err) + + result := decodeVerifyResult(t, out.Bytes()) + require.Equal(t, "failed", result.Status) + require.Equal(t, 1, result.Missing, "only the deleted blob is missing") + require.Equal(t, result.BlobCount-2, result.Verified) + require.Len(t, result.Unchecked, 1) + require.Equal(t, uncheckedHash, result.Unchecked[0].Hash) + require.Contains(t, result.Unchecked[0].Error, errStatDenied.Error()) + require.False(t, result.DatabaseMissing, + "a database that could not be checked is not missing") + require.Contains(t, result.DatabaseCheckError, errStatDenied.Error()) + + out.Reset() + err = newVerifier(&out).VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{}) + require.Error(t, err) + + text := out.String() + require.Contains(t, text, "Missing: "+missingHash) + require.NotContains(t, text, "Missing: "+uncheckedHash) + require.Contains(t, text, "Could not check: "+uncheckedHash) + require.Contains(t, text, "Encrypted database: could not be checked") + require.Contains(t, text, errStatDenied.Error()) + require.Contains(t, text, "FAILED") +} + +// TestShallowVerifyQuietFailsOnStatErrorAlone backs up a healthy snapshot, +// then makes storage fail Stat, with an error other than not-found, for +// one blob alone and then for the encrypted database alone. Each run must +// fail verify, and under --quiet, which drops the report, the error +// storage returned must still reach stderr. +// +//nolint:paralleltest // captureProcessStderr replaces os.Stderr +func TestShallowVerifyQuietFailsOnStatErrorAlone(t *testing.T) { + log.Initialize(log.Config{}) + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + storeDir := filepath.Join(tempDir, "remote") + dbPath := filepath.Join(tempDir, "index.sqlite") + + chunkSize := int64(32 * 1024) + maxBlobSize := int64(128 * 1024) + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, "data.bin"), + bytesPattern("shallow-quiet-", int(maxBlobSize*2)), 0o644)) + + ctx := context.Background() + + cfg, storer, snapshotID := runFileStorageBackup( + ctx, t, fs, dataDir, storeDir, dbPath, chunkSize, maxBlobSize) + + newQuietVerifier := func(s storage.Storer) *vaultik.Vaultik { + v := &vaultik.Vaultik{ + Config: cfg, + Storage: s, + Fs: fs, + Stdout: io.Discard, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + v.SetContext(ctx) + v.UI.SetQuiet(true) + + return v + } + + require.NoError(t, + newQuietVerifier(storer).VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{}), + "shallow verify should pass on a healthy snapshot") + + blobKeys := storedBlobKeys(t, storeDir) + require.NotEmpty(t, blobKeys) + + dbKey := "metadata/" + snapshot.RemoteSnapshotKey(snapshotID) + "/db.zst.age" + + for _, failKey := range []string{blobKeys[0], dbKey} { + v := newQuietVerifier(statFailingStorer{ + Storer: storer, + failKeys: []string{failKey}, + }) + + var err error + + stderr := captureProcessStderr(t, func() { + err = v.VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{}) + }) + + require.Error(t, err, + "verify must fail when %s could not be checked", failKey) + require.Contains(t, stderr, errStatDenied.Error(), + "under --quiet the error for %s must still reach stderr", failKey) + } +} + +// storedBlobKeys returns the storage key of every blob file under +// storeDir, sorted. +func storedBlobKeys(t *testing.T, storeDir string) []string { + t.Helper() + + var keys []string + + err := filepath.Walk(filepath.Join(storeDir, "blobs"), + func(p string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + if info.IsDir() { + return nil + } + + rel, err := filepath.Rel(storeDir, p) + if err != nil { + return err + } + + keys = append(keys, filepath.ToSlash(rel)) + + return nil + }) + require.NoError(t, err) + + return keys +} + // growOneBlob appends bytes to the first blob file found under blobsDir, // changing its on-disk size so it no longer matches the manifest. func growOneBlob(t *testing.T, fs afero.Fs, blobsDir string) { diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 17bb5ea..d5bdb19 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -14,6 +14,7 @@ import ( "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/storage" "sneak.berlin/go/vaultik/internal/types" ) @@ -777,18 +778,10 @@ func (v *Vaultik) VerifySnapshotWithOptions( v.stdoutf("Checking blob presence and sizes...\n") } - // A snapshot is only restorable if its encrypted database is present - // alongside the blobs. Shallow verify checks that the object exists; it - // does not decrypt it (that is deep verify's job). - dbPath := fmt.Sprintf("metadata/%s/db.zst.age", remoteKey) + v.checkSnapshotDatabase(remoteKey, result) - _, dbErr := v.Storage.Stat(v.ctx, dbPath) - if dbErr != nil { - result.DatabaseMissing = true - } - - result.Verified, result.Missing, result.Mismatched, result.MissingSize, err = - v.verifyManifestBlobs(manifest, opts) + result.Verified, result.Missing, result.Mismatched, result.MissingSize, + result.Unchecked, err = v.verifyManifestBlobs(manifest, opts) if err != nil { if opts.JSON { result.Status = verifyStatusFailed @@ -825,25 +818,46 @@ func (v *Vaultik) printVerifyHeader(snapshotID string, opts *VerifyOptions) { } } +// checkSnapshotDatabase records in result whether the snapshot's +// encrypted database is missing or could not be checked. A snapshot is +// only restorable if its database is present alongside the blobs. +// Shallow verify checks that the object exists; it does not decrypt it +// (that is deep verify's job). +func (v *Vaultik) checkSnapshotDatabase(remoteKey string, result *VerifyResult) { + dbPath := fmt.Sprintf("metadata/%s/db.zst.age", remoteKey) + + _, err := v.Storage.Stat(v.ctx, dbPath) + + switch { + case errors.Is(err, storage.ErrNotFound): + result.DatabaseMissing = true + case err != nil: + result.DatabaseCheckError = err.Error() + } +} + // verifyManifestBlobs checks that each blob in the manifest is present in // storage with the size the manifest records, returning the counts of // blobs that were present with the right size, absent, and present but the -// wrong size, plus the total bytes of the absent blobs. It does not read -// blob contents; deep verification (RunDeepVerify) does that. The size -// comparison matches the deep path (see verifyBlobExistenceFromDB). +// wrong size, the total bytes of the absent blobs, and the blobs it could +// not check because storage returned an error other than not-found. It +// does not read blob contents; deep verification (RunDeepVerify) does +// that. The size comparison matches the deep path (see +// verifyBlobExistenceFromDB). func (v *Vaultik) verifyManifestBlobs( manifest *snapshot.Manifest, opts *VerifyOptions, -) (int, int, int, int64, error) { +) (int, int, int, int64, []UncheckedBlob, error) { var ( verified, missing, mismatched int missingSize int64 + unchecked []UncheckedBlob ) for _, blob := range manifest.Blobs { // The manifest is unauthenticated, so its blob hashes are checked // before being spliced into a storage path. if !isBlobHash(blob.Hash) { - return 0, 0, 0, 0, fmt.Errorf("%w: %s", + return 0, 0, 0, 0, nil, fmt.Errorf("%w: %s", errInvalidBlobHash, shortHash(blob.Hash)) } @@ -852,7 +866,7 @@ func (v *Vaultik) verifyManifestBlobs( stat, err := v.Storage.Stat(v.ctx, blobPath) switch { - case err != nil: + case errors.Is(err, storage.ErrNotFound): if !opts.JSON && !v.UI.Quiet() { v.stdoutf(" Missing: %s (%s)\n", blob.Hash, ubytes(blob.CompressedSize)) @@ -860,6 +874,13 @@ func (v *Vaultik) verifyManifestBlobs( missing++ missingSize += blob.CompressedSize + case err != nil: + if !opts.JSON && !v.UI.Quiet() { + v.stdoutf(" Could not check: %s (%v)\n", blob.Hash, err) + } + + unchecked = append(unchecked, + UncheckedBlob{Hash: blob.Hash, Error: err.Error()}) case stat.Size != blob.CompressedSize: if !opts.JSON && !v.UI.Quiet() { v.stdoutf(" Wrong size: %s (store has %s, manifest lists %s)\n", @@ -872,7 +893,7 @@ func (v *Vaultik) verifyManifestBlobs( } } - return verified, missing, mismatched, missingSize, nil + return verified, missing, mismatched, missingSize, unchecked, nil } // formatVerifyResult outputs the final verification results as JSON or @@ -893,9 +914,19 @@ func (v *Vaultik) formatVerifyResult( return v.outputVerifyJSON(result) } - // Under --quiet a failure is still returned, and the cli layer - // prints it on stderr. - if !v.UI.Quiet() { + // --quiet drops the report but not the errors storage returned, which + // are logged on stderr. A failure is still returned either way, and + // the cli layer prints it on stderr. + if v.UI.Quiet() { + for _, blob := range result.Unchecked { + log.Warn("Could not check blob", "blob", blob.Hash, "error", blob.Error) + } + + if result.DatabaseCheckError != "" { + log.Warn("Could not check the encrypted database", + "snapshot", result.SnapshotID, "error", result.DatabaseCheckError) + } + } else { v.printVerifySummary(result, failure) } @@ -921,10 +952,19 @@ func (v *Vaultik) printVerifySummary(result *VerifyResult, failure string) { v.stdoutf(" Wrong size: %d blobs\n", result.Mismatched) } + if len(result.Unchecked) > 0 { + v.stdoutf(" Could not check: %d blobs\n", len(result.Unchecked)) + } + if result.DatabaseMissing { v.stdoutf(" Encrypted database: missing\n") } + if result.DatabaseCheckError != "" { + v.stdoutf(" Encrypted database: could not be checked (%s)\n", + result.DatabaseCheckError) + } + v.stdoutf(" Status: ") if failure != "" { @@ -952,10 +992,19 @@ func shallowVerifyFailure(result *VerifyResult) string { fmt.Sprintf("%d blobs have the wrong size", result.Mismatched)) } + if len(result.Unchecked) > 0 { + parts = append(parts, fmt.Sprintf("%d blobs could not be checked", + len(result.Unchecked))) + } + if result.DatabaseMissing { parts = append(parts, "the encrypted database is missing") } + if result.DatabaseCheckError != "" { + parts = append(parts, "the encrypted database could not be checked") + } + return strings.Join(parts, "; ") } diff --git a/internal/vaultik/verify.go b/internal/vaultik/verify.go index 070c47b..51d6f06 100644 --- a/internal/vaultik/verify.go +++ b/internal/vaultik/verify.go @@ -57,11 +57,25 @@ type VerifyResult struct { Missing int `json:"missing"` MissingSize int64 `json:"missing_size,omitempty"` Mismatched int `json:"mismatched,omitempty"` + // Unchecked lists the blobs shallow verify could not check, because + // storage answered with an error other than not-found, so whether + // they are present is unknown. + Unchecked []UncheckedBlob `json:"unchecked,omitempty"` // DatabaseMissing is set by shallow verify when the snapshot's // encrypted database (metadata//db.zst.age) is absent, which // makes the snapshot unrestorable regardless of the blobs. - DatabaseMissing bool `json:"database_missing,omitempty"` - ErrorMessage string `json:"error,omitempty"` + DatabaseMissing bool `json:"database_missing,omitempty"` + // DatabaseCheckError is set by shallow verify to the error storage + // returned when the encrypted database could not be checked. + DatabaseCheckError string `json:"database_check_error,omitempty"` + ErrorMessage string `json:"error,omitempty"` +} + +// UncheckedBlob is a blob shallow verify could not check, with the error +// storage returned for it. +type UncheckedBlob struct { + Hash string `json:"hash"` + Error string `json:"error"` } // deepVerifyFailure records a failure in the result and returns it appropriately From 27e9798da5aec721d374edaf68b3064854ef04c7 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 19:25:49 +0200 Subject: [PATCH 058/121] Make an S3 listing the server cuts short an error (closes #297) The SDK paginator takes a listing page marked truncated but carrying no continuation token for the last page and stops without an error. A server answering V2 listings V1-style sends such pages, so ListObjects and ListObjectsStream returned the first page as the whole listing, and prune treated the blobs of the snapshots on later pages as unreferenced. Both now fetch each page through nextListPage, which returns ErrNoContinuationToken for such a page; prune, snapshot list and remote nuke already handle a listing error. The test serves a fixed reply from a stub server, since gofakes3 always sends the token. Model: opus-5-5 --- internal/s3/client.go | 31 ++++++++++++++-- internal/storage/s3_test.go | 72 +++++++++++++++++++++++++++++++++++-- 2 files changed, 98 insertions(+), 5 deletions(-) diff --git a/internal/s3/client.go b/internal/s3/client.go index f5fc91c..0867a8a 100644 --- a/internal/s3/client.go +++ b/internal/s3/client.go @@ -18,6 +18,13 @@ import ( "github.com/aws/smithy-go/logging" ) +// ErrNoContinuationToken is returned by ListObjects and ListObjectsStream +// when the server marks a page of a listing truncated but sends no +// continuation token to fetch the rest with, as a server answering V2 +// listings V1-style does. +var ErrNoContinuationToken = errors.New( + "server marked the listing truncated but sent no continuation token") + // Client wraps the AWS S3 client for vaultik operations. // It provides a simplified interface for S3 operations with automatic // prefix handling and connection management. All operations are performed @@ -214,7 +221,7 @@ func (c *Client) ListObjects(ctx context.Context, prefix string) ([]string, erro }) for paginator.HasMorePages() { - page, err := paginator.NextPage(ctx) + page, err := nextListPage(ctx, paginator) if err != nil { return nil, err } @@ -235,6 +242,26 @@ func (c *Client) ListObjects(ctx context.Context, prefix string) ([]string, erro return keys, nil } +// nextListPage fetches the next page of a listing. The SDK paginator takes +// a page marked truncated without a continuation token for the last page +// and stops without an error, so such a page is ErrNoContinuationToken +// here instead. +func nextListPage( + ctx context.Context, paginator *s3.ListObjectsV2Paginator, +) (*s3.ListObjectsV2Output, error) { + page, err := paginator.NextPage(ctx) + if err != nil { + return nil, err + } + + truncated := aws.ToBool(page.IsTruncated) + if truncated && aws.ToString(page.NextContinuationToken) == "" { + return nil, ErrNoContinuationToken + } + + return page, nil +} + // HeadObject checks if an object exists in S3. // Returns true if the object exists, false otherwise. // The key is automatically prefixed with the configured prefix. @@ -300,7 +327,7 @@ func (c *Client) ListObjectsStream( }) for paginator.HasMorePages() { - page, err := paginator.NextPage(ctx) + page, err := nextListPage(ctx, paginator) if err != nil { ch <- ObjectInfo{Err: err} diff --git a/internal/storage/s3_test.go b/internal/storage/s3_test.go index 2434eb5..df16200 100644 --- a/internal/storage/s3_test.go +++ b/internal/storage/s3_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "io" "net/http" "net/http/httptest" "slices" @@ -22,13 +23,16 @@ import ( // s3TestBucket is the bucket created for each in-process S3 server. const s3TestBucket = "test-bucket" -// Credentials for the tests that build a storer from a config.Config. The -// in-process S3 server accepts any. +// Credentials for the tests' S3 clients. The test servers accept any. const ( s3TestAccessKeyID = "key" s3TestSecretAccessKey = "secret" ) +// s3TestRegion is the region of the S3 clients built here with +// s3.NewClient. The test servers ignore it. +const s3TestRegion = "us-east-1" + // newS3Storer builds an s3:// backend backed by a fresh in-process // S3 server. It reuses the same in-memory S3 harness (gofakes3 + s3mem // over httptest) that internal/s3 and the not-found regression test use, @@ -55,7 +59,7 @@ func newS3Storer(t *testing.T) storage.Storer { Bucket: s3TestBucket, AccessKeyID: "test", SecretAccessKey: "test", - Region: "us-east-1", + Region: s3TestRegion, }) if err != nil { t.Fatalf("new client: %v", err) @@ -93,6 +97,68 @@ func TestS3StorerMissingKeyMapsToErrNotFound(t *testing.T) { } } +// TestS3ListingCutShortIsAnError checks that List and ListStream fail on a +// listing page marked truncated that carries no continuation token, as a +// server answering V2 listings V1-style sends it. Taken as the last page, +// it would hide every later key, and prune would treat the blobs of the +// snapshots listed there as unreferenced. +func TestS3ListingCutShortIsAnError(t *testing.T) { + t.Parallel() + + const ( + prefix = "metadata/" + truncatedPage = ` + + test-bucket + metadata/ + 1 + 1 + true + + metadata/snap/manifest.json.zst + 8 + +` + ) + + srv := httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, truncatedPage) + })) + t.Cleanup(srv.Close) + + client, err := s3.NewClient(context.Background(), s3.Config{ + Endpoint: srv.URL, + Bucket: s3TestBucket, + AccessKeyID: s3TestAccessKeyID, + SecretAccessKey: s3TestSecretAccessKey, + Region: s3TestRegion, + }) + if err != nil { + t.Fatalf("new client: %v", err) + } + + storer := storage.NewS3Storer(client) + ctx := context.Background() + + keys, err := storer.List(ctx, prefix) + if !errors.Is(err, s3.ErrNoContinuationToken) { + t.Errorf("List = %q, %v; want ErrNoContinuationToken", keys, err) + } + + var streamErr error + + for obj := range storer.ListStream(ctx, prefix) { + if obj.Err != nil { + streamErr = obj.Err + } + } + + if !errors.Is(streamErr, s3.ErrNoContinuationToken) { + t.Errorf("ListStream error = %v, want ErrNoContinuationToken", streamErr) + } +} + // TestS3URLPrefixKeyLayout pins the bucket keys an s3:// URL reads and // writes: the README's remote storage layout, with the prefix joined to // each key by one "/". s3://b/p and s3://b/p/ must be the same From 740f474c59c6e833d2bb3200032152e2a264073c Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 19:29:52 +0200 Subject: [PATCH 059/121] Make prune and remote nuke fail when a delete fails (closes #290) prune, and the prune step of snapshot create --prune, counted a blob it could not delete and still exited 0. It now prints its summary or --json document and then returns an error, which replaces the "Failed to delete N blob(s)" line. remote nuke only warned when a snapshot's metadata could not be deleted, advised vaultik prune, which never removes metadata, and then reported the store empty. It now stops with an error, does not report the store empty, and says to run vaultik remote nuke --force again. It checks that the local index belongs to the configured destination before deleting anything, and that error carries no such advice. A successful nuke no longer advises prune. Model: opus-5-5 --- README.md | 9 +- internal/storage/faultstore/faultstore.go | 32 ++++-- internal/vaultik/nuke_remote_test.go | 82 +++++++++++++++- internal/vaultik/prune.go | 46 +++++++-- internal/vaultik/prune_delete_failure_test.go | 98 +++++++++++++++++++ internal/vaultik/remove_snapshot_test.go | 3 +- internal/vaultik/snapshot.go | 38 ++++--- 7 files changed, 267 insertions(+), 41 deletions(-) create mode 100644 internal/vaultik/prune_delete_failure_test.go diff --git a/README.md b/README.md index f4c5f61..471501e 100644 --- a/README.md +++ b/README.md @@ -386,10 +386,12 @@ manifest on the destination store to compute the still-referenced blob set and delete any blob not in that set. Step (3) reads all remote manifests — network cost scales with the number of snapshots. `snapshot create --prune` runs the same cleanup automatically; this is the -manual entry point for the same work. +manual entry point for the same work. If a blob cannot be deleted, the +command (and `snapshot create --prune`) exits non-zero. * `--force`: Skip confirmation prompt * `--json`: Output stats as JSON. Also skips the confirmation prompt, as - `--force` does. + `--force` does. A blob that cannot be deleted is counted in + `blobs_failed`, and the document is printed before the non-zero exit. **`info`**: Display system configuration, storage settings, encryption recipients, and local database statistics. @@ -411,7 +413,8 @@ since `prune` never deletes it. **`remote nuke`**: Delete every snapshot's metadata and every blob from the backup destination store, leaving the bucket prefix empty. Destructive and irreversible. This is the single supported way to wipe the entire -destination store. +destination store. If anything cannot be deleted, the command exits +non-zero; running it again deletes what is left. * `--force`: Required to confirm destruction. **`database delete`**: Delete the local SQLite state database file diff --git a/internal/storage/faultstore/faultstore.go b/internal/storage/faultstore/faultstore.go index ae5d889..bdc4dc3 100644 --- a/internal/storage/faultstore/faultstore.go +++ b/internal/storage/faultstore/faultstore.go @@ -1,15 +1,16 @@ // Package faultstore provides a storage.Storer wrapper that injects // faults on demand, so tests can reproduce the failure modes a real // backend exhibits: an upload that fails partway, a backend that reports -// success while storing nothing, and reads that return corrupt or -// truncated bytes. It is the seam called for by the fault-injection -// tests (sneak/vaultik issue 72) and is meant to be reused by future -// tests rather than re-implemented per case. +// success while storing nothing, reads that return corrupt or truncated +// bytes, and a delete the backend refuses. It is the seam called for by +// the fault-injection tests (sneak/vaultik issue 72) and is meant to be +// reused by future tests rather than re-implemented per case. // -// The wrapper delegates every method to the inner Storer. Two hooks -// change that: OnPut decides the fate of each write, and OnGet decides -// how each read's bytes are returned. Both are keyed by the object key, -// so a test can fault only blobs, only metadata, or a single object. +// The wrapper delegates every method to the inner Storer. Three hooks +// change that: OnPut decides the fate of each write, OnGet decides how +// each read's bytes are returned, and OnDelete decides whether each +// delete fails. All are keyed by the object key, so a test can fault +// only blobs, only metadata, or a single object. package faultstore import ( @@ -25,6 +26,10 @@ import ( // ErrInjectedUpload is returned by a Put the OnPut hook chose to fail. var ErrInjectedUpload = errors.New("faultstore: injected upload failure") +// ErrInjectedDelete is returned by a Delete the OnDelete hook chose to +// fail. +var ErrInjectedDelete = errors.New("faultstore: injected delete failure") + // PutAction is the disposition OnPut assigns to a write. type PutAction int @@ -66,6 +71,11 @@ type Storer struct { // OnGet, when set, is consulted for every Get with the object key // and damages the returned bytes accordingly. OnGet func(key string) GetFault + + // OnDelete, when set, is consulted before every Delete with the + // object key. Returning true fails the delete and leaves the object + // in place. + OnDelete func(key string) bool } // New wraps inner. inner must be non-nil. @@ -154,8 +164,12 @@ func (f *Storer) Stat(ctx context.Context, key string) (*storage.ObjectInfo, err return f.inner.Stat(ctx, key) } -// Delete delegates unchanged. +// Delete removes the object unless OnDelete fails the delete. func (f *Storer) Delete(ctx context.Context, key string) error { + if f.OnDelete != nil && f.OnDelete(key) { + return fmt.Errorf("%w for %q", ErrInjectedDelete, key) + } + return f.inner.Delete(ctx, key) } diff --git a/internal/vaultik/nuke_remote_test.go b/internal/vaultik/nuke_remote_test.go index 6e22699..701b0a5 100644 --- a/internal/vaultik/nuke_remote_test.go +++ b/internal/vaultik/nuke_remote_test.go @@ -5,12 +5,14 @@ import ( "io/fs" "os" "path/filepath" + "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/storage/faultstore" ) // TestNukeRemoteLeavesNoFiles checks that remote nuke leaves no file @@ -23,7 +25,7 @@ func TestNukeRemoteLeavesNoFiles(t *testing.T) { ctx := context.Background() storeDir := filepath.Join(t.TempDir(), "store") - v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + v, repos, out := backUpToFileDestination(ctx, t, storeDir) snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) require.NoError(t, err) @@ -61,4 +63,82 @@ func TestNukeRemoteLeavesNoFiles(t *testing.T) { }) require.NoError(t, err) assert.Empty(t, files) + + // Nuke deletes the blobs itself, so advice to run prune is wrong. + assert.Contains(t, out.String(), "Backup destination store is now empty.") + assert.NotContains(t, out.String(), "vaultik prune") +} + +// TestNukeRemoteFailsWhenADeleteFails checks that remote nuke returns an +// error when a snapshot's metadata or a blob cannot be deleted, does not +// report the store empty, and advises running nuke again: prune deletes +// no metadata. +func TestNukeRemoteFailsWhenADeleteFails(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + for _, refusedPrefix := range []string{"metadata/", "blobs/"} { + t.Run(refusedPrefix, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, out := backUpToFileDestination(ctx, t, storeDir) + + store := faultstore.New(v.Storage) + store.OnDelete = func(key string) bool { + return strings.HasPrefix(key, refusedPrefix) + } + v.Storage = store + + require.Error(t, v.NukeRemote(true)) + + assert.NotContains(t, out.String(), "now empty") + assert.Contains(t, out.String(), "vaultik remote nuke --force") + assert.NotContains(t, out.String(), "vaultik prune") + }) + } +} + +// TestNukeRemoteRefusesAnotherDestinationWithoutRetryAdvice checks that +// remote nuke, when the local index belongs to a different destination +// than the configured one, fails without advising to run nuke again: +// that run would fail the same way. +func TestNukeRemoteRefusesAnotherDestinationWithoutRetryAdvice(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, out := backUpToFileDestination(ctx, t, storeDir) + + v.Config.StorageURL = "file://" + filepath.Join(t.TempDir(), "elsewhere") + + err := v.NukeRemote(true) + + require.ErrorContains(t, err, "bound to a different backup destination") + assert.NotContains(t, out.String(), "vaultik remote nuke --force") +} + +// TestNukeRemoteFailsWhenALocalSnapshotCannotBeRemoved checks that a +// snapshot remote nuke cannot remove from the local index fails the +// run: nuke then leaves that snapshot's metadata on the destination +// store. +func TestNukeRemoteFailsWhenALocalSnapshotCannotBeRemoved(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, out := backUpToFileDestination(ctx, t, storeDir) + + _, err := v.DB.Conn().ExecContext(ctx, ` + CREATE TRIGGER refuse_snapshot_delete BEFORE DELETE ON snapshots + BEGIN SELECT RAISE(ABORT, 'simulated index error'); END`) + require.NoError(t, err) + + require.Error(t, v.NukeRemote(true)) + + assert.NotContains(t, out.String(), "now empty") + assert.Contains(t, out.String(), "vaultik remote nuke --force") } diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index 31949c9..7df20e1 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -19,6 +19,14 @@ type PruneOptions struct { var errNukeRequiresForce = errors.New( "nuke requires --force (this deletes ALL remote snapshots and blobs)") +// errBlobDeleteFailed reports unreferenced blobs prune could not delete. +var errBlobDeleteFailed = errors.New("blob(s) could not be deleted") + +// nukeCommandHint is the command suggested when a remote nuke could not +// delete everything: running it again deletes what is left, which +// `vaultik prune` does not do for snapshot metadata. +const nukeCommandHint = "vaultik remote nuke --force" + // metadataDirName is the top-level remote directory holding snapshot // metadata. const metadataDirName = "metadata" @@ -39,6 +47,29 @@ func (v *Vaultik) NukeRemote(force bool) error { return errNukeRequiresForce } + // Checked before anything is deleted: running nuke again would fail + // the same way, so the advice below must not follow this error. + err := v.EnsureStorageBinding() + if err != nil { + return err + } + + err = v.emptyDestinationStore() + if err != nil { + v.UI.Warningf("Run '%s' again to delete what is left on the "+ + "backup destination store.", nukeCommandHint) + + return err + } + + v.UI.Completef("Backup destination store is now empty.") + + return nil +} + +// emptyDestinationStore does the deleting for NukeRemote and stops at +// the first step that fails. +func (v *Vaultik) emptyDestinationStore() error { v.UI.Beginf("Removing all snapshot metadata from backup destination store.") _, err := v.RemoveAllSnapshots(&RemoveOptions{Force: true}) @@ -62,8 +93,6 @@ func (v *Vaultik) NukeRemote(force bool) error { } } - v.UI.Completef("Backup destination store is now empty.") - return nil } @@ -166,14 +195,17 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { v.deleteUnreferencedBlobs(unreferencedBlobs, allBlobs, result) if opts.JSON { - return v.outputPruneBlobsJSON(result) + err = v.outputPruneBlobsJSON(result) + if err != nil { + return err + } + } else { + v.stdoutf("\nDeleted %d blob(s) totaling %s\n", + result.BlobsDeleted, ubytes(result.BytesFreed)) } - v.stdoutf("\nDeleted %d blob(s) totaling %s\n", - result.BlobsDeleted, ubytes(result.BytesFreed)) - if result.BlobsFailed > 0 { - v.stdoutf("Failed to delete %d blob(s)\n", result.BlobsFailed) + return fmt.Errorf("%d %w", result.BlobsFailed, errBlobDeleteFailed) } return nil diff --git a/internal/vaultik/prune_delete_failure_test.go b/internal/vaultik/prune_delete_failure_test.go new file mode 100644 index 0000000..54fe788 --- /dev/null +++ b/internal/vaultik/prune_delete_failure_test.go @@ -0,0 +1,98 @@ +package vaultik_test + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// refuseBlobDeletes is an OnDelete hook that fails every blob delete. +func refuseBlobDeletes(key string) bool { + return strings.HasPrefix(key, "blobs/") +} + +// TestPruneBlobs_FailedDeleteReturnsError checks that prune returns an +// error, so the command exits non-zero, when an unreferenced blob cannot +// be deleted. +func TestPruneBlobs_FailedDeleteReturnsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + // The store holds no manifest, so nothing references this blob. + addBlob(t, env.store.testStorer, testBlobHashA) + + store := faultstore.New(env.store) + store.OnDelete = refuseBlobDeletes + env.v.Storage = store + + err := env.v.PruneBlobs(&vaultik.PruneOptions{Force: true}) + + require.ErrorContains(t, err, "1 blob(s) could not be deleted") +} + +// TestPruneBlobs_JSONFailedDeleteReturnsError checks that prune --json +// prints its document and then returns an error when an unreferenced +// blob cannot be deleted. +func TestPruneBlobs_JSONFailedDeleteReturnsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + addBlob(t, env.store.testStorer, testBlobHashA) + + store := faultstore.New(env.store) + store.OnDelete = refuseBlobDeletes + env.v.Storage = store + + err := env.v.PruneBlobs(&vaultik.PruneOptions{JSON: true}) + + require.Error(t, err, "prune must fail when a blob cannot be deleted") + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &result), + "stdout must hold the JSON document, got:\n%s", env.stdout.String()) + assert.Equal(t, 1, result.BlobsFailed) + assert.Equal(t, 0, result.BlobsDeleted) +} + +// TestCreateSnapshotPrune_FailedBlobDeleteReturnsError checks that the +// prune step of snapshot create --prune fails the run when an +// unreferenced blob cannot be deleted. +func TestCreateSnapshotPrune_FailedBlobDeleteReturnsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, _ := backUpToFileDestination(ctx, t, storeDir) + + // No snapshot references this blob, so the prune step deletes it. + orphan := filepath.Join(storeDir, "blobs", testBlobHashA[:2], + testBlobHashA[2:4], testBlobHashA) + require.NoError(t, os.MkdirAll(filepath.Dir(orphan), 0o750)) + require.NoError(t, os.WriteFile(orphan, []byte("orphan"), 0o600)) + + store := faultstore.New(v.Storage) + store.OnDelete = refuseBlobDeletes + v.Storage = store + + err := v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Cron: true, + Prune: true, + }) + + require.ErrorContains(t, err, "1 blob(s) could not be deleted") + assert.FileExists(t, orphan) +} diff --git a/internal/vaultik/remove_snapshot_test.go b/internal/vaultik/remove_snapshot_test.go index 076ccdd..7d85bea 100644 --- a/internal/vaultik/remove_snapshot_test.go +++ b/internal/vaultik/remove_snapshot_test.go @@ -476,7 +476,8 @@ func TestRemoveAllSnapshots_WithForce(t *testing.T) { out := tv.Stdout.String() assert.Contains(t, out, "Removed 2 snapshot(s)") assert.Contains(t, out, "Removed snapshot metadata from remote storage") - assert.Contains(t, out, "vaultik prune") + // Remote nuke, the only caller, deletes the blobs next itself. + assert.NotContains(t, out, "vaultik prune") } func TestRemoveAllSnapshots_DryRun(t *testing.T) { diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index d5bdb19..630e2ba 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -25,6 +25,7 @@ var ( errSnapshotVerifyFailed = errors.New("verification failed") errRemoveAllNeedsForce = errors.New("--all requires --force") errSnapshotNotFound = errors.New("snapshot not found") + errSnapshotRemoveFailed = errors.New("snapshot(s) could not be removed") errInvalidTableName = errors.New("invalid table name") errNoAgeRecipients = errors.New( "creating a snapshot needs at least one public key in " + @@ -1591,8 +1592,8 @@ func (v *Vaultik) handleRemoveAllDryRun( // executeRemoveAll deletes every local snapshot and, unless LocalOnly // is set, every corresponding remote metadata directory plus any -// orphan remote keys. Blobs are not touched; the printed prune-command -// hint is the next step. +// orphan remote keys. Blobs are not touched. It returns an error when +// any snapshot could not be removed. func (v *Vaultik) executeRemoveAll( localSnaps, orphanRemoteKeys []string, opts *RemoveOptions, ) (*RemoveResult, error) { @@ -1606,18 +1607,11 @@ func (v *Vaultik) executeRemoveAll( result := &RemoveResult{} - remoteErrors := v.removeAllLocalSnapshots(localSnaps, opts, result) + failures := v.removeAllLocalSnapshots(localSnaps, opts, result) if !opts.LocalOnly { - remoteErrors += v.removeAllOrphanRemotes(orphanRemoteKeys, result) - - if remoteErrors == 0 { - result.RemoteRemoved = true - } else if v.UI != nil { - v.UI.Warningf("Some remote metadata deletions failed. Run '%s' "+ - "once the remote is healthy to clean up unreferenced blobs.", - pruneCommandHint) - } + failures += v.removeAllOrphanRemotes(orphanRemoteKeys, result) + result.RemoteRemoved = failures == 0 } if v.SnapshotManager != nil { @@ -1627,6 +1621,10 @@ func (v *Vaultik) executeRemoveAll( } } + if failures > 0 { + return result, fmt.Errorf("%d %w", failures, errSnapshotRemoveFailed) + } + if opts.JSON { return result, v.outputRemoveJSON(result) } @@ -1635,9 +1633,6 @@ func (v *Vaultik) executeRemoveAll( if !opts.LocalOnly && result.RemoteRemoved { v.printlnStdout("Removed snapshot metadata from remote storage") - v.stdoutf("\nNote: Removed snapshots' blobs remain on the remote. "+ - "Run '%s' to delete any blobs no longer referenced by any "+ - "remaining remote snapshot.\n", pruneCommandHint) } return result, nil @@ -1680,12 +1675,13 @@ func (v *Vaultik) deleteIncompleteSnapshot(snapshotIDStr string, id any) bool { } // removeAllLocalSnapshots removes each known local snapshot (and, unless -// --local-only, its remote metadata), returning the number of remote -// deletion failures. +// --local-only, its remote metadata), returning the number of snapshots +// it could not remove. A snapshot left in the local index keeps its +// remote metadata too, since it is not an orphan remote key. func (v *Vaultik) removeAllLocalSnapshots( localSnaps []string, opts *RemoveOptions, result *RemoveResult, ) int { - remoteErrors := 0 + failures := 0 for _, snapshotID := range localSnaps { log.Info("Removing snapshot", "snapshot_id", snapshotID) @@ -1695,6 +1691,8 @@ func (v *Vaultik) removeAllLocalSnapshots( log.Error("Failed to remove from local database", "snapshot_id", snapshotID, "error", err) + failures++ + continue } @@ -1705,14 +1703,14 @@ func (v *Vaultik) removeAllLocalSnapshots( log.Warn("Failed to remove snapshot metadata from remote", "snapshot_id", snapshotID, "error", err) - remoteErrors++ + failures++ } } result.SnapshotsRemoved = append(result.SnapshotsRemoved, snapshotID) } - return remoteErrors + return failures } // removeAllOrphanRemotes deletes remote snapshot metadata that has no From dfa3bbc9e111648768126e3bb4a97fc263bad11a Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 19:36:43 +0200 Subject: [PATCH 060/121] Stop a stalled snapshot database read when restore or deep verify is interrupted (closes #356) Restore and deep verify read the snapshot database straight from storage rather than through FetchBlob, so the earlier fix for stalled blob reads did not cover it. A database read stalled on a slow USB stick or network share kept the operation from returning after Ctrl-C; the process then exited at the shutdown timeout and left the decrypted database in the temp directory. Both reads now wrap the storage reader in the close-on-cancel reader FetchBlob uses, so a cancel ends the stalled read and the temp directory is removed. The interrupt test now stalls either a blob or the snapshot database, for both commands. Limitation: a read stuck in the kernel that closing cannot interrupt, such as one on an unresponsive hard NFS mount, still cannot be stopped. Model: opus-5-5 --- internal/vaultik/restore.go | 2 + internal/vaultik/restore_interrupt_test.go | 134 ++++++++++++--------- internal/vaultik/verify.go | 2 + 3 files changed, 82 insertions(+), 56 deletions(-) diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index 08e71c2..96f4048 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -702,6 +702,8 @@ func (v *Vaultik) downloadSnapshotDB( return nil, "", fmt.Errorf("downloading %s: %w", dbKey, err) } + reader = newCloseOnCancelReader(v.ctx, reader) + defer func() { _ = reader.Close() }() // Decrypt and decompress straight from the storage stream, then stream diff --git a/internal/vaultik/restore_interrupt_test.go b/internal/vaultik/restore_interrupt_test.go index 2024a0d..9d96577 100644 --- a/internal/vaultik/restore_interrupt_test.go +++ b/internal/vaultik/restore_interrupt_test.go @@ -207,30 +207,37 @@ func TestRestoreSkipErrorsCancelDuringBlobDownload(t *testing.T) { "the cancel was reported as a failed file") } -// stallingBlobStorer wraps a Storer so that every blob download hands -// over the first half of the blob and then stalls, ignoring the context, -// as a file:// blob on a hung USB stick or network share does. Only -// closing the returned reader ends the stall. -type stallingBlobStorer struct { +// stallingStorer wraps a Storer so that each download of a key chosen by +// stalls hands over the first half of the object and then stalls, +// ignoring the context, as a file:// read on a hung USB stick or network +// share does. Only closing the returned reader ends the stall. +type stallingStorer struct { storage.Storer + stalls func(key string) bool once sync.Once stalled chan struct{} } -func newStallingBlobStorer(inner storage.Storer) *stallingBlobStorer { - return &stallingBlobStorer{Storer: inner, stalled: make(chan struct{})} +func newStallingStorer( + inner storage.Storer, stalls func(key string) bool, +) *stallingStorer { + return &stallingStorer{ + Storer: inner, + stalls: stalls, + stalled: make(chan struct{}), + } } -func (s *stallingBlobStorer) Get( +func (s *stallingStorer) Get( ctx context.Context, key string, ) (io.ReadCloser, error) { rc, err := s.Storer.Get(ctx, key) - if err != nil || !strings.HasPrefix(key, "blobs/") { + if err != nil || !s.stalls(key) { return rc, err } - blob, err := io.ReadAll(rc) + object, err := io.ReadAll(rc) _ = rc.Close() if err != nil { @@ -242,7 +249,7 @@ func (s *stallingBlobStorer) Get( pr, pw := io.Pipe() go func() { - _, _ = pw.Write(blob[:len(blob)/2]) + _, _ = pw.Write(object[:len(object)/2]) s.once.Do(func() { close(s.stalled) }) }() @@ -250,17 +257,26 @@ func (s *stallingBlobStorer) Get( return pr, nil } -// TestInterruptDuringStalledBlobReadCleansTempDir stops a restore and a -// deep verify while a blob read is stalled on a source that ignores the -// context. Stopping must end that read, so the operation unwinds and -// removes its decrypted scratch files well within the shutdown timeout -// (issue #325). +// TestInterruptDuringStalledReadCleansTempDir stops a restore and a deep +// verify while a read of a blob or of the snapshot database is stalled +// on a source that ignores the context. Stopping must end that read, so +// the operation unwinds and removes its decrypted scratch files well +// within the shutdown timeout (issues #325 and #356). // // Not parallel: it points TMPDIR at a private directory (via t.Setenv) // so it can assert on exactly the scratch files the operation created. -func TestInterruptDuringStalledBlobReadCleansTempDir(t *testing.T) { +func TestInterruptDuringStalledReadCleansTempDir(t *testing.T) { log.Initialize(log.Config{}) + stalledReads := map[string]func(key string) bool{ + "blob": func(key string) bool { + return strings.HasPrefix(key, "blobs/") + }, + "snapshot database": func(key string) bool { + return strings.HasSuffix(key, "/db.zst.age") + }, + } + operations := map[string]func(v *Vaultik, snapshotID, targetDir string) error{ "restore": func(v *Vaultik, snapshotID, targetDir string) error { return v.Restore(&RestoreOptions{ @@ -273,52 +289,58 @@ func TestInterruptDuringStalledBlobReadCleansTempDir(t *testing.T) { }, } - for name, op := range operations { - t.Run(name, func(t *testing.T) { - fs := afero.NewOsFs() - root := t.TempDir() + for readName, stalls := range stalledReads { + for opName, op := range operations { + t.Run(readName+" read during "+opName, func(t *testing.T) { + fs := afero.NewOsFs() + root := t.TempDir() - // Random content, so the blob stays large enough to stall - // part-way through its compressed, encrypted body. - cfg, storer, snapshotID, _ := backupOneFile(context.Background(), - t, fs, root, "a.bin", randomBytes(t, 256*1024), 0o644) + // Random content, so the blob stays large enough to stall + // part-way through its compressed, encrypted body. + cfg, storer, snapshotID, _ := backupOneFile(context.Background(), + t, fs, root, "a.bin", randomBytes(t, 256*1024), 0o644) - scratch := filepath.Join(root, "scratch") - require.NoError(t, fs.MkdirAll(scratch, 0o755)) - t.Setenv("TMPDIR", scratch) + scratch := filepath.Join(root, "scratch") + require.NoError(t, fs.MkdirAll(scratch, 0o755)) + t.Setenv("TMPDIR", scratch) - stalling := newStallingBlobStorer(storer) + stalling := newStallingStorer(storer, stalls) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() - v := newRestoreVaultik(ctx, cfg, stalling, fs) - v.cancel = cancel + v := newRestoreVaultik(ctx, cfg, stalling, fs) + v.cancel = cancel - var opErr error + var opErr error - stop := v.StartOperation(func() { - opErr = op(v, snapshotID, filepath.Join(root, "restored")) + stop := v.StartOperation(func() { + opErr = op(v, snapshotID, filepath.Join(root, "restored")) + }) + + select { + case <-stalling.stalled: + case <-time.After(30 * time.Second): + t.Fatal("the operation never reached the stalled read") + } + + // The snapshot database's temp directory is created just + // after its read starts, so it can appear after the stall. + require.Eventually(t, func() bool { + return len(scratchEntries(t, scratch)) > 0 + }, 10*time.Second, 10*time.Millisecond, + "expected decrypted scratch files to exist mid-read") + + stopCtx, stopCancel := context.WithTimeout( + context.Background(), 10*time.Second) + defer stopCancel() + + require.True(t, stop(stopCtx), + "stop timed out; the stalled read was not interrupted") + require.ErrorIs(t, opErr, context.Canceled) + require.Empty(t, scratchEntries(t, scratch), + "decrypted scratch files remained after the interrupt") }) - - select { - case <-stalling.stalled: - case <-time.After(30 * time.Second): - t.Fatal("the operation never reached a blob read") - } - - require.NotEmpty(t, scratchEntries(t, scratch), - "expected decrypted scratch files to exist mid-read") - - stopCtx, stopCancel := context.WithTimeout( - context.Background(), 10*time.Second) - defer stopCancel() - - require.True(t, stop(stopCtx), - "stop timed out; the stalled blob read was not interrupted") - require.ErrorIs(t, opErr, context.Canceled) - require.Empty(t, scratchEntries(t, scratch), - "decrypted scratch files remained after the interrupt") - }) + } } } diff --git a/internal/vaultik/verify.go b/internal/vaultik/verify.go index 51d6f06..3600208 100644 --- a/internal/vaultik/verify.go +++ b/internal/vaultik/verify.go @@ -260,6 +260,8 @@ func (v *Vaultik) downloadVerifiedSnapshotDB( fmt.Errorf("failed to download database: %w", err)) } + dbReader = newCloseOnCancelReader(v.ctx, dbReader) + defer func() { _ = dbReader.Close() }() tdb, err := v.decryptAndLoadDatabase(dbReader, identities) From 3b2b9cec84b90ed9563752124f546af96af43bce Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 19:46:48 +0200 Subject: [PATCH 061/121] Return errors instead of exiting on rollback, rows close and blob temp file cleanup (closes #345) WithReadTx ended the process when its rollback failed, including after Ctrl-C, when database/sql has already rolled back and Rollback returns sql.ErrTxDone; it now handles the rollback as WithTx does. The query functions ended the process when closing their rows failed; they now leave the deferred close alone, since database/sql reports a close failure through rows.Err(), which each returns. The unused database.Fatalf is removed. cleanupBlobTempFile now returns its close or remove failure, which fails the backup. No test makes a rows close fail: SQLite fails it only with the error the last read already returned. Model: opus-5-5 --- internal/database/blob_chunks.go | 7 +-- internal/database/blobs.go | 7 +-- internal/database/chunk_files.go | 21 ++------ internal/database/chunks.go | 14 +----- internal/database/chunks_ext.go | 7 +-- internal/database/errors.go | 12 ----- internal/database/file_chunks.go | 21 ++------ internal/database/files.go | 28 ++--------- internal/database/repositories.go | 20 ++++---- internal/database/repositories_test.go | 38 +++++++++++++++ internal/database/snapshots.go | 35 ++----------- internal/snapshot/blob_temp_file_test.go | 62 ++++++++++++++++++++++++ internal/snapshot/scanner.go | 22 ++++++--- 13 files changed, 145 insertions(+), 149 deletions(-) delete mode 100644 internal/database/errors.go create mode 100644 internal/snapshot/blob_temp_file_test.go diff --git a/internal/database/blob_chunks.go b/internal/database/blob_chunks.go index 64d99b0..1907323 100644 --- a/internal/database/blob_chunks.go +++ b/internal/database/blob_chunks.go @@ -58,12 +58,7 @@ func (r *BlobChunkRepository) GetByBlobID( return nil, fmt.Errorf("querying blob chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var blobChunks []*BlobChunk diff --git a/internal/database/blobs.go b/internal/database/blobs.go index dc85785..ccb6ad2 100644 --- a/internal/database/blobs.go +++ b/internal/database/blobs.go @@ -83,12 +83,7 @@ func (r *BlobRepository) GetAll(ctx context.Context) (map[string]*Blob, error) { return nil, fmt.Errorf("querying blobs: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() out := make(map[string]*Blob) diff --git a/internal/database/chunk_files.go b/internal/database/chunk_files.go index 0ce345a..b384d7f 100644 --- a/internal/database/chunk_files.go +++ b/internal/database/chunk_files.go @@ -61,12 +61,7 @@ func (r *ChunkFileRepository) GetByChunkHash( return nil, fmt.Errorf("querying chunk files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanChunkFiles(rows) } @@ -87,12 +82,7 @@ func (r *ChunkFileRepository) GetByFilePath( return nil, fmt.Errorf("querying chunk files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanChunkFiles(rows) } @@ -112,12 +102,7 @@ func (r *ChunkFileRepository) GetByFileID( return nil, fmt.Errorf("querying chunk files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanChunkFiles(rows) } diff --git a/internal/database/chunks.go b/internal/database/chunks.go index 51e95d1..c21475a 100644 --- a/internal/database/chunks.go +++ b/internal/database/chunks.go @@ -107,12 +107,7 @@ func (r *ChunkRepository) GetByHashes( return nil, fmt.Errorf("querying chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var chunks []*Chunk @@ -152,12 +147,7 @@ func (r *ChunkRepository) ListUnpacked( return nil, fmt.Errorf("querying unpacked chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var chunks []*Chunk diff --git a/internal/database/chunks_ext.go b/internal/database/chunks_ext.go index 0fc9e0a..5e78c5b 100644 --- a/internal/database/chunks_ext.go +++ b/internal/database/chunks_ext.go @@ -38,12 +38,7 @@ func (r *ChunkRepository) list(ctx context.Context, query string) ([]*Chunk, err return nil, fmt.Errorf("querying chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var chunks []*Chunk diff --git a/internal/database/errors.go b/internal/database/errors.go deleted file mode 100644 index 49492bd..0000000 --- a/internal/database/errors.go +++ /dev/null @@ -1,12 +0,0 @@ -package database - -import ( - "fmt" - "os" -) - -// Fatalf prints an error message to stderr and exits with status 1 -func Fatalf(format string, args ...any) { - fmt.Fprintf(os.Stderr, "FATAL: "+format+"\n", args...) - os.Exit(1) -} diff --git a/internal/database/file_chunks.go b/internal/database/file_chunks.go index 0803de2..bbecc03 100644 --- a/internal/database/file_chunks.go +++ b/internal/database/file_chunks.go @@ -62,12 +62,7 @@ func (r *FileChunkRepository) GetByPath( return nil, fmt.Errorf("querying file chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanFileChunks(rows) } @@ -88,12 +83,7 @@ func (r *FileChunkRepository) GetByFileID( return nil, fmt.Errorf("querying file chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanFileChunks(rows) } @@ -117,12 +107,7 @@ func (r *FileChunkRepository) GetByPathTx( return nil, fmt.Errorf("querying file chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() fileChunks, err := r.scanFileChunks(rows) LogSQL("GetByPathTx", "Complete", path, "count", len(fileChunks)) diff --git a/internal/database/files.go b/internal/database/files.go index bce0a3b..824267c 100644 --- a/internal/database/files.go +++ b/internal/database/files.go @@ -175,12 +175,7 @@ func (r *FileRepository) ListModifiedSince( return nil, fmt.Errorf("querying files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var files []*File @@ -256,12 +251,7 @@ func (r *FileRepository) ListUnderPath( return nil, fmt.Errorf("querying files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var files []*File @@ -304,12 +294,7 @@ func (r *FileRepository) ListIDsWithChunksNotInUploadedBlobs( return nil, fmt.Errorf("querying files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var ids []types.FileID @@ -340,12 +325,7 @@ func (r *FileRepository) ListAll(ctx context.Context) ([]*File, error) { return nil, fmt.Errorf("querying files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var files []*File diff --git a/internal/database/repositories.go b/internal/database/repositories.go index 4db15d1..fe3f5df 100644 --- a/internal/database/repositories.go +++ b/internal/database/repositories.go @@ -106,22 +106,24 @@ func (r *Repositories) WithReadTx(ctx context.Context, fn TxFunc) error { defer func() { if p := recover(); p != nil { - rollbackErr := tx.Rollback() - if rollbackErr != nil { - Fatalf("failed to rollback transaction: %v", rollbackErr) - } + // The panic is the failure to report, so a rollback error + // is dropped. + _ = tx.Rollback() panic(p) - } else if err != nil { - rollbackErr := tx.Rollback() - if rollbackErr != nil { - Fatalf("failed to rollback transaction: %v", rollbackErr) - } } }() err = fn(ctx, tx) if err != nil { + // Once ctx is cancelled, database/sql rolls the transaction + // back itself and Rollback returns sql.ErrTxDone. + rollbackErr := tx.Rollback() + if rollbackErr != nil && !errors.Is(rollbackErr, sql.ErrTxDone) { + return fmt.Errorf("%w; rolling back transaction: %w", + err, rollbackErr) + } + return err } diff --git a/internal/database/repositories_test.go b/internal/database/repositories_test.go index 06e588e..d1db401 100644 --- a/internal/database/repositories_test.go +++ b/internal/database/repositories_test.go @@ -411,3 +411,41 @@ func TestRepositoriesReadTransaction(t *testing.T) { t.Error("expected to retrieve file in read transaction") } } + +// When the context is cancelled during a read transaction's body, +// database/sql rolls the transaction back itself, so WithReadTx's own +// rollback finds it already done. WithReadTx must return the body's error +// alone, without that rollback. +func TestRepositoriesReadTransactionContextCancelled(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + repos := database.NewRepositories(db) + + err := repos.WithReadTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + cancel() + + // database/sql rolls back from a goroutine of its own; wait + // until it has, so the test does not depend on that race. + for { + _, err := tx.ExecContext(context.WithoutCancel(ctx), "SELECT 1") + if errors.Is(err, sql.ErrTxDone) { + return ctx.Err() + } + + time.Sleep(time.Millisecond) + } + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got: %v", err) + } + + if errors.Is(err, sql.ErrTxDone) { + t.Fatalf("the already-done rollback was reported: %v", err) + } +} diff --git a/internal/database/snapshots.go b/internal/database/snapshots.go index c9c609a..f16bc0d 100644 --- a/internal/database/snapshots.go +++ b/internal/database/snapshots.go @@ -241,12 +241,7 @@ func (r *SnapshotRepository) GetOnlySnapshot(ctx context.Context) (*Snapshot, er return nil, fmt.Errorf("querying snapshots: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() snapshots, err := r.scanSnapshotRows(rows) if err != nil { @@ -281,12 +276,7 @@ func (r *SnapshotRepository) ListRecent( return nil, fmt.Errorf("querying snapshots: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanSnapshotRows(rows) } @@ -501,12 +491,7 @@ func (r *SnapshotRepository) GetBlobHashes( return nil, fmt.Errorf("querying blob hashes: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var blobs []string @@ -634,12 +619,7 @@ func (r *SnapshotRepository) GetIncompleteSnapshots( return nil, fmt.Errorf("querying incomplete snapshots: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanSnapshotRows(rows) } @@ -662,12 +642,7 @@ func (r *SnapshotRepository) GetIncompleteByHostname( return nil, fmt.Errorf("querying incomplete snapshots: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() // Same column set as every other multi-row snapshot query, so the // shared scanner applies — including its timestamp normalization. diff --git a/internal/snapshot/blob_temp_file_test.go b/internal/snapshot/blob_temp_file_test.go new file mode 100644 index 0000000..ed03e19 --- /dev/null +++ b/internal/snapshot/blob_temp_file_test.go @@ -0,0 +1,62 @@ +//nolint:testpackage // exercises the unexported cleanupBlobTempFile +package snapshot + +import ( + "errors" + "os" + "testing" + + "github.com/spf13/afero" + "sneak.berlin/go/vaultik/internal/blob" +) + +// A blob temp file that cannot be closed or removed must make the cleanup +// return an error, not end the process. +func TestCleanupBlobTempFileReturnsErrors(t *testing.T) { + t.Parallel() + + fs := afero.NewOsFs() + s := &Scanner{fs: fs} + + tests := []struct { + name string + // prepare runs before the cleanup and makes its close or remove + // fail. + prepare func(tempFile afero.File) error + want error + }{ + { + name: "close fails", + prepare: func(tempFile afero.File) error { return tempFile.Close() }, + want: os.ErrClosed, + }, + { + name: "remove fails", + prepare: func(tempFile afero.File) error { + return fs.Remove(tempFile.Name()) + }, + want: os.ErrNotExist, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + tempFile, err := afero.TempFile(fs, t.TempDir(), "blob-*.tmp") + if err != nil { + t.Fatal(err) + } + + err = tt.prepare(tempFile) + if err != nil { + t.Fatal(err) + } + + err = s.cleanupBlobTempFile(&blob.WithReader{TempFile: tempFile}) + if !errors.Is(err, tt.want) { + t.Fatalf("expected an error wrapping %v, got: %v", tt.want, err) + } + }) + } +} diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 32441cf..debb061 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -1556,19 +1556,23 @@ func (s *Scanner) handleBlobReady( blobExists, err := s.uploadBlobIfNeeded( ctx, blobPath, blobWithReader, startTime, result) if err != nil { - s.cleanupBlobTempFile(blobWithReader) + cleanupErr := s.cleanupBlobTempFile(blobWithReader) - return fmt.Errorf("uploading blob %s: %w", finishedBlob.Hash, err) + return errors.Join( + fmt.Errorf("uploading blob %s: %w", finishedBlob.Hash, err), cleanupErr) } err = s.recordBlobMetadata(ctx, finishedBlob, blobExists, startTime) if err != nil { - s.cleanupBlobTempFile(blobWithReader) + cleanupErr := s.cleanupBlobTempFile(blobWithReader) - return err + return errors.Join(err, cleanupErr) } - s.cleanupBlobTempFile(blobWithReader) + err = s.cleanupBlobTempFile(blobWithReader) + if err != nil { + return err + } // Chunks from this blob are now committed to DB - remove from pending set s.removePendingChunkHashes(blobWithReader.InsertedChunkHashes) @@ -1762,20 +1766,22 @@ func (s *Scanner) recordBlobMetadata( } // cleanupBlobTempFile closes and removes the blob's temporary file -func (s *Scanner) cleanupBlobTempFile(blobWithReader *blob.WithReader) { +func (s *Scanner) cleanupBlobTempFile(blobWithReader *blob.WithReader) error { if blobWithReader.TempFile != nil { tempName := blobWithReader.TempFile.Name() err := blobWithReader.TempFile.Close() if err != nil { - log.Fatal("Failed to close temp file", "file", tempName, "error", err) + return fmt.Errorf("closing blob temp file: %w", err) } err = s.fs.Remove(tempName) if err != nil { - log.Fatal("Failed to remove temp file", "file", tempName, "error", err) + return fmt.Errorf("removing blob temp file: %w", err) } } + + return nil } // streamingChunkInfo tracks chunk metadata collected during streaming From 6aceaaf0867c4c52e764b531d859c5827a09de2e Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 20:01:42 +0200 Subject: [PATCH 062/121] Record the stored size of a blob a backup finds already stored (closes #300) When a finished blob already existed at the destination, the upload was skipped but the blob row, and so the manifest, kept the size of the local copy. That copy can differ from the stored object when compression_level or the recipients changed since it was written, and then shallow and deep verify failed on a good snapshot. Marking a blob uploaded now records the size of the object in storage: for an existing blob, the size Stat reports. Judgement call: the test adds a recipient rather than changing the compression level, because an extra age recipient always makes the local copy larger, while two zstd levels need not compress the test data differently. Model: opus-5-5 --- docs/DATAMODEL.md | 4 +- internal/database/blobs.go | 15 ++-- internal/database/blobs_test.go | 8 +- internal/snapshot/scanner.go | 26 ++++--- internal/vaultik/reused_blob_verify_test.go | 83 +++++++++++++++++++++ 5 files changed, 116 insertions(+), 20 deletions(-) create mode 100644 internal/vaultik/reused_blob_verify_test.go diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index b3191ac..463e6ec 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -90,7 +90,7 @@ Stores information about packed, compressed, and encrypted blob files. - `created_ts` (INTEGER NOT NULL) - Creation timestamp - `finished_ts` (INTEGER) - Finalization timestamp (NULL if in progress) - `uncompressed_size` (INTEGER NOT NULL DEFAULT 0) - Total size of chunks before compression -- `compressed_size` (INTEGER NOT NULL DEFAULT 0) - Size after compression and encryption +- `compressed_size` (INTEGER NOT NULL DEFAULT 0) - Size after compression and encryption. Once uploaded, the size of the object in storage: when the blob was already stored, under another compression level or other recipients, this can differ from the size of the local copy - `uploaded_ts` (INTEGER) - Upload completion timestamp (NULL if not uploaded) **Purpose:** Tracks blob lifecycle from creation through upload. The UUID primary key allows immediate association of chunks with blobs. @@ -184,7 +184,7 @@ Tracks blob upload metrics. - `UPDATE blobs SET blob_hash = ?, finished_ts = ?` - Finalize blob after packing 4. **Upload** - - `UPDATE blobs SET uploaded_ts = ?` - Mark blob as uploaded + - `UPDATE blobs SET uploaded_ts = ?, compressed_size = ?` - Mark blob as uploaded, with the size of the object in storage (the upload is skipped when the blob is already stored) - `INSERT INTO uploads` - Record upload metrics with snapshot_id - `INSERT INTO snapshot_blobs` - Associate blob with snapshot diff --git a/internal/database/blobs.go b/internal/database/blobs.go index ccb6ad2..aec4dca 100644 --- a/internal/database/blobs.go +++ b/internal/database/blobs.go @@ -154,13 +154,16 @@ func (r *BlobRepository) UpdateFinished( return nil } -// UpdateUploaded marks a blob as uploaded +// UpdateUploaded marks a blob as uploaded and records the size of the +// stored object as its compressed size. That size can differ from the +// local copy's when an identical blob was already stored with another +// compression level or other recipients. func (r *BlobRepository) UpdateUploaded( - ctx context.Context, tx *sql.Tx, id string, + ctx context.Context, tx *sql.Tx, id string, storedSize int64, ) error { query := ` - UPDATE blobs - SET uploaded_ts = ? + UPDATE blobs + SET uploaded_ts = ?, compressed_size = ? WHERE id = ? ` @@ -168,9 +171,9 @@ func (r *BlobRepository) UpdateUploaded( var err error if tx != nil { - _, err = tx.ExecContext(ctx, query, now, id) + _, err = tx.ExecContext(ctx, query, now, storedSize, id) } else { - _, err = r.db.ExecWithLog(ctx, query, now, id) + _, err = r.db.ExecWithLog(ctx, query, now, storedSize, id) } if err != nil { diff --git a/internal/database/blobs_test.go b/internal/database/blobs_test.go index 457b0db..3caf57a 100644 --- a/internal/database/blobs_test.go +++ b/internal/database/blobs_test.go @@ -122,8 +122,8 @@ func TestBlobRepositoryUpdates(t *testing.T) { t.Errorf("expected compressed size 500, got %d", updated.CompressedSize) } - // Test UpdateUploaded - err = repo.UpdateUploaded(ctx, nil, blob.ID.String()) + // Test UpdateUploaded, with a stored object larger than the local copy + err = repo.UpdateUploaded(ctx, nil, blob.ID.String(), 600) if err != nil { t.Fatalf("failed to update blob as uploaded: %v", err) } @@ -141,6 +141,10 @@ func TestBlobRepositoryUpdates(t *testing.T) { if uploaded.UploadedTS.Before(now.Add(-1 * time.Second)) { t.Error("uploaded timestamp should be around test time") } + + if uploaded.CompressedSize != 600 { + t.Errorf("expected the stored size 600, got %d", uploaded.CompressedSize) + } } func TestBlobRepositoryDuplicate(t *testing.T) { diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index debb061..ee8a954 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -1517,7 +1517,8 @@ func (s *Scanner) finalizeProcessPhase(ctx context.Context, result *ScanResult) // snapshot references has uploaded_ts set, so deduplication and // interrupted-run repair treat these blobs as trustworthy. err = s.repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { - err := s.repos.Blobs.UpdateUploaded(ctx, tx, b.ID) + err := s.repos.Blobs.UpdateUploaded( + ctx, tx, b.ID, b.Compressed) if err != nil { return fmt.Errorf("marking blob uploaded: %w", err) } @@ -1553,7 +1554,7 @@ func (s *Scanner) handleBlobReady( blobPath := fmt.Sprintf("blobs/%s/%s/%s", finishedBlob.Hash[:2], finishedBlob.Hash[2:4], finishedBlob.Hash) - blobExists, err := s.uploadBlobIfNeeded( + storedSize, blobExists, err := s.uploadBlobIfNeeded( ctx, blobPath, blobWithReader, startTime, result) if err != nil { cleanupErr := s.cleanupBlobTempFile(blobWithReader) @@ -1562,7 +1563,8 @@ func (s *Scanner) handleBlobReady( fmt.Errorf("uploading blob %s: %w", finishedBlob.Hash, err), cleanupErr) } - err = s.recordBlobMetadata(ctx, finishedBlob, blobExists, startTime) + err = s.recordBlobMetadata( + ctx, finishedBlob, storedSize, blobExists, startTime) if err != nil { cleanupErr := s.cleanupBlobTempFile(blobWithReader) @@ -1587,20 +1589,22 @@ func (s *Scanner) handleBlobReady( } // uploadBlobIfNeeded uploads the blob to storage if it doesn't already -// exist, returns whether it existed +// exist. It returns the size of the object in storage, which for an +// existing object can differ from the local copy's, and whether it +// already existed. func (s *Scanner) uploadBlobIfNeeded( ctx context.Context, blobPath string, blobWithReader *blob.WithReader, startTime time.Time, result *ScanResult, -) (bool, error) { +) (int64, bool, error) { finishedBlob := blobWithReader.FinishedBlob // Check if blob already exists (deduplication after restart) destination := s.storage.Info().Location - _, err := s.storage.Stat(ctx, blobPath) + stored, err := s.storage.Stat(ctx, blobPath) if err == nil { log.Info("Blob already exists in storage, skipping upload", "hash", finishedBlob.Hash, @@ -1609,7 +1613,7 @@ func (s *Scanner) uploadBlobIfNeeded( s.ui.Hex(finishedBlob.Hash), s.ui.Size(finishedBlob.Compressed), s.ui.Path(destination)) - return true, nil + return stored.Size, true, nil } s.ui.Beginf("Uploading blob %s (%s) to %s.", @@ -1623,7 +1627,7 @@ func (s *Scanner) uploadBlobIfNeeded( if err != nil { log.Error("Failed to upload blob", "hash", finishedBlob.Hash, "error", err) - return false, fmt.Errorf("uploading blob to storage: %w", err) + return 0, false, fmt.Errorf("uploading blob to storage: %w", err) } uploadDuration := time.Since(startTime) @@ -1654,7 +1658,7 @@ func (s *Scanner) uploadBlobIfNeeded( stats.BytesUploaded.Add(finishedBlob.Compressed) } - return false, nil + return finishedBlob.Compressed, false, nil } // makeUploadProgressCallback creates a progress callback for blob uploads. @@ -1724,6 +1728,7 @@ func (s *Scanner) makeUploadProgressCallback( func (s *Scanner) recordBlobMetadata( ctx context.Context, finishedBlob *blob.FinishedBlob, + storedSize int64, blobExists bool, startTime time.Time, ) error { @@ -1735,7 +1740,8 @@ func (s *Scanner) recordBlobMetadata( uploadDuration := time.Since(startTime) return s.repos.WithTx(ctx, func(txCtx context.Context, tx *sql.Tx) error { - err := s.repos.Blobs.UpdateUploaded(txCtx, tx, finishedBlob.ID) + err := s.repos.Blobs.UpdateUploaded( + txCtx, tx, finishedBlob.ID, storedSize) if err != nil { return fmt.Errorf("updating blob upload timestamp: %w", err) } diff --git a/internal/vaultik/reused_blob_verify_test.go b/internal/vaultik/reused_blob_verify_test.go new file mode 100644 index 0000000..68cd715 --- /dev/null +++ b/internal/vaultik/reused_blob_verify_test.go @@ -0,0 +1,83 @@ +package vaultik_test + +import ( + "context" + "io" + "path/filepath" + "testing" + + "filippo.io/age" + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestVerifyPassesWhenBackupReusesStoredBlob backs up a file, then backs it +// up again from an empty local index, as after `database delete`, with an +// extra age recipient. The second backup builds the same blob, finds it +// already stored and skips the upload, but its own copy is larger, because +// age writes a header entry for each recipient. The second snapshot must +// record the size of the stored object, so shallow and deep verify pass. +func TestVerifyPassesWhenBackupReusesStoredBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + storeDir := filepath.Join(tempDir, "remote") + secondDBPath := filepath.Join(tempDir, "second.sqlite") + + chunkSize := int64(64 * 1024) + maxBlobSize := int64(512 * 1024) + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, "data.bin"), + bytesPattern("reuse-", int(chunkSize*3)), 0o644)) + + ctx := context.Background() + + runFileStorageBackup(ctx, t, fs, dataDir, storeDir, + filepath.Join(tempDir, "first.sqlite"), chunkSize, maxBlobSize) + + env := setupDedupBackupEnv( + ctx, t, fs, storeDir, secondDBPath, chunkSize, maxBlobSize) + + defer func() { _ = env.db.Close() }() + + extra, err := age.GenerateX25519Identity() + require.NoError(t, err) + + env.cfg.AgeRecipients = append(env.cfg.AgeRecipients, + extra.Recipient().String()) + + snapshotID, result := runDedupSnapshot(ctx, t, env.sm, env.makeScanner(), + env.cfg.Hostname, "second", dataDir, secondDBPath) + require.Positive(t, result.BlobsCreated) + require.Zero(t, result.BlobsUploaded, + "the second backup should find every blob already stored") + + require.NoError(t, env.db.Close()) + + verifier := &vaultik.Vaultik{ + Config: env.cfg, + Storage: env.storer, + Fs: fs, + Stdout: io.Discard, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + verifier.SetContext(ctx) + + require.NoError(t, + verifier.VerifySnapshotWithOptions(snapshotID, &vaultik.VerifyOptions{}), + "shallow verify should pass") + require.NoError(t, + verifier.VerifySnapshotWithOptions(snapshotID, + &vaultik.VerifyOptions{Deep: true}), + "deep verify should pass") +} From fb8abcd049fc2ad7f23d167019591b79d35a5c05 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 20:12:48 +0200 Subject: [PATCH 063/121] Stop restore --verify re-reporting files that failed to restore (closes #323) With --skip-errors, a file that failed to restore was verified anyway, failed again because it was never written, and was added to the same failure list as the restore failure. restore --verify then listed it twice and called every entry a checksum mismatch. Verification now skips the files that failed to restore and keeps its own failures in a separate list, so failed restores and failed verifications are reported apart, each path once. The restore still exits non-zero. The tests cover a restore with skipped files where nothing fails verification, and one where another restored file also fails it. Judgement call: the second test has its own trailing-byte file-system wrapper; the one in restore_perms_test.go is in the internal test package. Model: opus-5-5 --- README.md | 4 +- internal/vaultik/restore.go | 39 ++++-- internal/vaultik/restore_skip_errors_test.go | 126 +++++++++++++++++++ 3 files changed, 156 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 471501e..b33d77a 100644 --- a/README.md +++ b/README.md @@ -375,7 +375,9 @@ on the destination in one go, use `vaultik remote nuke --force`. * Optional path arguments to restore specific files/directories (default: all) * Preserves file permissions, timestamps, ownership (ownership requires root), symlinks, and empty directories -* `--verify`: After restoring, verify every file's chunk hashes match +* `--verify`: After restoring, verify every restored file's chunk hashes + match. A file skipped under `--skip-errors` is reported as failed to + restore and is not verified. **`prune`**: Tidy up everything that isn't needed. Runs three passes: (1) reconcile the local index against the destination store — any diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index 96f4048..565883a 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -103,11 +103,12 @@ type RestoreResult struct { BlobsDownloaded int BytesDownloaded int64 Duration time.Duration + FilesFailed int + FailedFiles []string // Paths of files that failed to restore // Verification results (only populated if Verify option is set) - FilesVerified int - BytesVerified int64 - FilesFailed int - FailedFiles []string // Paths of files that failed verification + FilesVerified int + BytesVerified int64 + VerifyFailedFiles []string // Paths of restored files that failed verification } // Restore restores files from a snapshot to the target directory @@ -658,20 +659,34 @@ func (v *Vaultik) handleRestoreVerification( opts *RestoreOptions, result *RestoreResult, ) error { - err := v.verifyRestoredFiles(v.ctx, repos, files, opts.TargetDir, result) + // A file that failed to restore was not written and is already + // reported as such, so it is not verified. + failedToRestore := make(map[string]bool, len(result.FailedFiles)) + for _, path := range result.FailedFiles { + failedToRestore[path] = true + } + + restored := make([]*database.File, 0, len(files)) + for _, file := range files { + if !failedToRestore[file.Path.String()] { + restored = append(restored, file) + } + } + + err := v.verifyRestoredFiles(v.ctx, repos, restored, opts.TargetDir, result) if err != nil { return fmt.Errorf("verification failed: %w", err) } - if result.FilesFailed > 0 { + if len(result.VerifyFailedFiles) > 0 { v.UI.Errorf("Verification failed: %s files did not match expected checksums.", - v.UI.Count(result.FilesFailed)) + v.UI.Count(len(result.VerifyFailedFiles))) - for _, path := range result.FailedFiles { + for _, path := range result.VerifyFailedFiles { v.UI.Detailf("%s", v.UI.Path(path)) } - return fmt.Errorf("%d %w", result.FilesFailed, errFilesFailedVerify) + return fmt.Errorf("%d %w", len(result.VerifyFailedFiles), errFilesFailedVerify) } v.UI.Completef("Verified %s files (%s).", @@ -1433,8 +1448,8 @@ func (v *Vaultik) verifyRestoredFiles( if err != nil { log.Error("File verification failed", "path", file.Path, "error", err) - result.FilesFailed++ - result.FailedFiles = append(result.FailedFiles, file.Path.String()) + result.VerifyFailedFiles = append( + result.VerifyFailedFiles, file.Path.String()) } bytesProcessed += file.Size @@ -1450,7 +1465,7 @@ func (v *Vaultik) verifyRestoredFiles( log.Info("Verification complete", "files_verified", result.FilesVerified, "bytes_verified", ubytes(result.BytesVerified), - "files_failed", result.FilesFailed, + "files_failed", len(result.VerifyFailedFiles), ) return nil diff --git a/internal/vaultik/restore_skip_errors_test.go b/internal/vaultik/restore_skip_errors_test.go index c74b691..376c833 100644 --- a/internal/vaultik/restore_skip_errors_test.go +++ b/internal/vaultik/restore_skip_errors_test.go @@ -4,7 +4,9 @@ import ( "bytes" "context" "fmt" + "os" "path/filepath" + "strings" "testing" "github.com/spf13/afero" @@ -104,6 +106,130 @@ func assertRestoreSkipsLostFiles( } } +// TestRestoreSkipErrorsVerifyChecksOnlyRestoredFiles restores with +// SkipErrors and Verify after one blob of a two-blob snapshot was +// deleted. Verification must check only the files that were written, so +// a file of the deleted blob is reported as failed to restore and not +// also as failing verification, and Restore must still return an error. +func TestRestoreSkipErrorsVerifyChecksOnlyRestoredFiles(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + backup := backupThenDeleteOneBlob(ctx, t) + + var out bytes.Buffer + + v := newReaderVaultik(ctx, backup.cfg, backup.storer, nil, backup.fs) + v.UI = ui.NewWithColor(&out, false) + + err := v.Restore(&vaultik.RestoreOptions{ + SnapshotID: backup.snapshotID, + TargetDir: backup.restoreDir, + Verify: true, + SkipErrors: true, + }) + + require.Error(t, err, "restore must fail when files were skipped") + assert.Contains(t, err.Error(), + fmt.Sprintf("%d file(s) failed to restore", len(backup.lost))) + + written := len(backup.files) - len(backup.lost) + + assert.Contains(t, out.String(), fmt.Sprintf("Verifying %d files", written)) + assert.Contains(t, out.String(), fmt.Sprintf("Verified %d files", written)) + assert.NotContains(t, out.String(), "Verification failed") +} + +// TestRestoreSkipErrorsVerifyReportsFailuresApart restores with +// SkipErrors and Verify after one blob of a two-blob snapshot was +// deleted, while one file that does restore is written one byte too long. +// The restore warning must list only the files of the deleted blob, the +// verification summary only the long file, each path once, and Restore +// must return an error. +func TestRestoreSkipErrorsVerifyReportsFailuresApart(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + backup := backupThenDeleteOneBlob(ctx, t) + + var long string + + for path := range backup.files { + if !backup.lost[path] { + long = path + + break + } + } + + var out bytes.Buffer + + fs := trailingByteFs{Fs: backup.fs, suffix: long} + v := newReaderVaultik(ctx, backup.cfg, backup.storer, nil, fs) + v.UI = ui.NewWithColor(&out, false) + + err := v.Restore(&vaultik.RestoreOptions{ + SnapshotID: backup.snapshotID, + TargetDir: backup.restoreDir, + Verify: true, + SkipErrors: true, + }) + require.Error(t, err, "restore must fail when files failed") + + _, afterWarning, found := strings.Cut(out.String(), + fmt.Sprintf("%d file(s) failed to restore:", len(backup.lost))) + require.Truef(t, found, "no restore warning in:\n%s", out.String()) + + warning, summary, found := strings.Cut(afterWarning, + "Verification failed: 1 files did not match") + require.Truef(t, found, "no verification summary in:\n%s", out.String()) + + for path := range backup.lost { + assert.Equalf(t, 1, strings.Count(warning, path), + "%s must be listed once as failed to restore", path) + assert.NotContainsf(t, summary, path, + "%s was not restored and must not fail verification", path) + } + + assert.NotContainsf(t, warning, long, + "%s was restored and must not be listed as failed to restore", long) + assert.Equalf(t, 1, strings.Count(summary, long), + "%s must be listed once as failing verification", long) +} + +// trailingByteFs appends one byte, on close, to the file it opens whose +// path ends in suffix, so that file is restored one byte too long and +// fails verification. +type trailingByteFs struct { + afero.Fs + + suffix string +} + +//nolint:ireturn // afero.Fs.OpenFile is defined to return the interface +func (fs trailingByteFs) OpenFile( + name string, flag int, perm os.FileMode, +) (afero.File, error) { + f, err := fs.Fs.OpenFile(name, flag, perm) + if err != nil || !strings.HasSuffix(name, fs.suffix) { + return f, err + } + + return trailingByteFile{File: f}, nil +} + +type trailingByteFile struct { + afero.File +} + +func (f trailingByteFile) Close() error { + _, _ = f.Write([]byte{'x'}) + + return f.File.Close() +} + // TestRestoreMissingBlobAbortsWithoutSkipErrors checks that a deleted blob // still ends the restore with an error when SkipErrors is not set. func TestRestoreMissingBlobAbortsWithoutSkipErrors(t *testing.T) { From 3361e9ebd971da8e5e21584f3589f97c43999070 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 20:43:19 +0200 Subject: [PATCH 064/121] Record each snapshot's uncompressed size when its backup runs (closes #360) snapshot list summed the chunks a snapshot reaches through its file rows in the local index. A file's row is shared by every snapshot that lists it and rewritten when the file changes, so backing up a changed file changed every older snapshot's UNCOMPRESSED SIZE. The backup now takes that total when it records the snapshot's stats, into a new snapshots column, uncompressed_chunk_size, and snapshot list reads the column, as it already does for new_chunk_size. Model: opus-5-5 --- README.md | 3 +- docs/DATAMODEL.md | 1 + internal/database/schema/001.sql | 1 + internal/database/snapshots.go | 40 +++++----- internal/vaultik/snapshot_list_test.go | 15 ++-- internal/vaultik/uncompressed_size_test.go | 85 ++++++++++++++++++++++ 6 files changed, 120 insertions(+), 25 deletions(-) create mode 100644 internal/vaultik/uncompressed_size_test.go diff --git a/README.md b/README.md index b33d77a..784afca 100644 --- a/README.md +++ b/README.md @@ -294,7 +294,8 @@ needed. of the local index and the backup destination store — with timestamps and three sizes per snapshot (compressed remote size; total uncompressed chunk size; size of the chunks that snapshot stored that -were not stored before, recorded when its backup ran). +were not stored before). Both chunk sizes are recorded when the +snapshot's backup runs. Listing the destination store does **not** require the age secret key, so it works in vaultik's intended configuration, where the backed-up diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index 463e6ec..9f94fde 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -122,6 +122,7 @@ Tracks backup snapshots. - `new_chunk_size` (INTEGER) - Total size of those chunks before compression; `snapshot list` shows it as NEW CHUNK SIZE - `blob_count` (INTEGER) - Number of blobs this snapshot created - `total_size` (INTEGER) - Total size of all files +- `uncompressed_chunk_size` (INTEGER) - Total size before compression of the distinct chunks the snapshot's files reference, recorded when its backup ran; `snapshot list` shows it as UNCOMPRESSED SIZE - `blob_size` (INTEGER) - Total compressed size of all referenced blobs - `blob_uncompressed_size` (INTEGER) - Total uncompressed size of all referenced blobs - `compression_ratio` (REAL) - Compression ratio achieved diff --git a/internal/database/schema/001.sql b/internal/database/schema/001.sql index 0b022c2..9645b56 100644 --- a/internal/database/schema/001.sql +++ b/internal/database/schema/001.sql @@ -89,6 +89,7 @@ CREATE TABLE IF NOT EXISTS snapshots ( new_chunk_size INTEGER NOT NULL DEFAULT 0, blob_count INTEGER NOT NULL DEFAULT 0, total_size INTEGER NOT NULL DEFAULT 0, + uncompressed_chunk_size INTEGER NOT NULL DEFAULT 0, blob_size INTEGER NOT NULL DEFAULT 0, blob_uncompressed_size INTEGER NOT NULL DEFAULT 0, compression_ratio REAL NOT NULL DEFAULT 1.0, diff --git a/internal/database/snapshots.go b/internal/database/snapshots.go index f16bc0d..f4d5e77 100644 --- a/internal/database/snapshots.go +++ b/internal/database/snapshots.go @@ -120,7 +120,11 @@ func (r *SnapshotRepository) UpdateCounts( return nil } -// UpdateExtendedStats updates extended statistics for a snapshot +// UpdateExtendedStats updates extended statistics for a snapshot. It also +// records the total plaintext size of the distinct chunks the snapshot's +// files reference. Only the snapshot's own backup can take that total: a +// file's row is shared by every snapshot that lists it, and a later +// backup of a changed file rewrites the row with the new chunks. func (r *SnapshotRepository) UpdateExtendedStats( ctx context.Context, tx *sql.Tx, @@ -145,7 +149,17 @@ func (r *SnapshotRepository) UpdateExtendedStats( compression_level = ?, upload_bytes = ?, upload_duration_ms = ?, - new_chunk_size = ? + new_chunk_size = ?, + uncompressed_chunk_size = ( + SELECT COALESCE(SUM(c.size), 0) + FROM ( + SELECT DISTINCT fc.chunk_hash + FROM snapshot_files sf + JOIN file_chunks fc ON sf.file_id = fc.file_id + WHERE sf.snapshot_id = snapshots.id + ) sc + JOIN chunks c ON sc.chunk_hash = c.chunk_hash + ) WHERE id = ? ` @@ -555,30 +569,22 @@ func (r *SnapshotRepository) GetSnapshotBlobSizes( return compressed, uncompressed, nil } -// GetSnapshotUncompressedChunkSize returns the sum of plaintext sizes of all unique -// chunks referenced by a snapshot (via snapshot_files → file_chunks → chunks). +// GetSnapshotUncompressedChunkSize returns the total plaintext size of the +// distinct chunks the snapshot's files reference, as the snapshot's backup +// recorded it (see UpdateExtendedStats). func (r *SnapshotRepository) GetSnapshotUncompressedChunkSize( ctx context.Context, snapshotID string, ) (int64, error) { - query := ` - SELECT COALESCE(SUM(c.size), 0) - FROM ( - SELECT DISTINCT fc.chunk_hash - FROM snapshot_files sf - JOIN file_chunks fc ON sf.file_id = fc.file_id - WHERE sf.snapshot_id = ? - ) sc - JOIN chunks c ON sc.chunk_hash = c.chunk_hash - ` + query := `SELECT uncompressed_chunk_size FROM snapshots WHERE id = ?` - var totalSize int64 + var uncompressedChunkSize int64 - err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan(&totalSize) + err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan(&uncompressedChunkSize) if err != nil { return 0, fmt.Errorf("querying uncompressed chunk size: %w", err) } - return totalSize, nil + return uncompressedChunkSize, nil } // GetSnapshotNewChunkSize returns the total plaintext size of the chunks the diff --git a/internal/vaultik/snapshot_list_test.go b/internal/vaultik/snapshot_list_test.go index 3beb371..2dd88e4 100644 --- a/internal/vaultik/snapshot_list_test.go +++ b/internal/vaultik/snapshot_list_test.go @@ -483,13 +483,14 @@ func TestListSnapshots_UnreadableManifestDoesNotHideOthers(t *testing.T) { // //nolint:tagliatelle // snake_case is the established output format type listJSONRow struct { - ID string `json:"id"` - RemoteKey string `json:"remote_key"` - Timestamp string `json:"timestamp"` - CompressedSize int64 `json:"compressed_size"` - NewChunkSize int64 `json:"new_chunk_size"` - LocallyTracked bool `json:"locally_tracked"` - RemotePresent *bool `json:"remote_present"` + ID string `json:"id"` + RemoteKey string `json:"remote_key"` + Timestamp string `json:"timestamp"` + CompressedSize int64 `json:"compressed_size"` + UncompressedSize int64 `json:"uncompressed_size"` + NewChunkSize int64 `json:"new_chunk_size"` + LocallyTracked bool `json:"locally_tracked"` + RemotePresent *bool `json:"remote_present"` } // decodeListJSON parses the command's stdout, which must contain diff --git a/internal/vaultik/uncompressed_size_test.go b/internal/vaultik/uncompressed_size_test.go new file mode 100644 index 0000000..f9b77c1 --- /dev/null +++ b/internal/vaultik/uncompressed_size_test.go @@ -0,0 +1,85 @@ +package vaultik_test + +import ( + "bytes" + "context" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestUncompressedSizeOfChangedFileStaysFixed covers +// https://git.eeqj.de/sneak/vaultik/issues/360. A backup that changes a +// file leaves the earlier snapshot's UNCOMPRESSED SIZE as it was when that +// snapshot's backup completed. The file's row in the local index is shared +// by both snapshots and rewritten by the second backup. +func TestUncompressedSizeOfChangedFileStaysFixed(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + dbPath := filepath.Join(tempDir, "index.sqlite") + changedPath := filepath.Join(dataDir, "changed.bin") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, dataDir) + cfg := changedFileConfig(dataDir, dbPath) + + appendRandomBytes(t, fs, files, changedPath, appendedFileSize) + + store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, "first")) + + // With nothing to compare against, sizeOfNewChunks totals every + // distinct chunk of the files. + firstID := localSnapshotID(ctx, t, repos, "first") + firstSize := sizeOfNewChunks(t, files, nil) + require.Equal(t, firstSize, listedUncompressedSizes(t, v)[firstID], + "the first snapshot must count the chunks of every file it holds") + + appendRandomBytes(t, fs, files, changedPath, faultChunkSize) + require.NoError(t, backUp(v, "second")) + + secondID := localSnapshotID(ctx, t, repos, "second") + sizes := listedUncompressedSizes(t, v) + assert.Equal(t, firstSize, sizes[firstID], + "a later backup must not change the first snapshot's figure") + assert.Equal(t, sizeOfNewChunks(t, files, nil), sizes[secondID], + "the second snapshot must count the changed file's chunks") +} + +// listedUncompressedSizes runs `snapshot list --json` and returns each +// listed snapshot's uncompressed_size by snapshot ID. +func listedUncompressedSizes(t *testing.T, v *vaultik.Vaultik) map[string]int64 { + t.Helper() + + var out bytes.Buffer + + v.Stdout = &out + require.NoError(t, v.ListSnapshots(true)) + + sizes := make(map[string]int64) + for _, row := range decodeListJSON(t, out.String()) { + sizes[row.ID] = row.UncompressedSize + } + + return sizes +} From 25ee9211d3dbd285ee266a1c1079996145b0bad9 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 21:11:11 +0200 Subject: [PATCH 065/121] Limit and retry the module download in the Docker build (closes #351) Each `go mod download` in the Dockerfile now runs under a five-minute time limit and is tried up to three times. Without a limit, a stalled connection to the module proxy held the step, and every build on the host sharing it, until the kernel dropped the connection. Five minutes is well above the three minutes a working download can take on a busy build host. When all three attempts fail, the step prints "module download failed" and exits 1, so the build stops there instead of failing as a test or lint failure. A test checks every download step for the limit, the retries, the message and the final `exit 1`. Model: opus-5-5 --- Dockerfile | 27 ++++++++++++++-- cmd/vaultik/dockermoddownload_test.go | 45 +++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 3 deletions(-) create mode 100644 cmd/vaultik/dockermoddownload_test.go diff --git a/Dockerfile b/Dockerfile index b769346..c60db2c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,16 @@ FROM golangci/golangci-lint:v2.14.0@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f AS lint WORKDIR /src COPY go.mod go.sum ./ -RUN go mod download +# Without the time limit a stalled connection to the module proxy holds +# this step, and every build on the host sharing it, until the kernel +# drops the connection, which can take an hour. The limit is well above +# the three minutes a working download can take on a busy build host. +RUN for attempt in 1 2 3; do \ + timeout 300 go mod download && exit 0; \ + echo "go mod download attempt $attempt failed or ran over 300s" >&2; \ + done; \ + echo "module download failed: giving up after 3 attempts" >&2; \ + exit 1 COPY . . # `golangci-lint run` silently ignores an unknown top-level key in # .golangci.yml, such as a misspelt `linters:`; `config verify` fails on it. @@ -18,7 +27,13 @@ RUN golangci-lint run --config .golangci.yml ./... FROM golang:1.26.1@sha256:cd78d88e00afadbedd272f977d375a6247455f3a4b1178f8ae8bbcb201743a8a AS test WORKDIR /src COPY go.mod go.sum ./ -RUN go mod download +# Limited and retried as in the lint phase above. +RUN for attempt in 1 2 3; do \ + timeout 300 go mod download && exit 0; \ + echo "go mod download attempt $attempt failed or ran over 300s" >&2; \ + done; \ + echo "module download failed: giving up after 3 attempts" >&2; \ + exit 1 COPY . . RUN go test -timeout 90s -race -cover ./... || \ { echo "--- Rerunning with -v for details ---"; \ @@ -36,7 +51,13 @@ RUN apk add --no-cache git RUN git config --system --add safe.directory /src WORKDIR /src COPY go.mod go.sum ./ -RUN go mod download +# Limited and retried as in the lint phase above. +RUN for attempt in 1 2 3; do \ + timeout 300 go mod download && exit 0; \ + echo "go mod download attempt $attempt failed or ran over 300s" >&2; \ + done; \ + echo "module download failed: giving up after 3 attempts" >&2; \ + exit 1 COPY . . # The VERSION build arg when one is given, otherwise diff --git a/cmd/vaultik/dockermoddownload_test.go b/cmd/vaultik/dockermoddownload_test.go new file mode 100644 index 0000000..da9b704 --- /dev/null +++ b/cmd/vaultik/dockermoddownload_test.go @@ -0,0 +1,45 @@ +package main_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestDockerfileBoundsEveryModuleDownload fails unless every +// `go mod download` in the Dockerfile runs under a time limit, is tried +// a fixed number of times, and then fails the build with a message that +// names the module download (issue #351). Like the version tests, this +// parses the Dockerfile; that a stalled download really is cut off and +// retried was checked by hand. +func TestDockerfileBoundsEveryModuleDownload(t *testing.T) { + t.Parallel() + + var downloads []string + + for _, instruction := range instructions(t, productDockerfile) { + if strings.Contains(instruction, "go mod download") { + downloads = append(downloads, instruction) + } + } + + require.NotEmpty(t, downloads, "%s must download modules", + productDockerfile) + + for _, download := range downloads { + assert.Contains(t, download, "timeout 300 go mod download", + "%s: a module download must have a time limit: %s", + productDockerfile, download) + assert.Contains(t, download, "for attempt in 1 2 3", + "%s: a module download must be retried: %s", + productDockerfile, download) + assert.Contains(t, download, "module download failed", + "%s: a module download that never succeeds must say so: %s", + productDockerfile, download) + assert.True(t, strings.HasSuffix(download, "exit 1"), + "%s: a module download that never succeeds must fail the"+ + " build: %s", productDockerfile, download) + } +} From 42eb50b151a00bd2ac451fa6baf49be6bf025fd3 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 21:26:55 +0200 Subject: [PATCH 066/121] Report blob counts from snapshot verify --deep --json (closes #314) Deep verify set verified only on success and never set missing, so a failed --deep --json run reported zero for both. It now counts each blob whose contents pass, and its existence check covers every blob, counting not-found ones as missing and wrong-size ones as mismatched, as shallow verify does; it fails if it found any. Any other storage error stops the check and fails with that error, so a blob that cannot be checked is never reported as missing. Deep verify still stops at the first damaged blob and reads no contents while any blob is missing or the wrong size, so verified is 0 there. Model: opus-5-5 --- internal/vaultik/deep_verify_test.go | 172 +++++++++++++++++++++++++++ internal/vaultik/verify.go | 56 ++++++--- 2 files changed, 211 insertions(+), 17 deletions(-) diff --git a/internal/vaultik/deep_verify_test.go b/internal/vaultik/deep_verify_test.go index 6c7d782..0592935 100644 --- a/internal/vaultik/deep_verify_test.go +++ b/internal/vaultik/deep_verify_test.go @@ -1,7 +1,9 @@ package vaultik_test import ( + "bytes" "context" + "crypto/rand" "io" "os" "path/filepath" @@ -9,7 +11,9 @@ import ( "github.com/spf13/afero" "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" "sneak.berlin/go/vaultik/internal/ui" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -77,6 +81,174 @@ func TestDeepVerifyAcceptsHealthyAndRejectsCorruptBlob(t *testing.T) { "deep verify should fail on a corrupted blob") } +// TestDeepVerifyJSONCountsBlobs checks the verified and missing counts +// that deep verify reports under --json: on a healthy snapshot, with a +// damaged blob, and with missing blobs. Deep verify stops at the first +// damaged blob, so the blobs read before it are the ones verified; when +// blobs are missing it reads no blob contents, but counts every missing +// blob. +func TestDeepVerifyJSONCountsBlobs(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "remote") + + cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir) + + healthy, err := deepVerifyJSON(ctx, t, cfg, storer, snapshotID) + require.NoError(t, err) + require.Equal(t, "ok", healthy.Status) + require.Len(t, keys, healthy.BlobCount) + require.Equal(t, healthy.BlobCount, healthy.Verified) + require.Zero(t, healthy.Missing) + + // Damage the last blob read, keeping its length, so every blob before + // it is read and passes first. + lastPath := filepath.Join(storeDir, keys[len(keys)-1]) + blob, err := afero.ReadFile(fs, lastPath) + require.NoError(t, err) + + blob[len(blob)/2] ^= 0xff + require.NoError(t, afero.WriteFile(fs, lastPath, blob, 0o600)) + + got, err := deepVerifyJSON(ctx, t, cfg, storer, snapshotID) + require.Error(t, err) + require.Equal(t, "failed", got.Status) + require.Equal(t, healthy.BlobCount-1, got.Verified) + require.Zero(t, got.Missing) + + // Delete the first blob and the damaged last one: both must be + // counted as missing, not only the first one found. + var deletedSize int64 + + for _, key := range []string{keys[0], keys[len(keys)-1]} { + info, statErr := storer.Stat(ctx, key) + require.NoError(t, statErr) + + deletedSize += info.Size + + require.NoError(t, storer.Delete(ctx, key)) + } + + got, err = deepVerifyJSON(ctx, t, cfg, storer, snapshotID) + require.Error(t, err) + require.Equal(t, "failed", got.Status) + require.Equal(t, 2, got.Missing) + require.Equal(t, deletedSize, got.MissingSize) + require.Zero(t, got.Verified) +} + +// TestDeepVerifyJSONCountsWrongSizeBlob checks that under --deep --json a +// blob of the wrong size is counted in mismatched and fails the run, and +// that the check goes on past it to count a missing blob after it. +func TestDeepVerifyJSONCountsWrongSizeBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "remote") + + cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir) + + // Make the first blob checked longer, and delete the last one. + firstPath := filepath.Join(storeDir, keys[0]) + blob, err := afero.ReadFile(fs, firstPath) + require.NoError(t, err) + + blob = append(blob, []byte("extra")...) + require.NoError(t, afero.WriteFile(fs, firstPath, blob, 0o600)) + require.NoError(t, storer.Delete(ctx, keys[len(keys)-1])) + + got, err := deepVerifyJSON(ctx, t, cfg, storer, snapshotID) + require.Error(t, err) + require.Equal(t, "failed", got.Status) + require.Equal(t, 1, got.Mismatched) + require.Equal(t, 1, got.Missing) + require.Zero(t, got.Verified) +} + +// TestDeepVerifyStopsOnBlobThatCannotBeChecked checks that a blob that is +// present in storage but cannot be checked is not counted as missing: +// deep verify stops and fails with the storage error. +func TestDeepVerifyStopsOnBlobThatCannotBeChecked(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "remote") + + cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir) + failing := statFailingStorer{Storer: storer, failKeys: []string{keys[0]}} + + got, err := deepVerifyJSON(ctx, t, cfg, failing, snapshotID) + require.Error(t, err) + require.Equal(t, "failed", got.Status) + require.Zero(t, got.Missing) + require.Contains(t, got.ErrorMessage, errStatDenied.Error()) +} + +// backUpSeveralBlobs backs up random data, which does not compress or +// deduplicate, so it fills at least three blobs in a store on disk at +// storeDir. It returns the blobs' storage keys sorted, which is hash +// order, the order deep verify reads them in. +func backUpSeveralBlobs( + ctx context.Context, t *testing.T, storeDir string, +) (*config.Config, *storage.FileStorer, string, []string) { + t.Helper() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "source") + dbPath := filepath.Join(tempDir, "index.sqlite") + + chunkSize := int64(32 * 1024) + maxBlobSize := int64(128 * 1024) + + data := make([]byte, maxBlobSize*4) + _, err := rand.Read(data) + require.NoError(t, err) + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, "data.bin"), data, 0o644)) + + cfg, storer, snapshotID := runFileStorageBackup( + ctx, t, fs, dataDir, storeDir, dbPath, chunkSize, maxBlobSize) + + keys := storedBlobKeys(t, storeDir) + require.GreaterOrEqual(t, len(keys), 3) + + return cfg, storer, snapshotID, keys +} + +// deepVerifyJSON runs deep verify with --json on snapshotID and returns +// the decoded result and the error RunDeepVerify returned. +func deepVerifyJSON( + ctx context.Context, t *testing.T, + cfg *config.Config, storer storage.Storer, snapshotID string, +) (vaultik.VerifyResult, error) { + t.Helper() + + var out bytes.Buffer + + v := &vaultik.Vaultik{ + Config: cfg, + Storage: storer, + Fs: afero.NewOsFs(), + Stdout: &out, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + v.SetContext(ctx) + + err := v.RunDeepVerify(snapshotID, + &vaultik.VerifyOptions{Deep: true, JSON: true}) + + return decodeVerifyResult(t, out.Bytes()), err +} + // corruptOneBlob flips a middle byte of the first blob file found under // blobsDir, leaving the file length unchanged. func corruptOneBlob(t *testing.T, fs afero.Fs, blobsDir string) { diff --git a/internal/vaultik/verify.go b/internal/vaultik/verify.go index 3600208..1fd298c 100644 --- a/internal/vaultik/verify.go +++ b/internal/vaultik/verify.go @@ -17,6 +17,7 @@ import ( "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/storage" ) // Sentinel errors for snapshot verification failures. @@ -32,7 +33,9 @@ var ( errManifestExtraBlob = errors.New("manifest contains blob not in database") errManifestMissingBlob = errors.New( "manifest omits blob present in database") - errBlobSizeMismatch = errors.New("blob size mismatch") + errBlobSizeMismatch = errors.New("blob size mismatch") + errBlobsNotInStorage = errors.New( + "blobs missing from storage or stored with the wrong size") ) // verifyStatusFailed is the JSON status value for a failed verification. @@ -149,7 +152,6 @@ func (v *Vaultik) RunDeepVerify(snapshotID string, opts *VerifyOptions) error { } result.Status = "ok" - result.Verified = len(dbBlobs) if opts.JSON { return v.outputVerifyJSON(result) @@ -306,7 +308,7 @@ func (v *Vaultik) runVerificationSteps( v.stdoutf("Checking blob existence in remote storage...\n") } - err = v.verifyBlobExistenceFromDB(dbBlobs) + err = v.verifyBlobExistenceFromDB(dbBlobs, result) if err != nil { return v.deepVerifyFailure(result, opts, err.Error(), err) } @@ -317,7 +319,8 @@ func (v *Vaultik) runVerificationSteps( len(dbBlobs), ubytes(totalSize)) } - err = v.performDeepVerificationFromDB(dbBlobs, tdb.db.Conn(), opts, identities) + err = v.performDeepVerificationFromDB( + dbBlobs, tdb.db.Conn(), opts, result, identities) if err != nil { return v.deepVerifyFailure(result, opts, err.Error(), err) } @@ -669,8 +672,14 @@ func (v *Vaultik) verifyManifestAgainstDatabase( return nil } -// verifyBlobExistenceFromDB checks that all blobs from database exist in S3 -func (v *Vaultik) verifyBlobExistenceFromDB(blobs []snapshot.BlobInfo) error { +// verifyBlobExistenceFromDB checks that every blob from the database is +// in storage with the size the database records. It checks them all, +// counting the missing and wrong-size blobs in result, and fails if it +// found any. Any storage error other than not found stops the check and +// fails with that error. +func (v *Vaultik) verifyBlobExistenceFromDB( + blobs []snapshot.BlobInfo, result *VerifyResult, +) error { log.Info("Verifying blob existence in S3", "blob_count", len(blobs)) for i, blob := range blobs { @@ -683,17 +692,23 @@ func (v *Vaultik) verifyBlobExistenceFromDB(blobs []snapshot.BlobInfo) error { // Construct blob path blobPath := fmt.Sprintf("blobs/%s/%s/%s", blob.Hash[:2], blob.Hash[2:4], blob.Hash) - // Check blob exists stat, err := v.Storage.Stat(v.ctx, blobPath) - if err != nil { - return fmt.Errorf("blob %s missing from storage: %w", blob.Hash, err) - } + switch { + case errors.Is(err, storage.ErrNotFound): + log.Warn("Blob missing from storage", "hash", blob.Hash) - // Verify size matches - if stat.Size != blob.CompressedSize { - return fmt.Errorf( - "%w: blob %s: S3 has %d bytes, database has %d bytes", - errBlobSizeMismatch, blob.Hash, stat.Size, blob.CompressedSize) + result.Missing++ + result.MissingSize += blob.CompressedSize + case err != nil: + return fmt.Errorf("checking blob %s in storage: %w", + blob.Hash, err) + case stat.Size != blob.CompressedSize: + log.Warn("Blob has the wrong size in storage", + "hash", blob.Hash, + "storage_size", stat.Size, + "database_size", blob.CompressedSize) + + result.Mismatched++ } // Progress update every 100 blobs @@ -707,16 +722,22 @@ func (v *Vaultik) verifyBlobExistenceFromDB(blobs []snapshot.BlobInfo) error { } } + if result.Missing > 0 || result.Mismatched > 0 { + return fmt.Errorf("%w: %d missing, %d with the wrong size", + errBlobsNotInStorage, result.Missing, result.Mismatched) + } + log.Info("✓ All blobs exist in storage") return nil } // performDeepVerificationFromDB downloads and verifies the content of -// each blob using the database as source. +// each blob using the database as source, stopping at the first blob that +// fails. Each blob that passes is counted in result.Verified. func (v *Vaultik) performDeepVerificationFromDB( blobs []snapshot.BlobInfo, db *sql.DB, opts *VerifyOptions, - identities []age.Identity, + result *VerifyResult, identities []age.Identity, ) error { // Calculate total bytes for ETA var totalBytesExpected int64 @@ -739,6 +760,7 @@ func (v *Vaultik) performDeepVerificationFromDB( return fmt.Errorf("blob %s verification failed: %w", blobInfo.Hash, err) } + result.Verified++ bytesProcessed += blobInfo.CompressedSize elapsed := time.Since(startTime) remaining := len(blobs) - (i + 1) From 5d8c515192cb098e739b1dbe3941b83e5bf6e068 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 21:36:23 +0200 Subject: [PATCH 067/121] List a file:// destination through a symlinked directory (closes #296) List and ListStream walked the destination with afero.Walk, which uses Lstat and so saw a symlinked metadata/ or blobs/ as one file, while Put, Get and Stat follow the link. The store then listed as empty, and prune dropped the local snapshot records and deleted every blob. The listings, and DeletePartialUploads (used by remote nuke), now walk a view without Lstat, so afero falls back to Stat and enters the link. A prefix lists as empty only when truly missing; a missing symlink target on it or above it, such as an unmounted volume, fails the listing. Judgement call: a symlink loop is not detected; it is followed until the system refuses the path, and the listing fails. Model: opus-5-5 --- internal/storage/file.go | 76 +++++- internal/storage/file_backend_test.go | 232 ++++++++++++++++++ .../vaultik/symlinked_destination_test.go | 147 +++++++++++ 3 files changed, 442 insertions(+), 13 deletions(-) create mode 100644 internal/vaultik/symlinked_destination_test.go diff --git a/internal/storage/file.go b/internal/storage/file.go index 7bb74d1..83769a6 100644 --- a/internal/storage/file.go +++ b/internal/storage/file.go @@ -120,9 +120,10 @@ func (f *FileStorer) Delete(_ context.Context, key string) error { return nil } -// List returns all keys with the given prefix. It fails when the -// destination directory is missing; a missing prefix under it is an -// empty listing. +// List returns all keys with the given prefix, reading through symlinked +// directories. It fails when the destination directory is missing, or +// when the prefix or a directory above it is a symlink whose target is +// missing; a prefix that is truly missing is an empty listing. func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error) { var keys []string @@ -133,8 +134,7 @@ func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error) basePath := f.fullPath(prefix) - // Check if the prefix exists - exists, err := afero.Exists(f.fs, basePath) + exists, err := f.prefixExists(prefix) if err != nil { return nil, fmt.Errorf("checking path: %w", err) } @@ -143,7 +143,7 @@ func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error) return keys, nil // Empty list for non-existent prefix } - err = afero.Walk(f.fs, basePath, func(path string, info os.FileInfo, err error) error { + err = f.walk(basePath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } @@ -176,7 +176,9 @@ func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error) } // ListStream returns a channel of ObjectInfo for large result sets. Like -// List, it sends an error when the destination directory is missing. +// List, it reads through symlinked directories and sends an error when +// the destination directory is missing, or when the prefix or a directory +// above it is a symlink whose target is missing. func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan ObjectInfo { ch := make(chan ObjectInfo) @@ -192,8 +194,7 @@ func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan Objec basePath := f.fullPath(prefix) - // Check if the prefix exists - exists, err := afero.Exists(f.fs, basePath) + exists, err := f.prefixExists(prefix) if err != nil { ch <- ObjectInfo{Err: fmt.Errorf("checking path: %w", err)} @@ -204,7 +205,7 @@ func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan Objec return // Empty channel for non-existent prefix } - _ = afero.Walk(f.fs, basePath, func(path string, info os.FileInfo, err error) error { + _ = f.walk(basePath, func(path string, info os.FileInfo, err error) error { // Check context cancellation select { case <-ctx.Done(): @@ -243,11 +244,12 @@ func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan Objec } // DeletePartialUploads removes every file under prefix whose name ends in -// tempSuffix. A missing prefix has none to remove. +// tempSuffix. Like List, it reads through symlinked directories and fails +// on one whose target is missing. A missing prefix has none to remove. func (f *FileStorer) DeletePartialUploads(ctx context.Context, prefix string) error { basePath := f.fullPath(prefix) - exists, err := afero.Exists(f.fs, basePath) + exists, err := f.prefixExists(prefix) if err != nil { return fmt.Errorf("checking path: %w", err) } @@ -256,7 +258,7 @@ func (f *FileStorer) DeletePartialUploads(ctx context.Context, prefix string) er return nil } - err = afero.Walk(f.fs, basePath, func(path string, info os.FileInfo, err error) error { + err = f.walk(basePath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } @@ -352,6 +354,54 @@ func (f *FileStorer) writeAtomic( return nil } +// walk is afero.Walk, except that it reads through a symlinked directory +// the way Get and Stat do, where afero.Walk reports the link as one file. +// afero.Walk uses Lstat, which does not follow a link, whenever the +// filesystem has one; the struct below carries only the afero.Fs methods, +// so the walk uses Stat instead. A link back up the tree is followed until +// the operating system refuses the path for too many levels of links, and +// the walk then fails. +func (f *FileStorer) walk(root string, fn filepath.WalkFunc) error { + return afero.Walk(struct{ afero.Fs }{f.fs}, root, fn) +} + +// prefixExists reports whether prefix exists under the destination +// directory. It checks each directory on the way down to prefix in turn, +// and the first one Stat cannot find decides: if it is not there at all, +// prefix is missing; if it is a symlink whose target is missing, such as +// a link to a volume that is not mounted, prefixExists fails, since +// listing it as empty would let prune delete every blob. +func (f *FileStorer) prefixExists(prefix string) (bool, error) { + lstater, canLstat := f.fs.(afero.Lstater) + path := f.basePath + + for name := range strings.SplitSeq(prefix, "/") { + path = filepath.Join(path, name) + + _, err := f.fs.Stat(path) + if err == nil { + continue + } + + if !os.IsNotExist(err) { + return false, err + } + + // Lstat does not follow a symlink at path, so it finds the link + // that Stat could not follow. + if canLstat { + _, _, lstatErr := lstater.LstatIfPossible(path) + if lstatErr == nil { + return false, err + } + } + + return false, nil + } + + return true, nil +} + // fullPath returns the full filesystem path for a key. func (f *FileStorer) fullPath(key string) string { return filepath.Join(f.basePath, key) diff --git a/internal/storage/file_backend_test.go b/internal/storage/file_backend_test.go index f92331e..ec84910 100644 --- a/internal/storage/file_backend_test.go +++ b/internal/storage/file_backend_test.go @@ -4,7 +4,10 @@ import ( "context" "errors" "io/fs" + "os" "path/filepath" + "reflect" + "strings" "testing" "sneak.berlin/go/vaultik/internal/storage" @@ -60,3 +63,232 @@ func TestFileStorerListMissingDestination(t *testing.T) { t.Errorf("ListStream error = %v, want a not-exist error", streamErr) } } + +// The two directories at the top of a destination, either of which the +// tests below replace with a symlink. +const ( + metadataDir = "metadata" + blobsDir = "blobs" +) + +// moveBehindSymlink moves base/dir to a directory elsewhere and puts a +// symlink to it in its place. +func moveBehindSymlink(t *testing.T, base, dir string) { + t.Helper() + + linkPath := filepath.Join(base, dir) + movedPath := filepath.Join(t.TempDir(), dir) + + err := os.Rename(linkPath, movedPath) + if err != nil { + t.Fatalf("moving %s away: %v", dir, err) + } + + err = os.Symlink(movedPath, linkPath) + if err != nil { + t.Fatalf("linking %s: %v", dir, err) + } +} + +// TestFileStorerListsThroughSymlinkedDirectory checks that List and +// ListStream read through a symlinked metadata/ or blobs/ directory, as Get +// and Stat do, instead of listing the link as one key. Listing the whole +// destination meets the link part-way through the walk; listing its prefix +// starts the walk at the link. A prefix missing behind the link lists as +// empty. +func TestFileStorerListsThroughSymlinkedDirectory(t *testing.T) { + t.Parallel() + + for _, dir := range []string{metadataDir, blobsDir} { + t.Run(dir, func(t *testing.T) { + t.Parallel() + + base := t.TempDir() + key := dir + "/aa/bb/object" + + s, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + err = s.Put(context.Background(), key, strings.NewReader("data")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + moveBehindSymlink(t, base, dir) + + want := []string{key} + + for _, prefix := range []string{"", dir + "/"} { + got := listSorted(t, s, prefix) + if !reflect.DeepEqual(got, want) { + t.Errorf("List(%q) = %v, want %v", prefix, got, want) + } + + got = listStreamKeys(t, s, prefix) + if !reflect.DeepEqual(got, want) { + t.Errorf("ListStream(%q) = %v, want %v", prefix, got, want) + } + } + + absent := dir + "/absent/" + + if got := listSorted(t, s, absent); len(got) != 0 { + t.Errorf("List(%q) = %v, want empty", absent, got) + } + + if got := listStreamKeys(t, s, absent); len(got) != 0 { + t.Errorf("ListStream(%q) = %v, want empty", absent, got) + } + }) + } +} + +// TestFileStorerListFailsOnSymlinkWithMissingTarget checks that List and +// ListStream fail on a symlinked metadata/ or blobs/ directory whose target +// is missing, such as a link to a volume that is not mounted, as they do on +// a missing destination directory, instead of listing it as empty. That +// holds for a prefix below the link too. +func TestFileStorerListFailsOnSymlinkWithMissingTarget(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + for _, dir := range []string{metadataDir, blobsDir} { + t.Run(dir, func(t *testing.T) { + t.Parallel() + + base := t.TempDir() + + s, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + unmounted := filepath.Join(t.TempDir(), "unmounted") + + err = os.Symlink(unmounted, filepath.Join(base, dir)) + if err != nil { + t.Fatalf("Symlink: %v", err) + } + + for _, prefix := range []string{"", dir + "/", dir + "/aa/"} { + keys, err := s.List(ctx, prefix) + if !errors.Is(err, fs.ErrNotExist) { + t.Errorf("List(%q) = %v, %v; want a not-exist error", + prefix, keys, err) + } + + var streamErr error + + for object := range s.ListStream(ctx, prefix) { + if object.Err != nil { + streamErr = object.Err + } + } + + if !errors.Is(streamErr, fs.ErrNotExist) { + t.Errorf("ListStream(%q) error = %v, want a not-exist error", + prefix, streamErr) + } + } + }) + } +} + +// TestFileStorerListFailsOnSymlinkLoop checks that a symlink pointing back +// at the destination makes List and ListStream fail instead of walking it +// forever. +func TestFileStorerListFailsOnSymlinkLoop(t *testing.T) { + t.Parallel() + + ctx := context.Background() + base := t.TempDir() + + s, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + err = s.Put(ctx, testBlobKey, strings.NewReader("data")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + err = os.Symlink(base, filepath.Join(base, "blobs", "loop")) + if err != nil { + t.Fatalf("Symlink: %v", err) + } + + keys, err := s.List(ctx, "blobs/") + if err == nil { + t.Errorf("List = %d keys and no error, want an error", len(keys)) + } + + var streamErr error + + for object := range s.ListStream(ctx, "blobs/") { + if object.Err != nil { + streamErr = object.Err + } + } + + if streamErr == nil { + t.Error("ListStream sent no error, want one") + } +} + +// TestFileStorerDeletePartialUploadsThroughSymlinkedDirectory checks that +// DeletePartialUploads, which remote nuke uses, removes a leftover temp +// file behind a symlinked metadata/ or blobs/ directory and keeps the +// object at the real key. +func TestFileStorerDeletePartialUploadsThroughSymlinkedDirectory(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + for _, dir := range []string{metadataDir, blobsDir} { + t.Run(dir, func(t *testing.T) { + t.Parallel() + + base := t.TempDir() + key := dir + "/aa/bb/object" + + s, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + err = s.Put(ctx, key, strings.NewReader("data")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + leftover := filepath.Join(base, key+"-123456.partial") + + err = os.WriteFile(leftover, []byte("half"), 0o600) + if err != nil { + t.Fatalf("writing leftover temp file: %v", err) + } + + moveBehindSymlink(t, base, dir) + + err = s.DeletePartialUploads(ctx, dir+"/") + if err != nil { + t.Fatalf("DeletePartialUploads: %v", err) + } + + // leftover runs through the link. + _, err = os.Stat(leftover) + if !os.IsNotExist(err) { + t.Errorf("leftover temp file was not removed: %v", err) + } + + _, err = s.Stat(ctx, key) + if err != nil { + t.Errorf("Stat of the real key: %v", err) + } + }) + } +} diff --git a/internal/vaultik/symlinked_destination_test.go b/internal/vaultik/symlinked_destination_test.go new file mode 100644 index 0000000..934ca00 --- /dev/null +++ b/internal/vaultik/symlinked_destination_test.go @@ -0,0 +1,147 @@ +package vaultik_test + +import ( + "context" + "io/fs" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestPruneDeletesNothingThroughSymlinkedDirectory checks that prune keeps +// every blob and the local snapshot record when the metadata/ or blobs/ +// directory of a file:// destination is a symlink to a directory elsewhere +// (https://git.eeqj.de/sneak/vaultik/issues/296). A backup writes through +// such a link, so prune has to list through it too. +func TestPruneDeletesNothingThroughSymlinkedDirectory(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + for _, dir := range []string{"metadata", "blobs"} { + t.Run(dir, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + blobFiles := blobFilesIn(t, storeDir) + moveBehindSymlink(t, storeDir, dir) + + require.NoError(t, v.Prune(&vaultik.PruneOptions{Force: true})) + + // When blobs/ is the link, these paths run through it. + for _, blobFile := range blobFiles { + assert.FileExists(t, blobFile, "prune must delete no blob") + } + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "prune must delete no local snapshot record") + }) + } +} + +// TestPruneFailsOnSymlinkedDirectoryWithMissingTarget checks that prune +// fails, deleting no blob and keeping the local snapshot record, when the +// metadata/ or blobs/ directory of a file:// destination is a symlink +// whose target is missing, as a link to a volume that is not mounted is. +func TestPruneFailsOnSymlinkedDirectoryWithMissingTarget(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + for _, dir := range []string{"metadata", "blobs"} { + t.Run(dir, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + blobFiles := blobFilesIn(t, storeDir) + targetPath := moveBehindSymlink(t, storeDir, dir) + + // Unmount the volume the link points to, and mount it again + // once prune has run. + unmountedPath := targetPath + "-unmounted" + require.NoError(t, os.Rename(targetPath, unmountedPath)) + + err := v.Prune(&vaultik.PruneOptions{Force: true}) + require.ErrorIs(t, err, fs.ErrNotExist) + + require.NoError(t, os.Rename(unmountedPath, targetPath)) + + // When blobs/ is the link, these paths run through it. + for _, blobFile := range blobFiles { + assert.FileExists(t, blobFile, "prune must delete no blob") + } + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "prune must delete no local snapshot record") + }) + } +} + +// TestRemoveSnapshotWarnsOnSymlinkedMetadataWithMissingTarget checks that +// snapshot remove warns that the metadata could not be removed from the +// destination when metadata/ is a symlink whose target is missing, as it +// does when the destination directory is missing, instead of finding no +// metadata to remove. +func TestRemoveSnapshotWarnsOnSymlinkedMetadataWithMissingTarget(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, repos, out := backUpToFileDestination(ctx, t, storeDir) + targetPath := moveBehindSymlink(t, storeDir, "metadata") + require.NoError(t, os.Rename(targetPath, targetPath+"-unmounted")) + + result, err := v.RemoveSnapshot(localSnapshotID(ctx, t, repos, "first"), + &vaultik.RemoveOptions{Force: true}) + require.NoError(t, err) + + assert.False(t, result.RemoteRemoved) + assert.Contains(t, out.String(), + "Could not remove snapshot metadata from remote") + assert.NotContains(t, out.String(), + "Removed snapshot metadata from remote storage") +} + +// blobFilesIn returns the paths of the blob files under storeDir/blobs, and +// fails the test when there are none. +func blobFilesIn(t *testing.T, storeDir string) []string { + t.Helper() + + var blobFiles []string + + err := filepath.WalkDir(filepath.Join(storeDir, "blobs"), + func(path string, entry fs.DirEntry, err error) error { + if err == nil && !entry.IsDir() { + blobFiles = append(blobFiles, path) + } + + return err + }) + require.NoError(t, err) + require.NotEmpty(t, blobFiles) + + return blobFiles +} + +// moveBehindSymlink moves storeDir/dir to a directory elsewhere, puts a +// symlink to it in its place, and returns where it went. +func moveBehindSymlink(t *testing.T, storeDir, dir string) string { + t.Helper() + + linkPath := filepath.Join(storeDir, dir) + targetPath := filepath.Join(t.TempDir(), dir) + require.NoError(t, os.Rename(linkPath, targetPath)) + require.NoError(t, os.Symlink(targetPath, linkPath)) + + return targetPath +} From f89fac34f76982962eaca31dd0ad8307606e99df Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 22:43:41 +0200 Subject: [PATCH 068/121] Make config set create a list for an index under a missing key (closes #308) `config set age_recipients.0 age1...` on a file without `age_recipients` wrote a map keyed `0`, after which no command could load the config. A missing key is now created as a list when the next path element is a number. Before writing, `config set` checks the result with the config loader, refusing only a failure the change brings in: a config that loaded must still load; one that does not (still being filled in, or with a `${...}` reference that cannot be filled in here) is checked on the changed setting alone. The new `config.Parse`, split out of `config.Load`, decodes config data, filling in references, without validating. Rule suppressed: gosec G304 where `config.Load` and the new tests read a file. Model: opus-5-5 --- README.md | 13 ++- internal/cli/config.go | 145 +++++++++++++++++++----- internal/cli/config_test.go | 216 +++++++++++++++++++++++++++++++++++- internal/config/config.go | 65 +++++++---- 4 files changed, 383 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 784afca..9d29f10 100644 --- a/README.md +++ b/README.md @@ -271,8 +271,17 @@ existing file. Created with mode `0600` since it will contain credentials. **`config set`**: Set a scalar config value by dotted YAML path (e.g. `vaultik config set compression_level 9`, `vaultik config set storage_url "file:///mnt/backups"`). Comments and -formatting in the file are preserved; intermediate maps are created as -needed. +formatting in the file are preserved. Missing keys along the path are +created: as a list when the next path element is a number (so +`vaultik config set age_recipients.0 age1...` works on a file without +`age_recipients`), otherwise as a map. If the config loads, a change +after which it would not, such as `vaultik config set compression_level 99`, +is refused and the file is left unchanged. A config that does not load, +such as the one `config init` writes before `storage_url` is set or one +with a `${ENV:...}` reference to a variable not set in this shell, is +checked one setting at a time: only a change after which the changed +setting cannot be read, such as one giving it the wrong type (a single +value where a list belongs or a word where a number belongs), is refused. **`snapshot create`**: Perform incremental backup of configured snapshots. * Optional snapshot names argument to create specific snapshots (default: all) diff --git a/internal/cli/config.go b/internal/cli/config.go index ea477bd..bedfe89 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -8,6 +8,7 @@ import ( "os/exec" "path/filepath" "reflect" + "slices" "strconv" "strings" "unicode/utf8" @@ -44,6 +45,9 @@ var ( errNeedNumericIndex = errors.New("key is a list; use a numeric index") errIndexOutOfRange = errors.New("index out of range") errNotMapOrList = errors.New("key is not a map or list") + errWouldNotLoad = errors.New( + "vaultik would not load the config after this change, " + + "so the file was not changed") ) const defaultConfigTemplate = `# vaultik configuration @@ -391,8 +395,17 @@ func newConfigSetCommand() *cobra.Command { Use: "set ", Short: "Set a config value by dotted path (e.g. compression_level 5)", Long: `Sets a scalar config value addressed by dotted YAML path and writes -the file back, preserving comments and formatting. Intermediate maps -are created as needed. +the file back, preserving comments and formatting. Missing keys along +the path are created: as a list when the next path element is a +number, otherwise as a map. + +If the config loads, a change after which it would not, such as +compression_level 99, is refused and the file is left unchanged. A +config that does not load, such as the one config init writes before +storage_url is set or one with a ${ENV:...} reference to a variable +not set here, is checked one setting at a time: only a change after +which the changed setting cannot be read, such as one giving it the +wrong type, is refused. Examples: vaultik config set storage_url "file:///mnt/backups" @@ -422,7 +435,14 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error { return err } - err = yamlPathSet(root, strings.Split(key, "."), value) + oldData, err := marshalConfigYAML(root) + if err != nil { + return fmt.Errorf("marshaling config: %w", err) + } + + keys := strings.Split(key, ".") + + err = yamlPathSet(root, keys, value) if err != nil { return err } @@ -432,6 +452,21 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error { return fmt.Errorf("marshaling config: %w", err) } + setting, err := yamlPathOnly(root, keys) + if err != nil { + return err + } + + settingData, err := marshalConfigYAML(setting) + if err != nil { + return fmt.Errorf("marshaling config: %w", err) + } + + err = checkConfigChange(oldData, data, settingData) + if err != nil { + return fmt.Errorf("%w: %w", errWouldNotLoad, err) + } + err = os.WriteFile(path, data, configFileMode) if err != nil { return fmt.Errorf("writing config file: %w", err) @@ -453,6 +488,58 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error { return nil } +// checkConfigChange returns the reason vaultik would not load newData, the +// config after a change, if the change brings that failure in. If oldData, +// the config before it, loads, the new one must load too. A config that +// does not load, such as one still being filled in or one with a ${...} +// reference that cannot be filled in here, is checked one setting at a +// time: settingData, the changed setting on its own, must decode into the +// config type. +func checkConfigChange(oldData, newData, settingData []byte) error { + oldCfg, err := config.Parse(oldData) + if err == nil && oldCfg.Validate() == nil { + newCfg, err := config.Parse(newData) + if err != nil { + return err + } + + return newCfg.Validate() + } + + _, err = config.Parse(settingData) + + return err +} + +// yamlPathOnly returns a document holding only the value at the dotted key +// path in root, inside the maps and lists that lead to it there. +func yamlPathOnly(root *yaml.Node, keys []string) (*yaml.Node, error) { + node, err := yamlPathGet(root, keys) + if err != nil { + return nil, err + } + + for i, key := range slices.Backward(keys) { + parent, err := yamlPathGet(root, keys[:i]) + if err != nil { + return nil, err + } + + if parent.Kind == yaml.SequenceNode { + node = &yaml.Node{ + Kind: yaml.SequenceNode, Content: []*yaml.Node{node}, + } + } else { + keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key} + node = &yaml.Node{ + Kind: yaml.MappingNode, Content: []*yaml.Node{keyNode, node}, + } + } + } + + return &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{node}}, nil +} + // marshalConfigYAML renders a config document tree with 2-space indentation, // matching defaultConfigTemplate. yaml.Marshal defaults to 4 spaces, which // would reindent the whole file on the first `config set` despite the promise @@ -559,8 +646,8 @@ func yamlPathGet(root *yaml.Node, keys []string) (*yaml.Node, error) { return node, nil } -// yamlPathSet navigates a dotted key path, creating intermediate maps as -// needed, and sets the final key to the given scalar value. Numeric path +// yamlPathSet navigates a dotted key path, creating missing keys as needed, +// and sets the final key to the given scalar value. Numeric path // components index into sequences; an index equal to the sequence length // appends a new element (e.g. "age_recipients.1" on a 1-element list). func yamlPathSet(root *yaml.Node, keys []string, value string) error { @@ -573,12 +660,12 @@ func yamlPathSet(root *yaml.Node, keys []string, value string) error { node = node.Content[0] } - for i, key := range keys { + for i := range keys { last := i == len(keys)-1 switch node.Kind { case yaml.MappingNode: - node = yamlSetInMapping(node, key, value, last) + node = yamlSetInMapping(node, keys, i, value, last) case yaml.SequenceNode: next, err := yamlSetInSequence(node, keys, i, value, last) if err != nil { @@ -647,14 +734,16 @@ func yamlField(typ reflect.Type, key string) (reflect.StructField, bool) { return reflect.StructField{}, false } -// yamlSetInMapping resolves (creating if needed) the value node for key -// within a mapping node, setting it to value when it is the final path -// element, and returns the node to descend into. -func yamlSetInMapping(node *yaml.Node, key, value string, last bool) *yaml.Node { +// yamlSetInMapping resolves (creating if needed) the value node for the +// path element keys[i] within a mapping node, setting it to value when it +// is the final path element, and returns the node to descend into. +func yamlSetInMapping( + node *yaml.Node, keys []string, i int, value string, last bool, +) *yaml.Node { var valueNode *yaml.Node for j := 0; j+1 < len(node.Content); j += 2 { - if node.Content[j].Value == key { + if node.Content[j].Value == keys[i] { valueNode = node.Content[j+1] break @@ -662,13 +751,8 @@ func yamlSetInMapping(node *yaml.Node, key, value string, last bool) *yaml.Node } if valueNode == nil { - keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key} - - valueNode = &yaml.Node{Kind: yaml.MappingNode} - if last { - valueNode = &yaml.Node{Kind: yaml.ScalarNode, Value: value} - } - + keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: keys[i]} + valueNode = newPathNode(keys, i, value) node.Content = append(node.Content, keyNode, valueNode) } else if last { setScalar(valueNode, value) @@ -696,12 +780,7 @@ func yamlSetInSequence( } if idx == len(node.Content) { - newNode := &yaml.Node{Kind: yaml.MappingNode} - if last { - newNode = &yaml.Node{Kind: yaml.ScalarNode, Value: value} - } - - node.Content = append(node.Content, newNode) + node.Content = append(node.Content, newPathNode(keys, i, value)) } else if last { setScalar(node.Content[idx], value) } @@ -709,6 +788,22 @@ func yamlSetInSequence( return node.Content[idx], nil } +// newPathNode returns the node to create for the missing path element +// keys[i]: the value when it is the final path element, otherwise an empty +// list when the next path element is a number and an empty map when not. +func newPathNode(keys []string, i int, value string) *yaml.Node { + if i == len(keys)-1 { + return &yaml.Node{Kind: yaml.ScalarNode, Value: value} + } + + _, err := strconv.Atoi(keys[i+1]) + if err == nil { + return &yaml.Node{Kind: yaml.SequenceNode} + } + + return &yaml.Node{Kind: yaml.MappingNode} +} + // setScalar overwrites a node in place with a plain scalar value. func setScalar(n *yaml.Node, value string) { n.Kind = yaml.ScalarNode diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go index f7b9eb2..58ce82c 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -58,14 +58,17 @@ func TestDefaultConfigTemplateParses(t *testing.T) { } } +// testRecipient is a valid age public key. +const testRecipient = "age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj" + // TestConfigSetRecipientOnFreshConfig follows the README quickstart: on the // file `config init` writes, `config set age_recipients.0` and // `config set storage_url` give a config that loads with that recipient. +// Neither is refused, although the config does not load until both are set; +// once it loads, a recipient that is not a valid key is. func TestConfigSetRecipientOnFreshConfig(t *testing.T) { t.Parallel() - const recipient = "age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj" - path := filepath.Join(t.TempDir(), "config.yml") err := os.WriteFile(path, []byte(defaultConfigTemplate), configFileMode) @@ -75,7 +78,7 @@ func TestConfigSetRecipientOnFreshConfig(t *testing.T) { out := ui.NewWithColor(&bytes.Buffer{}, false) - err = writeConfigSet(out, path, "age_recipients.0", recipient) + err = writeConfigSet(out, path, "age_recipients.0", testRecipient) if err != nil { t.Fatalf("config set age_recipients.0: %v", err) } @@ -90,8 +93,211 @@ func TestConfigSetRecipientOnFreshConfig(t *testing.T) { t.Fatalf("config.Load: %v", err) } - if len(cfg.AgeRecipients) != 1 || cfg.AgeRecipients[0] != recipient { - t.Errorf("age_recipients = %v, want [%s]", cfg.AgeRecipients, recipient) + if len(cfg.AgeRecipients) != 1 || cfg.AgeRecipients[0] != testRecipient { + t.Errorf("age_recipients = %v, want [%s]", cfg.AgeRecipients, testRecipient) + } + + err = writeConfigSet(out, path, "age_recipients.0", "notakey") + if err == nil || !strings.Contains(err.Error(), "not a valid recipient") { + t.Errorf("config set age_recipients.0 notakey gives error %v, "+ + "want one saying it is not a valid recipient", err) + } + + _, err = config.Load(path) + if err != nil { + t.Errorf("config.Load after the refused change: %v", err) + } +} + +// configWithoutRecipients loads, but has no age_recipients key and no +// snapshot named work. +const configWithoutRecipients = `storage_url: file:///mnt/backups +snapshots: + home: + paths: + - "~" +` + +// configWithUnsetReference loads only where VAULTIK_TEST_UNSET_SECRET is +// set, as a backup job's environment might set it. No test sets it. +const configWithUnsetReference = configWithoutRecipients + `s3: + secret_access_key: ${ENV:VAULTIK_TEST_UNSET_SECRET} +` + +// configWithLevelReference returns configWithoutRecipients with a ${FILE:...} +// reference on compression_level to a file holding 9, so that the config +// loads once the reference is filled in. +func configWithLevelReference(t *testing.T) string { + t.Helper() + + levelPath := filepath.Join(t.TempDir(), "level") + + err := os.WriteFile(levelPath, []byte("9"), configFileMode) + if err != nil { + t.Fatalf("write level: %v", err) + } + + return configWithoutRecipients + + "compression_level: ${FILE:" + levelPath + "}\n" +} + +// TestConfigSetIndexUnderMissingKey checks that a list index under a key +// the file does not have creates a list, and that the result loads. +func TestConfigSetIndexUnderMissingKey(t *testing.T) { + t.Parallel() + + tests := []struct { + key string + value string + field func(cfg *config.Config) []string + }{ + {"age_recipients.0", testRecipient, + func(cfg *config.Config) []string { return cfg.AgeRecipients }}, + {"snapshots.work.paths.0", "/srv/work", + func(cfg *config.Config) []string { return cfg.Snapshots["work"].Paths }}, + } + + for _, tt := range tests { + t.Run(tt.key, func(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(configWithoutRecipients), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, tt.key, tt.value) + if err != nil { + t.Fatalf("config set %s: %v", tt.key, err) + } + + cfg, err := config.Load(path) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + + got := tt.field(cfg) + if len(got) != 1 || got[0] != tt.value { + t.Errorf("%s gives %v, want [%s]", tt.key, got, tt.value) + } + }) + } +} + +// TestConfigSetKeepsFileThatWouldNotLoad checks that config set refuses a +// change after which the config would not load, with an error giving the +// reason, and leaves the file as it was. On the file `config init` writes, +// which does not load until storage_url is set, and on one that cannot be +// read here, only a value of the wrong type is refused. +func TestConfigSetKeepsFileThatWouldNotLoad(t *testing.T) { + t.Parallel() + + levelReference := configWithLevelReference(t) + + tests := []struct { + config string + key string + value string + reason string + }{ + // Index 1 of the empty list the missing key gives. + {configWithoutRecipients, "age_recipients.1", testRecipient, + "index out of range"}, + // A list set to a single value. + {configWithoutRecipients, "snapshots.home.paths", "/srv", + "into []string"}, + {configWithoutRecipients, "chunk_size", "fast", + "invalid size format"}, + // Values of the right type that fail validation. + {configWithoutRecipients, "compression_level", "99", + "compression_level must be between 1 and 19"}, + {configWithoutRecipients, "chunk_size", "1KB", + "chunk_size must be at least 1MB"}, + // With its reference filled in, the config loads. + {levelReference, "blob_size_limit", "1MB", + "blob_size_limit must be at least"}, + // The type check on a config that does not load yet. + {defaultConfigTemplate, "snapshots.apps.paths", "/srv", + "into []string"}, + // The type check on a config that cannot be read here. + {configWithUnsetReference, "snapshots.home.paths", "/x", + "cannot unmarshal !!str `/x`"}, + } + + for _, tt := range tests { + t.Run(tt.key+" "+tt.value, func(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(tt.config), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, tt.key, tt.value) + if err == nil || !strings.Contains(err.Error(), tt.reason) { + t.Errorf("config set %s %s gives error %v, want one saying %q", + tt.key, tt.value, err, tt.reason) + } + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("read config: %v", err) + } + + if string(data) != tt.config { + t.Errorf("config set %s changed the file to:\n%s", + tt.key, data) + } + }) + } +} + +// TestConfigSetRefusesOnlyItsOwnFailure checks that setting another key +// works on a config with a ${...} reference on compression_level, which +// loads because loading fills the reference in, on one whose +// compression_level already fails to load, and on one with a reference +// that cannot be filled in here. +func TestConfigSetRefusesOnlyItsOwnFailure(t *testing.T) { + t.Parallel() + + configs := map[string]string{ + "reference": configWithLevelReference(t), + "failing": configWithoutRecipients + "compression_level: fast\n", + "unset reference": configWithUnsetReference, + } + + for name, configYAML := range configs { + t.Run(name, func(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(configYAML), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, "hostname", "myhost") + if err != nil { + t.Fatalf("config set hostname: %v", err) + } + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("read config: %v", err) + } + + if !strings.Contains(string(data), "hostname: myhost") { + t.Errorf("config set hostname wrote:\n%s", data) + } + }) } } diff --git a/internal/config/config.go b/internal/config/config.go index eb51263..c9dd2ec 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -4,6 +4,7 @@ package config import ( + "bytes" "errors" "fmt" "os" @@ -233,14 +234,48 @@ func New(path Path) (*Config, error) { return cfg, nil } -// Load reads and parses the configuration file from the specified path. -// It applies default values for optional fields, performs environment variable -// substitution using smartconfig, and validates the configuration. -// The configuration file should be in YAML format. Returns an error if the file -// cannot be read, parsed, or if validation fails. +// Load reads the configuration file at path, parses it with Parse, warns +// when others can read the file, and validates the configuration. +// Returns an error if the file cannot be read, parsed, or if validation +// fails. func Load(path string) (*Config, error) { + data, err := os.ReadFile(path) //nolint:gosec // G304: config path is operator-supplied + if err != nil { + return nil, fmt.Errorf("failed to load config file: %w", err) + } + + cfg, err := Parse(data) + if err != nil { + return nil, err + } + + // Check config file permissions (warn if world or group readable) + //nolint:gosec // G703: config path is operator-supplied by design + info, statErr := os.Stat(path) + if statErr == nil { + mode := info.Mode().Perm() + if mode&0044 != 0 { // group or world readable + log.Warn(cfg.readableByOthersWarning(), + "path", path, + "mode", fmt.Sprintf("%04o", mode), + "recommendation", "chmod 600 "+path) + } + } + + err = cfg.Validate() + if err != nil { + return nil, fmt.Errorf("invalid config: %w", err) + } + + return cfg, nil +} + +// Parse reads YAML config data as Load does, without validating it. It +// applies default values for optional fields, fills in ${...} references +// using smartconfig, and expands ~ in paths. +func Parse(data []byte) (*Config, error) { // Load config using smartconfig for interpolation - sc, err := smartconfig.NewFromConfigPath(path) + sc, err := smartconfig.NewFromReader(bytes.NewReader(data)) if err != nil { return nil, fmt.Errorf("failed to load config file: %w", err) } @@ -302,24 +337,6 @@ func Load(path string) (*Config, error) { cfg.S3.Region = "us-east-1" } - // Check config file permissions (warn if world or group readable) - //nolint:gosec // G703: config path is operator-supplied by design - info, statErr := os.Stat(path) - if statErr == nil { - mode := info.Mode().Perm() - if mode&0044 != 0 { // group or world readable - log.Warn(cfg.readableByOthersWarning(), - "path", path, - "mode", fmt.Sprintf("%04o", mode), - "recommendation", "chmod 600 "+path) - } - } - - err = cfg.Validate() - if err != nil { - return nil, fmt.Errorf("invalid config: %w", err) - } - return cfg, nil } From 37d525c3229cf069c75a183ac2e9c32aa4a59b41 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 22:50:09 +0200 Subject: [PATCH 069/121] Make remote nuke delete every object under metadata/ and blobs/ (closes #291) remote nuke deleted only the snapshot metadata and blobs the snapshot and blob listings recognise, so a snapshot's database whose manifest was never uploaded, and any name under blobs/ that is not a blob hash, survived while nuke reported the store empty. After removing every snapshot, nuke now deletes every object listed under metadata/ and blobs/, whatever its name, in place of the blob prune step. A delete that fails is logged and the others still run. A listing afterwards decides the result: nuke reports the store empty only when it finds nothing, and otherwise names each object left and fails. Judgement call: nuke no longer prints the blob prune summary. Model: opus-5-5 --- README.md | 11 ++-- internal/vaultik/nuke_remote_test.go | 34 ++++++++++++- internal/vaultik/prune.go | 76 ++++++++++++++++++++++------ 3 files changed, 99 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 9d29f10..080d0fb 100644 --- a/README.md +++ b/README.md @@ -422,11 +422,12 @@ under `blobs/` whose name is not a blob hash is not counted as a blob, since `prune` never deletes it. * `--json`: Output as JSON -**`remote nuke`**: Delete every snapshot's metadata and every blob from the -backup destination store, leaving the bucket prefix empty. Destructive and -irreversible. This is the single supported way to wipe the entire -destination store. If anything cannot be deleted, the command exits -non-zero; running it again deletes what is left. +**`remote nuke`**: Delete every object under `metadata/` and `blobs/` on +the backup destination store, whatever its name, leaving the bucket prefix +empty. Destructive and irreversible. This is the single supported way to +wipe the entire destination store. If a listing afterwards still finds +anything there, the command names each object left and exits non-zero; +running it again deletes what is left. * `--force`: Required to confirm destruction. **`database delete`**: Delete the local SQLite state database file diff --git a/internal/vaultik/nuke_remote_test.go b/internal/vaultik/nuke_remote_test.go index 701b0a5..04addda 100644 --- a/internal/vaultik/nuke_remote_test.go +++ b/internal/vaultik/nuke_remote_test.go @@ -18,7 +18,8 @@ import ( // TestNukeRemoteLeavesNoFiles checks that remote nuke leaves no file // under a file:// destination, including the `.partial` files uploads // killed part-way leave next to a snapshot's metadata and next to where a -// blob would have been. +// blob would have been, a snapshot's database whose manifest was never +// uploaded, and a file under blobs/ whose name is not a blob hash. func TestNukeRemoteLeavesNoFiles(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -38,6 +39,9 @@ func TestNukeRemoteLeavesNoFiles(t *testing.T) { "db.zst.age-123456.partial"), filepath.Join(storeDir, "blobs", hash[:2], hash[2:4], hash+"-123456.partial"), + filepath.Join(storeDir, "metadata", + snapshot.RemoteSnapshotKey("no-manifest"), "db.zst.age"), + filepath.Join(storeDir, "blobs", "0b", "01", ".DS_Store"), } for _, leftover := range leftovers { @@ -100,6 +104,34 @@ func TestNukeRemoteFailsWhenADeleteFails(t *testing.T) { } } +// TestNukeRemoteNamesWhatIsLeft checks that remote nuke, when an object +// it does not recognise cannot be deleted, does not report the store +// empty but names that object and fails. +func TestNukeRemoteNamesWhatIsLeft(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, out := backUpToFileDestination(ctx, t, storeDir) + + const leftKey = "blobs/0b/01/.DS_Store" + + leftPath := filepath.Join(storeDir, filepath.FromSlash(leftKey)) + require.NoError(t, os.MkdirAll(filepath.Dir(leftPath), 0o750)) + require.NoError(t, os.WriteFile(leftPath, []byte("finder"), 0o600)) + + store := faultstore.New(v.Storage) + store.OnDelete = func(key string) bool { return key == leftKey } + v.Storage = store + + require.Error(t, v.NukeRemote(true)) + + assert.Contains(t, out.String(), leftKey) + assert.NotContains(t, out.String(), "now empty") + assert.Contains(t, out.String(), "vaultik remote nuke --force") +} + // TestNukeRemoteRefusesAnotherDestinationWithoutRetryAdvice checks that // remote nuke, when the local index belongs to a different destination // than the configured one, fails without advising to run nuke again: diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index 7df20e1..d32f68c 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -22,6 +22,11 @@ var errNukeRequiresForce = errors.New( // errBlobDeleteFailed reports unreferenced blobs prune could not delete. var errBlobDeleteFailed = errors.New("blob(s) could not be deleted") +// errObjectsLeft reports objects remote nuke still finds on the backup +// destination store after deleting. +var errObjectsLeft = errors.New( + "object(s) still on the backup destination store") + // nukeCommandHint is the command suggested when a remote nuke could not // delete everything: running it again deletes what is left, which // `vaultik prune` does not do for snapshot metadata. @@ -35,10 +40,11 @@ const metadataDirName = "metadata" // (blobs///). const blobKeyParts = 4 -// NukeRemote deletes every snapshot's metadata and every blob from remote -// storage, along with any object an upload cut off part-way left under a -// temporary `.partial` name. After this returns successfully the bucket -// prefix is empty and the next backup starts from scratch. +// NukeRemote deletes every object under metadata/ and blobs/ in remote +// storage, whatever its name, along with any object an upload cut off +// part-way left under a temporary `.partial` name. It returns +// successfully only when a listing afterwards finds nothing left there, +// and the next backup then starts from scratch. // // Refuses to run unless force is true. The caller is responsible for // confirming with the user. @@ -68,7 +74,8 @@ func (v *Vaultik) NukeRemote(force bool) error { } // emptyDestinationStore does the deleting for NukeRemote and stops at -// the first step that fails. +// the first step that fails. It also fails when objects are still +// listed at the end, naming each one. func (v *Vaultik) emptyDestinationStore() error { v.UI.Beginf("Removing all snapshot metadata from backup destination store.") @@ -77,25 +84,62 @@ func (v *Vaultik) emptyDestinationStore() error { return fmt.Errorf("removing all snapshots: %w", err) } - v.UI.Beginf("Removing any blobs still present in backup destination store.") + v.UI.Beginf("Removing everything still present in backup destination store.") - err = v.PruneBlobs(&PruneOptions{Force: true}) - if err != nil { - return fmt.Errorf("pruning blobs: %w", err) + var left []string + + for _, prefix := range []string{"metadata/", "blobs/"} { + keys, err := v.deleteEverythingUnder(prefix) + if err != nil { + return err + } + + left = append(left, keys...) } - // The file and rclone listings skip `.partial` objects, so the two - // steps above never delete them. - for _, prefix := range []string{"metadata/", "blobs/"} { - err = v.Storage.DeletePartialUploads(v.ctx, prefix) - if err != nil { - return fmt.Errorf("deleting partial uploads: %w", err) - } + for _, key := range left { + v.UI.Warningf("Still on the backup destination store: %s", key) + } + + if len(left) > 0 { + return fmt.Errorf("%d %w", len(left), errObjectsLeft) } return nil } +// deleteEverythingUnder deletes every object under prefix, whatever its +// name, and returns the keys a listing afterwards still finds. A delete +// that fails is logged and the others still run; that object then +// shows up in the listing afterwards. +func (v *Vaultik) deleteEverythingUnder(prefix string) ([]string, error) { + keys, err := v.Storage.List(v.ctx, prefix) + if err != nil { + return nil, fmt.Errorf("listing %s: %w", prefix, err) + } + + for _, key := range keys { + err = v.Storage.Delete(v.ctx, key) + if err != nil { + log.Error("Failed to delete object", "key", key, "error", err) + } + } + + // The file and rclone listings skip `.partial` objects, so the + // deletes above never reach them. + err = v.Storage.DeletePartialUploads(v.ctx, prefix) + if err != nil { + return nil, fmt.Errorf("deleting partial uploads: %w", err) + } + + left, err := v.Storage.List(v.ctx, prefix) + if err != nil { + return nil, fmt.Errorf("listing %s: %w", prefix, err) + } + + return left, nil +} + // PruneBlobsResult contains the result of a blob prune operation // //nolint:tagliatelle // snake_case is the established JSON output format From 2c087be577cac9af4292e3472f43e55158a619a8 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 23:14:22 +0200 Subject: [PATCH 070/121] Fail restore for a requested path that matches nothing (closes #309) snapshot restore said nothing about a requested path that matched no entry in the snapshot (a typo, a relative path, or a path through a symlinked snapshot path, whose entries are stored under the resolved directory) and exited 0, even when nothing matched. Each such path is now named in a warning as soon as the file list is built, so it shows even when the restore then stops on an error, and restore returns an error after restoring the paths that do match. The restore summary moved into finishRestore to keep Restore within the length limit. Making a path through a symlink match is not part of this change. Judgement call: when the restore itself fails, that error is returned. Model: opus-5-5 --- README.md | 4 +- internal/cli/snapshot_restore.go | 2 + internal/vaultik/restore.go | 79 ++++--- .../vaultik/restore_unmatched_path_test.go | 202 ++++++++++++++++++ 4 files changed, 262 insertions(+), 25 deletions(-) create mode 100644 internal/vaultik/restore_unmatched_path_test.go diff --git a/README.md b/README.md index 080d0fb..ee375b0 100644 --- a/README.md +++ b/README.md @@ -382,7 +382,9 @@ on the destination in one go, use `vaultik remote nuke --force`. store — its remote key (or an unambiguous leading part of it) as shown by `snapshot list`. See [restoring on another machine](#restoring-on-another-machine). -* Optional path arguments to restore specific files/directories (default: all) +* Optional path arguments to restore specific files/directories (default: all). + A path that matches nothing in the snapshot is named in a warning, and the + command exits non-zero after restoring the paths that match. * Preserves file permissions, timestamps, ownership (ownership requires root), symlinks, and empty directories * `--verify`: After restoring, verify every restored file's chunk hashes diff --git a/internal/cli/snapshot_restore.go b/internal/cli/snapshot_restore.go index ce28542..8609b90 100644 --- a/internal/cli/snapshot_restore.go +++ b/internal/cli/snapshot_restore.go @@ -30,6 +30,8 @@ This command will restore files from the specified snapshot to the target directory. If no paths are specified, all files are restored. If paths are specified, only matching files/directories are restored. +A path that matches nothing in the snapshot is named in a warning, and +the command exits non-zero after restoring the paths that match. The snapshot may be named by its ID or, when restoring on a host with no local index, by the remote key that 'snapshot list' prints for a diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index 565883a..9b114ee 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -27,6 +27,7 @@ import ( // Sentinel errors for restore failures. var ( errFilesFailedRestore = errors.New("file(s) failed to restore") + errPathsNotInSnapshot = errors.New("requested path(s) not in the snapshot") errFilesFailedVerify = errors.New("files failed verification") errDecryptionKeyRequired = errors.New( "decryption key required for restore\n\n" + @@ -150,16 +151,20 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error { repos := database.NewRepositories(tempDB) // Step 2: Get list of files to restore - files, err := v.getFilesToRestore(v.ctx, repos, opts.Paths) + files, unmatched, err := v.getFilesToRestore(v.ctx, repos, opts.Paths) if err != nil { return fmt.Errorf("getting files to restore: %w", err) } + // Named before anything is restored, so the names are shown even + // when the restore stops on an error. + unmatchedErr := v.reportUnmatchedPaths(unmatched) + if len(files) == 0 { log.Warn("No files found to restore") v.UI.Warningf("No files found to restore.") - return nil + return unmatchedErr } log.Info("Found files to restore", "count", len(files)) @@ -185,6 +190,20 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error { result.Duration = time.Since(startTime) + return v.finishRestore(repos, files, unmatchedErr, opts, result) +} + +// finishRestore prints the restore summary and the post-restore +// warnings, runs optional verification, and converts any failed-file +// count into an error. Otherwise it returns unmatchedErr, the error for +// the requested paths that matched nothing (nil when there are none). +func (v *Vaultik) finishRestore( + repos *database.Repositories, + files []*database.File, + unmatchedErr error, + opts *RestoreOptions, + result *RestoreResult, +) error { log.Info("Restore complete", "files_restored", result.FilesRestored, "bytes_restored", ubytes(result.BytesRestored), @@ -199,17 +218,6 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error { v.UI.Duration(result.Duration), ) - return v.finishRestore(repos, files, opts, result) -} - -// finishRestore emits the post-restore warnings, runs optional -// verification, and converts any failed-file count into an error. -func (v *Vaultik) finishRestore( - repos *database.Repositories, - files []*database.File, - opts *RestoreOptions, - result *RestoreResult, -) error { if os.Geteuid() != 0 { v.UI.Warningf("Restore did not preserve file ownership: chown(2) " + "requires root. Re-run as root (e.g. with sudo) if you need " + @@ -236,7 +244,23 @@ func (v *Vaultik) finishRestore( return fmt.Errorf("%d %w", result.FilesFailed, errFilesFailedRestore) } - return nil + return unmatchedErr +} + +// reportUnmatchedPaths warns, by name, about each requested path that +// matched nothing in the snapshot, and returns an error counting them, +// or nil when there are none. +func (v *Vaultik) reportUnmatchedPaths(unmatched []string) error { + if len(unmatched) == 0 { + return nil + } + + for _, path := range unmatched { + log.Warn("Requested path matches nothing in the snapshot", "path", path) + v.UI.Warningf("%s matches nothing in the snapshot.", v.UI.Path(path)) + } + + return fmt.Errorf("%d %w", len(unmatched), errPathsNotInSnapshot) } // restoreIdentities parses the configured age secret key once into every @@ -840,27 +864,34 @@ func (v *Vaultik) materializeSnapshotDB( return db, tempDir, nil } -// getFilesToRestore returns the list of files to restore based on path filters +// getFilesToRestore returns the list of files to restore based on path +// filters, and the filters, as given, that matched no file. func (v *Vaultik) getFilesToRestore( ctx context.Context, repos *database.Repositories, pathFilters []string, -) ([]*database.File, error) { +) ([]*database.File, []string, error) { // If no filters, get all files if len(pathFilters) == 0 { - return repos.Files.ListAll(ctx) + files, err := repos.Files.ListAll(ctx) + + return files, nil, err } // Get files matching the path filters - var result []*database.File + var ( + result []*database.File + unmatched []string + ) seen := make(map[string]bool) for _, filter := range pathFilters { - // Normalize the filter path - filter = filepath.Clean(filter) - - files, err := repos.Files.ListUnderPath(ctx, filter) + files, err := repos.Files.ListUnderPath(ctx, filepath.Clean(filter)) if err != nil { - return nil, fmt.Errorf("listing files under %s: %w", filter, err) + return nil, nil, fmt.Errorf("listing files under %s: %w", filter, err) + } + + if len(files) == 0 { + unmatched = append(unmatched, filter) } for _, file := range files { @@ -871,7 +902,7 @@ func (v *Vaultik) getFilesToRestore( } } - return result, nil + return result, unmatched, nil } // buildChunkToBlobMap creates a mapping from chunk hash to blob information diff --git a/internal/vaultik/restore_unmatched_path_test.go b/internal/vaultik/restore_unmatched_path_test.go new file mode 100644 index 0000000..44c437d --- /dev/null +++ b/internal/vaultik/restore_unmatched_path_test.go @@ -0,0 +1,202 @@ +package vaultik_test + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/309: a path +// given to restore that matches nothing in the snapshot is named in a +// warning and makes the restore fail, after the paths that do match are +// restored. + +func TestRestoreNamesUnmatchedPathAndRestoresTheMatchingOne(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := filepath.Join(tempDir, "remote") + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + cfg := faultTestConfig() + files := writeFaultSourceTree(t, fs, dataDir) + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + id := fullFaultBackup(ctx, t, fs, store, cfg, + database.NewRepositories(db), dataDir, dbPath, "unmatched") + require.NoError(t, db.Close()) + + matched := filepath.Join(dataDir, "small.txt") + unmatched := filepath.Join(dataDir, "typo.txt") + + var out bytes.Buffer + + v := newReaderVaultik(ctx, cfg, store, nil, fs) + v.UI = ui.NewWithColor(&out, false) + + err = v.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Paths: []string{matched, unmatched}, + }) + + require.Error(t, err, "a path that matches nothing must fail the restore") + assert.Contains(t, out.String(), unmatched, + "the path that matches nothing must be named") + assert.NotContains(t, out.String(), matched, + "the path that matches must not be reported") + + got, err := afero.ReadFile(fs, filepath.Join(restoreDir, matched)) + require.NoError(t, err, "the path that matches must still be restored") + assert.Equal(t, files[matched], got) +} + +// When no requested path matches, nothing is restored and each path is +// named. One path is relative. The other goes through the symlink that +// is the snapshot's configured path, while the entries are stored under +// the directory the symlink points to. +func TestRestoreNamesEveryPathWhenNothingMatches(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const snapshotName = "linked" + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + linkDir := filepath.Join(tempDir, "srclink") + storeDir := filepath.Join(tempDir, "remote") + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + + writeFaultSourceTree(t, fs, dataDir) + require.NoError(t, os.Symlink(dataDir, linkDir)) + + cfg := faultTestConfig() + cfg.IndexPath = dbPath + cfg.ChunkSize = config.Size(faultChunkSize) + cfg.Snapshots = map[string]config.SnapshotConfig{ + snapshotName: {Paths: []string{linkDir}}, + } + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, snapshotName)) + + id := localSnapshotID(ctx, t, repos, snapshotName) + require.NoError(t, db.Close()) + + throughLink := filepath.Join(linkDir, "sub") + relative := strings.TrimPrefix(filepath.Join(dataDir, "small.txt"), "/") + + var out bytes.Buffer + + reader := newReaderVaultik(ctx, cfg, store, nil, fs) + reader.UI = ui.NewWithColor(&out, false) + + err = reader.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Paths: []string{throughLink, relative}, + }) + + require.Error(t, err, "a restore that matches nothing must fail") + assert.Contains(t, out.String(), throughLink, + "the path through the symlink must be named") + assert.Contains(t, out.String(), relative, + "the relative path must be named") + + _, err = fs.Stat(restoreDir) + assert.True(t, os.IsNotExist(err), "nothing must be restored") +} + +// Without --skip-errors a damaged blob stops the restore part way. The +// path that matches nothing must still be named. +func TestRestoreNamesUnmatchedPathWhenADamagedBlobStopsIt(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := filepath.Join(tempDir, "remote") + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + cfg := faultTestConfig() + + writeFaultSourceTree(t, fs, dataDir) + + inner, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + id := fullFaultBackup(ctx, t, fs, inner, cfg, + database.NewRepositories(db), dataDir, dbPath, "damaged") + require.NoError(t, db.Close()) + + damaged := faultstore.New(inner) + damaged.OnGet = func(key string) faultstore.GetFault { + if strings.HasPrefix(key, "blobs/") { + return faultstore.GetCorrupt + } + + return faultstore.GetNormal + } + + matched := filepath.Join(dataDir, "small.txt") + unmatched := filepath.Join(dataDir, "typo.txt") + + var out bytes.Buffer + + v := newReaderVaultik(ctx, cfg, damaged, nil, fs) + v.UI = ui.NewWithColor(&out, false) + + err = v.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Paths: []string{matched, unmatched}, + }) + + require.Error(t, err, "a damaged blob must stop the restore") + assert.Contains(t, err.Error(), "blob", + "the restore must stop on the damaged blob") + assert.Contains(t, out.String(), unmatched, + "the path that matches nothing must be named") +} From d8f78a1f4509511c34049b21d5ee6071e3f8c03c Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 23:36:22 +0200 Subject: [PATCH 071/121] Keep remote metadata when purge cannot remove a snapshot locally (closes #337) snapshot purge, and the purge step of snapshot create --prune, logged a failure to delete a snapshot from the local index, deleted that snapshot's metadata from the destination store anyway, and exited 0. The purge now stops at that snapshot with an error before touching its remote metadata, so the command exits non-zero. Stopping matches what the same loop already does when the remote delete fails; snapshots purged before the failure stay purged. The test drives snapshot purge only: the trigger that makes the local index refuse the delete also breaks the backup's metadata export, so snapshot create --prune cannot be tested that way. Model: opus-5-5 --- internal/cli/entry_snapshot_purge_test.go | 68 +++++++++++++++++++++++ internal/vaultik/snapshot.go | 5 +- 2 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 internal/cli/entry_snapshot_purge_test.go diff --git a/internal/cli/entry_snapshot_purge_test.go b/internal/cli/entry_snapshot_purge_test.go new file mode 100644 index 0000000..64d7a81 --- /dev/null +++ b/internal/cli/entry_snapshot_purge_test.go @@ -0,0 +1,68 @@ +package cli //nolint:testpackage // shares runEntry and the hermetic config helpers + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/snapshot" +) + +// Words and flags of `snapshot purge` used to build argument vectors +// below. +const ( + cmdPurge = "purge" + flagOlderThan = "--older-than" + flagForce = "--force" +) + +// TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails makes +// the local index refuse to delete an old snapshot and checks that +// `snapshot purge` exits non-zero and leaves that snapshot's metadata on +// the destination store. It used to log the error, delete the metadata +// and exit 0. +// +// `snapshot create --prune` runs the same purge, but cannot be driven +// this way: the refusal also breaks the backup's metadata export, which +// deletes the other snapshots from its copy of the local index. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails(t *testing.T) { + configPath := writeHermeticPruneConfig(t, false) + dir := filepath.Dir(configPath) + indexPath := filepath.Join(dir, "index.sqlite") + + // seedStaleSnapshotRecord writes an old snapshot to the local index + // only; the manifest planted here puts it on the destination store + // too, so the purge selects it rather than dropping it as stale. + seedStaleSnapshotRecord(t, indexPath) + + manifestDir := filepath.Join(dir, "store", "metadata", + snapshot.RemoteSnapshotKey(stalePruneSnapshotID)) + require.NoError(t, os.MkdirAll(manifestDir, 0o750)) + + manifestPath := filepath.Join(manifestDir, "manifest.json.zst") + require.NoError(t, os.WriteFile(manifestPath, []byte("stub"), 0o600)) + + ctx := context.Background() + + db, err := database.New(ctx, indexPath) + require.NoError(t, err) + + _, err = db.Conn().ExecContext(ctx, ` + CREATE TRIGGER refuse_snapshot_delete BEFORE DELETE ON snapshots + BEGIN SELECT RAISE(ABORT, 'simulated index error'); END`) + require.NoError(t, err) + require.NoError(t, db.Close()) + + code, _, _ := runEntry(t, flagConfig, configPath, + cmdSnapshot, cmdPurge, flagOlderThan, "30d", flagForce) + + assert.Equal(t, 1, code) + assert.FileExists(t, manifestPath, + "the snapshot is still in the local index, so its metadata must stay") +} diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 630e2ba..cef9cbf 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -669,10 +669,11 @@ func (v *Vaultik) confirmAndExecutePurge( snapshotID := snap.ID.String() log.Info("Deleting snapshot", "id", snapshotID) + // Stop before the remote delete, so a snapshot still in the local + // index keeps its metadata on the destination store. err := v.deleteSnapshotFromLocalDB(snapshotID) if err != nil { - log.Error("Failed to delete from local database", - "snapshot_id", snapshotID, "error", err) + return fmt.Errorf("deleting snapshot %s from local index: %w", snapshotID, err) } _, err = v.deleteRemoteSnapshotByKey(snapshot.RemoteSnapshotKey(snapshotID)) From 05a2c86d65ba0f7b58fe5ec3ba7d44e1761c1952 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 13 Oct 2026 23:56:22 +0200 Subject: [PATCH 072/121] Make the size defaults and the chunk_size minimum 1000-based (closes #313) The chunk_size and blob_size_limit defaults and the chunk_size minimum were 1024-based, while the size parser reads 10MB as 10,000,000 bytes and the docs and info use 1000-based units. So chunk_size: 1MB was rejected, writing out a documented default changed it, and info showed an 11 GB blob limit. They are now 1000-based like the parser. The examples below the 1MB minimum in config.example.yml and the config init template are replaced, and both now state the minimum. Judgement call: s3.part_size keeps its 5MiB to 5GiB bounds, which are S3's own limits, and MiB and GiB stay listed as accepted spellings. Model: opus-5-5 --- config.example.yml | 3 +- internal/cli/config.go | 2 +- internal/config/config.go | 10 +++-- internal/config/config_test.go | 75 ++++++++++++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 6 deletions(-) diff --git a/config.example.yml b/config.example.yml index fd76d48..55dae8e 100644 --- a/config.example.yml +++ b/config.example.yml @@ -302,7 +302,8 @@ storage_url: "rclone://myremote/path/to/backups" # Average chunk size for content-defined chunking # Smaller chunks = better deduplication but more metadata -# Supports: 10MB, 5M, 1GB, 500KB, 64MiB, etc. +# Minimum 1MB +# Supports: 10MB, 5M, 1GB, 64MiB, etc. # Default: 10MB #chunk_size: 10MB diff --git a/internal/cli/config.go b/internal/cli/config.go index bedfe89..5a00a2f 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -224,7 +224,7 @@ storage_url: "" # Average chunk size for content-defined chunking (FastCDC). # Smaller = better deduplication but more metadata overhead. -# Accepts: 1MB, 10M, 64KB, etc. +# Minimum 1MB. Accepts: 1MB, 10M, 64MiB, etc. # Default: 10MB # chunk_size: 10MB diff --git a/internal/config/config.go b/internal/config/config.go index c9dd2ec..64778c5 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -30,13 +30,15 @@ const appName = "vaultik" //nolint:gosec // G101: marker for detecting a pasted secret key, not a credential const secretKeyPrefix = "AGE-SECRET-KEY-" -// Defaults and validation bounds for tunable settings. +// Defaults and validation bounds for tunable settings. MB and GB are +// 1000-based, as the size parser reads them; the S3 part sizes are S3's own +// limits, which are 1024-based (MiB, GiB). const ( - defaultBlobSizeLimit = Size(10 * 1024 * 1024 * 1024) // 10GB - defaultChunkSize = Size(10 * 1024 * 1024) // 10MB + defaultBlobSizeLimit = Size(10 * 1000 * 1000 * 1000) // 10GB + defaultChunkSize = Size(10 * 1000 * 1000) // 10MB defaultS3PartSize = Size(5 * 1024 * 1024) // 5MiB defaultCompressionLevel = 3 - minChunkSize = 1024 * 1024 // 1MB + minChunkSize = 1000 * 1000 // 1MB minCompressionLevel = 1 maxCompressionLevel = 19 // S3 accepts a multipart upload part from 5MiB to 5GiB. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index bd7abe3..897b7e7 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -337,6 +337,81 @@ func TestLoadS3PartSize(t *testing.T) { }) } +// TestDocumentedSizeDefaults checks that the defaults are the documented +// chunk_size 10MB and blob_size_limit 10GB as the parser reads those values +// (1000-based), so writing a default out in the config file changes nothing. +func TestDocumentedSizeDefaults(t *testing.T) { + t.Parallel() + + cfg, err := Parse([]byte("chunk_size: 10MB\nblob_size_limit: 10GB\n")) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } + + if cfg.ChunkSize != defaultChunkSize { + t.Errorf("chunk_size: 10MB is %d bytes, the default is %d", + cfg.ChunkSize, defaultChunkSize) + } + + if cfg.BlobSizeLimit != defaultBlobSizeLimit { + t.Errorf("blob_size_limit: 10GB is %d bytes, the default is %d", + cfg.BlobSizeLimit, defaultBlobSizeLimit) + } +} + +// TestDocumentedSizeExamples checks the 1MB minimum chunk_size and that +// every size the README, config.example.yml and the config init template +// list as an example is accepted. +func TestDocumentedSizeExamples(t *testing.T) { + t.Parallel() + + const withoutSizes = "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file:///tmp/vaultik-test-storage\n" + + tests := []struct { + setting string + wantErr error + }{ + {"chunk_size: 1MB", nil}, + {"chunk_size: 999999", errChunkSizeTooSmall}, + {"chunk_size: 5M", nil}, + {"chunk_size: 10M", nil}, + {"chunk_size: 10MB", nil}, + {"chunk_size: 64MiB", nil}, + {"chunk_size: 1GB", nil}, + // Four times the default chunk_size, the documented minimum. + {"blob_size_limit: 40MB", nil}, + {"blob_size_limit: 500MB", nil}, + {"blob_size_limit: 1GB", nil}, + {"blob_size_limit: 1GiB", nil}, + {"blob_size_limit: 10G", nil}, + {"blob_size_limit: 10GB", nil}, + {"s3: {part_size: 5MiB}", nil}, + {"s3: {part_size: 10MB}", nil}, + {"s3: {part_size: 16MiB}", nil}, + {"s3: {part_size: 100MiB}", nil}, + {"s3: {part_size: 5GiB}", nil}, + } + + for _, tt := range tests { + t.Run(tt.setting, func(t *testing.T) { + t.Parallel() + + cfg, err := Parse([]byte(withoutSizes + tt.setting + "\n")) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } + + err = cfg.Validate() + if !errors.Is(err, tt.wantErr) { + t.Fatalf("Validate() error = %v, want %v", err, tt.wantErr) + } + }) + } +} + // TestLoadRejectsRelativeFileURL checks that a file:// storage_url with a // relative path fails at load. Accepted, it would resolve against the // working directory, so a backup run from another directory would write From abad8161bcc07a59fa3377d5579481b8d8ba37ca Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 00:13:27 +0200 Subject: [PATCH 073/121] Make **/ in an exclude pattern match zero directories (closes #338) The glob library needs a slash on both sides of **, so the anchored pattern /**/x missed an x directly under the snapshot path, and a/**/*.log missed a/x.log. As in gitignore, a leading **/ now makes any pattern, anchored or not, match at every depth, and a pattern holding /**/ is also compiled with each /**/ made a single slash. The library's {a,b} alternatives cannot express this: with ** inside them in mid-pattern they miss paths they should match. Judgement call: the test for a/**/b uses a/**/*.log, because with a plain name after the ** the glob library already matched a/b. Model: opus-5-5 --- internal/snapshot/exclude_test.go | 51 +++++++++++++++++++++++++ internal/snapshot/scanner.go | 63 ++++++++++++++++++++++--------- 2 files changed, 96 insertions(+), 18 deletions(-) diff --git a/internal/snapshot/exclude_test.go b/internal/snapshot/exclude_test.go index 48deb70..c23d03e 100644 --- a/internal/snapshot/exclude_test.go +++ b/internal/snapshot/exclude_test.go @@ -578,3 +578,54 @@ func TestExcludePatterns_DoubleStarFileAtEveryDepth(t *testing.T) { require.Equal(t, 1, result.FilesScanned, "**/ file pattern should match at the top level and nested") } + +func TestExcludePatterns_AnchoredDoubleStarAtEveryDepth(t *testing.T) { + t.Parallel() + + // As in gitignore, /**/ also matches directly under the source dir + fs := setupAnchoredTestFS(t) + + scanner, repos, cleanup := createTestScanner(t, fs, []string{"/**/projectname"}) + defer cleanup() + + ctx := context.Background() + createSnapshotRecord(ctx, t, repos, "test-snapshot") + + result, err := scanner.Scan(ctx, "/backup", "test-snapshot") + require.NoError(t, err) + + // /**/projectname should exclude BOTH: + // - /backup/projectname/file.txt + // - /backup/otherproject/projectname/file.txt + // Total files: 4, excluded: 2 + require.Equal(t, 2, result.FilesScanned, + "/**/ pattern should match at the top level and nested") +} + +func TestExcludePatterns_DoubleStarInMiddleMatchesZeroDirectories(t *testing.T) { + t.Parallel() + + // As in gitignore, a/**/b matches a/b as well as a/c/b. The last part + // is a glob: with a plain name the glob library already matched a/b. + fs := &afero.MemMapFs{} + files := []string{"/backup/a/x.log", "/backup/a/c/y.log", "/backup/a/c/kept.txt"} + + for _, path := range files { + require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0755)) + require.NoError(t, afero.WriteFile(fs, path, []byte(path), 0644)) + } + + scanner, repos, cleanup := createTestScanner(t, fs, []string{"a/**/*.log"}) + defer cleanup() + + ctx := context.Background() + createSnapshotRecord(ctx, t, repos, "test-snapshot") + + result, err := scanner.Scan(ctx, "/backup", "test-snapshot") + require.NoError(t, err) + + // a/**/*.log should exclude /backup/a/x.log and /backup/a/c/y.log + // Total files: 3, excluded: 2 + require.Equal(t, 1, result.FilesScanned, + "a/**/*.log should match a/x.log as well as a/c/y.log") +} diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index ee8a954..093a472 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -2035,33 +2035,60 @@ func compileExcludePatterns(patterns []string) []compiledPattern { pattern = strings.TrimSuffix(pattern, "/") // A leading "**/" demands a "/" before the name and so misses an - // entry directly under the source path. An unanchored pattern - // already matches at every depth, so drop the prefix: as in - // gitignore, "**/x" then also matches a top-level "x". - if !anchored { - pattern = strings.TrimPrefix(pattern, "**/") + // entry directly under the source path. It means "at every depth", + // which is what an unanchored pattern already does, so drop the + // prefix and match unanchored: as in gitignore, "**/x" and + // "/**/x" then also match a top-level "x". + if rest, found := strings.CutPrefix(pattern, "**/"); found { + pattern = rest + anchored = false } - // Compile the glob pattern - // For patterns without path separators, we need to match them as components - // e.g., ".git" should match ".git" anywhere in the path - g, err := glob.Compile(pattern, '/') - if err != nil { - log.Warn("Invalid exclude pattern, skipping", "pattern", p, "error", err) + // Likewise "/**/" inside a pattern demands two slashes, so + // "a/**/*.log" misses "a/x.log". As in gitignore it stands for + // zero or more directories, so also compile the pattern with it + // made a single "/". The glob library's {a,b} is no help: with a + // "**" inside it in mid-pattern, it misses paths it should match. + for _, variant := range doubleStarVariants(pattern) { + // For patterns without path separators, we need to match them as components + // e.g., ".git" should match ".git" anywhere in the path + g, err := glob.Compile(variant, '/') + if err != nil { + log.Warn("Invalid exclude pattern, skipping", "pattern", p, "error", err) - continue + break + } + + compiled = append(compiled, compiledPattern{ + pattern: g, + anchored: anchored, + original: p, + }) } - - compiled = append(compiled, compiledPattern{ - pattern: g, - anchored: anchored, - original: p, - }) } return compiled } +// doubleStarVariants returns pattern once for every way of keeping each +// "/**/" in it or making it a single "/". +func doubleStarVariants(pattern string) []string { + const doubleStar = "/**/" + + before, after, found := strings.Cut(pattern, doubleStar) + if !found { + return []string{pattern} + } + + var variants []string + + for _, rest := range doubleStarVariants(after) { + variants = append(variants, before+doubleStar+rest, before+"/"+rest) + } + + return variants +} + // shouldExclude checks if a path should be excluded based on exclude patterns // filePath is the full path to the file // rootPath is the root of the backup source directory From 8d5e6f339934372149aa05b759e498cff44f1e19 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 00:39:32 +0200 Subject: [PATCH 074/121] Read the rclone config file named by RCLONE_CONFIG (closes #321) An rclone destination whose remote is defined only in the file RCLONE_CONFIG names was reported as not found: rclone reads that variable only as the value of its --config flag, which vaultik does not have, so vaultik always used rclone's default config file. NewRcloneStorer now sets rclone's config path from RCLONE_CONFIG when the variable is set, as that flag would, including an empty value, which rclone takes to mean no config file. Model: opus-5-5 --- internal/storage/rclone.go | 11 ++++++++++ internal/storage/rclone_test.go | 39 +++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/internal/storage/rclone.go b/internal/storage/rclone.go index 43ac7ba..4ca2be1 100644 --- a/internal/storage/rclone.go +++ b/internal/storage/rclone.go @@ -7,10 +7,12 @@ import ( "errors" "fmt" "io" + "os" "strings" "time" "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/config" "github.com/rclone/rclone/fs/config/configfile" "github.com/rclone/rclone/fs/operations" @@ -33,6 +35,15 @@ type RcloneStorer struct { // The remote parameter is the rclone remote name (as configured via `rclone config`). // The path parameter is the path within the remote. func NewRcloneStorer(ctx context.Context, remote, path string) (*RcloneStorer, error) { + // rclone reads RCLONE_CONFIG only as the value of its --config flag, + // which vaultik does not have, so it is applied here as that flag would. + if configPath, ok := os.LookupEnv("RCLONE_CONFIG"); ok { + err := config.SetConfigPath(configPath) + if err != nil { + return nil, fmt.Errorf("using RCLONE_CONFIG %q: %w", configPath, err) + } + } + // Install the default config file handler configfile.Install() diff --git a/internal/storage/rclone_test.go b/internal/storage/rclone_test.go index c666a64..1f2d9ee 100644 --- a/internal/storage/rclone_test.go +++ b/internal/storage/rclone_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/config" "github.com/rclone/rclone/fs/config/configmap" "sneak.berlin/go/vaultik/internal/storage" ) @@ -390,3 +391,41 @@ func TestNewRcloneStorerUnknownRemote(t *testing.T) { t.Errorf("NewRcloneStorer error = %v, want ErrRemoteNotFound", err) } } + +// TestNewRcloneStorerReadsRcloneConfigEnv checks that a remote defined only +// in the file RCLONE_CONFIG names is found and written to, as rclone itself +// would. +func TestNewRcloneStorerReadsRcloneConfigEnv(t *testing.T) { + // rclone keeps the config file path in a process-global variable, which + // NewRcloneStorer leaves pointing at this test's file. + previous := config.GetConfigPath() + + t.Cleanup(func() { _ = config.SetConfigPath(previous) }) + + confFile := filepath.Join(t.TempDir(), "rclone.conf") + + err := os.WriteFile(confFile, []byte("[loc]\ntype = local\n"), 0o600) + if err != nil { + t.Fatalf("writing rclone config: %v", err) + } + + t.Setenv("RCLONE_CONFIG", confFile) + + dir := t.TempDir() + ctx := context.Background() + + s, err := storage.NewRcloneStorer(ctx, "loc", dir) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + err = s.Put(ctx, testBlobKey, strings.NewReader("blob-bytes")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + _, err = os.Stat(filepath.Join(dir, testBlobKey)) + if err != nil { + t.Errorf("object is not in the remote's directory: %v", err) + } +} From 30285c7a8cb4c52af5af2ab6ca210f984cf679d5 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 01:10:43 +0200 Subject: [PATCH 075/121] Silence prune and snapshot removal status under --cron and --quiet (closes #294) PruneBlobs, CleanupLocalSnapshots, RemoveSnapshot, RemoveAllSnapshots and snapshot purge wrote their status lines straight to stdout, so `snapshot create --cron --prune` printed on every successful run and --quiet did not silence `prune`, `snapshot purge`, `snapshot remove` or `remote nuke`. Those lines now go through internal/ui, which drops them under --cron and --quiet; warnings, errors and --json documents still print. The confirmation prompts still write straight to stdout, as the `database delete` prompt does, together with what they ask to delete: the snapshot list before the purge prompt, and the blob count and size before the prune prompt. With --force those lines are status lines. The two purge test fixtures gained the UI writer production always sets. Model: opus-5-5 --- README.md | 6 +- internal/cli/entry_prune_quiet_test.go | 123 +++++++++++++++ internal/vaultik/prune.go | 13 +- .../purge_local_remote_consistency_test.go | 6 +- internal/vaultik/purge_per_name_test.go | 2 + internal/vaultik/remove_quiet_test.go | 148 ++++++++++++++++++ internal/vaultik/remove_snapshot_test.go | 4 +- internal/vaultik/snapshot.go | 76 +++++---- 8 files changed, 337 insertions(+), 41 deletions(-) create mode 100644 internal/cli/entry_prune_quiet_test.go create mode 100644 internal/vaultik/remove_quiet_test.go diff --git a/README.md b/README.md index ee375b0..3ba0768 100644 --- a/README.md +++ b/README.md @@ -712,8 +712,10 @@ the `NO_COLOR` environment variable is unset (https://no-color.org/). reports and tables (`version`, `info`, `remote info`, `snapshot verify`, `snapshot list`) but never the machine-consumed `config get` value or the `--json` documents, which a script depends on. The - `database delete` confirmation prompt is also written this way and - always shown: it is an interactive exchange the operator must see. + confirmation prompts of `database delete`, `prune`, `snapshot purge` + and `snapshot remove`, each with what it asks to delete, are also + written this way and always shown: they are an interactive exchange + the operator must see. `internal/ui` writes to stdout; it is the output the user asked for. The exceptions are the startup banner and the error a failed command ends diff --git a/internal/cli/entry_prune_quiet_test.go b/internal/cli/entry_prune_quiet_test.go new file mode 100644 index 0000000..92e7a3b --- /dev/null +++ b/internal/cli/entry_prune_quiet_test.go @@ -0,0 +1,123 @@ +package cli //nolint:testpackage // shares runEntry and the hermetic config helpers + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// flagCron is used to build the argument vectors below. +const flagCron = "--cron" + +// plantUnreferencedBlob writes a blob that no snapshot references to the +// destination store at storeDir, so that a prune deletes it. Returns its +// path. +func plantUnreferencedBlob(t *testing.T, storeDir string) string { + t.Helper() + + hash := strings.Repeat("b", 64) + path := filepath.Join(storeDir, "blobs", hash[:2], hash[2:4], hash) + + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o750)) + require.NoError(t, os.WriteFile(path, []byte("unreferenced"), 0o600)) + + return path +} + +// TestEntrySnapshotCreatePruneIsSilent checks that a successful +// `snapshot create --prune` under --cron or --quiet prints nothing on +// stdout or stderr, whether or not the prune finds a blob to delete. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreatePruneIsSilent(t *testing.T) { + for _, testCase := range []struct { + name string + args []string + plantBlob bool + }{ + { + name: "cron, no blob to delete", + args: []string{cmdSnapshot, cmdCreate, flagCron, flagPrune}, + }, + { + name: "cron, blob to delete", + args: []string{cmdSnapshot, cmdCreate, flagCron, flagPrune}, + plantBlob: true, + }, + { + name: "cron with keep-newer-than", + args: []string{ + cmdSnapshot, cmdCreate, flagCron, flagPrune, + flagKeepNewerThan, "4w", + }, + plantBlob: true, + }, + { + name: "quiet", + args: []string{flagQuiet, cmdSnapshot, cmdCreate, flagPrune}, + plantBlob: true, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + configPath, storeDir := writeBackupConfig(t) + + var blob string + if testCase.plantBlob { + blob = plantUnreferencedBlob(t, storeDir) + } + + code, stdout, stderr := runEntry(t, + append([]string{flagConfig, configPath}, testCase.args...)...) + + assert.Equal(t, 0, code) + assert.Empty(t, stdout) + assert.Empty(t, stderr) + + if testCase.plantBlob { + assert.NoFileExists(t, blob, "the prune must delete the blob") + } + }) + } +} + +// TestEntryPruneQuietIsSilent checks that a successful `prune --force` +// under --quiet prints nothing on stdout or stderr, both when there is +// nothing to remove and when it removes a stale local snapshot record +// and an unreferenced blob. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntryPruneQuietIsSilent(t *testing.T) { + for _, testCase := range []struct { + name string + staleRecordAndBlob bool + }{ + {name: "nothing to remove"}, + {name: "stale record and blob to remove", staleRecordAndBlob: true}, + } { + t.Run(testCase.name, func(t *testing.T) { + configPath := writeHermeticPruneConfig(t, testCase.staleRecordAndBlob) + + var blob string + if testCase.staleRecordAndBlob { + // writeHermeticPruneConfig puts the store beside the config. + blob = plantUnreferencedBlob(t, + filepath.Join(filepath.Dir(configPath), "store")) + } + + code, stdout, stderr := runEntry(t, + flagConfig, configPath, flagQuiet, cmdPrune, flagForce) + + assert.Equal(t, 0, code) + assert.Empty(t, stdout) + assert.Empty(t, stderr) + + if testCase.staleRecordAndBlob { + assert.NoFileExists(t, blob, "the prune must delete the blob") + } + }) + } +} diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index d32f68c..6d07e41 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -204,7 +204,7 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { return v.outputPruneBlobsJSON(result) } - v.printlnStdout("No unreferenced blobs to remove.") + v.UI.Infof("No unreferenced blobs to remove.") return nil } @@ -212,12 +212,17 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { log.Info("Found unreferenced blobs", "count", len(unreferencedBlobs), "total_size", ubytes(totalSize)) - if !opts.JSON { - v.stdoutf("Found %d unreferenced blob(s) totaling %s\n", + if opts.Force && !opts.JSON { + v.UI.Infof("Found %d unreferenced blob(s) totaling %s.", len(unreferencedBlobs), ubytes(totalSize)) } if !opts.Force && !opts.JSON { + // The count, the prompt and its answer bypass the UI: they are an + // interactive exchange the operator must see, so --quiet does not + // silence them. + v.stdoutf("Found %d unreferenced blob(s) totaling %s.\n", + len(unreferencedBlobs), ubytes(totalSize)) v.stdoutf("\nDelete %d unreferenced blob(s)? [y/N] ", len(unreferencedBlobs)) var confirm string @@ -244,7 +249,7 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { return err } } else { - v.stdoutf("\nDeleted %d blob(s) totaling %s\n", + v.UI.Infof("Deleted %d blob(s) totaling %s.", result.BlobsDeleted, ubytes(result.BytesFreed)) } diff --git a/internal/vaultik/purge_local_remote_consistency_test.go b/internal/vaultik/purge_local_remote_consistency_test.go index f170d2f..c3d827f 100644 --- a/internal/vaultik/purge_local_remote_consistency_test.go +++ b/internal/vaultik/purge_local_remote_consistency_test.go @@ -14,6 +14,7 @@ import ( "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/types" + "sneak.berlin/go/vaultik/internal/ui" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -58,13 +59,16 @@ func setupConsistencyTest( require.NoError(t, err) } + stdout := &bytes.Buffer{} + v := &vaultik.Vaultik{ Storage: mockStorage, Repositories: repos, DB: db, - Stdout: &bytes.Buffer{}, + Stdout: stdout, Stderr: &bytes.Buffer{}, Stdin: &bytes.Buffer{}, + UI: ui.NewWithColor(stdout, false), } v.SetContext(ctx) diff --git a/internal/vaultik/purge_per_name_test.go b/internal/vaultik/purge_per_name_test.go index f895f61..8b537b8 100644 --- a/internal/vaultik/purge_per_name_test.go +++ b/internal/vaultik/purge_per_name_test.go @@ -14,6 +14,7 @@ import ( "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/types" + "sneak.berlin/go/vaultik/internal/ui" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -86,6 +87,7 @@ func setupPurgeTest( Stdout: stdout, Stderr: stderr, Stdin: stdin, + UI: ui.NewWithColor(stdout, false), } v.SetContext(ctx) diff --git a/internal/vaultik/remove_quiet_test.go b/internal/vaultik/remove_quiet_test.go new file mode 100644 index 0000000..c8916fd --- /dev/null +++ b/internal/vaultik/remove_quiet_test.go @@ -0,0 +1,148 @@ +package vaultik_test + +import ( + "bytes" + "context" + "encoding/json" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestPurgeSnapshots_QuietSuppressesReport checks that `snapshot purge +// --keep-latest --force` under --quiet deletes the older snapshot and +// prints nothing. +func TestPurgeSnapshots_QuietSuppressesReport(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + v := setupPurgeTest(t, snapHostname, []string{snapHomeT0, snapHomeT1}) + + var out bytes.Buffer + + v.Stdout = &out + v.UI = ui.NewWithColor(&out, false) + v.UI.SetQuiet(true) + + require.NoError(t, v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + KeepLatest: true, + Force: true, + })) + + assert.Equal(t, []string{snapHomeT1}, listRemainingSnapshots(t, v)) + assert.Empty(t, out.String()) +} + +// TestPurgeSnapshots_QuietPromptListsSnapshots checks that `snapshot +// purge --keep-latest` without --force still lists the snapshots its +// prompt asks to delete under --quiet. +func TestPurgeSnapshots_QuietPromptListsSnapshots(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + v := setupPurgeTest(t, snapHostname, []string{snapHomeT0, snapHomeT1}) + + var out bytes.Buffer + + v.Stdout = &out + v.UI = ui.NewWithColor(&out, false) + v.UI.SetQuiet(true) + + // Stdin is empty, so the prompt reads no answer and cancels. + require.NoError(t, v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + KeepLatest: true, + })) + + assert.Contains(t, out.String(), snapHomeT0) + assert.Contains(t, out.String(), "Delete 1 snapshot(s)? [y/N]") + assert.Len(t, listRemainingSnapshots(t, v), 2) +} + +// TestPruneBlobs_QuietPromptShowsBlobTotal checks that `prune` without +// --force still states the count and total size of the blobs its prompt +// asks to delete under --quiet. +func TestPruneBlobs_QuietPromptShowsBlobTotal(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + env.v.UI.SetQuiet(true) + + // The store holds no manifest, so nothing references this blob. + addBlob(t, env.store.testStorer, testBlobHashA) + + // Stdin is empty, so the prompt reads no answer and cancels. + require.NoError(t, env.v.PruneBlobs(&vaultik.PruneOptions{})) + + assert.Contains(t, env.stdout.String(), + "Found 1 unreferenced blob(s) totaling") + assert.Contains(t, env.stdout.String(), + "Delete 1 unreferenced blob(s)? [y/N]") +} + +// TestRemoveSnapshot_QuietSuppressesReport checks that `snapshot remove` +// under --quiet prints nothing with --dry-run or with --force, and that +// the --json document still prints. +func TestRemoveSnapshot_QuietSuppressesReport(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + newQuietRemover := func() (*vaultik.TestVaultik, *testStorer) { + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001") + tv.UI.SetQuiet(true) + + return tv, store + } + + tv, store := newQuietRemover() + + _, err := tv.RemoveSnapshot("snapshot-001", + &vaultik.RemoveOptions{DryRun: true}) + require.NoError(t, err) + assert.Empty(t, tv.Stdout.String(), + "--dry-run must print nothing under --quiet") + + _, err = tv.RemoveSnapshot("snapshot-001", + &vaultik.RemoveOptions{Force: true}) + require.NoError(t, err) + assert.False(t, store.hasKey(remoteKeyPath("snapshot-001"))) + assert.Empty(t, tv.Stdout.String(), + "--force must print nothing under --quiet") + + tv, _ = newQuietRemover() + + _, err = tv.RemoveSnapshot("snapshot-001", + &vaultik.RemoveOptions{JSON: true}) + require.NoError(t, err) + + var result vaultik.RemoveResult + + require.NoError(t, json.Unmarshal(tv.Stdout.Bytes(), &result), + "the --json document must still print under --quiet") + assert.True(t, result.RemoteRemoved) +} + +// TestNukeRemote_QuietSuppressesReport checks that `remote nuke --force` +// under --quiet prints nothing while it removes a snapshot's metadata +// and its blobs. +func TestNukeRemote_QuietSuppressesReport(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, out := backUpToFileDestination(ctx, t, storeDir) + v.UI.SetQuiet(true) + + require.NoError(t, v.NukeRemote(true)) + assert.Empty(t, out.String()) +} diff --git a/internal/vaultik/remove_snapshot_test.go b/internal/vaultik/remove_snapshot_test.go index 7d85bea..77dfc2f 100644 --- a/internal/vaultik/remove_snapshot_test.go +++ b/internal/vaultik/remove_snapshot_test.go @@ -350,7 +350,7 @@ func TestRemoveSnapshot_DryRun(t *testing.T) { assert.True(t, store.hasKey("blobs/aa/aa/"+blobA)) assert.True(t, store.hasKey(remoteKeyPath("snapshot-001"))) - assert.Contains(t, tv.Stdout.String(), "[Dry run - no changes made]") + assert.Contains(t, tv.Stdout.String(), "Dry run: no changes made.") } // TestRemoveSnapshot_UnknownIDIsError checks that an ID naming no @@ -504,7 +504,7 @@ func TestRemoveAllSnapshots_DryRun(t *testing.T) { assert.Equal(t, initialCount, store.keyCount()) - assert.Contains(t, tv.Stdout.String(), "[Dry run - no changes made]") + assert.Contains(t, tv.Stdout.String(), "Dry run: no changes made.") } func TestRemoveAllSnapshots_NoSnapshots(t *testing.T) { diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index cef9cbf..63a9809 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -574,7 +574,7 @@ func (v *Vaultik) PurgeSnapshotsWithOptions(opts *SnapshotPurgeOptions) error { if len(toDelete) == 0 { if !opts.Quiet { - v.printlnStdout("No snapshots to delete") + v.UI.Infof("No snapshots to delete.") } return nil @@ -631,19 +631,19 @@ func selectSnapshotsToPurge( func (v *Vaultik) confirmAndExecutePurge( toDelete []SnapshotInfo, force, quiet bool, ) error { - if !quiet { + // Confirm unless --force is used. The list, the prompt and its answer + // bypass the UI: they are an interactive exchange the operator must + // see, so --quiet does not silence them. + if !force { v.stdoutf("The following snapshots will be deleted:\n\n") for _, snap := range toDelete { v.stdoutf(" %s (%s, %s)\n", snap.ID, - snap.Timestamp.Format("2006-01-02 15:04:05"), + snap.Timestamp.Format(time.DateTime), ubytes(snap.CompressedSize)) } - } - // Confirm unless --force is used - if !force { v.stdoutf("\nDelete %d snapshot(s)? [y/N] ", len(toDelete)) var confirm string @@ -661,7 +661,16 @@ func (v *Vaultik) confirmAndExecutePurge( return nil } } else if !quiet { - v.stdoutf("\nDeleting %d snapshot(s) (--force specified)\n", len(toDelete)) + v.UI.Infof("The following snapshots will be deleted:") + + for _, snap := range toDelete { + v.UI.Detailf("%s (%s, %s)", + v.UI.Snapshot(snap.ID.String()), + snap.Timestamp.Format(time.DateTime), + ubytes(snap.CompressedSize)) + } + + v.UI.Infof("Deleting %d snapshot(s) (--force specified).", len(toDelete)) } // Delete snapshots (both local and remote) @@ -694,9 +703,9 @@ func (v *Vaultik) confirmAndExecutePurge( } if !quiet { - v.stdoutf("Deleted %d snapshot(s)\n", len(toDelete)) - v.printlnStdout( - "\nNote: Run 'vaultik prune' to clean up unreferenced remote blobs.") + v.UI.Infof("Deleted %d snapshot(s).", len(toDelete)) + v.UI.Noticef("Run '%s' to clean up unreferenced remote blobs.", + pruneCommandHint) } return nil @@ -1069,7 +1078,7 @@ func (v *Vaultik) CleanupLocalSnapshots(opts *PruneOptions) error { log.Info("Removing stale local snapshot record", "snapshot_id", id) if !opts.JSON { - v.stdoutf("Removing stale local record: %s\n", id) + v.UI.Infof("Removing stale local record: %s.", v.UI.Snapshot(id)) } err = v.deleteSnapshotFromLocalDB(id) @@ -1092,9 +1101,9 @@ func (v *Vaultik) CleanupLocalSnapshots(opts *PruneOptions) error { } if removed == 0 { - v.printlnStdout("No stale local snapshots found.") + v.UI.Infof("No stale local snapshots found.") } else { - v.stdoutf("Removed %d stale local snapshot record(s).\n", removed) + v.UI.Infof("Removed %d stale local snapshot record(s).", removed) } return nil @@ -1273,14 +1282,15 @@ func (v *Vaultik) RemoveSnapshot( } if inLocalIndex { - v.stdoutf("Removed snapshot '%s' from local database\n", snapshotID) + v.UI.Infof("Removed snapshot '%s' from local database.", + v.UI.Snapshot(snapshotID)) } if result.RemoteRemoved { - v.printlnStdout("Removed snapshot metadata from remote storage") - v.stdoutf("\nNote: The removed snapshot's blobs remain on the remote. "+ + v.UI.Infof("Removed snapshot metadata from remote storage.") + v.UI.Noticef("The removed snapshot's blobs remain on the remote. "+ "Run '%s' to delete any blobs no longer referenced by any "+ - "remaining remote snapshot.\n", pruneCommandHint) + "remaining remote snapshot.", pruneCommandHint) } return result, nil @@ -1336,21 +1346,23 @@ func (v *Vaultik) removeSnapshotDryRun( return result, v.outputRemoveJSON(result) } - v.stdoutf("Would remove snapshot: %s\n", snapshotID) + v.UI.Infof("Would remove snapshot: %s.", v.UI.Snapshot(snapshotID)) if !opts.LocalOnly { - v.printlnStdout("Would also remove snapshot metadata from " + - "remote storage (blobs untouched)") + v.UI.Infof("Would also remove snapshot metadata from " + + "remote storage (blobs untouched).") } - v.printlnStdout("[Dry run - no changes made]") + v.UI.Noticef("Dry run: no changes made.") return result, nil } // confirmRemoveSnapshot prompts for confirmation before removing a // snapshot. Returns false (treating EOF/read errors as "no") unless the -// user answers "y". +// user answers "y". The prompt and its answer bypass the UI: they are an +// interactive exchange the operator must see, so --quiet does not +// silence them. func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) bool { if opts.LocalOnly { v.stdoutf("Remove snapshot '%s' from local database "+ @@ -1456,7 +1468,7 @@ func (v *Vaultik) RemoveAllSnapshots(opts *RemoveOptions) (*RemoveResult, error) if len(localSnaps) == 0 && len(orphanRemoteKeys) == 0 { if !opts.JSON { - v.printlnStdout("No snapshots found") + v.UI.Infof("No snapshots found.") } return &RemoveResult{}, nil @@ -1561,27 +1573,27 @@ func (v *Vaultik) handleRemoveAllDryRun( } if !opts.JSON { - v.stdoutf("Would remove %d local snapshot(s):\n", len(localSnaps)) + v.UI.Infof("Would remove %d local snapshot(s):", len(localSnaps)) for _, id := range localSnaps { - v.stdoutf(" %s\n", id) + v.UI.Detailf("%s", v.UI.Snapshot(id)) } if !opts.LocalOnly { if len(orphanRemoteKeys) > 0 { - v.stdoutf("Would also remove %d orphan remote snapshot key(s):\n", + v.UI.Infof("Would also remove %d orphan remote snapshot key(s):", len(orphanRemoteKeys)) for _, key := range orphanRemoteKeys { - v.stdoutf(" %s\n", key) + v.UI.Detailf("%s", key) } } else { - v.printlnStdout("Would also remove snapshot metadata from " + - "remote storage (blobs untouched)") + v.UI.Infof("Would also remove snapshot metadata from " + + "remote storage (blobs untouched).") } } - v.printlnStdout("[Dry run - no changes made]") + v.UI.Noticef("Dry run: no changes made.") } if opts.JSON { @@ -1630,10 +1642,10 @@ func (v *Vaultik) executeRemoveAll( return result, v.outputRemoveJSON(result) } - v.stdoutf("Removed %d snapshot(s)\n", len(result.SnapshotsRemoved)) + v.UI.Infof("Removed %d snapshot(s).", len(result.SnapshotsRemoved)) if !opts.LocalOnly && result.RemoteRemoved { - v.printlnStdout("Removed snapshot metadata from remote storage") + v.UI.Infof("Removed snapshot metadata from remote storage.") } return result, nil From dd3667c8e92df1de1833937a58e410fbf49b41ad Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 01:34:38 +0200 Subject: [PATCH 076/121] Keep the whole startup error when it contains "): " (closes #320) A startup error was cut at its last "): " to drop the annotations fx adds, so the blob_size_limit message, which itself contains "(... size spread): ", lost everything but "need at least N bytes". cleanStartupError now uses dig.RootCause, from the library fx is built on, which removes exactly those annotations and returns the error underneath unchanged. The test starts a real fx app on a config whose blob_size_limit is below the minimum. The old cases fed it plain strings that only looked like fx output; such an error is now rightly left whole, so they are replaced. go.uber.org/dig, already required through fx, becomes a direct requirement in go.mod. Model: opus-5-5 --- go.mod | 2 +- internal/cli/app.go | 16 +++----- internal/cli/app_test.go | 87 ++++++++++++++++++++++------------------ 3 files changed, 54 insertions(+), 51 deletions(-) diff --git a/go.mod b/go.mod index d00f7f3..3acb01e 100644 --- a/go.mod +++ b/go.mod @@ -22,6 +22,7 @@ require ( github.com/spf13/cobra v1.10.1 github.com/spf13/pflag v1.0.10 github.com/stretchr/testify v1.11.1 + go.uber.org/dig v1.19.0 go.uber.org/fx v1.24.0 golang.org/x/sync v0.18.0 golang.org/x/sys v0.38.0 @@ -256,7 +257,6 @@ require ( go.opentelemetry.io/otel/metric v1.38.0 // indirect go.opentelemetry.io/otel/trace v1.38.0 // indirect go.shabbyrobe.org/gocovmerge v0.0.0-20230507111327-fa4f82cfbf4d // indirect - go.uber.org/dig v1.19.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect diff --git a/internal/cli/app.go b/internal/cli/app.go index 889327f..5b4fb50 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -8,12 +8,12 @@ import ( "errors" "fmt" "path/filepath" - "strings" "sync" "time" "github.com/adrg/xdg" "github.com/spf13/cobra" + "go.uber.org/dig" "go.uber.org/fx" "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/database" @@ -146,16 +146,12 @@ func (e *startupError) Error() string { // could not build arguments for function "Y" (file:line): failed to build U: // received non-nil error from function "Z" (file:line): // -// Users care about the real error, not the DI plumbing. We strip everything -// up through the last "): " (which is always the close-paren of an fx -// function-location annotation followed by the wrapped error). +// Users care about the real error, not the DI plumbing. dig.RootCause, +// from the library fx is built on, unwraps those layers and returns the +// real error whole. Cutting the text at "): " instead would also cut a +// real error that contains it, such as the blob_size_limit one. func cleanStartupError(err error) error { - msg := err.Error() - if idx := strings.LastIndex(msg, "): "); idx >= 0 { - msg = msg[idx+3:] - } - - return &startupError{msg: msg} + return &startupError{msg: dig.RootCause(err).Error()} } // RunApp starts the fx application, blocks until it is asked to stop, and diff --git a/internal/cli/app_test.go b/internal/cli/app_test.go index 102bfae..c1de5a0 100644 --- a/internal/cli/app_test.go +++ b/internal/cli/app_test.go @@ -2,58 +2,65 @@ package cli //nolint:testpackage // needs access to unexported cleanStartupError import ( "errors" + "os" "path/filepath" "testing" + "go.uber.org/fx" + "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/pidlock" ) +// TestCleanStartupError starts a real fx app whose config has a +// blob_size_limit below the minimum. fx puts annotations naming the +// functions it was building in front of the config error; only those +// may be removed, although the config error itself contains "): ". func TestCleanStartupError(t *testing.T) { t.Parallel() - tests := []struct { - name string - in string - want string - }{ - { - name: "real fx error chain", - in: `could not build arguments for function ` + - `"sneak.berlin/go/vaultik/internal/cli".newSnapshotCreateCommand.func1.1 ` + - `(/Users/user/dev/vaultik/internal/cli/snapshot.go:71): ` + - `failed to build *vaultik.Vaultik: ` + - `could not build arguments for function ` + - `"sneak.berlin/go/vaultik/internal/vaultik".New ` + - `(/Users/user/dev/vaultik/internal/vaultik/vaultik.go:59): ` + - `failed to build storage.Storer: ` + - `received non-nil error from function ` + - `"sneak.berlin/go/vaultik/internal/storage".NewStorer ` + - `(/Users/user/dev/vaultik/internal/storage/module.go:23): ` + - `creating base path: mkdir /Volumes/BACKUPS: permission denied`, - want: `creating base path: mkdir /Volumes/BACKUPS: permission denied`, - }, - { - name: "no fx wrapping", - in: "plain error", - want: "plain error", - }, - { - name: "single fx wrapping", - in: `received non-nil error from function "foo" (file.go:1): underlying problem`, - want: "underlying problem", - }, + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte("snapshots:\n"+ + " test:\n"+ + " paths: [/tmp/vaultik-test-source]\n"+ + "storage_url: file:///tmp/vaultik-test-storage\n"+ + "chunk_size: 10MB\n"+ + "blob_size_limit: 30MB\n"), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() + app := fx.New( + fx.NopLogger, + fx.Supply(config.Path(path)), + config.Module, + fx.Invoke(func(*config.Config) {}), + ) - //nolint:err113 // test constructs errors from table input - got := cleanStartupError(errors.New(tt.in)).Error() - if got != tt.want { - t.Errorf("got %q, want %q", got, tt.want) - } - }) + err = app.Start(t.Context()) + if err == nil { + t.Fatal("app started; want a blob_size_limit error") + } + + want := "failed to load config: invalid config: blob_size_limit must " + + "be at least the largest chunk the chunker can emit (chunk_size " + + "times the FastCDC size spread): need at least 40000000 bytes" + + got := cleanStartupError(err).Error() + if got != want { + t.Errorf("got %q, want %q", got, want) + } +} + +// TestCleanStartupErrorNotFromFx checks that an error fx did not wrap is +// shown unchanged. +func TestCleanStartupErrorNotFromFx(t *testing.T) { + t.Parallel() + + //nolint:err113 // a one-off error standing in for a startup failure + got := cleanStartupError(errors.New("plain error")).Error() + if got != "plain error" { + t.Errorf("got %q, want %q", got, "plain error") } } From 66ea7f5f4559df8d3fe36f18abcda2cd5ca0f226 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 01:47:48 +0200 Subject: [PATCH 077/121] Free a cached blob once no file still to restore needs it (closes #324) A restore of selected paths, or one where files failed under --skip-errors, kept the blobs those files share in the temporary cache until it ended: the sweeper freed a blob only once every file in the snapshot database that uses it had been restored, and files outside the selection or that failed never are. The sweeper now asks the restore plan, through pendingFileUsesBlob, whether any pending file still uses a cached blob. The plan holds only this run's files and drops each one once it is restored or has failed. The new test backs up 16 KiB files so it stays quick; the locality backup helper takes the file size for that. Model: opus-5-5 --- internal/vaultik/blobcache.go | 6 +- internal/vaultik/restore.go | 18 +-- internal/vaultik/restore_interrupt_test.go | 3 +- internal/vaultik/restore_locality_test.go | 26 ++-- internal/vaultik/restore_plan.go | 9 +- internal/vaultik/restore_plan_test.go | 18 +-- internal/vaultik/restore_sweeper.go | 102 ++----------- internal/vaultik/restore_sweeper_test.go | 163 +++++++++++++++++++++ 8 files changed, 222 insertions(+), 123 deletions(-) create mode 100644 internal/vaultik/restore_sweeper_test.go diff --git a/internal/vaultik/blobcache.go b/internal/vaultik/blobcache.go index 313c3f9..505f796 100644 --- a/internal/vaultik/blobcache.go +++ b/internal/vaultik/blobcache.go @@ -39,9 +39,9 @@ type blobDiskCacheEntry struct { // internally and will fall back to LRU eviction if curBytes exceeds // maxBytes. Restore passes math.MaxInt64 as maxBytes and drives // eviction itself via Delete() through restoreSweeper, which deletes -// each blob the moment every file that references its chunks has been -// written. LRU never fires under that configuration; it is kept as a -// safety net for callers that don't manage eviction themselves. +// each blob once no file still to be restored in this run needs it. +// LRU never fires under that configuration; it is kept as a safety net +// for callers that don't manage eviction themselves. // // Get/ReadAt/peak-Len counters are debugging instrumentation used by // tests to assert that the restore code path uses ReadAt rather than diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index 9b114ee..a3c8a3f 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -323,12 +323,6 @@ func (v *Vaultik) restoreAllFiles( _ = blobCache.Close() }() - // Per-restore sweep state: every blob_size_limit/100 bytes written, - // scan the cache and delete any blob whose remaining file references - // are all already restored. - sweeper := newRestoreSweeper(v.ctx, repos, blobCache, - v.Config.BlobSizeLimit.Int64()/sweepIntervalDivisor) - blobByHash, blobIDToHash, err := v.buildBlobIndexes(repos) if err != nil { return nil, err @@ -340,6 +334,12 @@ func (v *Vaultik) restoreAllFiles( return nil, fmt.Errorf("building restore plan: %w", err) } + // Per-restore sweep state: every blob_size_limit/100 bytes written, + // scan the cache and delete any blob that no pending file in the + // plan references. + sweeper := newRestoreSweeper(plan, blobCache, + v.Config.BlobSizeLimit.Int64()/sweepIntervalDivisor) + // Ranging over files rather than the map reports them in a stable order. for _, file := range files { if planErr, ok := unplanned[file.ID]; ok { @@ -427,10 +427,8 @@ func (v *Vaultik) runRestoreLoop( continue } - // Record the file as restored so the sweeper can free blobs - // once all referencing files are done, and drop it from the - // plan's indexes so future picks ignore it. - session.sweeper.fileRestored(fileID.String()) + // Drop the file from the plan's indexes so future picks ignore + // it and the sweeper can free blobs no pending file needs. plan.finishFile(fileID) processed++ diff --git a/internal/vaultik/restore_interrupt_test.go b/internal/vaultik/restore_interrupt_test.go index 9d96577..28e09f0 100644 --- a/internal/vaultik/restore_interrupt_test.go +++ b/internal/vaultik/restore_interrupt_test.go @@ -74,7 +74,8 @@ func TestRestoreCleansTempDirOnInterrupt(t *testing.T) { buildLocalityFixture(t, fs, dataDir) cfg, storer, snapshotID := setupLocalityBackup( - context.Background(), t, fs, dataDir, storeDir, dbPath) + context.Background(), t, fs, dataDir, storeDir, dbPath, + localitySourceBytes) // Point the "" temp paths (the blob cache directory and the // snapshot-database directory) at a private directory so the test can diff --git a/internal/vaultik/restore_locality_test.go b/internal/vaultik/restore_locality_test.go index 67b1310..39f15a1 100644 --- a/internal/vaultik/restore_locality_test.go +++ b/internal/vaultik/restore_locality_test.go @@ -63,6 +63,10 @@ type localityCopy struct { data []byte } +// localitySourceBytes is the size of each source file of the locality +// fixture. +const localitySourceBytes = 1024 * 1024 + // buildLocalityFixture writes the adversarial source layout described // in TestRestoreLocalityAndReadAt: 15 sources of 1 MiB each (which the // backup packs into 3 blobs of 5 chunks) plus 9 interleaved-name copies @@ -73,7 +77,6 @@ func buildLocalityFixture( t.Helper() const ( - srcBytes = 1024 * 1024 srcCount = 15 blobsCount = 3 perBlob = srcCount / blobsCount @@ -83,7 +86,7 @@ func buildLocalityFixture( for i := range srcCount { s := &localitySource{ path: fmt.Sprintf("src-%03d.bin", i+1), - data: randomBytes(t, srcBytes), + data: randomBytes(t, localitySourceBytes), } sources[i] = s require.NoError(t, afero.WriteFile( @@ -115,19 +118,20 @@ func buildLocalityFixture( // setupLocalityBackup runs the backup half of the locality test: a // snapshot of dataDir into a file storer with sizes tuned so 15 one-chunk -// files pack into 3 blobs. The index database is closed before returning -// so the restore half runs from remote bytes only. +// files of srcBytes pack into 3 blobs. The index database is closed +// before returning so the restore half runs from remote bytes only. func setupLocalityBackup( ctx context.Context, t *testing.T, fs afero.Fs, - dataDir, storeDir, dbPath string, + dataDir, storeDir, dbPath string, srcBytes int64, ) (*config.Config, *storage.FileStorer, string) { t.Helper() - // chunkSize avg = 4 MiB makes minSize = 1 MiB, so a 1 MiB file - // becomes one chunk. maxBlobSize = 5 MiB packs exactly 5 chunks - // per blob, yielding 3 blobs from 15 source files. - chunkSize := int64(4 * 1024 * 1024) - maxBlobSize := int64(5 * 1024 * 1024) + // An average chunk size of four times srcBytes makes the minimum + // chunk srcBytes, so each source file becomes one chunk. A blob limit + // of five times srcBytes packs exactly 5 chunks per blob, yielding 3 + // blobs from 15 source files. + chunkSize := 4 * srcBytes + maxBlobSize := 5 * srcBytes storer, err := storage.NewFileStorer(storeDir) require.NoError(t, err) @@ -208,7 +212,7 @@ func TestRestoreLocalityAndReadAt(t *testing.T) { ctx := context.Background() cfg, storer, snapshotID := setupLocalityBackup( - ctx, t, fs, dataDir, storeDir, dbPath) + ctx, t, fs, dataDir, storeDir, dbPath, localitySourceBytes) // Wrap the storer so we can count downloads per blob key. counter := newCountingStorer(storer) diff --git a/internal/vaultik/restore_plan.go b/internal/vaultik/restore_plan.go index 2615c52..24b52d5 100644 --- a/internal/vaultik/restore_plan.go +++ b/internal/vaultik/restore_plan.go @@ -31,7 +31,8 @@ var ( // with no further downloads. // - blobFiles: for each blob, the set of pending files referencing // it. Used to short-circuit "when this blob lands, which files -// become ready" without a global scan. +// become ready" without a global scan, and by the sweeper to tell +// whether a cached blob is still needed. type restorePlan struct { fileBlobs map[types.FileID]map[string]struct{} blobFiles map[string]map[types.FileID]struct{} @@ -237,6 +238,12 @@ func (p *restorePlan) filesReferencingBlob(blobHash string) []types.FileID { return out } +// pendingFileUsesBlob reports whether any pending file references the +// named blob, whether or not the blob is cached. +func (p *restorePlan) pendingFileUsesBlob(blobHash string) bool { + return len(p.blobFiles[blobHash]) > 0 +} + // hasPending reports whether any unfinished files remain. func (p *restorePlan) hasPending() bool { return len(p.fileBlobs) > 0 diff --git a/internal/vaultik/restore_plan_test.go b/internal/vaultik/restore_plan_test.go index ce23200..0306717 100644 --- a/internal/vaultik/restore_plan_test.go +++ b/internal/vaultik/restore_plan_test.go @@ -63,15 +63,6 @@ func TestRunRestoreLoopFailsOnAbandonedFiles(t *testing.T) { t.Cleanup(func() { _ = cache.Close() }) - v := &Vaultik{ctx: ctx} - session := &restoreSession{ - v: v, - ctx: ctx, - repos: repos, - sweeper: newRestoreSweeper(ctx, repos, cache, 1), - result: &RestoreResult{}, - } - // A file that is still pending but whose uncached-blob set is empty // and which was never queued as ready: the loop can neither restore // nor download it. This is the abandonment the guard must catch. @@ -83,6 +74,15 @@ func TestRunRestoreLoopFailsOnAbandonedFiles(t *testing.T) { cached: map[string]struct{}{}, } + v := &Vaultik{ctx: ctx} + session := &restoreSession{ + v: v, + ctx: ctx, + repos: repos, + sweeper: newRestoreSweeper(plan, cache, 1), + result: &RestoreResult{}, + } + err = v.runRestoreLoop(session, plan, map[types.FileID]*database.File{}, 0) require.ErrorIs(t, err, errRestoreIncomplete) } diff --git a/internal/vaultik/restore_sweeper.go b/internal/vaultik/restore_sweeper.go index 5659f6b..004a557 100644 --- a/internal/vaultik/restore_sweeper.go +++ b/internal/vaultik/restore_sweeper.go @@ -1,46 +1,30 @@ package vaultik -import ( - "context" - "fmt" - - "sneak.berlin/go/vaultik/internal/database" - "sneak.berlin/go/vaultik/internal/log" -) - -// restoreSweeper frees cached blobs once all files that reference any of -// their chunks have been restored. It works as follows: +// restoreSweeper frees cached blobs once no file still to be restored in +// this run needs them. It works as follows: // -// 1. Callers add a file's ID to an in-memory restored set via -// fileRestored once the file is fully written to disk. -// 2. After each chunk is restored, chunkRestored accumulates a running +// 1. After each chunk is restored, chunkRestored accumulates a running // byte count. -// 3. When the accumulator crosses a threshold (one hundredth of the +// 2. When the accumulator crosses a threshold (one hundredth of the // configured blob size — so a sweep runs about a hundred times per // blob's worth of restored bytes), the sweeper iterates every key in -// the cache. For each cached blob it asks the DB which files -// reference any chunk in that blob, then compares that list against -// the in-memory restored set. If any referencing file is missing -// from the set the blob is kept; otherwise the cache entry is -// deleted. +// the cache and deletes each blob that the restore plan no longer +// needs. // -// All DB reads happen against the snapshot's temporary metadata DB, -// which is local, indexed, and not under contention — the queries are -// cheap and run at most once per blob per sweep interval. +// The plan drops a file once it is restored or has failed, and holds +// only the files this run restores, so files outside the requested paths +// never keep a blob. type restoreSweeper struct { - ctx context.Context //nolint:containedctx // ctx bound at construction by design - repos *database.Repositories + plan *restorePlan cache *blobDiskCache threshold int64 bytesAccum int64 - restored map[string]struct{} } // newRestoreSweeper returns a sweeper that triggers eviction every // `threshold` bytes restored. Callers should pass blob_size_limit/100. func newRestoreSweeper( - ctx context.Context, - repos *database.Repositories, + plan *restorePlan, cache *blobDiskCache, threshold int64, ) *restoreSweeper { @@ -49,21 +33,12 @@ func newRestoreSweeper( } return &restoreSweeper{ - ctx: ctx, - repos: repos, + plan: plan, cache: cache, threshold: threshold, - restored: make(map[string]struct{}), } } -// fileRestored records a file as fully restored. After this call, any -// blob whose only remaining references come from files in the restored -// set may be evicted on the next sweep. -func (s *restoreSweeper) fileRestored(fileID string) { - s.restored[fileID] = struct{}{} -} - // chunkRestored accounts n bytes against the sweep threshold and runs a // sweep if the threshold has been crossed since the last sweep. func (s *restoreSweeper) chunkRestored(n int64) { @@ -76,60 +51,11 @@ func (s *restoreSweeper) chunkRestored(n int64) { s.sweep() } -// sweep deletes any cached blob whose chunks are no longer referenced -// by an unrestored file. Per-blob DB failures are logged and the blob -// is kept — we'd rather hold a blob longer than risk a re-download. +// sweep deletes every cached blob that no pending file references. func (s *restoreSweeper) sweep() { for _, blobHash := range s.cache.Keys() { - needed, err := s.blobStillNeeded(blobHash) - if err != nil { - log.Debug("sweeper referencing-files query failed", - "blob_hash", blobHash[:16], "error", err) - - continue - } - - if !needed { + if !s.plan.pendingFileUsesBlob(blobHash) { s.cache.Delete(blobHash) } } } - -// blobStillNeeded returns true if any file that references a chunk in -// this blob has not yet been restored. On any error the function -// returns true — keeping the blob is always the safe answer because we -// can't prove we're done with it. -func (s *restoreSweeper) blobStillNeeded(blobHash string) (bool, error) { - rows, err := s.repos.DB().Conn().QueryContext(s.ctx, ` - SELECT DISTINCT fc.file_id - FROM file_chunks fc - JOIN blob_chunks bc ON bc.chunk_hash = fc.chunk_hash - JOIN blobs b ON b.id = bc.blob_id - WHERE b.blob_hash = ? - `, blobHash) - if err != nil { - return true, fmt.Errorf("querying referencing files: %w", err) - } - - defer func() { _ = rows.Close() }() - - for rows.Next() { - var fileID string - - err := rows.Scan(&fileID) - if err != nil { - return true, fmt.Errorf("scanning file_id: %w", err) - } - - if _, ok := s.restored[fileID]; !ok { - return true, nil - } - } - - err = rows.Err() - if err != nil { - return true, err - } - - return false, nil -} diff --git a/internal/vaultik/restore_sweeper_test.go b/internal/vaultik/restore_sweeper_test.go new file mode 100644 index 0000000..82729c9 --- /dev/null +++ b/internal/vaultik/restore_sweeper_test.go @@ -0,0 +1,163 @@ +package vaultik //nolint:testpackage // reads the restore blob cache's peak size + +import ( + "context" + "fmt" + "io" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/ui" +) + +// TestRestoreFreesBlobsNoPendingFileNeeds asserts that the restore cache +// frees a blob once no file still to be restored in this run needs it. +// Every original file has a copy with the same content, so every blob +// holds chunks of copies: a restore that leaves the copies out of its +// paths, or fails on them, must not keep the blobs for them. +func TestRestoreFreesBlobsNoPendingFileNeeds(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + // Small files keep the backup and both restores quick. + const fileBytes = 16 * 1024 + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + originalsDir := filepath.Join(dataDir, "originals") + copiesDir := filepath.Join(dataDir, "copies") + storeDir := filepath.Join(tempDir, "remote") + dbPath := filepath.Join(tempDir, "index.sqlite") + + originals := writeFilesWithCopies(t, fs, originalsDir, copiesDir, fileBytes) + + ctx := context.Background() + + cfg, storer, snapshotID := setupLocalityBackup( + ctx, t, fs, dataDir, storeDir, dbPath, fileBytes) + + t.Run("restore by path", func(t *testing.T) { + t.Parallel() + + restoreDir := filepath.Join(tempDir, "by-path") + + peak, err := restorePeakCachedBlobs(ctx, t, fs, cfg, storer, + &RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: restoreDir, + Paths: []string{originalsDir}, + }) + require.NoError(t, err) + + requireRestoredFiles(t, fs, restoreDir, originals) + assert.LessOrEqualf(t, peak, 1, + "peak cached blobs was %d; blobs were kept for unselected files", + peak) + }) + + t.Run("restore with failed files", func(t *testing.T) { + t.Parallel() + + restoreDir := filepath.Join(tempDir, "with-failures") + + // A regular file where the copies directory belongs makes every + // copy fail to restore. + blocker := filepath.Join(restoreDir, copiesDir) + require.NoError(t, fs.MkdirAll(filepath.Dir(blocker), 0o755)) + require.NoError(t, afero.WriteFile(fs, blocker, nil, 0o644)) + + peak, err := restorePeakCachedBlobs(ctx, t, fs, cfg, storer, + &RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: restoreDir, + SkipErrors: true, + }) + require.ErrorIs(t, err, errFilesFailedRestore) + + requireRestoredFiles(t, fs, restoreDir, originals) + assert.LessOrEqualf(t, peak, 1, + "peak cached blobs was %d; blobs were kept for failed files", peak) + }) +} + +// writeFilesWithCopies writes 15 random files of fileBytes into +// originalsDir and a copy of each into copiesDir. With +// setupLocalityBackup given the same size, each file is one chunk and the +// 15 chunks fill 3 blobs. Returns the originals' content by path. +func writeFilesWithCopies( + t *testing.T, fs afero.Fs, originalsDir, copiesDir string, fileBytes int, +) map[string][]byte { + t.Helper() + + const fileCount = 15 + + require.NoError(t, fs.MkdirAll(originalsDir, 0o755)) + require.NoError(t, fs.MkdirAll(copiesDir, 0o755)) + + originals := make(map[string][]byte, fileCount) + + for i := range fileCount { + name := fmt.Sprintf("file-%02d.bin", i) + data := randomBytes(t, fileBytes) + original := filepath.Join(originalsDir, name) + originals[original] = data + + require.NoError(t, afero.WriteFile(fs, original, data, 0o644)) + require.NoError(t, afero.WriteFile( + fs, filepath.Join(copiesDir, name), data, 0o644)) + } + + return originals +} + +// requireRestoredFiles requires every file in want to have been restored +// under restoreDir with its content intact. +func requireRestoredFiles( + t *testing.T, fs afero.Fs, restoreDir string, want map[string][]byte, +) { + t.Helper() + + for path, data := range want { + got, err := afero.ReadFile(fs, filepath.Join(restoreDir, path)) + require.NoErrorf(t, err, "file missing after restore: %s", path) + require.Equalf(t, data, got, "byte mismatch for %s", path) + } +} + +// restorePeakCachedBlobs runs a restore and returns the most blobs its +// cache held at once, together with the restore's error. +func restorePeakCachedBlobs( + ctx context.Context, t *testing.T, fs afero.Fs, + cfg *config.Config, storer storage.Storer, opts *RestoreOptions, +) (int, error) { + t.Helper() + + var cache *blobDiskCache + + v := &Vaultik{ + Config: cfg, + Storage: storer, + Fs: fs, + Stdout: io.Discard, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + restoreCacheObserver: func(c *blobDiskCache) { + cache = c + }, + } + v.SetContext(ctx) + + err := v.Restore(opts) + + require.NotNil(t, cache, "restoreCacheObserver must fire during restore") + + return cache.PeakLen(), err +} From 5db2e920e5f19abb4dcc4a47a829c0cb3723131e Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 02:03:51 +0200 Subject: [PATCH 078/121] Label the index cleanup totals as totals (closes #306) The summary printed by the local index cleanup before each backup gave, in brackets after each removed count, the number of snapshots, files, chunks or blobs left in the local index, worded "(N remain)", which read as incomplete or orphaned rows left over: removing the only incomplete snapshot printed "1 removed (1 remain)". Each line now labels that figure as the total of its kind left in the local index. Model: opus-5-5 --- internal/vaultik/prune_count_test.go | 60 ++++++++++++++++++++++++++++ internal/vaultik/snapshot.go | 12 ++++-- 2 files changed, 68 insertions(+), 4 deletions(-) diff --git a/internal/vaultik/prune_count_test.go b/internal/vaultik/prune_count_test.go index 11401c6..2009e01 100644 --- a/internal/vaultik/prune_count_test.go +++ b/internal/vaultik/prune_count_test.go @@ -1,13 +1,17 @@ package vaultik //nolint:testpackage // exercises unexported count helpers import ( + "bytes" "context" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/ui" ) // TestTableCountForReportSurfacesReadFailure is the regression guard for @@ -76,3 +80,59 @@ func TestCountDiffUnknownWhenEitherSideUnknown(t *testing.T) { assert.Nil(t, countDiff(&before, nil), "unknown after yields unknown delta") assert.Nil(t, countDiff(nil, nil)) } + +// TestPruneDatabaseSummaryLabelsTotals removes the only incomplete +// snapshot from an index that also holds a complete one. The figure in +// brackets is every snapshot left in the local index, so the line must +// say so rather than read as incomplete snapshots that remain. +func TestPruneDatabaseSummaryLabelsTotals(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + + db, err := database.New(ctx, ":memory:") + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + + startedAt := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + completedAt := startedAt.Add(time.Minute) + + require.NoError(t, repos.Snapshots.Create(ctx, nil, &database.Snapshot{ + ID: "host_complete_2026-01-02T03:04:05Z", + Hostname: "host", + StartedAt: startedAt, + CompletedAt: &completedAt, + })) + require.NoError(t, repos.Snapshots.Create(ctx, nil, &database.Snapshot{ + ID: "host_incomplete_2026-01-02T03:04:05Z", + Hostname: "host", + StartedAt: startedAt, + })) + + var out bytes.Buffer + + v := &Vaultik{ + DB: db, + Repositories: repos, + SnapshotManager: snapshot.NewSnapshotManager( + snapshot.SnapshotManagerParams{Repos: repos}), + UI: ui.NewWithColor(&out, false), + } + v.SetContext(ctx) + + result, err := v.PruneDatabase() + require.NoError(t, err) + require.Equal(t, int64(1), result.SnapshotsDeleted) + + assert.Contains(t, out.String(), "Incomplete snapshots: 1 removed "+ + "(total snapshots left in the local index: 1).") + assert.Contains(t, out.String(), "Orphaned files: 0 removed "+ + "(total files left in the local index: 0).") + assert.Contains(t, out.String(), "Orphaned chunks: 0 removed "+ + "(total chunks left in the local index: 0).") + assert.Contains(t, out.String(), "Orphaned blobs: 0 removed "+ + "(total blobs left in the local index: 0).") +} diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 63a9809..52a638a 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -1902,13 +1902,17 @@ func (v *Vaultik) PruneDatabase() (*PruneResult, error) { snapshotsRemain := countDiff(snapshotCountBefore, &result.SnapshotsDeleted) v.UI.Completef("Pruned local index database.") - v.UI.Detailf("Incomplete snapshots: %s removed (%s remain).", + v.UI.Detailf("Incomplete snapshots: %s removed "+ + "(total snapshots left in the local index: %s).", countText(&result.SnapshotsDeleted), countText(snapshotsRemain)) - v.UI.Detailf("Orphaned files: %s removed (%s remain).", + v.UI.Detailf("Orphaned files: %s removed "+ + "(total files left in the local index: %s).", countText(result.FilesDeleted), countText(fileCountAfter)) - v.UI.Detailf("Orphaned chunks: %s removed (%s remain).", + v.UI.Detailf("Orphaned chunks: %s removed "+ + "(total chunks left in the local index: %s).", countText(result.ChunksDeleted), countText(chunkCountAfter)) - v.UI.Detailf("Orphaned blobs: %s removed (%s remain).", + v.UI.Detailf("Orphaned blobs: %s removed "+ + "(total blobs left in the local index: %s).", countText(result.BlobsDeleted), countText(blobCountAfter)) return result, nil From 9fd88a34c7a1e81662d72b4d29d683dbb390bdba Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 02:20:01 +0200 Subject: [PATCH 079/121] Fail snapshot remove when a destination-only snapshot's metadata cannot be deleted (closes #340) When a snapshot was only on the destination store and deleting its metadata there failed, snapshot remove warned and exited 0 having removed nothing. That failure is now an error. A snapshot in the local index keeps its behaviour: it is removed from the local index and the failed delete on the destination store is a warning. The README and the help text said the `vaultik prune` follow-up is printed on every success; they now say it is printed only when metadata was removed from the destination store, and never under --json. The comments on RemoveSnapshot and removeSnapshotRemote describe both cases; removeSnapshotRemote's also says it returns true only when the delete finished without an error and removed at least one object. Model: opus-5-5 --- README.md | 22 +++++++----- internal/cli/snapshot.go | 15 ++++---- internal/vaultik/remove_snapshot_test.go | 35 ++++++++++++++++++ internal/vaultik/snapshot.go | 46 ++++++++++++++++-------- 4 files changed, 89 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 3ba0768..17ff3b9 100644 --- a/README.md +++ b/README.md @@ -360,16 +360,20 @@ snapshot from the local index and strips the snapshot's metadata from the backup destination store. Blobs are NOT touched — deleting blobs requires reading every remaining remote manifest (the destination store may hold snapshots this host doesn't know about), which is what -`vaultik prune` does. On success the command prints the exact `vaultik -prune` invocation to run as a follow-up. An ID that names no snapshot in -the local index or on the destination store is an error; with -`--local-only`, the snapshot must be in the local index. Local row +`vaultik prune` does. The command prints the `vaultik prune` invocation +to run as a follow-up only when it removed the snapshot's metadata from +the destination store, and never under `--json`. An ID that names no +snapshot in the local index or on the destination store is an error; +with `--local-only`, the snapshot must be in the local index. Local row cleanup (files, chunks, blobs the snapshot was the last referrer for) -runs automatically. If the destination store is unreachable, the local-DB -removal still completes and a warning is emitted; run `vaultik snapshot -remove ` again once the store is reachable to remove the -snapshot's metadata from it (`vaultik prune` does not). To wipe everything -on the destination in one go, use `vaultik remote nuke --force`. +runs automatically. If removing the snapshot's metadata from the +destination store fails (for example because the store is unreachable), +the local-DB removal still completes and a warning is emitted; run +`vaultik snapshot remove ` again once the store is reachable +to remove the snapshot's metadata from it (`vaultik prune` does not). For +a snapshot that is only on the destination store, that failure is an +error. To wipe everything on the destination in one go, use `vaultik +remote nuke --force`. * `--local-only`: Skip remote cleanup; only touch the local index * `--dry-run`: Show what would be deleted without deleting * `--force`: Skip confirmation prompt diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 0997140..7fd5b73 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -270,8 +270,9 @@ By default, this removes the snapshot from the local index database and strips the snapshot's metadata from the backup destination store. Blobs are NOT touched: deleting them requires reading every remaining remote manifest (the destination store may hold snapshots this host doesn't -know about), which is what 'vaultik prune' does. On success the command -prints the exact 'vaultik prune' invocation to run as a follow-up. +know about), which is what 'vaultik prune' does. The command prints the +'vaultik prune' invocation to run as a follow-up only when it removed the +snapshot's metadata from the destination store, and never under --json. An ID that names no snapshot in the local index or on the destination store is an error. @@ -280,10 +281,12 @@ Use --local-only to skip the remote half (e.g. when you want to forget a snapshot locally without touching the destination store); the snapshot must then be in the local index. -If the remote is unreachable, the local-database removal still completes -and a warning is emitted; run 'vaultik snapshot remove ' again -once the destination store is reachable to remove the snapshot's metadata -from it ('vaultik prune' does not). +If removing the snapshot's metadata from the destination store fails (for +example because the remote is unreachable), the local-database removal +still completes and a warning is emitted; run 'vaultik snapshot remove +' again once the destination store is reachable to remove +the snapshot's metadata from it ('vaultik prune' does not). For a +snapshot that is only on the destination store, that failure is an error. To wipe the entire destination store and start over, use 'vaultik remote nuke --force' — it is the single supported entry point for that.`, diff --git a/internal/vaultik/remove_snapshot_test.go b/internal/vaultik/remove_snapshot_test.go index 77dfc2f..7e13f7a 100644 --- a/internal/vaultik/remove_snapshot_test.go +++ b/internal/vaultik/remove_snapshot_test.go @@ -17,6 +17,7 @@ import ( "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" "sneak.berlin/go/vaultik/internal/types" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -431,6 +432,40 @@ func TestRemoveSnapshot_NotInLocalIndex(t *testing.T) { assert.Contains(t, out, "Removed snapshot metadata from remote storage") } +// TestRemoveSnapshot_NotInLocalIndexDeleteFails checks that removing a +// snapshot only the destination store holds fails when its metadata +// cannot be deleted there, under --force and under --json: nothing was +// removed, so the command must not succeed. +func TestRemoveSnapshot_NotInLocalIndexDeleteFails(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + for name, opts := range map[string]vaultik.RemoveOptions{ + "force": {Force: true}, + "json": {JSON: true}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + faulty := faultstore.New(store) + faulty.OnDelete = func(string) bool { return true } + + tv := vaultik.NewForTesting(faulty) + tv.Repositories = newLocalIndex(t) + + result, err := tv.RemoveSnapshot("snapshot-001", &opts) + + require.ErrorIs(t, err, faultstore.ErrInjectedDelete) + assert.False(t, result.RemoteRemoved) + assert.True(t, store.hasKey(remoteKeyPath("snapshot-001"))) + assert.Empty(t, tv.Stdout.String()) + }) + } +} + func TestRemoveAllSnapshots_RequiresForce(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 52a638a..d7e5c2d 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -1228,9 +1228,11 @@ const snapshotRemoveCommandHint = "vaultik snapshot remove" // destination store. Blobs are NOT touched: removing a snapshot's // blobs requires reading every remaining remote manifest (the remote // may hold snapshots this host doesn't know about), which is what -// `vaultik prune` is for — the command prints the prune invocation to -// run as a follow-up. When the remote is unreachable the command still -// completes the local-DB removal and warns. +// `vaultik prune` is for — when metadata was removed from the +// destination store, the text output names the prune invocation to run +// as a follow-up. When removing the metadata fails, a snapshot in the +// local index is still removed from it, with a warning; a snapshot +// only on the destination store is an error. func (v *Vaultik) RemoveSnapshot( snapshotID string, opts *RemoveOptions, ) (*RemoveResult, error) { @@ -1265,8 +1267,10 @@ func (v *Vaultik) RemoveSnapshot( } } - if !opts.LocalOnly { - result.RemoteRemoved = v.removeSnapshotRemote(snapshotID, opts) + result.RemoteRemoved, err = v.removeSnapshotRemote( + snapshotID, inLocalIndex, opts) + if err != nil { + return result, err } if v.SnapshotManager != nil { @@ -1391,19 +1395,33 @@ func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) } // removeSnapshotRemote strips the snapshot's metadata from the -// destination store, warning and proceeding on failure: the local-DB -// removal has already happened, so the user is told the remote half -// didn't finish and to run `vaultik snapshot remove` for the snapshot -// again once the destination store is reachable (`vaultik prune` never -// removes snapshot metadata). Returns true when the remote removal -// succeeded and deleted something. -func (v *Vaultik) removeSnapshotRemote(snapshotID string, opts *RemoveOptions) bool { +// destination store. It returns true only when the delete finished +// without an error and removed at least one object; under LocalOnly it +// does nothing. When the snapshot is only on the destination store, a +// failure is returned as an error, because that removal is all the +// command does. When the snapshot was in the local index, its removal +// there has already happened, so a failure is only a warning telling the +// user to run `vaultik snapshot remove` for the snapshot again once the +// destination store is reachable (`vaultik prune` never removes snapshot +// metadata). +func (v *Vaultik) removeSnapshotRemote( + snapshotID string, inLocalIndex bool, opts *RemoveOptions, +) (bool, error) { + if opts.LocalOnly { + return false, nil + } + log.Info("Removing snapshot metadata from remote storage", "snapshot_id", snapshotID) remoteKey := snapshot.RemoteSnapshotKey(snapshotID) deleted, err := v.deleteRemoteSnapshotByKey(remoteKey) + if err != nil && !inLocalIndex { + return false, fmt.Errorf( + "removing snapshot metadata from destination store: %w", err) + } + if err != nil { log.Warn("Could not remove snapshot metadata from remote storage; "+ "run '"+snapshotRemoveCommandHint+"' with the snapshot's ID "+ @@ -1418,10 +1436,10 @@ func (v *Vaultik) removeSnapshotRemote(snapshotID string, opts *RemoveOptions) b err, snapshotRemoveCommandHint, snapshotID) } - return false + return false, nil } - return deleted > 0 + return deleted > 0, nil } // RemoveAllSnapshots removes every snapshot known to the local From d8f4f62f412251bd86d7ee2fe04958dbf6d8bb74 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 03:06:57 +0200 Subject: [PATCH 080/121] Run $EDITOR through the shell in config edit (closes #315) config edit used the whole of $EDITOR as the program name, so a value with arguments such as "code --wait" or "emacsclient -t" failed with "executable file not found". It now runs $EDITOR the way git does: sh -c ' "$@"' with the config path as a separate argument, so the editor's own arguments and quoting work and a path with spaces reaches it whole. A test runs config edit with an $EDITOR carrying an argument on a config path that contains a space. Model: opus-5-5 --- internal/cli/config.go | 9 ++++++++- internal/cli/config_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/internal/cli/config.go b/internal/cli/config.go index 5a00a2f..468d031 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -333,8 +333,15 @@ func newConfigEditCommand() *cobra.Command { editor = "vi" } + // Run $EDITOR through the shell, as git does, so a value + // with arguments such as "code --wait" works. The path + // goes in as an argument ("$@"), not into the command + // text, so a path with spaces or quotes arrives whole. + // sh -c takes the word after the command as $0, which + // is why editor appears twice. //nolint:gosec // G204: launching the operator's own $EDITOR is the point - ed := exec.CommandContext(cmd.Context(), editor, path) + ed := exec.CommandContext(cmd.Context(), + "sh", "-c", editor+` "$@"`, editor, path) ed.Stdin = os.Stdin ed.Stdout = os.Stdout ed.Stderr = os.Stderr diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go index 58ce82c..7dccfa0 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -647,6 +647,30 @@ func TestWriteConfigSetTightensMode(t *testing.T) { } } +// TestConfigEditEditorWithArgument checks that an $EDITOR carrying an +// argument works and that a config path with a space reaches it whole. +// The "editor" is cp with the replacement file as its argument, so the +// config ends up with the replacement's content only if both arrived. +func TestConfigEditEditorWithArgument(t *testing.T) { + dir := t.TempDir() + path := seedFile(t, dir, "my config.yml", "compression_level: 3\n") + edited := seedFile(t, dir, "edited.yml", "compression_level: 9\n") + + setRootFlags(t, RootFlags{ConfigPath: path}) + t.Setenv("EDITOR", "cp '"+edited+"'") + + mustExecute(t, newConfigEditCommand()) + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("reading config back: %v", err) + } + + if string(data) != "compression_level: 9\n" { + t.Errorf("config after edit = %q, want the edited content", data) + } +} + func splitPath(s string) []string { return strings.Split(s, ".") } From aeac897805e9840cc0123a0a3b2aa526a4b2c233 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 03:26:02 +0200 Subject: [PATCH 081/121] Refuse credentials in a storage URL's endpoint or rclone remote name (closes #322) storage_url refused only the outer URL's userinfo and unknown query parameters. Userinfo inside the s3 endpoint= value, and rclone's remote,param=value parameters in the remote name, were accepted and then printed by info, remote info and snapshot create. Both are now refused without echoing the value: a host name never contains "@", and an rclone remote name never contains a comma. An s3 or rclone query that cannot be decoded (a ";" or a bad "%" escape) is refused too, because decoding drops that part before it can be checked. The comma is checked before url.Parse, whose error for such a name prints part of it. The rclone remote name case has its own error pointing at rclone config. Model: opus-5-5 --- internal/storage/url.go | 53 +++++++++++-- internal/storage/url_parse_test.go | 119 +++++++++++++++++++++++++++++ 2 files changed, 166 insertions(+), 6 deletions(-) diff --git a/internal/storage/url.go b/internal/storage/url.go index 3e41198..8d2b046 100644 --- a/internal/storage/url.go +++ b/internal/storage/url.go @@ -30,6 +30,12 @@ var ( "storage URL must not carry credentials; " + "set s3.access_key_id and s3.secret_access_key in the config instead") ErrURLUnknownParam = errors.New("unknown query parameter in storage URL") + ErrURLBadQuery = errors.New( + "storage URL query cannot be decoded; " + + "check it for a ; or a % not followed by two hex digits") + ErrRcloneRemoteParams = errors.New( + "rclone URL must not carry parameters in the remote name; " + + "set them on the remote with rclone config instead") ) // URL represents a parsed storage URL. @@ -90,8 +96,9 @@ func parseFileURL(rawPath string) (*URL, error) { } // parseS3URL parses an s3://bucket/prefix URL. It rejects credentials in -// the userinfo and any query parameter other than endpoint, region and -// ssl, so a credential-bearing URL is never stored or echoed. +// the userinfo or in the endpoint parameter's userinfo, a query that +// cannot be decoded, and any query parameter other than endpoint, region +// and ssl, so a credential-bearing URL is never stored or echoed. func parseS3URL(rawURL string) (*URL, error) { u, err := url.Parse(rawURL) if err != nil { @@ -107,13 +114,26 @@ func parseS3URL(rawURL string) (*URL, error) { return nil, ErrMissingBucket } - query := u.Query() + // u.Query() would silently drop a part it cannot decode, endpoint + // included. The decode error is not wrapped: it can quote the value. + query, err := url.ParseQuery(u.RawQuery) + if err != nil { + return nil, ErrURLBadQuery + } err = rejectUnknownParams(query, "endpoint", "region", "ssl") if err != nil { return nil, err } + // A host name never contains "@", so one in an endpoint, with or + // without a scheme, can only introduce userinfo. + for _, endpoint := range query["endpoint"] { + if strings.Contains(endpoint, "@") { + return nil, ErrURLCredentials + } + } + return &URL{ Scheme: schemeS3, Bucket: bucket, @@ -125,9 +145,23 @@ func parseS3URL(rawURL string) (*URL, error) { } // parseRcloneURL parses an rclone://remote/path URL. rclone:// takes no -// query parameters, so credentials in the userinfo and any parameter at +// query parameters, so credentials in the userinfo, parameters in the +// remote name, a query that cannot be decoded and any query parameter at // all are rejected rather than silently ignored. func parseRcloneURL(rawURL string) (*URL, error) { + // The remote name runs up to the first "/", "?" or "#". It never + // contains a comma; one starts rclone's remote,param=value form, + // whose values can be credentials. This is checked before url.Parse, + // whose error for such a name can print part of it. + remote := strings.TrimPrefix(rawURL, "rclone://") + if end := strings.IndexAny(remote, "/?#"); end >= 0 { + remote = remote[:end] + } + + if strings.Contains(remote, ",") { + return nil, ErrRcloneRemoteParams + } + u, err := url.Parse(rawURL) if err != nil { return nil, wrapParseError(err) @@ -137,12 +171,19 @@ func parseRcloneURL(rawURL string) (*URL, error) { return nil, ErrURLCredentials } - remote := u.Host + remote = u.Host if remote == "" { return nil, ErrMissingRemote } - err = rejectUnknownParams(u.Query()) + // As in parseS3URL: u.Query() would drop a part it cannot decode, and + // the decode error can quote the value. + query, err := url.ParseQuery(u.RawQuery) + if err != nil { + return nil, ErrURLBadQuery + } + + err = rejectUnknownParams(query) if err != nil { return nil, err } diff --git a/internal/storage/url_parse_test.go b/internal/storage/url_parse_test.go index 2151249..b6a9424 100644 --- a/internal/storage/url_parse_test.go +++ b/internal/storage/url_parse_test.go @@ -150,6 +150,19 @@ func TestParseStorageURLRejectsCredentials(t *testing.T) { wantErr: storage.ErrURLCredentials, secrets: []string{key, secret, "mybucket"}, }, + { + name: "s3 userinfo in endpoint", + raw: "s3://mybucket?endpoint=https://" + + key + ":" + secret + "@minio.example.com", + wantErr: storage.ErrURLCredentials, + secrets: []string{key, secret}, + }, + { + name: "s3 userinfo in endpoint without scheme", + raw: "s3://mybucket?endpoint=" + key + ":" + secret + "@minio.example.com", + wantErr: storage.ErrURLCredentials, + secrets: []string{key, secret}, + }, { name: "s3 unknown query param", raw: "s3://mybucket?access_key=" + key + "&secret=" + secret, @@ -203,6 +216,112 @@ func TestParseStorageURLRejectsCredentials(t *testing.T) { } } +// TestParseStorageURLRejectsRcloneRemoteParams checks that an rclone +// remote name carrying parameters (rclone's "remote,param=value" form, +// which can hold a credential) is rejected without echoing the value, +// including the URLs that url.Parse itself refuses. +func TestParseStorageURLRejectsRcloneRemoteParams(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + raw string + secrets []string // must not appear in the error message + }{ + { + name: "configured remote", + raw: "rclone://gdrive,client_secret=topsecret/backups", + secrets: []string{"topsecret"}, + }, + { + name: "remote defined inline", + raw: "rclone://:s3,access_key_id=KEY,secret_access_key=SECRET/bucket", + secrets: []string{"KEY", "SECRET"}, + }, + { + name: "colon in a parameter value", + raw: "rclone://gdrive,client_secret=ab:cd/backups", + secrets: []string{"cd"}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, err := storage.ParseStorageURL(tc.raw) + if !errors.Is(err, storage.ErrRcloneRemoteParams) { + t.Fatalf("ParseStorageURL(%q) error = %v, want %v", + tc.raw, err, storage.ErrRcloneRemoteParams) + } + + for _, secret := range tc.secrets { + if strings.Contains(err.Error(), secret) { + t.Errorf("error message leaked %q: %v", secret, err.Error()) + } + } + }) + } +} + +// TestParseStorageURLRejectsUndecodableQuery checks that an s3 or rclone +// URL whose query cannot be decoded is rejected, not read with that part +// of the query left out, and that the error does not echo it. +func TestParseStorageURLRejectsUndecodableQuery(t *testing.T) { + t.Parallel() + + const ( + key = "AKIAKEY" + secret = "topsecret" + ) + + cases := []struct { + name string + raw string + }{ + { + name: "semicolon", + raw: "s3://mybucket/prefix?endpoint=https://" + key + ":" + secret + + "@minio.example.com:9000;region=us-east-1", + }, + { + name: "bad percent escape", + raw: "s3://mybucket/prefix?endpoint=https://" + key + ":" + secret + + "%zz@minio.example.com:9000", + }, + { + name: "rclone semicolon", + raw: "rclone://gdrive/backups?token=" + secret + ";x=1", + }, + { + name: "rclone bad percent escape", + raw: "rclone://gdrive/backups?token=" + secret + "%zz", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, err := storage.ParseStorageURL(tc.raw) + if err == nil { + t.Fatalf("ParseStorageURL(%q) returned no error", tc.raw) + } + + if !errors.Is(err, storage.ErrURLBadQuery) { + t.Errorf("ParseStorageURL(%q) error = %v, want %v", + tc.raw, err, storage.ErrURLBadQuery) + } + + for _, s := range []string{key, secret, "minio.example.com"} { + if strings.Contains(err.Error(), s) { + t.Errorf("error message leaked %q: %v", s, err.Error()) + } + } + }) + } +} + // TestParseStorageURLParseFailureHidesURL checks that when url.Parse // itself fails, the wrapped error carries only the inner cause, not the // *url.Error whose text embeds the raw (possibly credential-bearing) URL. From d156a02c49b90c761c43c3336da35cc6b3515e99 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 04:04:14 +0200 Subject: [PATCH 082/121] Name each prefix once in restore, verify and purge errors (closes #327) A missing blob during restore, a failed shallow verify and an invalid purge duration each printed their prefix twice. FetchBlob now returns the storage error as is, since restore and deep verify name the blob themselves; purge returns the duration parser's error unchanged; and a failed shallow verify wraps "problems found in storage" instead of "verification failed", which the command already prints. Deep verify words a storage error other than not found as a blob it could not check, and its log line no longer says S3. Already fixed for https://git.eeqj.de/sneak/vaultik/issues/314: the deep verify size message naming S3 and other errors called missing; tests now check both. Not tested: the log line. Model: opus-5-5 --- internal/vaultik/blob_fetch.go | 5 +++-- internal/vaultik/deep_verify_test.go | 11 +++++++++-- internal/vaultik/purge_per_name_test.go | 3 ++- internal/vaultik/restore_skip_errors_test.go | 5 ++++- internal/vaultik/shallow_verify_test.go | 8 +++++++- internal/vaultik/snapshot.go | 7 +++++-- internal/vaultik/verify.go | 4 ++-- 7 files changed, 32 insertions(+), 11 deletions(-) diff --git a/internal/vaultik/blob_fetch.go b/internal/vaultik/blob_fetch.go index aa00243..4672921 100644 --- a/internal/vaultik/blob_fetch.go +++ b/internal/vaultik/blob_fetch.go @@ -104,7 +104,8 @@ func (v *Vaultik) FetchAndDecryptBlob( // FetchBlob downloads a blob and returns a reader for the encrypted data. // The reader is closed as soon as ctx is cancelled, which ends a read -// blocked inside it. +// blocked inside it. A storage error is returned as is: restore and deep +// verify name the blob in their own errors. func (v *Vaultik) FetchBlob( ctx context.Context, blobHash string, ) (io.ReadCloser, error) { @@ -119,7 +120,7 @@ func (v *Vaultik) FetchBlob( rc, err := v.Storage.Get(ctx, blobPath) if err != nil { - return nil, fmt.Errorf("downloading blob %s: %w", shortHash(blobHash), err) + return nil, err } return newCloseOnCancelReader(ctx, rc), nil diff --git a/internal/vaultik/deep_verify_test.go b/internal/vaultik/deep_verify_test.go index 0592935..0651bf2 100644 --- a/internal/vaultik/deep_verify_test.go +++ b/internal/vaultik/deep_verify_test.go @@ -6,6 +6,7 @@ import ( "crypto/rand" "io" "os" + "path" "path/filepath" "testing" @@ -142,7 +143,8 @@ func TestDeepVerifyJSONCountsBlobs(t *testing.T) { // TestDeepVerifyJSONCountsWrongSizeBlob checks that under --deep --json a // blob of the wrong size is counted in mismatched and fails the run, and -// that the check goes on past it to count a missing blob after it. +// that the check goes on past it to count a missing blob after it. The +// store is on disk, so the message must not call it S3. func TestDeepVerifyJSONCountsWrongSizeBlob(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -168,11 +170,14 @@ func TestDeepVerifyJSONCountsWrongSizeBlob(t *testing.T) { require.Equal(t, 1, got.Mismatched) require.Equal(t, 1, got.Missing) require.Zero(t, got.Verified) + require.Contains(t, got.ErrorMessage, "with the wrong size") + require.NotContains(t, got.ErrorMessage, "S3") } // TestDeepVerifyStopsOnBlobThatCannotBeChecked checks that a blob that is // present in storage but cannot be checked is not counted as missing: -// deep verify stops and fails with the storage error. +// deep verify stops and fails, saying it could not check the blob, with +// the storage error. func TestDeepVerifyStopsOnBlobThatCannotBeChecked(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -187,6 +192,8 @@ func TestDeepVerifyStopsOnBlobThatCannotBeChecked(t *testing.T) { require.Error(t, err) require.Equal(t, "failed", got.Status) require.Zero(t, got.Missing) + require.Contains(t, got.ErrorMessage, + "could not check blob "+path.Base(keys[0])) require.Contains(t, got.ErrorMessage, errStatDenied.Error()) } diff --git a/internal/vaultik/purge_per_name_test.go b/internal/vaultik/purge_per_name_test.go index 8b537b8..700bf43 100644 --- a/internal/vaultik/purge_per_name_test.go +++ b/internal/vaultik/purge_per_name_test.go @@ -281,7 +281,8 @@ func TestPurgeOlderThan_TooLargeDeletesNothing(t *testing.T) { OlderThan: "1000y", Force: true, }) - require.Error(t, err) + require.EqualError(t, err, + `invalid duration: "1000y" is longer than about 292 years`) err = v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ OlderThan: "292y", diff --git a/internal/vaultik/restore_skip_errors_test.go b/internal/vaultik/restore_skip_errors_test.go index 376c833..311d21d 100644 --- a/internal/vaultik/restore_skip_errors_test.go +++ b/internal/vaultik/restore_skip_errors_test.go @@ -231,7 +231,8 @@ func (f trailingByteFile) Close() error { } // TestRestoreMissingBlobAbortsWithoutSkipErrors checks that a deleted blob -// still ends the restore with an error when SkipErrors is not set. +// still ends the restore with an error when SkipErrors is not set, and +// that the error names the blob once. func TestRestoreMissingBlobAbortsWithoutSkipErrors(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -247,6 +248,8 @@ func TestRestoreMissingBlobAbortsWithoutSkipErrors(t *testing.T) { }) require.ErrorIs(t, err, storage.ErrNotFound) + assert.Equal(t, 1, strings.Count(err.Error(), "downloading blob"), + err.Error()) } // TestRestoreChunkInNoBlobAbortsWithoutSkipErrors checks that a chunk held diff --git a/internal/vaultik/shallow_verify_test.go b/internal/vaultik/shallow_verify_test.go index 3633cf6..68fe1fe 100644 --- a/internal/vaultik/shallow_verify_test.go +++ b/internal/vaultik/shallow_verify_test.go @@ -27,7 +27,7 @@ import ( // then grows one stored blob so its size no longer matches the manifest. // Shallow verify must then fail, count the grown blob as a size mismatch, // and drop it from the verified count rather than continuing to report it -// as checked. +// as checked, and its error must not repeat the cli layer's prefix. func TestShallowVerifyDetectsWrongBlobSize(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -96,6 +96,12 @@ func TestShallowVerifyDetectsWrongBlobSize(t *testing.T) { require.Equal(t, 1, bad.Mismatched) require.Equal(t, healthy.BlobCount-1, bad.Verified, "the wrong-sized blob must not be counted as verified") + + // The cli layer prints this error after its own "Verification failed:". + err = newVerifier(io.Discard).VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{}) + require.EqualError(t, err, + "problems found in storage: 1 blobs have the wrong size") } // TestShallowVerifyDetectsMissingDatabase backs up a real snapshot, diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index d7e5c2d..38f964b 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -23,6 +23,7 @@ var ( errSnapshotNotInConfig = errors.New("snapshot not found in config") errNoSnapshotsInConfig = errors.New("no snapshots configured") errSnapshotVerifyFailed = errors.New("verification failed") + errProblemsInStorage = errors.New("problems found in storage") errRemoveAllNeedsForce = errors.New("--all requires --force") errSnapshotNotFound = errors.New("snapshot not found") errSnapshotRemoveFailed = errors.New("snapshot(s) could not be removed") @@ -612,7 +613,7 @@ func selectSnapshotsToPurge( case opts.OlderThan != "": duration, err := parseDuration(opts.OlderThan) if err != nil { - return nil, fmt.Errorf("invalid duration: %w", err) + return nil, err } cutoff := time.Now().UTC().Add(-duration) @@ -941,8 +942,10 @@ func (v *Vaultik) formatVerifyResult( v.printVerifySummary(result, failure) } + // Not errSnapshotVerifyFailed: the cli layer prints this after its own + // "Verification failed:". if failure != "" { - return fmt.Errorf("%w: %s", errSnapshotVerifyFailed, failure) + return fmt.Errorf("%w: %s", errProblemsInStorage, failure) } return nil diff --git a/internal/vaultik/verify.go b/internal/vaultik/verify.go index 1fd298c..6c88d93 100644 --- a/internal/vaultik/verify.go +++ b/internal/vaultik/verify.go @@ -680,7 +680,7 @@ func (v *Vaultik) verifyManifestAgainstDatabase( func (v *Vaultik) verifyBlobExistenceFromDB( blobs []snapshot.BlobInfo, result *VerifyResult, ) error { - log.Info("Verifying blob existence in S3", "blob_count", len(blobs)) + log.Info("Verifying blob existence in storage", "blob_count", len(blobs)) for i, blob := range blobs { // The hash is read from the snapshot database, which is not @@ -700,7 +700,7 @@ func (v *Vaultik) verifyBlobExistenceFromDB( result.Missing++ result.MissingSize += blob.CompressedSize case err != nil: - return fmt.Errorf("checking blob %s in storage: %w", + return fmt.Errorf("could not check blob %s in storage: %w", blob.Hash, err) case stat.Size != blob.CompressedSize: log.Warn("Blob has the wrong size in storage", From 54ad279dd6dcc57fcd4d2f4e63111a6d87d5834f Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 04:24:30 +0200 Subject: [PATCH 083/121] Count a file as deleted only if the previous snapshot of its name had it (closes #304) A backup counted as deleted every file in the local index under the source path that the walk did not find: files the snapshot excludes but another snapshot backs up, and files removed long ago, which every later backup, and the first backup of another name over the same path, reported as deleted again. The backup now counts only files that the latest completed snapshot of the same name lists, the walk did not find, and are gone from disk, including a file whose directory became a regular file. Excluded files and files the walk could not reach under --skip-errors are not counted. Only the backup's output changes; the snapshots row stores no deleted figure. Model: opus-5-5 --- ARCHITECTURE.md | 8 +- internal/database/files.go | 39 +++ internal/database/files_test.go | 59 +++++ internal/snapshot/module.go | 26 +- internal/snapshot/scanner.go | 93 +++++-- internal/vaultik/fault_injection_test.go | 23 +- internal/vaultik/snapshot.go | 34 ++- .../vaultik/snapshot_deleted_count_test.go | 249 ++++++++++++++++++ 8 files changed, 481 insertions(+), 50 deletions(-) create mode 100644 internal/vaultik/snapshot_deleted_count_test.go diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b791882..53acfeb 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -279,8 +279,8 @@ Key methods: - `Scan(ctx, path, snapshotID)` → Main scan operation Scan phases: -1. **Phase 0**: Detect deleted files from previous snapshots -2. **Phase 1**: Walk directory, identify files needing processing +1. **Phase 1**: Walk directory, identify files needing processing +2. **Phase 1b**: Count as deleted the files that the previous snapshot of the same name lists, the walk did not find, and are gone from disk; a file that is excluded, or inside an excluded directory, is not counted 3. **Phase 2**: Process files (chunk → pack → upload) #### SnapshotManager @@ -320,13 +320,13 @@ CreateSnapshot(opts) │ │ │ ├─► scanner.Scan(ctx, path, snapshotID) │ │ │ - │ │ ├─► Phase 0: detectDeletedFiles() - │ │ │ │ │ ├─► Phase 1: scanPhase() │ │ │ Walk directory │ │ │ Check file metadata changes │ │ │ Build list of files to process │ │ │ + │ │ ├─► Phase 1b: detectDeletedFiles() + │ │ │ │ │ └─► Phase 2: processPhase() │ │ For each file: │ │ chunker.ChunkReaderStreaming() diff --git a/internal/database/files.go b/internal/database/files.go index 824267c..5608fd5 100644 --- a/internal/database/files.go +++ b/internal/database/files.go @@ -267,6 +267,45 @@ func (r *FileRepository) ListUnderPath( return files, rows.Err() } +// ListUnderPathInSnapshot returns the files that ListUnderPath returns +// for path and that the snapshot lists, in no particular order. +func (r *FileRepository) ListUnderPathInSnapshot( + ctx context.Context, path, snapshotID string, +) ([]*File, error) { + path = strings.TrimRight(path, "/") + dirPrefix := path + "/" + + query := ` + SELECT f.id, f.path, f.source_path, f.mtime, f.mtime_nsec, f.size, + f.mode, f.uid, f.gid, f.link_target + FROM files f + JOIN snapshot_files sf ON sf.file_id = f.id + WHERE sf.snapshot_id = ? + AND (f.path = ? OR substr(f.path, 1, length(?)) = ?) + ` + + rows, err := r.db.conn.QueryContext(ctx, query, + snapshotID, path, dirPrefix, dirPrefix) + if err != nil { + return nil, fmt.Errorf("querying files: %w", err) + } + + defer func() { _ = rows.Close() }() + + var files []*File + + for rows.Next() { + file, err := r.scanFileRows(rows) + if err != nil { + return nil, fmt.Errorf("scanning file: %w", err) + } + + files = append(files, file) + } + + return files, rows.Err() +} + // ListIDsWithChunksNotInUploadedBlobs returns the IDs of the files whose // path starts with prefix and that list at least one chunk held by no // blob whose upload has completed (uploaded_ts set). A new snapshot diff --git a/internal/database/files_test.go b/internal/database/files_test.go index 8153766..343c482 100644 --- a/internal/database/files_test.go +++ b/internal/database/files_test.go @@ -212,6 +212,65 @@ func TestFileRepositoryListUnderPath(t *testing.T) { } } +// ListUnderPathInSnapshot leaves out files outside path and files the +// snapshot does not list, though another snapshot lists them. +func TestFileRepositoryListUnderPathInSnapshot(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + files := database.NewFileRepository(db) + snapshots := database.NewSnapshotRepository(db) + + listed := map[string][]string{ + "one": {"/src/a.txt", "/src2/c.txt"}, + "two": {"/src/b.txt"}, + } + + for snapshotID, paths := range listed { + err := snapshots.Create(ctx, nil, &database.Snapshot{ + ID: types.SnapshotID(snapshotID), + Hostname: "host", + StartedAt: time.Now(), + }) + if err != nil { + t.Fatalf("failed to create snapshot %s: %v", snapshotID, err) + } + + for _, path := range paths { + err := files.Create(ctx, nil, &database.File{ + Path: types.FilePath(path), + MTime: time.Now().Truncate(time.Second), + Mode: 0644, + }) + if err != nil { + t.Fatalf("failed to create %s: %v", path, err) + } + + err = snapshots.AddFile(ctx, nil, snapshotID, path) + if err != nil { + t.Fatalf("failed to add %s to %s: %v", path, snapshotID, err) + } + } + } + + found, err := files.ListUnderPathInSnapshot(ctx, "/src", "one") + if err != nil { + t.Fatalf("failed to list files: %v", err) + } + + got := make([]string, 0, len(found)) + for _, f := range found { + got = append(got, f.Path.String()) + } + + if !slices.Equal(got, []string{"/src/a.txt"}) { + t.Errorf("got %q, want only /src/a.txt", got) + } +} + func TestFileRepositorySymlink(t *testing.T) { t.Parallel() diff --git a/internal/snapshot/module.go b/internal/snapshot/module.go index fc0dfec..e9f6aab 100644 --- a/internal/snapshot/module.go +++ b/internal/snapshot/module.go @@ -16,6 +16,9 @@ type ScannerParams struct { Fs afero.Fs Exclude []string // Exclude patterns (combined global + snapshot-specific) SkipErrors bool // Skip file read errors (log loudly but continue) + // PreviousSnapshotID is the most recent completed snapshot of the + // same name, "" for none. + PreviousSnapshotID string } // Module exports backup functionality as an fx module. @@ -44,17 +47,18 @@ func provideScannerFactory( } return NewScanner(ScannerConfig{ - FS: params.Fs, - ChunkSize: cfg.ChunkSize.Int64(), - Repositories: repos, - Storage: storer, - MaxBlobSize: cfg.BlobSizeLimit.Int64(), - CompressionLevel: cfg.CompressionLevel, - AgeRecipients: cfg.AgeRecipients, - EnableProgress: params.EnableProgress, - UI: params.UI, - Exclude: excludes, - SkipErrors: params.SkipErrors, + FS: params.Fs, + ChunkSize: cfg.ChunkSize.Int64(), + Repositories: repos, + Storage: storer, + MaxBlobSize: cfg.BlobSizeLimit.Int64(), + CompressionLevel: cfg.CompressionLevel, + AgeRecipients: cfg.AgeRecipients, + EnableProgress: params.EnableProgress, + UI: params.UI, + Exclude: excludes, + SkipErrors: params.SkipErrors, + PreviousSnapshotID: params.PreviousSnapshotID, }) } } diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 093a472..10a5541 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -58,6 +58,10 @@ type Scanner struct { compressionLevel int ageRecipient string snapshotID string // Current snapshot being processed + // previousSnapshotID is the most recent completed snapshot of the + // same name, "" for none. Only a file it lists can be counted as + // deleted. + previousSnapshotID string // currentSourcePath is the source directory being scanned, stored with // each file record. currentSourcePath string @@ -129,6 +133,9 @@ type ScannerConfig struct { // SkipErrors skips files that cannot be opened or read (log loudly but // continue); packer, database, encryption, and upload errors still abort. SkipErrors bool + // PreviousSnapshotID is the most recent completed snapshot of the + // same name, "" for none. + PreviousSnapshotID string } // ScanResult contains the results of a scan operation. Files and bytes @@ -207,6 +214,7 @@ func NewScanner(cfg ScannerConfig) *Scanner { compiledExclude: compiledExclude, progress: progress, skipErrors: cfg.SkipErrors, + previousSnapshotID: cfg.PreviousSnapshotID, ui: uiw, pendingChunkHashes: make(map[string]struct{}), } @@ -258,8 +266,9 @@ func (s *Scanner) Scan( filesToProcess := scanResult.FilesToProcess - // Phase 1b: Detect deleted files by comparing DB against scanned files - err = s.detectDeletedFilesFromMap(ctx, knownFiles, existingFiles, result) + // Phase 1b: Detect deleted files by comparing the previous snapshot + // of this name against scanned files + err = s.detectDeletedFiles(ctx, path, existingFiles, result) if err != nil { return nil, fmt.Errorf("detecting deleted files: %w", err) } @@ -439,9 +448,8 @@ func (s *Scanner) summarizeScanPhase( } // loadKnownFiles loads the known files at and beneath path from the -// database into a map for fast lookup. Every loaded file the scan does -// not find is counted as deleted. This avoids per-file database queries -// during the scan phase. +// database into a map for fast lookup. This avoids per-file database +// queries during the scan phase. func (s *Scanner) loadKnownFiles( ctx context.Context, path string, ) (map[string]*database.File, error) { @@ -1954,21 +1962,29 @@ func (s *Scanner) queueFileForBatchInsert( }) } -// detectDeletedFilesFromMap finds files that existed in previous snapshots -// but no longer exist. Uses pre-loaded maps to avoid any filesystem or -// database access. -func (s *Scanner) detectDeletedFilesFromMap( +// detectDeletedFiles counts as deleted each file at or beneath path that +// the previous snapshot of this name lists, the walk did not find, and +// is gone from disk. A file that is excluded, or inside an excluded +// directory, is not counted: the walk skips it whether or not it is +// still on disk. +func (s *Scanner) detectDeletedFiles( ctx context.Context, - knownFiles map[string]*database.File, + path string, existingFiles map[string]struct{}, result *ScanResult, ) error { - if len(knownFiles) == 0 { + if s.previousSnapshotID == "" { return nil } - // Check each known file against the enumerated set (no filesystem access needed) - for path, file := range knownFiles { + previousFiles, err := s.repos.Files.ListUnderPathInSnapshot( + ctx, path, s.previousSnapshotID) + if err != nil { + return fmt.Errorf("listing files of snapshot %s: %w", + s.previousSnapshotID, err) + } + + for _, file := range previousFiles { // Check context cancellation periodically select { case <-ctx.Done(): @@ -1976,13 +1992,22 @@ func (s *Scanner) detectDeletedFilesFromMap( default: } - // Check if the file exists in our enumerated set - if _, exists := existingFiles[path]; !exists { - // File has been deleted - result.FilesDeleted++ - result.BytesDeleted += file.Size - log.Debug("Detected deleted file", "path", path, "size", file.Size) + filePath := file.Path.String() + + _, exists := existingFiles[filePath] + if exists || s.excludedOrInExcludedDir(filePath, path) { + continue } + + // Under --skip-errors the walk also misses what it cannot reach, + // such as the files in a directory it cannot open. + if !s.goneFromDisk(filePath) { + continue + } + + result.FilesDeleted++ + result.BytesDeleted += file.Size + log.Debug("Detected deleted file", "path", filePath, "size", file.Size) } if result.FilesDeleted > 0 { @@ -1993,6 +2018,36 @@ func (s *Scanner) detectDeletedFilesFromMap( return nil } +// excludedOrInExcludedDir reports whether filePath, which is at or +// beneath rootPath, or any directory between rootPath and it, matches an +// exclude pattern. A pattern such as */.local/share/Trash matches the +// directory but not the files inside it, which the walk skips too. +func (s *Scanner) excludedOrInExcludedDir(filePath, rootPath string) bool { + for p := filePath; len(p) > len(rootPath); p = filepath.Dir(p) { + if s.shouldExclude(p, rootPath) { + return true + } + } + + return false +} + +// goneFromDisk reports whether looking filePath up on disk finds that +// it does not exist. Like the walk, it does not follow a symlink, so a +// symlink whose target is gone is still on disk. A file whose directory +// was replaced by a regular file is gone too, though the lookup reports +// "not a directory". +func (s *Scanner) goneFromDisk(filePath string) bool { + var err error + if lstater, ok := s.fs.(afero.Lstater); ok { + _, _, err = lstater.LstatIfPossible(filePath) + } else { + _, err = s.fs.Stat(filePath) + } + + return errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) +} + // wrapPermissionError augments permission errors with platform-specific // remediation instructions. On macOS, TCC-protected directories (Calendars, // Reminders, Photos, etc.) return EPERM unless the running application has diff --git a/internal/vaultik/fault_injection_test.go b/internal/vaultik/fault_injection_test.go index 1595151..805cec3 100644 --- a/internal/vaultik/fault_injection_test.go +++ b/internal/vaultik/fault_injection_test.go @@ -661,17 +661,18 @@ func faultScannerFactory( ) snapshot.ScannerFactory { return func(params snapshot.ScannerParams) *snapshot.Scanner { return snapshot.NewScanner(snapshot.ScannerConfig{ - FS: params.Fs, - Storage: storer, - ChunkSize: faultChunkSize, - MaxBlobSize: faultMaxBlobSize, - CompressionLevel: cfg.CompressionLevel, - AgeRecipients: cfg.AgeRecipients, - Repositories: repos, - EnableProgress: params.EnableProgress, - UI: params.UI, - Exclude: params.Exclude, - SkipErrors: params.SkipErrors, + FS: params.Fs, + Storage: storer, + ChunkSize: faultChunkSize, + MaxBlobSize: faultMaxBlobSize, + CompressionLevel: cfg.CompressionLevel, + AgeRecipients: cfg.AgeRecipients, + Repositories: repos, + EnableProgress: params.EnableProgress, + UI: params.UI, + Exclude: params.Exclude, + SkipErrors: params.SkipErrors, + PreviousSnapshotID: params.PreviousSnapshotID, }) } } diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 38f964b..3adeff9 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -244,12 +244,18 @@ func (v *Vaultik) createNamedSnapshot( return err } + previousSnapshotID, err := v.previousSnapshotID(snapName) + if err != nil { + return err + } + scanner := v.ScannerFactory(snapshot.ScannerParams{ - EnableProgress: !opts.Cron, - UI: v.UI, - Fs: v.Fs, - Exclude: v.Config.GetExcludes(snapName), - SkipErrors: opts.SkipErrors, + EnableProgress: !opts.Cron, + UI: v.UI, + Fs: v.Fs, + Exclude: v.Config.GetExcludes(snapName), + SkipErrors: opts.SkipErrors, + PreviousSnapshotID: previousSnapshotID, }) snapshotID, err := v.SnapshotManager.CreateSnapshotWithName( @@ -284,6 +290,24 @@ func (v *Vaultik) createNamedSnapshot( return nil } +// previousSnapshotID returns the ID of the most recent completed snapshot +// named snapName in the local index, or "" when there is none. +func (v *Vaultik) previousSnapshotID(snapName string) (string, error) { + snapshots, err := v.Repositories.Snapshots.ListRecent(v.ctx, listRecentLimit) + if err != nil { + return "", fmt.Errorf("listing snapshots: %w", err) + } + + for _, s := range snapshots { + if s.CompletedAt != nil && + parseSnapshotName(s.ID.String(), s.Hostname.String()) == snapName { + return s.ID.String(), nil + } + } + + return "", nil +} + // resolveSnapshotPaths resolves source directories to absolute paths // with symlink resolution. func (v *Vaultik) resolveSnapshotPaths(snapName string) ([]string, error) { diff --git a/internal/vaultik/snapshot_deleted_count_test.go b/internal/vaultik/snapshot_deleted_count_test.go new file mode 100644 index 0000000..bce2a4c --- /dev/null +++ b/internal/vaultik/snapshot_deleted_count_test.go @@ -0,0 +1,249 @@ +package vaultik_test + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/304: a +// backup counts a file as deleted only when the previous snapshot of +// the same name had it and it is gone, and never counts an excluded +// file. + +// deletedCountEnv is a backup setup over the source directory src whose +// user-facing output is kept in out. Each test configures its snapshots +// with setSnapshot. +type deletedCountEnv struct { + v *vaultik.Vaultik + out *bytes.Buffer + src string +} + +// newDeletedCountEnv writes files, keyed by path relative to src. +func newDeletedCountEnv(t *testing.T, files map[string][]byte) *deletedCountEnv { + t.Helper() + + ctx := context.Background() + fs := afero.NewOsFs() + tempDir := t.TempDir() + srcDir := filepath.Join(tempDir, "src") + + for rel, content := range files { + path := filepath.Join(srcDir, rel) + require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, afero.WriteFile(fs, path, content, 0o644)) + } + + cfg := faultTestConfig() + cfg.IndexPath = filepath.Join(tempDir, "index.sqlite") + cfg.Snapshots = map[string]config.SnapshotConfig{} + + store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + require.NoError(t, err) + + db, err := database.New(ctx, cfg.IndexPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + out := &bytes.Buffer{} + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + v.UI = ui.NewWithColor(out, false) + + return &deletedCountEnv{v: v, out: out, src: srcDir} +} + +// setSnapshot configures the snapshot name to back up the path rel +// beneath src, with the given excludes. +func (e *deletedCountEnv) setSnapshot(name, rel string, exclude ...string) { + e.v.Config.Snapshots[name] = config.SnapshotConfig{ + Paths: []string{filepath.Join(e.src, rel)}, + Exclude: exclude, + } +} + +// backUp runs a backup of the named snapshot and returns its output. +func (e *deletedCountEnv) backUp(t *testing.T, name string) string { + t.Helper() + + e.out.Reset() + require.NoError(t, e.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Snapshots: []string{name}, + })) + + return e.out.String() +} + +// A file this snapshot excludes is not counted as deleted: neither one +// that another snapshot backs up, nor one that the previous snapshot of +// this name had before the exclude was added. +func TestBackupDoesNotCountExcludedFileAsDeleted(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "top.txt": []byte("top"), + "cache/tmp.bin": []byte("cache"), + "photos/a.jpg": []byte("photo a"), + "photos/b.jpg": []byte("photo b"), + "photos/c.jpg": []byte("photo c"), + }) + env.setSnapshot("photos", "photos") + env.setSnapshot("home", "", "/photos") + + env.backUp(t, "photos") + assert.Contains(t, env.backUp(t, "home"), filesLine(2, 2, 0)) + + env.setSnapshot("home", "", "/photos", "/cache") + assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1)) +} + +// A file inside a directory that an exclude added after a backup +// matches is not counted as deleted, though the pattern matches only the +// directory and the directory is gone from disk. +func TestBackupDoesNotCountFileInExcludedDirectoryAsDeleted(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "top.txt": []byte("top"), + "user/.local/share/Trash/old.txt": []byte("old"), + }) + env.setSnapshot("home", "") + + assert.Contains(t, env.backUp(t, "home"), filesLine(2, 2, 0)) + + require.NoError(t, os.RemoveAll( + filepath.Join(env.src, "user/.local/share/Trash"))) + + env.setSnapshot("home", "", "*/.local/share/Trash") + assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1)) +} + +// A file whose directory was replaced by a regular file of the same name +// is counted as deleted. +func TestBackupCountsFileInDirectoryReplacedByFileAsDeleted(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "dir/inside.txt": []byte("inside"), + }) + env.setSnapshot("home", "") + + assert.Contains(t, env.backUp(t, "home"), filesLine(1, 1, 0)) + + dir := filepath.Join(env.src, "dir") + require.NoError(t, os.RemoveAll(dir)) + require.NoError(t, os.WriteFile(dir, []byte("now a file"), 0o600)) + + assert.Contains(t, env.backUp(t, "home"), + "Files: 1 examined, 1 backed up, 0 unchanged, 1 deleted.") +} + +// Under --skip-errors a file inside a directory that the walk cannot +// open is not counted as deleted: it is still on disk. +func TestBackupDoesNotCountFileInUnopenableDirectoryAsDeleted(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "open.txt": []byte("open"), + "locked/inside.txt": []byte("inside"), + }) + env.setSnapshot("work", "") + + assert.Contains(t, env.backUp(t, "work"), filesLine(2, 2, 0)) + + // A directory's mode does not lock out root, who runs the tests, so + // opening the directory is made to fail instead. + env.v.Fs = &openFailFs{ + path: filepath.Join(env.src, "locked"), + err: os.ErrPermission, + } + + env.out.Reset() + require.NoError(t, env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: true, + Snapshots: []string{"work"}, + })) + assert.Contains(t, env.out.String(), filesLine(1, 0, 1)) +} + +// A backup counts only files that the previous snapshot of its own name +// had, not one that a later snapshot of another name over the same path +// had and that is since removed. +func TestBackupIgnoresSnapshotOfAnotherName(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "kept.txt": []byte("kept"), + }) + env.setSnapshot("home", "") + env.setSnapshot("other", "") + + env.backUp(t, "home") + + // Snapshot start times are kept in whole seconds: wait so that other's + // snapshot is strictly the most recent. + time.Sleep(time.Second) + + extra := filepath.Join(env.src, "extra.txt") + require.NoError(t, os.WriteFile(extra, []byte("extra"), 0o600)) + env.backUp(t, "other") + require.NoError(t, os.Remove(extra)) + + assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1)) +} + +// A file removed from disk is counted as deleted by the next backup of +// the snapshot that had it, and not by any later backup of that +// snapshot, nor by the first backup of another name over the same path. +func TestBackupCountsDeletedFileOnce(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + aContent := bytes.Repeat([]byte("a"), 1000) + bContent := bytes.Repeat([]byte("b"), 2000) + keptContent := bytes.Repeat([]byte("k"), 500) + + env := newDeletedCountEnv(t, map[string][]byte{ + "a.txt": aContent, + "b.txt": bContent, + "kept.txt": keptContent, + }) + env.setSnapshot("home", "") + env.setSnapshot("other", "") + + assert.Contains(t, env.backUp(t, "home"), filesLine(3, 3, 0)) + + require.NoError(t, os.Remove(filepath.Join(env.src, "a.txt"))) + require.NoError(t, os.Remove(filepath.Join(env.src, "b.txt"))) + + summary := env.backUp(t, "home") + assert.Contains(t, summary, + "Files: 1 examined, 0 backed up, 1 unchanged, 2 deleted.") + assert.Contains(t, summary, + fmt.Sprintf("Data: %s total (%s backed up), %s deleted.", + env.v.UI.Size(int64(len(keptContent))), env.v.UI.Size(0), + env.v.UI.Size(int64(len(aContent)+len(bContent))))) + + assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1)) + assert.Contains(t, env.backUp(t, "other"), filesLine(1, 0, 1)) +} From 65036bba1b2fd3afb1616a5ee2d86ff10c1f32a2 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 04:29:36 +0200 Subject: [PATCH 084/121] Make snapshot list report a changed destination instead of advising prune (closes #317) When the local index is bound to a different destination than the configured one, snapshot list now gives the warning prune, snapshot purge and snapshot remove refuse with: both destinations and the two ways out (revert the configuration, or run vaultik database delete). Below the table it replaces the local-only note and its prune advice. With --json it goes to stderr through the logger, so stdout stays the document, whose local rows show remote_present false. Reading the binding moves out of EnsureStorageBinding into storageBinding, which records nothing, so the read-only list can call it without binding a fresh index. Model: opus-5-5 --- README.md | 14 ++++-- internal/vaultik/snapshot_list.go | 37 ++++++++++++-- internal/vaultik/snapshot_list_test.go | 68 ++++++++++++++++++++++++++ internal/vaultik/storage_bind.go | 33 +++++++++---- 4 files changed, 134 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 17ff3b9..f0cc9ba 100644 --- a/README.md +++ b/README.md @@ -323,7 +323,11 @@ read from the manifest. Snapshots in the local index with no counterpart on the destination store are reported below the table as drift, with the `vaultik prune` -invocation that reconciles them. +invocation that reconciles them. If the local index is bound to a +different destination than the configured one (after a change to +`storage_url`, or `s3.endpoint`, `s3.bucket` or `s3.prefix`), the +command says so instead and gives the same two ways out that `prune` +gives: revert the configuration, or run `vaultik database delete`. If the destination store cannot be listed (unmounted volume, permission denied, network down), the command warns, falls back to the @@ -332,9 +336,11 @@ local index alone, and still exits zero. (whether the snapshot is in the local index), `remote_key` (the full 64-character storage key), and `remote_present` (whether it was seen on the destination store, or `null` if the destination could not be - listed). Warnings about an unlistable destination, unreadable - manifests, and a truncated listing all go to stderr through the - logger, so stdout stays a single parseable document. + listed). Warnings about an unlistable destination, a local index + bound to a different destination (with both destinations and the + same two ways out), unreadable manifests, and a truncated listing all + go to stderr through the logger, so stdout stays a single parseable + document. **`snapshot verify`**: Verify snapshot integrity. * Default (shallow): checks that every blob the manifest lists is present in diff --git a/internal/vaultik/snapshot_list.go b/internal/vaultik/snapshot_list.go index 8ed7b6b..7862e2e 100644 --- a/internal/vaultik/snapshot_list.go +++ b/internal/vaultik/snapshot_list.go @@ -61,7 +61,9 @@ const tabPadding = 3 // attempt is made to recover or fabricate the human ID. // // Snapshots in the local index with no counterpart on the destination -// store are reported as drift below the table. +// store are reported as drift below the table, unless the local index +// is bound to a different destination than the configured one: that is +// reported instead. // // If remote listing fails (unmounted volume, permission denied, // network), we degrade to local-only with a warning. List never fails @@ -103,7 +105,26 @@ func (v *Vaultik) ListSnapshots(jsonOutput bool) error { return snapshots[i].Timestamp.After(snapshots[j].Timestamp) }) + stored, configured, err := v.storageBinding() + if err != nil { + return err + } + + // A local index bound to another destination describes that one, so + // its records are expected to be missing here, and prune refuses to + // run. The binding is reported instead of advising prune. + boundElsewhere := stored != "" && stored != configured + if jsonOutput { + // stdout holds only the document, so this goes to the logger. + if boundElsewhere { + log.Warn("Local index is bound to a different backup "+ + "destination; to proceed, revert storage_url (or the s3.* "+ + "endpoint, bucket and prefix) to the bound destination, "+ + "or run 'vaultik database delete'", + "bound_to", stored, "configured", configured) + } + if remoteErr == nil { v.reportJSONListingLimits(listing) } @@ -125,8 +146,13 @@ func (v *Vaultik) ListSnapshots(jsonOutput bool) error { } } + if boundElsewhere { + v.UI.Warningf("%v\n%s", errStorageBindingMismatch, + buildBindingMismatchMessage(stored, configured)) + } + if remoteErr == nil { - v.reportListDrift(snapshots, listing) + v.reportListDrift(snapshots, listing, boundElsewhere) } return nil @@ -432,7 +458,9 @@ func (v *Vaultik) snapshotInfoFromLocal(ls *database.Snapshot) SnapshotInfo { // reportListDrift prints the reconciliation notes the merged table // cannot express on its own: local records with no counterpart on the // destination store, plus counts of remote snapshots that were -// unreadable or omitted. +// unreadable or omitted. Local records are not reported when +// boundElsewhere is set: ListSnapshots has already said why they are +// missing. // // This is what remains of the old reportRemoteDrift, and it no longer // touches the destination store. Its remote-only half collapsed into @@ -441,6 +469,7 @@ func (v *Vaultik) snapshotInfoFromLocal(ls *database.Snapshot) SnapshotInfo { // so `snapshot list` lists the destination exactly once per invocation. func (v *Vaultik) reportListDrift( snapshots []SnapshotInfo, listing *remoteSnapshotListing, + boundElsewhere bool, ) { var localOnly []string @@ -450,7 +479,7 @@ func (v *Vaultik) reportListDrift( } } - if len(localOnly) > 0 { + if len(localOnly) > 0 && !boundElsewhere { v.UI.Warningf("%d local snapshot record(s) not found in backup "+ "destination store:", len(localOnly)) diff --git a/internal/vaultik/snapshot_list_test.go b/internal/vaultik/snapshot_list_test.go index 2dd88e4..ee60b3c 100644 --- a/internal/vaultik/snapshot_list_test.go +++ b/internal/vaultik/snapshot_list_test.go @@ -421,6 +421,74 @@ func TestListSnapshots_LocalOnlyReportedAsDrift(t *testing.T) { assert.NotContains(t, out, "snapshot cleanup") } +// TestListSnapshots_BoundElsewhereDoesNotAdvisePrune covers a changed +// storage_url: the local index is still bound to the old destination, +// so its records are missing from the new one. prune refuses to run in +// that state, so the listing must give the choices prune gives instead +// of advising it. +func TestListSnapshots_BoundElsewhereDoesNotAdvisePrune(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const ( + oldURL = "file:///mnt/backups/old" + newURL = "file:///mnt/backups/new" + ) + + env := newListEnv(t) + env.v.Config.StorageURL = newURL + require.NoError(t, env.v.Repositories.LocalMeta.Set(context.Background(), + database.LocalMetaKeyStorageURL, oldURL)) + env.addLocal(t, listLocalID, time.Date(2026, 3, 1, 10, 0, 0, 0, time.UTC)) + + err := env.v.ListSnapshots(false) + require.NoError(t, err) + + out := env.stdout.String() + + assert.Contains(t, out, listLocalID) + assert.Contains(t, out, + "local index is bound to a different backup destination") + assert.Contains(t, out, oldURL) + assert.Contains(t, out, newURL) + assert.Contains(t, out, "revert storage_url") + assert.Contains(t, out, "vaultik database delete") + assert.NotContains(t, out, "vaultik prune") +} + +// TestListSnapshots_JSONReportsBoundElsewhere is the --json side of the +// test above. Every local row comes out with remote_present false, which +// a script reads as stale local records unless it is told, on stderr, +// that the local index is bound to a different destination. +// +//nolint:paralleltest // captureProcessStderr replaces os.Stderr +func TestListSnapshots_JSONReportsBoundElsewhere(t *testing.T) { + const ( + oldURL = "file:///mnt/backups/old" + newURL = "file:///mnt/backups/new" + ) + + env := newListEnv(t) + env.v.Config.StorageURL = newURL + require.NoError(t, env.v.Repositories.LocalMeta.Set(context.Background(), + database.LocalMetaKeyStorageURL, oldURL)) + env.addLocal(t, listLocalID, time.Date(2026, 3, 1, 10, 0, 0, 0, time.UTC)) + + stderr := captureProcessStderr(t, func() { + require.NoError(t, env.v.ListSnapshots(true)) + }) + + rows := decodeListJSON(t, env.stdout.String()) + require.Len(t, rows, 1) + assert.Equal(t, listLocalID, rows[0].ID) + + assert.Contains(t, stderr, "bound to a different backup destination") + assert.Contains(t, stderr, oldURL) + assert.Contains(t, stderr, newURL) + assert.Contains(t, stderr, "revert storage_url") + assert.Contains(t, stderr, "vaultik database delete") +} + // TestListSnapshots_UnreachableRemoteDegrades covers the promise in the // doc comment: an unreachable destination is a warning plus local-only // output, never a failure. diff --git a/internal/vaultik/storage_bind.go b/internal/vaultik/storage_bind.go index d9fe081..d72ae34 100644 --- a/internal/vaultik/storage_bind.go +++ b/internal/vaultik/storage_bind.go @@ -45,17 +45,9 @@ func (v *Vaultik) EnsureStorageBinding() error { return nil } - configured := v.Config.StorageURL - if configured == "" { - // The s3.* form: bind on its endpoint, bucket and prefix, - // written the way storage_url would name the same destination. - s3 := v.Config.S3 - configured = "s3://" + s3.Bucket + "/" + s3.Prefix + "?endpoint=" + s3.Endpoint - } - - stored, err := v.Repositories.LocalMeta.Get(v.ctx, database.LocalMetaKeyStorageURL) + stored, configured, err := v.storageBinding() if err != nil { - return fmt.Errorf("reading local storage binding: %w", err) + return err } if stored == "" { @@ -78,6 +70,27 @@ func (v *Vaultik) EnsureStorageBinding() error { errStorageBindingMismatch, buildBindingMismatchMessage(stored, configured)) } +// storageBinding returns the destination the local index is bound to +// ("" when no binding is recorded yet), then the configured destination +// written the same way. It records nothing, so a read-only command can +// call it. +func (v *Vaultik) storageBinding() (string, string, error) { + configured := v.Config.StorageURL + if configured == "" { + // The s3.* form: bind on its endpoint, bucket and prefix, + // written the way storage_url would name the same destination. + s3 := v.Config.S3 + configured = "s3://" + s3.Bucket + "/" + s3.Prefix + "?endpoint=" + s3.Endpoint + } + + stored, err := v.Repositories.LocalMeta.Get(v.ctx, database.LocalMetaKeyStorageURL) + if err != nil { + return "", "", fmt.Errorf("reading local storage binding: %w", err) + } + + return stored, configured, nil +} + // buildBindingMismatchMessage assembles the multi-line explanation // shown when the local index is bound to a different destination than // the currently-configured one (the first line lives in the From 291c39174f966416500cfac7035426566f1500fb Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 05:39:27 +0200 Subject: [PATCH 085/121] Warn about restored ownership only when an entry's owner or group differs (closes #316) A restore by a normal user always warned that file ownership was not preserved, even when every entry came out with its recorded owner and group. The owner and group each restored entry has on disk are now compared with the recorded ones, and the warning is printed once if any differ. The comparison is made on disk because on macOS, and in a setgid directory on Linux, a new entry takes the group of its directory, not the user's. Judgement call: an entry that is not on disk after the restore is not compared. Unverified: not run on a Mac; the directory-group test runs only as root. Model: opus-5-5 --- internal/vaultik/restore.go | 47 ++++++- .../vaultik/restore_ownership_warning_test.go | 131 ++++++++++++++++++ 2 files changed, 173 insertions(+), 5 deletions(-) create mode 100644 internal/vaultik/restore_ownership_warning_test.go diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index a3c8a3f..f02caeb 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -12,6 +12,7 @@ import ( "path/filepath" "slices" "strings" + "syscall" "time" "filippo.io/age" @@ -219,9 +220,7 @@ func (v *Vaultik) finishRestore( ) if os.Geteuid() != 0 { - v.UI.Warningf("Restore did not preserve file ownership: chown(2) " + - "requires root. Re-run as root (e.g. with sudo) if you need " + - "original UID/GID preserved.") + v.warnIfOwnershipNotPreserved(files, opts.TargetDir) } if result.FilesFailed > 0 { @@ -247,6 +246,43 @@ func (v *Vaultik) finishRestore( return unmatchedErr } +// warnIfOwnershipNotPreserved warns once if some entry restored under +// targetDir has another owner or group on disk than the snapshot +// records. It is meant for a restore by a normal user, which changes no +// owner or group: a new entry is owned by that user, and its group is +// that user's, or the group of the directory it is created in on macOS +// and in a setgid directory on Linux. An entry that is not on disk, or +// whose filesystem reports no owner, is skipped. +func (v *Vaultik) warnIfOwnershipNotPreserved( + files []*database.File, targetDir string, +) { + for _, file := range files { + targetPath, err := containedRestorePath( + v.Fs, targetDir, file.Path.String()) + if err != nil { + continue + } + + info, err := lstatIfPossible(v.Fs, targetPath) + if err != nil { + continue + } + + owner, ok := info.Sys().(*syscall.Stat_t) + if !ok { + continue + } + + if owner.Uid != file.UID || owner.Gid != file.GID { + v.UI.Warningf("Restore did not preserve file ownership: chown(2) " + + "requires root. Re-run as root (e.g. with sudo) if you need " + + "original UID/GID preserved.") + + return + } + } +} + // reportUnmatchedPaths warns, by name, about each requested path that // matched nothing in the snapshot, and returns an error counting them, // or nil when there are none. @@ -965,8 +1001,9 @@ type restoreSession struct { // root can chown a file to an arbitrary UID/GID — non-root chown // always fails with EPERM. Attempting it anyway produces N // guaranteed-failed syscalls + N noisy debug lines, so we skip - // the call entirely as non-root and emit one warning at the end - // of the restore explaining that ownership was not preserved. + // the call entirely as non-root; warnIfOwnershipNotPreserved warns + // once at the end of the restore if that left any owner or group + // other than recorded. runningAsRoot bool // directories holds every restored directory, for // applyDirectoryMetadata to finish after the restore loop. diff --git a/internal/vaultik/restore_ownership_warning_test.go b/internal/vaultik/restore_ownership_warning_test.go new file mode 100644 index 0000000..9c7353a --- /dev/null +++ b/internal/vaultik/restore_ownership_warning_test.go @@ -0,0 +1,131 @@ +package vaultik //nolint:testpackage // calls the unexported ownership check + +import ( + "bytes" + "context" + "os" + "strings" + "syscall" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/ui" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/316: a +// restore by a normal user warns that ownership was not preserved only +// when some restored entry has another owner or group on disk than the +// snapshot records. + +const ownershipWarning = "did not preserve file ownership" + +// TestOwnershipWarningSilentWhenEntriesMatch checks that a restore whose +// entries all end up with their recorded owner and group prints no +// warning. +func TestOwnershipWarningSilentWhenEntriesMatch(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + targetDir := t.TempDir() + owner := ownerOf(t, targetDir) + + out := restoreAsNormalUser(t, targetDir, []*database.File{ + {Path: "/a", Mode: plainFileMode, UID: owner.Uid, GID: owner.Gid}, + {Path: "/b", Mode: plainFileMode, UID: owner.Uid, GID: owner.Gid}, + }) + + assert.Empty(t, out) +} + +// TestOwnershipWarningWhenOwnerDiffers checks that the warning is printed +// when an entry recorded with another owner is restored owned by the +// restoring user, even though its group matches the recorded one. +func TestOwnershipWarningWhenOwnerDiffers(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + targetDir := t.TempDir() + owner := ownerOf(t, targetDir) + + out := restoreAsNormalUser(t, targetDir, []*database.File{ + {Path: "/a", Mode: plainFileMode, UID: otherOwnerID, GID: owner.Gid}, + }) + + assert.Equal(t, 1, strings.Count(out, ownershipWarning), out) +} + +// TestOwnershipWarningWhenDirectoryGivesItsGroup checks that the warning +// is printed, once, when entries recorded with the restoring user's +// owner and group take another group from the setgid directory they are +// restored into, as every new entry takes its directory's group on +// macOS. +func TestOwnershipWarningWhenDirectoryGivesItsGroup(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + if os.Geteuid() != 0 { + t.Skip("giving a directory to another group needs root") + } + + targetDir := t.TempDir() + user := ownerOf(t, targetDir) + + require.NoError(t, os.Chown(targetDir, -1, int(otherOwnerID))) + require.NoError(t, os.Chmod(targetDir, os.ModeSetgid|writableTestMode)) + + out := restoreAsNormalUser(t, targetDir, []*database.File{ + {Path: "/a", Mode: plainFileMode, UID: user.Uid, GID: user.Gid}, + {Path: "/b", Mode: plainFileMode, UID: user.Uid, GID: user.Gid}, + }) + + assert.Equal(t, 1, strings.Count(out, ownershipWarning), out) +} + +// ownerOf returns the owner and group path has on disk. +func ownerOf(t *testing.T, path string) *syscall.Stat_t { + t.Helper() + + info, err := os.Lstat(path) + require.NoError(t, err) + + owner, ok := info.Sys().(*syscall.Stat_t) + require.True(t, ok) + + return owner +} + +// restoreAsNormalUser restores rows, all empty regular files, into +// targetDir without changing any owner or group, as restore does for a +// normal user, and returns what warnIfOwnershipNotPreserved prints. +func restoreAsNormalUser( + t *testing.T, targetDir string, rows []*database.File, +) string { + t.Helper() + + ctx := context.Background() + rows, repos := makeFiles(ctx, t, rows) + + var out bytes.Buffer + + v := newContainmentVaultik(ctx, afero.NewOsFs()) + v.UI = ui.NewWithColor(&out, false) + + session := &restoreSession{ + v: v, + ctx: ctx, + repos: repos, + opts: &RestoreOptions{TargetDir: targetDir}, + result: &RestoreResult{}, + } + for _, row := range rows { + require.NoError(t, session.restoreFile(row)) + } + + v.warnIfOwnershipNotPreserved(rows, targetDir) + + return out.String() +} From a0de8bfdb7a06d2cc05beccf46109bb5590faa62 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 05:46:42 +0200 Subject: [PATCH 086/121] Refuse a backup destination an unplugged volume left empty (closes #239) Every backup writes vaultik-destination.txt at the destination root. While the local index holds snapshots stored there, a destination without it is not present: snapshot create refuses before writing, prune and snapshot purge fail, and snapshot list and snapshot remove act as for a destination that cannot be listed. snapshot create and snapshot remove check it first. remote nuke deletes the marker last. The file:// backend never creates its destination directory, which protects a directory on a removable volume, not a mount point. Tests back up into directories that exist; fixtures for a written destination carry the marker. Judgement call: the marker is rewritten on every backup. Deviation: for the complexity limit, two blocks moved, unchanged, into snapshotNamesToCreate and confirmRemoveSnapshot. Model: opus-5-5 --- ARCHITECTURE.md | 13 + README.md | 64 +++- docs/REPOSTRUCTURE.md | 7 +- internal/cli/entry_prune_json_test.go | 8 +- internal/cli/entry_snapshot_purge_test.go | 9 +- internal/storage/file.go | 24 +- internal/storage/file_backend_test.go | 40 +++ internal/storage/storer.go | 3 +- internal/vaultik/changed_file_restore_test.go | 4 +- internal/vaultik/deep_verify_test.go | 8 +- internal/vaultik/destination_marker.go | 90 ++++++ internal/vaultik/destination_marker_test.go | 278 ++++++++++++++++++ internal/vaultik/fault_injection_test.go | 28 +- internal/vaultik/integration_test.go | 4 +- internal/vaultik/missing_destination_test.go | 51 +++- internal/vaultik/new_chunk_size_test.go | 2 +- internal/vaultik/prune.go | 14 +- .../purge_local_remote_consistency_test.go | 3 + internal/vaultik/purge_per_name_test.go | 3 + internal/vaultik/remove_quiet_test.go | 4 + internal/vaultik/remove_snapshot_test.go | 15 +- .../vaultik/restore_another_machine_test.go | 2 +- internal/vaultik/restore_interrupt_test.go | 2 +- internal/vaultik/restore_locality_test.go | 2 +- internal/vaultik/restore_perms_test.go | 2 +- internal/vaultik/restore_skip_errors_test.go | 2 +- .../vaultik/restore_snapshot_identity_test.go | 4 +- .../restore_sweeper_integration_test.go | 2 +- internal/vaultik/restore_sweeper_test.go | 2 +- internal/vaultik/restore_truncated_db_test.go | 2 +- .../vaultik/restore_unmatched_path_test.go | 6 +- internal/vaultik/reused_blob_verify_test.go | 2 +- internal/vaultik/same_second_rewrite_test.go | 2 +- internal/vaultik/shallow_verify_test.go | 8 +- internal/vaultik/snapshot.go | 116 +++++--- .../vaultik/snapshot_deleted_count_test.go | 2 +- internal/vaultik/snapshot_failed_file_test.go | 2 +- internal/vaultik/snapshot_list_test.go | 3 + internal/vaultik/snapshot_skip_errors_test.go | 2 +- internal/vaultik/snapshot_summary_test.go | 2 +- internal/vaultik/two_path_snapshot_test.go | 2 +- internal/vaultik/uncompressed_size_test.go | 2 +- internal/vaultik/verify_quiet_test.go | 2 +- 43 files changed, 719 insertions(+), 124 deletions(-) create mode 100644 internal/vaultik/destination_marker.go create mode 100644 internal/vaultik/destination_marker_test.go diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 53acfeb..8079402 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -311,6 +311,8 @@ Repository interfaces: ``` CreateSnapshot(opts) + │ + ├─► markDestination() // Refuse a destination without the marker, then write it │ ├─► PruneDatabase() // Critical: avoid dedup errors │ @@ -367,6 +369,8 @@ CreateSnapshot(opts) ``` bucket/ +├── vaultik-destination.txt # Marker written by every backup +│ ├── blobs/ │ └── {hash[0:2]}/ │ └── {hash[2:4]}/ @@ -378,6 +382,15 @@ bucket/ └── manifest.json.zst # Blob list (for pruning/verification) ``` +A destination without `vaultik-destination.txt` is treated as not present +while the local index holds snapshots stored there (`checkDestinationMarker` +in `internal/vaultik/destination_marker.go`): `snapshot create` refuses to +write to it, `prune` and `snapshot purge` fail, and `snapshot list` and +`snapshot remove` behave as for a destination that cannot be listed. This +keeps those commands from taking an unplugged volume's empty mount point for +a destination whose snapshots are all gone. The `file://` backend never +creates its destination directory, so a write to a missing one fails. + The `{remote-key}` directory name is a one-way double SHA-256 hash of the human snapshot ID, so the human ID (hostname, snapshot name, timestamp) is never written to the store as a directory name. See diff --git a/README.md b/README.md index f0cc9ba..a84d9ff 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,10 @@ grep 'public key' vaultik_backup_private_key.txt vaultik config set age_recipients.0 age1YOUR_PUBLIC_KEY_HERE vaultik config set storage_url "file:///Volumes/usbstick/mybackup" +# create the destination directory; vaultik never creates it, so a backup +# to a volume that is not plugged in fails instead of filling the disk +mkdir /Volumes/usbstick/mybackup + # macOS only: grant your terminal app Full Disk Access first # (System Settings → Privacy & Security → Full Disk Access), otherwise # the backup will abort with a permission error on protected directories @@ -298,6 +302,10 @@ value where a list belongs or a word where a number belongs), is refused. this duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`). Without `--prune`, or with a value that is not a valid duration, the command fails before the backup starts. +* Fails before it writes anything when a `file://` destination directory + does not exist, or when the local index holds snapshots and the + destination has no `vaultik-destination.txt` (see + [remote storage layout](#remote-storage-layout)) **`snapshot list`**: Show every snapshot known to this host — the union of the local index and the backup destination store — with timestamps @@ -331,7 +339,10 @@ gives: revert the configuration, or run `vaultik database delete`. If the destination store cannot be listed (unmounted volume, permission denied, network down), the command warns, falls back to the -local index alone, and still exits zero. +local index alone, and still exits zero. It does the same when the +destination has no `vaultik-destination.txt` while the local index +holds snapshots stored there, as when a volume mounted at the +destination is unplugged and leaves its empty mount point behind. * `--json`: Output in JSON format. Each entry carries `locally_tracked` (whether the snapshot is in the local index), `remote_key` (the full 64-character storage key), and `remote_present` (whether it was seen @@ -373,13 +384,14 @@ snapshot in the local index or on the destination store is an error; with `--local-only`, the snapshot must be in the local index. Local row cleanup (files, chunks, blobs the snapshot was the last referrer for) runs automatically. If removing the snapshot's metadata from the -destination store fails (for example because the store is unreachable), -the local-DB removal still completes and a warning is emitted; run -`vaultik snapshot remove ` again once the store is reachable -to remove the snapshot's metadata from it (`vaultik prune` does not). For -a snapshot that is only on the destination store, that failure is an -error. To wipe everything on the destination in one go, use `vaultik -remote nuke --force`. +destination store fails (for example because the store is unreachable, +or the local index holds snapshots and the destination has no +`vaultik-destination.txt`), the local-DB removal still completes and a +warning is emitted; run `vaultik snapshot remove ` again +once the store is reachable to remove the snapshot's metadata from it +(`vaultik prune` does not). For a snapshot that is only on the +destination store, that failure is an error. To wipe everything on the +destination in one go, use `vaultik remote nuke --force`. * `--local-only`: Skip remote cleanup; only touch the local index * `--dry-run`: Show what would be deleted without deleting * `--force`: Skip confirmation prompt @@ -410,8 +422,12 @@ manifest on the destination store to compute the still-referenced blob set and delete any blob not in that set. Step (3) reads all remote manifests — network cost scales with the number of snapshots. `snapshot create --prune` runs the same cleanup automatically; this is the -manual entry point for the same work. If a blob cannot be deleted, the -command (and `snapshot create --prune`) exits non-zero. +manual entry point for the same work. If the destination store cannot +be listed, or the local index holds snapshots and the destination has +no `vaultik-destination.txt` (an unplugged volume's empty mount point), +prune fails and deletes nothing. `snapshot purge` does the same. If a +blob cannot be deleted, the command (and `snapshot create --prune`) +exits non-zero. * `--force`: Skip confirmation prompt * `--json`: Output stats as JSON. Also skips the confirmation prompt, as `--force` does. A blob that cannot be deleted is counted in @@ -435,11 +451,12 @@ since `prune` never deletes it. * `--json`: Output as JSON **`remote nuke`**: Delete every object under `metadata/` and `blobs/` on -the backup destination store, whatever its name, leaving the bucket prefix -empty. Destructive and irreversible. This is the single supported way to -wipe the entire destination store. If a listing afterwards still finds -anything there, the command names each object left and exits non-zero; -running it again deletes what is left. +the backup destination store, whatever its name, and then +`vaultik-destination.txt`, leaving the bucket prefix empty. Destructive +and irreversible. This is the single supported way to wipe the entire +destination store. If a listing afterwards still finds anything under +`metadata/` or `blobs/`, the command names each object left and exits +non-zero; running it again deletes what is left. * `--force`: Required to confirm destruction. **`database delete`**: Delete the local SQLite state database file @@ -464,7 +481,12 @@ object store. Credentials are read from `s3.access_key_id` and a local or mounted filesystem. Useful for testing or backing up to a NAS. The path must be absolute; a relative one is refused when the config loads. Percent-escapes in the path are decoded, so `my%20stick` and `my stick` name -the same directory. +the same directory. The directory must exist before the first backup: vaultik +never creates it. A directory on a removable volume is gone while the volume is +not mounted, so a backup then fails instead of writing to the disk under the +mount point. The mount point itself stays behind when the volume is unplugged: +there only `vaultik-destination.txt` stops such a backup, and only while the +local index holds snapshots. **Rclone** (`rclone://remote/path`): Uses rclone's 70+ supported cloud providers. Requires rclone to be configured separately (`rclone config`). @@ -495,6 +517,7 @@ For an implementation-level view of the internals — the data model, the ``` // +├── vaultik-destination.txt # Marker written by every backup ├── blobs/ │ └── // └── metadata/ @@ -503,6 +526,15 @@ For an implementation-level view of the internals — the data model, the └── manifest.json.zst # Unencrypted blob list (for pruning) ``` +* `vaultik-destination.txt` holds one fixed line of text, with no host + name, path or time. A destination without it is treated as not + present while the local index holds snapshots stored there: + `snapshot create` refuses to write to it, `prune` and `snapshot purge` + fail, and `snapshot list` and `snapshot remove` behave as for a + destination that cannot be listed. This keeps an unplugged volume's empty mount point + from being taken for a destination whose snapshots are all gone. Mount + the volume if it is removable; if the destination was emptied on + purpose, run `vaultik database delete` and back up again. * Blobs are two-level directory sharded using the first 4 hex chars of the blob hash * `db.zst.age` is a binary SQLite database (zstd compressed, age encrypted) containing all file metadata, chunk mappings, and relationships for the snapshot diff --git a/docs/REPOSTRUCTURE.md b/docs/REPOSTRUCTURE.md index 0ad5884..36711c7 100644 --- a/docs/REPOSTRUCTURE.md +++ b/docs/REPOSTRUCTURE.md @@ -4,7 +4,7 @@ This document describes the structure and organization of data stored in the S3 ## Overview -Vaultik stores all backup data in an S3-compatible object store. The repository consists of two main components: +Vaultik stores all backup data in an S3-compatible object store. The repository consists of two main components, plus a marker file: 1. **Blobs** - The actual backup data (content-addressed, encrypted) 2. **Metadata** - Snapshot information and manifests (partially encrypted) @@ -12,6 +12,7 @@ Vaultik stores all backup data in an S3-compatible object store. The repository ``` // +├── vaultik-destination.txt ├── blobs/ │ └── / │ └── / @@ -24,6 +25,10 @@ Vaultik stores all backup data in an S3-compatible object store. The repository The metadata subdirectory is named with the **remote key**, a one-way hash of the snapshot ID, not with the human-readable snapshot ID itself. See [Remote Key Derivation](#remote-key-derivation). +## Marker File (`vaultik-destination.txt`) + +Every backup writes this file at the root before it uploads anything. It holds one fixed line of plain text and names no host, path or time. A destination without it is treated as not present while the local index holds snapshots stored there: `snapshot create` refuses to write to it, and `prune`, `snapshot purge`, `snapshot remove` and `snapshot list` behave as for a destination that cannot be listed. An unplugged volume leaves an empty directory at its mount point, and without the marker that directory would read as a destination whose snapshots are all gone. `remote nuke` deletes the marker last. + ## Blobs Directory (`blobs/`) ### Structure diff --git a/internal/cli/entry_prune_json_test.go b/internal/cli/entry_prune_json_test.go index b220df4..a326535 100644 --- a/internal/cli/entry_prune_json_test.go +++ b/internal/cli/entry_prune_json_test.go @@ -101,7 +101,8 @@ func TestEntryPruneJSONStdoutIsExactlyOneDocument(t *testing.T) { // writeHermeticPruneConfig builds a config over a temp directory with an // empty destination directory and, if seedStale is set, creates the // index database up front with one snapshot record that has no -// counterpart on the destination store. Returns the config path. +// counterpart on the destination store, and gives the destination the +// marker a backup writes. Returns the config path. func writeHermeticPruneConfig(t *testing.T, seedStale bool) string { t.Helper() @@ -131,6 +132,11 @@ func writeHermeticPruneConfig(t *testing.T, seedStale bool) string { if seedStale { seedStaleSnapshotRecord(t, indexPath) + + // While the local index holds a snapshot, prune fails on a + // destination without the marker a backup writes. + require.NoError(t, os.WriteFile( + filepath.Join(storeDir, "vaultik-destination.txt"), nil, 0o600)) } return configPath diff --git a/internal/cli/entry_snapshot_purge_test.go b/internal/cli/entry_snapshot_purge_test.go index 64d7a81..3f7b8c8 100644 --- a/internal/cli/entry_snapshot_purge_test.go +++ b/internal/cli/entry_snapshot_purge_test.go @@ -41,6 +41,11 @@ func TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails(t *testing.T) // too, so the purge selects it rather than dropping it as stale. seedStaleSnapshotRecord(t, indexPath) + // While the local index holds a snapshot, purge fails on a + // destination without the marker a backup writes. + require.NoError(t, os.WriteFile( + filepath.Join(dir, "store", "vaultik-destination.txt"), nil, 0o600)) + manifestDir := filepath.Join(dir, "store", "metadata", snapshot.RemoteSnapshotKey(stalePruneSnapshotID)) require.NoError(t, os.MkdirAll(manifestDir, 0o750)) @@ -59,10 +64,12 @@ func TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails(t *testing.T) require.NoError(t, err) require.NoError(t, db.Close()) - code, _, _ := runEntry(t, flagConfig, configPath, + code, _, stderr := runEntry(t, flagConfig, configPath, cmdSnapshot, cmdPurge, flagOlderThan, "30d", flagForce) assert.Equal(t, 1, code) + assert.Contains(t, stderr, "simulated index error", + "the purge must fail at the local-index delete") assert.FileExists(t, manifestPath, "the snapshot is still in the local index, so its metadata must stay") } diff --git a/internal/storage/file.go b/internal/storage/file.go index 83769a6..af97ef7 100644 --- a/internal/storage/file.go +++ b/internal/storage/file.go @@ -21,9 +21,13 @@ type FileStorer struct { // NewFileStorer creates a new filesystem storage backend. // // Construction is intentionally cheap and does not touch the filesystem. -// The basePath is recorded; the directory is created lazily on first -// write. Write operations (Put/PutWithProgress) call MkdirAll for the -// per-blob parent directory, which also covers basePath on first use. +// The backend never creates basePath: the user does, so that when +// basePath is a directory on an unplugged volume, a write fails instead +// of landing on the disk under the mount point. This does not hold when +// basePath is the mount point itself, which stays behind when its volume +// is unplugged. +// Put and PutWithProgress fail on a missing basePath and create the +// directories below it as needed. // Get and Stat report a key under a missing basePath as ErrNotFound. // List and ListStream fail on a missing basePath, because listing it as // an empty store would make `prune` drop every local snapshot record. @@ -299,7 +303,19 @@ func (f *FileStorer) writeAtomic( path := f.fullPath(key) dir := filepath.Dir(path) - err := f.fs.MkdirAll(dir, storageDirPerm) + // Checked on every write, so a destination that disappears part-way + // through a backup fails it rather than being recreated by MkdirAll. + _, err := f.fs.Stat(f.basePath) + if os.IsNotExist(err) { + return fmt.Errorf("destination directory does not exist; "+ + "create it, or mount the volume it is on: %w", err) + } + + if err != nil { + return fmt.Errorf("checking destination directory: %w", err) + } + + err = f.fs.MkdirAll(dir, storageDirPerm) if err != nil { return fmt.Errorf("creating directories: %w", err) } diff --git a/internal/storage/file_backend_test.go b/internal/storage/file_backend_test.go index ec84910..15cf6a8 100644 --- a/internal/storage/file_backend_test.go +++ b/internal/storage/file_backend_test.go @@ -292,3 +292,43 @@ func TestFileStorerDeletePartialUploadsThroughSymlinkedDirectory(t *testing.T) { }) } } + +// TestFileStorerPutMissingDestination checks that a write fails when the +// destination directory has gone, even after earlier writes to it +// succeeded, and that it does not create the directory again. +func TestFileStorerPutMissingDestination(t *testing.T) { + t.Parallel() + + ctx := context.Background() + base := filepath.Join(t.TempDir(), "usbstick") + + err := os.Mkdir(base, 0o750) + if err != nil { + t.Fatalf("Mkdir: %v", err) + } + + s, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + err = s.Put(ctx, "blobs/aa/bb/first", strings.NewReader("first")) + if err != nil { + t.Fatalf("first Put: %v", err) + } + + err = os.Rename(base, base+"-unplugged") + if err != nil { + t.Fatalf("Rename: %v", err) + } + + err = s.Put(ctx, "blobs/aa/bb/second", strings.NewReader("second")) + if !errors.Is(err, fs.ErrNotExist) { + t.Errorf("Put = %v, want a not-exist error", err) + } + + _, err = os.Stat(base) + if !errors.Is(err, fs.ErrNotExist) { + t.Errorf("Put created the destination directory again (Stat = %v)", err) + } +} diff --git a/internal/storage/storer.go b/internal/storage/storer.go index 44a4861..85081f3 100644 --- a/internal/storage/storer.go +++ b/internal/storage/storer.go @@ -41,7 +41,8 @@ type Info struct { // directory for filesystem). type Storer interface { // Put stores data at the specified key. - // Parent directories are created automatically for filesystem backends. + // The filesystem backend fails when its destination directory does + // not exist, and creates the directories below it as needed. Put(ctx context.Context, key string, data io.Reader) error // PutWithProgress stores data with progress reporting. diff --git a/internal/vaultik/changed_file_restore_test.go b/internal/vaultik/changed_file_restore_test.go index 01ed0ec..e82c2b3 100644 --- a/internal/vaultik/changed_file_restore_test.go +++ b/internal/vaultik/changed_file_restore_test.go @@ -137,7 +137,7 @@ func TestBackupAfterRemovingNewestSnapshotRestoresChangedFile(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") changedPath := filepath.Join(dataDir, "appended.bin") @@ -184,7 +184,7 @@ func TestBackupAfterInterruptedRunRestoresChangedFile(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") changedPath := filepath.Join(dataDir, "appended.bin") diff --git a/internal/vaultik/deep_verify_test.go b/internal/vaultik/deep_verify_test.go index 0651bf2..63ea4f1 100644 --- a/internal/vaultik/deep_verify_test.go +++ b/internal/vaultik/deep_verify_test.go @@ -35,7 +35,7 @@ func TestDeepVerifyAcceptsHealthyAndRejectsCorruptBlob(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") chunkSize := int64(64 * 1024) @@ -94,7 +94,7 @@ func TestDeepVerifyJSONCountsBlobs(t *testing.T) { fs := afero.NewOsFs() ctx := context.Background() - storeDir := filepath.Join(t.TempDir(), "remote") + storeDir := t.TempDir() cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir) @@ -151,7 +151,7 @@ func TestDeepVerifyJSONCountsWrongSizeBlob(t *testing.T) { fs := afero.NewOsFs() ctx := context.Background() - storeDir := filepath.Join(t.TempDir(), "remote") + storeDir := t.TempDir() cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir) @@ -183,7 +183,7 @@ func TestDeepVerifyStopsOnBlobThatCannotBeChecked(t *testing.T) { t.Parallel() ctx := context.Background() - storeDir := filepath.Join(t.TempDir(), "remote") + storeDir := t.TempDir() cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir) failing := statFailingStorer{Storer: storer, failKeys: []string{keys[0]}} diff --git a/internal/vaultik/destination_marker.go b/internal/vaultik/destination_marker.go new file mode 100644 index 0000000..7ce437d --- /dev/null +++ b/internal/vaultik/destination_marker.go @@ -0,0 +1,90 @@ +package vaultik + +import ( + "errors" + "fmt" + "strings" + + "sneak.berlin/go/vaultik/internal/storage" +) + +// destinationMarkerKey is the object every backup writes at the root of +// the backup destination store. While the local index holds a snapshot +// stored there, a destination without it is treated as not present: an +// unplugged volume leaves an empty directory at its mount point, which +// would otherwise read as a store whose snapshots are all gone. +const destinationMarkerKey = "vaultik-destination.txt" + +// destinationMarkerText is the whole content of the marker. It names no +// host, path or time. +const destinationMarkerText = "This is a vaultik backup destination store.\n" + +// errDestinationNotPresent is returned when the local index holds a +// snapshot stored on the backup destination store and the store has no +// marker. +var errDestinationNotPresent = errors.New("backup destination store is not present") + +// checkDestinationMarker returns errDestinationNotPresent when the local +// index holds a snapshot stored on the backup destination store and the +// store has no marker. With no snapshot in the local index, as on a +// first backup or on another machine, there is nothing to check; nor +// when the local index is bound to a different destination than the +// configured one, since its snapshots are stored there. +func (v *Vaultik) checkDestinationMarker() error { + ids, err := v.localSnapshotIDs() + if err != nil { + return fmt.Errorf("listing local snapshots: %w", err) + } + + if len(ids) == 0 { + return nil + } + + // Config is nil only in tests, which then record no binding (see + // EnsureStorageBinding). + if v.Config != nil { + stored, configured, err := v.storageBinding() + if err != nil { + return err + } + + if stored != "" && stored != configured { + return nil + } + } + + _, err = v.Storage.Stat(v.ctx, destinationMarkerKey) + if errors.Is(err, storage.ErrNotFound) { + return fmt.Errorf("%w: %s has no %s, but the local index holds "+ + "snapshots stored there; mount the volume if it is removable, "+ + "or if the destination was emptied on purpose, run "+ + "'vaultik database delete' and back up again", + errDestinationNotPresent, v.Storage.Info().Location, + destinationMarkerKey) + } + + if err != nil { + return fmt.Errorf("checking for %s: %w", destinationMarkerKey, err) + } + + return nil +} + +// markDestination checks the backup destination store with +// checkDestinationMarker and then writes the marker, so a first backup +// marks its destination and a later one writes the same text again. +func (v *Vaultik) markDestination() error { + err := v.checkDestinationMarker() + if err != nil { + return err + } + + err = v.Storage.Put(v.ctx, destinationMarkerKey, + strings.NewReader(destinationMarkerText)) + if err != nil { + return fmt.Errorf("writing %s to the backup destination store: %w", + destinationMarkerKey, err) + } + + return nil +} diff --git a/internal/vaultik/destination_marker_test.go b/internal/vaultik/destination_marker_test.go new file mode 100644 index 0000000..03775d6 --- /dev/null +++ b/internal/vaultik/destination_marker_test.go @@ -0,0 +1,278 @@ +package vaultik_test + +import ( + "bytes" + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/239: a +// file:// destination at a volume's mount point leaves an empty directory +// behind when the volume is unplugged. While the local index holds +// snapshots, a destination without vaultik-destination.txt is not present, +// so no command may write to it or conclude from it that the local +// snapshots are gone. + +// markerFile is the name of the file a backup writes at the root of the +// destination. +const markerFile = "vaultik-destination.txt" + +// backUpThenUnplugMountPoint backs up to a file:// destination, then +// moves the destination directory away and leaves an empty directory in +// its place, as unplugging a volume mounted there would. It returns the +// path of that empty directory. +func backUpThenUnplugMountPoint( + ctx context.Context, t *testing.T, +) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer, string) { + t.Helper() + + storeDir := filepath.Join(t.TempDir(), "mnt") + v, repos, out := backUpToFileDestination(ctx, t, storeDir) + + require.NoError(t, os.Rename(storeDir, storeDir+"-unplugged")) + require.NoError(t, os.Mkdir(storeDir, 0o750)) + + return v, repos, out, storeDir +} + +// assertUntouched checks that the local index still holds its one +// snapshot and that nothing was written to the empty mount point. +func assertUntouched( + ctx context.Context, t *testing.T, + repos *database.Repositories, storeDir string, +) { + t.Helper() + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "no local snapshot record may be deleted") + + entries, err := os.ReadDir(storeDir) + require.NoError(t, err) + assert.Empty(t, entries, "nothing may be written to the empty mount point") +} + +// TestFirstBackupWritesMarker checks that a backup writes the marker +// file at the root of the destination. +func TestFirstBackupWritesMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + storeDir := t.TempDir() + backUpToFileDestination(context.Background(), t, storeDir) + + assert.FileExists(t, filepath.Join(storeDir, markerFile)) +} + +// TestBackupRefusesDestinationWithoutMarker checks that snapshot create +// --prune writes nothing and drops no local snapshot record when the +// destination has no marker. +func TestBackupRefusesDestinationWithoutMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, _, storeDir := backUpThenUnplugMountPoint(ctx, t) + + err := v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Cron: true, + Prune: true, + }) + require.ErrorContains(t, err, markerFile) + + assertUntouched(ctx, t, repos, storeDir) +} + +// TestBackupChecksMarkerBeforeDroppingIncompleteSnapshots checks that +// snapshot create writes nothing when the local index holds only an +// incomplete snapshot and the destination has no marker. The backup drops +// incomplete snapshots before it scans; checked after that, the local +// index would hold none and nothing would be checked. +func TestBackupChecksMarkerBeforeDroppingIncompleteSnapshots(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := t.TempDir() + v, repos := newFileDestinationVaultik(ctx, t, storeDir) + + require.NoError(t, repos.Snapshots.Create(ctx, nil, &database.Snapshot{ + ID: "host_first_2026-01-02T03:04:05Z", + Hostname: "host", + StartedAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), + })) + + err := backUp(v, "first") + require.ErrorContains(t, err, markerFile) + + assertUntouched(ctx, t, repos, storeDir) +} + +// TestPruneRefusesDestinationWithoutMarker checks that prune fails and +// deletes no local snapshot record when the destination has no marker. +func TestPruneRefusesDestinationWithoutMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, _, storeDir := backUpThenUnplugMountPoint(ctx, t) + + err := v.Prune(&vaultik.PruneOptions{Force: true}) + require.ErrorContains(t, err, markerFile) + + assertUntouched(ctx, t, repos, storeDir) +} + +// TestPurgeRefusesDestinationWithoutMarker checks that snapshot purge +// fails and deletes no local snapshot record when the destination has no +// marker. +func TestPurgeRefusesDestinationWithoutMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, _, storeDir := backUpThenUnplugMountPoint(ctx, t) + + err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + KeepLatest: true, + Force: true, + }) + require.ErrorContains(t, err, markerFile) + + assertUntouched(ctx, t, repos, storeDir) +} + +// TestRemoveSnapshotWarnsWhenDestinationHasNoMarker checks that snapshot +// remove warns that the metadata could not be removed from a destination +// without a marker, instead of reporting that it was. +func TestRemoveSnapshotWarnsWhenDestinationHasNoMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out, _ := backUpThenUnplugMountPoint(ctx, t) + + result, err := v.RemoveSnapshot(localSnapshotID(ctx, t, repos, "first"), + &vaultik.RemoveOptions{Force: true}) + require.NoError(t, err) + + assert.False(t, result.RemoteRemoved) + assert.Contains(t, out.String(), + "Could not remove snapshot metadata from remote") + assert.Contains(t, out.String(), markerFile) + assert.NotContains(t, out.String(), + "Removed snapshot metadata from remote storage") +} + +// TestRemoveSnapshotOnlyOnDestinationFailsWithoutMarker checks that +// snapshot remove, for a snapshot that is only on the destination, fails +// saying the destination is not present when it has no marker, instead +// of saying the snapshot does not exist. +func TestRemoveSnapshotOnlyOnDestinationFailsWithoutMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "mnt") + v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + require.NoError(t, backUp(v, "second")) + + id := localSnapshotID(ctx, t, repos, "first") + _, err := v.RemoveSnapshot(id, + &vaultik.RemoveOptions{Force: true, LocalOnly: true}) + require.NoError(t, err) + + // Unplug the volume: an empty directory stays at its mount point. + require.NoError(t, os.Rename(storeDir, storeDir+"-unplugged")) + require.NoError(t, os.Mkdir(storeDir, 0o750)) + + _, err = v.RemoveSnapshot(id, &vaultik.RemoveOptions{Force: true}) + require.ErrorContains(t, err, markerFile) + require.ErrorContains(t, err, "mount the volume") + + assertUntouched(ctx, t, repos, storeDir) +} + +// TestListSnapshotsWarnsWhenDestinationHasNoMarker checks that snapshot +// list warns and shows the local index alone when the destination has no +// marker, without reporting the local snapshot as missing from it. +func TestListSnapshotsWarnsWhenDestinationHasNoMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out, _ := backUpThenUnplugMountPoint(ctx, t) + id := localSnapshotID(ctx, t, repos, "first") + + require.NoError(t, v.ListSnapshots(false)) + + assert.Contains(t, out.String(), "Could not list backup destination store") + assert.Contains(t, out.String(), markerFile) + assert.Contains(t, out.String(), id) + assert.NotContains(t, out.String(), "not found in backup destination store") +} + +// TestListSnapshotsAfterStorageURLChangeToEmptyDirectory checks that +// snapshot list, after storage_url is changed to an empty directory, +// warns only that the local index is bound to a different destination: +// the local snapshots are stored at the old one, so the new one's lack +// of a marker says nothing. With --json the local row is not on the new +// destination, so remote_present is false, not unknown. +func TestListSnapshotsAfterStorageURLChangeToEmptyDirectory(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out := backUpToFileDestination(ctx, t, t.TempDir()) + id := localSnapshotID(ctx, t, repos, "first") + + newDir := t.TempDir() + store, err := storage.NewFileStorer(newDir) + require.NoError(t, err) + + v.Storage = store + v.Config.StorageURL = "file://" + newDir + + require.NoError(t, v.ListSnapshots(false)) + + assert.Contains(t, out.String(), id) + assert.Contains(t, out.String(), + "local index is bound to a different backup destination") + assert.NotContains(t, out.String(), "Could not list backup destination store") + assert.NotContains(t, out.String(), markerFile) + + out.Reset() + require.NoError(t, v.ListSnapshots(true)) + + rows := decodeListJSON(t, out.String()) + require.Len(t, rows, 1) + require.NotNil(t, rows[0].RemotePresent) + assert.False(t, *rows[0].RemotePresent) +} + +// TestBackupAfterNukeRemoteSucceeds checks that remote nuke leaves the +// destination ready for a new first backup, which writes the marker +// again. +func TestBackupAfterNukeRemoteSucceeds(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + storeDir := t.TempDir() + v, _, _ := backUpToFileDestination(context.Background(), t, storeDir) + + require.NoError(t, v.NukeRemote(true)) + assert.NoFileExists(t, filepath.Join(storeDir, markerFile)) + + require.NoError(t, backUp(v, "second")) + assert.FileExists(t, filepath.Join(storeDir, markerFile)) +} diff --git a/internal/vaultik/fault_injection_test.go b/internal/vaultik/fault_injection_test.go index 805cec3..c3f2f5d 100644 --- a/internal/vaultik/fault_injection_test.go +++ b/internal/vaultik/fault_injection_test.go @@ -192,7 +192,7 @@ func assertRestoreRejectsDamagedBlob( fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -238,7 +238,7 @@ func TestDeepVerifyCatchesLyingBackend(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") ctx := context.Background() @@ -290,7 +290,7 @@ func TestInterruptedBlobUploadRecordsNoUploadedBlob(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") ctx := context.Background() @@ -298,10 +298,6 @@ func TestInterruptedBlobUploadRecordsNoUploadedBlob(t *testing.T) { writeFaultSourceTree(t, fs, dataDir) - // No upload succeeds, so nothing creates the destination directory. - // It must exist for the listing below to show that no blob survived. - require.NoError(t, os.Mkdir(storeDir, 0o750)) - inner, err := storage.NewFileStorer(storeDir) require.NoError(t, err) @@ -365,7 +361,7 @@ func TestBackupRetryAfterInterruptedUploadIsRestorable(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -429,7 +425,7 @@ func TestBackupSurvivesMetadataExportInterruption(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") ctx := context.Background() @@ -445,6 +441,10 @@ func TestBackupSurvivesMetadataExportInterruption(t *testing.T) { repos := database.NewRepositories(db) + // snapshot create writes the marker; this backup runs its steps one + // by one, so the marker is written here. + require.NoError(t, inner.Put(ctx, markerFile, strings.NewReader(""))) + // Back up and complete with a working backend. sm := newFaultSnapshotManager(fs, inner, cfg, repos) scanner := newFaultScanner(fs, inner, cfg, repos) @@ -493,8 +493,14 @@ func TestBackupSurvivesMetadataExportInterruption(t *testing.T) { "shallow verify must report the missing manifest") // snapshot list must not crash on the partial snapshot. + var listOut strings.Builder + + reader.UI = ui.NewWithColor(&listOut, false) require.NoError(t, reader.ListSnapshots(false), "snapshot list must tolerate a partially-exported snapshot") + assert.NotContains(t, listOut.String(), + "Could not list backup destination store", + "snapshot list must read the partial snapshot from the destination") } // Scenario 2, repair: the process dies during the metadata export of a @@ -511,7 +517,7 @@ func TestBackupCompletesOnlyAfterMetadataExport(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -687,7 +693,7 @@ func TestRestoreReportsDiskFull(t *testing.T) { osFS := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") diff --git a/internal/vaultik/integration_test.go b/internal/vaultik/integration_test.go index e2891ee..f9a90b7 100644 --- a/internal/vaultik/integration_test.go +++ b/internal/vaultik/integration_test.go @@ -771,7 +771,7 @@ func TestEndToEndFileStorage(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -964,7 +964,7 @@ func TestDedupOnlySnapshotRestores(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") diff --git a/internal/vaultik/missing_destination_test.go b/internal/vaultik/missing_destination_test.go index e3d3561..cf8cc54 100644 --- a/internal/vaultik/missing_destination_test.go +++ b/internal/vaultik/missing_destination_test.go @@ -24,13 +24,11 @@ import ( // that is not plugged in, cannot be listed. It is not an empty store, so // no command may conclude from it that the local snapshots are gone. -// backUpToFileDestination backs up the snapshot named "first" to a -// file:// destination at storeDir, which need not exist yet. Everything -// the returned Vaultik prints after the backup goes to the returned -// buffer. -func backUpToFileDestination( +// newFileDestinationVaultik returns a Vaultik that backs up the +// snapshot named "first" to a file:// destination at storeDir. +func newFileDestinationVaultik( ctx context.Context, t *testing.T, storeDir string, -) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer) { +) (*vaultik.Vaultik, *database.Repositories) { t.Helper() osFs := afero.NewOsFs() @@ -49,8 +47,22 @@ func backUpToFileDestination( repos := database.NewRepositories(db) cfg := changedFileConfig(dataDir, dbPath) - v := newBackupVaultik(ctx, cfg, store, repos, db, osFs) + return newBackupVaultik(ctx, cfg, store, repos, db, osFs), repos +} + +// backUpToFileDestination creates the directory storeDir, as a user must +// before the first backup, and backs up the snapshot named "first" to a +// file:// destination there. Everything the returned Vaultik prints +// after the backup goes to the returned buffer. +func backUpToFileDestination( + ctx context.Context, t *testing.T, storeDir string, +) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer) { + t.Helper() + + require.NoError(t, os.MkdirAll(storeDir, 0o750)) + + v, repos := newFileDestinationVaultik(ctx, t, storeDir) require.NoError(t, backUp(v, "first")) out := &bytes.Buffer{} @@ -75,21 +87,28 @@ func backUpThenUnplug( return v, repos, out } -// TestFirstBackupCreatesDestinationDirectory checks that a first backup -// to a destination directory that does not exist yet creates it, and -// that the destination can be listed afterwards. -func TestFirstBackupCreatesDestinationDirectory(t *testing.T) { +// TestBackupFailsWhenDestinationDirectoryMissing checks that a backup to +// a file:// destination whose directory does not exist fails before it +// records a snapshot, and does not create the directory. +func TestBackupFailsWhenDestinationDirectoryMissing(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() ctx := context.Background() - storeDir := filepath.Join(t.TempDir(), "volume", "backup") - v, _, out := backUpToFileDestination(ctx, t, storeDir) + volume := filepath.Join(t.TempDir(), "volume") + v, repos := newFileDestinationVaultik(ctx, t, filepath.Join(volume, "backup")) - require.NoError(t, v.ListSnapshots(false)) + err := backUp(v, "first") + require.ErrorIs(t, err, fs.ErrNotExist) + require.ErrorContains(t, err, "create it, or mount the volume it is on") - assert.NotContains(t, out.String(), "Could not list backup destination store") - assert.NotContains(t, out.String(), "not found in backup destination store") + _, err = os.Stat(volume) + require.ErrorIs(t, err, fs.ErrNotExist, + "the backup must not create the destination directory") + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Empty(t, snapshots) } // TestListSnapshotsWarnsWhenDestinationMissing checks that snapshot list diff --git a/internal/vaultik/new_chunk_size_test.go b/internal/vaultik/new_chunk_size_test.go index 5301334..c9e9254 100644 --- a/internal/vaultik/new_chunk_size_test.go +++ b/internal/vaultik/new_chunk_size_test.go @@ -39,7 +39,7 @@ func TestNewChunkSizeOfChangedFileStaysFixed(t *testing.T) { appendRandomBytes(t, fs, files, changedPath, appendedFileSize) - store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + store, err := storage.NewFileStorer(t.TempDir()) require.NoError(t, err) db, err := database.New(ctx, dbPath) diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index 6d07e41..f8e68cc 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -42,9 +42,10 @@ const blobKeyParts = 4 // NukeRemote deletes every object under metadata/ and blobs/ in remote // storage, whatever its name, along with any object an upload cut off -// part-way left under a temporary `.partial` name. It returns -// successfully only when a listing afterwards finds nothing left there, -// and the next backup then starts from scratch. +// part-way left under a temporary `.partial` name, and last the +// destination marker. It returns successfully only when a listing +// afterwards finds nothing left under metadata/ and blobs/, and the next +// backup then starts from scratch. // // Refuses to run unless force is true. The caller is responsible for // confirming with the user. @@ -105,6 +106,13 @@ func (v *Vaultik) emptyDestinationStore() error { return fmt.Errorf("%d %w", len(left), errObjectsLeft) } + // Last, once the local snapshot records are gone: the next backup + // then has none and writes the marker again. + err = v.Storage.Delete(v.ctx, destinationMarkerKey) + if err != nil { + return fmt.Errorf("deleting %s: %w", destinationMarkerKey, err) + } + return nil } diff --git a/internal/vaultik/purge_local_remote_consistency_test.go b/internal/vaultik/purge_local_remote_consistency_test.go index c3d827f..72dd91c 100644 --- a/internal/vaultik/purge_local_remote_consistency_test.go +++ b/internal/vaultik/purge_local_remote_consistency_test.go @@ -35,6 +35,9 @@ func setupConsistencyTest( repos := database.NewRepositories(db) mockStorage := NewMockStorer() + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, mockStorage.Put(ctx, markerFile, strings.NewReader(""))) + for _, id := range snapshotIDs { parts := strings.Split(id, "_") startedAt, err := time.Parse(time.RFC3339, parts[len(parts)-1]) diff --git a/internal/vaultik/purge_per_name_test.go b/internal/vaultik/purge_per_name_test.go index 700bf43..58c8af1 100644 --- a/internal/vaultik/purge_per_name_test.go +++ b/internal/vaultik/purge_per_name_test.go @@ -45,6 +45,9 @@ func setupPurgeTest( repos := database.NewRepositories(db) mockStorage := NewMockStorer() + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, mockStorage.Put(ctx, markerFile, strings.NewReader(""))) + // Insert each snapshot into the DB and create remote metadata stubs. // Use timestamps parsed from snapshot IDs for realistic ordering. for _, id := range snapshotIDs { diff --git a/internal/vaultik/remove_quiet_test.go b/internal/vaultik/remove_quiet_test.go index c8916fd..4116780 100644 --- a/internal/vaultik/remove_quiet_test.go +++ b/internal/vaultik/remove_quiet_test.go @@ -96,6 +96,10 @@ func TestRemoveSnapshot_QuietSuppressesReport(t *testing.T) { store := newTestStorer() addManifest(t, store, "snapshot-001", nil) + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + tv := vaultik.NewForTesting(store) tv.Repositories = newLocalIndex(t, "snapshot-001") tv.UI.SetQuiet(true) diff --git a/internal/vaultik/remove_snapshot_test.go b/internal/vaultik/remove_snapshot_test.go index 7e13f7a..c9cc7fe 100644 --- a/internal/vaultik/remove_snapshot_test.go +++ b/internal/vaultik/remove_snapshot_test.go @@ -304,6 +304,10 @@ func TestRemoveSnapshot_DefaultRemovesMetadataNotBlobs(t *testing.T) { addBlob(t, store, blobUnique) addBlob(t, store, blobShared) + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + tv := vaultik.NewForTesting(store) tv.Repositories = newLocalIndex(t, "snapshot-001", "snapshot-002") @@ -373,6 +377,10 @@ func TestRemoveSnapshot_UnknownIDIsError(t *testing.T) { store := newTestStorer() addManifest(t, store, "snapshot-001", nil) + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + tv := vaultik.NewForTesting(store) tv.Repositories = newLocalIndex(t, "snapshot-001") @@ -393,7 +401,12 @@ func TestRemoveSnapshot_NoMetadataOnDestination(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() - tv := vaultik.NewForTesting(newTestStorer()) + // A backup wrote to this destination, so it carries the marker. + store := newTestStorer() + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + + tv := vaultik.NewForTesting(store) tv.Repositories = newLocalIndex(t, "snapshot-001") result, err := tv.RemoveSnapshot("snapshot-001", diff --git a/internal/vaultik/restore_another_machine_test.go b/internal/vaultik/restore_another_machine_test.go index 3f53202..3d0fde9 100644 --- a/internal/vaultik/restore_another_machine_test.go +++ b/internal/vaultik/restore_another_machine_test.go @@ -42,7 +42,7 @@ func TestRestoreOnAnotherMachine(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") diff --git a/internal/vaultik/restore_interrupt_test.go b/internal/vaultik/restore_interrupt_test.go index 28e09f0..134e3f3 100644 --- a/internal/vaultik/restore_interrupt_test.go +++ b/internal/vaultik/restore_interrupt_test.go @@ -65,7 +65,7 @@ func TestRestoreCleansTempDirOnInterrupt(t *testing.T) { root := t.TempDir() dataDir := filepath.Join(root, "source") - storeDir := filepath.Join(root, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(root, "restored") dbPath := filepath.Join(root, "index.sqlite") diff --git a/internal/vaultik/restore_locality_test.go b/internal/vaultik/restore_locality_test.go index 39f15a1..19e03e6 100644 --- a/internal/vaultik/restore_locality_test.go +++ b/internal/vaultik/restore_locality_test.go @@ -201,7 +201,7 @@ func TestRestoreLocalityAndReadAt(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") diff --git a/internal/vaultik/restore_perms_test.go b/internal/vaultik/restore_perms_test.go index 9dbcfc5..837aa8d 100644 --- a/internal/vaultik/restore_perms_test.go +++ b/internal/vaultik/restore_perms_test.go @@ -107,7 +107,7 @@ func backupOneFile( require.NoError(t, afero.WriteFile(fs, srcPath, content, mode)) require.NoError(t, fs.Chmod(srcPath, mode)) - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") storer, err := storage.NewFileStorer(storeDir) diff --git a/internal/vaultik/restore_skip_errors_test.go b/internal/vaultik/restore_skip_errors_test.go index 311d21d..8c3bcf1 100644 --- a/internal/vaultik/restore_skip_errors_test.go +++ b/internal/vaultik/restore_skip_errors_test.go @@ -348,7 +348,7 @@ func backupSingleChunkFiles( require.NoError(t, afero.WriteFile(fs, path, files[path], 0o644)) } - storer, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + storer, err := storage.NewFileStorer(t.TempDir()) require.NoError(t, err) db, err := database.New(ctx, dbPath) diff --git a/internal/vaultik/restore_snapshot_identity_test.go b/internal/vaultik/restore_snapshot_identity_test.go index 5cdedd4..c7e6dea 100644 --- a/internal/vaultik/restore_snapshot_identity_test.go +++ b/internal/vaultik/restore_snapshot_identity_test.go @@ -29,7 +29,7 @@ func TestRestoreAndDeepVerifyRejectSwappedDatabase(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() chunkSize := int64(64 * 1024) @@ -100,7 +100,7 @@ func TestDeepVerifyRejectsSwappedDatabaseWithEmptyManifest(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() chunkSize := int64(64 * 1024) diff --git a/internal/vaultik/restore_sweeper_integration_test.go b/internal/vaultik/restore_sweeper_integration_test.go index 13cc5cc..57b8563 100644 --- a/internal/vaultik/restore_sweeper_integration_test.go +++ b/internal/vaultik/restore_sweeper_integration_test.go @@ -186,7 +186,7 @@ func TestRestoreSweeperEvictsBlobs(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") diff --git a/internal/vaultik/restore_sweeper_test.go b/internal/vaultik/restore_sweeper_test.go index 82729c9..1f767f3 100644 --- a/internal/vaultik/restore_sweeper_test.go +++ b/internal/vaultik/restore_sweeper_test.go @@ -34,7 +34,7 @@ func TestRestoreFreesBlobsNoPendingFileNeeds(t *testing.T) { dataDir := filepath.Join(tempDir, "source") originalsDir := filepath.Join(dataDir, "originals") copiesDir := filepath.Join(dataDir, "copies") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") originals := writeFilesWithCopies(t, fs, originalsDir, copiesDir, fileBytes) diff --git a/internal/vaultik/restore_truncated_db_test.go b/internal/vaultik/restore_truncated_db_test.go index aeedd79..4b03715 100644 --- a/internal/vaultik/restore_truncated_db_test.go +++ b/internal/vaultik/restore_truncated_db_test.go @@ -33,7 +33,7 @@ func TestRestoreRejectsTruncatedMetadataDB(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") diff --git a/internal/vaultik/restore_unmatched_path_test.go b/internal/vaultik/restore_unmatched_path_test.go index 44c437d..c9da298 100644 --- a/internal/vaultik/restore_unmatched_path_test.go +++ b/internal/vaultik/restore_unmatched_path_test.go @@ -32,7 +32,7 @@ func TestRestoreNamesUnmatchedPathAndRestoresTheMatchingOne(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -89,7 +89,7 @@ func TestRestoreNamesEveryPathWhenNothingMatches(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") linkDir := filepath.Join(tempDir, "srclink") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -152,7 +152,7 @@ func TestRestoreNamesUnmatchedPathWhenADamagedBlobStopsIt(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") diff --git a/internal/vaultik/reused_blob_verify_test.go b/internal/vaultik/reused_blob_verify_test.go index 68cd715..f499e0e 100644 --- a/internal/vaultik/reused_blob_verify_test.go +++ b/internal/vaultik/reused_blob_verify_test.go @@ -28,7 +28,7 @@ func TestVerifyPassesWhenBackupReusesStoredBlob(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() secondDBPath := filepath.Join(tempDir, "second.sqlite") chunkSize := int64(64 * 1024) diff --git a/internal/vaultik/same_second_rewrite_test.go b/internal/vaultik/same_second_rewrite_test.go index 998330b..80464f0 100644 --- a/internal/vaultik/same_second_rewrite_test.go +++ b/internal/vaultik/same_second_rewrite_test.go @@ -25,7 +25,7 @@ func TestBackupOfSameSecondRewriteRestoresNewContent(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") rewrittenPath := filepath.Join(dataDir, "small.txt") diff --git a/internal/vaultik/shallow_verify_test.go b/internal/vaultik/shallow_verify_test.go index 68fe1fe..ce5a294 100644 --- a/internal/vaultik/shallow_verify_test.go +++ b/internal/vaultik/shallow_verify_test.go @@ -36,7 +36,7 @@ func TestShallowVerifyDetectsWrongBlobSize(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") chunkSize := int64(32 * 1024) @@ -116,7 +116,7 @@ func TestShallowVerifyDetectsMissingDatabase(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") chunkSize := int64(32 * 1024) @@ -199,7 +199,7 @@ func TestShallowVerifyReportsStatErrorsApartFromMissing(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") chunkSize := int64(32 * 1024) @@ -288,7 +288,7 @@ func TestShallowVerifyQuietFailsOnStatErrorAlone(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") chunkSize := int64(32 * 1024) diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 3adeff9..7c9b5fe 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -95,6 +95,13 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { return err } + // Before PruneDatabase: it drops incomplete snapshots, which could + // leave the local index without one and so skip the marker check. + err = v.markDestination() + if err != nil { + return err + } + // Clean up incomplete snapshots FIRST, before any scanning. // This is critical for data safety; PruneDatabase below does it. hostname := v.Config.Hostname @@ -117,21 +124,9 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { return fmt.Errorf("prune database: %w", err) } - // Determine which snapshots to process - snapshotNames := opts.Snapshots - if len(snapshotNames) == 0 { - snapshotNames = v.Config.SnapshotNames() - } else { - // Validate requested snapshot names exist - for _, name := range snapshotNames { - if _, ok := v.Config.Snapshots[name]; !ok { - return fmt.Errorf("%w: %q", errSnapshotNotInConfig, name) - } - } - } - - if len(snapshotNames) == 0 { - return errNoSnapshotsInConfig + snapshotNames, err := v.snapshotNamesToCreate(opts.Snapshots) + if err != nil { + return err } // Process each named snapshot @@ -171,6 +166,28 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { return nil } +// snapshotNamesToCreate returns the requested snapshot names, each checked +// against the config, or every configured name when none was requested. +func (v *Vaultik) snapshotNamesToCreate(requested []string) ([]string, error) { + snapshotNames := requested + if len(snapshotNames) == 0 { + snapshotNames = v.Config.SnapshotNames() + } else { + // Validate requested snapshot names exist + for _, name := range snapshotNames { + if _, ok := v.Config.Snapshots[name]; !ok { + return nil, fmt.Errorf("%w: %q", errSnapshotNotInConfig, name) + } + } + } + + if len(snapshotNames) == 0 { + return nil, errNoSnapshotsInConfig + } + + return snapshotNames, nil +} + // runPostBackupPrune drops older snapshots of the given names and removes // orphan blobs from remote storage. If keepNewerThan is set (e.g. "4w"), // snapshots newer than that duration are kept. Otherwise only the latest @@ -1281,10 +1298,18 @@ func (v *Vaultik) RemoveSnapshot( return v.removeSnapshotDryRun(result, snapshotID, opts) } - if !opts.Force && !opts.JSON && !v.confirmRemoveSnapshot(snapshotID, opts) { + if !v.confirmRemoveSnapshot(snapshotID, opts) { return result, nil } + // Checked before the local record is deleted: it may be the last + // snapshot in the local index, and the check applies only while the + // local index holds one. + var markerErr error + if !opts.LocalOnly { + markerErr = v.checkDestinationMarker() + } + if inLocalIndex { log.Info("Removing snapshot from local database", "snapshot_id", snapshotID) @@ -1295,7 +1320,7 @@ func (v *Vaultik) RemoveSnapshot( } result.RemoteRemoved, err = v.removeSnapshotRemote( - snapshotID, inLocalIndex, opts) + snapshotID, inLocalIndex, markerErr, opts) if err != nil { return result, err } @@ -1332,7 +1357,9 @@ func (v *Vaultik) RemoveSnapshot( // remove: no row and, unless LocalOnly is set, no metadata on the // destination store either. The destination store is consulted only // when the local index has no row, so a snapshot in the local index can -// still be removed from it while the destination store is unreachable. +// still be removed from it while the destination store is unreachable, +// and only after checkDestinationMarker passes, so an unplugged volume's +// empty mount point is not taken for a store without the snapshot. func (v *Vaultik) findSnapshotToRemove( snapshotID string, opts *RemoveOptions, ) (bool, error) { @@ -1352,6 +1379,11 @@ func (v *Vaultik) findSnapshotToRemove( errSnapshotNotFound, snapshotID) } + err := v.checkDestinationMarker() + if err != nil { + return false, err + } + objects, err := v.remoteSnapshotObjects(snapshot.RemoteSnapshotKey(snapshotID)) if err != nil { return false, fmt.Errorf("looking up snapshot on destination store: %w", err) @@ -1390,11 +1422,15 @@ func (v *Vaultik) removeSnapshotDryRun( } // confirmRemoveSnapshot prompts for confirmation before removing a -// snapshot. Returns false (treating EOF/read errors as "no") unless the -// user answers "y". The prompt and its answer bypass the UI: they are an -// interactive exchange the operator must see, so --quiet does not -// silence them. +// snapshot, unless --force or --json is set. Returns false (treating +// EOF/read errors as "no") unless the user answers "y". The prompt and +// its answer bypass the UI: they are an interactive exchange the +// operator must see, so --quiet does not silence them. func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) bool { + if opts.Force || opts.JSON { + return true + } + if opts.LocalOnly { v.stdoutf("Remove snapshot '%s' from local database "+ "(remote untouched)? [y/N] ", snapshotID) @@ -1424,15 +1460,17 @@ func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) // removeSnapshotRemote strips the snapshot's metadata from the // destination store. It returns true only when the delete finished // without an error and removed at least one object; under LocalOnly it -// does nothing. When the snapshot is only on the destination store, a -// failure is returned as an error, because that removal is all the -// command does. When the snapshot was in the local index, its removal -// there has already happened, so a failure is only a warning telling the -// user to run `vaultik snapshot remove` for the snapshot again once the -// destination store is reachable (`vaultik prune` never removes snapshot -// metadata). +// does nothing. markerErr is the result of checkDestinationMarker; when +// it is set, nothing is deleted and it is the failure. When the snapshot +// is only on the destination store, a failure is returned as an error, +// because that removal is all the command does. When the snapshot was in +// the local index, its removal there has already happened, so a failure +// is only a warning telling the user to run `vaultik snapshot remove` +// for the snapshot again once the destination store is reachable +// (`vaultik prune` never removes snapshot metadata). func (v *Vaultik) removeSnapshotRemote( - snapshotID string, inLocalIndex bool, opts *RemoveOptions, + snapshotID string, inLocalIndex bool, markerErr error, + opts *RemoveOptions, ) (bool, error) { if opts.LocalOnly { return false, nil @@ -1441,9 +1479,14 @@ func (v *Vaultik) removeSnapshotRemote( log.Info("Removing snapshot metadata from remote storage", "snapshot_id", snapshotID) - remoteKey := snapshot.RemoteSnapshotKey(snapshotID) + var deleted int + + err := markerErr + if err == nil { + deleted, err = v.deleteRemoteSnapshotByKey( + snapshot.RemoteSnapshotKey(snapshotID)) + } - deleted, err := v.deleteRemoteSnapshotByKey(remoteKey) if err != nil && !inLocalIndex { return false, fmt.Errorf( "removing snapshot metadata from destination store: %w", err) @@ -1552,8 +1595,8 @@ func (v *Vaultik) localSnapshotIDs() ([]string, error) { // listAllRemoteSnapshotKeys collects the hashed remote keys // (subdirectories under metadata/) currently present in the // destination store. Returns (nil, err) when the store cannot be -// listed; callers must treat that as "no remote info available," not -// fatal. +// listed, or is not present by checkDestinationMarker; callers must +// treat that as "no remote info available," not fatal. func (v *Vaultik) listAllRemoteSnapshotKeys() ([]string, error) { log.Info("Listing all remote snapshots") @@ -1602,6 +1645,11 @@ func (v *Vaultik) listAllRemoteSnapshotKeys() ([]string, error) { } } + err := v.checkDestinationMarker() + if err != nil { + return nil, err + } + return keys, nil } diff --git a/internal/vaultik/snapshot_deleted_count_test.go b/internal/vaultik/snapshot_deleted_count_test.go index bce2a4c..80dbd0a 100644 --- a/internal/vaultik/snapshot_deleted_count_test.go +++ b/internal/vaultik/snapshot_deleted_count_test.go @@ -53,7 +53,7 @@ func newDeletedCountEnv(t *testing.T, files map[string][]byte) *deletedCountEnv cfg.IndexPath = filepath.Join(tempDir, "index.sqlite") cfg.Snapshots = map[string]config.SnapshotConfig{} - store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + store, err := storage.NewFileStorer(t.TempDir()) require.NoError(t, err) db, err := database.New(ctx, cfg.IndexPath) diff --git a/internal/vaultik/snapshot_failed_file_test.go b/internal/vaultik/snapshot_failed_file_test.go index a5f8bc4..2742115 100644 --- a/internal/vaultik/snapshot_failed_file_test.go +++ b/internal/vaultik/snapshot_failed_file_test.go @@ -87,7 +87,7 @@ func TestSnapshotSummaryCountsFileNotStoredAsFailed(t *testing.T) { "src": {Paths: []string{srcDir}}, } - store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + store, err := storage.NewFileStorer(t.TempDir()) require.NoError(t, err) db, err := database.New(ctx, cfg.IndexPath) diff --git a/internal/vaultik/snapshot_list_test.go b/internal/vaultik/snapshot_list_test.go index ee60b3c..811d545 100644 --- a/internal/vaultik/snapshot_list_test.go +++ b/internal/vaultik/snapshot_list_test.go @@ -122,6 +122,9 @@ func newListEnv(t *testing.T) *listEnv { store := newObservingStorer() stdout := &bytes.Buffer{} + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(ctx, markerFile, strings.NewReader(""))) + v := &vaultik.Vaultik{ Config: &config.Config{ AgeSecretKey: "", diff --git a/internal/vaultik/snapshot_skip_errors_test.go b/internal/vaultik/snapshot_skip_errors_test.go index 0f88515..af07afe 100644 --- a/internal/vaultik/snapshot_skip_errors_test.go +++ b/internal/vaultik/snapshot_skip_errors_test.go @@ -45,7 +45,7 @@ func TestSkipErrorsBackupStopsOnIndexErrorRecordingDirectory(t *testing.T) { "tree": {Paths: []string{srcDir}}, } - store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + store, err := storage.NewFileStorer(t.TempDir()) require.NoError(t, err) db, err := database.New(ctx, cfg.IndexPath) diff --git a/internal/vaultik/snapshot_summary_test.go b/internal/vaultik/snapshot_summary_test.go index 3e180b6..a901562 100644 --- a/internal/vaultik/snapshot_summary_test.go +++ b/internal/vaultik/snapshot_summary_test.go @@ -84,7 +84,7 @@ func newSummaryEnv(t *testing.T) *summaryEnv { "split": {Paths: []string{dirOne, dirTwo}}, } - inner, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + inner, err := storage.NewFileStorer(t.TempDir()) require.NoError(t, err) store := faultstore.New(inner) diff --git a/internal/vaultik/two_path_snapshot_test.go b/internal/vaultik/two_path_snapshot_test.go index 06c2fed..e6673c9 100644 --- a/internal/vaultik/two_path_snapshot_test.go +++ b/internal/vaultik/two_path_snapshot_test.go @@ -28,7 +28,7 @@ func TestBackupWithoutCronOfTwoPathSnapshotRestoresBothPaths(t *testing.T) { tempDir := t.TempDir() firstDir := filepath.Join(tempDir, "first") secondDir := filepath.Join(tempDir, "second") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") diff --git a/internal/vaultik/uncompressed_size_test.go b/internal/vaultik/uncompressed_size_test.go index f9b77c1..9d8fd8e 100644 --- a/internal/vaultik/uncompressed_size_test.go +++ b/internal/vaultik/uncompressed_size_test.go @@ -36,7 +36,7 @@ func TestUncompressedSizeOfChangedFileStaysFixed(t *testing.T) { appendRandomBytes(t, fs, files, changedPath, appendedFileSize) - store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote")) + store, err := storage.NewFileStorer(t.TempDir()) require.NoError(t, err) db, err := database.New(ctx, dbPath) diff --git a/internal/vaultik/verify_quiet_test.go b/internal/vaultik/verify_quiet_test.go index b4350db..c8dd630 100644 --- a/internal/vaultik/verify_quiet_test.go +++ b/internal/vaultik/verify_quiet_test.go @@ -28,7 +28,7 @@ func TestVerify_QuietSuppressesReport(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") chunkSize := int64(32 * 1024) From 2125a9d451349925addb11b058fa353c1697d18e Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 06:46:45 +0200 Subject: [PATCH 087/121] Stop counting directories and unchanged symlinks as files to back up (closes #305) Every backup queued every directory and symlink for the second phase. The line ending the walk counted directories, and their stat sizes, as files to back up while its enumerated count left them out, and a symlink was counted as backed up on every run, its target length as data. The walk now sets directories aside: they are recorded before the files are backed up and never counted as files or data, and the walk's progress estimate leaves out the directories the local index knows. A symlink is checked against its record like a regular file, its target included, so an unchanged one counts as unchanged. Judgement call: every directory is still written to the local index on every backup, as before; no report shows it. Model: opus-5-5 --- ARCHITECTURE.md | 2 +- internal/snapshot/progress_test.go | 3 +- internal/snapshot/scanner.go | 179 +++++++++++++-------- internal/snapshot/scanner_estimate_test.go | 28 ++++ internal/vaultik/snapshot_summary_test.go | 116 +++++++++++++ 5 files changed, 254 insertions(+), 74 deletions(-) create mode 100644 internal/snapshot/scanner_estimate_test.go diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 8079402..045e39c 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -359,7 +359,7 @@ CreateSnapshot(opts) ## Deduplication Strategy -1. **File-level**: Files unchanged since last backup are skipped (metadata comparison: size, mtime, mode, uid, gid), unless the file lists a chunk that no uploaded blob holds; such a file is re-chunked +1. **File-level**: Files and symlinks unchanged since last backup are skipped (metadata comparison: size, mtime, mode, uid, gid, and a symlink's target), unless the file lists a chunk that no uploaded blob holds; such a file is re-chunked 2. **Chunk-level**: Chunks are content-addressed by SHA256 hash. If a chunk hash already exists in the database, the chunk data is not re-uploaded. diff --git a/internal/snapshot/progress_test.go b/internal/snapshot/progress_test.go index ed63c91..e106cf3 100644 --- a/internal/snapshot/progress_test.go +++ b/internal/snapshot/progress_test.go @@ -78,8 +78,7 @@ func TestProgressPercentWithSecondPathSmaller(t *testing.T) { stats := progress.GetStats() - // Directories count toward the total size but produce no chunks, so - // the percentage ends just under 100%. + // With both paths counted, the percentage must not exceed 100%. percent := float64(stats.BytesProcessed.Load()) / float64(stats.TotalSize.Load()) * 100 if percent > 100 { diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 10a5541..61ac3d0 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -284,6 +284,11 @@ func (s *Scanner) Scan( } } + err = s.recordDirectories(ctx, scanResult.Directories) + if err != nil { + return nil, err + } + // Summarize scan phase results and update progress s.summarizeScanPhase(result, filesToProcess) @@ -855,14 +860,15 @@ func (s *Scanner) batchInsertFileData( // ScanPhaseResult contains the results of the scan phase type ScanPhaseResult struct { FilesToProcess []*FileToProcess - UnchangedFileIDs []types.FileID // IDs of unchanged files to associate with snapshot + UnchangedFileIDs []types.FileID // IDs of unchanged files to associate with snapshot + Directories []*FileToProcess // Every directory found, to record } // scanPhase performs the initial directory scan to identify files to process // It uses the pre-loaded knownFiles map for fast change detection without DB // queries. It also populates existingFiles map for deletion detection. -// Returns files needing processing and IDs of unchanged files for snapshot -// association. +// Returns files needing processing, IDs of unchanged files for snapshot +// association, and the directories found. func (s *Scanner) scanPhase( ctx context.Context, path string, @@ -870,8 +876,10 @@ func (s *Scanner) scanPhase( existingFiles map[string]struct{}, knownFiles map[string]*database.File, ) (*ScanPhaseResult, error) { - // Use known file count as estimate for progress (accurate for subsequent backups) - estimatedTotal := int64(len(knownFiles)) + // Use known file count as estimate for progress (accurate for + // subsequent backups). The walk does not count directories, so the + // estimate leaves them out. + estimatedTotal := countNonDirectories(knownFiles) collector := &scanCollector{} @@ -904,7 +912,7 @@ func (s *Scanner) scanPhase( // Handle symlinks and directories handled, err := s.recordSpecialEntry( - filePath, info, existingFiles, collector, result) + filePath, info, existingFiles, knownFiles, collector, result) if handled { return err } @@ -918,9 +926,10 @@ func (s *Scanner) scanPhase( existingFiles[filePath] = struct{}{} // Check file against in-memory map (no DB query!) - file, needsProcessing := s.checkFileInMemory(filePath, info, knownFiles) + file := s.buildRegularFileEntry(filePath, info) + needsProcessing := s.checkFileInMemory(file, knownFiles) - filesScanned, changedCount := collector.recordRegularFile( + filesScanned, changedCount := collector.recordFile( filePath, info, file, needsProcessing) // Update result stats @@ -944,15 +953,32 @@ func (s *Scanner) scanPhase( return &ScanPhaseResult{ FilesToProcess: collector.filesToProcess, UnchangedFileIDs: collector.unchangedFileIDs, + Directories: collector.directories, }, nil } +// countNonDirectories returns how many of files are not directories. +func countNonDirectories(files map[string]*database.File) int64 { + var count int64 + + for _, f := range files { + if f.Mode&uint32(os.ModeDir) == 0 { + count++ + } + } + + return count +} + // recordSpecialEntry records symlinks and directories (which have no -// data to chunk) and reports whether it handled the entry. For a symlink -// whose target cannot be read it returns handleWalkError's result. +// data to chunk) and reports whether it handled the entry. A symlink is +// counted and checked for changes as a regular file is; a directory is +// set aside to be recorded and is not counted. For a symlink whose +// target cannot be read it returns handleWalkError's result. func (s *Scanner) recordSpecialEntry( filePath string, info os.FileInfo, existingFiles map[string]struct{}, + knownFiles map[string]*database.File, collector *scanCollector, result *ScanResult, ) (bool, error) { // Handle symlinks @@ -963,8 +989,9 @@ func (s *Scanner) recordSpecialEntry( } existingFiles[filePath] = struct{}{} - collector.addToProcess(filePath, info, file) - s.updateScanEntryStats(result, true, info) + needsProcessing := s.checkFileInMemory(file, knownFiles) + collector.recordFile(filePath, info, file, needsProcessing) + s.updateScanEntryStats(result, needsProcessing, info) return true, nil } @@ -974,7 +1001,7 @@ func (s *Scanner) recordSpecialEntry( if info.IsDir() { file := s.buildDirectoryEntry(filePath, info) existingFiles[filePath] = struct{}{} - collector.addToProcess(filePath, info, file) + collector.addDirectory(filePath, info, file) return true, nil } @@ -1004,28 +1031,29 @@ type scanCollector struct { mu sync.Mutex filesToProcess []*FileToProcess unchangedFileIDs []types.FileID // Just IDs - no new records needed + directories []*FileToProcess filesScanned int64 } -// addToProcess queues a file entry for processing. -func (c *scanCollector) addToProcess( +// addDirectory sets a directory aside to be recorded. It is not counted +// as a file. +func (c *scanCollector) addDirectory( path string, info os.FileInfo, file *database.File, ) { c.mu.Lock() defer c.mu.Unlock() - c.filesToProcess = append(c.filesToProcess, &FileToProcess{ + c.directories = append(c.directories, &FileToProcess{ Path: path, FileInfo: info, File: file, }) - c.filesScanned++ } -// recordRegularFile records a regular file as changed (to process) or -// unchanged (snapshot association only) and returns the running scanned -// and changed counts. -func (c *scanCollector) recordRegularFile( +// recordFile records a regular file or symlink as changed (to process) +// or unchanged (snapshot association only) and returns the running +// scanned and changed counts. +func (c *scanCollector) recordFile( path string, info os.FileInfo, file *database.File, needsProcessing bool, ) (int64, int) { c.mu.Lock() @@ -1128,7 +1156,28 @@ func (s *Scanner) printScanProgressLine( } } -// buildSymlinkEntry creates a File record for a symlink. +// buildRegularFileEntry creates a File record for a regular file, with +// no ID: checkFileInMemory sets it. +func (s *Scanner) buildRegularFileEntry(path string, info os.FileInfo) *database.File { + var uid, gid uint32 + if stat, ok := info.Sys().(*syscall.Stat_t); ok { + uid = stat.Uid + gid = stat.Gid + } + + return &database.File{ + Path: types.FilePath(path), + SourcePath: types.SourcePath(s.currentSourcePath), + MTime: info.ModTime(), + Size: info.Size(), + Mode: uint32(info.Mode()), + UID: uid, + GID: gid, + } +} + +// buildSymlinkEntry creates a File record for a symlink, with no ID: +// checkFileInMemory sets it. func (s *Scanner) buildSymlinkEntry( path string, info os.FileInfo, ) (*database.File, error) { @@ -1144,7 +1193,6 @@ func (s *Scanner) buildSymlinkEntry( } return &database.File{ - ID: types.NewFileID(), Path: types.FilePath(path), SourcePath: types.SourcePath(s.currentSourcePath), MTime: info.ModTime(), @@ -1176,6 +1224,22 @@ func (s *Scanner) buildDirectoryEntry(path string, info os.FileInfo) *database.F } } +// recordDirectories records every directory the walk found. A directory +// has no data to back up, so it is not among the files counted and +// backed up. +func (s *Scanner) recordDirectories( + ctx context.Context, directories []*FileToProcess, +) error { + for _, dir := range directories { + err := s.recordNonRegularFile(ctx, dir) + if err != nil { + return fmt.Errorf("recording directory %s: %w", dir.Path, err) + } + } + + return nil +} + // recordNonRegularFile writes a symlink or directory entry to the database // and associates it with the current snapshot. No chunking is performed. func (s *Scanner) recordNonRegularFile(ctx context.Context, ftp *FileToProcess) error { @@ -1189,62 +1253,36 @@ func (s *Scanner) recordNonRegularFile(ctx context.Context, ftp *FileToProcess) }) } -// checkFileInMemory checks if a file needs processing using the in-memory map +// checkFileInMemory reports whether a regular file or symlink needs +// processing, and gives file the ID of its known record, or a new ID for +// a new path. // No database access is performed - this is purely CPU/memory work func (s *Scanner) checkFileInMemory( - path string, info os.FileInfo, knownFiles map[string]*database.File, -) (*database.File, bool) { - var uid, gid uint32 - if stat, ok := info.Sys().(*syscall.Stat_t); ok { - uid = stat.Uid - gid = stat.Gid - } - - // Check against in-memory map first to get existing ID if available - existingFile, exists := knownFiles[path] - - // Create file record with ID set upfront - // For new files, generate UUID immediately so it's available for chunk associations - // For existing files, reuse the existing ID - var fileID types.FileID - if exists { - fileID = existingFile.ID - } else { - fileID = types.NewFileID() - } - - file := &database.File{ - ID: fileID, - Path: types.FilePath(path), - SourcePath: types.SourcePath(s.currentSourcePath), - MTime: info.ModTime(), - Size: info.Size(), - Mode: uint32(info.Mode()), - UID: uid, - GID: gid, - } + file *database.File, knownFiles map[string]*database.File, +) bool { + existingFile, exists := knownFiles[file.Path.String()] // New file - needs processing if !exists { - return file, true + file.ID = types.NewFileID() + + return true } + file.ID = existingFile.ID + // No uploaded blob holds one of its chunks (see loadFilesToRechunk) - if _, rechunk := s.filesToRechunk[fileID]; rechunk { - return file, true + if _, rechunk := s.filesToRechunk[file.ID]; rechunk { + return true } // Check if file has changed - if existingFile.Size != file.Size || + return existingFile.Size != file.Size || !existingFile.MTime.Equal(file.MTime) || existingFile.Mode != file.Mode || existingFile.UID != file.UID || - existingFile.GID != file.GID { - return file, true - } - - // File unchanged - return file, false + existingFile.GID != file.GID || + existingFile.LinkTarget != file.LinkTarget } // batchAddFilesToSnapshot adds existing file IDs to the snapshot association table @@ -1371,17 +1409,16 @@ func (s *Scanner) processPhase( return s.finalizeProcessPhase(ctx, result) } -// processFileWithErrorHandling records a directory or symlink, or wraps +// processFileWithErrorHandling records a symlink, or wraps // processFileStreaming for a regular file with error recovery for deleted // files and skip-errors mode. Returns (skipped, error). func (s *Scanner) processFileWithErrorHandling( ctx context.Context, fileToProcess *FileToProcess, result *ScanResult, ) (bool, error) { - // A directory or symlink has no data to open or read; it is only - // recorded in the local index. An error recording it stops the run - // even under --skip-errors, or the snapshot would complete without it. - mode := os.FileMode(fileToProcess.File.Mode) - if mode&os.ModeSymlink != 0 || mode.IsDir() { + // A symlink has no data to open or read; it is only recorded in the + // local index. An error recording it stops the run even under + // --skip-errors, or the snapshot would complete without it. + if os.FileMode(fileToProcess.File.Mode)&os.ModeSymlink != 0 { err := s.recordNonRegularFile(ctx, fileToProcess) if err != nil { return false, fmt.Errorf("processing file %s: %w", fileToProcess.Path, err) diff --git a/internal/snapshot/scanner_estimate_test.go b/internal/snapshot/scanner_estimate_test.go new file mode 100644 index 0000000..501c1a2 --- /dev/null +++ b/internal/snapshot/scanner_estimate_test.go @@ -0,0 +1,28 @@ +//nolint:testpackage // exercises the unexported countNonDirectories helper +package snapshot + +import ( + "os" + "testing" + + "sneak.berlin/go/vaultik/internal/database" +) + +// The walk counts regular files and symlinks, not directories, so the +// estimate of its count made from the local index's records leaves the +// directories out. See https://git.eeqj.de/sneak/vaultik/issues/305. +func TestCountNonDirectories(t *testing.T) { + t.Parallel() + + known := map[string]*database.File{ + "/src": {Mode: uint32(os.ModeDir | 0o755)}, + "/src/sub": {Mode: uint32(os.ModeDir | 0o755)}, + "/src/a.txt": {Mode: 0o644}, + "/src/link": {Mode: uint32(os.ModeSymlink | 0o777), LinkTarget: "a.txt"}, + } + + got := countNonDirectories(known) + if got != 2 { + t.Errorf("countNonDirectories = %d, want 2", got) + } +} diff --git a/internal/vaultik/snapshot_summary_test.go b/internal/vaultik/snapshot_summary_test.go index a901562..1385637 100644 --- a/internal/vaultik/snapshot_summary_test.go +++ b/internal/vaultik/snapshot_summary_test.go @@ -13,6 +13,7 @@ import ( "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" @@ -188,6 +189,42 @@ func (e *summaryEnv) dataLine(total, backedUp int64) string { e.v.UI.Size(total), e.v.UI.Size(backedUp)) } +// enumeratedLine returns the line printed when the walk of a source path +// ends. +func (e *summaryEnv) enumeratedLine( + files int, total int64, toBackUp int, toBackUpSize int64, +) string { + return fmt.Sprintf( + "Enumerated %d snapshot source files (%s total), %d to back up (%s).", + files, e.v.UI.Size(total), toBackUp, e.v.UI.Size(toBackUpSize)) +} + +// snapshotPaths returns the paths the snapshot lists, sorted. +func (e *summaryEnv) snapshotPaths(t *testing.T, snapshotID string) []string { + t.Helper() + + rows, err := e.db.Conn().QueryContext(context.Background(), ` + SELECT f.path FROM snapshot_files sf JOIN files f ON f.id = sf.file_id + WHERE sf.snapshot_id = ? ORDER BY f.path`, snapshotID) + require.NoError(t, err) + + defer func() { _ = rows.Close() }() + + var paths []string + + for rows.Next() { + var path string + + require.NoError(t, rows.Scan(&path)) + + paths = append(paths, path) + } + + require.NoError(t, rows.Err()) + + return paths +} + // A first backup stores copy.bin's chunks while backing up a.bin, so // copy.bin's chunks are deduplicated within the run. Each file and byte // is still counted once. @@ -248,6 +285,85 @@ func TestSnapshotSummaryIncrementalRunWithDeduplicatedChunks(t *testing.T) { assert.Equal(t, uncompressed, snap.BlobUncompressedSize) } +// A backup of a tree with directories and a symlink, none of which +// changed since the last backup, backs up nothing, and the snapshot +// still lists every one of them. Both sides of the line that ends the +// walk count the same entries, the files and the symlink, and no +// directory's size. See https://git.eeqj.de/sneak/vaultik/issues/305. +func TestSnapshotSummaryUnchangedRunWithDirectoriesAndSymlink(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newSummaryEnv(t) + + const linkTarget = "a.bin" + + require.NoError(t, os.Symlink(linkTarget, + filepath.Join(filepath.Dir(env.aPath), "link"))) + + // A symlink's size is the length of its target. + total := env.totalSize + int64(len(linkTarget)) + + first := env.backUp(t, "first", false) + assert.Contains(t, first, env.enumeratedLine(4, total, 4, total)) + assert.Contains(t, first, filesLine(4, 4, 0)) + + second := env.backUp(t, "second", false) + assert.Contains(t, second, env.enumeratedLine(4, total, 0, 0)) + assert.Contains(t, second, filesLine(4, 0, 4)) + assert.Contains(t, second, env.dataLine(total, 0)) + + assert.Equal(t, + env.snapshotPaths(t, env.snapshot(t, "first").ID.String()), + env.snapshotPaths(t, env.snapshot(t, "second").ID.String())) +} + +// A directory whose mtime changed and a symlink whose target changed are +// recorded again by the next backup, which counts only the symlink as +// backed up. +func TestSnapshotSummaryChangedDirectoryAndSymlink(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newSummaryEnv(t) + + // The local index keeps paths with symlinks resolved. + dir, err := filepath.EvalSymlinks(filepath.Dir(env.aPath)) + require.NoError(t, err) + + // The new link gets the old one's mtime, and a target, which need not + // exist, of the old target's length, a symlink's size: only the + // target differs. + linkTime := unix.NsecToTimeval( + time.Date(2029, time.March, 4, 5, 6, 7, 0, time.UTC).UnixNano()) + link := filepath.Join(dir, "link") + require.NoError(t, os.Symlink("a.bin", link)) + require.NoError(t, unix.Lutimes(link, []unix.Timeval{linkTime, linkTime})) + + env.backUp(t, "first", false) + + require.NoError(t, os.Remove(link)) + require.NoError(t, os.Symlink("b.bin", link)) + require.NoError(t, unix.Lutimes(link, []unix.Timeval{linkTime, linkTime})) + + mtime := time.Date(2030, time.January, 2, 3, 4, 5, 0, time.UTC) + require.NoError(t, os.Chtimes(dir, mtime, mtime)) + + assert.Contains(t, env.backUp(t, "second", false), filesLine(4, 1, 3)) + + ctx := context.Background() + + dirRow, err := env.repos.Files.GetByPath(ctx, dir) + require.NoError(t, err) + require.NotNil(t, dirRow) + assert.Equal(t, mtime.Unix(), dirRow.MTime.Unix()) + + linkRow, err := env.repos.Files.GetByPath(ctx, link) + require.NoError(t, err) + require.NotNil(t, linkRow) + assert.Equal(t, "b.bin", linkRow.LinkTarget.String()) +} + // Under --cron the progress reporter is off; the upload figures must // still reach the summary and the snapshots row. The snapshot has two // paths, each backed up by its own scan. From 16b03dfda5d3518ee16ae989ab72952322515f9b Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 06:47:38 +0200 Subject: [PATCH 088/121] Keep the local index when remote nuke cannot list or find the destination (closes #292) `remote nuke` took a destination store it could not list, or one without `vaultik-destination.txt` while the local index held snapshots, as a warning: it then cleared the local snapshot records, and for an unplugged volume's empty mount point reported the store empty and exited zero. Nuke now fails on either before it removes anything, without its advice to run it again, which would fail the same way. The bulk remove it runs fails on either too; only a local-only remove still goes on with a warning. Nuke also deletes each snapshot's remote metadata before its local record, so a failed delete keeps the snapshot in the local index rather than leaving it on the store as a remote-only snapshot. Model: opus-5-5 --- ARCHITECTURE.md | 11 +++-- README.md | 20 +++++--- docs/REPOSTRUCTURE.md | 2 +- internal/vaultik/destination_marker_test.go | 19 ++++++++ internal/vaultik/missing_destination_test.go | 38 +++++++++++++++ internal/vaultik/nuke_remote_test.go | 29 ++++++++++- internal/vaultik/prune.go | 9 +++- internal/vaultik/snapshot.go | 51 ++++++++++++-------- 8 files changed, 142 insertions(+), 37 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 045e39c..d716e16 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -385,11 +385,12 @@ bucket/ A destination without `vaultik-destination.txt` is treated as not present while the local index holds snapshots stored there (`checkDestinationMarker` in `internal/vaultik/destination_marker.go`): `snapshot create` refuses to -write to it, `prune` and `snapshot purge` fail, and `snapshot list` and -`snapshot remove` behave as for a destination that cannot be listed. This -keeps those commands from taking an unplugged volume's empty mount point for -a destination whose snapshots are all gone. The `file://` backend never -creates its destination directory, so a write to a missing one fails. +write to it, `prune`, `snapshot purge` and `remote nuke` fail, and +`snapshot list` and `snapshot remove` behave as for a destination that cannot +be listed. This keeps those commands from taking an unplugged volume's empty +mount point for a destination whose snapshots are all gone. The `file://` +backend never creates its destination directory, so a write to a missing one +fails. The `{remote-key}` directory name is a one-way double SHA-256 hash of the human snapshot ID, so the human ID (hostname, snapshot name, timestamp) is never diff --git a/README.md b/README.md index a84d9ff..f1facea 100644 --- a/README.md +++ b/README.md @@ -454,9 +454,14 @@ since `prune` never deletes it. the backup destination store, whatever its name, and then `vaultik-destination.txt`, leaving the bucket prefix empty. Destructive and irreversible. This is the single supported way to wipe the entire -destination store. If a listing afterwards still finds anything under -`metadata/` or `blobs/`, the command names each object left and exits -non-zero; running it again deletes what is left. +destination store. A snapshot is removed from the local index only once +its metadata is deleted from the destination store. If the destination +store cannot be listed, or the local index holds snapshots and the +destination has no `vaultik-destination.txt` (an unplugged volume's +empty mount point), the command fails before it removes anything. If a +listing afterwards still finds anything under `metadata/` or `blobs/`, +the command names each object left and exits non-zero; running it again +deletes what is left. * `--force`: Required to confirm destruction. **`database delete`**: Delete the local SQLite state database file @@ -529,10 +534,11 @@ For an implementation-level view of the internals — the data model, the * `vaultik-destination.txt` holds one fixed line of text, with no host name, path or time. A destination without it is treated as not present while the local index holds snapshots stored there: - `snapshot create` refuses to write to it, `prune` and `snapshot purge` - fail, and `snapshot list` and `snapshot remove` behave as for a - destination that cannot be listed. This keeps an unplugged volume's empty mount point - from being taken for a destination whose snapshots are all gone. Mount + `snapshot create` refuses to write to it, `prune`, `snapshot purge` + and `remote nuke` fail, and `snapshot list` and `snapshot remove` + behave as for a destination that cannot be listed. This keeps an + unplugged volume's empty mount point from being taken for a + destination whose snapshots are all gone. Mount the volume if it is removable; if the destination was emptied on purpose, run `vaultik database delete` and back up again. * Blobs are two-level directory sharded using the first 4 hex chars of the blob hash diff --git a/docs/REPOSTRUCTURE.md b/docs/REPOSTRUCTURE.md index 36711c7..6a0661a 100644 --- a/docs/REPOSTRUCTURE.md +++ b/docs/REPOSTRUCTURE.md @@ -27,7 +27,7 @@ The metadata subdirectory is named with the **remote key**, a one-way hash of th ## Marker File (`vaultik-destination.txt`) -Every backup writes this file at the root before it uploads anything. It holds one fixed line of plain text and names no host, path or time. A destination without it is treated as not present while the local index holds snapshots stored there: `snapshot create` refuses to write to it, and `prune`, `snapshot purge`, `snapshot remove` and `snapshot list` behave as for a destination that cannot be listed. An unplugged volume leaves an empty directory at its mount point, and without the marker that directory would read as a destination whose snapshots are all gone. `remote nuke` deletes the marker last. +Every backup writes this file at the root before it uploads anything. It holds one fixed line of plain text and names no host, path or time. A destination without it is treated as not present while the local index holds snapshots stored there: `snapshot create` refuses to write to it, and `prune`, `snapshot purge`, `snapshot remove`, `snapshot list` and `remote nuke` behave as for a destination that cannot be listed. An unplugged volume leaves an empty directory at its mount point, and without the marker that directory would read as a destination whose snapshots are all gone. `remote nuke` deletes the marker last. ## Blobs Directory (`blobs/`) diff --git a/internal/vaultik/destination_marker_test.go b/internal/vaultik/destination_marker_test.go index 03775d6..08cb35b 100644 --- a/internal/vaultik/destination_marker_test.go +++ b/internal/vaultik/destination_marker_test.go @@ -152,6 +152,25 @@ func TestPurgeRefusesDestinationWithoutMarker(t *testing.T) { assertUntouched(ctx, t, repos, storeDir) } +// TestNukeRemoteRefusesDestinationWithoutMarker checks that remote nuke +// fails, deletes no local snapshot record, and neither reports the +// destination empty nor advises running nuke again when the destination +// has no marker. +func TestNukeRemoteRefusesDestinationWithoutMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out, storeDir := backUpThenUnplugMountPoint(ctx, t) + + err := v.NukeRemote(true) + require.ErrorContains(t, err, markerFile) + assert.NotContains(t, out.String(), "now empty") + assert.NotContains(t, out.String(), "vaultik remote nuke --force") + + assertUntouched(ctx, t, repos, storeDir) +} + // TestRemoveSnapshotWarnsWhenDestinationHasNoMarker checks that snapshot // remove warns that the metadata could not be removed from a destination // without a marker, instead of reporting that it was. diff --git a/internal/vaultik/missing_destination_test.go b/internal/vaultik/missing_destination_test.go index cf8cc54..1ab5a5c 100644 --- a/internal/vaultik/missing_destination_test.go +++ b/internal/vaultik/missing_destination_test.go @@ -188,3 +188,41 @@ func TestPurgeSaysListingFailedOnceWhenDestinationMissing(t *testing.T) { assert.Equal(t, 1, strings.Count(err.Error(), "listing remote snapshots"), err.Error()) } + +// TestNukeRemoteKeepsLocalIndexWhenDestinationMissing checks that remote +// nuke fails on a destination it cannot list, leaves the local index +// unchanged, and neither reports the destination empty nor advises +// running nuke again. +func TestNukeRemoteKeepsLocalIndexWhenDestinationMissing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out := backUpThenUnplug(ctx, t) + + filesBefore, err := repos.Files.ListAll(ctx) + require.NoError(t, err) + require.NotEmpty(t, filesBefore) + + blobsBefore, err := repos.Blobs.GetAll(ctx) + require.NoError(t, err) + require.NotEmpty(t, blobsBefore) + + err = v.NukeRemote(true) + require.ErrorIs(t, err, fs.ErrNotExist) + require.ErrorContains(t, err, "listing remote snapshots") + assert.NotContains(t, out.String(), "now empty") + assert.NotContains(t, out.String(), "vaultik remote nuke --force") + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "nuke must delete no local snapshot record") + + files, err := repos.Files.ListAll(ctx) + require.NoError(t, err) + assert.Len(t, files, len(filesBefore), "nuke must delete no local file record") + + blobs, err := repos.Blobs.GetAll(ctx) + require.NoError(t, err) + assert.Len(t, blobs, len(blobsBefore), "nuke must delete no local blob record") +} diff --git a/internal/vaultik/nuke_remote_test.go b/internal/vaultik/nuke_remote_test.go index 04addda..63ebcbe 100644 --- a/internal/vaultik/nuke_remote_test.go +++ b/internal/vaultik/nuke_remote_test.go @@ -104,6 +104,32 @@ func TestNukeRemoteFailsWhenADeleteFails(t *testing.T) { } } +// TestNukeRemoteKeepsLocalSnapshotWhoseMetadataIsNotDeleted checks that +// remote nuke keeps a snapshot in the local index while its metadata +// cannot be deleted from the destination store: dropped from the local +// index, it would be left there as a remote-only snapshot without its +// name. +func TestNukeRemoteKeepsLocalSnapshotWhoseMetadataIsNotDeleted(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + + store := faultstore.New(v.Storage) + store.OnDelete = func(key string) bool { + return strings.HasPrefix(key, "metadata/") + } + v.Storage = store + + require.Error(t, v.NukeRemote(true)) + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1) +} + // TestNukeRemoteNamesWhatIsLeft checks that remote nuke, when an object // it does not recognise cannot be deleted, does not report the store // empty but names that object and fails. @@ -154,8 +180,7 @@ func TestNukeRemoteRefusesAnotherDestinationWithoutRetryAdvice(t *testing.T) { // TestNukeRemoteFailsWhenALocalSnapshotCannotBeRemoved checks that a // snapshot remote nuke cannot remove from the local index fails the -// run: nuke then leaves that snapshot's metadata on the destination -// store. +// run, and that nuke then does not report the destination store empty. func TestNukeRemoteFailsWhenALocalSnapshotCannotBeRemoved(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index f8e68cc..b7148e9 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -55,12 +55,19 @@ func (v *Vaultik) NukeRemote(force bool) error { } // Checked before anything is deleted: running nuke again would fail - // the same way, so the advice below must not follow this error. + // the same way, so the advice below must not follow these errors. + // The listing also fails on a destination without the marker while + // the local index holds snapshots. err := v.EnsureStorageBinding() if err != nil { return err } + _, err = v.listAllRemoteSnapshotKeys() + if err != nil { + return err + } + err = v.emptyDestinationStore() if err != nil { v.UI.Warningf("Run '%s' again to delete what is left on the "+ diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 7c9b5fe..6d74865 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -1516,7 +1516,9 @@ func (v *Vaultik) removeSnapshotRemote( // database from the local index, and (with --remote) every snapshot // metadata directory in remote storage. Both sides are processed so a // "remove --all" leaves nothing behind, even when the local DB and -// remote storage have diverged. +// remote storage have diverged. Unless LocalOnly is set, it fails +// before it removes anything when the destination store cannot be +// listed or is not present by checkDestinationMarker. func (v *Vaultik) RemoveAllSnapshots(opts *RemoveOptions) (*RemoveResult, error) { err := v.EnsureStorageBinding() if err != nil { @@ -1529,11 +1531,15 @@ func (v *Vaultik) RemoveAllSnapshots(opts *RemoveOptions) (*RemoveResult, error) } // remoteKeys is the set of metadata// subdirectories on the - // destination store; failures are downgraded to a warning so a - // permission-denied or unreachable remote can't block a local-only - // remove. + // destination store. Only for a local-only remove is a failure + // downgraded to a warning, so a permission-denied or unreachable + // remote can't block it. remoteKeys, remoteErr := v.listAllRemoteSnapshotKeys() if remoteErr != nil { + if !opts.LocalOnly { + return nil, remoteErr + } + log.Warn("Could not list remote snapshots", "error", remoteErr) v.UI.Warningf("Could not list remote snapshots: %v.", remoteErr) } @@ -1595,8 +1601,7 @@ func (v *Vaultik) localSnapshotIDs() ([]string, error) { // listAllRemoteSnapshotKeys collects the hashed remote keys // (subdirectories under metadata/) currently present in the // destination store. Returns (nil, err) when the store cannot be -// listed, or is not present by checkDestinationMarker; callers must -// treat that as "no remote info available," not fatal. +// listed, or is not present by checkDestinationMarker. func (v *Vaultik) listAllRemoteSnapshotKeys() ([]string, error) { log.Info("Listing all remote snapshots") @@ -1780,10 +1785,12 @@ func (v *Vaultik) deleteIncompleteSnapshot(snapshotIDStr string, id any) bool { return true } -// removeAllLocalSnapshots removes each known local snapshot (and, unless -// --local-only, its remote metadata), returning the number of snapshots -// it could not remove. A snapshot left in the local index keeps its -// remote metadata too, since it is not an orphan remote key. +// removeAllLocalSnapshots removes each known local snapshot's remote +// metadata, unless --local-only, and then its local record, returning +// the number of snapshots it could not remove. The local record goes +// only once the metadata is deleted: dropped first, it would leave that +// metadata on the destination store as a remote-only snapshot whose name +// is lost. func (v *Vaultik) removeAllLocalSnapshots( localSnaps []string, opts *RemoveOptions, result *RemoveResult, ) int { @@ -1792,6 +1799,19 @@ func (v *Vaultik) removeAllLocalSnapshots( for _, snapshotID := range localSnaps { log.Info("Removing snapshot", "snapshot_id", snapshotID) + if !opts.LocalOnly { + _, err := v.deleteRemoteSnapshotByKey( + snapshot.RemoteSnapshotKey(snapshotID)) + if err != nil { + log.Warn("Failed to remove snapshot metadata from remote", + "snapshot_id", snapshotID, "error", err) + + failures++ + + continue + } + } + err := v.deleteSnapshotFromLocalDB(snapshotID) if err != nil { log.Error("Failed to remove from local database", @@ -1802,17 +1822,6 @@ func (v *Vaultik) removeAllLocalSnapshots( continue } - if !opts.LocalOnly { - _, err = v.deleteRemoteSnapshotByKey( - snapshot.RemoteSnapshotKey(snapshotID)) - if err != nil { - log.Warn("Failed to remove snapshot metadata from remote", - "snapshot_id", snapshotID, "error", err) - - failures++ - } - } - result.SnapshotsRemoved = append(result.SnapshotsRemoved, snapshotID) } From 7a950ea2aab4a9be1e1ebb756c89b0bb5e194ef9 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 07:13:48 +0200 Subject: [PATCH 089/121] Exit non-zero when snapshot create --skip-errors skips anything it cannot read (closes #310) A backup under --skip-errors printed its skip errors, then "Finished successfully.", and exited 0, so a cron wrapper could not tell it from a complete backup. Each skipped entry, including a directory the walk could not list, is now counted as examined and failed. If --skip-errors skipped anything it could not read or list, the run still keeps its snapshots and prunes as before, then fails with "Backup completed, but N file(s) could not be read". A file removed during the run, even before the walk reaches it, counts once as failed and leaves the exit status alone; without the flag it no longer stops the backup. Excluded entries are never counted. Model: opus-5-5 --- README.md | 2 +- .../entry_snapshot_create_skip_errors_test.go | 30 ++++ internal/cli/snapshot.go | 7 + internal/snapshot/scanner.go | 76 +++++++--- internal/vaultik/snapshot.go | 47 ++++-- .../vaultik/snapshot_deleted_count_test.go | 8 +- internal/vaultik/snapshot_failed_file_test.go | 13 +- internal/vaultik/snapshot_skip_errors_test.go | 142 ++++++++++++++++++ 8 files changed, 292 insertions(+), 33 deletions(-) create mode 100644 internal/cli/entry_snapshot_create_skip_errors_test.go diff --git a/README.md b/README.md index f1facea..5827e84 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ vaultik version * `--verbose`, `-v`: Enable verbose output (on stderr — see below) * `--debug`: Enable debug output (on stderr — see below) * `--quiet`, `-q`: Suppress non-error output (also suppresses startup banner) -* `--skip-errors`: Skip files that cannot be read when creating a snapshot, or that cannot be restored when restoring, instead of aborting. Packing and storage errors while creating a snapshot (which would leave a chunk recorded but not stored) still abort the run. +* `--skip-errors`: Skip files that cannot be read when creating a snapshot, or that cannot be restored when restoring, instead of aborting. Packing and storage errors while creating a snapshot (which would leave a chunk recorded but not stored) still abort the run. A run that skipped anything still finishes but exits non-zero: `snapshot create` keeps the snapshot and counts each file or directory it skipped as failed. A file removed during the backup is also counted as failed but does not change the exit status. ### locking diff --git a/internal/cli/entry_snapshot_create_skip_errors_test.go b/internal/cli/entry_snapshot_create_skip_errors_test.go new file mode 100644 index 0000000..e52491d --- /dev/null +++ b/internal/cli/entry_snapshot_create_skip_errors_test.go @@ -0,0 +1,30 @@ +package cli //nolint:testpackage // shares runEntry and the hermetic config helpers + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestEntrySnapshotCreateSkipErrorsExitsNonZeroWhenItSkips backs up, +// under --skip-errors, a source directory that does not exist, which the +// walk skips. The command exits non-zero and reports the backup as +// completed, not as a failed snapshot creation. See +// https://git.eeqj.de/sneak/vaultik/issues/310. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreateSkipErrorsExitsNonZeroWhenItSkips(t *testing.T) { + // writeBackupConfig would create the source directory. + configPath := writeHermeticPruneConfig(t, false) + + code, stdout, stderr := runEntry(t, + flagConfig, configPath, "--skip-errors", cmdSnapshot, cmdCreate) + + assert.Equal(t, 1, code) + assert.Contains(t, stdout, + "Files: 1 examined, 0 backed up, 0 unchanged, 1 failed.") + assert.NotContains(t, stdout, "Finished successfully.") + assert.Contains(t, stderr, + "Backup completed, but 1 file(s) could not be read") + assert.NotContains(t, stderr, "Snapshot creation failed") +} diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 7fd5b73..7f7742c 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -115,6 +115,13 @@ on Linux), then /etc/vaultik/config.yml.`, return } + if errors.Is(err, vaultik.ErrFilesUnreadable) { + log.Error("Backup completed with unreadable files", "error", err) + ReportErrorf("Backup completed, but %v", err) + + return + } + log.Error("Snapshot creation failed", "error", err) ReportErrorf("Snapshot creation failed: %v", err) }) diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 61ac3d0..47a79fd 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -141,10 +141,12 @@ type ScannerConfig struct { // ScanResult contains the results of a scan operation. Files and bytes // are counted per file: BytesScanned is the size of the new and changed // files, BytesSkipped that of the unchanged ones. FilesFailed counts the -// new and changed files that phase 2 could not store; FilesScanned -// includes them and BytesScanned does not. ChunksCreated counts the -// chunks that were not already stored, and NewChunkSize is their total -// size. +// new and changed files that phase 2 could not store, each entry removed +// after the walk listed its directory and, under --skip-errors, each +// entry the walk could not read, such as a directory it could not list; +// FilesScanned includes them and BytesScanned does not. ChunksCreated +// counts the chunks that were not already stored, and NewChunkSize is +// their total size. type ScanResult struct { FilesScanned int FilesSkipped int @@ -161,6 +163,11 @@ type ScanResult struct { UploadDuration time.Duration StartTime time.Time EndTime time.Time + + // FilesUnreadable is the part of FilesFailed that --skip-errors + // skipped because it could not be read or listed; the rest are files + // removed after the walk listed them. + FilesUnreadable int } // NewScanner creates a new scanner instance @@ -890,8 +897,28 @@ func (s *Scanner) scanPhase( log.Debug("Starting directory walk", "path", path) walkFn := func(filePath string, info os.FileInfo, err error) error { + // Check exclude patterns first, so an excluded entry that is gone + // or cannot be looked up is neither counted nor reported. For + // directories, skip the entire subtree. info is nil when the + // walk could not look the entry up. + if s.shouldExclude(filePath, path) { + if info != nil && info.IsDir() { + return filepath.SkipDir + } + + return nil + } + + // The source path is in no directory listing, so its absence is + // an error rather than a removal. + if errors.Is(err, os.ErrNotExist) && filePath != path { + countRemovedDuringWalk(filePath, existingFiles, result) + + return nil + } + if err != nil { - return s.handleWalkError(filePath, err) + return s.handleWalkError(filePath, err, result) } // Check context cancellation @@ -901,15 +928,6 @@ func (s *Scanner) scanPhase( default: } - // Check exclude patterns - for directories, skip the entire subtree - if s.shouldExclude(filePath, path) { - if info.IsDir() { - return filepath.SkipDir - } - - return nil - } - // Handle symlinks and directories handled, err := s.recordSpecialEntry( filePath, info, existingFiles, knownFiles, collector, result) @@ -985,7 +1003,7 @@ func (s *Scanner) recordSpecialEntry( if info.Mode()&os.ModeSymlink != 0 { file, err := s.buildSymlinkEntry(filePath, info) if err != nil { - return true, s.handleWalkError(filePath, err) + return true, s.handleWalkError(filePath, err, result) } existingFiles[filePath] = struct{}{} @@ -1009,15 +1027,38 @@ func (s *Scanner) recordSpecialEntry( return false, nil } +// countRemovedDuringWalk counts an entry that was in its directory's +// listing but was gone when the walk looked it up, like a file removed +// before phase 2 reads it: as examined and failed, and not as an error, +// with or without --skip-errors. +func countRemovedDuringWalk( + filePath string, existingFiles map[string]struct{}, result *ScanResult, +) { + log.Warn("File was deleted during the directory walk, skipping", + "path", filePath) + + // The walk found it, so it is not also counted as deleted. + existingFiles[filePath] = struct{}{} + result.FilesScanned++ + result.FilesFailed++ +} + // handleWalkError deals with a filesystem error surfaced by the walk: -// skipped (with a UI notice) under --skip-errors, fatal otherwise. -func (s *Scanner) handleWalkError(filePath string, err error) error { +// under --skip-errors the entry is skipped with a UI notice and counted +// as examined, failed and unreadable, otherwise the error is fatal. +func (s *Scanner) handleWalkError( + filePath string, err error, result *ScanResult, +) error { if s.skipErrors { log.Error("Failed to access file (skipping due to --skip-errors)", "path", filePath, "error", err) s.ui.Errorf("Failed to access %s: %v. Skipping (--skip-errors).", s.ui.Path(filePath), err) + result.FilesScanned++ + result.FilesFailed++ + result.FilesUnreadable++ + return nil // Continue scanning } @@ -1459,6 +1500,7 @@ func (s *Scanner) processFileWithErrorHandling( s.ui.Path(fileToProcess.Path), err) countFailedFile(fileToProcess, result) + result.FilesUnreadable++ return true, nil } diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 6d74865..5f533ba 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -39,6 +39,11 @@ var ( // caller can report it apart from a failed backup. var ErrPostBackupPruneFailed = errors.New("post-backup prune failed") +// ErrFilesUnreadable is returned when --skip-errors skipped files or +// directories it could not read or list. The snapshot is complete and +// kept, so the caller can report it apart from a failed backup. +var ErrFilesUnreadable = errors.New("file(s) could not be read") + // listRecentLimit caps how many snapshot rows are fetched from the // local index for listing and purge operations. const listRecentLimit = 10000 @@ -130,12 +135,16 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { } // Process each named snapshot + filesUnreadable := 0 + for snapIdx, snapName := range snapshotNames { - err = v.createNamedSnapshot( + unreadable, err := v.createNamedSnapshot( opts, hostname, snapName, snapIdx+1, len(snapshotNames)) if err != nil { return err } + + filesUnreadable += unreadable } // Print overall summary if multiple snapshots @@ -151,6 +160,19 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { } } + return v.finishCreateSnapshot(filesUnreadable) +} + +// finishCreateSnapshot ends a run whose snapshots are all complete and +// kept. Like finishRestore, it returns an error when --skip-errors +// skipped anything it could not read or list; otherwise it prints the +// closing line. A file removed during the run is counted as failed in +// the summary but is not an error, with or without --skip-errors. +func (v *Vaultik) finishCreateSnapshot(filesUnreadable int) error { + if filesUnreadable > 0 { + return fmt.Errorf("%d %w", filesUnreadable, ErrFilesUnreadable) + } + // Terminus must obey the --cron invariant: silent on total // success only. UI.Complete is dropped in cron/quiet mode (that's // the success path), but if any warnings fired during the run we @@ -240,16 +262,22 @@ type snapshotStats struct { totalBlobsUploaded int uploadDuration time.Duration + // The part of totalFilesFailed that --skip-errors skipped because it + // could not be read or listed. + totalFilesUnreadable int + // The sizes of all blobs the snapshot references, set by // finalizeSnapshotMetadata once snapshot_blobs is populated. blobSize int64 blobUncompressedSize int64 } -// createNamedSnapshot creates a single named snapshot +// createNamedSnapshot creates a single named snapshot and returns the +// number of entries --skip-errors skipped because it could not read or +// list them. func (v *Vaultik) createNamedSnapshot( opts *SnapshotCreateOptions, hostname, snapName string, idx, total int, -) error { +) (int, error) { snapshotStartTime := time.Now() if total > 1 { @@ -258,12 +286,12 @@ func (v *Vaultik) createNamedSnapshot( resolvedDirs, err := v.resolveSnapshotPaths(snapName) if err != nil { - return err + return 0, err } previousSnapshotID, err := v.previousSnapshotID(snapName) if err != nil { - return err + return 0, err } scanner := v.ScannerFactory(snapshot.ScannerParams{ @@ -278,7 +306,7 @@ func (v *Vaultik) createNamedSnapshot( snapshotID, err := v.SnapshotManager.CreateSnapshotWithName( v.ctx, hostname, snapName, v.Globals.Version, v.Globals.Commit) if err != nil { - return fmt.Errorf("creating snapshot: %w", err) + return 0, fmt.Errorf("creating snapshot: %w", err) } log.Info("Beginning snapshot", "snapshot_id", snapshotID, "name", snapName) @@ -286,12 +314,12 @@ func (v *Vaultik) createNamedSnapshot( stats, err := v.scanAllDirectories(scanner, resolvedDirs, snapshotID) if err != nil { - return err + return 0, err } err = v.finalizeSnapshotMetadata(snapshotID, stats) if err != nil { - return err + return 0, err } log.Info("Snapshot complete", @@ -304,7 +332,7 @@ func (v *Vaultik) createNamedSnapshot( v.printSnapshotSummary(snapshotID, snapshotStartTime, stats) - return nil + return stats.totalFilesUnreadable, nil } // previousSnapshotID returns the ID of the most recent completed snapshot @@ -390,6 +418,7 @@ func (v *Vaultik) scanAllDirectories( stats.totalBlobs += result.BlobsCreated stats.totalFilesSkipped += result.FilesSkipped stats.totalFilesFailed += result.FilesFailed + stats.totalFilesUnreadable += result.FilesUnreadable stats.totalBytesSkipped += result.BytesSkipped stats.totalFilesDeleted += result.FilesDeleted stats.totalBytesDeleted += result.BytesDeleted diff --git a/internal/vaultik/snapshot_deleted_count_test.go b/internal/vaultik/snapshot_deleted_count_test.go index 80dbd0a..24f78fd 100644 --- a/internal/vaultik/snapshot_deleted_count_test.go +++ b/internal/vaultik/snapshot_deleted_count_test.go @@ -178,11 +178,13 @@ func TestBackupDoesNotCountFileInUnopenableDirectoryAsDeleted(t *testing.T) { } env.out.Reset() - require.NoError(t, env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + err := env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ SkipErrors: true, Snapshots: []string{"work"}, - })) - assert.Contains(t, env.out.String(), filesLine(1, 0, 1)) + }) + require.ErrorIs(t, err, vaultik.ErrFilesUnreadable) + assert.Contains(t, env.out.String(), + "Files: 2 examined, 0 backed up, 1 unchanged, 1 failed.") } // A backup counts only files that the previous snapshot of its own name diff --git a/internal/vaultik/snapshot_failed_file_test.go b/internal/vaultik/snapshot_failed_file_test.go index 2742115..0c906fe 100644 --- a/internal/vaultik/snapshot_failed_file_test.go +++ b/internal/vaultik/snapshot_failed_file_test.go @@ -49,13 +49,19 @@ func TestSnapshotSummaryCountsFileNotStoredAsFailed(t *testing.T) { name string openErr error skipErrors bool + wantErr error // nil for none }{ // What a normal user gets opening a file with mode 000. {name: "unopenable under skip-errors", - openErr: os.ErrPermission, skipErrors: true}, + openErr: os.ErrPermission, skipErrors: true, + wantErr: vaultik.ErrFilesUnreadable}, // What opening a file removed after phase 1 gives. {name: "removed between the phases", openErr: os.ErrNotExist, skipErrors: false}, + // A removal is not an error, so --skip-errors does not make the + // run fail. See https://git.eeqj.de/sneak/vaultik/issues/310. + {name: "removed between the phases under skip-errors", + openErr: os.ErrNotExist, skipErrors: true}, } for _, tt := range tests { @@ -99,10 +105,11 @@ func TestSnapshotSummaryCountsFileNotStoredAsFailed(t *testing.T) { v := newBackupVaultik(ctx, cfg, store, repos, db, fs) v.UI = ui.NewWithColor(out, false) - require.NoError(t, v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + err = v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ SkipErrors: tt.skipErrors, Snapshots: []string{"src"}, - })) + }) + require.ErrorIs(t, err, tt.wantErr) summary := out.String() assert.Contains(t, summary, diff --git a/internal/vaultik/snapshot_skip_errors_test.go b/internal/vaultik/snapshot_skip_errors_test.go index af07afe..4864760 100644 --- a/internal/vaultik/snapshot_skip_errors_test.go +++ b/internal/vaultik/snapshot_skip_errors_test.go @@ -3,6 +3,7 @@ package vaultik_test import ( "context" "fmt" + "os" "path/filepath" "testing" @@ -73,3 +74,144 @@ func TestSkipErrorsBackupStopsOnIndexErrorRecordingDirectory(t *testing.T) { require.Len(t, snapshots, 1) assert.Nil(t, snapshots[0].CompletedAt) } + +// A backup under --skip-errors that skips a file it cannot open, or a +// directory it cannot list, keeps the snapshot, counts what it skipped +// as failed and returns an error instead of finishing successfully. See +// https://git.eeqj.de/sneak/vaultik/issues/310. +func TestSkipErrorsBackupKeepsSnapshotAndFailsWhenItSkips(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + tests := []struct { + name string + skipped string // relative to the source directory + }{ + {name: "file it cannot open", skipped: "skipdir/file.txt"}, + {name: "directory it cannot list", skipped: "skipdir"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "stored.txt": []byte("stored"), + "skipdir/file.txt": []byte("in skipdir"), + }) + env.setSnapshot("work", "") + + // A mode does not lock out root, who runs the tests, so + // opening the skipped path is made to fail instead. + env.v.Fs = &openFailFs{ + path: filepath.Join(env.src, tt.skipped), + err: os.ErrPermission, + } + + err := env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: true, + Snapshots: []string{"work"}, + }) + require.ErrorIs(t, err, vaultik.ErrFilesUnreadable) + + assert.Contains(t, env.out.String(), + "Files: 2 examined, 1 backed up, 0 unchanged, 1 failed.") + assert.NotContains(t, env.out.String(), "Finished successfully.") + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + context.Background(), listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1) + assert.NotNil(t, snapshots[0].CompletedAt, "the snapshot is kept") + }) + } +} + +// removeOnLookupFs is the real filesystem, except that path is removed +// just before it is looked up. The walk looks an entry up after listing +// its directory, so path is listed but gone when the walk reaches it. +type removeOnLookupFs struct { + afero.OsFs + + path string +} + +func (f *removeOnLookupFs) LstatIfPossible( + name string, +) (os.FileInfo, bool, error) { + if name == f.path { + _ = os.Remove(name) + } + + return f.OsFs.LstatIfPossible(name) +} + +// A file removed before the walk reaches it is counted once, as failed, +// like a file removed before its data is read, and the backup finishes +// successfully, with or without --skip-errors. See +// https://git.eeqj.de/sneak/vaultik/issues/310. +func TestBackupCountsFileRemovedBeforeWalkReachesItAsFailed(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + tests := []struct { + name string + skipErrors bool + }{ + {name: "under skip-errors", skipErrors: true}, + {name: "without skip-errors", skipErrors: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "stays.txt": []byte("stays"), + "removed.txt": []byte("removed"), + }) + env.setSnapshot("walk", "") + + // The previous snapshot has the file, so a removal the walk + // also counted as deleted would show. + env.backUp(t, "walk") + + env.v.Fs = &removeOnLookupFs{ + path: filepath.Join(env.src, "removed.txt"), + } + + env.out.Reset() + require.NoError(t, env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: tt.skipErrors, + Snapshots: []string{"walk"}, + })) + assert.Contains(t, env.out.String(), + "Files: 2 examined, 0 backed up, 1 unchanged, 1 failed.") + assert.Contains(t, env.out.String(), "Finished successfully.") + }) + } +} + +// A file an exclude pattern matches is not counted when it is removed +// before the walk reaches it. See +// https://git.eeqj.de/sneak/vaultik/issues/310. +func TestBackupIgnoresExcludedFileRemovedBeforeWalkReachesIt(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "stays.txt": []byte("stays"), + "removed.tmp": []byte("removed"), + }) + env.setSnapshot("walk", "", "*.tmp") + env.v.Fs = &removeOnLookupFs{ + path: filepath.Join(env.src, "removed.tmp"), + } + + require.NoError(t, env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: true, + Snapshots: []string{"walk"}, + })) + assert.Contains(t, env.out.String(), filesLine(1, 1, 0)) + assert.Contains(t, env.out.String(), "Finished successfully.") +} From 5b8d84e38a8da703d9ae13c0c7932a739bad1359 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 07:44:50 +0200 Subject: [PATCH 090/121] Do not prune after a backup that skipped unreadable files (closes #382) snapshot create --skip-errors --prune pruned even when files were skipped, so by default it deleted the previous snapshot of that name, the only one still holding a file that had become unreadable, along with blobs only that snapshot referenced. The prune is now skipped exactly when the run exits non-zero for entries --skip-errors could not read or list: older snapshots are kept, a warning says why, and the run still exits non-zero. A file removed during the run does not count, so such a run still prunes. The README's --prune text and the flag's help say so. Model: opus-5-5 --- README.md | 6 +- internal/cli/snapshot.go | 3 +- internal/vaultik/snapshot.go | 10 ++- internal/vaultik/snapshot_skip_errors_test.go | 66 +++++++++++++++++++ 4 files changed, 82 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5827e84..32a0c81 100644 --- a/README.md +++ b/README.md @@ -297,7 +297,11 @@ value where a list belongs or a word where a number belongs), is refused. (for crontab) * `--prune`: After backup, drop older snapshots of each backed-up name and remove orphaned blobs from remote storage. By default keeps only the latest - snapshot per name; use `--keep-newer-than` for a rolling window. + snapshot per name; use `--keep-newer-than` for a rolling window. When + `--skip-errors` skipped a file or directory it could not read or list, the + prune does not run and every older snapshot is kept, since one of them may + be the only one that holds what was skipped; the command says so and exits + non-zero. A file removed during the backup does not stop the prune. * `--keep-newer-than `: With `--prune`, keep snapshots newer than this duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`). Without `--prune`, or with a value that is not a valid duration, the diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 7f7742c..7464681 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -132,7 +132,8 @@ on Linux), then /etc/vaultik/config.yml.`, "Run in cron mode (silent unless warning or error)") cmd.Flags().BoolVar(&opts.Prune, "prune", false, "After backup, drop older snapshots of the same name and remove "+ - "orphaned blobs") + "orphaned blobs (not after a backup that skipped unreadable "+ + "files)") cmd.Flags().StringVar(&opts.KeepNewerThan, "keep-newer-than", "", "With --prune: keep snapshots newer than this duration "+ "(e.g. 30d, 4w, 6mo, 1y; m is minutes, mo is months) "+ diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 5f533ba..806495f 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -153,7 +153,15 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { len(snapshotNames), v.UI.Duration(time.Since(overallStartTime))) } - if opts.Prune { + switch { + case opts.Prune && filesUnreadable > 0: + // An older snapshot may be the only one that still holds a file + // this run could not read. + log.Warn("Skipping post-backup prune", + "files_unreadable", filesUnreadable) + v.UI.Warningf("Skipped the post-backup prune because %d file(s) "+ + "could not be read; older snapshots are kept.", filesUnreadable) + case opts.Prune: err = v.runPostBackupPrune(snapshotNames, opts.KeepNewerThan) if err != nil { return fmt.Errorf("%w: %w", ErrPostBackupPruneFailed, err) diff --git a/internal/vaultik/snapshot_skip_errors_test.go b/internal/vaultik/snapshot_skip_errors_test.go index 4864760..0bf1ea3 100644 --- a/internal/vaultik/snapshot_skip_errors_test.go +++ b/internal/vaultik/snapshot_skip_errors_test.go @@ -215,3 +215,69 @@ func TestBackupIgnoresExcludedFileRemovedBeforeWalkReachesIt(t *testing.T) { assert.Contains(t, env.out.String(), filesLine(1, 1, 0)) assert.Contains(t, env.out.String(), "Finished successfully.") } + +// A backup under --skip-errors --prune that skipped a file it could not +// read does not prune: the previous snapshot, the only one that holds +// the file, is kept, and the output says the prune was skipped. See +// https://git.eeqj.de/sneak/vaultik/issues/382. +func TestSkipErrorsBackupDoesNotPruneWhenItSkips(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "other.txt": []byte("other"), + "skipped.txt": []byte("skipped"), + }) + env.setSnapshot("photos", "") + env.backUp(t, "photos") + + // An unchanged file is not read again, so the file is changed before + // it becomes unreadable. + skipped := filepath.Join(env.src, "skipped.txt") + require.NoError(t, os.WriteFile(skipped, []byte("changed"), 0o600)) + env.v.Fs = &openFailFs{path: skipped, err: os.ErrPermission} + + env.out.Reset() + err := env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + SkipErrors: true, + Snapshots: []string{"photos"}, + }) + require.ErrorIs(t, err, vaultik.ErrFilesUnreadable) + assert.Contains(t, env.out.String(), + "Skipped the post-backup prune because 1 file(s) could not be read") + assert.NotContains(t, env.out.String(), "Running post-backup prune.") + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + context.Background(), listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 2, "the previous snapshot is kept") +} + +// A file removed during a backup under --skip-errors --prune is not a +// skipped file, so the backup prunes as usual. See +// https://git.eeqj.de/sneak/vaultik/issues/382. +func TestSkipErrorsBackupPrunesWhenAFileIsRemovedDuringIt(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "other.txt": []byte("other"), + "removed.txt": []byte("removed"), + }) + env.setSnapshot("photos", "") + env.backUp(t, "photos") + + env.v.Fs = &removeOnLookupFs{path: filepath.Join(env.src, "removed.txt")} + + require.NoError(t, env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + SkipErrors: true, + Snapshots: []string{"photos"}, + })) + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + context.Background(), listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "the previous snapshot is pruned") +} From 2590f4958320672286e00413662f01baecbf8718 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 09:18:09 +0200 Subject: [PATCH 091/121] Record the defect-hunt fixes in TODO.md Completed Steps (closes #334) Adds a Completed Steps entry, newest first, for every issue from the defect hunt (https://git.eeqj.de/sneak/vaultik/issues/288) that a merged fix closed and that had none: the hunt's own issues, those filed while fixing them, and the owner's ruling on https://git.eeqj.de/sneak/vaultik/issues/239. Each entry says in one or two sentences what was wrong and what changed; the detail is in each fix's commit. Next Step now says the hunt's fixes have landed. Judgement call: https://git.eeqj.de/sneak/vaultik/issues/332, closed as covered by the fix for https://git.eeqj.de/sneak/vaultik/issues/296, is named in that entry rather than given its own. Judgement call: https://git.eeqj.de/sneak/vaultik/issues/351, a Docker build fix filed while gating these fixes, gets an entry. Model: opus-5-5 --- TODO.md | 224 +++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 220 insertions(+), 4 deletions(-) diff --git a/TODO.md b/TODO.md index 9160574..70ba387 100644 --- a/TODO.md +++ b/TODO.md @@ -15,13 +15,229 @@ pre-1.0 # Next Step The 1.0 work is complete on `next`: the scope settled on -[issue #125](https://git.eeqj.de/sneak/vaultik/issues/125) was the work -already planned for 1.0, and all of it has landed. The mechanism to cut -the tag exists and is exercised; what is left is merging `next` to -`main` and tagging, both the owner's. +[issue #125](https://git.eeqj.de/sneak/vaultik/issues/125) has landed, +and so has every fix from the defect hunt before the release candidate +([issue #288](https://git.eeqj.de/sneak/vaultik/issues/288)). What is +left is merging `next` to `main` and tagging the release, both the +owner's; a `v*` tag runs the release build in +`.gitea/workflows/release.yml`. # Completed Steps +- 2026-10-14: Stopped `snapshot create --prune` pruning after a backup + that skipped files it could not read + ([issue #382](https://git.eeqj.de/sneak/vaultik/issues/382)). Such a + prune could delete the only snapshot still holding those files. + +- 2026-10-14: Made `snapshot create --skip-errors` exit non-zero, + instead of 0, when it skips anything it cannot read + ([issue #310](https://git.eeqj.de/sneak/vaultik/issues/310)). + +- 2026-10-14: Kept the local index when `remote nuke` cannot list or + find the destination store + ([issue #292](https://git.eeqj.de/sneak/vaultik/issues/292)). Nuke + had cleared the local snapshot records anyway; it now fails before + removing anything. + +- 2026-10-14: Stopped counting directories and unchanged symlinks as + files to back up + ([issue #305](https://git.eeqj.de/sneak/vaultik/issues/305)). + +- 2026-10-14: Refused a backup destination that an unplugged volume + left empty, as the owner ruled + ([issue #239](https://git.eeqj.de/sneak/vaultik/issues/239)). Every + backup now writes `vaultik-destination.txt` at the destination root, + and while the local index holds snapshots stored there, a destination + without it is treated as not present. + +- 2026-10-14: Warned about restored ownership only when an entry's + owner or group differs from the recorded one + ([issue #316](https://git.eeqj.de/sneak/vaultik/issues/316)); a + restore by a non-root user had warned even when none did. + +- 2026-10-14: Made `snapshot list` report a changed destination instead + of advising `prune`, which refuses in that case + ([issue #317](https://git.eeqj.de/sneak/vaultik/issues/317)). + +- 2026-10-14: Counted a file as deleted by a backup only if the + previous snapshot of the same name listed it + ([issue #304](https://git.eeqj.de/sneak/vaultik/issues/304)); files + that snapshot did not list had been counted too. + +- 2026-10-14: Named each prefix once in restore, verify and purge + errors, some of which repeated it + ([issue #327](https://git.eeqj.de/sneak/vaultik/issues/327)). A deep + verify log line that named S3 whatever the destination now names + storage. + +- 2026-10-14: Refused credentials in a storage URL's endpoint or rclone + remote name, which were accepted and could then be printed + ([issue #322](https://git.eeqj.de/sneak/vaultik/issues/322)). + +- 2026-10-14: Ran `$EDITOR` through the shell in `config edit`, so a + value with arguments, such as `code --wait`, no longer fails + ([issue #315](https://git.eeqj.de/sneak/vaultik/issues/315)). + +- 2026-10-14: Made `snapshot remove` fail, instead of exiting 0, when + it cannot delete the metadata of a snapshot that is only on the + destination store + ([issue #340](https://git.eeqj.de/sneak/vaultik/issues/340)). The + README and the help now say when it prints the `vaultik prune` + follow-up. + +- 2026-10-14: Labelled the totals in the local index cleanup before + each backup as totals + ([issue #306](https://git.eeqj.de/sneak/vaultik/issues/306)). Each + was shown as `(N remain)`, which read as rows left to clean up. + +- 2026-10-13: Freed a cached blob once no file still to restore needs + it ([issue #324](https://git.eeqj.de/sneak/vaultik/issues/324)); one + also used by a file outside the selected paths had stayed in the + temporary cache until the restore ended. + +- 2026-10-13: Kept the whole startup error when it contains `): ` + ([issue #320](https://git.eeqj.de/sneak/vaultik/issues/320)). Such + an error was cut at its last `): `, so the `blob_size_limit` one lost + the setting's name. + +- 2026-10-13: Silenced the status lines of `prune` and snapshot removal + under `--cron` and `--quiet` + ([issue #294](https://git.eeqj.de/sneak/vaultik/issues/294)). + +- 2026-10-13: Read the rclone config file that `RCLONE_CONFIG` names + ([issue #321](https://git.eeqj.de/sneak/vaultik/issues/321)); a + remote defined only there had been reported as not found. + +- 2026-10-13: Made `/**/` in an exclude pattern match zero directories, + as in gitignore + ([issue #338](https://git.eeqj.de/sneak/vaultik/issues/338)); + `a/**/*.log` had missed `a/x.log`. + +- 2026-10-13: Made the `chunk_size` and `blob_size_limit` defaults and + the `chunk_size` minimum 1000-based, like the size parser and the + docs ([issue #313](https://git.eeqj.de/sneak/vaultik/issues/313)). + +- 2026-10-13: Kept a snapshot's remote metadata when `snapshot purge` + cannot remove it from the local index + ([issue #337](https://git.eeqj.de/sneak/vaultik/issues/337)); the + purge had deleted the metadata anyway and exited 0. + +- 2026-10-13: Made `snapshot restore` fail for a requested path that + matches nothing, which it had ignored + ([issue #309](https://git.eeqj.de/sneak/vaultik/issues/309)). + +- 2026-10-13: Made `remote nuke` delete every object under `metadata/` + and `blobs/` + ([issue #291](https://git.eeqj.de/sneak/vaultik/issues/291)); it had + left some, such as a stray `.DS_Store`, while reporting the store + empty. + +- 2026-10-13: Made `config set` create a list for an index under a + missing key + ([issue #308](https://git.eeqj.de/sneak/vaultik/issues/308)); it had + written a map, after which no command could load the config. + +- 2026-10-13: Listed a `file://` destination through a symlinked + `metadata/` or `blobs/`, which had listed as empty + ([issue #296](https://git.eeqj.de/sneak/vaultik/issues/296)). A link + to a missing target now fails the listing + ([issue #332](https://git.eeqj.de/sneak/vaultik/issues/332)). + +- 2026-10-13: Made `snapshot verify --deep --json` report its blob + counts ([issue #314](https://git.eeqj.de/sneak/vaultik/issues/314)); + a failed run had reported 0 missing and 0 verified. + +- 2026-10-13: Limited and retried the module download in the Docker + build ([issue #351](https://git.eeqj.de/sneak/vaultik/issues/351)), + which had hung for as long as a stalled connection to the module + proxy lasted. + +- 2026-10-13: Recorded each snapshot's uncompressed size when its + backup runs + ([issue #360](https://git.eeqj.de/sneak/vaultik/issues/360)). A later + backup could change an older snapshot's UNCOMPRESSED SIZE in + `snapshot list`. + +- 2026-10-13: Stopped `snapshot restore --skip-errors --verify` + reporting a file that failed to restore again as a checksum failure + ([issue #323](https://git.eeqj.de/sneak/vaultik/issues/323)). + +- 2026-10-13: Recorded the stored size of a blob a backup finds already + stored, not the size of its local copy, which can differ, so + `snapshot verify` could fail on a good snapshot + ([issue #300](https://git.eeqj.de/sneak/vaultik/issues/300)). + +- 2026-10-13: Stopped the local index and the blob upload step ending + the process on a failed close of query results or a failed temp file + cleanup ([issue #345](https://git.eeqj.de/sneak/vaultik/issues/345)); + both are now returned as errors. + +- 2026-10-13: Closed the snapshot database's storage reader too when + restore or deep verify is interrupted + ([issue #356](https://git.eeqj.de/sneak/vaultik/issues/356)). + +- 2026-10-13: Made `prune` and `remote nuke` fail when a delete on the + backup destination store fails + ([issue #290](https://git.eeqj.de/sneak/vaultik/issues/290)). + +- 2026-10-13: Made an S3 listing that the server cuts short an error + ([issue #297](https://git.eeqj.de/sneak/vaultik/issues/297)); `prune` + had taken it as complete and could delete blobs still in use. + +- 2026-10-13: Made shallow `snapshot verify` report a blob it could not + check apart from a missing one + ([issue #318](https://git.eeqj.de/sneak/vaultik/issues/318)); any + error checking a blob had counted as missing, its cause dropped. + +- 2026-10-13: Restored the other files when a file's chunk is in no + blob under `--skip-errors` + ([issue #326](https://git.eeqj.de/sneak/vaultik/issues/326)); that + file had stopped the restore before anything was restored. + +- 2026-10-13: Recorded each snapshot's new chunk size when its backup + runs ([issue #311](https://git.eeqj.de/sneak/vaultik/issues/311)). + `snapshot list` could show a NEW CHUNK SIZE of 0 B for a snapshot + whose change was a modified file. + +- 2026-10-13: Made a backup interrupted during a local index write exit + as interrupted + ([issue #301](https://git.eeqj.de/sneak/vaultik/issues/301)); it could + end with `FATAL: failed to rollback transaction` and exit 1 instead of + 130. + +- 2026-10-13: Printed `snapshot list` and `snapshot purge` sizes like + every other command + ([issue #312](https://git.eeqj.de/sneak/vaultik/issues/312)). They, + and the `bytes` value in terminal log lines, were 1024-based but + labelled KB or MB, and now use 1000-based units. + +- 2026-10-13: Closed each blob's storage reader when restore or deep + verify is interrupted, which ends a stalled read unless it is stuck in + the kernel ([issue #325](https://git.eeqj.de/sneak/vaultik/issues/325)). + +- 2026-10-13: Made a mistyped subcommand under `snapshot`, `config`, + `remote`, `database` or `completion` an error + ([issue #319](https://git.eeqj.de/sneak/vaultik/issues/319)); each had + printed its help and exited 0. + +- 2026-10-13: Made an exclude pattern starting with `**/` match + directly under the snapshot path too, as in gitignore + ([issue #303](https://git.eeqj.de/sneak/vaultik/issues/303)). + +- 2026-10-13: Refused a relative `file://` storage URL and decoded its + percent-escapes + ([issue #299](https://git.eeqj.de/sneak/vaultik/issues/299)); a + relative path had moved with the working directory. + +- 2026-10-13: Removed the blob temp file when a backup stops part-way + ([issue #302](https://git.eeqj.de/sneak/vaultik/issues/302)); the + half-written blob had stayed in `$TMPDIR`. + +- 2026-10-13: Checked `--keep-newer-than` before a backup starts + ([issue #307](https://git.eeqj.de/sneak/vaultik/issues/307)); an + invalid value had been read only by the prune after the backup, so + retention never ran. + - 2026-10-13: Stopped `remote info` counting a file under `blobs/` that is not a blob as an orphaned blob ([issue #295](https://git.eeqj.de/sneak/vaultik/issues/295)). A stray From 6a57750a7bfd4489520e4c686225b363f4ba5240 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 14 Oct 2026 13:06:35 +0200 Subject: [PATCH 092/121] Keep unreferenced blobs newer than prune_grace_period (closes #387) A backup uploads its blobs before the manifest that lists them, and the process lock covers one user on one machine, so a prune from another host or user sharing the destination deleted a running backup's blobs. Prune now deletes an unreferenced blob only once its listed time is older than the new config key prune_grace_period (default 24h; a negative value is refused). A newer blob, or one listed with no time, is kept and counted (blobs_too_new). The rclone backend takes each object's time from the listing (use_server_modtime). Decision: a blob a backup reuses from an earlier run that stopped before its manifest keeps its old time and is not protected; the docs and config comments say so. Model: opus-5-5 --- README.md | 55 ++++++- config.example.yml | 12 ++ docs/DATAMODEL.md | 3 +- docs/REPOSTRUCTURE.md | 2 +- internal/cli/config.go | 10 ++ internal/cli/entry_prune_quiet_test.go | 8 +- internal/cli/prune.go | 7 +- internal/cli/snapshot.go | 4 +- internal/config/config.go | 17 ++ internal/config/config_test.go | 68 ++++++++ internal/s3/client.go | 11 +- internal/storage/conformance_test.go | 38 ++++- internal/storage/file.go | 5 +- internal/storage/rclone.go | 13 +- internal/storage/rclone_test.go | 75 +++++++++ internal/storage/s3.go | 7 +- internal/storage/storer.go | 9 +- internal/vaultik/info.go | 8 +- internal/vaultik/prune.go | 76 +++++++-- internal/vaultik/prune_grace_period_test.go | 166 ++++++++++++++++++++ internal/vaultik/remove_snapshot_test.go | 12 +- 21 files changed, 554 insertions(+), 52 deletions(-) create mode 100644 internal/vaultik/prune_grace_period_test.go diff --git a/README.md b/README.md index 32a0c81..14a7bb1 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,14 @@ vaultik snapshot restore ~/vaultik-restore # 0 3 * * * vaultik snapshot create --cron --prune --keep-newer-than 4w ``` +On a destination shared between hosts or users, the prune in that cron line +relies on `prune_grace_period` (default `24h`) to leave the blobs of a backup +another one is still running, so it must be longer than the longest backup +run. It does not protect a blob that backup reuses from an earlier run that +stopped before its manifest: the prune can delete such a blob, and the new +snapshot then cannot be restored. To not depend on the grace period, give each +host its own prefix or directory. See [locking](#locking). + ## restoring on another machine Restoring on a host that never ran the backup — a replacement machine @@ -192,7 +200,22 @@ process-wide lock at `$XDG_DATA_HOME/vaultik/vaultik.pid` (`~/.local/share/vaultik/vaultik.pid` on Linux) for the whole run. Only one of them runs at a time: a second one exits immediately with an "already running" error rather than waiting, so two writers can never -corrupt the local index or the destination store. +corrupt the local index. + +The lock covers one user on one machine. It does not stop another user, +or another host, from writing to the same destination store at the same +time. A backup uploads its blobs before the manifest that lists them, so a +prune from elsewhere at that moment finds blobs no snapshot lists. It +deletes such a blob only once it is older than `prune_grace_period` +(default `24h`), which therefore must be longer than the longest backup run +of any host or user sharing the destination. The grace period does not +protect a blob a backup reuses from an earlier run that stopped before its +manifest: a backup skips the upload of a blob already on the destination, so +that blob keeps the time of its first upload, and a prune from elsewhere +during the backup can delete it; the new snapshot then cannot be restored. +`remote nuke` deletes everything regardless. To not depend on the grace +period, give each host or user its own prefix (or directory) on the +destination. Read-only commands — `info`, `snapshot list`, `snapshot verify`, and `remote info` — do not take the lock and are never blocked, so they run @@ -296,7 +319,8 @@ value where a list belongs or a word where a number belongs), is refused. * `--cron`: Silent on total success; warnings and errors are still printed (for crontab) * `--prune`: After backup, drop older snapshots of each backed-up name and - remove orphaned blobs from remote storage. By default keeps only the latest + remove orphaned blobs older than `prune_grace_period` from remote storage, + as `prune` does. By default keeps only the latest snapshot per name; use `--keep-newer-than` for a rolling window. When `--skip-errors` skipped a file or directory it could not read or list, the prune does not run and every older snapshot is kept, since one of them may @@ -423,9 +447,15 @@ local snapshot whose remote metadata is missing is dropped from the local index; (2) delete orphaned local rows (files, chunks, blobs no longer referenced by any completed snapshot); (3) list every remote manifest on the destination store to compute the still-referenced blob -set and delete any blob not in that set. Step (3) reads all remote -manifests — network cost scales with the number of snapshots. `snapshot -create --prune` runs the same cleanup automatically; this is the +set and delete any blob not in that set that is older than +`prune_grace_period` (default `24h`). A newer one is kept and counted: it +may belong to a backup still running, on this host or another sharing the +destination store, that has not yet uploaded its manifest. The grace period +does not protect a blob such a backup reuses from an earlier run that stopped +before its manifest: that blob keeps the time of its first upload, so it can +be deleted. Step (3) reads all remote manifests — network cost scales with +the number of snapshots. +`snapshot create --prune` runs the same cleanup automatically; this is the manual entry point for the same work. If the destination store cannot be listed, or the local index holds snapshots and the destination has no `vaultik-destination.txt` (an unplugged volume's empty mount point), @@ -436,6 +466,9 @@ exits non-zero. * `--json`: Output stats as JSON. Also skips the confirmation prompt, as `--force` does. A blob that cannot be deleted is counted in `blobs_failed`, and the document is printed before the non-zero exit. + A blob kept for being newer than `prune_grace_period`, or because the + listing of the destination gives no time for it, is counted in + `blobs_too_new` and not in `blobs_found`. **`info`**: Display system configuration, storage settings, encryption recipients, and local database statistics. @@ -510,6 +543,14 @@ being written, a killed upload can leave a truncated object under its name, which a later backup takes for complete. A leftover `.partial` file is ignored and can be deleted. +A destination shared between hosts or users, each with its own local index, +relies on `prune_grace_period` to keep one's prune from deleting the blobs of +another's backup still running, so it must be longer than the longest backup +run. It does not protect a blob that backup reuses from an earlier run that +stopped before its manifest, which the prune can delete. To not depend on the +grace period, give each host its own prefix (or directory). See +[locking](#locking). + Legacy S3 configuration via `s3.*` fields (endpoint, bucket, prefix, etc.) is still supported for backward compatibility. `storage_url` takes precedence if both are set. @@ -596,7 +637,8 @@ format does and does not protect. 1. List all snapshot manifests 2. Build set of all referenced blob hashes 3. List all blobs in storage -4. Delete any blob not in the referenced set +4. Delete any blob not in the referenced set that is older than + `prune_grace_period` ### chunking and deduplication @@ -641,6 +683,7 @@ complete annotated example also lives in | `chunk_size` | `10MB` | Average chunk size for content-defined chunking | | `blob_size_limit` | `10GB` | Maximum blob size before splitting. Must be at least four times `chunk_size` (the largest chunk the chunker can emit), otherwise a single-chunk blob could exceed the limit. A backup needs free temporary space, because each blob is written whole to a temporary file before it is uploaded (up to about `blob_size_limit`; an rclone destination that cannot stream uploads needs about twice that) and the metadata export writes copies of the local index. Temporary files go to `$TMPDIR` (default `/tmp`); with `TMPDIR` unset, SQLite writes one of those copies to `/var/tmp` | | `compression_level` | `3` | zstd compression level (1-19) | +| `prune_grace_period` | `24h` | How old a blob that no snapshot lists must be before `prune` deletes it. A backup uploads its blobs before the manifest that lists them, so on a destination shared between hosts or users this must be longer than the longest backup run (see [locking](#locking)). It does not protect a blob a backup reuses from an earlier run that stopped before its manifest: that blob keeps the time of its first upload, so a prune can delete it. A duration such as `36h` or `90m`; `0s` deletes such blobs at once | | `hostname` | system hostname | Hostname used in snapshot IDs | | `index_path` | platform data dir | Local SQLite index path | diff --git a/config.example.yml b/config.example.yml index 55dae8e..a2d8f84 100644 --- a/config.example.yml +++ b/config.example.yml @@ -328,6 +328,18 @@ storage_url: "rclone://myremote/path/to/backups" # Higher = better compression but slower # Default: 3 compression_level: 5 + +# How old a blob that no snapshot lists must be before prune deletes it +# A backup uploads its blobs before the manifest that lists them, so on a +# destination shared between hosts or users this must be longer than the +# longest backup run +# It does not protect a blob a backup reuses from an earlier run that stopped +# before its manifest: that blob keeps the time of its first upload, so a +# prune can delete it +# Supports: 36h, 90m, etc.; 0s deletes them at once +# Default: 24h +#prune_grace_period: 24h + # Hostname to use in backup metadata # Default: system hostname #hostname: myserver diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index 9f94fde..4f0ad45 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -228,7 +228,8 @@ The restore process doesn't use the local database. Instead: 1. **Identify Unreferenced Blobs** - Query blobs not referenced by any remaining snapshot - - Delete from S3 and local database + - Delete from S3, once older than `prune_grace_period`, and from the local + database ### 6. Incomplete Snapshot Cleanup diff --git a/docs/REPOSTRUCTURE.md b/docs/REPOSTRUCTURE.md index 6a0661a..b7c6946 100644 --- a/docs/REPOSTRUCTURE.md +++ b/docs/REPOSTRUCTURE.md @@ -166,7 +166,7 @@ The prune operation is safe because: 1. It keeps every blob listed in any snapshot's manifest and deletes only blobs that no manifest references 2. Manifests are unencrypted and can be read without keys 3. If any manifest cannot be downloaded or decoded, prune deletes nothing and exits with an error, rather than treating that snapshot's blobs as unreferenced -4. Prune requires exclusive access to the destination: running it during a concurrent backup can race a snapshot whose manifest is not yet written, so do not prune while a backup is in progress +4. It deletes an unreferenced blob only once the blob is older than `prune_grace_period` (default `24h`). A backup uploads its blobs before the manifest that lists them, so a prune running meanwhile, on this host or another sharing the destination, leaves them as long as no backup run takes longer than the grace period. The grace period does not protect a blob a backup reuses from an earlier run that stopped before its manifest: the backup skips the upload of a blob already on the destination, so that blob keeps the time of its first upload, and a prune before the backup's manifest is written can delete it; the new snapshot then cannot be restored. `remote nuke` has no such check ## Restoration Requirements diff --git a/internal/cli/config.go b/internal/cli/config.go index 468d031..638b6ef 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -239,6 +239,16 @@ storage_url: "" # Default: 3 # compression_level: 3 +# How old a blob that no snapshot lists must be before prune deletes it. +# A backup uploads its blobs before the manifest that lists them, so on a +# destination shared between hosts or users this must be longer than the +# longest backup run. It does not protect a blob a backup reuses from an +# earlier run that stopped before its manifest: that blob keeps the time of +# its first upload, so a prune can delete it. +# Accepts: 36h, 90m, etc. 0s deletes them at once. +# Default: 24h +# prune_grace_period: 24h + # Hostname used in snapshot IDs. Default: system hostname. # hostname: myserver diff --git a/internal/cli/entry_prune_quiet_test.go b/internal/cli/entry_prune_quiet_test.go index 92e7a3b..30e1a33 100644 --- a/internal/cli/entry_prune_quiet_test.go +++ b/internal/cli/entry_prune_quiet_test.go @@ -5,6 +5,7 @@ import ( "path/filepath" "strings" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -14,8 +15,8 @@ import ( const flagCron = "--cron" // plantUnreferencedBlob writes a blob that no snapshot references to the -// destination store at storeDir, so that a prune deletes it. Returns its -// path. +// destination store at storeDir, dated long before any prune grace period, +// so that a prune deletes it. Returns its path. func plantUnreferencedBlob(t *testing.T, storeDir string) string { t.Helper() @@ -25,6 +26,9 @@ func plantUnreferencedBlob(t *testing.T, storeDir string) string { require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o750)) require.NoError(t, os.WriteFile(path, []byte("unreferenced"), 0o600)) + longAgo := time.Unix(0, 0) + require.NoError(t, os.Chtimes(path, longAgo, longAgo)) + return path } diff --git a/internal/cli/prune.go b/internal/cli/prune.go index 707617b..77f38b6 100644 --- a/internal/cli/prune.go +++ b/internal/cli/prune.go @@ -20,7 +20,12 @@ Local cleanup drops incomplete snapshots and any files, chunks, or blobs no longer referenced by a completed snapshot. Remote cleanup scans every snapshot manifest in the destination store, builds the set of still-referenced blob hashes, and deletes any blob not in that -set. +set that is older than prune_grace_period (default 24h). A newer one +is kept: it may belong to a backup still running, on this host or +another sharing the destination store, that has not yet uploaded its +manifest. The grace period does not protect a blob such a backup +reuses from an earlier run that stopped before its manifest: that +blob keeps the time of its first upload, so it can be deleted. Snapshot create --prune runs the same cleanup automatically; this command is the manual entry point for the same work (e.g. after a diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 7464681..efb176b 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -132,8 +132,8 @@ on Linux), then /etc/vaultik/config.yml.`, "Run in cron mode (silent unless warning or error)") cmd.Flags().BoolVar(&opts.Prune, "prune", false, "After backup, drop older snapshots of the same name and remove "+ - "orphaned blobs (not after a backup that skipped unreadable "+ - "files)") + "orphaned blobs older than prune_grace_period (not after a "+ + "backup that skipped unreadable files)") cmd.Flags().StringVar(&opts.KeepNewerThan, "keep-newer-than", "", "With --prune: keep snapshots newer than this duration "+ "(e.g. 30d, 4w, 6mo, 1y; m is minutes, mo is months) "+ diff --git a/internal/config/config.go b/internal/config/config.go index 64778c5..a2b86b9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -11,6 +11,7 @@ import ( "path/filepath" "sort" "strings" + "time" "filippo.io/age" "git.eeqj.de/sneak/smartconfig" @@ -38,6 +39,7 @@ const ( defaultChunkSize = Size(10 * 1000 * 1000) // 10MB defaultS3PartSize = Size(5 * 1024 * 1024) // 5MiB defaultCompressionLevel = 3 + defaultPruneGracePeriod = 24 * time.Hour minChunkSize = 1000 * 1000 // 1MB minCompressionLevel = 1 maxCompressionLevel = 19 @@ -67,6 +69,8 @@ var ( errFileURLNotAbsolute = errors.New( "a file:// storage_url needs an absolute path, " + "as in file:///path/to/backup") + errNegativePruneGracePeriod = errors.New( + "prune_grace_period must not be negative") errStorageNotConfigured = errors.New( "storage not configured; set storage_url or provide s3.endpoint + " + "s3.bucket + credentials") @@ -187,6 +191,13 @@ type Config struct { Snapshots map[string]SnapshotConfig `yaml:"snapshots"` CompressionLevel int `yaml:"compression_level"` + // PruneGracePeriod is how old a blob no manifest lists must be before + // a prune deletes it. A backup lists its blobs in a manifest only + // once it has uploaded them all, so a younger one may belong to a + // backup still running, on this host or another sharing the + // destination store. + PruneGracePeriod time.Duration `yaml:"prune_grace_period"` + // StorageURL specifies the storage backend using a URL format. // Takes precedence over S3Config if set. // Supported formats: @@ -288,6 +299,7 @@ func Parse(data []byte) (*Config, error) { ChunkSize: defaultChunkSize, IndexPath: filepath.Join(xdg.DataHome, appName, "index.sqlite"), CompressionLevel: defaultCompressionLevel, + PruneGracePeriod: defaultPruneGracePeriod, S3: S3Config{PartSize: defaultS3PartSize}, } @@ -356,6 +368,7 @@ func Parse(data []byte) (*Config, error) { // exceeds the configured limit // - Compression level must be between 1 and 19 // - S3 part size must be between 5MiB and 5GiB, the part sizes S3 accepts +// - Prune grace period must not be negative // // Returns an error describing the first validation failure encountered. func (c *Config) Validate() error { @@ -405,6 +418,10 @@ func (c *Config) Validate() error { return errBadS3PartSize } + if c.PruneGracePeriod < 0 { + return errNegativePruneGracePeriod + } + return nil } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 897b7e7..3f1a26b 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -6,6 +6,7 @@ import ( "path/filepath" "strings" "testing" + "time" "sneak.berlin/go/vaultik/internal/chunker" "sneak.berlin/go/vaultik/internal/log" @@ -412,6 +413,73 @@ func TestDocumentedSizeExamples(t *testing.T) { } } +// TestValidatePruneGracePeriod checks that a negative prune_grace_period +// is refused rather than acting like 0s, which deletes unreferenced blobs +// at once, and that 0s and the documented examples are accepted. +func TestValidatePruneGracePeriod(t *testing.T) { + t.Parallel() + + const withoutGracePeriod = "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file:///tmp/vaultik-test-storage\n" + + tests := []struct { + setting string + wantErr error + }{ + {"prune_grace_period: 0s", nil}, + {"prune_grace_period: 90m", nil}, + {"prune_grace_period: 36h", nil}, + {"prune_grace_period: -1h", errNegativePruneGracePeriod}, + } + + for _, tt := range tests { + t.Run(tt.setting, func(t *testing.T) { + t.Parallel() + + cfg, err := Parse([]byte(withoutGracePeriod + tt.setting + "\n")) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } + + err = cfg.Validate() + if !errors.Is(err, tt.wantErr) { + t.Fatalf("Validate() error = %v, want %v", err, tt.wantErr) + } + }) + } +} + +// TestLoadPruneGracePeriod checks that a config file without +// prune_grace_period loads with the documented 24h. The value is written out +// here rather than taken from defaultPruneGracePeriod, so that a change of the +// default fails this test. +func TestLoadPruneGracePeriod(t *testing.T) { + t.Parallel() + + const withoutGracePeriod = "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file:///tmp/vaultik-test-storage\n" + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(withoutGracePeriod), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) + } + + cfg, err := Load(path) + if err != nil { + t.Fatalf("Load() unexpected error: %v", err) + } + + if cfg.PruneGracePeriod != 24*time.Hour { + t.Errorf("prune_grace_period = %s, want 24h", cfg.PruneGracePeriod) + } +} + // TestLoadRejectsRelativeFileURL checks that a file:// storage_url with a // relative path fails at load. Accepted, it would resolve against the // working directory, so a backup run from another directory would write diff --git a/internal/s3/client.go b/internal/s3/client.go index 0867a8a..fe74a82 100644 --- a/internal/s3/client.go +++ b/internal/s3/client.go @@ -8,6 +8,7 @@ import ( "io" "strings" "sync/atomic" + "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" @@ -302,7 +303,10 @@ func IsNotFound(err error) bool { type ObjectInfo struct { Key string Size int64 - Err error + // ModTime is the object's LastModified time. Only ListObjectsStream + // sets it. + ModTime time.Time + Err error } // ListObjectsStream lists objects with the given prefix and returns a channel. @@ -343,8 +347,9 @@ func (c *Client) ListObjectsStream( } ch <- ObjectInfo{ - Key: key, - Size: *obj.Size, + Key: key, + Size: *obj.Size, + ModTime: aws.ToTime(obj.LastModified), } } } diff --git a/internal/storage/conformance_test.go b/internal/storage/conformance_test.go index e5c35f9..8e8ebbe 100644 --- a/internal/storage/conformance_test.go +++ b/internal/storage/conformance_test.go @@ -8,6 +8,7 @@ import ( "reflect" "sort" "testing" + "time" "sneak.berlin/go/vaultik/internal/storage" ) @@ -19,15 +20,17 @@ import ( // constructor, so the contract is defined once. // // It exercises the public Storer interface: round-trip, stat, list with -// prefix filtering, overwrite, delete, delete-of-missing, and not-found on -// Get and Stat. Each section takes its own fresh backend instance, so the -// order of sections never matters and no section sees another's objects. +// prefix filtering, the modification time ListStream reports, overwrite, +// delete, delete-of-missing, and not-found on Get and Stat. Each section +// takes its own fresh backend instance, so the order of sections never +// matters and no section sees another's objects. func runStorerConformance(t *testing.T, newStorer func(*testing.T) storage.Storer) { t.Helper() conformanceRoundTrip(t, newStorer(t)) conformanceOverwrite(t, newStorer(t)) conformanceList(t, newStorer(t)) + conformanceListStreamModTime(t, newStorer(t)) conformanceDelete(t, newStorer(t)) conformanceNotFound(t, newStorer(t)) } @@ -118,6 +121,35 @@ func conformanceList(t *testing.T, s storage.Storer) { } } +// conformanceListStreamModTime checks that ListStream gives an object +// just written a modification time of about now, which prune compares +// with its grace period. +func conformanceListStreamModTime(t *testing.T, s storage.Storer) { + t.Helper() + + ctx := context.Background() + + err := s.Put(ctx, "blobs/dd/written-now", bytes.NewReader([]byte("data"))) + if err != nil { + t.Fatalf("Put: %v", err) + } + + var listed []storage.ObjectInfo + + for info := range s.ListStream(ctx, "blobs/") { + listed = append(listed, info) + } + + if len(listed) != 1 || listed[0].Err != nil { + t.Fatalf("ListStream(\"blobs/\") = %v, want the one object", listed) + } + + if time.Since(listed[0].ModTime).Abs() > time.Minute { + t.Errorf("ListStream ModTime = %v, want within a minute of now", + listed[0].ModTime) + } +} + // conformanceDelete checks that Delete removes an object and that deleting // a missing key is not an error. func conformanceDelete(t *testing.T, s storage.Storer) { diff --git a/internal/storage/file.go b/internal/storage/file.go index af97ef7..734a748 100644 --- a/internal/storage/file.go +++ b/internal/storage/file.go @@ -235,8 +235,9 @@ func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan Objec // Normalize path separators relPath = strings.ReplaceAll(relPath, string(filepath.Separator), "/") ch <- ObjectInfo{ - Key: relPath, - Size: info.Size(), + Key: relPath, + Size: info.Size(), + ModTime: info.ModTime(), } } diff --git a/internal/storage/rclone.go b/internal/storage/rclone.go index 4ca2be1..39413cb 100644 --- a/internal/storage/rclone.go +++ b/internal/storage/rclone.go @@ -53,6 +53,14 @@ func NewRcloneStorer(ctx context.Context, remote, path string) (*RcloneStorer, e rclonePath += path } + // On S3, Swift and some other remotes rclone keeps a time of its own in + // each object's metadata, which costs one request per object to read. + // rclone's use_server_modtime setting makes ModTime the time the + // listing gives instead: when the object was stored, which is what + // prune compares with prune_grace_period. + ctx, ci := fs.AddConfig(ctx) + ci.UseServerModTime = true + // Create the rclone filesystem fsys, err := fs.NewFs(ctx, rclonePath) if err != nil { @@ -211,8 +219,9 @@ func (r *RcloneStorer) ListStream( if prefix == "" || strings.HasPrefix(key, prefix) { ch <- ObjectInfo{ - Key: key, - Size: obj.Size(), + Key: key, + Size: obj.Size(), + ModTime: obj.ModTime(ctx), } } }) diff --git a/internal/storage/rclone_test.go b/internal/storage/rclone_test.go index 1f2d9ee..32ac7a2 100644 --- a/internal/storage/rclone_test.go +++ b/internal/storage/rclone_test.go @@ -5,11 +5,17 @@ import ( "context" "errors" "io" + "net/http" + "net/http/httptest" "os" "path/filepath" "strings" + "sync/atomic" "testing" + "time" + "github.com/johannesboyne/gofakes3" + "github.com/johannesboyne/gofakes3/backend/s3mem" "github.com/rclone/rclone/fs" "github.com/rclone/rclone/fs/config" "github.com/rclone/rclone/fs/config/configmap" @@ -429,3 +435,72 @@ func TestNewRcloneStorerReadsRcloneConfigEnv(t *testing.T) { t.Errorf("object is not in the remote's directory: %v", err) } } + +// TestRcloneListStreamOnS3MakesNoRequestPerObject checks that listing an +// rclone S3 remote takes each object's time from the listing itself. By +// default rclone reads the time it keeps in each object's metadata, one +// request per object, and every command that lists the destination store +// would slow down as it grows. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneListStreamOnS3MakesNoRequestPerObject(t *testing.T) { + backend := s3mem.New() + + err := backend.CreateBucket(s3TestBucket) + if err != nil { + t.Fatalf("create bucket: %v", err) + } + + const body = "blob-bytes" + + _, err = backend.PutObject(s3TestBucket, testBlobKey, nil, + strings.NewReader(body), int64(len(body))) + if err != nil { + t.Fatalf("seed object: %v", err) + } + + var headRequests atomic.Int64 + + fakeS3 := gofakes3.New(backend).Server() + srv := httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + headRequests.Add(1) + } + + fakeS3.ServeHTTP(w, r) + })) + t.Cleanup(srv.Close) + + remote := ":s3,provider=Other" + + ",access_key_id=" + s3TestAccessKeyID + + ",secret_access_key=" + s3TestSecretAccessKey + + ",endpoint='" + srv.URL + "'" + ctx := context.Background() + + s, err := storage.NewRcloneStorer(ctx, remote, s3TestBucket) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + headRequests.Store(0) + + var listed []storage.ObjectInfo + + for info := range s.ListStream(ctx, "blobs/") { + listed = append(listed, info) + } + + if len(listed) != 1 || listed[0].Err != nil { + t.Fatalf("ListStream(\"blobs/\") = %v, want the one object", listed) + } + + if time.Since(listed[0].ModTime).Abs() > time.Minute { + t.Errorf("ListStream ModTime = %v, want within a minute of now", + listed[0].ModTime) + } + + if n := headRequests.Load(); n != 0 { + t.Errorf("ListStream made %d HEAD request(s), want none", n) + } +} diff --git a/internal/storage/s3.go b/internal/storage/s3.go index 4f2b53b..bbe133b 100644 --- a/internal/storage/s3.go +++ b/internal/storage/s3.go @@ -89,9 +89,10 @@ func (s *S3Storer) ListStream(ctx context.Context, prefix string) <-chan ObjectI for info := range s.client.ListObjectsStream(ctx, prefix, false) { ch <- ObjectInfo{ - Key: info.Key, - Size: info.Size, - Err: info.Err, + Key: info.Key, + Size: info.Size, + ModTime: info.ModTime, + Err: info.Err, } } }() diff --git a/internal/storage/storer.go b/internal/storage/storer.go index 85081f3..3417cb7 100644 --- a/internal/storage/storer.go +++ b/internal/storage/storer.go @@ -14,6 +14,7 @@ import ( "context" "errors" "io" + "time" ) // ErrNotFound is returned when an object does not exist. @@ -27,7 +28,10 @@ type ProgressCallback func(bytesTransferred int64) error type ObjectInfo struct { Key string // Object key/path Size int64 // Size in bytes - Err error // Error for streaming results (nil on success) + // ModTime is when the object was written, as the store reports it. + // Only ListStream sets it; Stat leaves it zero. + ModTime time.Time + Err error // Error for streaming results (nil on success) } // Info provides human-readable storage configuration. @@ -67,7 +71,8 @@ type Storer interface { // For large result sets, prefer ListStream. List(ctx context.Context, prefix string) ([]string, error) - // ListStream returns a channel of ObjectInfo for large result sets. + // ListStream returns a channel of ObjectInfo, with each object's key, + // size and modification time, for large result sets. // The channel is closed when listing completes. // If an error occurs during listing, the final item will have Err set. ListStream(ctx context.Context, prefix string) <-chan ObjectInfo diff --git a/internal/vaultik/info.go b/internal/vaultik/info.go index 64656d8..9cd034f 100644 --- a/internal/vaultik/info.go +++ b/internal/vaultik/info.go @@ -457,9 +457,9 @@ func (v *Vaultik) scanRemoteBlobStorage( return err } - for _, size := range allBlobs { + for _, blob := range allBlobs { result.TotalBlobCount++ - result.TotalBlobSize += size + result.TotalBlobSize += blob.Size } // A blob named only by a manifest that could not be read, or by one @@ -474,10 +474,10 @@ func (v *Vaultik) scanRemoteBlobStorage( orphanedSize int64 ) - for hash, size := range allBlobs { + for hash, blob := range allBlobs { if _, referenced := referencedBlobs[hash]; !referenced { orphanedCount++ - orphanedSize += size + orphanedSize += blob.Size } } diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index b7148e9..56619d7 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -5,8 +5,10 @@ import ( "errors" "fmt" "strings" + "time" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" ) // PruneOptions contains options for the prune command @@ -163,6 +165,10 @@ type PruneBlobsResult struct { BlobsDeleted int `json:"blobs_deleted"` BlobsFailed int `json:"blobs_failed,omitempty"` BytesFreed int64 `json:"bytes_freed"` + // BlobsTooNew counts the unreferenced blobs kept because they are + // newer than the prune grace period, or of unknown age. BlobsFound + // does not include them. + BlobsTooNew int `json:"blobs_too_new"` } // Prune removes orphaned data from the local index database AND @@ -208,9 +214,15 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { return err } - unreferencedBlobs, totalSize := v.findUnreferencedBlobs(allBlobs, allBlobsReferenced) + unreferencedBlobs, totalSize, tooNew := v.findUnreferencedBlobs( + allBlobs, allBlobsReferenced) - result := &PruneBlobsResult{BlobsFound: len(unreferencedBlobs)} + result := &PruneBlobsResult{ + BlobsFound: len(unreferencedBlobs), + BlobsTooNew: tooNew, + } + + v.reportBlobsTooNew(tooNew, opts) if len(unreferencedBlobs) == 0 { log.Info("No unreferenced blobs found") @@ -344,11 +356,12 @@ func (v *Vaultik) listUniqueSnapshotIDs() ([]string, error) { return snapshotIDs, nil } -// listAllRemoteBlobs returns a map of all blob hashes to their sizes in remote storage -func (v *Vaultik) listAllRemoteBlobs() (map[string]int64, error) { +// listAllRemoteBlobs returns a map of all blob hashes in remote storage +// to their listing entries. +func (v *Vaultik) listAllRemoteBlobs() (map[string]storage.ObjectInfo, error) { log.Info("Listing all blobs in storage") - allBlobs := make(map[string]int64) + allBlobs := make(map[string]storage.ObjectInfo) blobObjectCh := v.Storage.ListStream(v.ctx, "blobs/") for object := range blobObjectCh { @@ -372,7 +385,7 @@ func (v *Vaultik) listAllRemoteBlobs() (map[string]int64, error) { continue } - allBlobs[parts[3]] = object.Size + allBlobs[parts[3]] = object } log.Info("Found blobs in storage", "count", len(allBlobs)) @@ -380,30 +393,59 @@ func (v *Vaultik) listAllRemoteBlobs() (map[string]int64, error) { return allBlobs, nil } -// findUnreferencedBlobs returns blob hashes not referenced by any -// manifest and their total size. +// findUnreferencedBlobs returns the hashes of the blobs no manifest +// references that are older than the prune grace period, and their total +// size. It also returns how many unreferenced blobs it left out for +// being newer than that, or of unknown age because the listing gave no +// time for them. func (v *Vaultik) findUnreferencedBlobs( - allBlobs map[string]int64, referenced map[string]bool, -) ([]string, int64) { + allBlobs map[string]storage.ObjectInfo, referenced map[string]bool, +) ([]string, int64, int) { var ( unreferenced []string totalSize int64 + tooNew int ) - for hash, size := range allBlobs { - if !referenced[hash] { - unreferenced = append(unreferenced, hash) - totalSize += size + cutoff := time.Now().UTC().Add(-v.Config.PruneGracePeriod) + + for hash, blob := range allBlobs { + if referenced[hash] { + continue } + + if blob.ModTime.IsZero() || blob.ModTime.After(cutoff) { + tooNew++ + + continue + } + + unreferenced = append(unreferenced, hash) + totalSize += blob.Size } - return unreferenced, totalSize + return unreferenced, totalSize, tooNew +} + +// reportBlobsTooNew says how many unreferenced blobs prune kept for being +// newer than the grace period or of unknown age. Under --json the +// document carries the count instead. +func (v *Vaultik) reportBlobsTooNew(tooNew int, opts *PruneOptions) { + if tooNew == 0 || opts.JSON { + return + } + + v.UI.Infof("Kept %d unreferenced blob(s) newer than "+ + "prune_grace_period (%s), or of unknown age: a backup still "+ + "running may need them.", + tooNew, v.Config.PruneGracePeriod) } // deleteUnreferencedBlobs deletes the given blobs from storage and // populates the result. func (v *Vaultik) deleteUnreferencedBlobs( - unreferencedBlobs []string, allBlobs map[string]int64, result *PruneBlobsResult, + unreferencedBlobs []string, allBlobs map[string]storage.ObjectInfo, + result *PruneBlobsResult, ) { log.Info("Deleting unreferenced blobs") @@ -418,7 +460,7 @@ func (v *Vaultik) deleteUnreferencedBlobs( } result.BlobsDeleted++ - result.BytesFreed += allBlobs[hash] + result.BytesFreed += allBlobs[hash].Size if (i+1)%progressLogEvery == 0 || i == len(unreferencedBlobs)-1 { log.Info("Deletion progress", diff --git a/internal/vaultik/prune_grace_period_test.go b/internal/vaultik/prune_grace_period_test.go new file mode 100644 index 0000000..e5004bf --- /dev/null +++ b/internal/vaultik/prune_grace_period_test.go @@ -0,0 +1,166 @@ +package vaultik_test + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestPruneDuringBackupKeepsItsBlobs runs a prune from another host +// sharing the destination store at the moment a backup has uploaded its +// blobs but not yet its manifest, so no manifest lists those blobs. The +// prune must leave them, and the backup must then restore. +func TestPruneDuringBackupKeepsItsBlobs(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := t.TempDir() + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + cfg := faultTestConfig() + testFiles := writeFaultSourceTree(t, fs, dataDir) + + inner, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + otherHostCfg := faultTestConfig() + otherHostCfg.PruneGracePeriod = time.Hour + otherHost := newReaderVaultik(ctx, otherHostCfg, inner, nil, fs) + + var ( + pruned bool + pruneErr error + ) + + store := faultstore.New(inner) + store.OnPut = func(key string) faultstore.PutAction { + if strings.HasSuffix(key, "/manifest.json.zst") { + pruned = true + pruneErr = otherHost.PruneBlobs(&vaultik.PruneOptions{Force: true}) + } + + return faultstore.PutNormal + } + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + + id := fullFaultBackup(ctx, t, fs, store, cfg, repos, dataDir, dbPath, "shared") + require.NoError(t, db.Close()) + + require.True(t, pruned, "the prune must run before the manifest upload") + require.NoError(t, pruneErr) + + v := newReaderVaultik(ctx, cfg, inner, nil, fs) + require.NoError(t, v.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Verify: true, + }), "a prune during the backup must not delete the backup's blobs") + + assertRestoredTree(t, fs, restoreDir, testFiles) +} + +// TestPruneKeepsUnreferencedBlobWithNoTime checks that a blob no +// manifest lists, whose listing gives no modification time (as an S3 +// listing entry without LastModified does), is kept and counted with +// the blobs too new to delete: its age is unknown. +func TestPruneKeepsUnreferencedBlobWithNoTime(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + // Written into the mock store's map directly rather than through + // Put, so its listing gives no time. + blobKey := "blobs/" + testBlobHashA[:2] + "/" + testBlobHashA[2:4] + + "/" + testBlobHashA + env.store.data[blobKey] = []byte("blob") + + require.NoError(t, env.v.PruneBlobs(&vaultik.PruneOptions{JSON: true})) + + assert.True(t, env.store.hasKey(blobKey), + "a blob of unknown age must be kept") + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &result)) + assert.Equal(t, 0, result.BlobsDeleted) + assert.Equal(t, 1, result.BlobsTooNew) +} + +// TestPruneDeletesUnreferencedBlobOlderThanGracePeriod checks that the +// grace period only delays deletion: a blob no manifest lists is deleted +// once it is older than the grace period, and kept and counted until +// then. +func TestPruneDeletesUnreferencedBlobOlderThanGracePeriod(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := t.TempDir() + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + oldKey := "blobs/" + testBlobHashA[:2] + "/" + testBlobHashA[2:4] + + "/" + testBlobHashA + newKey := "blobs/" + testBlobHashB[:2] + "/" + testBlobHashB[2:4] + + "/" + testBlobHashB + + for _, key := range []string{oldKey, newKey} { + require.NoError(t, store.Put(ctx, key, strings.NewReader("blob"))) + } + + gracePeriod := time.Hour + beforeGracePeriod := time.Now().Add(-gracePeriod - time.Minute) + require.NoError(t, os.Chtimes(filepath.Join(storeDir, oldKey), + beforeGracePeriod, beforeGracePeriod)) + + stdout := &bytes.Buffer{} + v := &vaultik.Vaultik{ + Config: &config.Config{PruneGracePeriod: gracePeriod}, + Storage: store, + Stdout: stdout, + UI: ui.NewWithColor(stdout, false), + } + v.SetContext(ctx) + + require.NoError(t, v.PruneBlobs(&vaultik.PruneOptions{JSON: true})) + + _, err = store.Stat(ctx, oldKey) + require.ErrorIs(t, err, storage.ErrNotFound, + "a blob older than the grace period must be deleted") + + _, err = store.Stat(ctx, newKey) + require.NoError(t, err, "a blob newer than the grace period must be kept") + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(stdout.Bytes(), &result)) + assert.Equal(t, 1, result.BlobsDeleted) + assert.Equal(t, 1, result.BlobsTooNew) +} diff --git a/internal/vaultik/remove_snapshot_test.go b/internal/vaultik/remove_snapshot_test.go index c9cc7fe..9d43aec 100644 --- a/internal/vaultik/remove_snapshot_test.go +++ b/internal/vaultik/remove_snapshot_test.go @@ -26,11 +26,14 @@ import ( type testStorer struct { mu sync.Mutex data map[string][]byte + // putTimes holds when Put stored each object; ListStream reports it. + putTimes map[string]time.Time } func newTestStorer() *testStorer { return &testStorer{ - data: make(map[string][]byte), + data: make(map[string][]byte), + putTimes: make(map[string]time.Time), } } @@ -44,6 +47,7 @@ func (s *testStorer) Put(_ context.Context, key string, reader io.Reader) error } s.data[key] = data + s.putTimes[key] = time.Now().UTC() return nil } @@ -87,6 +91,7 @@ func (s *testStorer) Delete(_ context.Context, key string) error { defer s.mu.Unlock() delete(s.data, key) + delete(s.putTimes, key) return nil } @@ -120,8 +125,9 @@ func (s *testStorer) ListStream( for key, data := range s.data { if prefix == "" || strings.HasPrefix(key, prefix) { ch <- storage.ObjectInfo{ - Key: key, - Size: int64(len(data)), + Key: key, + Size: int64(len(data)), + ModTime: s.putTimes[key], } } } From 850e2de25a032f11cb5fd7eac5033ff0b84b617c Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 15 Oct 2026 02:02:35 +0200 Subject: [PATCH 093/121] Go on with a backup when the destination marker cannot be checked (closes #389) A source host whose credentials allow only PUT, which the documents say is enough to back up, failed every backup after its first: the marker check looks the marker up with an S3 HEAD, which those credentials are refused, and any error other than not found was fatal. Such an error now means the check could not be made: it is logged at info level, so --cron stays silent, and the command goes on. Not found still stops it. The documents now say so, and that such a host does not notice an emptied destination, so vaultik database delete must be run on it after the destination is emptied. The fault-injecting test store gains a Stat hook for the test. Model: opus-5-5 --- ARCHITECTURE.md | 25 +++++++----- README.md | 45 ++++++++++++--------- docs/REPOSTRUCTURE.md | 4 +- internal/cli/entry_prune_json_test.go | 2 +- internal/cli/entry_snapshot_purge_test.go | 2 +- internal/storage/faultstore/faultstore.go | 31 ++++++++++---- internal/vaultik/destination_marker.go | 33 ++++++++++----- internal/vaultik/destination_marker_test.go | 40 ++++++++++++++++-- internal/vaultik/prune.go | 4 +- 9 files changed, 132 insertions(+), 54 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index d716e16..b41dc22 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -312,7 +312,7 @@ Repository interfaces: ``` CreateSnapshot(opts) │ - ├─► markDestination() // Refuse a destination without the marker, then write it + ├─► markDestination() // Check the marker (see Storage Layout in S3), then write it │ ├─► PruneDatabase() // Critical: avoid dedup errors │ @@ -382,15 +382,20 @@ bucket/ └── manifest.json.zst # Blob list (for pruning/verification) ``` -A destination without `vaultik-destination.txt` is treated as not present -while the local index holds snapshots stored there (`checkDestinationMarker` -in `internal/vaultik/destination_marker.go`): `snapshot create` refuses to -write to it, `prune`, `snapshot purge` and `remote nuke` fail, and -`snapshot list` and `snapshot remove` behave as for a destination that cannot -be listed. This keeps those commands from taking an unplugged volume's empty -mount point for a destination whose snapshots are all gone. The `file://` -backend never creates its destination directory, so a write to a missing one -fails. +A destination that answers a look-up of `vaultik-destination.txt` with not +found is treated as not present while the local index holds snapshots stored +there (`checkDestinationMarker` in `internal/vaultik/destination_marker.go`): +`snapshot create` refuses to write to it, `prune`, `snapshot purge` and +`remote nuke` fail, and `snapshot list` and `snapshot remove` behave as for a +destination that cannot be listed. This keeps those commands from taking an +unplugged volume's empty mount point for a destination whose snapshots are +all gone. When the look-up fails for any reason other than not found, for +example when S3 refuses it to credentials that allow only PUT, the check is +skipped, so a host with such credentials does not notice an emptied +destination; see +[docs/REPOSTRUCTURE.md](docs/REPOSTRUCTURE.md#marker-file-vaultik-destinationtxt). +The `file://` backend never creates its destination directory, so a write to a +missing one fails. The `{remote-key}` directory name is a one-way double SHA-256 hash of the human snapshot ID, so the human ID (hostname, snapshot name, timestamp) is never diff --git a/README.md b/README.md index 14a7bb1..381e26c 100644 --- a/README.md +++ b/README.md @@ -332,7 +332,9 @@ value where a list belongs or a word where a number belongs), is refused. command fails before the backup starts. * Fails before it writes anything when a `file://` destination directory does not exist, or when the local index holds snapshots and the - destination has no `vaultik-destination.txt` (see + destination answers that it has no `vaultik-destination.txt`. When that + look-up fails for any reason other than not found, for example when S3 + refuses it to credentials that allow only PUT, the check is skipped (see [remote storage layout](#remote-storage-layout)) **`snapshot list`**: Show every snapshot known to this host — the union @@ -368,9 +370,9 @@ gives: revert the configuration, or run `vaultik database delete`. If the destination store cannot be listed (unmounted volume, permission denied, network down), the command warns, falls back to the local index alone, and still exits zero. It does the same when the -destination has no `vaultik-destination.txt` while the local index -holds snapshots stored there, as when a volume mounted at the -destination is unplugged and leaves its empty mount point behind. +destination answers that it has no `vaultik-destination.txt` while the +local index holds snapshots stored there, as when a volume mounted at +the destination is unplugged and leaves its empty mount point behind. * `--json`: Output in JSON format. Each entry carries `locally_tracked` (whether the snapshot is in the local index), `remote_key` (the full 64-character storage key), and `remote_present` (whether it was seen @@ -413,8 +415,8 @@ with `--local-only`, the snapshot must be in the local index. Local row cleanup (files, chunks, blobs the snapshot was the last referrer for) runs automatically. If removing the snapshot's metadata from the destination store fails (for example because the store is unreachable, -or the local index holds snapshots and the destination has no -`vaultik-destination.txt`), the local-DB removal still completes and a +or the local index holds snapshots and the destination answers that it +has no `vaultik-destination.txt`), the local-DB removal still completes and a warning is emitted; run `vaultik snapshot remove ` again once the store is reachable to remove the snapshot's metadata from it (`vaultik prune` does not). For a snapshot that is only on the @@ -457,9 +459,9 @@ be deleted. Step (3) reads all remote manifests — network cost scales with the number of snapshots. `snapshot create --prune` runs the same cleanup automatically; this is the manual entry point for the same work. If the destination store cannot -be listed, or the local index holds snapshots and the destination has -no `vaultik-destination.txt` (an unplugged volume's empty mount point), -prune fails and deletes nothing. `snapshot purge` does the same. If a +be listed, or the local index holds snapshots and the destination answers +that it has no `vaultik-destination.txt` (an unplugged volume's empty mount +point), prune fails and deletes nothing. `snapshot purge` does the same. If a blob cannot be deleted, the command (and `snapshot create --prune`) exits non-zero. * `--force`: Skip confirmation prompt @@ -494,8 +496,8 @@ and irreversible. This is the single supported way to wipe the entire destination store. A snapshot is removed from the local index only once its metadata is deleted from the destination store. If the destination store cannot be listed, or the local index holds snapshots and the -destination has no `vaultik-destination.txt` (an unplugged volume's -empty mount point), the command fails before it removes anything. If a +destination answers that it has no `vaultik-destination.txt` (an unplugged +volume's empty mount point), the command fails before it removes anything. If a listing afterwards still finds anything under `metadata/` or `blobs/`, the command names each object left and exits non-zero; running it again deletes what is left. @@ -577,15 +579,22 @@ For an implementation-level view of the internals — the data model, the ``` * `vaultik-destination.txt` holds one fixed line of text, with no host - name, path or time. A destination without it is treated as not - present while the local index holds snapshots stored there: - `snapshot create` refuses to write to it, `prune`, `snapshot purge` - and `remote nuke` fail, and `snapshot list` and `snapshot remove` - behave as for a destination that cannot be listed. This keeps an - unplugged volume's empty mount point from being taken for a - destination whose snapshots are all gone. Mount + name, path or time. While the local index holds snapshots stored + there, a destination that answers a look-up of it with not found is + treated as not present: `snapshot create` refuses to write to it, + `prune`, `snapshot purge` and `remote nuke` fail, and `snapshot list` + and `snapshot remove` behave as for a destination that cannot be + listed. This keeps an unplugged volume's empty mount point from being + taken for a destination whose snapshots are all gone. Mount the volume if it is removable; if the destination was emptied on purpose, run `vaultik database delete` and back up again. + When the look-up fails for any reason other than not found, the check + is skipped and the command goes on. S3 refuses it on every run to + credentials that allow only PUT, so a host with such credentials does + not notice a destination emptied since its last backup, and its next + backup would leave out the data its local index records as already + stored. After the destination is emptied, run + `vaultik database delete` on such a host before it backs up again. * Blobs are two-level directory sharded using the first 4 hex chars of the blob hash * `db.zst.age` is a binary SQLite database (zstd compressed, age encrypted) containing all file metadata, chunk mappings, and relationships for the snapshot diff --git a/docs/REPOSTRUCTURE.md b/docs/REPOSTRUCTURE.md index b7c6946..0768c9d 100644 --- a/docs/REPOSTRUCTURE.md +++ b/docs/REPOSTRUCTURE.md @@ -27,7 +27,9 @@ The metadata subdirectory is named with the **remote key**, a one-way hash of th ## Marker File (`vaultik-destination.txt`) -Every backup writes this file at the root before it uploads anything. It holds one fixed line of plain text and names no host, path or time. A destination without it is treated as not present while the local index holds snapshots stored there: `snapshot create` refuses to write to it, and `prune`, `snapshot purge`, `snapshot remove`, `snapshot list` and `remote nuke` behave as for a destination that cannot be listed. An unplugged volume leaves an empty directory at its mount point, and without the marker that directory would read as a destination whose snapshots are all gone. `remote nuke` deletes the marker last. +Every backup writes this file at the root before it uploads anything. It holds one fixed line of plain text and names no host, path or time. While the local index holds snapshots stored there, a destination that answers a look-up of the marker with not found is treated as not present: `snapshot create` refuses to write to it, and `prune`, `snapshot purge`, `snapshot remove`, `snapshot list` and `remote nuke` behave as for a destination that cannot be listed. An unplugged volume leaves an empty directory at its mount point, and without the marker that directory would read as a destination whose snapshots are all gone. `remote nuke` deletes the marker last. + +When the look-up of the marker fails for any reason other than not found, the check is skipped and the command goes on. S3 refuses it on every run to credentials that allow only PUT, so a host with such credentials does not notice a destination emptied since its last backup, and its next backup would leave out the data its local index records as already stored. After the destination is emptied, run `vaultik database delete` on such a host before it backs up again. ## Blobs Directory (`blobs/`) diff --git a/internal/cli/entry_prune_json_test.go b/internal/cli/entry_prune_json_test.go index a326535..3f43226 100644 --- a/internal/cli/entry_prune_json_test.go +++ b/internal/cli/entry_prune_json_test.go @@ -134,7 +134,7 @@ func writeHermeticPruneConfig(t *testing.T, seedStale bool) string { seedStaleSnapshotRecord(t, indexPath) // While the local index holds a snapshot, prune fails on a - // destination without the marker a backup writes. + // destination that answers that it has no marker. require.NoError(t, os.WriteFile( filepath.Join(storeDir, "vaultik-destination.txt"), nil, 0o600)) } diff --git a/internal/cli/entry_snapshot_purge_test.go b/internal/cli/entry_snapshot_purge_test.go index 3f7b8c8..3e3c32c 100644 --- a/internal/cli/entry_snapshot_purge_test.go +++ b/internal/cli/entry_snapshot_purge_test.go @@ -42,7 +42,7 @@ func TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails(t *testing.T) seedStaleSnapshotRecord(t, indexPath) // While the local index holds a snapshot, purge fails on a - // destination without the marker a backup writes. + // destination that answers that it has no marker. require.NoError(t, os.WriteFile( filepath.Join(dir, "store", "vaultik-destination.txt"), nil, 0o600)) diff --git a/internal/storage/faultstore/faultstore.go b/internal/storage/faultstore/faultstore.go index bdc4dc3..10afb4f 100644 --- a/internal/storage/faultstore/faultstore.go +++ b/internal/storage/faultstore/faultstore.go @@ -2,15 +2,17 @@ // faults on demand, so tests can reproduce the failure modes a real // backend exhibits: an upload that fails partway, a backend that reports // success while storing nothing, reads that return corrupt or truncated -// bytes, and a delete the backend refuses. It is the seam called for by -// the fault-injection tests (sneak/vaultik issue 72) and is meant to be -// reused by future tests rather than re-implemented per case. +// bytes, and a delete or a stat the backend refuses. It is the seam +// called for by the fault-injection tests (sneak/vaultik issue 72) and +// is meant to be reused by future tests rather than re-implemented per +// case. // -// The wrapper delegates every method to the inner Storer. Three hooks +// The wrapper delegates every method to the inner Storer. Four hooks // change that: OnPut decides the fate of each write, OnGet decides how -// each read's bytes are returned, and OnDelete decides whether each -// delete fails. All are keyed by the object key, so a test can fault -// only blobs, only metadata, or a single object. +// each read's bytes are returned, OnDelete decides whether each delete +// fails, and OnStat whether each stat fails. All are keyed by the object +// key, so a test can fault only blobs, only metadata, or a single +// object. package faultstore import ( @@ -30,6 +32,11 @@ var ErrInjectedUpload = errors.New("faultstore: injected upload failure") // fail. var ErrInjectedDelete = errors.New("faultstore: injected delete failure") +// ErrInjectedStat is returned by a Stat the OnStat hook chose to fail. +// It is not storage.ErrNotFound: the backend refused the request, as S3 +// refuses a HEAD to credentials that allow only PUT. +var ErrInjectedStat = errors.New("faultstore: injected stat failure") + // PutAction is the disposition OnPut assigns to a write. type PutAction int @@ -76,6 +83,10 @@ type Storer struct { // object key. Returning true fails the delete and leaves the object // in place. OnDelete func(key string) bool + + // OnStat, when set, is consulted before every Stat with the object + // key. Returning true fails the stat with ErrInjectedStat. + OnStat func(key string) bool } // New wraps inner. inner must be non-nil. @@ -159,8 +170,12 @@ func damage(fault GetFault, data []byte) []byte { return out } -// Stat delegates unchanged. +// Stat returns the object's info unless OnStat fails the stat. func (f *Storer) Stat(ctx context.Context, key string) (*storage.ObjectInfo, error) { + if f.OnStat != nil && f.OnStat(key) { + return nil, fmt.Errorf("%w for %q", ErrInjectedStat, key) + } + return f.inner.Stat(ctx, key) } diff --git a/internal/vaultik/destination_marker.go b/internal/vaultik/destination_marker.go index 7ce437d..af28fcf 100644 --- a/internal/vaultik/destination_marker.go +++ b/internal/vaultik/destination_marker.go @@ -5,14 +5,16 @@ import ( "fmt" "strings" + "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/storage" ) // destinationMarkerKey is the object every backup writes at the root of // the backup destination store. While the local index holds a snapshot -// stored there, a destination without it is treated as not present: an -// unplugged volume leaves an empty directory at its mount point, which -// would otherwise read as a store whose snapshots are all gone. +// stored there, a destination that answers a look-up of it with not +// found is treated as not present: an unplugged volume leaves an empty +// directory at its mount point, which would otherwise read as a store +// whose snapshots are all gone. const destinationMarkerKey = "vaultik-destination.txt" // destinationMarkerText is the whole content of the marker. It names no @@ -20,16 +22,24 @@ const destinationMarkerKey = "vaultik-destination.txt" const destinationMarkerText = "This is a vaultik backup destination store.\n" // errDestinationNotPresent is returned when the local index holds a -// snapshot stored on the backup destination store and the store has no -// marker. +// snapshot stored on the backup destination store and the store answers +// that it has no marker. var errDestinationNotPresent = errors.New("backup destination store is not present") // checkDestinationMarker returns errDestinationNotPresent when the local // index holds a snapshot stored on the backup destination store and the -// store has no marker. With no snapshot in the local index, as on a -// first backup or on another machine, there is nothing to check; nor -// when the local index is bound to a different destination than the -// configured one, since its snapshots are stored there. +// store answers that it has no marker. With no snapshot in the local +// index, as on a first backup or on another machine, there is nothing to +// check; nor when the local index is bound to a different destination +// than the configured one, since its snapshots are stored there. +// +// A look-up of the marker that fails for any other reason than not +// found is logged and otherwise ignored, because the check could not be +// made: S3 refuses it to credentials that allow only PUT, which is all +// a backup needs. The check exists for a file:// volume's empty mount +// point, which always answers not found, and a destination that cannot +// be reached fails on the next request made to it, such as the backup's +// PUT of the marker. func (v *Vaultik) checkDestinationMarker() error { ids, err := v.localSnapshotIDs() if err != nil { @@ -63,8 +73,11 @@ func (v *Vaultik) checkDestinationMarker() error { destinationMarkerKey) } + // Info, not a warning: --cron must stay silent on a successful + // backup from a host whose credentials allow only PUT. if err != nil { - return fmt.Errorf("checking for %s: %w", destinationMarkerKey, err) + log.Info("Could not check the backup destination store for its marker", + "key", destinationMarkerKey, "error", err) } return nil diff --git a/internal/vaultik/destination_marker_test.go b/internal/vaultik/destination_marker_test.go index 08cb35b..0166a76 100644 --- a/internal/vaultik/destination_marker_test.go +++ b/internal/vaultik/destination_marker_test.go @@ -13,15 +13,16 @@ import ( "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" "sneak.berlin/go/vaultik/internal/vaultik" ) // These tests cover https://git.eeqj.de/sneak/vaultik/issues/239: a // file:// destination at a volume's mount point leaves an empty directory // behind when the volume is unplugged. While the local index holds -// snapshots, a destination without vaultik-destination.txt is not present, -// so no command may write to it or conclude from it that the local -// snapshots are gone. +// snapshots, a destination that answers that it has no +// vaultik-destination.txt is not present, so no command may write to it +// or conclude from it that the local snapshots are gone. // markerFile is the name of the file a backup writes at the root of the // destination. @@ -93,6 +94,39 @@ func TestBackupRefusesDestinationWithoutMarker(t *testing.T) { assertUntouched(ctx, t, repos, storeDir) } +// TestBackupGoesOnWhenMarkerCannotBeChecked checks that a backup goes on +// and writes the marker when looking it up fails with an error other +// than not found, as S3 answers credentials that allow only PUT +// (https://git.eeqj.de/sneak/vaultik/issues/389), and that a marker +// that is not found still stops it. +func TestBackupGoesOnWhenMarkerCannotBeChecked(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := t.TempDir() + v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + + // Removed so the test sees the backup write it again: with the + // look-up failing, the backup cannot tell that it is gone. + markerPath := filepath.Join(storeDir, markerFile) + require.NoError(t, os.Remove(markerPath)) + + store := faultstore.New(v.Storage) + store.OnStat = func(key string) bool { return key == markerFile } + v.Storage = store + + require.NoError(t, backUp(v, "second")) + localSnapshotID(ctx, t, repos, "second") + assert.FileExists(t, markerPath) + + require.NoError(t, os.Remove(markerPath)) + + store.OnStat = nil + + require.ErrorContains(t, backUp(v, "third"), markerFile) +} + // TestBackupChecksMarkerBeforeDroppingIncompleteSnapshots checks that // snapshot create writes nothing when the local index holds only an // incomplete snapshot and the destination has no marker. The backup drops diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index 56619d7..de75d9b 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -58,8 +58,8 @@ func (v *Vaultik) NukeRemote(force bool) error { // Checked before anything is deleted: running nuke again would fail // the same way, so the advice below must not follow these errors. - // The listing also fails on a destination without the marker while - // the local index holds snapshots. + // The listing also fails on a destination that answers that it has + // no marker while the local index holds snapshots. err := v.EnsureStorageBinding() if err != nil { return err From e9b17cc5fdcb12f11289768006b1c38c97aacac9 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 15 Oct 2026 02:49:21 +0200 Subject: [PATCH 094/121] Do not prune after a backup that found a configured path empty (closes #388) snapshot create --prune of a snapshot whose path was an empty directory, as the mount point of a volume that is not mounted is, recorded an empty snapshot and then purged the older snapshots that held the data, with their blobs. The scan now counts the entries it finds in each configured path. Under --prune, a run in which a path of a snapshot it made held nothing skips the prune, keeps every older snapshot, names each such path with its snapshot, and exits non-zero, as https://git.eeqj.de/sneak/vaultik/issues/382 does for unreadable files. Only the current run is looked at. Without --prune this check does nothing. A configured path that is a symlink whose target is gone now fails every run, with or without --prune. Model: opus-5-5 --- README.md | 10 +- TODO.md | 8 + .../cli/entry_snapshot_create_prune_test.go | 30 +++ internal/cli/snapshot.go | 8 +- internal/snapshot/scanner.go | 49 +++- internal/vaultik/snapshot.go | 126 +++++++--- internal/vaultik/snapshot_prune_test.go | 234 ++++++++++++++++++ 7 files changed, 418 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 381e26c..4e60953 100644 --- a/README.md +++ b/README.md @@ -325,7 +325,13 @@ value where a list belongs or a word where a number belongs), is refused. `--skip-errors` skipped a file or directory it could not read or list, the prune does not run and every older snapshot is kept, since one of them may be the only one that holds what was skipped; the command says so and exits - non-zero. A file removed during the backup does not stop the prune. + non-zero. When the backup found nothing in a configured path, as in the + mount point of a volume that is not mounted, the prune does not run + either: every older snapshot is kept, and the command names the path and + exits non-zero, on every run until the path holds something again. Take a + path that is empty on purpose out of the config, or remove the older + snapshots by hand with `snapshot purge`. A file removed during the backup + does not stop the prune. * `--keep-newer-than `: With `--prune`, keep snapshots newer than this duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`). Without `--prune`, or with a value that is not a valid duration, the @@ -336,6 +342,8 @@ value where a list belongs or a word where a number belongs), is refused. look-up fails for any reason other than not found, for example when S3 refuses it to credentials that allow only PUT, the check is skipped (see [remote storage layout](#remote-storage-layout)) +* Fails, before anything is pruned, when a configured path is a symlink + whose target does not exist, as one into a volume that is not mounted **`snapshot list`**: Show every snapshot known to this host — the union of the local index and the backup destination store — with timestamps diff --git a/TODO.md b/TODO.md index 70ba387..6c73004 100644 --- a/TODO.md +++ b/TODO.md @@ -24,6 +24,14 @@ owner's; a `v*` tag runs the release build in # Completed Steps +- 2026-10-14: Stopped `snapshot create --prune` pruning after a backup + that found nothing in a configured path + ([issue #388](https://git.eeqj.de/sneak/vaultik/issues/388)), as in + the mount point of a volume that is not mounted. Such a prune could + delete every snapshot still holding that path's files. A configured + path that is a symlink whose target is gone, as one into such a + volume, now fails the backup, with or without `--prune`. + - 2026-10-14: Stopped `snapshot create --prune` pruning after a backup that skipped files it could not read ([issue #382](https://git.eeqj.de/sneak/vaultik/issues/382)). Such a diff --git a/internal/cli/entry_snapshot_create_prune_test.go b/internal/cli/entry_snapshot_create_prune_test.go index 2a7b229..c6b9597 100644 --- a/internal/cli/entry_snapshot_create_prune_test.go +++ b/internal/cli/entry_snapshot_create_prune_test.go @@ -87,6 +87,36 @@ func TestEntrySnapshotCreateReportsPostBackupPruneFailure(t *testing.T) { "the new snapshot is on the store beside the planted one") } +// TestEntrySnapshotCreatePruneExitsNonZeroWhenSourceIsEmpty backs up, +// empties the source directory, as a volume that is not mounted leaves +// its mount point, and runs `snapshot create --prune`. The command exits +// non-zero and reports the backup as completed, not as a failed snapshot +// creation. See https://git.eeqj.de/sneak/vaultik/issues/388. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreatePruneExitsNonZeroWhenSourceIsEmpty(t *testing.T) { + configPath, storeDir := writeBackupConfig(t) + + code, _, _ := runEntry(t, flagConfig, configPath, cmdSnapshot, cmdCreate) + require.Equal(t, 0, code) + + // writeBackupConfig puts the source directory beside the config file. + require.NoError(t, os.Remove( + filepath.Join(filepath.Dir(configPath), "source", "file.txt"))) + + code, _, stderr := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate, flagPrune) + + assert.Equal(t, 1, code) + assert.Contains(t, stderr, + "Backup completed, but 1 source path(s) were empty") + assert.NotContains(t, stderr, "Snapshot creation failed") + + snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata")) + require.NoError(t, err) + assert.Len(t, snapshots, 2, "the older snapshot is kept") +} + // writeBackupConfig builds a hermetic config with one small file in its // source directory and an empty destination store directory. Returns the // config path and the store directory. diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index efb176b..4958c62 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -115,8 +115,9 @@ on Linux), then /etc/vaultik/config.yml.`, return } - if errors.Is(err, vaultik.ErrFilesUnreadable) { - log.Error("Backup completed with unreadable files", "error", err) + if errors.Is(err, vaultik.ErrFilesUnreadable) || + errors.Is(err, vaultik.ErrSourcePathEmpty) { + log.Error("Backup completed with an error", "error", err) ReportErrorf("Backup completed, but %v", err) return @@ -133,7 +134,8 @@ on Linux), then /etc/vaultik/config.yml.`, cmd.Flags().BoolVar(&opts.Prune, "prune", false, "After backup, drop older snapshots of the same name and remove "+ "orphaned blobs older than prune_grace_period (not after a "+ - "backup that skipped unreadable files)") + "backup that skipped unreadable files or found a configured "+ + "path empty)") cmd.Flags().StringVar(&opts.KeepNewerThan, "keep-newer-than", "", "With --prune: keep snapshots newer than this duration "+ "(e.g. 30d, 4w, 6mo, 1y; m is minutes, mo is months) "+ diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 47a79fd..5c2dd77 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -168,6 +168,12 @@ type ScanResult struct { // skipped because it could not be read or listed; the rest are files // removed after the walk listed them. FilesUnreadable int + + // EntriesFound counts the entries the walk found and could look up + // that no exclude pattern matches, leaving out the scanned path + // itself when it is a directory. It is zero for an empty directory, + // such as the mount point of a volume that is not mounted. + EntriesFound int } // NewScanner creates a new scanner instance @@ -928,6 +934,11 @@ func (s *Scanner) scanPhase( default: } + // The scanned directory itself is not an entry found in it. + if filePath != path || !info.IsDir() { + result.EntriesFound++ + } + // Handle symlinks and directories handled, err := s.recordSpecialEntry( filePath, info, existingFiles, knownFiles, collector, result) @@ -940,18 +951,8 @@ func (s *Scanner) scanPhase( return nil } - // Track this file as existing (for deletion detection) - existingFiles[filePath] = struct{}{} - - // Check file against in-memory map (no DB query!) - file := s.buildRegularFileEntry(filePath, info) - needsProcessing := s.checkFileInMemory(file, knownFiles) - - filesScanned, changedCount := collector.recordFile( - filePath, info, file, needsProcessing) - - // Update result stats - s.updateScanEntryStats(result, needsProcessing, info) + filesScanned, changedCount := s.recordRegularFile( + filePath, info, existingFiles, knownFiles, collector, result) // Output periodic status if time.Since(lastStatusTime) >= scanStatusInterval { @@ -1027,6 +1028,30 @@ func (s *Scanner) recordSpecialEntry( return false, nil } +// recordRegularFile records a regular file as recordSpecialEntry does a +// symlink and returns the running scanned and changed counts. +func (s *Scanner) recordRegularFile( + filePath string, info os.FileInfo, + existingFiles map[string]struct{}, + knownFiles map[string]*database.File, + collector *scanCollector, result *ScanResult, +) (int64, int) { + // Track this file as existing (for deletion detection) + existingFiles[filePath] = struct{}{} + + // Check file against in-memory map (no DB query!) + file := s.buildRegularFileEntry(filePath, info) + needsProcessing := s.checkFileInMemory(file, knownFiles) + + filesScanned, changedCount := collector.recordFile( + filePath, info, file, needsProcessing) + + // Update result stats + s.updateScanEntryStats(result, needsProcessing, info) + + return filesScanned, changedCount +} + // countRemovedDuringWalk counts an entry that was in its directory's // listing but was gone when the walk looked it up, like a file removed // before phase 2 reads it: as examined and failed, and not as an error, diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 806495f..a898e25 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -44,6 +44,14 @@ var ErrPostBackupPruneFailed = errors.New("post-backup prune failed") // kept, so the caller can report it apart from a failed backup. var ErrFilesUnreadable = errors.New("file(s) could not be read") +// ErrSourcePathEmpty is returned when --prune skipped the post-backup +// prune because the scan found nothing in a configured path of a +// snapshot, as in the mount point of a volume that is not mounted. The +// snapshots are complete and kept, so the caller can report it apart +// from a failed backup. A run that also skipped unreadable files +// returns ErrFilesUnreadable instead. +var ErrSourcePathEmpty = errors.New("source path(s) were empty") + // listRecentLimit caps how many snapshot rows are fetched from the // local index for listing and purge operations. const listRecentLimit = 10000 @@ -134,17 +142,10 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { return err } - // Process each named snapshot - filesUnreadable := 0 - - for snapIdx, snapName := range snapshotNames { - unreadable, err := v.createNamedSnapshot( - opts, hostname, snapName, snapIdx+1, len(snapshotNames)) - if err != nil { - return err - } - - filesUnreadable += unreadable + filesUnreadable, emptyPaths, err := v.createNamedSnapshots( + opts, hostname, snapshotNames) + if err != nil { + return err } // Print overall summary if multiple snapshots @@ -154,13 +155,8 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { } switch { - case opts.Prune && filesUnreadable > 0: - // An older snapshot may be the only one that still holds a file - // this run could not read. - log.Warn("Skipping post-backup prune", - "files_unreadable", filesUnreadable) - v.UI.Warningf("Skipped the post-backup prune because %d file(s) "+ - "could not be read; older snapshots are kept.", filesUnreadable) + case opts.Prune && (filesUnreadable > 0 || len(emptyPaths) > 0): + return v.skipPostBackupPrune(filesUnreadable, emptyPaths) case opts.Prune: err = v.runPostBackupPrune(snapshotNames, opts.KeepNewerThan) if err != nil { @@ -171,6 +167,61 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { return v.finishCreateSnapshot(filesUnreadable) } +// createNamedSnapshots creates each named snapshot in turn. It returns +// the number of entries --skip-errors skipped because it could not read +// or list them, and each configured path in which the scan found +// nothing, named with its snapshot. +func (v *Vaultik) createNamedSnapshots( + opts *SnapshotCreateOptions, hostname string, snapshotNames []string, +) (int, []string, error) { + filesUnreadable := 0 + + var emptyPaths []string + + for snapIdx, snapName := range snapshotNames { + stats, err := v.createNamedSnapshot( + opts, hostname, snapName, snapIdx+1, len(snapshotNames)) + if err != nil { + return 0, nil, err + } + + filesUnreadable += stats.totalFilesUnreadable + + for _, dir := range stats.emptyPaths { + emptyPaths = append(emptyPaths, dir+" of snapshot "+snapName) + } + } + + return filesUnreadable, emptyPaths, nil +} + +// skipPostBackupPrune says why the post-backup prune does not run, naming +// every cause, and returns the error the run ends with. An older snapshot +// may be the only one that still holds a file this run could not read, +// or what an empty path held. The previous snapshot is no guide: after +// one run with an empty path it is empty too. +func (v *Vaultik) skipPostBackupPrune( + filesUnreadable int, emptyPaths []string, +) error { + log.Warn("Skipping post-backup prune", + "files_unreadable", filesUnreadable, "empty_paths", emptyPaths) + + if len(emptyPaths) > 0 { + v.UI.Warningf("Skipped the post-backup prune because nothing was "+ + "found in %s; older snapshots are kept.", + strings.Join(emptyPaths, ", ")) + } + + if filesUnreadable > 0 { + v.UI.Warningf("Skipped the post-backup prune because %d file(s) "+ + "could not be read; older snapshots are kept.", filesUnreadable) + + return fmt.Errorf("%d %w", filesUnreadable, ErrFilesUnreadable) + } + + return fmt.Errorf("%d %w", len(emptyPaths), ErrSourcePathEmpty) +} + // finishCreateSnapshot ends a run whose snapshots are all complete and // kept. Like finishRestore, it returns an error when --skip-errors // skipped anything it could not read or list; otherwise it prints the @@ -274,6 +325,9 @@ type snapshotStats struct { // could not be read or listed. totalFilesUnreadable int + // The configured paths in which the scan found nothing. + emptyPaths []string + // The sizes of all blobs the snapshot references, set by // finalizeSnapshotMetadata once snapshot_blobs is populated. blobSize int64 @@ -281,11 +335,10 @@ type snapshotStats struct { } // createNamedSnapshot creates a single named snapshot and returns the -// number of entries --skip-errors skipped because it could not read or -// list them. +// statistics of its scan. func (v *Vaultik) createNamedSnapshot( opts *SnapshotCreateOptions, hostname, snapName string, idx, total int, -) (int, error) { +) (*snapshotStats, error) { snapshotStartTime := time.Now() if total > 1 { @@ -294,12 +347,12 @@ func (v *Vaultik) createNamedSnapshot( resolvedDirs, err := v.resolveSnapshotPaths(snapName) if err != nil { - return 0, err + return nil, err } previousSnapshotID, err := v.previousSnapshotID(snapName) if err != nil { - return 0, err + return nil, err } scanner := v.ScannerFactory(snapshot.ScannerParams{ @@ -314,7 +367,7 @@ func (v *Vaultik) createNamedSnapshot( snapshotID, err := v.SnapshotManager.CreateSnapshotWithName( v.ctx, hostname, snapName, v.Globals.Version, v.Globals.Commit) if err != nil { - return 0, fmt.Errorf("creating snapshot: %w", err) + return nil, fmt.Errorf("creating snapshot: %w", err) } log.Info("Beginning snapshot", "snapshot_id", snapshotID, "name", snapName) @@ -322,12 +375,12 @@ func (v *Vaultik) createNamedSnapshot( stats, err := v.scanAllDirectories(scanner, resolvedDirs, snapshotID) if err != nil { - return 0, err + return nil, err } err = v.finalizeSnapshotMetadata(snapshotID, stats) if err != nil { - return 0, err + return nil, err } log.Info("Snapshot complete", @@ -340,7 +393,7 @@ func (v *Vaultik) createNamedSnapshot( v.printSnapshotSummary(snapshotID, snapshotStartTime, stats) - return stats.totalFilesUnreadable, nil + return stats, nil } // previousSnapshotID returns the ID of the most recent completed snapshot @@ -362,7 +415,8 @@ func (v *Vaultik) previousSnapshotID(snapName string) (string, error) { } // resolveSnapshotPaths resolves source directories to absolute paths -// with symlink resolution. +// with symlink resolution. A path that is a symlink whose target does +// not exist is an error. func (v *Vaultik) resolveSnapshotPaths(snapName string) ([]string, error) { snapConfig := v.Config.Snapshots[snapName] resolvedDirs := make([]string, 0, len(snapConfig.Paths)) @@ -375,12 +429,18 @@ func (v *Vaultik) resolveSnapshotPaths(snapName string) ([]string, error) { resolvedPath, err := filepath.EvalSymlinks(absPath) if err != nil { - if os.IsNotExist(err) { - resolvedPath = absPath - } else { + // A path that does not exist is left for the scan to report. + // One that exists is a symlink whose target is gone, as one + // into a volume that is not mounted: the scan would record + // only the link, and --prune would then drop the older + // snapshots that hold the files. + _, lstatErr := os.Lstat(absPath) + if !os.IsNotExist(err) || lstatErr == nil { return nil, fmt.Errorf( "failed to resolve symlinks for %s: %w", absPath, err) } + + resolvedPath = absPath } resolvedDirs = append(resolvedDirs, resolvedPath) @@ -434,6 +494,10 @@ func (v *Vaultik) scanAllDirectories( stats.totalBytesUploaded += result.BytesUploaded stats.uploadDuration += result.UploadDuration + if result.EntriesFound == 0 { + stats.emptyPaths = append(stats.emptyPaths, dir) + } + log.Info("Directory scan complete", "path", dir, "files", result.FilesScanned, diff --git a/internal/vaultik/snapshot_prune_test.go b/internal/vaultik/snapshot_prune_test.go index 8b76a93..035dd5a 100644 --- a/internal/vaultik/snapshot_prune_test.go +++ b/internal/vaultik/snapshot_prune_test.go @@ -1,8 +1,15 @@ package vaultik_test import ( + "context" + "os" + "path/filepath" "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -25,3 +32,230 @@ func TestSnapshotCreateOptions_PruneFlag(t *testing.T) { t.Error("Expected Prune to be false") } } + +// A backup under --prune that finds nothing in a configured path, as in +// the mount point of a volume that is not mounted, does not prune: run +// after run, the snapshot that holds the files is kept with everything +// it stored, and the run fails. That holds whether the empty path is the +// snapshot's only path or one of two. See +// https://git.eeqj.de/sneak/vaultik/issues/388. +func TestBackupWithEmptySourcePathDoesNotPrune(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + // emptied is the path, relative to the source directory, that is + // emptied after the first backup. + const ( + snapshotName = "media" + emptied = "music" + ) + + tests := []struct { + name string + paths []string // relative to the source directory + }{ + {name: "only path", paths: []string{emptied}}, + {name: "one of two paths", paths: []string{emptied, "docs"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + env := newDeletedCountEnv(t, map[string][]byte{ + emptied + "/a.mp3": []byte("song a"), + emptied + "/b.mp3": []byte("song b"), + "docs/notes.txt": []byte("notes"), + }) + + paths := make([]string, 0, len(tt.paths)) + + for _, rel := range tt.paths { + paths = append(paths, filepath.Join(env.src, rel)) + } + + env.v.Config.Snapshots[snapshotName] = config.SnapshotConfig{ + Paths: paths, + } + env.backUp(t, snapshotName) + + firstID := localSnapshotID(ctx, t, env.v.Repositories, snapshotName) + stored, err := env.v.Storage.List(ctx, "") + require.NoError(t, err) + + // A volume that is not mounted leaves its mount point behind + // as an empty directory. + emptiedDir := filepath.Join(env.src, emptied) + require.NoError(t, os.RemoveAll(emptiedDir)) + require.NoError(t, os.Mkdir(emptiedDir, 0o750)) + + for range 2 { + env.out.Reset() + + err := env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + Snapshots: []string{snapshotName}, + }) + require.ErrorIs(t, err, vaultik.ErrSourcePathEmpty) + assert.Contains(t, env.out.String(), + "Skipped the post-backup prune because nothing was found in ") + assert.Contains(t, env.out.String(), + emptied+" of snapshot "+snapshotName+";") + assert.NotContains(t, env.out.String(), "Running post-backup prune.") + } + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 3) + assert.Equal(t, firstID, snapshots[2].ID.String(), + "the snapshot that holds the files is kept") + + for _, key := range stored { + _, err := env.v.Storage.Stat(ctx, key) + require.NoError(t, err, "%s is kept", key) + } + }) + } +} + +// A backup under --prune of a configured path that is a symlink whose +// target is gone, as one into a volume that is not mounted, fails before +// anything is pruned: the snapshot that holds the files is kept with +// everything it stored. See https://git.eeqj.de/sneak/vaultik/issues/388. +func TestBackupThroughSymlinkWhoseTargetIsGoneDoesNotPrune(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const snapshotName = "photos" + + ctx := context.Background() + env := newDeletedCountEnv(t, map[string][]byte{ + "volume/a.jpg": []byte("photo a"), + "volume/b.jpg": []byte("photo b"), + }) + + target := filepath.Join(env.src, "volume") + link := filepath.Join(env.src, "photos") + require.NoError(t, os.Symlink(target, link)) + env.setSnapshot(snapshotName, "photos") + env.backUp(t, snapshotName) + + firstID := localSnapshotID(ctx, t, env.v.Repositories, snapshotName) + stored, err := env.v.Storage.List(ctx, "") + require.NoError(t, err) + + // The volume is not mounted, so the symlink points at nothing. + require.NoError(t, os.RemoveAll(target)) + + env.out.Reset() + err = env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + Snapshots: []string{snapshotName}, + }) + require.ErrorIs(t, err, os.ErrNotExist) + assert.Contains(t, err.Error(), link) + assert.NotContains(t, env.out.String(), "Running post-backup prune.") + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1) + assert.Equal(t, firstID, snapshots[0].ID.String(), + "the snapshot that holds the files is kept") + + for _, key := range stored { + _, err := env.v.Storage.Stat(ctx, key) + require.NoError(t, err, "%s is kept", key) + } +} + +// A backup under --skip-errors --prune that both skipped a file it could +// not read and found nothing in a configured path names the empty path +// too when it skips the prune. See +// https://git.eeqj.de/sneak/vaultik/issues/388. +func TestBackupWithEmptySourcePathAndUnreadableFileNamesBoth(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const snapshotName = "media" + + env := newDeletedCountEnv(t, map[string][]byte{ + "docs/notes.txt": []byte("notes"), + }) + require.NoError(t, os.Mkdir(filepath.Join(env.src, "music"), 0o750)) + env.v.Config.Snapshots[snapshotName] = config.SnapshotConfig{ + Paths: []string{ + filepath.Join(env.src, "docs"), + filepath.Join(env.src, "music"), + }, + } + + // A mode does not lock out root, who runs the tests, so opening the + // file is made to fail instead. + env.v.Fs = &openFailFs{ + path: filepath.Join(env.src, "docs", "notes.txt"), + err: os.ErrPermission, + } + + err := env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + SkipErrors: true, + Snapshots: []string{snapshotName}, + }) + require.ErrorIs(t, err, vaultik.ErrFilesUnreadable) + assert.Contains(t, env.out.String(), + "Skipped the post-backup prune because 1 file(s) could not be read") + assert.Contains(t, env.out.String(), + "Skipped the post-backup prune because nothing was found in ") + assert.Contains(t, env.out.String(), "music of snapshot "+snapshotName+";") + assert.NotContains(t, env.out.String(), "Running post-backup prune.") +} + +// A backup under --prune that finds something in each configured path +// prunes the previous snapshot, also when a path is a single file. See +// https://git.eeqj.de/sneak/vaultik/issues/388. +func TestBackupWithNoEmptySourcePathPrunes(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const ( + snapshotName = "album" + file = "pictures/one.jpg" // relative to the source directory + ) + + tests := []struct { + name string + path string // relative to the source directory + }{ + {name: "directory", path: filepath.Dir(file)}, + {name: "single file", path: file}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + env := newDeletedCountEnv(t, map[string][]byte{ + file: []byte("picture"), + }) + env.setSnapshot(snapshotName, tt.path) + env.backUp(t, snapshotName) + + firstID := localSnapshotID(ctx, t, env.v.Repositories, snapshotName) + + require.NoError(t, env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + Snapshots: []string{snapshotName}, + })) + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1, "the previous snapshot is pruned") + assert.NotEqual(t, firstID, snapshots[0].ID.String()) + }) + } +} From ff50a137dd9079b951baa6903235ed4bc5a2da7d Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 15 Oct 2026 03:49:19 +0200 Subject: [PATCH 095/121] Delete metadata directories a backup left without a manifest (closes #390) A backup that stopped between uploading db.zst.age and its manifest left that directory under metadata/ on the destination for good: prune deleted nothing there. The blob step of prune, which snapshot create --prune also runs, now deletes each directory under metadata/ that has no manifest.json.zst, that no local snapshot record claims, and all of whose objects are older than prune_grace_period; an object listed with no time keeps its directory, and only names that are remote keys are deleted. The prompt and the --force output name each such directory, the --json result counts them (metadata_dirs_deleted, metadata_dirs_failed), and a failed delete fails the run. Every description of the grace period now covers these directories. Model: opus-5-5 --- README.md | 70 +++-- config.example.yml | 8 +- docs/DATAMODEL.md | 4 + docs/REPOSTRUCTURE.md | 4 +- internal/cli/config.go | 16 +- internal/cli/prune.go | 9 +- internal/cli/snapshot.go | 10 +- internal/config/config.go | 10 +- internal/config/config_test.go | 3 +- internal/storage/s3_test.go | 5 +- internal/vaultik/nuke_remote_test.go | 2 +- internal/vaultik/prune.go | 304 ++++++++++++++++---- internal/vaultik/prune_grace_period_test.go | 8 +- internal/vaultik/prune_metadata_dir_test.go | 225 +++++++++++++++ internal/vaultik/snapshot.go | 14 +- 15 files changed, 570 insertions(+), 122 deletions(-) create mode 100644 internal/vaultik/prune_metadata_dir_test.go diff --git a/README.md b/README.md index 4e60953..c710ecb 100644 --- a/README.md +++ b/README.md @@ -98,11 +98,12 @@ vaultik snapshot restore ~/vaultik-restore On a destination shared between hosts or users, the prune in that cron line relies on `prune_grace_period` (default `24h`) to leave the blobs of a backup -another one is still running, so it must be longer than the longest backup -run. It does not protect a blob that backup reuses from an earlier run that -stopped before its manifest: the prune can delete such a blob, and the new -snapshot then cannot be restored. To not depend on the grace period, give each -host its own prefix or directory. See [locking](#locking). +another one is still running, and its directory under `metadata/` that has no +manifest yet, so it must be longer than the longest backup run. It does not +protect a blob that backup reuses from an earlier run that stopped before its +manifest: the prune can delete such a blob, and the new snapshot then cannot +be restored. To not depend on the grace period, give each host its own prefix +or directory. See [locking](#locking). ## restoring on another machine @@ -204,18 +205,19 @@ corrupt the local index. The lock covers one user on one machine. It does not stop another user, or another host, from writing to the same destination store at the same -time. A backup uploads its blobs before the manifest that lists them, so a -prune from elsewhere at that moment finds blobs no snapshot lists. It -deletes such a blob only once it is older than `prune_grace_period` -(default `24h`), which therefore must be longer than the longest backup run -of any host or user sharing the destination. The grace period does not -protect a blob a backup reuses from an earlier run that stopped before its -manifest: a backup skips the upload of a blob already on the destination, so -that blob keeps the time of its first upload, and a prune from elsewhere -during the backup can delete it; the new snapshot then cannot be restored. -`remote nuke` deletes everything regardless. To not depend on the grace -period, give each host or user its own prefix (or directory) on the -destination. +time. A backup uploads its blobs, and then its `db.zst.age`, before its +manifest, so a prune from elsewhere at that moment finds blobs no snapshot +lists and a directory under `metadata/` with no manifest. It +deletes such a blob only once it is older than `prune_grace_period` (default +`24h`), and such a directory only once every object in it is, so the grace +period must be longer than the longest backup run of any host or user sharing +the destination. The grace period does not protect a blob a backup reuses +from an earlier run that stopped before its manifest: a backup skips the +upload of a blob already on the destination, so that blob keeps the time of +its first upload, and a prune from elsewhere during the backup can delete it; +the new snapshot then cannot be restored. `remote nuke` deletes everything +regardless. To not depend on the grace period, give each host or user its own +prefix (or directory) on the destination. Read-only commands — `info`, `snapshot list`, `snapshot verify`, and `remote info` — do not take the lock and are never blocked, so they run @@ -318,9 +320,12 @@ value where a list belongs or a word where a number belongs), is refused. error that explains how to fix it * `--cron`: Silent on total success; warnings and errors are still printed (for crontab) -* `--prune`: After backup, drop older snapshots of each backed-up name and +* `--prune`: After backup, drop older snapshots of each backed-up name, remove orphaned blobs older than `prune_grace_period` from remote storage, - as `prune` does. By default keeps only the latest + and delete each directory under `metadata/` that has no + `manifest.json.zst` once every object in it is older than + `prune_grace_period` and its snapshot is not in the local index, as `prune` + does. By default keeps only the latest snapshot per name; use `--keep-newer-than` for a rolling window. When `--skip-errors` skipped a file or directory it could not read or list, the prune does not run and every older snapshot is kept, since one of them may @@ -463,22 +468,29 @@ may belong to a backup still running, on this host or another sharing the destination store, that has not yet uploaded its manifest. The grace period does not protect a blob such a backup reuses from an earlier run that stopped before its manifest: that blob keeps the time of its first upload, so it can -be deleted. Step (3) reads all remote manifests — network cost scales with -the number of snapshots. +be deleted. Step (3) also deletes each directory under `metadata/` that has +no `manifest.json.zst`, as a backup leaves when it stops after uploading +`db.zst.age` but before its manifest, once every object in it is older than +`prune_grace_period` and its snapshot is not in the local index. An object the +listing gives no time for keeps its directory, and a directory whose name is +not a remote key is left alone. Step (3) reads all remote manifests — network +cost scales with the number of snapshots. `snapshot create --prune` runs the same cleanup automatically; this is the manual entry point for the same work. If the destination store cannot be listed, or the local index holds snapshots and the destination answers that it has no `vaultik-destination.txt` (an unplugged volume's empty mount point), prune fails and deletes nothing. `snapshot purge` does the same. If a -blob cannot be deleted, the command (and `snapshot create --prune`) -exits non-zero. +blob or such a directory cannot be deleted, the command (and +`snapshot create --prune`) exits non-zero. * `--force`: Skip confirmation prompt * `--json`: Output stats as JSON. Also skips the confirmation prompt, as `--force` does. A blob that cannot be deleted is counted in `blobs_failed`, and the document is printed before the non-zero exit. A blob kept for being newer than `prune_grace_period`, or because the listing of the destination gives no time for it, is counted in - `blobs_too_new` and not in `blobs_found`. + `blobs_too_new` and not in `blobs_found`. A directory under `metadata/` + with no manifest is counted in `metadata_dirs_deleted` once deleted, or + in `metadata_dirs_failed` if it cannot be. **`info`**: Display system configuration, storage settings, encryption recipients, and local database statistics. @@ -555,8 +567,9 @@ and can be deleted. A destination shared between hosts or users, each with its own local index, relies on `prune_grace_period` to keep one's prune from deleting the blobs of -another's backup still running, so it must be longer than the longest backup -run. It does not protect a blob that backup reuses from an earlier run that +another's backup still running, or its directory under `metadata/` that has +no manifest yet, so it must be longer than the longest backup run. It does not +protect a blob that backup reuses from an earlier run that stopped before its manifest, which the prune can delete. To not depend on the grace period, give each host its own prefix (or directory). See [locking](#locking). @@ -656,6 +669,9 @@ format does and does not protect. 3. List all blobs in storage 4. Delete any blob not in the referenced set that is older than `prune_grace_period` +5. Delete each directory under `metadata/` with no manifest whose objects + are all older than `prune_grace_period`, unless its snapshot is in the + local index ### chunking and deduplication @@ -700,7 +716,7 @@ complete annotated example also lives in | `chunk_size` | `10MB` | Average chunk size for content-defined chunking | | `blob_size_limit` | `10GB` | Maximum blob size before splitting. Must be at least four times `chunk_size` (the largest chunk the chunker can emit), otherwise a single-chunk blob could exceed the limit. A backup needs free temporary space, because each blob is written whole to a temporary file before it is uploaded (up to about `blob_size_limit`; an rclone destination that cannot stream uploads needs about twice that) and the metadata export writes copies of the local index. Temporary files go to `$TMPDIR` (default `/tmp`); with `TMPDIR` unset, SQLite writes one of those copies to `/var/tmp` | | `compression_level` | `3` | zstd compression level (1-19) | -| `prune_grace_period` | `24h` | How old a blob that no snapshot lists must be before `prune` deletes it. A backup uploads its blobs before the manifest that lists them, so on a destination shared between hosts or users this must be longer than the longest backup run (see [locking](#locking)). It does not protect a blob a backup reuses from an earlier run that stopped before its manifest: that blob keeps the time of its first upload, so a prune can delete it. A duration such as `36h` or `90m`; `0s` deletes such blobs at once | +| `prune_grace_period` | `24h` | How old a blob that no snapshot lists must be before `prune` deletes it, and how old every object in a directory under `metadata/` with no manifest must be before `prune` deletes that directory. A backup uploads its blobs and its `db.zst.age` before its manifest, so on a destination shared between hosts or users this must be longer than the longest backup run (see [locking](#locking)). It does not protect a blob a backup reuses from an earlier run that stopped before its manifest: that blob keeps the time of its first upload, so a prune can delete it. A duration such as `36h` or `90m`; `0s` deletes such blobs and directories at once | | `hostname` | system hostname | Hostname used in snapshot IDs | | `index_path` | platform data dir | Local SQLite index path | diff --git a/config.example.yml b/config.example.yml index a2d8f84..b23252f 100644 --- a/config.example.yml +++ b/config.example.yml @@ -329,14 +329,16 @@ storage_url: "rclone://myremote/path/to/backups" # Default: 3 compression_level: 5 -# How old a blob that no snapshot lists must be before prune deletes it -# A backup uploads its blobs before the manifest that lists them, so on a +# How old a blob that no snapshot lists must be before prune deletes it, and +# how old every object in a directory under metadata/ with no manifest must +# be before prune deletes that directory +# A backup uploads its blobs and its db.zst.age before its manifest, so on a # destination shared between hosts or users this must be longer than the # longest backup run # It does not protect a blob a backup reuses from an earlier run that stopped # before its manifest: that blob keeps the time of its first upload, so a # prune can delete it -# Supports: 36h, 90m, etc.; 0s deletes them at once +# Supports: 36h, 90m, etc.; 0s deletes such blobs and directories at once # Default: 24h #prune_grace_period: 24h diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index 4f0ad45..f2462e1 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -230,6 +230,10 @@ The restore process doesn't use the local database. Instead: - Query blobs not referenced by any remaining snapshot - Delete from S3, once older than `prune_grace_period`, and from the local database +2. **Delete Metadata Directories With No Manifest** + - Delete each directory under `metadata/` that has no `manifest.json.zst` + and no local snapshot record, once every object in it is older than + `prune_grace_period` ### 6. Incomplete Snapshot Cleanup diff --git a/docs/REPOSTRUCTURE.md b/docs/REPOSTRUCTURE.md index 0768c9d..d2f003a 100644 --- a/docs/REPOSTRUCTURE.md +++ b/docs/REPOSTRUCTURE.md @@ -165,10 +165,10 @@ These are known, deliberate properties of the format and the tooling, recorded s ## Pruning Safety The prune operation is safe because: -1. It keeps every blob listed in any snapshot's manifest and deletes only blobs that no manifest references +1. It keeps every blob listed in any snapshot's manifest and deletes only blobs that no manifest references. Under `metadata/` it deletes only a directory that has no `manifest.json.zst`, whose name is a remote key, and that no local snapshot record claims 2. Manifests are unencrypted and can be read without keys 3. If any manifest cannot be downloaded or decoded, prune deletes nothing and exits with an error, rather than treating that snapshot's blobs as unreferenced -4. It deletes an unreferenced blob only once the blob is older than `prune_grace_period` (default `24h`). A backup uploads its blobs before the manifest that lists them, so a prune running meanwhile, on this host or another sharing the destination, leaves them as long as no backup run takes longer than the grace period. The grace period does not protect a blob a backup reuses from an earlier run that stopped before its manifest: the backup skips the upload of a blob already on the destination, so that blob keeps the time of its first upload, and a prune before the backup's manifest is written can delete it; the new snapshot then cannot be restored. `remote nuke` has no such check +4. It deletes an unreferenced blob only once the blob is older than `prune_grace_period` (default `24h`), and a directory under `metadata/` with no manifest only once every object in it is. A backup uploads its blobs and its `db.zst.age` before its manifest, so a prune running meanwhile, on this host or another sharing the destination, leaves them as long as no backup run takes longer than the grace period. The grace period does not protect a blob a backup reuses from an earlier run that stopped before its manifest: the backup skips the upload of a blob already on the destination, so that blob keeps the time of its first upload, and a prune before the backup's manifest is written can delete it; the new snapshot then cannot be restored. `remote nuke` has no such check ## Restoration Requirements diff --git a/internal/cli/config.go b/internal/cli/config.go index 638b6ef..2a18fc1 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -239,13 +239,15 @@ storage_url: "" # Default: 3 # compression_level: 3 -# How old a blob that no snapshot lists must be before prune deletes it. -# A backup uploads its blobs before the manifest that lists them, so on a -# destination shared between hosts or users this must be longer than the -# longest backup run. It does not protect a blob a backup reuses from an -# earlier run that stopped before its manifest: that blob keeps the time of -# its first upload, so a prune can delete it. -# Accepts: 36h, 90m, etc. 0s deletes them at once. +# How old a blob that no snapshot lists must be before prune deletes it, +# and how old every object in a directory under metadata/ with no manifest +# must be before prune deletes that directory. A backup uploads its blobs +# and its db.zst.age before its manifest, so on a destination shared +# between hosts or users this must be longer than the longest backup run. +# It does not protect a blob a backup reuses from an earlier run that +# stopped before its manifest: that blob keeps the time of its first +# upload, so a prune can delete it. +# Accepts: 36h, 90m, etc. 0s deletes such blobs and directories at once. # Default: 24h # prune_grace_period: 24h diff --git a/internal/cli/prune.go b/internal/cli/prune.go index 77f38b6..6b6843a 100644 --- a/internal/cli/prune.go +++ b/internal/cli/prune.go @@ -13,8 +13,9 @@ func NewPruneCommand() *cobra.Command { cmd := &cobra.Command{ Use: "prune", Short: "Tidy local database and remote storage", - Long: `Removes orphaned data from both the local index database and -unreferenced blobs from the backup destination store. + Long: `Removes orphaned data from the local index database, and +unreferenced blobs and directories under metadata/ with no manifest +from the backup destination store. Local cleanup drops incomplete snapshots and any files, chunks, or blobs no longer referenced by a completed snapshot. Remote cleanup @@ -26,6 +27,10 @@ another sharing the destination store, that has not yet uploaded its manifest. The grace period does not protect a blob such a backup reuses from an earlier run that stopped before its manifest: that blob keeps the time of its first upload, so it can be deleted. +Remote cleanup also deletes each directory under metadata/ with no +manifest, as a backup that stopped before its manifest leaves, once +all its objects are older than prune_grace_period and its snapshot is +not in the local index. Snapshot create --prune runs the same cleanup automatically; this command is the manual entry point for the same work (e.g. after a diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 4958c62..3c67594 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -132,10 +132,12 @@ on Linux), then /etc/vaultik/config.yml.`, cmd.Flags().BoolVar(&opts.Cron, "cron", false, "Run in cron mode (silent unless warning or error)") cmd.Flags().BoolVar(&opts.Prune, "prune", false, - "After backup, drop older snapshots of the same name and remove "+ - "orphaned blobs older than prune_grace_period (not after a "+ - "backup that skipped unreadable files or found a configured "+ - "path empty)") + "After backup, drop older snapshots of the same name, remove "+ + "orphaned blobs older than prune_grace_period, and delete each "+ + "directory under metadata/ with no manifest once all its "+ + "objects are older than prune_grace_period and its snapshot is "+ + "not in the local index (not after a backup that skipped "+ + "unreadable files or found a configured path empty)") cmd.Flags().StringVar(&opts.KeepNewerThan, "keep-newer-than", "", "With --prune: keep snapshots newer than this duration "+ "(e.g. 30d, 4w, 6mo, 1y; m is minutes, mo is months) "+ diff --git a/internal/config/config.go b/internal/config/config.go index a2b86b9..01cf8cb 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -192,10 +192,12 @@ type Config struct { CompressionLevel int `yaml:"compression_level"` // PruneGracePeriod is how old a blob no manifest lists must be before - // a prune deletes it. A backup lists its blobs in a manifest only - // once it has uploaded them all, so a younger one may belong to a - // backup still running, on this host or another sharing the - // destination store. + // a prune deletes it, and how old every object in a directory under + // metadata/ with no manifest must be before a prune deletes that + // directory. A backup writes its manifest only once it has uploaded + // all its blobs and its db.zst.age, so a younger blob or directory may + // belong to a backup still running, on this host or another sharing + // the destination store. PruneGracePeriod time.Duration `yaml:"prune_grace_period"` // StorageURL specifies the storage backend using a URL format. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 3f1a26b..b1af7cd 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -415,7 +415,8 @@ func TestDocumentedSizeExamples(t *testing.T) { // TestValidatePruneGracePeriod checks that a negative prune_grace_period // is refused rather than acting like 0s, which deletes unreferenced blobs -// at once, and that 0s and the documented examples are accepted. +// and directories under metadata/ with no manifest at once, and that 0s +// and the documented examples are accepted. func TestValidatePruneGracePeriod(t *testing.T) { t.Parallel() diff --git a/internal/storage/s3_test.go b/internal/storage/s3_test.go index df16200..8902bc7 100644 --- a/internal/storage/s3_test.go +++ b/internal/storage/s3_test.go @@ -100,8 +100,9 @@ func TestS3StorerMissingKeyMapsToErrNotFound(t *testing.T) { // TestS3ListingCutShortIsAnError checks that List and ListStream fail on a // listing page marked truncated that carries no continuation token, as a // server answering V2 listings V1-style sends it. Taken as the last page, -// it would hide every later key, and prune would treat the blobs of the -// snapshots listed there as unreferenced. +// it would hide every later key: prune would treat the blobs of the +// snapshots listed there as unreferenced, and a directory under metadata/ +// whose manifest is listed there as one with no manifest. func TestS3ListingCutShortIsAnError(t *testing.T) { t.Parallel() diff --git a/internal/vaultik/nuke_remote_test.go b/internal/vaultik/nuke_remote_test.go index 63ebcbe..913f005 100644 --- a/internal/vaultik/nuke_remote_test.go +++ b/internal/vaultik/nuke_remote_test.go @@ -76,7 +76,7 @@ func TestNukeRemoteLeavesNoFiles(t *testing.T) { // TestNukeRemoteFailsWhenADeleteFails checks that remote nuke returns an // error when a snapshot's metadata or a blob cannot be deleted, does not // report the store empty, and advises running nuke again: prune deletes -// no metadata. +// no snapshot metadata that has its manifest. func TestNukeRemoteFailsWhenADeleteFails(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index de75d9b..dcffb0e 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -4,10 +4,12 @@ import ( "encoding/json" "errors" "fmt" + "sort" "strings" "time" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/storage" ) @@ -24,6 +26,11 @@ var errNukeRequiresForce = errors.New( // errBlobDeleteFailed reports unreferenced blobs prune could not delete. var errBlobDeleteFailed = errors.New("blob(s) could not be deleted") +// errMetadataDirDeleteFailed reports directories under metadata/ with no +// manifest that prune could not delete. +var errMetadataDirDeleteFailed = errors.New( + "metadata director(ies) with no manifest could not be deleted") + // errObjectsLeft reports objects remote nuke still finds on the backup // destination store after deleting. var errObjectsLeft = errors.New( @@ -31,7 +38,8 @@ var errObjectsLeft = errors.New( // nukeCommandHint is the command suggested when a remote nuke could not // delete everything: running it again deletes what is left, which -// `vaultik prune` does not do for snapshot metadata. +// `vaultik prune` does not do for snapshot metadata that has its +// manifest. const nukeCommandHint = "vaultik remote nuke --force" // metadataDirName is the top-level remote directory holding snapshot @@ -169,14 +177,20 @@ type PruneBlobsResult struct { // newer than the prune grace period, or of unknown age. BlobsFound // does not include them. BlobsTooNew int `json:"blobs_too_new"` + // MetadataDirsDeleted counts the directories under metadata/ with no + // manifest that prune deleted, and MetadataDirsFailed those it could + // not delete. + MetadataDirsDeleted int `json:"metadata_dirs_deleted"` + MetadataDirsFailed int `json:"metadata_dirs_failed,omitempty"` } -// Prune removes orphaned data from the local index database AND -// unreferenced blobs from the backup destination store. This is the -// single user-facing prune entry point — the split between local and -// remote cleanup is an implementation detail. Calling code should -// prefer this method over PruneDatabase or PruneBlobs individually -// unless it specifically wants one half. +// Prune removes orphaned data from the local index database AND, from the +// backup destination store, unreferenced blobs and the directories under +// metadata/ with no manifest. This is the single user-facing prune entry +// point — the split between local and remote cleanup is an +// implementation detail. Calling code should prefer this method over +// PruneDatabase or PruneBlobs individually unless it specifically wants +// one half. func (v *Vaultik) Prune(opts *PruneOptions) error { err := v.EnsureStorageBinding() if err != nil { @@ -200,11 +214,17 @@ func (v *Vaultik) Prune(opts *PruneOptions) error { return v.PruneBlobs(opts) } -// PruneBlobs removes unreferenced blobs from storage +// PruneBlobs removes unreferenced blobs from storage, and each directory +// under metadata/ that a backup left with no manifest. func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { log.Info("Starting prune operation") - allBlobsReferenced, err := v.collectReferencedBlobs() + metadataObjects, err := v.listMetadataObjects() + if err != nil { + return err + } + + allBlobsReferenced, err := v.collectReferencedBlobs(metadataObjects) if err != nil { return err } @@ -217,6 +237,11 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { unreferencedBlobs, totalSize, tooNew := v.findUnreferencedBlobs( allBlobs, allBlobsReferenced) + dirsWithoutManifest, err := v.findMetadataDirsWithoutManifest(metadataObjects) + if err != nil { + return err + } + result := &PruneBlobsResult{ BlobsFound: len(unreferencedBlobs), BlobsTooNew: tooNew, @@ -224,7 +249,7 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { v.reportBlobsTooNew(tooNew, opts) - if len(unreferencedBlobs) == 0 { + if len(unreferencedBlobs) == 0 && len(dirsWithoutManifest) == 0 { log.Info("No unreferenced blobs found") if opts.JSON { @@ -237,38 +262,16 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { } log.Info("Found unreferenced blobs", - "count", len(unreferencedBlobs), "total_size", ubytes(totalSize)) + "count", len(unreferencedBlobs), "total_size", ubytes(totalSize), + "metadata_dirs_without_manifest", len(dirsWithoutManifest)) - if opts.Force && !opts.JSON { - v.UI.Infof("Found %d unreferenced blob(s) totaling %s.", - len(unreferencedBlobs), ubytes(totalSize)) - } - - if !opts.Force && !opts.JSON { - // The count, the prompt and its answer bypass the UI: they are an - // interactive exchange the operator must see, so --quiet does not - // silence them. - v.stdoutf("Found %d unreferenced blob(s) totaling %s.\n", - len(unreferencedBlobs), ubytes(totalSize)) - v.stdoutf("\nDelete %d unreferenced blob(s)? [y/N] ", len(unreferencedBlobs)) - - var confirm string - - _, err = v.scanStdin(&confirm) - if err != nil { - v.printlnStdout("Cancelled") - - return nil //nolint:nilerr // read failure means no confirmation - } - - if strings.ToLower(confirm) != "y" { - v.printlnStdout("Cancelled") - - return nil - } + if !v.confirmPrune(opts, len(unreferencedBlobs), totalSize, + dirsWithoutManifest) { + return nil } v.deleteUnreferencedBlobs(unreferencedBlobs, allBlobs, result) + v.deleteMetadataDirs(dirsWithoutManifest, result) if opts.JSON { err = v.outputPruneBlobsJSON(result) @@ -276,33 +279,142 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { return err } } else { + v.reportPruneDeletions(result, len(dirsWithoutManifest)) + } + + var failures []error + + if result.BlobsFailed > 0 { + failures = append(failures, + fmt.Errorf("%d %w", result.BlobsFailed, errBlobDeleteFailed)) + } + + if result.MetadataDirsFailed > 0 { + failures = append(failures, fmt.Errorf("%d %w", + result.MetadataDirsFailed, errMetadataDirDeleteFailed)) + } + + return errors.Join(failures...) +} + +// confirmPrune states what prune found to delete, unreferenced blobs and +// directories under metadata/ with no manifest, naming each directory by +// its remote key, and, unless --force is given, asks the operator to +// confirm. Under --json it prints nothing and does not ask. It reports +// whether to go ahead. +func (v *Vaultik) confirmPrune( + opts *PruneOptions, blobCount int, blobsSize int64, dirs []string, +) bool { + if opts.JSON { + return true + } + + dirCount := len(dirs) + blobsFound := fmt.Sprintf("Found %d unreferenced blob(s) totaling %s.", + blobCount, ubytes(blobsSize)) + dirsFound := fmt.Sprintf("Found %d metadata director(ies) left by "+ + "backups that stopped before their manifest:", dirCount) + + if opts.Force { + if blobCount > 0 { + v.UI.Infof("%s", blobsFound) + } + + if dirCount > 0 { + v.UI.Infof("%s", dirsFound) + + for _, remoteKey := range dirs { + v.UI.Detailf("metadata/%s/", remoteKey) + } + } + + return true + } + + // The counts, the names, the prompt and its answer bypass the UI: + // they are an interactive exchange the operator must see, so --quiet + // does not silence them. + if blobCount > 0 { + v.stdoutf("%s\n", blobsFound) + } + + if dirCount > 0 { + v.stdoutf("%s\n", dirsFound) + + for _, remoteKey := range dirs { + v.stdoutf(" metadata/%s/\n", remoteKey) + } + } + + switch { + case dirCount == 0: + v.stdoutf("\nDelete %d unreferenced blob(s)? [y/N] ", blobCount) + case blobCount == 0: + v.stdoutf("\nDelete %d metadata director(ies)? [y/N] ", dirCount) + default: + v.stdoutf("\nDelete %d unreferenced blob(s) and %d metadata "+ + "director(ies)? [y/N] ", blobCount, dirCount) + } + + var confirm string + + // A failure to read the answer means no confirmation. + _, err := v.scanStdin(&confirm) + if err != nil || strings.ToLower(confirm) != "y" { + v.printlnStdout("Cancelled") + + return false + } + + return true +} + +// reportPruneDeletions says how many blobs and metadata directories +// prune deleted, naming each kind only when it found some to delete. +func (v *Vaultik) reportPruneDeletions(result *PruneBlobsResult, dirCount int) { + if result.BlobsFound > 0 { v.UI.Infof("Deleted %d blob(s) totaling %s.", result.BlobsDeleted, ubytes(result.BytesFreed)) } - if result.BlobsFailed > 0 { - return fmt.Errorf("%d %w", result.BlobsFailed, errBlobDeleteFailed) + if dirCount > 0 { + v.UI.Infof("Deleted %d metadata director(ies) with no manifest.", + result.MetadataDirsDeleted) } - - return nil } -// collectReferencedBlobs downloads all manifests and returns the set of -// referenced blob hashes. +// listMetadataObjects lists every object under metadata/ on the +// destination store. +func (v *Vaultik) listMetadataObjects() ([]storage.ObjectInfo, error) { + log.Info("Listing remote snapshots") + + var objects []storage.ObjectInfo + + for object := range v.Storage.ListStream(v.ctx, "metadata/") { + if object.Err != nil { + return nil, fmt.Errorf("listing metadata objects: %w", object.Err) + } + + objects = append(objects, object) + } + + return objects, nil +} + +// collectReferencedBlobs downloads every manifest among the listed +// metadata objects and returns the set of referenced blob hashes. // // Every manifest must be read successfully. A manifest that cannot be // downloaded or decoded means its snapshot's blobs are unknown, so // treating them as unreferenced would let prune delete data a snapshot // still needs. Rather than risk that silent loss, any failure returns an // error naming the remote key and prune deletes nothing. -func (v *Vaultik) collectReferencedBlobs() (map[string]bool, error) { - log.Info("Listing remote snapshots") - // IDs returned by listUniqueSnapshotIDs are remote keys (hashed +func (v *Vaultik) collectReferencedBlobs( + metadataObjects []storage.ObjectInfo, +) (map[string]bool, error) { + // IDs returned by uniqueSnapshotIDs are remote keys (hashed // subdirectories under metadata/), not human snapshot IDs. - remoteKeys, err := v.listUniqueSnapshotIDs() - if err != nil { - return nil, fmt.Errorf("listing snapshot keys: %w", err) - } + remoteKeys := uniqueSnapshotIDs(metadataObjects) log.Info("Found manifests in remote storage", "count", len(remoteKeys)) @@ -327,18 +439,14 @@ func (v *Vaultik) collectReferencedBlobs() (map[string]bool, error) { return allBlobsReferenced, nil } -// listUniqueSnapshotIDs returns deduplicated snapshot IDs from remote metadata -func (v *Vaultik) listUniqueSnapshotIDs() ([]string, error) { - objectCh := v.Storage.ListStream(v.ctx, "metadata/") +// uniqueSnapshotIDs returns deduplicated snapshot IDs from the listed +// metadata objects. +func uniqueSnapshotIDs(metadataObjects []storage.ObjectInfo) []string { seen := make(map[string]bool) var snapshotIDs []string - for object := range objectCh { - if object.Err != nil { - return nil, fmt.Errorf("listing metadata objects: %w", object.Err) - } - + for _, object := range metadataObjects { parts := strings.Split(object.Key, "/") if len(parts) >= minSnapshotIDParts && parts[0] == metadataDirName && parts[1] != "" { @@ -353,7 +461,7 @@ func (v *Vaultik) listUniqueSnapshotIDs() ([]string, error) { } } - return snapshotIDs, nil + return snapshotIDs } // listAllRemoteBlobs returns a map of all blob hashes in remote storage @@ -427,6 +535,82 @@ func (v *Vaultik) findUnreferencedBlobs( return unreferenced, totalSize, tooNew } +// findMetadataDirsWithoutManifest returns the remote key of each +// directory under metadata/ that has no manifest.json.zst, such as one a +// backup leaves when its manifest upload fails after db.zst.age was +// uploaded. It leaves out a directory a local snapshot record claims, +// and one holding an object newer than the prune grace period, or of +// unknown age because the listing gave no time for it: a backup still +// running may be writing there. A name that is not a remote key is +// never returned. +func (v *Vaultik) findMetadataDirsWithoutManifest( + metadataObjects []storage.ObjectInfo, +) ([]string, error) { + localIDs, err := v.localSnapshotIDs() + if err != nil { + return nil, fmt.Errorf("listing local snapshots: %w", err) + } + + keep := make(map[string]bool, len(localIDs)) + for _, id := range localIDs { + keep[snapshot.RemoteSnapshotKey(id)] = true + } + + cutoff := time.Now().UTC().Add(-v.Config.PruneGracePeriod) + listed := make(map[string]bool) + + for _, object := range metadataObjects { + parts := strings.Split(object.Key, "/") + if len(parts) < metadataKeyParts || !isBlobHash(parts[1]) { + continue + } + + remoteKey := parts[1] + listed[remoteKey] = true + + if parts[2] == "manifest.json.zst" || + object.ModTime.IsZero() || object.ModTime.After(cutoff) { + keep[remoteKey] = true + } + } + + var remoteKeys []string + + for remoteKey := range listed { + if !keep[remoteKey] { + remoteKeys = append(remoteKeys, remoteKey) + } + } + + sort.Strings(remoteKeys) + + return remoteKeys, nil +} + +// deleteMetadataDirs deletes everything in the given directories under +// metadata/ and counts in the result the directories deleted and those +// it could not delete. +func (v *Vaultik) deleteMetadataDirs( + remoteKeys []string, result *PruneBlobsResult, +) { + for _, remoteKey := range remoteKeys { + _, err := v.deleteRemoteSnapshotByKey(remoteKey) + if err != nil { + log.Error("Failed to delete metadata directory with no manifest", + "remote_key", remoteKey, "error", err) + + result.MetadataDirsFailed++ + + continue + } + + log.Info("Deleted metadata directory with no manifest", + "remote_key", remoteKey) + + result.MetadataDirsDeleted++ + } +} + // reportBlobsTooNew says how many unreferenced blobs prune kept for being // newer than the grace period or of unknown age. Under --json the // document carries the count instead. diff --git a/internal/vaultik/prune_grace_period_test.go b/internal/vaultik/prune_grace_period_test.go index e5004bf..d31d354 100644 --- a/internal/vaultik/prune_grace_period_test.go +++ b/internal/vaultik/prune_grace_period_test.go @@ -24,8 +24,9 @@ import ( // TestPruneDuringBackupKeepsItsBlobs runs a prune from another host // sharing the destination store at the moment a backup has uploaded its -// blobs but not yet its manifest, so no manifest lists those blobs. The -// prune must leave them, and the backup must then restore. +// blobs and its db.zst.age but not yet its manifest, so no manifest lists +// those blobs. The prune must leave the blobs and the db.zst.age, and the +// backup must then restore. func TestPruneDuringBackupKeepsItsBlobs(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -79,7 +80,8 @@ func TestPruneDuringBackupKeepsItsBlobs(t *testing.T) { SnapshotID: id, TargetDir: restoreDir, Verify: true, - }), "a prune during the backup must not delete the backup's blobs") + }), "a prune during the backup must not delete the backup's blobs "+ + "or its db.zst.age") assertRestoredTree(t, fs, restoreDir, testFiles) } diff --git a/internal/vaultik/prune_metadata_dir_test.go b/internal/vaultik/prune_metadata_dir_test.go new file mode 100644 index 0000000..3bf5210 --- /dev/null +++ b/internal/vaultik/prune_metadata_dir_test.go @@ -0,0 +1,225 @@ +package vaultik_test + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// metadataObjectKey returns the key of the named file in the metadata +// directory of the snapshot with the given human ID. +func metadataObjectKey(snapshotID, name string) string { + return "metadata/" + snapshot.RemoteSnapshotKey(snapshotID) + "/" + name +} + +// TestPruneDeletesMetadataDirWithoutManifestOlderThanGracePeriod checks +// that prune deletes a directory under metadata/ holding only +// db.zst.age, as a backup leaves when its manifest upload fails, once it +// is older than the grace period, and keeps one newer than that. A +// directory with a manifest is never deleted, however old. +func TestPruneDeletesMetadataDirWithoutManifestOlderThanGracePeriod( + t *testing.T, +) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := t.TempDir() + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + const ( + oldID = "testhost_home_2026-01-01T00:00:00Z" + newID = "testhost_home_2026-01-02T00:00:00Z" + completeID = "testhost_home_2026-01-03T00:00:00Z" + ) + + oldDB := metadataObjectKey(oldID, "db.zst.age") + newDB := metadataObjectKey(newID, "db.zst.age") + completeDB := metadataObjectKey(completeID, "db.zst.age") + completeManifest := metadataObjectKey(completeID, "manifest.json.zst") + + manifest, err := snapshot.EncodeManifest(&snapshot.Manifest{ + SnapshotID: snapshot.RemoteSnapshotKey(completeID), + }, 3) + require.NoError(t, err) + + for _, key := range []string{oldDB, newDB, completeDB} { + require.NoError(t, store.Put(ctx, key, strings.NewReader("db"))) + } + + require.NoError(t, store.Put(ctx, completeManifest, + bytes.NewReader(manifest))) + + gracePeriod := time.Hour + beforeGracePeriod := time.Now().Add(-gracePeriod - time.Minute) + + for _, key := range []string{oldDB, completeDB, completeManifest} { + require.NoError(t, os.Chtimes(filepath.Join(storeDir, key), + beforeGracePeriod, beforeGracePeriod)) + } + + stdout := &bytes.Buffer{} + v := &vaultik.Vaultik{ + Config: &config.Config{PruneGracePeriod: gracePeriod}, + Storage: store, + Stdout: stdout, + UI: ui.NewWithColor(stdout, false), + } + v.SetContext(ctx) + + require.NoError(t, v.PruneBlobs(&vaultik.PruneOptions{JSON: true})) + + _, err = store.Stat(ctx, oldDB) + require.ErrorIs(t, err, storage.ErrNotFound, + "a directory with no manifest older than the grace period "+ + "must be deleted") + + for _, key := range []string{newDB, completeDB, completeManifest} { + _, err = store.Stat(ctx, key) + require.NoError(t, err, "%s must be kept", key) + } + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(stdout.Bytes(), &result)) + assert.Equal(t, 1, result.MetadataDirsDeleted) +} + +// TestPruneKeepsMetadataDirClaimedUnknownAgeOrNotRemoteKey checks that +// prune --force keeps a directory under metadata/ with no manifest when a +// local snapshot record claims it, when the listing gives no time for an +// object in it, or when its name is not a remote key. A fourth such +// directory is named, deleted and reported, although there are no +// unreferenced blobs to delete. +func TestPruneKeepsMetadataDirClaimedUnknownAgeOrNotRemoteKey(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + env := newListEnv(t) + + const ( + claimedID = "testhost_home_2026-01-01T00:00:00Z" + leftID = "testhost_home_2026-01-03T00:00:00Z" + ) + + env.addLocal(t, claimedID, time.Now().Add(-time.Hour)) + + claimedDB := metadataObjectKey(claimedID, "db.zst.age") + unknownAgeDB := metadataObjectKey("testhost_home_2026-01-02T00:00:00Z", + "db.zst.age") + leftDB := metadataObjectKey(leftID, "db.zst.age") + notRemoteKeyDB := "metadata/not-a-remote-key/db.zst.age" + + for _, key := range []string{claimedDB, leftDB, notRemoteKeyDB} { + require.NoError(t, env.store.Put(ctx, key, strings.NewReader("db"))) + } + + // Written into the mock store's map directly rather than through + // Put, so its listing gives no time. + env.store.data[unknownAgeDB] = []byte("db") + + require.NoError(t, env.v.PruneBlobs(&vaultik.PruneOptions{Force: true})) + + assert.True(t, env.store.hasKey(claimedDB), + "a directory a local snapshot record claims must be kept") + assert.True(t, env.store.hasKey(unknownAgeDB), + "a directory holding an object of unknown age must be kept") + assert.True(t, env.store.hasKey(notRemoteKeyDB), + "a directory whose name is not a remote key must be kept") + assert.False(t, env.store.hasKey(leftDB), + "a directory with no manifest, unclaimed and old, must be deleted") + + output := env.stdout.String() + + assert.Contains(t, output, "Found 1 metadata director(ies) left by "+ + "backups that stopped before their manifest:") + assert.Contains(t, output, + "metadata/"+snapshot.RemoteSnapshotKey(leftID)+"/") + assert.NotContains(t, output, "not-a-remote-key") + assert.Contains(t, output, + "Deleted 1 metadata director(ies) with no manifest.") + assert.NotContains(t, output, "No unreferenced blobs to remove.") +} + +// TestPruneDeclinedKeepsMetadataDirWithoutManifest checks that the prompt +// names a directory under metadata/ with no manifest that prune is about +// to delete, and that answering no keeps it. +func TestPruneDeclinedKeepsMetadataDirWithoutManifest(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + const leftID = "testhost_home_2026-01-01T00:00:00Z" + + leftDB := metadataObjectKey(leftID, "db.zst.age") + require.NoError(t, env.store.Put(context.Background(), leftDB, + strings.NewReader("db"))) + + env.v.Stdin = strings.NewReader("n\n") + + require.NoError(t, env.v.PruneBlobs(&vaultik.PruneOptions{})) + + assert.True(t, env.store.hasKey(leftDB), + "a declined prune must keep the directory") + + output := env.stdout.String() + + assert.Contains(t, output, + " metadata/"+snapshot.RemoteSnapshotKey(leftID)+"/\n") + assert.Contains(t, output, "Delete 1 metadata director(ies)? [y/N] ") + assert.Contains(t, output, "Cancelled") + assert.NotContains(t, output, "Deleted") +} + +// TestPruneFailedMetadataDirDeleteReturnsError checks that prune --json +// counts a directory under metadata/ with no manifest that it cannot +// delete, and then returns an error, so the command exits non-zero. +func TestPruneFailedMetadataDirDeleteReturnsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + leftDB := metadataObjectKey("testhost_home_2026-01-01T00:00:00Z", + "db.zst.age") + require.NoError(t, env.store.Put(context.Background(), leftDB, + strings.NewReader("db"))) + + store := faultstore.New(env.store) + store.OnDelete = func(key string) bool { + return strings.HasPrefix(key, "metadata/") + } + env.v.Storage = store + + err := env.v.PruneBlobs(&vaultik.PruneOptions{JSON: true}) + + require.ErrorContains(t, err, + "1 metadata director(ies) with no manifest could not be deleted") + assert.True(t, env.store.hasKey(leftDB)) + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &result), + "stdout must hold the JSON document, got:\n%s", env.stdout.String()) + assert.Equal(t, 1, result.MetadataDirsFailed) + assert.Equal(t, 0, result.MetadataDirsDeleted) +} diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index a898e25..68a44d5 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -270,9 +270,10 @@ func (v *Vaultik) snapshotNamesToCreate(requested []string) ([]string, error) { } // runPostBackupPrune drops older snapshots of the given names and removes -// orphan blobs from remote storage. If keepNewerThan is set (e.g. "4w"), -// snapshots newer than that duration are kept. Otherwise only the latest -// snapshot of each name is kept. +// from remote storage the orphan blobs and the directories under +// metadata/ with no manifest, as PruneBlobs does. If keepNewerThan is set +// (e.g. "4w"), snapshots newer than that duration are kept. Otherwise only +// the latest snapshot of each name is kept. func (v *Vaultik) runPostBackupPrune( snapshotNames []string, keepNewerThan string, ) error { @@ -299,7 +300,7 @@ func (v *Vaultik) runPostBackupPrune( err = v.PruneBlobs(&PruneOptions{Force: true}) if err != nil { - return fmt.Errorf("pruning orphaned blobs: %w", err) + return fmt.Errorf("pruning the destination store: %w", err) } return nil @@ -1365,7 +1366,7 @@ const pruneCommandHint = "vaultik prune" // snapshotRemoveCommandHint is the command suggested, with the // snapshot's ID, when a remove could not reach the destination store: // running it again removes the snapshot's metadata there, which -// `vaultik prune` never does. +// `vaultik prune` never does while the manifest is there. const snapshotRemoveCommandHint = "vaultik snapshot remove" // RemoveSnapshot removes a snapshot from the local index database and, @@ -1568,7 +1569,8 @@ func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) // the local index, its removal there has already happened, so a failure // is only a warning telling the user to run `vaultik snapshot remove` // for the snapshot again once the destination store is reachable -// (`vaultik prune` never removes snapshot metadata). +// (`vaultik prune` never removes snapshot metadata that has its +// manifest). func (v *Vaultik) removeSnapshotRemote( snapshotID string, inLocalIndex bool, markerErr error, opts *RemoveOptions, From 5abacbc5c1c42ba8be1ab88d323685a79866af35 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 15 Oct 2026 08:32:28 +0200 Subject: [PATCH 096/121] Do not prune when a backup misses an earlier mount point (closes #395) snapshot create --prune purged the older snapshots holding a volume's files when the volume, mounted below a configured path, was not mounted: its empty mount point read as deleted files. The scan now records in the local index each directory at or below a configured path that the walk found an entry in and that, once listed, is on a different device from its parent; listing mounts an automounted volume. Under --prune, when an earlier snapshot of that name recorded such a directory and this run does not, the run skips the prune, keeps every older snapshot and exits non-zero, naming the directory. For a volume retired on purpose, snapshot purge removes the older snapshots. Model: opus-5-5 --- README.md | 15 +- TODO.md | 9 + docs/DATAMODEL.md | 13 +- .../cli/entry_snapshot_create_prune_test.go | 47 ++++ internal/cli/snapshot.go | 6 +- internal/database/schema/001.sql | 10 + internal/database/snapshots.go | 89 +++++-- internal/database/snapshots_test.go | 50 ++++ internal/snapshot/device_number_test.go | 40 +++ internal/snapshot/module.go | 6 + internal/snapshot/mount_point_test.go | 245 ++++++++++++++++++ internal/snapshot/scanner.go | 140 +++++++++- internal/snapshot/snapshot.go | 21 +- internal/snapshot/snapshot_test.go | 73 ++++++ internal/vaultik/fault_injection_test.go | 1 + internal/vaultik/snapshot.go | 117 ++++++++- internal/vaultik/snapshot_prune_test.go | 152 +++++++++++ 17 files changed, 988 insertions(+), 46 deletions(-) create mode 100644 internal/snapshot/device_number_test.go create mode 100644 internal/snapshot/mount_point_test.go diff --git a/README.md b/README.md index c710ecb..f83d065 100644 --- a/README.md +++ b/README.md @@ -335,8 +335,19 @@ value where a list belongs or a word where a number belongs), is refused. either: every older snapshot is kept, and the command names the path and exits non-zero, on every run until the path holds something again. Take a path that is empty on purpose out of the config, or remove the older - snapshots by hand with `snapshot purge`. A file removed during the backup - does not stop the prune. + snapshots by hand with `snapshot purge`. When an earlier snapshot of the + same name in the local index found a volume mounted at or below a + configured path (a directory on a different filesystem from its parent, + with an entry in it that the backup does not exclude) and this backup does + not, the prune does not run either: every older snapshot is kept, and the + command names the directory and exits non-zero, on every run until the + volume is mounted again. A backup also does not find the volume when it + finds no such entry in its directory, as when an automounted volume cannot + be mounted, or when that directory is no longer backed up, because it is + excluded or its configured path was removed. If any of this is on purpose, + as for a retired volume, remove the older snapshots by hand with + `snapshot purge`. A file removed during the backup does not stop the + prune. * `--keep-newer-than `: With `--prune`, keep snapshots newer than this duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`). Without `--prune`, or with a value that is not a valid duration, the diff --git a/TODO.md b/TODO.md index 6c73004..c32824f 100644 --- a/TODO.md +++ b/TODO.md @@ -24,6 +24,15 @@ owner's; a `v*` tag runs the release build in # Completed Steps +- 2026-10-15: Stopped `snapshot create --prune` pruning after a backup + in which a volume mounted below a configured path in an earlier + snapshot of the same name was not mounted + ([issue #395](https://git.eeqj.de/sneak/vaultik/issues/395)). Such a + prune could delete every snapshot still holding the volume's files. + Each snapshot now records in the local index the directories it found + on a different filesystem from their parent and found an entry in that + the backup does not exclude. + - 2026-10-14: Stopped `snapshot create --prune` pruning after a backup that found nothing in a configured path ([issue #388](https://git.eeqj.de/sneak/vaultik/issues/388)), as in diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index f2462e1..3b197e3 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -153,7 +153,17 @@ Maps snapshots to the blobs they reference. **Purpose:** Tracks blob dependencies for snapshots and enables manifest generation. -### 10. `uploads` +### 10. `snapshot_mount_points` +The directories at or below a configured path, the configured path itself included, that a snapshot's backup found an entry in and, once it had listed them, found on a different filesystem from their parent directory (a different device number), as a mount point is. An automount point whose volume cannot be mounted is not recorded, because the backup finds no entry in it. + +**Columns:** +- `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id) +- `path` (TEXT) - Absolute path of the directory +- PRIMARY KEY (`snapshot_id`, `path`) + +**Purpose:** Lets `snapshot create --prune` skip the prune when a backup does not find a mount point that an earlier snapshot of the same name found, as when the volume is not mounted. + +### 11. `uploads` Tracks blob upload metrics. **Columns:** @@ -173,6 +183,7 @@ Tracks blob upload metrics. - `INSERT OR REPLACE INTO files` - Update file metadata - `SELECT * FROM files WHERE path = ?` - Check if file has changed - `INSERT INTO snapshot_files` - Add file to current snapshot + - `INSERT OR IGNORE INTO snapshot_mount_points` - Record each directory on a different filesystem from its parent that the walk found an entry in 2. **Chunking** (for changed files) - `INSERT OR IGNORE INTO chunks` - Store new chunks diff --git a/internal/cli/entry_snapshot_create_prune_test.go b/internal/cli/entry_snapshot_create_prune_test.go index c6b9597..6f64997 100644 --- a/internal/cli/entry_snapshot_create_prune_test.go +++ b/internal/cli/entry_snapshot_create_prune_test.go @@ -1,6 +1,7 @@ package cli //nolint:testpackage // shares runEntry and the hermetic config helpers import ( + "context" "os" "path/filepath" "strings" @@ -8,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" ) // Flags of `snapshot create` used to build argument vectors below. @@ -117,6 +119,51 @@ func TestEntrySnapshotCreatePruneExitsNonZeroWhenSourceIsEmpty(t *testing.T) { assert.Len(t, snapshots, 2, "the older snapshot is kept") } +// TestEntrySnapshotCreatePruneExitsNonZeroWhenMountPointIsMissing backs +// up, records in the local index that this backup found the source +// directory as a mount point, and runs `snapshot create --prune`, which +// does not find it as one. The command exits non-zero, reports the +// backup as completed, not as a failed snapshot creation, and keeps the +// older snapshot. See https://git.eeqj.de/sneak/vaultik/issues/395. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreatePruneExitsNonZeroWhenMountPointIsMissing( + t *testing.T, +) { + configPath, storeDir := writeBackupConfig(t) + + code, _, _ := runEntry(t, flagConfig, configPath, cmdSnapshot, cmdCreate) + require.Equal(t, 0, code) + + // writeBackupConfig puts the source directory and the local index + // beside the config file. + dir := filepath.Dir(configPath) + ctx := context.Background() + + db, err := database.New(ctx, filepath.Join(dir, "index.sqlite")) + require.NoError(t, err) + + repos := database.NewRepositories(db) + + backedUp, err := repos.Snapshots.GetOnlySnapshot(ctx) + require.NoError(t, err) + require.NoError(t, repos.Snapshots.AddMountPoint(ctx, nil, + backedUp.ID.String(), filepath.Join(dir, "source"))) + require.NoError(t, db.Close()) + + code, _, stderr := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate, flagPrune) + + assert.Equal(t, 1, code) + assert.Contains(t, stderr, "Backup completed, but 1 mount point(s) "+ + "an earlier snapshot recorded were not found") + assert.NotContains(t, stderr, "Snapshot creation failed") + + snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata")) + require.NoError(t, err) + assert.Len(t, snapshots, 2, "the older snapshot is kept") +} + // writeBackupConfig builds a hermetic config with one small file in its // source directory and an empty destination store directory. Returns the // config path and the store directory. diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 3c67594..8996d35 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -116,7 +116,8 @@ on Linux), then /etc/vaultik/config.yml.`, } if errors.Is(err, vaultik.ErrFilesUnreadable) || - errors.Is(err, vaultik.ErrSourcePathEmpty) { + errors.Is(err, vaultik.ErrSourcePathEmpty) || + errors.Is(err, vaultik.ErrVolumeNotMounted) { log.Error("Backup completed with an error", "error", err) ReportErrorf("Backup completed, but %v", err) @@ -137,7 +138,8 @@ on Linux), then /etc/vaultik/config.yml.`, "directory under metadata/ with no manifest once all its "+ "objects are older than prune_grace_period and its snapshot is "+ "not in the local index (not after a backup that skipped "+ - "unreadable files or found a configured path empty)") + "unreadable files, found a configured path empty, or did not "+ + "find a mount point an earlier snapshot found)") cmd.Flags().StringVar(&opts.KeepNewerThan, "keep-newer-than", "", "With --prune: keep snapshots newer than this duration "+ "(e.g. 30d, 4w, 6mo, 1y; m is minutes, mo is months) "+ diff --git a/internal/database/schema/001.sql b/internal/database/schema/001.sql index 9645b56..9c541d6 100644 --- a/internal/database/schema/001.sql +++ b/internal/database/schema/001.sql @@ -123,6 +123,16 @@ CREATE TABLE IF NOT EXISTS snapshot_blobs ( -- Index for efficient blob lookups (used in orphan detection) CREATE INDEX IF NOT EXISTS idx_snapshot_blobs_blob_id ON snapshot_blobs(blob_id); +-- Snapshot mount points table: the directories at or below a configured +-- path that the snapshot's backup found on a different filesystem from +-- their parent directory, as a mount point is, and found an entry in +CREATE TABLE IF NOT EXISTS snapshot_mount_points ( + snapshot_id TEXT NOT NULL, + path TEXT NOT NULL, + PRIMARY KEY (snapshot_id, path), + FOREIGN KEY (snapshot_id) REFERENCES snapshots(id) ON DELETE CASCADE +); + -- Uploads table: tracks blob upload metrics CREATE TABLE IF NOT EXISTS uploads ( blob_hash TEXT PRIMARY KEY, diff --git a/internal/database/snapshots.go b/internal/database/snapshots.go index f4d5e77..7ada98c 100644 --- a/internal/database/snapshots.go +++ b/internal/database/snapshots.go @@ -24,7 +24,8 @@ var ( ) // SnapshotRepository provides access to the snapshots table and its -// snapshot_files / snapshot_blobs association tables. +// snapshot_files / snapshot_blobs association tables, and to the mount +// points each snapshot's backup found (snapshot_mount_points). type SnapshotRepository struct { db *DB } @@ -494,33 +495,63 @@ func (r *SnapshotRepository) GetBlobHashes( ctx context.Context, snapshotID string, ) ([]string, error) { query := ` - SELECT sb.blob_hash + SELECT sb.blob_hash FROM snapshot_blobs sb WHERE sb.snapshot_id = ? ORDER BY sb.blob_hash ` - rows, err := r.db.conn.QueryContext(ctx, query, snapshotID) + blobs, err := r.queryStrings(ctx, query, snapshotID) if err != nil { return nil, fmt.Errorf("querying blob hashes: %w", err) } - defer func() { _ = rows.Close() }() + return blobs, nil +} - var blobs []string +// AddMountPoint records dir as a directory that the backup of a snapshot +// found on a different filesystem from its parent directory, as a mount +// point is, using tx when non-nil. +func (r *SnapshotRepository) AddMountPoint( + ctx context.Context, tx *sql.Tx, snapshotID string, dir string, +) error { + query := ` + INSERT OR IGNORE INTO snapshot_mount_points (snapshot_id, path) + VALUES (?, ?) + ` - for rows.Next() { - var blobHash string - - err := rows.Scan(&blobHash) - if err != nil { - return nil, fmt.Errorf("scanning blob hash: %w", err) - } - - blobs = append(blobs, blobHash) + var err error + if tx != nil { + _, err = tx.ExecContext(ctx, query, snapshotID, dir) + } else { + _, err = r.db.ExecWithLog(ctx, query, snapshotID, dir) } - return blobs, rows.Err() + if err != nil { + return fmt.Errorf("adding mount point to snapshot: %w", err) + } + + return nil +} + +// GetMountPoints returns the directories AddMountPoint recorded for a +// snapshot, sorted. +func (r *SnapshotRepository) GetMountPoints( + ctx context.Context, snapshotID string, +) ([]string, error) { + query := ` + SELECT path + FROM snapshot_mount_points + WHERE snapshot_id = ? + ORDER BY path + ` + + dirs, err := r.queryStrings(ctx, query, snapshotID) + if err != nil { + return nil, fmt.Errorf("querying mount points: %w", err) + } + + return dirs, nil } // GetSnapshotTotalCompressedSize returns the total compressed size of all @@ -709,6 +740,34 @@ func (r *SnapshotRepository) DeleteSnapshotUploads( return nil } +// queryStrings runs query, which selects one text column, and returns +// its values in the order of the rows. +func (r *SnapshotRepository) queryStrings( + ctx context.Context, query string, args ...any, +) ([]string, error) { + rows, err := r.db.conn.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + + defer func() { _ = rows.Close() }() + + var values []string + + for rows.Next() { + var value string + + err := rows.Scan(&value) + if err != nil { + return nil, err + } + + values = append(values, value) + } + + return values, rows.Err() +} + // extendedCompressionRatio computes the compression ratio for a snapshot // from its stored blob_size and the given uncompressed size. Returns 1.0 // when the uncompressed size is zero. diff --git a/internal/database/snapshots_test.go b/internal/database/snapshots_test.go index 5ddbd14..bc943fc 100644 --- a/internal/database/snapshots_test.go +++ b/internal/database/snapshots_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "math" + "slices" "testing" "time" @@ -422,3 +423,52 @@ func TestSnapshotRepositoryDuplicate(t *testing.T) { t.Error("expected error for duplicate snapshot") } } + +// Deleting a snapshot from the local index deletes the mount points its +// backup recorded, and no other snapshot's. See +// https://git.eeqj.de/sneak/vaultik/issues/395. +func TestSnapshotRepositoryDeleteRemovesMountPoints(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repo := database.NewSnapshotRepository(db) + + for _, id := range []types.SnapshotID{"kept", "deleted"} { + err := repo.Create(ctx, nil, &database.Snapshot{ + ID: id, + Hostname: testHostname, + VaultikVersion: testVersion, + StartedAt: time.Now().Truncate(time.Second), + }) + if err != nil { + t.Fatalf("failed to create snapshot: %v", err) + } + + err = repo.AddMountPoint(ctx, nil, id.String(), "/data/nas") + if err != nil { + t.Fatalf("failed to add mount point: %v", err) + } + } + + err := repo.Delete(ctx, "deleted") + if err != nil { + t.Fatalf("failed to delete snapshot: %v", err) + } + + for id, want := range map[string][]string{ + "kept": {"/data/nas"}, + "deleted": nil, + } { + got, err := repo.GetMountPoints(ctx, id) + if err != nil { + t.Fatalf("failed to read mount points: %v", err) + } + + if !slices.Equal(got, want) { + t.Errorf("mount points of %s: got %v, want %v", id, got, want) + } + } +} diff --git a/internal/snapshot/device_number_test.go b/internal/snapshot/device_number_test.go new file mode 100644 index 0000000..85fd8f8 --- /dev/null +++ b/internal/snapshot/device_number_test.go @@ -0,0 +1,40 @@ +//nolint:testpackage // exercises the unexported deviceNumberFromStat +package snapshot + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The device number a real backup reads is the same for a directory and +// a file in it, and differs between the temp directory and /dev. +// Without it no mount point is ever found. See +// https://git.eeqj.de/sneak/vaultik/issues/395. +func TestDeviceNumberFromStat(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + file := filepath.Join(dir, "file.txt") + require.NoError(t, os.WriteFile(file, nil, 0o600)) + + deviceOf := func(path string) uint64 { + t.Helper() + + info, err := os.Stat(path) + require.NoError(t, err) + + device, ok := deviceNumberFromStat(info) + require.True(t, ok, "no device number read for %s", path) + + return device + } + + assert.Equal(t, deviceOf(dir), deviceOf(file)) + + // /dev is a different filesystem from the temp dir on Linux, macOS and in Docker. + assert.NotEqual(t, deviceOf(dir), deviceOf("/dev")) +} diff --git a/internal/snapshot/module.go b/internal/snapshot/module.go index e9f6aab..f83ac07 100644 --- a/internal/snapshot/module.go +++ b/internal/snapshot/module.go @@ -1,6 +1,8 @@ package snapshot import ( + "os" + "github.com/spf13/afero" "go.uber.org/fx" "sneak.berlin/go/vaultik/internal/config" @@ -19,6 +21,9 @@ type ScannerParams struct { // PreviousSnapshotID is the most recent completed snapshot of the // same name, "" for none. PreviousSnapshotID string + // DeviceNumber is ScannerConfig.DeviceNumber; nil reads it from the + // file's stat. + DeviceNumber func(info os.FileInfo) (uint64, bool) } // Module exports backup functionality as an fx module. @@ -59,6 +64,7 @@ func provideScannerFactory( Exclude: excludes, SkipErrors: params.SkipErrors, PreviousSnapshotID: params.PreviousSnapshotID, + DeviceNumber: params.DeviceNumber, }) } } diff --git a/internal/snapshot/mount_point_test.go b/internal/snapshot/mount_point_test.go new file mode 100644 index 0000000..415fe7c --- /dev/null +++ b/internal/snapshot/mount_point_test.go @@ -0,0 +1,245 @@ +package snapshot_test + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "syscall" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/snapshot" +) + +// A scan records with the snapshot each directory on a different device +// from its parent directory that the walk found an entry in, as a mount +// point is, the scanned path included. A filesystem that gives no device +// numbers, as the in-memory one, records none. See +// https://git.eeqj.de/sneak/vaultik/issues/395. +func TestScanRecordsMountPoints(t *testing.T) { + t.Parallel() + + const ( + scannedPath = "/data/source" + snapshotID = "mount-points" + ) + + tests := []struct { + name string + // onVolume names the directories on the volume's device; every + // other directory is on another one. nil leaves the device + // numbers to the in-memory filesystem, which has none. + onVolume []string + want []string + }{ + { + name: "volume below the scanned path", + onVolume: []string{"nas"}, + want: []string{scannedPath + "/nas"}, + }, + { + name: "volume at the scanned path", + onVolume: []string{"source", "nas"}, + want: []string{scannedPath}, + }, + {name: "no device numbers", want: nil}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + fs := afero.NewMemMapFs() + + for _, path := range []string{ + scannedPath + "/notes.txt", scannedPath + "/nas/a.txt", + } { + require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, afero.WriteFile(fs, path, []byte(path), 0o644)) + } + + db, err := database.NewTestDB() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + createTestSnapshotRecord(ctx, t, repos, snapshotID) + + cfg := snapshot.ScannerConfig{ + FS: fs, + ChunkSize: int64(1024 * 16), + Repositories: repos, + MaxBlobSize: int64(1024 * 1024), + CompressionLevel: 3, + AgeRecipients: []string{testAgePublicKey}, + } + if tt.onVolume != nil { + cfg.DeviceNumber = func(info os.FileInfo) (uint64, bool) { + if slices.Contains(tt.onVolume, info.Name()) { + return 2, true + } + + return 1, true + } + } + + _, err = snapshot.NewScanner(cfg).Scan(ctx, scannedPath, snapshotID) + require.NoError(t, err) + + got, err := repos.Snapshots.GetMountPoints(ctx, snapshotID) + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +// automountFs is an in-memory filesystem with a volume at mountPoint +// that is mounted on first access: opening mountPoint to list it mounts +// the volume or, if it cannot be mounted, fails with "no such file or +// directory", as with the autofs daemon. Stat records the device an +// entry is on at that moment, as a real stat does: unmountedDevice for +// mountPoint until the volume is mounted; the volume's, 2, for +// mountPoint once it is and for everything in it; 1 for everything else. +type automountFs struct { + afero.Fs + + mountPoint string + unmountedDevice uint64 + canMount bool + mounted bool +} + +//nolint:ireturn // afero.Fs.Open is defined to return the interface. +func (fs *automountFs) Open(name string) (afero.File, error) { + if name == fs.mountPoint && !fs.canMount { + return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT} + } + + if name == fs.mountPoint { + fs.mounted = true + } + + return fs.Fs.Open(name) +} + +func (fs *automountFs) Stat(name string) (os.FileInfo, error) { + info, err := fs.Fs.Stat(name) + if err != nil { + return nil, err + } + + device := uint64(1) + + switch { + case name == fs.mountPoint && !fs.mounted: + device = fs.unmountedDevice + case name == fs.mountPoint || strings.HasPrefix(name, fs.mountPoint+"/"): + device = 2 + } + + return statWithDevice{FileInfo: info, device: device}, nil +} + +// statWithDevice is an entry automountFs.Stat looked up, with the device +// it was on then. +type statWithDevice struct { + os.FileInfo + + device uint64 +} + +// deviceAtLookup returns the device automountFs.Stat recorded for info. +func deviceAtLookup(info os.FileInfo) (uint64, bool) { + stat, ok := info.(statWithDevice) + + return stat.device, ok +} + +// A volume mounted on first access is mounted when the walk lists its +// mount point. Until then the mount point is on the automounter's own +// device (a systemd automount) or on its parent's (an autofs map that +// shows its mount points before mounting them). Either way only the +// mount point is recorded, by the backup that mounts the volume and by a +// later one that finds it mounted. Listing an automount point whose +// volume cannot be mounted fails; it is not recorded, because the walk +// finds no entry in it. See https://git.eeqj.de/sneak/vaultik/issues/395. +func TestScanRecordsOnlyTheMountPointOfAnAutomountedVolume(t *testing.T) { + t.Parallel() + + const scannedPath = "/data/source" + + mountPoint := scannedPath + "/nas" + + tests := []struct { + name string + unmountedDevice uint64 + canMount bool + want []string + }{ + { + name: "on the automounter's device until listed", + unmountedDevice: 3, canMount: true, want: []string{mountPoint}, + }, + { + name: "on its parent's device until listed", + unmountedDevice: 1, canMount: true, want: []string{mountPoint}, + }, + { + name: "volume that cannot be mounted", + unmountedDevice: 1, canMount: false, want: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + fs := &automountFs{ + Fs: afero.NewMemMapFs(), mountPoint: mountPoint, + unmountedDevice: tt.unmountedDevice, canMount: tt.canMount, + } + + require.NoError(t, fs.MkdirAll(mountPoint+"/photos", 0o755)) + + for _, path := range []string{ + scannedPath + "/notes.txt", mountPoint + "/photos/a.jpg", + } { + require.NoError(t, afero.WriteFile(fs, path, []byte(path), 0o644)) + } + + db, err := database.NewTestDB() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + + for _, snapshotID := range []string{"first", "later"} { + createTestSnapshotRecord(ctx, t, repos, snapshotID) + + scanner := snapshot.NewScanner(snapshot.ScannerConfig{ + FS: fs, + ChunkSize: int64(1024 * 16), + Repositories: repos, + MaxBlobSize: int64(1024 * 1024), + CompressionLevel: 3, + AgeRecipients: []string{testAgePublicKey}, + DeviceNumber: deviceAtLookup, + }) + + _, err = scanner.Scan(ctx, scannedPath, snapshotID) + require.NoError(t, err) + + got, err := repos.Snapshots.GetMountPoints(ctx, snapshotID) + require.NoError(t, err) + assert.Equal(t, tt.want, got, "mount points of the %s backup", snapshotID) + } + }) + } +} diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 5c2dd77..de8db7e 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -73,6 +73,9 @@ type Scanner struct { skipErrors bool // ui is the user-facing output; never nil (defaults to a discarding writer). ui *ui.Writer + // deviceNumber returns the number of the device that holds a file; + // never nil (defaults to deviceNumberFromStat). + deviceNumber func(info os.FileInfo) (uint64, bool) // In-memory cache of known chunk hashes for fast existence checks knownChunks map[string]struct{} @@ -136,6 +139,10 @@ type ScannerConfig struct { // PreviousSnapshotID is the most recent completed snapshot of the // same name, "" for none. PreviousSnapshotID string + // DeviceNumber returns the number of the device that holds a file, + // and false when there is none to read. nil reads it from the file's + // stat; tests replace it, since the in-memory test filesystem has none. + DeviceNumber func(info os.FileInfo) (uint64, bool) } // ScanResult contains the results of a scan operation. Files and bytes @@ -214,6 +221,11 @@ func NewScanner(cfg ScannerConfig) *Scanner { uiw = ui.NewWithColor(io.Discard, false) } + deviceNumber := cfg.DeviceNumber + if deviceNumber == nil { + deviceNumber = deviceNumberFromStat + } + return &Scanner{ fs: cfg.FS, chunker: chunker.NewChunker(cfg.ChunkSize), @@ -229,6 +241,7 @@ func NewScanner(cfg ScannerConfig) *Scanner { skipErrors: cfg.SkipErrors, previousSnapshotID: cfg.PreviousSnapshotID, ui: uiw, + deviceNumber: deviceNumber, pendingChunkHashes: make(map[string]struct{}), } } @@ -297,7 +310,7 @@ func (s *Scanner) Scan( } } - err = s.recordDirectories(ctx, scanResult.Directories) + err = s.recordDirectories(ctx, scanResult) if err != nil { return nil, err } @@ -875,6 +888,11 @@ type ScanPhaseResult struct { FilesToProcess []*FileToProcess UnchangedFileIDs []types.FileID // IDs of unchanged files to associate with snapshot Directories []*FileToProcess // Every directory found, to record + // MountPoints are the directories, the scanned path included, that + // the walk found an entry in and, once it had listed them, on a + // different device from their parent directory (see + // recordIfMountPoint). + MountPoints []string } // scanPhase performs the initial directory scan to identify files to process @@ -894,7 +912,7 @@ func (s *Scanner) scanPhase( // estimate leaves them out. estimatedTotal := countNonDirectories(knownFiles) - collector := &scanCollector{} + collector := &scanCollector{dirsWithEntries: make(map[string]struct{})} // Set up periodic status output startTime := time.Now() @@ -939,6 +957,8 @@ func (s *Scanner) scanPhase( result.EntriesFound++ } + s.recordIfMountPoint(filePath, path, collector) + // Handle symlinks and directories handled, err := s.recordSpecialEntry( filePath, info, existingFiles, knownFiles, collector, result) @@ -973,6 +993,7 @@ func (s *Scanner) scanPhase( FilesToProcess: collector.filesToProcess, UnchangedFileIDs: collector.unchangedFileIDs, Directories: collector.directories, + MountPoints: collector.mountPoints, }, nil } @@ -1099,6 +1120,29 @@ type scanCollector struct { unchangedFileIDs []types.FileID // Just IDs - no new records needed directories []*FileToProcess filesScanned int64 + // dirsWithEntries holds each directory the walk has found an entry in. + dirsWithEntries map[string]struct{} + mountPoints []string +} + +// firstEntryIn notes that the walk found an entry in directory dir and +// reports whether it is the first one. +func (c *scanCollector) firstEntryIn(dir string) bool { + c.mu.Lock() + defer c.mu.Unlock() + + _, seen := c.dirsWithEntries[dir] + c.dirsWithEntries[dir] = struct{}{} + + return !seen +} + +// addMountPoint sets a mount point aside to be recorded. +func (c *scanCollector) addMountPoint(dir string) { + c.mu.Lock() + defer c.mu.Unlock() + + c.mountPoints = append(c.mountPoints, dir) } // addDirectory sets a directory aside to be recorded. It is not counted @@ -1290,20 +1334,100 @@ func (s *Scanner) buildDirectoryEntry(path string, info os.FileInfo) *database.F } } -// recordDirectories records every directory the walk found. A directory -// has no data to back up, so it is not among the files counted and -// backed up. +// recordDirectories records every directory the walk found, and its +// mount points (see recordMountPoints). A directory has no data to back +// up, so it is not among the files counted and backed up. func (s *Scanner) recordDirectories( - ctx context.Context, directories []*FileToProcess, + ctx context.Context, scanned *ScanPhaseResult, ) error { - for _, dir := range directories { + for _, dir := range scanned.Directories { err := s.recordNonRegularFile(ctx, dir) if err != nil { return fmt.Errorf("recording directory %s: %w", dir.Path, err) } } - return nil + return s.recordMountPoints(ctx, scanned.MountPoints) +} + +// recordMountPoints records with the snapshot the mount points the walk +// found (see ScanPhaseResult.MountPoints). +func (s *Scanner) recordMountPoints( + ctx context.Context, mountPoints []string, +) error { + return s.repos.WithTx(ctx, func(txCtx context.Context, tx *sql.Tx) error { + for _, dir := range mountPoints { + log.Info("Found a mount point", "path", dir) + + err := s.repos.Snapshots.AddMountPoint(txCtx, tx, s.snapshotID, dir) + if err != nil { + return fmt.Errorf("recording mount point %s: %w", dir, err) + } + } + + return nil + }) +} + +// recordIfMountPoint sets the directory that holds entry, a path the +// walk found, aside to be recorded as a mount point if it is on a +// different device from its parent directory. The walk calls it for each +// entry it finds, and it decides on the first entry in a directory, so a +// directory the walk found no entry in is never recorded. By then the +// walk has listed the directory, which mounts a volume mounted there on +// first access, so the directory and its parent are looked up again: +// before the listing, the directory can be on the automounter's own +// device (a systemd automount) or on its parent's (an autofs map that +// shows its mount points before mounting them). The scanned path is in +// no listing the walk made, so it is skipped as an entry. A directory +// that cannot be looked up then, or whose parent cannot, is not +// recorded, so this snapshot does not stop the prune of a later backup +// that misses its volume. +func (s *Scanner) recordIfMountPoint( + entry, scannedPath string, collector *scanCollector, +) { + dir := filepath.Dir(entry) + + if entry == scannedPath || !collector.firstEntryIn(dir) { + return + } + + dirDevice, ok := s.deviceNumberAt(dir) + if !ok { + return + } + + parentDevice, ok := s.deviceNumberAt(filepath.Dir(dir)) + if ok && dirDevice != parentDevice { + collector.addMountPoint(dir) + } +} + +// deviceNumberAt looks path up now and returns the number of the device +// that holds it, and false when the lookup fails (logged) or gives no +// device number. +func (s *Scanner) deviceNumberAt(path string) (uint64, bool) { + info, err := s.fs.Stat(path) + if err != nil { + log.Warn("Could not look up a directory to check for a mount point", + "path", path, "error", err) + + return 0, false + } + + return s.deviceNumber(info) +} + +// deviceNumberFromStat returns the number of the device that holds the +// file info describes, and false when info carries no stat, as from the +// in-memory test filesystem. +func deviceNumberFromStat(info os.FileInfo) (uint64, bool) { + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return 0, false + } + + return uint64(stat.Dev), true //nolint:unconvert // Dev is an int32 on darwin } // recordNonRegularFile writes a symlink or directory entry to the database diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index a959930..80b032c 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -518,8 +518,8 @@ type CleanupStats struct { // // The cleanup is performed in a specific order to maintain referential integrity: // 1. Delete other snapshots -// 2. Delete orphaned snapshot associations (snapshot_files, snapshot_blobs) -// for deleted snapshots +// 2. Delete orphaned snapshot associations (snapshot_files, snapshot_blobs, +// snapshot_mount_points) for deleted snapshots // 3. Delete orphaned files (not in the current snapshot) // 4. Delete orphaned chunk-to-file mappings (references to deleted files) // 5. Delete orphaned blobs (not in the current snapshot) @@ -948,8 +948,8 @@ func (sm *SnapshotManager) deleteOtherSnapshots( return nil } -// deleteOrphanedSnapshotAssociations deletes snapshot_files and -// snapshot_blobs for deleted snapshots +// deleteOrphanedSnapshotAssociations deletes snapshot_files, +// snapshot_blobs and snapshot_mount_points for deleted snapshots func (sm *SnapshotManager) deleteOrphanedSnapshotAssociations( ctx context.Context, tx *sql.Tx, currentSnapshotID string, ) error { @@ -983,6 +983,19 @@ func (sm *SnapshotManager) deleteOrphanedSnapshotAssociations( log.Debug("[Temp DB Cleanup] Deleted snapshot_blobs associations", "count", rowsAffected) + // Delete the mount points other snapshots recorded + query := "DELETE FROM snapshot_mount_points WHERE snapshot_id != ?" + database.LogSQL("Execute", query, currentSnapshotID) + + result, err = tx.ExecContext(ctx, query, currentSnapshotID) + if err != nil { + return fmt.Errorf("deleting orphaned snapshot_mount_points: %w", err) + } + + rowsAffected, _ = result.RowsAffected() + log.Debug("[Temp DB Cleanup] Deleted snapshot_mount_points rows", + "count", rowsAffected) + return nil } diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go index 38e38d8..b371d72 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -7,12 +7,14 @@ import ( "database/sql" "io" "path/filepath" + "slices" "testing" "github.com/spf13/afero" "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/types" ) const ( @@ -387,6 +389,77 @@ func TestCleanSnapshotDBNonExistentSnapshot(t *testing.T) { } } +// The exported metadata database keeps only the mount points that the +// exported snapshot recorded. See +// https://git.eeqj.de/sneak/vaultik/issues/395. +func TestCleanSnapshotDBKeepsOnlyTheSnapshotsMountPoints(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + dbPath := filepath.Join(t.TempDir(), "export.db") + + db, err := database.New(ctx, dbPath) + if err != nil { + t.Fatalf("failed to create database: %v", err) + } + + repos := database.NewRepositories(db) + + for _, id := range []types.SnapshotID{"exported", "other"} { + err = repos.Snapshots.Create(ctx, nil, &database.Snapshot{ID: id}) + if err != nil { + t.Fatalf("failed to create snapshot: %v", err) + } + + err = repos.Snapshots.AddMountPoint(ctx, nil, id.String(), "/data/"+id.String()) + if err != nil { + t.Fatalf("failed to add mount point: %v", err) + } + } + + err = db.Close() + if err != nil { + t.Fatalf("failed to close database: %v", err) + } + + sm := &SnapshotManager{ + config: &config.Config{ + CompressionLevel: 3, + AgeRecipients: []string{testAgeRecipient}, + }, + fs: afero.NewOsFs(), + } + + _, err = sm.cleanSnapshotDB(ctx, dbPath, "exported") + if err != nil { + t.Fatalf("failed to clean snapshot database: %v", err) + } + + cleaned, err := database.New(ctx, dbPath) + if err != nil { + t.Fatalf("failed to open cleaned database: %v", err) + } + + defer func() { _ = cleaned.Close() }() + + cleanedRepos := database.NewRepositories(cleaned) + + for id, want := range map[string][]string{ + "exported": {"/data/exported"}, + "other": nil, + } { + got, err := cleanedRepos.Snapshots.GetMountPoints(ctx, id) + if err != nil { + t.Fatalf("failed to read mount points: %v", err) + } + + if !slices.Equal(got, want) { + t.Errorf("mount points of %s: got %v, want %v", id, got, want) + } + } +} + // Two creates of one snapshot name back to back start within one second, // the resolution of the timestamp in a snapshot ID. See // https://git.eeqj.de/sneak/vaultik/issues/270. diff --git a/internal/vaultik/fault_injection_test.go b/internal/vaultik/fault_injection_test.go index c3f2f5d..3cccec3 100644 --- a/internal/vaultik/fault_injection_test.go +++ b/internal/vaultik/fault_injection_test.go @@ -679,6 +679,7 @@ func faultScannerFactory( Exclude: params.Exclude, SkipErrors: params.SkipErrors, PreviousSnapshotID: params.PreviousSnapshotID, + DeviceNumber: params.DeviceNumber, }) } } diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 68a44d5..68b7d00 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "sort" "strconv" "strings" @@ -52,6 +53,17 @@ var ErrFilesUnreadable = errors.New("file(s) could not be read") // returns ErrFilesUnreadable instead. var ErrSourcePathEmpty = errors.New("source path(s) were empty") +// ErrVolumeNotMounted is returned when --prune skipped the post-backup +// prune because a directory that an earlier snapshot of the same name +// found as a mount point was not found as one in this run: the volume +// mounted there is not mounted, the run found no entry in it, or the +// directory is no longer backed up. The snapshots are complete and +// kept, so the caller can report it apart from a failed backup. A run +// that also skipped unreadable files or found a configured path empty +// returns ErrFilesUnreadable or ErrSourcePathEmpty instead. +var ErrVolumeNotMounted = errors.New( + "mount point(s) an earlier snapshot recorded were not found") + // listRecentLimit caps how many snapshot rows are fetched from the // local index for listing and purge operations. const listRecentLimit = 10000 @@ -142,7 +154,7 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { return err } - filesUnreadable, emptyPaths, err := v.createNamedSnapshots( + filesUnreadable, emptyPaths, unmountedPaths, err := v.createNamedSnapshots( opts, hostname, snapshotNames) if err != nil { return err @@ -155,8 +167,10 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { } switch { - case opts.Prune && (filesUnreadable > 0 || len(emptyPaths) > 0): - return v.skipPostBackupPrune(filesUnreadable, emptyPaths) + case opts.Prune && (filesUnreadable > 0 || len(emptyPaths) > 0 || + len(unmountedPaths) > 0): + return v.skipPostBackupPrune( + filesUnreadable, emptyPaths, unmountedPaths) case opts.Prune: err = v.runPostBackupPrune(snapshotNames, opts.KeepNewerThan) if err != nil { @@ -169,20 +183,22 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { // createNamedSnapshots creates each named snapshot in turn. It returns // the number of entries --skip-errors skipped because it could not read -// or list them, and each configured path in which the scan found -// nothing, named with its snapshot. +// or list them, each configured path in which the scan found nothing, +// and, under --prune, each directory where an earlier snapshot found a +// volume mounted and this run did not, the paths named with their +// snapshot. func (v *Vaultik) createNamedSnapshots( opts *SnapshotCreateOptions, hostname string, snapshotNames []string, -) (int, []string, error) { +) (int, []string, []string, error) { filesUnreadable := 0 - var emptyPaths []string + var emptyPaths, unmountedPaths []string for snapIdx, snapName := range snapshotNames { stats, err := v.createNamedSnapshot( opts, hostname, snapName, snapIdx+1, len(snapshotNames)) if err != nil { - return 0, nil, err + return 0, nil, nil, err } filesUnreadable += stats.totalFilesUnreadable @@ -190,21 +206,27 @@ func (v *Vaultik) createNamedSnapshots( for _, dir := range stats.emptyPaths { emptyPaths = append(emptyPaths, dir+" of snapshot "+snapName) } + + for _, dir := range stats.unmountedPaths { + unmountedPaths = append(unmountedPaths, + dir+" of snapshot "+snapName) + } } - return filesUnreadable, emptyPaths, nil + return filesUnreadable, emptyPaths, unmountedPaths, nil } // skipPostBackupPrune says why the post-backup prune does not run, naming // every cause, and returns the error the run ends with. An older snapshot // may be the only one that still holds a file this run could not read, -// or what an empty path held. The previous snapshot is no guide: after -// one run with an empty path it is empty too. +// or what an empty path or a volume that is not mounted held. The +// previous snapshot is no guide: after one such run it lacks them too. func (v *Vaultik) skipPostBackupPrune( - filesUnreadable int, emptyPaths []string, + filesUnreadable int, emptyPaths, unmountedPaths []string, ) error { log.Warn("Skipping post-backup prune", - "files_unreadable", filesUnreadable, "empty_paths", emptyPaths) + "files_unreadable", filesUnreadable, "empty_paths", emptyPaths, + "unmounted_paths", unmountedPaths) if len(emptyPaths) > 0 { v.UI.Warningf("Skipped the post-backup prune because nothing was "+ @@ -212,6 +234,17 @@ func (v *Vaultik) skipPostBackupPrune( strings.Join(emptyPaths, ", ")) } + if len(unmountedPaths) > 0 { + v.UI.Warningf("Skipped the post-backup prune because this backup "+ + "did not find a mount point at %s, where an earlier snapshot "+ + "found one: the volume is not mounted, this backup found no "+ + "entry in it, or the directory is no longer backed up. Older "+ + "snapshots are kept. Mount the volume again, or, if that is on "+ + "purpose, remove the older snapshots by hand with "+ + "'vaultik snapshot purge'.", + strings.Join(unmountedPaths, ", ")) + } + if filesUnreadable > 0 { v.UI.Warningf("Skipped the post-backup prune because %d file(s) "+ "could not be read; older snapshots are kept.", filesUnreadable) @@ -219,7 +252,11 @@ func (v *Vaultik) skipPostBackupPrune( return fmt.Errorf("%d %w", filesUnreadable, ErrFilesUnreadable) } - return fmt.Errorf("%d %w", len(emptyPaths), ErrSourcePathEmpty) + if len(emptyPaths) > 0 { + return fmt.Errorf("%d %w", len(emptyPaths), ErrSourcePathEmpty) + } + + return fmt.Errorf("%d %w", len(unmountedPaths), ErrVolumeNotMounted) } // finishCreateSnapshot ends a run whose snapshots are all complete and @@ -329,6 +366,10 @@ type snapshotStats struct { // The configured paths in which the scan found nothing. emptyPaths []string + // Under --prune, the directories where an earlier snapshot of the + // same name found a volume mounted and this one did not. + unmountedPaths []string + // The sizes of all blobs the snapshot references, set by // finalizeSnapshotMetadata once snapshot_blobs is populated. blobSize int64 @@ -394,9 +435,57 @@ func (v *Vaultik) createNamedSnapshot( v.printSnapshotSummary(snapshotID, snapshotStartTime, stats) + if opts.Prune { + stats.unmountedPaths, err = v.findUnmountedPaths(snapName, snapshotID) + if err != nil { + return nil, err + } + } + return stats, nil } +// findUnmountedPaths returns each directory that an earlier snapshot +// named snapName in the local index recorded as a mount point and +// snapshot snapshotID did not, as when the volume mounted there is not +// mounted. +func (v *Vaultik) findUnmountedPaths( + snapName, snapshotID string, +) ([]string, error) { + found, err := v.Repositories.Snapshots.GetMountPoints(v.ctx, snapshotID) + if err != nil { + return nil, err + } + + snapshots, err := v.Repositories.Snapshots.ListRecent(v.ctx, listRecentLimit) + if err != nil { + return nil, fmt.Errorf("listing snapshots: %w", err) + } + + var unmounted []string + + for _, s := range snapshots { + if s.ID.String() == snapshotID || + parseSnapshotName(s.ID.String(), s.Hostname.String()) != snapName { + continue + } + + recorded, err := v.Repositories.Snapshots.GetMountPoints( + v.ctx, s.ID.String()) + if err != nil { + return nil, err + } + + for _, dir := range recorded { + if !slices.Contains(found, dir) && !slices.Contains(unmounted, dir) { + unmounted = append(unmounted, dir) + } + } + } + + return unmounted, nil +} + // previousSnapshotID returns the ID of the most recent completed snapshot // named snapName in the local index, or "" when there is none. func (v *Vaultik) previousSnapshotID(snapName string) (string, error) { diff --git a/internal/vaultik/snapshot_prune_test.go b/internal/vaultik/snapshot_prune_test.go index 035dd5a..e0e2e49 100644 --- a/internal/vaultik/snapshot_prune_test.go +++ b/internal/vaultik/snapshot_prune_test.go @@ -4,12 +4,15 @@ import ( "context" "os" "path/filepath" + "syscall" "testing" + "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -259,3 +262,152 @@ func TestBackupWithNoEmptySourcePathPrunes(t *testing.T) { }) } } + +// automountFs is the real filesystem with a volume at volumeDir that is +// mounted on first access, as by an autofs map that shows its mount +// points before mounting them: listing volumeDir mounts the volume or, +// while cannotMount, fails with "no such file or directory". +type automountFs struct { + afero.OsFs + + volumeDir string + cannotMount bool + mounted bool +} + +//nolint:ireturn // afero.Fs.Open is defined to return the interface. +func (f *automountFs) Open(name string) (afero.File, error) { + if name == f.volumeDir && f.cannotMount { + return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT} + } + + if name == f.volumeDir { + f.mounted = true + } + + return f.OsFs.Open(name) +} + +// A backup under --prune in which a volume that an earlier snapshot found +// mounted below the configured path is missing does not prune: run after +// run, the snapshot that holds the volume's files is kept with everything +// it stored, and the run fails. Once the volume is back, the prune runs. +// The volume is mounted on first access and every backup starts with it +// not mounted, so its directory is on its parent's device until the walk +// lists it. While the volume is missing, its directory is left empty, or +// listing it fails with "no such file or directory", as when an autofs +// volume cannot be mounted, which the walk counts as a directory removed +// during the backup. See https://git.eeqj.de/sneak/vaultik/issues/395. +func TestBackupWithVolumeNotMountedDoesNotPrune(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + tests := []struct { + name string + listingFails bool + }{ + {name: "directory left empty", listingFails: false}, + {name: "listing fails", listingFails: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + backUpWithVolumeNotMounted(t, tt.listingFails) + }) + } +} + +// backUpWithVolumeNotMounted runs the backups of +// TestBackupWithVolumeNotMountedDoesNotPrune. While the volume is +// missing, listing its directory fails if listingFails; otherwise the +// directory is empty. +func backUpWithVolumeNotMounted(t *testing.T, listingFails bool) { + t.Helper() + + // volume is the directory, below the configured path, where the + // volume is mounted. + const ( + snapshotName = "data" + volume = "nas" + ) + + ctx := context.Background() + env := newDeletedCountEnv(t, map[string][]byte{ + volume + "/a.txt": []byte("file a"), + "notes.txt": []byte("notes"), + }) + env.setSnapshot(snapshotName, "") + prune := &vaultik.SnapshotCreateOptions{ + Prune: true, Snapshots: []string{snapshotName}, + } + + // The volume's directory is on the volume's device, 2, while the + // volume is mounted. Everything else is on device 1. + volumeDir := filepath.Join(env.src, volume) + fs := &automountFs{volumeDir: volumeDir} + newScanner := env.v.ScannerFactory + env.v.ScannerFactory = func(params snapshot.ScannerParams) *snapshot.Scanner { + fs.mounted = false + params.Fs = fs + params.DeviceNumber = func(info os.FileInfo) (uint64, bool) { + if info.Name() == volume && fs.mounted { + return 2, true + } + + return 1, true + } + + return newScanner(params) + } + + env.backUp(t, snapshotName) + + firstID := localSnapshotID(ctx, t, env.v.Repositories, snapshotName) + stored, err := env.v.Storage.List(ctx, "") + require.NoError(t, err) + + // The volume goes missing. + fs.cannotMount = listingFails + + if !listingFails { + require.NoError(t, os.RemoveAll(volumeDir)) + require.NoError(t, os.Mkdir(volumeDir, 0o750)) + } + + for range 2 { + env.out.Reset() + + err := env.v.CreateSnapshot(prune) + require.ErrorIs(t, err, vaultik.ErrVolumeNotMounted) + assert.Contains(t, env.out.String(), + "did not find a mount point at "+volumeDir+" of snapshot "+snapshotName) + assert.Contains(t, env.out.String(), "'vaultik snapshot purge'") + assert.NotContains(t, env.out.String(), "Running post-backup prune.") + } + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 3) + assert.Equal(t, firstID, snapshots[2].ID.String(), + "the snapshot that holds the volume's files is kept") + + for _, key := range stored { + _, err := env.v.Storage.Stat(ctx, key) + require.NoError(t, err, "%s is kept", key) + } + + // The volume is back. + fs.cannotMount = false + + require.NoError(t, os.WriteFile( + filepath.Join(volumeDir, "a.txt"), []byte("file a"), 0o600)) + require.NoError(t, env.v.CreateSnapshot(prune)) + + snapshots, err = env.v.Repositories.Snapshots.ListRecent( + ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1, "the older snapshots are pruned") +} From 13a35a986a7ec3f71233071095e18f412cc49a54 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Mon, 9 Nov 2026 07:43:24 +0100 Subject: [PATCH 097/121] Correct two false doc comments (closes #403) Two doc comments described behaviour that no longer exists. The comment on `ExportSnapshotMetadata` described an SQL dump uploaded under `snapshots/`; it now lists the steps the function performs and the two keys it writes. The comment on `EnsureStorageBinding` named `vaultik database purge`; the command is `vaultik database delete`. Comments only. Model: opus-5-5 --- internal/snapshot/snapshot.go | 12 +++++++----- internal/vaultik/storage_bind.go | 2 +- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 80b032c..80c764e 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -271,16 +271,18 @@ func (sm *SnapshotManager) CompleteSnapshot( return sm.MarkSnapshotComplete(ctx, snapshotID) } -// ExportSnapshotMetadata exports snapshot metadata to S3 +// ExportSnapshotMetadata exports snapshot metadata to the backup destination store // // This method executes the complete snapshot metadata export process: // 1. Creates a temporary directory for working files // 2. Copies the main database to preserve its state // 3. Cleans the copy to contain only current snapshot data -// 4. Dumps the cleaned database to SQL -// 5. Compresses the SQL dump with zstd -// 6. Encrypts the compressed data with age (always; recipients are required) -// 7. Uploads to S3 at: snapshots/{snapshot-id}.sql.zst[.age] +// 4. Vacuums the copy to remove the deleted data +// 5. Compresses the copy with zstd +// 6. Encrypts the compressed copy with age (always; recipients are required) +// 7. Builds the blob manifest from the copy, compressed but not encrypted +// 8. Uploads the database to metadata/{remote-key}/db.zst.age +// 9. Uploads the manifest to metadata/{remote-key}/manifest.json.zst // // The only caller (finalizeSnapshotMetadata) does not close the main database // before calling this method: the index is copied at dbPath while it is still diff --git a/internal/vaultik/storage_bind.go b/internal/vaultik/storage_bind.go index d72ae34..c3dcc83 100644 --- a/internal/vaultik/storage_bind.go +++ b/internal/vaultik/storage_bind.go @@ -30,7 +30,7 @@ var errStorageBindingMismatch = errors.New( // nothing and return nil. // - When the two differ, refuse with an error that tells the user // how to recover (revert the config, or run `vaultik database -// purge` to discard the local index and rebuild against the new +// delete` to discard the local index and rebuild against the new // destination on the next backup). // // Read-only inspection commands (remote info, snapshot list, etc.) From 5a0da6da12a5c1e5971f688c80c974152b6704db Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 10 Nov 2026 21:52:03 +0100 Subject: [PATCH 098/121] Write the apps snapshot in config init only on macOS (closes #408) The default config backed up /Applications on every system. That directory exists only on macOS, so on Linux the first snapshot create stopped on the missing path. config init now writes the apps snapshot only when runtime.GOOS is darwin; the macOS file is unchanged. Model: opus-5-5 (implementation, review); opus-5-5 (merge) --- README.md | 4 ++-- TODO.md | 5 ++++ internal/cli/config.go | 31 ++++++++++++++++++++---- internal/cli/config_test.go | 48 +++++++++++++++++++++++++++++++------ 4 files changed, 75 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index f83d065..c436e22 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,8 @@ mkdir /Volumes/usbstick/mybackup # (System Settings → Privacy & Security → Full Disk Access), otherwise # the backup will abort with a permission error on protected directories -# run your first backup (the default config backs up ~ and /Applications -# with sensible excludes) +# run your first backup (the default config backs up ~, and /Applications +# on macOS only, with sensible excludes) vaultik snapshot create # see what you have diff --git a/TODO.md b/TODO.md index c32824f..64f0e47 100644 --- a/TODO.md +++ b/TODO.md @@ -24,6 +24,11 @@ owner's; a `v*` tag runs the release build in # Completed Steps +- 2026-11-10: Made `config init` write the `apps` snapshot, which backs + up `/Applications`, only on macOS + ([issue #408](https://git.eeqj.de/sneak/vaultik/issues/408)). On + Linux the first `snapshot create` stopped on the missing directory. + - 2026-10-15: Stopped `snapshot create --prune` pruning after a backup in which a volume mounted below a configured path in an earlier snapshot of the same name was not mounted diff --git a/internal/cli/config.go b/internal/cli/config.go index 2a18fc1..96976aa 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -8,6 +8,7 @@ import ( "os/exec" "path/filepath" "reflect" + "runtime" "slices" "strconv" "strings" @@ -30,7 +31,7 @@ const configSetArgs = 2 // parent config dirs (e.g. ~/.config) are conventionally traversable. const configDirMode = 0o755 -// configYAMLIndent matches the 2-space indentation of defaultConfigTemplate, +// configYAMLIndent matches the 2-space indentation of the default config, // so `config set` writes the file back with the same indentation rather than // yaml.Marshal's 4-space default. const configYAMLIndent = 2 @@ -50,7 +51,22 @@ var ( "so the file was not changed") ) -const defaultConfigTemplate = `# vaultik configuration +// macOS is the value of runtime.GOOS on macOS. +const macOS = "darwin" + +// defaultConfigText returns the file `config init` writes on the operating +// system goos, named as runtime.GOOS names it. Only macOS gets the apps +// snapshot, since /Applications exists nowhere else. +func defaultConfigText(goos string) string { + if goos == macOS { + return defaultConfigHead + appsSnapshotConfig + defaultConfigTail + } + + return defaultConfigHead + defaultConfigTail +} + +// defaultConfigHead is the default config up to the end of the home snapshot. +const defaultConfigHead = `# vaultik configuration # Documentation: https://sneak.berlin/go/vaultik # ─── REQUIRED ──────────────────────────────────────────────────────────────── @@ -168,7 +184,10 @@ snapshots: - "/Movies/ProxyMedia" - "/Music/iTunes/Album Artwork" - "/Pictures/iPod Photo Cache" +` +// appsSnapshotConfig is the apps snapshot of the default config. +const appsSnapshotConfig = ` # Third-party applications. OS-provided apps live in /System/Applications # on modern macOS and are never in /Applications, but Apple-installed # App Store apps (Safari, GarageBand, iWork, iMovie) are excluded since @@ -189,7 +208,10 @@ snapshots: - "/Steam.app" - "/VirtualBox.app" - "/Utilities/Adobe Installers" +` +// defaultConfigTail is the default config after the snapshots. +const defaultConfigTail = ` # Storage backend (pick ONE of the three forms below). # # S3-compatible: @@ -311,7 +333,8 @@ on macOS, ~/.config/ on Linux, /etc/vaultik/ as root).`, return fmt.Errorf("creating config directory %s: %w", dir, err) } - err = os.WriteFile(path, []byte(defaultConfigTemplate), configFileMode) + err = os.WriteFile(path, []byte(defaultConfigText(runtime.GOOS)), + configFileMode) if err != nil { return fmt.Errorf("writing config file: %w", err) } @@ -560,7 +583,7 @@ func yamlPathOnly(root *yaml.Node, keys []string) (*yaml.Node, error) { } // marshalConfigYAML renders a config document tree with 2-space indentation, -// matching defaultConfigTemplate. yaml.Marshal defaults to 4 spaces, which +// matching the default config. yaml.Marshal defaults to 4 spaces, which // would reindent the whole file on the first `config set` despite the promise // to preserve formatting. func marshalConfigYAML(root *yaml.Node) ([]byte, error) { diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go index 7dccfa0..7f7d390 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -13,14 +13,15 @@ import ( "sneak.berlin/go/vaultik/internal/ui" ) -// TestDefaultConfigTemplateParses ensures the init template is valid YAML -// that unmarshals into the Config struct with the expected snapshots. -func TestDefaultConfigTemplateParses(t *testing.T) { +// TestDefaultConfigParsesOnMacOS ensures the config `config init` writes on +// macOS is valid YAML that unmarshals into the Config struct with the +// expected snapshots. +func TestDefaultConfigParsesOnMacOS(t *testing.T) { t.Parallel() var cfg config.Config - err := yaml.Unmarshal([]byte(defaultConfigTemplate), &cfg) + err := yaml.Unmarshal([]byte(defaultConfigText("darwin")), &cfg) if err != nil { t.Fatalf("default config template is not valid YAML: %v", err) } @@ -58,6 +59,39 @@ func TestDefaultConfigTemplateParses(t *testing.T) { } } +// TestDefaultConfigOnLinux checks that the config `config init` writes on +// Linux loads with its home snapshot and without the apps snapshot, whose +// /Applications exists only on macOS. +func TestDefaultConfigOnLinux(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(defaultConfigText("linux")), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, "storage_url", "file:///mnt/backups") + if err != nil { + t.Fatalf("config set storage_url: %v", err) + } + + cfg, err := config.Load(path) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + + if _, ok := cfg.Snapshots["home"]; !ok { + t.Error("expected 'home' snapshot in the Linux default config") + } + + if _, ok := cfg.Snapshots["apps"]; ok { + t.Error("the Linux default config should have no 'apps' snapshot") + } +} + // testRecipient is a valid age public key. const testRecipient = "age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj" @@ -71,7 +105,7 @@ func TestConfigSetRecipientOnFreshConfig(t *testing.T) { path := filepath.Join(t.TempDir(), "config.yml") - err := os.WriteFile(path, []byte(defaultConfigTemplate), configFileMode) + err := os.WriteFile(path, []byte(defaultConfigText(macOS)), configFileMode) if err != nil { t.Fatalf("write config: %v", err) } @@ -220,7 +254,7 @@ func TestConfigSetKeepsFileThatWouldNotLoad(t *testing.T) { {levelReference, "blob_size_limit", "1MB", "blob_size_limit must be at least"}, // The type check on a config that does not load yet. - {defaultConfigTemplate, "snapshots.apps.paths", "/srv", + {defaultConfigText(macOS), "snapshots.apps.paths", "/srv", "into []string"}, // The type check on a config that cannot be read here. {configWithUnsetReference, "snapshots.home.paths", "/x", @@ -380,7 +414,7 @@ func loadAfterConfigSet(t *testing.T, key, value string) *config.Config { path := filepath.Join(t.TempDir(), "config.yml") - err := os.WriteFile(path, []byte(defaultConfigTemplate), configFileMode) + err := os.WriteFile(path, []byte(defaultConfigText(macOS)), configFileMode) if err != nil { t.Fatalf("write config: %v", err) } From 4418dc3e97b6af1b7303fb0a3bee7cdca87a049e Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 10 Nov 2026 22:12:46 +0100 Subject: [PATCH 099/121] Print remote info and verify status lines through internal/ui (closes #410) The status and progress lines of remote info and snapshot verify (shallow and deep) were written with stdoutf, so they had no marker and no color, unlike every other command's. They now go through Beginf, Completef and Progressf, as the README's output style section says. The reports stay plain, and --quiet and --json still drop these lines. Model: opus-5-5 --- TODO.md | 6 ++++ internal/vaultik/info.go | 6 ++-- internal/vaultik/remote_info_test.go | 22 ++++++++++++ internal/vaultik/snapshot.go | 2 +- internal/vaultik/verify.go | 20 +++++------ internal/vaultik/verify_quiet_test.go | 48 +++++++++++++++++++++++++++ 6 files changed, 90 insertions(+), 14 deletions(-) diff --git a/TODO.md b/TODO.md index 64f0e47..69d31aa 100644 --- a/TODO.md +++ b/TODO.md @@ -24,6 +24,12 @@ owner's; a `v*` tag runs the release build in # Completed Steps +- 2026-11-10: Printed the status and progress lines of `remote info` + and `snapshot verify` through `internal/ui`, with its marker and + color, as the README describes + ([issue #410](https://git.eeqj.de/sneak/vaultik/issues/410)). Their + reports stay plain. + - 2026-11-10: Made `config init` write the `apps` snapshot, which backs up `/Applications`, only on macOS ([issue #408](https://git.eeqj.de/sneak/vaultik/issues/408)). On diff --git a/internal/vaultik/info.go b/internal/vaultik/info.go index 9cd034f..c4cc18c 100644 --- a/internal/vaultik/info.go +++ b/internal/vaultik/info.go @@ -246,7 +246,7 @@ func (v *Vaultik) RemoteInfo(jsonOutput bool) error { v.stdoutf("Type: %s\n", storageInfo.Type) v.stdoutf("Location: %s\n", storageInfo.Location) v.printlnStdout() - v.stdoutf("Scanning snapshot metadata...\n") + v.UI.Beginf("Scanning snapshot metadata...") } snapshotMetadata, snapshotIDs, skippedManifestCount, err := v.collectSnapshotMetadata() @@ -265,7 +265,7 @@ func (v *Vaultik) RemoteInfo(jsonOutput bool) error { } } - v.stdoutf("Downloading %d manifest(s)...\n", manifestCount) + v.UI.Beginf("Downloading %d manifest(s)...", manifestCount) } referencedBlobs, unreadableManifests := v.collectReferencedBlobsFromManifests( @@ -447,7 +447,7 @@ func (v *Vaultik) scanRemoteBlobStorage( result *RemoteInfoResult, referencedBlobs map[string]int64, showText bool, ) error { if showText { - v.stdoutf("Scanning blobs...\n") + v.UI.Beginf("Scanning blobs...") } // Use prune's listing, so a file under blobs/ that prune would never diff --git a/internal/vaultik/remote_info_test.go b/internal/vaultik/remote_info_test.go index 76bac72..5d68a03 100644 --- a/internal/vaultik/remote_info_test.go +++ b/internal/vaultik/remote_info_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/require" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/ui" ) // testBlobHashB is a blob that the manifest written by addRemote does @@ -259,3 +260,24 @@ func TestRemoteInfo_DirectoryWithoutManifestLeavesOrphansKnown(t *testing.T) { assert.NotContains(t, doc, "unreadable_manifests") assert.NotContains(t, doc, "skipped_manifest_count") } + +// TestRemoteInfo_StatusLineUsesUIMarker checks that the remote info +// status lines go through internal/ui: marker-prefixed, and silenced by +// --quiet. +func TestRemoteInfo_StatusLineUsesUIMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + env.addRemote(t, listRemoteID, time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + + const statusLine = ui.Marker + " Scanning snapshot metadata...\n" + + require.NoError(t, env.v.RemoteInfo(false)) + assert.Contains(t, env.stdout.String(), statusLine) + + env.stdout.Reset() + env.v.UI.SetQuiet(true) + require.NoError(t, env.v.RemoteInfo(false)) + assert.NotContains(t, env.stdout.String(), "Scanning snapshot metadata") +} diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 68b7d00..663656e 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -1019,7 +1019,7 @@ func (v *Vaultik) VerifySnapshotWithOptions( v.printlnStdout() // Check each blob is present with the size the manifest records. - v.stdoutf("Checking blob presence and sizes...\n") + v.UI.Beginf("Checking blob presence and sizes...") } v.checkSnapshotDatabase(remoteKey, result) diff --git a/internal/vaultik/verify.go b/internal/vaultik/verify.go index 6c88d93..ba6c2d3 100644 --- a/internal/vaultik/verify.go +++ b/internal/vaultik/verify.go @@ -190,7 +190,7 @@ func (v *Vaultik) loadVerificationData( log.Info("Downloading manifest", "remote_key", remoteKey) if !opts.JSON && !v.UI.Quiet() { - v.stdoutf("Downloading manifest...\n") + v.UI.Beginf("Downloading manifest...") } manifest, err := v.downloadManifestByKey(remoteKey) @@ -205,9 +205,9 @@ func (v *Vaultik) loadVerificationData( "manifest_total_size", ubytes(manifest.TotalCompressedSize)) if !opts.JSON && !v.UI.Quiet() { - v.stdoutf("Manifest loaded: %d blobs (%s)\n", + v.UI.Completef("Manifest loaded: %d blobs (%s)", manifest.BlobCount, ubytes(manifest.TotalCompressedSize)) - v.stdoutf("Downloading and decrypting database...\n") + v.UI.Beginf("Downloading and decrypting database...") } tdb, err := v.downloadVerifiedSnapshotDB( @@ -235,7 +235,7 @@ func (v *Vaultik) loadVerificationData( "db_total_size", ubytes(dbTotalSize)) if !opts.JSON && !v.UI.Quiet() { - v.stdoutf("Database loaded: %d blobs (%s)\n", + v.UI.Completef("Database loaded: %d blobs (%s)", len(dbBlobs), ubytes(dbTotalSize)) } @@ -295,7 +295,7 @@ func (v *Vaultik) runVerificationSteps( identities []age.Identity, ) error { if !opts.JSON && !v.UI.Quiet() { - v.stdoutf("Verifying manifest against database...\n") + v.UI.Beginf("Verifying manifest against database...") } err := v.verifyManifestAgainstDatabase(manifest, dbBlobs) @@ -304,8 +304,8 @@ func (v *Vaultik) runVerificationSteps( } if !opts.JSON && !v.UI.Quiet() { - v.stdoutf("Manifest verified.\n") - v.stdoutf("Checking blob existence in remote storage...\n") + v.UI.Completef("Manifest verified.") + v.UI.Beginf("Checking blob existence in remote storage...") } err = v.verifyBlobExistenceFromDB(dbBlobs, result) @@ -314,8 +314,8 @@ func (v *Vaultik) runVerificationSteps( } if !opts.JSON && !v.UI.Quiet() { - v.stdoutf("All blobs exist.\n") - v.stdoutf("Downloading and verifying blob contents (%d blobs, %s)...\n", + v.UI.Completef("All blobs exist.") + v.UI.Beginf("Downloading and verifying blob contents (%d blobs, %s)...", len(dbBlobs), ubytes(totalSize)) } @@ -790,7 +790,7 @@ func (v *Vaultik) performDeepVerificationFromDB( ) if !opts.JSON && !v.UI.Quiet() { - v.stdoutf(" Verified %d/%d blobs (%d remaining) - %s/%s - elapsed %s, eta %s\n", + v.UI.Progressf("Verified %d/%d blobs (%d remaining) - %s/%s - elapsed %s, eta %s", i+1, len(blobs), remaining, ubytes(bytesProcessed), ubytes(totalBytesExpected), diff --git a/internal/vaultik/verify_quiet_test.go b/internal/vaultik/verify_quiet_test.go index c8dd630..bc3b26e 100644 --- a/internal/vaultik/verify_quiet_test.go +++ b/internal/vaultik/verify_quiet_test.go @@ -100,3 +100,51 @@ func TestVerify_QuietSuppressesReport(t *testing.T) { require.Empty(t, stdout.String(), "a failed verify must write no report under --quiet") } + +// TestVerify_DeepStatusLineUsesUIMarker checks that the deep verify +// status lines go through internal/ui: marker-prefixed, and silenced by +// --quiet. +func TestVerify_DeepStatusLineUsesUIMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + storeDir := t.TempDir() + dbPath := filepath.Join(tempDir, "index.sqlite") + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, "data.bin"), + bytesPattern("marker-", 64*1024), 0o644)) + + ctx := context.Background() + + cfg, storer, snapshotID := runFileStorageBackup( + ctx, t, fs, dataDir, storeDir, dbPath, 32*1024, 128*1024) + + var stdout bytes.Buffer + + v := &vaultik.Vaultik{ + Config: cfg, + Storage: storer, + Fs: fs, + Stdout: &stdout, + Stderr: io.Discard, + UI: ui.NewWithColor(&stdout, false), + } + v.SetContext(ctx) + + opts := &vaultik.VerifyOptions{Deep: true} + + require.NoError(t, v.VerifySnapshotWithOptions(snapshotID, opts)) + require.Contains(t, stdout.String(), + "\n"+ui.Marker+" Downloading manifest...\n") + + stdout.Reset() + v.UI.SetQuiet(true) + require.NoError(t, v.VerifySnapshotWithOptions(snapshotID, opts)) + require.NotContains(t, stdout.String(), "Downloading manifest") +} From 9236c0727c4e51b46ef88e813467d88c04430042 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 10 Nov 2026 22:34:51 +0100 Subject: [PATCH 100/121] Label the commit date "commit date" in version and banner (closes #409) vaultik version printed globals.CommitDate, the date of the commit the binary was built from, labelled "build date", and the startup banner called it "built on". Both now say "commit date". The test sets Commit and CommitDate to distinct values and checks the label, padding and value of every report line. Model: opus-5-5 --- internal/cli/app.go | 2 +- internal/cli/entry_banner_test.go | 30 +++++++++++++++++++++++++ internal/cli/version.go | 14 ++++++------ internal/cli/version_test.go | 37 +++++++++++++++++++++++++++++++ 4 files changed, 75 insertions(+), 8 deletions(-) diff --git a/internal/cli/app.go b/internal/cli/app.go index 5b4fb50..bd54f1d 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -90,7 +90,7 @@ func setupGlobals( // blank line. Used both from the fx hook (for subcommand invocations) and // from the root cobra Run handler (for `vaultik` with no subcommand). func writeStartupBanner(w *ui.Writer, startTime time.Time, shortCommit string) { - w.Bannerf("%s %s by %s (commit %s, built on %s) starting up at %s.", + w.Bannerf("%s %s by %s (commit %s, commit date %s) starting up at %s.", globals.Appname, globals.Version, globals.Author, shortCommit, globals.CommitDate, startTime.Format(time.RFC3339)) diff --git a/internal/cli/entry_banner_test.go b/internal/cli/entry_banner_test.go index 26015d5..412b5d0 100644 --- a/internal/cli/entry_banner_test.go +++ b/internal/cli/entry_banner_test.go @@ -13,6 +13,7 @@ import ( "github.com/adrg/xdg" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/globals" ) // Command words and flags used to build argument vectors below. They are @@ -112,6 +113,35 @@ func TestBannerStillPrintedWithoutSuppressingFlag(t *testing.T) { } } +// TestBannerLabelsCommitDate checks that the banner prints the commit +// and the commit date, each after its own label. Commit and CommitDate +// get different values, so printing the wrong one fails. +// +//nolint:paralleltest // sets globals.Commit and globals.CommitDate +func TestBannerLabelsCommitDate(t *testing.T) { + const ( + commit = "abc1234" + commitDate = "2026-11-09" + ) + + previousCommit, previousCommitDate := globals.Commit, globals.CommitDate + + t.Cleanup(func() { + globals.Commit = previousCommit + globals.CommitDate = previousCommitDate + }) + + globals.Commit = commit + globals.CommitDate = commitDate + + var banner bytes.Buffer + + emitStartupBanner(nil, &banner) + + assert.Contains(t, banner.String(), + "(commit "+commit+", commit date "+commitDate+")") +} + // TestBannerSuppressedInArgs covers the suppression scan directly, // including the flags that suppressed the banner before --json joined // them, so that adding --json cannot regress them. diff --git a/internal/cli/version.go b/internal/cli/version.go index 0307060..400d6eb 100644 --- a/internal/cli/version.go +++ b/internal/cli/version.go @@ -37,13 +37,13 @@ func writeVersion(out *ui.Writer) { w := out.Out() _, _ = fmt.Fprintf(w, "vaultik %s\n", globals.Version) - _, _ = fmt.Fprintf(w, " commit: %s\n", globals.Commit) - _, _ = fmt.Fprintf(w, " build date: %s\n", globals.CommitDate) - _, _ = fmt.Fprintf(w, " go: %s\n", runtime.Version()) - _, _ = fmt.Fprintf(w, " os/arch: %s/%s\n", runtime.GOOS, runtime.GOARCH) - _, _ = fmt.Fprintf(w, " author: %s\n", globals.Author) - _, _ = fmt.Fprintf(w, " homepage: %s\n", globals.Homepage) - _, _ = fmt.Fprintf(w, " license: %s\n", globals.License) + _, _ = fmt.Fprintf(w, " commit: %s\n", globals.Commit) + _, _ = fmt.Fprintf(w, " commit date: %s\n", globals.CommitDate) + _, _ = fmt.Fprintf(w, " go: %s\n", runtime.Version()) + _, _ = fmt.Fprintf(w, " os/arch: %s/%s\n", runtime.GOOS, runtime.GOARCH) + _, _ = fmt.Fprintf(w, " author: %s\n", globals.Author) + _, _ = fmt.Fprintf(w, " homepage: %s\n", globals.Homepage) + _, _ = fmt.Fprintf(w, " license: %s\n", globals.License) if globals.IsDevVersion(globals.Version) { _, _ = fmt.Fprintln(w) diff --git a/internal/cli/version_test.go b/internal/cli/version_test.go index 7068f9d..3215029 100644 --- a/internal/cli/version_test.go +++ b/internal/cli/version_test.go @@ -2,6 +2,7 @@ package cli_test import ( "bytes" + "runtime" "strings" "testing" @@ -49,6 +50,42 @@ func TestVersionCommandReportsBuildVersion(t *testing.T) { } } +// TestVersionCommandReportLines checks the label, padding and value of +// every line of the report. Commit and CommitDate get different values, +// so a line that prints the wrong one fails. +// +//nolint:paralleltest // sets globals.Commit and globals.CommitDate +func TestVersionCommandReportLines(t *testing.T) { + const ( + commit = "abc1234" + commitDate = "2026-11-09" + ) + + previousCommit, previousCommitDate := globals.Commit, globals.CommitDate + + t.Cleanup(func() { + globals.Commit = previousCommit + globals.CommitDate = previousCommitDate + }) + + globals.Commit = commit + globals.CommitDate = commitDate + + want := "vaultik " + globals.Version + "\n" + + " commit: " + commit + "\n" + + " commit date: " + commitDate + "\n" + + " go: " + runtime.Version() + "\n" + + " os/arch: " + runtime.GOOS + "/" + runtime.GOARCH + "\n" + + " author: " + globals.Author + "\n" + + " homepage: " + globals.Homepage + "\n" + + " license: " + globals.License + "\n" + + out := runVersionCommand(t) + if !strings.HasPrefix(out, want) { + t.Errorf("report:\n%s\nwant it to start with:\n%s", out, want) + } +} + // TestVersionCommandFlagsDevelopmentBuild is the regression test for // the thing this command exists to prevent: a build that is not a // release must say so. The notice used to be gated on the version From aae7fa17aebc3dca543df5a3cda40e997f03b334 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 10 Nov 2026 23:22:31 +0100 Subject: [PATCH 101/121] Format Markdown with prettier and move documents out of the root (closes #411) REPO_POLICIES.md names prettier as the Markdown formatter and keeps documents out of the root. script/fmt and script/fmt-check now run prettier over all Markdown (4-space indents, proseWrap always) besides gofmt, with node and yarn installed by script/bootstrap as in sneak/prompts. All Markdown is reformatted with no text change. ARCHITECTURE.md and TODO.md move to docs/, config.example.yml to configs/, and every reference follows. Model: opus-5-5 --- .prettierignore | 2 + .prettierrc | 4 + AGENTS.md | 147 +- README.md | 1345 ++++++++--------- TODO.md | 1331 ---------------- .../config.example.yml | 0 ARCHITECTURE.md => docs/ARCHITECTURE.md | 157 +- docs/DATAMODEL.md | 209 ++- docs/REPOSTRUCTURE.md | 284 +++- docs/TODO.md | 1224 +++++++++++++++ internal/config/config.go | 2 +- internal/config/config_test.go | 8 +- package.json | 5 + script/bootstrap | 81 +- script/fmt | 20 + script/fmt-check | 22 +- yarn.lock | 8 + 17 files changed, 2592 insertions(+), 2257 deletions(-) create mode 100644 .prettierignore create mode 100644 .prettierrc delete mode 100644 TODO.md rename config.example.yml => configs/config.example.yml (100%) rename ARCHITECTURE.md => docs/ARCHITECTURE.md (83%) create mode 100644 docs/TODO.md create mode 100644 package.json create mode 100644 yarn.lock diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..23d67fc --- /dev/null +++ b/.prettierignore @@ -0,0 +1,2 @@ +node_modules/ +yarn.lock diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..8af31cd --- /dev/null +++ b/.prettierrc @@ -0,0 +1,4 @@ +{ + "tabWidth": 4, + "proseWrap": "always" +} diff --git a/AGENTS.md b/AGENTS.md index 2f253ae..2d82840 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,127 +4,122 @@ Version: 2025-06-08 # Instructions and Contextual Information -* Be direct, robotic, expert, accurate, and professional. +- Be direct, robotic, expert, accurate, and professional. -* Do not butter me up or kiss my ass. +- Do not butter me up or kiss my ass. -* Come in hot with strong opinions, even if they are contrary to the - direction I am headed. +- Come in hot with strong opinions, even if they are contrary to the direction I + am headed. -* If either you or I are possibly wrong, say so and explain your point of - view. +- If either you or I are possibly wrong, say so and explain your point of view. -* Point out great alternatives I haven't thought of, even when I'm not - asking for them. +- Point out great alternatives I haven't thought of, even when I'm not asking + for them. -* Treat me like the world's leading expert in every situation and every +- Treat me like the world's leading expert in every situation and every conversation, and deliver the absolute best recommendations. -* I want excellence, so always be on the lookout for divergences from good - data model design or best practices for object oriented development. +- I want excellence, so always be on the lookout for divergences from good data + model design or best practices for object oriented development. -* IMPORTANT: This is production code, not a research or teaching exercise. +- IMPORTANT: This is production code, not a research or teaching exercise. Deliver professional-level results, not prototypes. -* Please read and understand the `README.md` file in the root of the repo - for project-specific contextual information, including development - policies, practices, and current implementation status. +- Please read and understand the `README.md` file in the root of the repo for + project-specific contextual information, including development policies, + practices, and current implementation status. -* Be proactive in suggesting improvements or refactorings in places where we +- Be proactive in suggesting improvements or refactorings in places where we diverge from best practices for clean, modular, maintainable code. # Policies 1. Before committing, tests must pass (`make test`), linting must pass - (`make lint`), and code must be formatted (`make fmt`). For go, those + (`make lint`), and code must be formatted (`make fmt`). For go, those makefile targets should use `go fmt` and `go test -v ./...` and - `golangci-lint run`. Each Makefile target does exactly one thing — to - run lint + fmt-check + test together (the standard pre-commit gate), - use `make check`. + `golangci-lint run`. Each Makefile target does exactly one thing — to run + lint + fmt-check + test together (the standard pre-commit gate), use + `make check`. -2. Always write a `Makefile` with the default target being `test`, and with - a `fmt` target that formats the code. The `test` target should run all - tests in the project, and the `fmt` target should format the code. - `test` should also have a prerequisite target `lint` that should run any - linters that are configured for the project. +2. Always write a `Makefile` with the default target being `test`, and with a + `fmt` target that formats the code. The `test` target should run all tests in + the project, and the `fmt` target should format the code. `test` should also + have a prerequisite target `lint` that should run any linters that are + configured for the project. -3. After each completed bugfix or feature, the code must be committed. Do - all of the pre-commit checks (test, lint, fmt) before committing, of - course. +3. After each completed bugfix or feature, the code must be committed. Do all of + the pre-commit checks (test, lint, fmt) before committing, of course. 4. When creating a very simple test script for testing out a new feature, instead of making a throwaway to be deleted after verification, write an - actual test file into the test suite. It doesn't need to be very big or + actual test file into the test suite. It doesn't need to be very big or complex, but it should be a real test that can be run. 5. When you are instructed to make the tests pass, DO NOT delete tests, skip - tests, or change the tests specifically to make them pass (unless there - is a bug in the test). This is cheating, and it is bad. You should only - be modifying the test if it is incorrect or if the test is no longer - relevant. In almost all cases, you should be fixing the code that is - being tested, or updating the tests to match a refactored implementation. + tests, or change the tests specifically to make them pass (unless there is a + bug in the test). This is cheating, and it is bad. You should only be + modifying the test if it is incorrect or if the test is no longer relevant. + In almost all cases, you should be fixing the code that is being tested, or + updating the tests to match a refactored implementation. 6. When dealing with dates and times or timestamps, always use, display, and - store UTC. Set the local timezone to UTC on startup. If the user needs - to see the time in a different timezone, store the user's timezone in a - separate field and convert the UTC time to the user's timezone when - displaying it. For internal use and internal applications and - administrative purposes, always display UTC. + store UTC. Set the local timezone to UTC on startup. If the user needs to see + the time in a different timezone, store the user's timezone in a separate + field and convert the UTC time to the user's timezone when displaying it. For + internal use and internal applications and administrative purposes, always + display UTC. 7. Always write tests, even if they are extremely simple and just check for - correct syntax (ability to compile/import). If you are writing a new - feature, write a test for it. You don't need to target complete - coverage, but you should at least test any new functionality you add. If - you are fixing a bug, write a test first that reproduces the bug, and - then fix the bug in the code. + correct syntax (ability to compile/import). If you are writing a new feature, + write a test for it. You don't need to target complete coverage, but you + should at least test any new functionality you add. If you are fixing a bug, + write a test first that reproduces the bug, and then fix the bug in the code. -8. When implementing new features, be aware of potential side-effects (such - as state files on disk, data in the database, etc.) and ensure that it is +8. When implementing new features, be aware of potential side-effects (such as + state files on disk, data in the database, etc.) and ensure that it is possible to mock or stub these side-effects in tests. -9. Always use structured logging. Log any relevant state/context with the - messages (but do not log secrets). If the log stream is not a terminal, +9. Always use structured logging. Log any relevant state/context with the + messages (but do not log secrets). If the log stream is not a terminal, output the structured logs in jsonl format. 10. Avoid using bare strings or numbers in code, especially if they appear - anywhere more than once. Always define a constant (usually at the top - of the file) and give it a descriptive name, then use that constant in - the code instead of the bare string or number. + anywhere more than once. Always define a constant (usually at the top of the + file) and give it a descriptive name, then use that constant in the code + instead of the bare string or number. 11. You do not need to summarize your changes in the chat after making them. - Making the changes and committing them is sufficient. If anything out - of the ordinary happened, please explain it, but in the normal case - where you found and fixed the bug, or implemented the feature, there is - no need for the end-of-change summary. + Making the changes and committing them is sufficient. If anything out of the + ordinary happened, please explain it, but in the normal case where you found + and fixed the bug, or implemented the feature, there is no need for the + end-of-change summary. -12. Do not create additional files in the root directory of the project - without asking permission first. Configuration files, documentation, and - build files are acceptable in the root, but source code and other files - should be organized in appropriate subdirectories. +12. Do not create additional files in the root directory of the project without + asking permission first. Configuration files, documentation, and build files + are acceptable in the root, but source code and other files should be + organized in appropriate subdirectories. 13. Pre-1.0: NEVER add a database migration. Migrations are supported, but - nothing is installed anywhere yet, so there is nothing to migrate. To - change the schema, edit `internal/database/schema/001.sql` (and any - code that touches the affected tables) directly. After 1.0, each schema - change is a new numbered file in that directory and a released file is - never edited; an existing local database is then migrated when vaultik - is updated. Before 1.0, a local database left on an older schema is - deleted and re-created by a full backup. See - [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations). + nothing is installed anywhere yet, so there is nothing to migrate. To change + the schema, edit `internal/database/schema/001.sql` (and any code that + touches the affected tables) directly. After 1.0, each schema change is a + new numbered file in that directory and a released file is never edited; an + existing local database is then migrated when vaultik is updated. Before + 1.0, a local database left on an older schema is deleted and re-created by a + full backup. See [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations). -14. Never use `git add -A`. Stage only the files you intentionally - changed. +14. Never use `git add -A`. Stage only the files you intentionally changed. -15. Commit messages carry no attribution or advertising trailers for the - tool that helped write the code, or for its vendor: the owner is the - sole author of code written with a tool. +15. Commit messages carry no attribution or advertising trailers for the tool + that helped write the code, or for its vendor: the owner is the sole author + of code written with a tool. 16. Run the whole test suite with `make test` every time, and read its full - output. Never run `go test`, a single test or a single package, and - never grep the output. + output. Never run `go test`, a single test or a single package, and never + grep the output. 17. Do not stop working on a task until the definition of done given in the initial instruction is met: all of the work, not part or most of it. -18. For estimates: backing up over 2.5Gbit/s ethernet to an S3 server - backed by 2000MB/sec SSD takes about 4 seconds per gigabyte. +18. For estimates: backing up over 2.5Gbit/s ethernet to an S3 server backed by + 2000MB/sec SSD takes about 4 seconds per gigabyte. diff --git a/README.md b/README.md index c436e22..be62a24 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # vaultik (ваултик) -`vaultik` is an incremental backup tool written in Go. It encrypts data -using an `age` public key and uploads each encrypted blob directly to a -remote S3-compatible object store. It requires no private keys, secrets, or -credentials (other than those required to PUT to encrypted object storage, -such as S3 API keys) stored on the backed-up system. +`vaultik` is an incremental backup tool written in Go. It encrypts data using an +`age` public key and uploads each encrypted blob directly to a remote +S3-compatible object store. It requires no private keys, secrets, or credentials +(other than those required to PUT to encrypted object storage, such as S3 API +keys) stored on the backed-up system. ## quickstart @@ -42,36 +42,36 @@ vaultik snapshot list Features: -* modern encryption ([age](https://age-encryption.org/), X25519 + ChaCha20-Poly1305) -* content-defined chunking with deduplication (FastCDC) -* incremental backups (a file is re-chunked only when it changed or a - chunk it lists is held by no uploaded blob) -* multithreaded zstd compression at configurable levels -* content-addressed immutable storage -* local state tracking in SQLite (enables write-only incremental backups) -* no mutable remote metadata -* no plaintext file paths or metadata in remote storage -* packs small files into large blobs (keeps S3 operation counts down) -* backs up regular files, symlinks, empty directories, and file permissions -* pluggable storage backends: S3, local filesystem, rclone (70+ providers) -* pure Go (no CGO), cross-compiles to linux/darwin × amd64/arm64 +- modern encryption ([age](https://age-encryption.org/), X25519 + + ChaCha20-Poly1305) +- content-defined chunking with deduplication (FastCDC) +- incremental backups (a file is re-chunked only when it changed or a chunk it + lists is held by no uploaded blob) +- multithreaded zstd compression at configurable levels +- content-addressed immutable storage +- local state tracking in SQLite (enables write-only incremental backups) +- no mutable remote metadata +- no plaintext file paths or metadata in remote storage +- packs small files into large blobs (keeps S3 operation counts down) +- backs up regular files, symlinks, empty directories, and file permissions +- pluggable storage backends: S3, local filesystem, rclone (70+ providers) +- pure Go (no CGO), cross-compiles to linux/darwin × amd64/arm64 ## why Other backup tools like `restic`, `borg`, and `duplicity` are designed for environments where the source host can store secrets and has access to -decryption keys. `vaultik` is for environments where you don't want to -store backup decryption keys on your hosts — only public keys for -encryption. +decryption keys. `vaultik` is for environments where you don't want to store +backup decryption keys on your hosts — only public keys for encryption. Requirements that no existing tool meets: -* open source -* no passphrases or private keys on the source host -* incremental -* compressed -* encrypted -* s3 compatible without an intermediate step or tool +- open source +- no passphrases or private keys on the source host +- incremental +- compressed +- encrypted +- s3 compatible without an intermediate step or tool ## daily use @@ -101,17 +101,17 @@ relies on `prune_grace_period` (default `24h`) to leave the blobs of a backup another one is still running, and its directory under `metadata/` that has no manifest yet, so it must be longer than the longest backup run. It does not protect a blob that backup reuses from an earlier run that stopped before its -manifest: the prune can delete such a blob, and the new snapshot then cannot -be restored. To not depend on the grace period, give each host its own prefix -or directory. See [locking](#locking). +manifest: the prune can delete such a blob, and the new snapshot then cannot be +restored. To not depend on the grace period, give each host its own prefix or +directory. See [locking](#locking). ## restoring on another machine -Restoring on a host that never ran the backup — a replacement machine -after the original is gone — is the case vaultik is built for. That host -needs only three things: the `vaultik` binary, the age **private** key, -and the storage credentials for the destination. It does **not** need the -local index, the original config file, or the original hostname. +Restoring on a host that never ran the backup — a replacement machine after the +original is gone — is the case vaultik is built for. That host needs only three +things: the `vaultik` binary, the age **private** key, and the storage +credentials for the destination. It does **not** need the local index, the +original config file, or the original hostname. ```sh # install @@ -127,17 +127,16 @@ vaultik config set s3.secret_access_key "..." vaultik snapshot list ``` -`snapshot list` reads the destination store without the private key. A -snapshot that is not in this host's (empty) local index is shown as -remote-only: its row is identified by `` rather than by -a `hostname_name_timestamp` name, because the name lives only in the -local index and the encrypted database and cannot be recovered from the -store. Its timestamp and compressed size are real. (See the `snapshot -list` description under [command details](#command-details) for the full -explanation.) +`snapshot list` reads the destination store without the private key. A snapshot +that is not in this host's (empty) local index is shown as remote-only: its row +is identified by `` rather than by a `hostname_name_timestamp` +name, because the name lives only in the local index and the encrypted database +and cannot be recovered from the store. Its timestamp and compressed size are +real. (See the `snapshot list` description under +[command details](#command-details) for the full explanation.) -Use that remote key — the hex printed inside ``, or the -full `remote_key` from `snapshot list --json` — to restore and verify: +Use that remote key — the hex printed inside ``, or the full +`remote_key` from `snapshot list --json` — to restore and verify: ```sh # put the private key file in the environment (reading it from the file @@ -154,10 +153,10 @@ vaultik snapshot restore --verify ~/vaultik-restore vaultik snapshot verify --deep ``` -`age_recipients` (the public key) is not needed to restore — only the -private key in `VAULTIK_AGE_SECRET_KEY`. Both the abbreviated key printed -in the table and the full 64-character key from `--json` are accepted; a -leading part of the key is enough as long as it is unambiguous. +`age_recipients` (the public key) is not needed to restore — only the private +key in `VAULTIK_AGE_SECRET_KEY`. Both the abbreviated key printed in the table +and the full 64-character key from `--json` are accepted; a leading part of the +key is enough as long as it is unambiguous. --- @@ -187,83 +186,92 @@ vaultik version ### global flags -* `--config `: Path to config file (default: `$VAULTIK_CONFIG`, then platform config dir, then `/etc/vaultik/config.yml`) -* `--verbose`, `-v`: Enable verbose output (on stderr — see below) -* `--debug`: Enable debug output (on stderr — see below) -* `--quiet`, `-q`: Suppress non-error output (also suppresses startup banner) -* `--skip-errors`: Skip files that cannot be read when creating a snapshot, or that cannot be restored when restoring, instead of aborting. Packing and storage errors while creating a snapshot (which would leave a chunk recorded but not stored) still abort the run. A run that skipped anything still finishes but exits non-zero: `snapshot create` keeps the snapshot and counts each file or directory it skipped as failed. A file removed during the backup is also counted as failed but does not change the exit status. +- `--config `: Path to config file (default: `$VAULTIK_CONFIG`, then + platform config dir, then `/etc/vaultik/config.yml`) +- `--verbose`, `-v`: Enable verbose output (on stderr — see below) +- `--debug`: Enable debug output (on stderr — see below) +- `--quiet`, `-q`: Suppress non-error output (also suppresses startup banner) +- `--skip-errors`: Skip files that cannot be read when creating a snapshot, or + that cannot be restored when restoring, instead of aborting. Packing and + storage errors while creating a snapshot (which would leave a chunk recorded + but not stored) still abort the run. A run that skipped anything still + finishes but exits non-zero: `snapshot create` keeps the snapshot and counts + each file or directory it skipped as failed. A file removed during the backup + is also counted as failed but does not change the exit status. ### locking -Commands that write persistent state — `snapshot create`, `snapshot -purge`, `snapshot remove`, `prune`, and `remote nuke` — take a -process-wide lock at `$XDG_DATA_HOME/vaultik/vaultik.pid` -(`~/.local/share/vaultik/vaultik.pid` on Linux) for the whole run. Only -one of them runs at a time: a second one exits immediately with an -"already running" error rather than waiting, so two writers can never -corrupt the local index. +Commands that write persistent state — `snapshot create`, `snapshot purge`, +`snapshot remove`, `prune`, and `remote nuke` — take a process-wide lock at +`$XDG_DATA_HOME/vaultik/vaultik.pid` (`~/.local/share/vaultik/vaultik.pid` on +Linux) for the whole run. Only one of them runs at a time: a second one exits +immediately with an "already running" error rather than waiting, so two writers +can never corrupt the local index. -The lock covers one user on one machine. It does not stop another user, -or another host, from writing to the same destination store at the same -time. A backup uploads its blobs, and then its `db.zst.age`, before its -manifest, so a prune from elsewhere at that moment finds blobs no snapshot -lists and a directory under `metadata/` with no manifest. It -deletes such a blob only once it is older than `prune_grace_period` (default -`24h`), and such a directory only once every object in it is, so the grace -period must be longer than the longest backup run of any host or user sharing -the destination. The grace period does not protect a blob a backup reuses -from an earlier run that stopped before its manifest: a backup skips the -upload of a blob already on the destination, so that blob keeps the time of -its first upload, and a prune from elsewhere during the backup can delete it; -the new snapshot then cannot be restored. `remote nuke` deletes everything -regardless. To not depend on the grace period, give each host or user its own -prefix (or directory) on the destination. +The lock covers one user on one machine. It does not stop another user, or +another host, from writing to the same destination store at the same time. A +backup uploads its blobs, and then its `db.zst.age`, before its manifest, so a +prune from elsewhere at that moment finds blobs no snapshot lists and a +directory under `metadata/` with no manifest. It deletes such a blob only once +it is older than `prune_grace_period` (default `24h`), and such a directory only +once every object in it is, so the grace period must be longer than the longest +backup run of any host or user sharing the destination. The grace period does +not protect a blob a backup reuses from an earlier run that stopped before its +manifest: a backup skips the upload of a blob already on the destination, so +that blob keeps the time of its first upload, and a prune from elsewhere during +the backup can delete it; the new snapshot then cannot be restored. +`remote nuke` deletes everything regardless. To not depend on the grace period, +give each host or user its own prefix (or directory) on the destination. Read-only commands — `info`, `snapshot list`, `snapshot verify`, and -`remote info` — do not take the lock and are never blocked, so they run -even while a backup is in progress. `snapshot restore` does not take the -lock either: it writes only to the target directory you name, not the -local index or the destination store. `config`, `database delete`, -`completion`, and `version` do not take the lock. +`remote info` — do not take the lock and are never blocked, so they run even +while a backup is in progress. `snapshot restore` does not take the lock either: +it writes only to the target directory you name, not the local index or the +destination store. `config`, `database delete`, `completion`, and `version` do +not take the lock. ### stdout and stderr -Log output — everything from `--verbose` and `--debug`, and every -warning and error the logger emits — goes to **stderr**, and so does the -startup banner. stdout carries the output you asked for: tables, the -documents produced by `--json`, `config get` values, and completion -scripts. +Log output — everything from `--verbose` and `--debug`, and every warning and +error the logger emits — goes to **stderr**, and so does the startup banner. +stdout carries the output you asked for: tables, the documents produced by +`--json`, `config get` values, and completion scripts. -This means `vaultik snapshot list --verbose > out.txt` captures the -listing and leaves the diagnostics on your terminal. To capture both, -redirect stderr as well (`> out.txt 2> log.txt`, or `> out.txt 2>&1` to -interleave them). +This means `vaultik snapshot list --verbose > out.txt` captures the listing and +leaves the diagnostics on your terminal. To capture both, redirect stderr as +well (`> out.txt 2> log.txt`, or `> out.txt 2>&1` to interleave them). -The split is what makes `--json` usable from a script. Warnings and -errors are never suppressed — not by `--quiet`, not by `--cron` — so a -logger on stdout would eventually land a log line inside a JSON -document and break the parse. A config file with group- or -world-readable permissions is enough to trigger it. +The split is what makes `--json` usable from a script. Warnings and errors are +never suppressed — not by `--quiet`, not by `--cron` — so a logger on stdout +would eventually land a log line inside a JSON document and break the parse. A +config file with group- or world-readable permissions is enough to trigger it. -Format follows the stream: when stderr is a terminal the records are -colorized one-liners, and when it is redirected or piped they are -JSON, one object per line. +Format follows the stream: when stderr is a terminal the records are colorized +one-liners, and when it is redirected or piped they are JSON, one object per +line. -Under `--json`, stdout holds the document and nothing else. The startup -banner is suppressed, as `--quiet` and `--cron` suppress it, and the -progress narration a command would otherwise print — such as the stale -local records `prune` reconciles away — is suppressed too, so it cannot -land ahead of the document. Every `--json` command therefore pipes on -its own, with no additional flag: `vaultik snapshot list --json | jq .` -and `vaultik prune --json | jq .` both work as written. +Under `--json`, stdout holds the document and nothing else. The startup banner +is suppressed, as `--quiet` and `--cron` suppress it, and the progress narration +a command would otherwise print — such as the stale local records `prune` +reconciles away — is suppressed too, so it cannot land ahead of the document. +Every `--json` command therefore pipes on its own, with no additional flag: +`vaultik snapshot list --json | jq .` and `vaultik prune --json | jq .` both +work as written. ### environment variables -* `VAULTIK_AGE_SECRET_KEY`: Age private key for decryption (required for `snapshot restore` and `snapshot verify --deep`). May hold the whole `age-keygen` file — comments and every identity in it are accepted. Set it from the file, e.g. `export VAULTIK_AGE_SECRET_KEY="$(cat vaultik_backup_private_key.txt)"`, so the key is not typed into your shell history. -* `VAULTIK_CONFIG`: Path to config file (overridden by `--config`) -* `VAULTIK_INDEX_PATH`: Override local SQLite index path -* `VAULTIK_CPUPROFILE`: Write a CPU profile to this path for the duration of the run (development/debugging) -* `VAULTIK_MEMPROFILE`: Write a heap profile to this path when the run exits (development/debugging) +- `VAULTIK_AGE_SECRET_KEY`: Age private key for decryption (required for + `snapshot restore` and `snapshot verify --deep`). May hold the whole + `age-keygen` file — comments and every identity in it are accepted. Set it + from the file, e.g. + `export VAULTIK_AGE_SECRET_KEY="$(cat vaultik_backup_private_key.txt)"`, so + the key is not typed into your shell history. +- `VAULTIK_CONFIG`: Path to config file (overridden by `--config`) +- `VAULTIK_INDEX_PATH`: Override local SQLite index path +- `VAULTIK_CPUPROFILE`: Write a CPU profile to this path for the duration of the + run (development/debugging) +- `VAULTIK_MEMPROFILE`: Write a heap profile to this path when the run exits + (development/debugging) ### shell completion @@ -294,282 +302,279 @@ existing file. Created with mode `0600` since it will contain credentials. **`config edit`**: Open the config file in `$EDITOR` (falls back to `vi`). -**`config get`**: Print a config value addressed by dotted YAML path -(e.g. `vaultik config get storage_url`). Non-scalar values print as YAML. +**`config get`**: Print a config value addressed by dotted YAML path (e.g. +`vaultik config get storage_url`). Non-scalar values print as YAML. -**`config set`**: Set a scalar config value by dotted YAML path -(e.g. `vaultik config set compression_level 9`, -`vaultik config set storage_url "file:///mnt/backups"`). Comments and -formatting in the file are preserved. Missing keys along the path are -created: as a list when the next path element is a number (so +**`config set`**: Set a scalar config value by dotted YAML path (e.g. +`vaultik config set compression_level 9`, +`vaultik config set storage_url "file:///mnt/backups"`). Comments and formatting +in the file are preserved. Missing keys along the path are created: as a list +when the next path element is a number (so `vaultik config set age_recipients.0 age1...` works on a file without -`age_recipients`), otherwise as a map. If the config loads, a change -after which it would not, such as `vaultik config set compression_level 99`, -is refused and the file is left unchanged. A config that does not load, -such as the one `config init` writes before `storage_url` is set or one -with a `${ENV:...}` reference to a variable not set in this shell, is -checked one setting at a time: only a change after which the changed -setting cannot be read, such as one giving it the wrong type (a single -value where a list belongs or a word where a number belongs), is refused. +`age_recipients`), otherwise as a map. If the config loads, a change after which +it would not, such as `vaultik config set compression_level 99`, is refused and +the file is left unchanged. A config that does not load, such as the one +`config init` writes before `storage_url` is set or one with a `${ENV:...}` +reference to a variable not set in this shell, is checked one setting at a time: +only a change after which the changed setting cannot be read, such as one giving +it the wrong type (a single value where a list belongs or a word where a number +belongs), is refused. **`snapshot create`**: Perform incremental backup of configured snapshots. -* Optional snapshot names argument to create specific snapshots (default: all) -* On macOS, the terminal application running vaultik needs Full Disk Access + +- Optional snapshot names argument to create specific snapshots (default: all) +- On macOS, the terminal application running vaultik needs Full Disk Access (System Settings → Privacy & Security → Full Disk Access) to read TCC-protected directories; without it the backup aborts with a permission error that explains how to fix it -* `--cron`: Silent on total success; warnings and errors are still printed - (for crontab) -* `--prune`: After backup, drop older snapshots of each backed-up name, - remove orphaned blobs older than `prune_grace_period` from remote storage, - and delete each directory under `metadata/` that has no - `manifest.json.zst` once every object in it is older than - `prune_grace_period` and its snapshot is not in the local index, as `prune` - does. By default keeps only the latest - snapshot per name; use `--keep-newer-than` for a rolling window. When - `--skip-errors` skipped a file or directory it could not read or list, the - prune does not run and every older snapshot is kept, since one of them may - be the only one that holds what was skipped; the command says so and exits - non-zero. When the backup found nothing in a configured path, as in the - mount point of a volume that is not mounted, the prune does not run - either: every older snapshot is kept, and the command names the path and - exits non-zero, on every run until the path holds something again. Take a - path that is empty on purpose out of the config, or remove the older - snapshots by hand with `snapshot purge`. When an earlier snapshot of the - same name in the local index found a volume mounted at or below a - configured path (a directory on a different filesystem from its parent, - with an entry in it that the backup does not exclude) and this backup does - not, the prune does not run either: every older snapshot is kept, and the - command names the directory and exits non-zero, on every run until the - volume is mounted again. A backup also does not find the volume when it - finds no such entry in its directory, as when an automounted volume cannot - be mounted, or when that directory is no longer backed up, because it is - excluded or its configured path was removed. If any of this is on purpose, - as for a retired volume, remove the older snapshots by hand with - `snapshot purge`. A file removed during the backup does not stop the - prune. -* `--keep-newer-than `: With `--prune`, keep snapshots newer than - this duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`). - Without `--prune`, or with a value that is not a valid duration, the - command fails before the backup starts. -* Fails before it writes anything when a `file://` destination directory - does not exist, or when the local index holds snapshots and the - destination answers that it has no `vaultik-destination.txt`. When that - look-up fails for any reason other than not found, for example when S3 - refuses it to credentials that allow only PUT, the check is skipped (see +- `--cron`: Silent on total success; warnings and errors are still printed (for + crontab) +- `--prune`: After backup, drop older snapshots of each backed-up name, remove + orphaned blobs older than `prune_grace_period` from remote storage, and delete + each directory under `metadata/` that has no `manifest.json.zst` once every + object in it is older than `prune_grace_period` and its snapshot is not in the + local index, as `prune` does. By default keeps only the latest snapshot per + name; use `--keep-newer-than` for a rolling window. When `--skip-errors` + skipped a file or directory it could not read or list, the prune does not run + and every older snapshot is kept, since one of them may be the only one that + holds what was skipped; the command says so and exits non-zero. When the + backup found nothing in a configured path, as in the mount point of a volume + that is not mounted, the prune does not run either: every older snapshot is + kept, and the command names the path and exits non-zero, on every run until + the path holds something again. Take a path that is empty on purpose out of + the config, or remove the older snapshots by hand with `snapshot purge`. When + an earlier snapshot of the same name in the local index found a volume mounted + at or below a configured path (a directory on a different filesystem from its + parent, with an entry in it that the backup does not exclude) and this backup + does not, the prune does not run either: every older snapshot is kept, and the + command names the directory and exits non-zero, on every run until the volume + is mounted again. A backup also does not find the volume when it finds no such + entry in its directory, as when an automounted volume cannot be mounted, or + when that directory is no longer backed up, because it is excluded or its + configured path was removed. If any of this is on purpose, as for a retired + volume, remove the older snapshots by hand with `snapshot purge`. A file + removed during the backup does not stop the prune. +- `--keep-newer-than `: With `--prune`, keep snapshots newer than this + duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`). Without + `--prune`, or with a value that is not a valid duration, the command fails + before the backup starts. +- Fails before it writes anything when a `file://` destination directory does + not exist, or when the local index holds snapshots and the destination answers + that it has no `vaultik-destination.txt`. When that look-up fails for any + reason other than not found, for example when S3 refuses it to credentials + that allow only PUT, the check is skipped (see [remote storage layout](#remote-storage-layout)) -* Fails, before anything is pruned, when a configured path is a symlink - whose target does not exist, as one into a volume that is not mounted +- Fails, before anything is pruned, when a configured path is a symlink whose + target does not exist, as one into a volume that is not mounted -**`snapshot list`**: Show every snapshot known to this host — the union -of the local index and the backup destination store — with timestamps -and three sizes per snapshot (compressed remote size; total -uncompressed chunk size; size of the chunks that snapshot stored that -were not stored before). Both chunk sizes are recorded when the -snapshot's backup runs. +**`snapshot list`**: Show every snapshot known to this host — the union of the +local index and the backup destination store — with timestamps and three sizes +per snapshot (compressed remote size; total uncompressed chunk size; size of the +chunks that snapshot stored that were not stored before). Both chunk sizes are +recorded when the snapshot's backup runs. -Listing the destination store does **not** require the age secret key, -so it works in vaultik's intended configuration, where the backed-up -host holds only the public key. A host that has lost its local index -can still see what it has backed up. +Listing the destination store does **not** require the age secret key, so it +works in vaultik's intended configuration, where the backed-up host holds only +the public key. A host that has lost its local index can still see what it has +backed up. -What that host cannot see is a remote-only snapshot's name. The -snapshot ID is hashed at the storage boundary and the manifest records -only the hash, so hostname and snapshot name exist solely in the local -index and in the encrypted per-snapshot database. Snapshots found only -on the destination store are therefore listed as -`>` and show `` in -the uncompressed and "new chunk" columns, which come only from the -local index. Their timestamp and compressed size are real, -read from the manifest. +What that host cannot see is a remote-only snapshot's name. The snapshot ID is +hashed at the storage boundary and the manifest records only the hash, so +hostname and snapshot name exist solely in the local index and in the encrypted +per-snapshot database. Snapshots found only on the destination store are +therefore listed as `>` and show +`` in the uncompressed and "new chunk" columns, which come only +from the local index. Their timestamp and compressed size are real, read from +the manifest. -Snapshots in the local index with no counterpart on the destination -store are reported below the table as drift, with the `vaultik prune` -invocation that reconciles them. If the local index is bound to a -different destination than the configured one (after a change to -`storage_url`, or `s3.endpoint`, `s3.bucket` or `s3.prefix`), the -command says so instead and gives the same two ways out that `prune` -gives: revert the configuration, or run `vaultik database delete`. +Snapshots in the local index with no counterpart on the destination store are +reported below the table as drift, with the `vaultik prune` invocation that +reconciles them. If the local index is bound to a different destination than the +configured one (after a change to `storage_url`, or `s3.endpoint`, `s3.bucket` +or `s3.prefix`), the command says so instead and gives the same two ways out +that `prune` gives: revert the configuration, or run `vaultik database delete`. -If the destination store cannot be listed (unmounted volume, -permission denied, network down), the command warns, falls back to the -local index alone, and still exits zero. It does the same when the -destination answers that it has no `vaultik-destination.txt` while the -local index holds snapshots stored there, as when a volume mounted at -the destination is unplugged and leaves its empty mount point behind. -* `--json`: Output in JSON format. Each entry carries `locally_tracked` - (whether the snapshot is in the local index), `remote_key` (the full - 64-character storage key), and `remote_present` (whether it was seen - on the destination store, or `null` if the destination could not be - listed). Warnings about an unlistable destination, a local index - bound to a different destination (with both destinations and the - same two ways out), unreadable manifests, and a truncated listing all - go to stderr through the logger, so stdout stays a single parseable - document. +If the destination store cannot be listed (unmounted volume, permission denied, +network down), the command warns, falls back to the local index alone, and still +exits zero. It does the same when the destination answers that it has no +`vaultik-destination.txt` while the local index holds snapshots stored there, as +when a volume mounted at the destination is unplugged and leaves its empty mount +point behind. + +- `--json`: Output in JSON format. Each entry carries `locally_tracked` (whether + the snapshot is in the local index), `remote_key` (the full 64-character + storage key), and `remote_present` (whether it was seen on the destination + store, or `null` if the destination could not be listed). Warnings about an + unlistable destination, a local index bound to a different destination (with + both destinations and the same two ways out), unreadable manifests, and a + truncated listing all go to stderr through the logger, so stdout stays a + single parseable document. **`snapshot verify`**: Verify snapshot integrity. -* Default (shallow): checks that every blob the manifest lists is present in + +- Default (shallow): checks that every blob the manifest lists is present in storage with the size the manifest records, and that the encrypted database is present. It does not read blob contents. -* `--deep`: Downloads and decrypts each blob, verifies chunk hashes against the +- `--deep`: Downloads and decrypts each blob, verifies chunk hashes against the encrypted metadata database -* Accepts the same identifiers as `snapshot restore`: a snapshot ID, or a +- Accepts the same identifiers as `snapshot restore`: a snapshot ID, or a remote-only snapshot's remote key (or an unambiguous leading part of it) -* `--json`: Output results as JSON +- `--json`: Output results as JSON **`snapshot purge`**: Remove old snapshots based on criteria. Retention is -per-snapshot-name (`--keep-latest` keeps the latest of each name, not the -latest globally). -* `--keep-latest`: Keep only the most recent snapshot of each name -* `--older-than `: Remove snapshots older than duration (e.g. `30d`, - `4w`, `6mo`, `1y`; `m` is minutes, `mo` is months) -* `--snapshot `: Restrict to specific snapshot names (repeat for multiple) -* `--force`: Skip confirmation prompt +per-snapshot-name (`--keep-latest` keeps the latest of each name, not the latest +globally). -**`snapshot remove`**: Remove one snapshot. By default this removes the -snapshot from the local index and strips the snapshot's metadata from -the backup destination store. Blobs are NOT touched — deleting blobs -requires reading every remaining remote manifest (the destination store -may hold snapshots this host doesn't know about), which is what -`vaultik prune` does. The command prints the `vaultik prune` invocation -to run as a follow-up only when it removed the snapshot's metadata from -the destination store, and never under `--json`. An ID that names no -snapshot in the local index or on the destination store is an error; -with `--local-only`, the snapshot must be in the local index. Local row -cleanup (files, chunks, blobs the snapshot was the last referrer for) -runs automatically. If removing the snapshot's metadata from the -destination store fails (for example because the store is unreachable, -or the local index holds snapshots and the destination answers that it -has no `vaultik-destination.txt`), the local-DB removal still completes and a -warning is emitted; run `vaultik snapshot remove ` again -once the store is reachable to remove the snapshot's metadata from it -(`vaultik prune` does not). For a snapshot that is only on the -destination store, that failure is an error. To wipe everything on the -destination in one go, use `vaultik remote nuke --force`. -* `--local-only`: Skip remote cleanup; only touch the local index -* `--dry-run`: Show what would be deleted without deleting -* `--force`: Skip confirmation prompt -* `--json`: Output result as JSON. Also skips the confirmation prompt, as +- `--keep-latest`: Keep only the most recent snapshot of each name +- `--older-than `: Remove snapshots older than duration (e.g. `30d`, + `4w`, `6mo`, `1y`; `m` is minutes, `mo` is months) +- `--snapshot `: Restrict to specific snapshot names (repeat for multiple) +- `--force`: Skip confirmation prompt + +**`snapshot remove`**: Remove one snapshot. By default this removes the snapshot +from the local index and strips the snapshot's metadata from the backup +destination store. Blobs are NOT touched — deleting blobs requires reading every +remaining remote manifest (the destination store may hold snapshots this host +doesn't know about), which is what `vaultik prune` does. The command prints the +`vaultik prune` invocation to run as a follow-up only when it removed the +snapshot's metadata from the destination store, and never under `--json`. An ID +that names no snapshot in the local index or on the destination store is an +error; with `--local-only`, the snapshot must be in the local index. Local row +cleanup (files, chunks, blobs the snapshot was the last referrer for) runs +automatically. If removing the snapshot's metadata from the destination store +fails (for example because the store is unreachable, or the local index holds +snapshots and the destination answers that it has no `vaultik-destination.txt`), +the local-DB removal still completes and a warning is emitted; run +`vaultik snapshot remove ` again once the store is reachable to +remove the snapshot's metadata from it (`vaultik prune` does not). For a +snapshot that is only on the destination store, that failure is an error. To +wipe everything on the destination in one go, use `vaultik remote nuke --force`. + +- `--local-only`: Skip remote cleanup; only touch the local index +- `--dry-run`: Show what would be deleted without deleting +- `--force`: Skip confirmation prompt +- `--json`: Output result as JSON. Also skips the confirmation prompt, as `--force` does. **`snapshot restore`**: Restore files from a backup snapshot. -* Requires `VAULTIK_AGE_SECRET_KEY` environment variable -* Accepts a snapshot ID, or — for a snapshot only on the destination - store — its remote key (or an unambiguous leading part of it) as shown - by `snapshot list`. See - [restoring on another machine](#restoring-on-another-machine). -* Optional path arguments to restore specific files/directories (default: all). + +- Requires `VAULTIK_AGE_SECRET_KEY` environment variable +- Accepts a snapshot ID, or — for a snapshot only on the destination store — its + remote key (or an unambiguous leading part of it) as shown by `snapshot list`. + See [restoring on another machine](#restoring-on-another-machine). +- Optional path arguments to restore specific files/directories (default: all). A path that matches nothing in the snapshot is named in a warning, and the command exits non-zero after restoring the paths that match. -* Preserves file permissions, timestamps, ownership (ownership requires root), +- Preserves file permissions, timestamps, ownership (ownership requires root), symlinks, and empty directories -* `--verify`: After restoring, verify every restored file's chunk hashes - match. A file skipped under `--skip-errors` is reported as failed to - restore and is not verified. +- `--verify`: After restoring, verify every restored file's chunk hashes match. + A file skipped under `--skip-errors` is reported as failed to restore and is + not verified. -**`prune`**: Tidy up everything that isn't needed. Runs three passes: -(1) reconcile the local index against the destination store — any -local snapshot whose remote metadata is missing is dropped from the -local index; (2) delete orphaned local rows (files, chunks, blobs no -longer referenced by any completed snapshot); (3) list every remote -manifest on the destination store to compute the still-referenced blob -set and delete any blob not in that set that is older than -`prune_grace_period` (default `24h`). A newer one is kept and counted: it +**`prune`**: Tidy up everything that isn't needed. Runs three passes: (1) +reconcile the local index against the destination store — any local snapshot +whose remote metadata is missing is dropped from the local index; (2) delete +orphaned local rows (files, chunks, blobs no longer referenced by any completed +snapshot); (3) list every remote manifest on the destination store to compute +the still-referenced blob set and delete any blob not in that set that is older +than `prune_grace_period` (default `24h`). A newer one is kept and counted: it may belong to a backup still running, on this host or another sharing the -destination store, that has not yet uploaded its manifest. The grace period -does not protect a blob such a backup reuses from an earlier run that stopped -before its manifest: that blob keeps the time of its first upload, so it can -be deleted. Step (3) also deletes each directory under `metadata/` that has -no `manifest.json.zst`, as a backup leaves when it stops after uploading +destination store, that has not yet uploaded its manifest. The grace period does +not protect a blob such a backup reuses from an earlier run that stopped before +its manifest: that blob keeps the time of its first upload, so it can be +deleted. Step (3) also deletes each directory under `metadata/` that has no +`manifest.json.zst`, as a backup leaves when it stops after uploading `db.zst.age` but before its manifest, once every object in it is older than `prune_grace_period` and its snapshot is not in the local index. An object the -listing gives no time for keeps its directory, and a directory whose name is -not a remote key is left alone. Step (3) reads all remote manifests — network -cost scales with the number of snapshots. -`snapshot create --prune` runs the same cleanup automatically; this is the -manual entry point for the same work. If the destination store cannot -be listed, or the local index holds snapshots and the destination answers -that it has no `vaultik-destination.txt` (an unplugged volume's empty mount -point), prune fails and deletes nothing. `snapshot purge` does the same. If a -blob or such a directory cannot be deleted, the command (and +listing gives no time for keeps its directory, and a directory whose name is not +a remote key is left alone. Step (3) reads all remote manifests — network cost +scales with the number of snapshots. `snapshot create --prune` runs the same +cleanup automatically; this is the manual entry point for the same work. If the +destination store cannot be listed, or the local index holds snapshots and the +destination answers that it has no `vaultik-destination.txt` (an unplugged +volume's empty mount point), prune fails and deletes nothing. `snapshot purge` +does the same. If a blob or such a directory cannot be deleted, the command (and `snapshot create --prune`) exits non-zero. -* `--force`: Skip confirmation prompt -* `--json`: Output stats as JSON. Also skips the confirmation prompt, as - `--force` does. A blob that cannot be deleted is counted in - `blobs_failed`, and the document is printed before the non-zero exit. - A blob kept for being newer than `prune_grace_period`, or because the - listing of the destination gives no time for it, is counted in - `blobs_too_new` and not in `blobs_found`. A directory under `metadata/` - with no manifest is counted in `metadata_dirs_deleted` once deleted, or - in `metadata_dirs_failed` if it cannot be. + +- `--force`: Skip confirmation prompt +- `--json`: Output stats as JSON. Also skips the confirmation prompt, as + `--force` does. A blob that cannot be deleted is counted in `blobs_failed`, + and the document is printed before the non-zero exit. A blob kept for being + newer than `prune_grace_period`, or because the listing of the destination + gives no time for it, is counted in `blobs_too_new` and not in `blobs_found`. + A directory under `metadata/` with no manifest is counted in + `metadata_dirs_deleted` once deleted, or in `metadata_dirs_failed` if it + cannot be. **`info`**: Display system configuration, storage settings, encryption recipients, and local database statistics. -**`remote info`**: Show storage backend type and location plus detailed -remote storage inventory: per-snapshot metadata sizes, blob counts, and -orphaned blob detection. A name under `metadata/` that is not a remote -key is skipped with a warning and is not printed. If a listed -`manifest.json.zst` cannot be read, or sits under a skipped name, the -orphaned blob figures are reported as unknown; `--json` gives them as -`null`, lists the remote key of each unreadable manifest in -`unreadable_manifests` and counts the manifests under skipped names in -`skipped_manifest_count`. An unreadable manifest also leaves its -snapshot's blob count and blob size unknown, `null` in `--json`. A file -under `blobs/` whose name is not a blob hash is not counted as a blob, -since `prune` never deletes it. -* `--json`: Output as JSON +**`remote info`**: Show storage backend type and location plus detailed remote +storage inventory: per-snapshot metadata sizes, blob counts, and orphaned blob +detection. A name under `metadata/` that is not a remote key is skipped with a +warning and is not printed. If a listed `manifest.json.zst` cannot be read, or +sits under a skipped name, the orphaned blob figures are reported as unknown; +`--json` gives them as `null`, lists the remote key of each unreadable manifest +in `unreadable_manifests` and counts the manifests under skipped names in +`skipped_manifest_count`. An unreadable manifest also leaves its snapshot's blob +count and blob size unknown, `null` in `--json`. A file under `blobs/` whose +name is not a blob hash is not counted as a blob, since `prune` never deletes +it. -**`remote nuke`**: Delete every object under `metadata/` and `blobs/` on -the backup destination store, whatever its name, and then -`vaultik-destination.txt`, leaving the bucket prefix empty. Destructive -and irreversible. This is the single supported way to wipe the entire -destination store. A snapshot is removed from the local index only once -its metadata is deleted from the destination store. If the destination -store cannot be listed, or the local index holds snapshots and the -destination answers that it has no `vaultik-destination.txt` (an unplugged -volume's empty mount point), the command fails before it removes anything. If a -listing afterwards still finds anything under `metadata/` or `blobs/`, -the command names each object left and exits non-zero; running it again -deletes what is left. -* `--force`: Required to confirm destruction. +- `--json`: Output as JSON -**`database delete`**: Delete the local SQLite state database file -entirely. Remote storage is unaffected; the next backup will do a full -scan and re-deduplicate against existing remote blobs, and the local -index will re-bind to the currently configured storage destination. -Use this after changing `storage_url`, or `s3.endpoint`, `s3.bucket` or -`s3.prefix`, to a different destination. -* `--force`: Skip confirmation prompt +**`remote nuke`**: Delete every object under `metadata/` and `blobs/` on the +backup destination store, whatever its name, and then `vaultik-destination.txt`, +leaving the bucket prefix empty. Destructive and irreversible. This is the +single supported way to wipe the entire destination store. A snapshot is removed +from the local index only once its metadata is deleted from the destination +store. If the destination store cannot be listed, or the local index holds +snapshots and the destination answers that it has no `vaultik-destination.txt` +(an unplugged volume's empty mount point), the command fails before it removes +anything. If a listing afterwards still finds anything under `metadata/` or +`blobs/`, the command names each object left and exits non-zero; running it +again deletes what is left. + +- `--force`: Required to confirm destruction. + +**`database delete`**: Delete the local SQLite state database file entirely. +Remote storage is unaffected; the next backup will do a full scan and +re-deduplicate against existing remote blobs, and the local index will re-bind +to the currently configured storage destination. Use this after changing +`storage_url`, or `s3.endpoint`, `s3.bucket` or `s3.prefix`, to a different +destination. + +- `--force`: Skip confirmation prompt --- ## storage backends -vaultik supports three storage backends, selected via the `storage_url` config field: +vaultik supports three storage backends, selected via the `storage_url` config +field: **S3** (`s3://bucket/prefix?endpoint=host®ion=us-east-1`): Any S3-compatible object store. Credentials are read from `s3.access_key_id` and `s3.secret_access_key` in the config file. -**Local filesystem** (`file:///path/to/backup`): Stores blobs and metadata on -a local or mounted filesystem. Useful for testing or backing up to a NAS. The -path must be absolute; a relative one is refused when the config loads. -Percent-escapes in the path are decoded, so `my%20stick` and `my stick` name -the same directory. The directory must exist before the first backup: vaultik -never creates it. A directory on a removable volume is gone while the volume is -not mounted, so a backup then fails instead of writing to the disk under the -mount point. The mount point itself stays behind when the volume is unplugged: -there only `vaultik-destination.txt` stops such a backup, and only while the -local index holds snapshots. +**Local filesystem** (`file:///path/to/backup`): Stores blobs and metadata on a +local or mounted filesystem. Useful for testing or backing up to a NAS. The path +must be absolute; a relative one is refused when the config loads. +Percent-escapes in the path are decoded, so `my%20stick` and `my stick` name the +same directory. The directory must exist before the first backup: vaultik never +creates it. A directory on a removable volume is gone while the volume is not +mounted, so a backup then fails instead of writing to the disk under the mount +point. The mount point itself stays behind when the volume is unplugged: there +only `vaultik-destination.txt` stops such a backup, and only while the local +index holds snapshots. **Rclone** (`rclone://remote/path`): Uses rclone's 70+ supported cloud providers. Requires rclone to be configured separately (`rclone config`). An upload cut off part-way leaves nothing under the object's name on S3, which shows an object only once its upload has completed, and on the local filesystem -backend, which writes a temporary file and renames it into place. Rclone -remotes with a server-side move (local and sftp among them) are written under a +backend, which writes a temporary file and renames it into place. Rclone remotes +with a server-side move (local and sftp among them) are written under a temporary name ending in `.partial` and moved into place. Rclone remotes without one are written in place: where such a remote shows a file while it is still being written, a killed upload can leave a truncated object under its name, @@ -578,12 +583,11 @@ and can be deleted. A destination shared between hosts or users, each with its own local index, relies on `prune_grace_period` to keep one's prune from deleting the blobs of -another's backup still running, or its directory under `metadata/` that has -no manifest yet, so it must be longer than the longest backup run. It does not -protect a blob that backup reuses from an earlier run that -stopped before its manifest, which the prune can delete. To not depend on the -grace period, give each host its own prefix (or directory). See -[locking](#locking). +another's backup still running, or its directory under `metadata/` that has no +manifest yet, so it must be longer than the longest backup run. It does not +protect a blob that backup reuses from an earlier run that stopped before its +manifest, which the prune can delete. To not depend on the grace period, give +each host its own prefix (or directory). See [locking](#locking). Legacy S3 configuration via `s3.*` fields (endpoint, bucket, prefix, etc.) is still supported for backward compatibility. `storage_url` takes precedence if @@ -593,9 +597,9 @@ both are set. ## architecture -For an implementation-level view of the internals — the data model, the -`fx` dependency-injection wiring, and the scanner — see -[`ARCHITECTURE.md`](ARCHITECTURE.md). +For an implementation-level view of the internals — the data model, the `fx` +dependency-injection wiring, and the scanner — see +[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md). ### remote storage layout @@ -610,44 +614,45 @@ For an implementation-level view of the internals — the data model, the └── manifest.json.zst # Unencrypted blob list (for pruning) ``` -* `vaultik-destination.txt` holds one fixed line of text, with no host - name, path or time. While the local index holds snapshots stored - there, a destination that answers a look-up of it with not found is - treated as not present: `snapshot create` refuses to write to it, - `prune`, `snapshot purge` and `remote nuke` fail, and `snapshot list` - and `snapshot remove` behave as for a destination that cannot be - listed. This keeps an unplugged volume's empty mount point from being - taken for a destination whose snapshots are all gone. Mount - the volume if it is removable; if the destination was emptied on - purpose, run `vaultik database delete` and back up again. - When the look-up fails for any reason other than not found, the check - is skipped and the command goes on. S3 refuses it on every run to - credentials that allow only PUT, so a host with such credentials does - not notice a destination emptied since its last backup, and its next - backup would leave out the data its local index records as already - stored. After the destination is emptied, run +- `vaultik-destination.txt` holds one fixed line of text, with no host name, + path or time. While the local index holds snapshots stored there, a + destination that answers a look-up of it with not found is treated as not + present: `snapshot create` refuses to write to it, `prune`, `snapshot purge` + and `remote nuke` fail, and `snapshot list` and `snapshot remove` behave as + for a destination that cannot be listed. This keeps an unplugged volume's + empty mount point from being taken for a destination whose snapshots are all + gone. Mount the volume if it is removable; if the destination was emptied on + purpose, run `vaultik database delete` and back up again. When the look-up + fails for any reason other than not found, the check is skipped and the + command goes on. S3 refuses it on every run to credentials that allow only + PUT, so a host with such credentials does not notice a destination emptied + since its last backup, and its next backup would leave out the data its local + index records as already stored. After the destination is emptied, run `vaultik database delete` on such a host before it backs up again. -* Blobs are two-level directory sharded using the first 4 hex chars of the blob hash -* `db.zst.age` is a binary SQLite database (zstd compressed, age encrypted) - containing all file metadata, chunk mappings, and relationships for the snapshot -* `manifest.json.zst` is an unencrypted compressed JSON blob list, enabling +- Blobs are two-level directory sharded using the first 4 hex chars of the blob + hash +- `db.zst.age` is a binary SQLite database (zstd compressed, age encrypted) + containing all file metadata, chunk mappings, and relationships for the + snapshot +- `manifest.json.zst` is an unencrypted compressed JSON blob list, enabling pruning without the private key Snapshot IDs follow the human-readable format `__` (e.g. `server1_home_2025-06-01T12:00:00Z`), but this ID is never written to the -destination store in plaintext. Each snapshot's metadata directory is named -with its ``, a one-way double SHA-256 hash of the ID, so a plain -listing of the store shows no hostname or snapshot name. The hash uses no -secret, though, so an observer who guesses a candidate hostname and snapshot -name can hash it and confirm the snapshot is present; the remote key keeps -names out of a listing but does not hide them from a guess. The backup time is -not hidden either: manifest.json.zst carries a plaintext timestamp, and object -modification times are visible at the storage layer regardless. For example, +destination store in plaintext. Each snapshot's metadata directory is named with +its ``, a one-way double SHA-256 hash of the ID, so a plain listing +of the store shows no hostname or snapshot name. The hash uses no secret, +though, so an observer who guesses a candidate hostname and snapshot name can +hash it and confirm the snapshot is present; the remote key keeps names out of a +listing but does not hide them from a guess. The backup time is not hidden +either: manifest.json.zst carries a plaintext timestamp, and object modification +times are visible at the storage layer regardless. For example, `server1_home_2025-06-01T12:00:00Z` is stored under `metadata/17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa/`. See [docs/REPOSTRUCTURE.md](docs/REPOSTRUCTURE.md#remote-key-derivation) for the -derivation, and [Security Considerations](docs/REPOSTRUCTURE.md#security-considerations) +derivation, and +[Security Considerations](docs/REPOSTRUCTURE.md#security-considerations) (including [Accepted Risks](docs/REPOSTRUCTURE.md#accepted-risks)) for what the format does and does not protect. @@ -680,89 +685,88 @@ format does and does not protect. 3. List all blobs in storage 4. Delete any blob not in the referenced set that is older than `prune_grace_period` -5. Delete each directory under `metadata/` with no manifest whose objects - are all older than `prune_grace_period`, unless its snapshot is in the - local index +5. Delete each directory under `metadata/` with no manifest whose objects are + all older than `prune_grace_period`, unless its snapshot is in the local + index ### chunking and deduplication -* Content-defined chunking using the FastCDC algorithm -* Average chunk size: configurable (default 10MB) -* Deduplication at file level (unchanged files skipped, unless a chunk - the file lists is held by no uploaded blob) and chunk level (identical - chunks across files stored once) -* Multiple chunks packed into blobs to reduce object count +- Content-defined chunking using the FastCDC algorithm +- Average chunk size: configurable (default 10MB) +- Deduplication at file level (unchanged files skipped, unless a chunk the file + lists is held by no uploaded blob) and chunk level (identical chunks across + files stored once) +- Multiple chunks packed into blobs to reduce object count ### encryption -* Asymmetric encryption using age (X25519 + ChaCha20-Poly1305) -* Only the public key is needed on the source host -* Each blob and each metadata database is encrypted independently -* Multiple recipients supported (encrypt to multiple keys) +- Asymmetric encryption using age (X25519 + ChaCha20-Poly1305) +- Only the public key is needed on the source host +- Each blob and each metadata database is encrypted independently +- Multiple recipients supported (encrypt to multiple keys) ### compression -* zstd compression at configurable level (1-19, default 3). The level is - accepted as 1-19 but maps onto zstd's four internal speed presets: - 1-2 fastest, 3-5 default, 6-9 better, 10-19 best. Levels within the - same band compress identically. -* Applied before encryption at the blob level +- zstd compression at configurable level (1-19, default 3). The level is + accepted as 1-19 but maps onto zstd's four internal speed presets: 1-2 + fastest, 3-5 default, 6-9 better, 10-19 best. Levels within the same band + compress identically. +- Applied before encryption at the blob level --- ## configuration reference -Run `vaultik config init` to generate a fully commented config file; a -complete annotated example also lives in -[`config.example.yml`](config.example.yml). Key fields: +Run `vaultik config init` to generate a fully commented config file; a complete +annotated example also lives in +[`configs/config.example.yml`](configs/config.example.yml). Key fields: -| Field | Default | Description | -|-------|---------|-------------| -| `age_recipients` | (required by `snapshot create`) | Age public keys for encryption. Other commands run without one, so a machine that only restores can leave it empty | -| `age_secret_key` | (unset) | Age private key for decryption (`snapshot restore`, `snapshot verify --deep`). Setting it in the config file places the private key on the backed-up host, defeating the public-key-only design (see "why" above). Prefer the `VAULTIK_AGE_SECRET_KEY` environment variable, supplied only on the machine you restore from. | -| `snapshots` | (required) | Named snapshot definitions with paths and excludes | -| `storage_url` | | Storage backend URL (`s3://`, `file://`, `rclone://`) | -| `s3.*` | | Legacy S3 configuration (endpoint, bucket, credentials) | -| `exclude` | | Global exclude patterns (applied to all snapshots) | -| `chunk_size` | `10MB` | Average chunk size for content-defined chunking | -| `blob_size_limit` | `10GB` | Maximum blob size before splitting. Must be at least four times `chunk_size` (the largest chunk the chunker can emit), otherwise a single-chunk blob could exceed the limit. A backup needs free temporary space, because each blob is written whole to a temporary file before it is uploaded (up to about `blob_size_limit`; an rclone destination that cannot stream uploads needs about twice that) and the metadata export writes copies of the local index. Temporary files go to `$TMPDIR` (default `/tmp`); with `TMPDIR` unset, SQLite writes one of those copies to `/var/tmp` | -| `compression_level` | `3` | zstd compression level (1-19) | -| `prune_grace_period` | `24h` | How old a blob that no snapshot lists must be before `prune` deletes it, and how old every object in a directory under `metadata/` with no manifest must be before `prune` deletes that directory. A backup uploads its blobs and its `db.zst.age` before its manifest, so on a destination shared between hosts or users this must be longer than the longest backup run (see [locking](#locking)). It does not protect a blob a backup reuses from an earlier run that stopped before its manifest: that blob keeps the time of its first upload, so a prune can delete it. A duration such as `36h` or `90m`; `0s` deletes such blobs and directories at once | -| `hostname` | system hostname | Hostname used in snapshot IDs | -| `index_path` | platform data dir | Local SQLite index path | +| Field | Default | Description | +| -------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `age_recipients` | (required by `snapshot create`) | Age public keys for encryption. Other commands run without one, so a machine that only restores can leave it empty | +| `age_secret_key` | (unset) | Age private key for decryption (`snapshot restore`, `snapshot verify --deep`). Setting it in the config file places the private key on the backed-up host, defeating the public-key-only design (see "why" above). Prefer the `VAULTIK_AGE_SECRET_KEY` environment variable, supplied only on the machine you restore from. | +| `snapshots` | (required) | Named snapshot definitions with paths and excludes | +| `storage_url` | | Storage backend URL (`s3://`, `file://`, `rclone://`) | +| `s3.*` | | Legacy S3 configuration (endpoint, bucket, credentials) | +| `exclude` | | Global exclude patterns (applied to all snapshots) | +| `chunk_size` | `10MB` | Average chunk size for content-defined chunking | +| `blob_size_limit` | `10GB` | Maximum blob size before splitting. Must be at least four times `chunk_size` (the largest chunk the chunker can emit), otherwise a single-chunk blob could exceed the limit. A backup needs free temporary space, because each blob is written whole to a temporary file before it is uploaded (up to about `blob_size_limit`; an rclone destination that cannot stream uploads needs about twice that) and the metadata export writes copies of the local index. Temporary files go to `$TMPDIR` (default `/tmp`); with `TMPDIR` unset, SQLite writes one of those copies to `/var/tmp` | +| `compression_level` | `3` | zstd compression level (1-19) | +| `prune_grace_period` | `24h` | How old a blob that no snapshot lists must be before `prune` deletes it, and how old every object in a directory under `metadata/` with no manifest must be before `prune` deletes that directory. A backup uploads its blobs and its `db.zst.age` before its manifest, so on a destination shared between hosts or users this must be longer than the longest backup run (see [locking](#locking)). It does not protect a blob a backup reuses from an earlier run that stopped before its manifest: that blob keeps the time of its first upload, so a prune can delete it. A duration such as `36h` or `90m`; `0s` deletes such blobs and directories at once | +| `hostname` | system hostname | Hostname used in snapshot IDs | +| `index_path` | platform data dir | Local SQLite index path | --- ## limitations -* **No extended attributes (xattrs).** ACLs, macOS Finder metadata, - quarantine flags, SELinux labels, and other extended attributes are not - backed up or restored. -* **No hard link detection.** Two hard links to the same inode are backed - up as independent files. Content deduplication means the data is stored - once, but the hard link relationship is lost on restore. -* **No sparse file support.** Sparse files are fully materialized during - backup. A 100 GB sparse VM disk that is mostly zeros will consume the - full (compressed) size in storage. -* **No bandwidth limiting.** Uploads and downloads use whatever bandwidth - is available. There is no `--bwlimit` flag yet. -* **No parallel blob downloads during restore.** Blobs are fetched - sequentially. Restore speed is bound by single-stream throughput. -* **Device nodes, named pipes, and sockets are silently skipped.** Only - regular files, directories, and symlinks are backed up. -* **Before 1.0, an update can make the local index unusable.** Vaultik - supports schema migrations, but none are added before 1.0 because - there is no installed base yet. If an update leaves your local index - unusable, run `vaultik database delete` and then a full backup; remote - storage is unaffected. After 1.0, the local index is migrated when - vaultik is updated. See - [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations). -* **Files that change during backup may be inconsistent.** There is no - filesystem snapshot or freeze. If a file is modified between the scan - and chunk phases, the backed-up copy may reflect a partial write. -* **Ownership restoration requires root.** File uid/gid are recorded - and restored, but `chown` requires elevated privileges. Without root, - files are restored with the current user's ownership. +- **No extended attributes (xattrs).** ACLs, macOS Finder metadata, quarantine + flags, SELinux labels, and other extended attributes are not backed up or + restored. +- **No hard link detection.** Two hard links to the same inode are backed up as + independent files. Content deduplication means the data is stored once, but + the hard link relationship is lost on restore. +- **No sparse file support.** Sparse files are fully materialized during backup. + A 100 GB sparse VM disk that is mostly zeros will consume the full + (compressed) size in storage. +- **No bandwidth limiting.** Uploads and downloads use whatever bandwidth is + available. There is no `--bwlimit` flag yet. +- **No parallel blob downloads during restore.** Blobs are fetched sequentially. + Restore speed is bound by single-stream throughput. +- **Device nodes, named pipes, and sockets are silently skipped.** Only regular + files, directories, and symlinks are backed up. +- **Before 1.0, an update can make the local index unusable.** Vaultik supports + schema migrations, but none are added before 1.0 because there is no installed + base yet. If an update leaves your local index unusable, run + `vaultik database delete` and then a full backup; remote storage is + unaffected. After 1.0, the local index is migrated when vaultik is updated. + See [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations). +- **Files that change during backup may be inconsistent.** There is no + filesystem snapshot or freeze. If a file is modified between the scan and + chunk phases, the backed-up copy may reflect a partial write. +- **Ownership restoration requires root.** File uid/gid are recorded and + restored, but `chown` requires elevated privileges. Without root, files are + restored with the current user's ownership. --- @@ -772,161 +776,150 @@ Work planned after 1.0. Loosely ordered by priority. ### correctness and operability -* **Outside security audit.** Before 1.0 the encryption and - blob-generation code was reviewed: every bug the review found was - fixed, and the risks it accepted are listed in - [Accepted Risks](docs/REPOSTRUCTURE.md#accepted-risks). No outside - audit has been done. age + zstd + content-defined chunking - is mostly off-the-shelf pieces, but the seams (key handling, - recipient parsing, manifest trust boundary, restore-time identity - validation) need an outside read. -* **Verify restored content end-to-end in CI.** The current - integration test does this for a small synthetic snapshot but - not at scale. A nightly job against a multi-GB representative - snapshot would catch silent regressions in the chunker, packer, - or restore planner. +- **Outside security audit.** Before 1.0 the encryption and blob-generation code + was reviewed: every bug the review found was fixed, and the risks it accepted + are listed in [Accepted Risks](docs/REPOSTRUCTURE.md#accepted-risks). No + outside audit has been done. age + zstd + content-defined chunking is mostly + off-the-shelf pieces, but the seams (key handling, recipient parsing, manifest + trust boundary, restore-time identity validation) need an outside read. +- **Verify restored content end-to-end in CI.** The current integration test + does this for a small synthetic snapshot but not at scale. A nightly job + against a multi-GB representative snapshot would catch silent regressions in + the chunker, packer, or restore planner. ### performance -* **Parallel blob downloads during restore.** Single-stream right - now. With a fast S3 endpoint and a multi-core machine restore is - bound by per-blob fetch + decrypt + decompress; running N of - those in parallel against the disk cache would close most of the - remaining gap. Needs to interact correctly with the locality - planner and sweeper. -* **Bandwidth limiting (`--bwlimit`).** Both upload and download. - Useful for backing up over a shared link. Tricky to make work - correctly with the parallel-download story. -* **Restart of interrupted restore.** Today restore is restartable - in the sense that re-running it overwrites partial output; it - doesn't resume from where it stopped or skip already-present - files. A `--resume` mode that checks targets before fetching - blobs would matter for very large restores. -* **Daemon mode.** A long-running mode that watches for file - changes so frequent backups, such as hourly, skip the full scan. - It adds little for the usual runs from cron every 12 to 36 hours. - See [issue #204](https://git.eeqj.de/sneak/vaultik/issues/204). +- **Parallel blob downloads during restore.** Single-stream right now. With a + fast S3 endpoint and a multi-core machine restore is bound by per-blob fetch + + decrypt + decompress; running N of those in parallel against the disk cache + would close most of the remaining gap. Needs to interact correctly with the + locality planner and sweeper. +- **Bandwidth limiting (`--bwlimit`).** Both upload and download. Useful for + backing up over a shared link. Tricky to make work correctly with the + parallel-download story. +- **Restart of interrupted restore.** Today restore is restartable in the sense + that re-running it overwrites partial output; it doesn't resume from where it + stopped or skip already-present files. A `--resume` mode that checks targets + before fetching blobs would matter for very large restores. +- **Daemon mode.** A long-running mode that watches for file changes so frequent + backups, such as hourly, skip the full scan. It adds little for the usual runs + from cron every 12 to 36 hours. See + [issue #204](https://git.eeqj.de/sneak/vaultik/issues/204). ### usability -* **Man pages and richer `--help` examples.** Cobra generates - basic help; man pages would be a separate target. -* **`vaultik snapshot diff `** — show which files changed - between two snapshots without restoring either. -* **Status reporting hook for `--cron`.** When a backup fails - silently in cron, the user has no idea. A configurable - webhook / email / `notify-send` hook on completion (success and - failure) would close the loop. +- **Man pages and richer `--help` examples.** Cobra generates basic help; man + pages would be a separate target. +- **`vaultik snapshot diff `** — show which files changed between two + snapshots without restoring either. +- **Status reporting hook for `--cron`.** When a backup fails silently in cron, + the user has no idea. A configurable webhook / email / `notify-send` hook on + completion (success and failure) would close the loop. ### infrastructure -* **Schema migrations after 1.0.** Migrations are supported, but none - are added before 1.0 because there is no installed base yet. After - 1.0, each schema change is a new migration, so an existing local - index is migrated when vaultik is updated (see - [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations)). -* **Storage backend coverage tests.** S3, file://, and rclone:// - all share the Storer interface but the rclone path is the least - exercised in CI. +- **Schema migrations after 1.0.** Migrations are supported, but none are added + before 1.0 because there is no installed base yet. After 1.0, each schema + change is a new migration, so an existing local index is migrated when vaultik + is updated (see [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations)). +- **Storage backend coverage tests.** S3, file://, and rclone:// all share the + Storer interface but the rclone path is the least exercised in CI. --- ## output style -Every command's user-facing output is governed by `internal/ui`, in one -of two ways. Color is enabled when the stream written to is a TTY and -the `NO_COLOR` environment variable is unset (https://no-color.org/). +Every command's user-facing output is governed by `internal/ui`, in one of two +ways. Color is enabled when the stream written to is a TTY and the `NO_COLOR` +environment variable is unset (https://no-color.org/). -* **Status, progress, warnings, and errors** go through the `internal/ui` +- **Status, progress, warnings, and errors** go through the `internal/ui` message methods below: marker-prefixed, colored on a TTY, and — except - warnings and errors — silenced by `--quiet`. This is the operational - narration of the long-running commands (`snapshot create`, `prune`, - `snapshot restore`, and the like) and the confirmations of - `config init`, `config set`, and `database delete`. -* **The data a command exists to produce** is written plain, with no - marker and no color, because a marker would corrupt a table or a - parsed document. This covers the `version`, `info`, `remote info` and - `snapshot verify` reports, the `snapshot list` table, `config get` - values, and every `--json` document. `--quiet` silences the human - reports and tables (`version`, `info`, `remote info`, `snapshot - verify`, `snapshot list`) but never the machine-consumed `config get` - value or the `--json` documents, which a script depends on. The - confirmation prompts of `database delete`, `prune`, `snapshot purge` - and `snapshot remove`, each with what it asks to delete, are also - written this way and always shown: they are an interactive exchange - the operator must see. + warnings and errors — silenced by `--quiet`. This is the operational narration + of the long-running commands (`snapshot create`, `prune`, `snapshot restore`, + and the like) and the confirmations of `config init`, `config set`, and + `database delete`. +- **The data a command exists to produce** is written plain, with no marker and + no color, because a marker would corrupt a table or a parsed document. This + covers the `version`, `info`, `remote info` and `snapshot verify` reports, the + `snapshot list` table, `config get` values, and every `--json` document. + `--quiet` silences the human reports and tables (`version`, `info`, + `remote info`, `snapshot verify`, `snapshot list`) but never the + machine-consumed `config get` value or the `--json` documents, which a script + depends on. The confirmation prompts of `database delete`, `prune`, + `snapshot purge` and `snapshot remove`, each with what it asks to delete, are + also written this way and always shown: they are an interactive exchange the + operator must see. `internal/ui` writes to stdout; it is the output the user asked for. The -exceptions are the startup banner and the error a failed command ends -with, which go to stderr. Structured log records are a different thing -and go through `internal/log`, which writes to stderr (see "stdout and -stderr" above). +exceptions are the startup banner and the error a failed command ends with, +which go to stderr. Structured log records are a different thing and go through +`internal/log`, which writes to stderr (see "stdout and stderr" above). Message classes: -| Class | Marker | Alignment | Use for | -|-------|--------|-----------|---------| -| Banner | none | column 0 | The startup line printed once per invocation, on stderr | -| Begin | `》` (white) | column 0 | An operation is about to start (present-continuous verb) | -| Complete | `》` (green) | column 0 | An operation just finished (past-tense verb) | -| Info | `》` (white) | column 0 | Neutral status update | -| Notice | `》` (cyan) | column 0 | Important note that is not a warning | -| Warning | `⚠️ Warning:` (orange/yellow) | column 0 | Recoverable problem | -| Error | `🛑 ERROR:` (red) | column 0 | Operation aborted | -| Progress | ` 》` (white) | column 2 | Heartbeat or per-item status during a long-running operation | -| Detail | ` 》` (white) | column 2 | Continuation/sub-line of a preceding Complete (visually identical to Progress) | +| Class | Marker | Alignment | Use for | +| -------- | ------------------------------ | --------- | ------------------------------------------------------------------------------ | +| Banner | none | column 0 | The startup line printed once per invocation, on stderr | +| Begin | `》` (white) | column 0 | An operation is about to start (present-continuous verb) | +| Complete | `》` (green) | column 0 | An operation just finished (past-tense verb) | +| Info | `》` (white) | column 0 | Neutral status update | +| Notice | `》` (cyan) | column 0 | Important note that is not a warning | +| Warning | `⚠️ Warning:` (orange/yellow) | column 0 | Recoverable problem | +| Error | `🛑 ERROR:` (red) | column 0 | Operation aborted | +| Progress | ` 》` (white) | column 2 | Heartbeat or per-item status during a long-running operation | +| Detail | ` 》` (white) | column 2 | Continuation/sub-line of a preceding Complete (visually identical to Progress) | Conventions: -* Messages are complete English sentences ending with a period. -* Fully qualify terms — say "backup destination store" instead of - "storage", "snapshot source files enumeration" instead of "scan", - "local index database" instead of "database". -* Every operation that emits a Complete also emits a corresponding - Begin. Operations that print only a Begin (because completion is - obvious from a later Begin) should be rare and intentional. -* Use natural verb tense to signal state: "Uploading" for Begin, - "Uploaded" for Complete. Never write the words "begin" or "complete" - in the body — the marker color already conveys that. -* All elapsed and remaining-time fields are explicitly scoped to their - subject: write "blob upload elapsed: 30s, blob upload ETA: 03:15:00 - (est remain 14s)", never just "elapsed 30s, ETA 14s". -* "ETA" means an absolute clock time (when the operation will finish), - not a remaining-duration. Use `ui.Time()` for the former and - `ui.Duration()` for the latter, and label both. -* `ui.Time` formats same-day times as `HH:MM:SS` and other-day times as +- Messages are complete English sentences ending with a period. +- Fully qualify terms — say "backup destination store" instead of "storage", + "snapshot source files enumeration" instead of "scan", "local index database" + instead of "database". +- Every operation that emits a Complete also emits a corresponding Begin. + Operations that print only a Begin (because completion is obvious from a later + Begin) should be rare and intentional. +- Use natural verb tense to signal state: "Uploading" for Begin, "Uploaded" for + Complete. Never write the words "begin" or "complete" in the body — the marker + color already conveys that. +- All elapsed and remaining-time fields are explicitly scoped to their subject: + write "blob upload elapsed: 30s, blob upload ETA: 03:15:00 (est remain 14s)", + never just "elapsed 30s, ETA 14s". +- "ETA" means an absolute clock time (when the operation will finish), not a + remaining-duration. Use `ui.Time()` for the former and `ui.Duration()` for the + latter, and label both. +- `ui.Time` formats same-day times as `HH:MM:SS` and other-day times as `YYYY-MM-DD HH:MM:SS`. No timezone — local time is implied. -Value colorizers in `internal/ui` colorize specific value types -consistently. Compose messages from these helpers rather than embedding -ANSI escapes inline: +Value colorizers in `internal/ui` colorize specific value types consistently. +Compose messages from these helpers rather than embedding ANSI escapes inline: -| Helper | Color | Use for | -|--------|-------|---------| -| `Hex` | cyan | Blob hashes, chunk hashes (truncated to 12 chars + `...`) | -| `Snapshot` | bold cyan | Snapshot IDs (untruncated) | -| `Path` | blue | Filesystem paths | -| `Size` | magenta | Byte counts (human-readable) | -| `Speed` | magenta | Bytes-per-second rates | -| `Duration` | yellow | Elapsed or remaining time | -| `Time` | yellow | Absolute clock times | -| `Count` | magenta | Integer counts with thousands separators | -| `Percent` | magenta | Percentages | +| Helper | Color | Use for | +| ---------- | --------- | --------------------------------------------------------- | +| `Hex` | cyan | Blob hashes, chunk hashes (truncated to 12 chars + `...`) | +| `Snapshot` | bold cyan | Snapshot IDs (untruncated) | +| `Path` | blue | Filesystem paths | +| `Size` | magenta | Byte counts (human-readable) | +| `Speed` | magenta | Bytes-per-second rates | +| `Duration` | yellow | Elapsed or remaining time | +| `Time` | yellow | Absolute clock times | +| `Count` | magenta | Integer counts with thousands separators | +| `Percent` | magenta | Percentages | -When `NO_COLOR` is set or output is not a TTY, all helpers return plain -text and the marker prefixes (`》`, `Warning:`, `ERROR:`) emit without -ANSI escapes. The emoji prefixes on Warning and Error are always emitted -regardless of color setting (emoji are not color). +When `NO_COLOR` is set or output is not a TTY, all helpers return plain text and +the marker prefixes (`》`, `Warning:`, `ERROR:`) emit without ANSI escapes. The +emoji prefixes on Warning and Error are always emitted regardless of color +setting (emoji are not color). ## requirements -* Go 1.26 or later -* Docker, with a reachable daemon, to test, lint, check, or commit: - `script/test` and `script/lint` build the `test` and `lint` phases of - the `Dockerfile`, and `make check` and the pre-commit hook both run - them. A `golangci-lint` installed on `PATH` is not a substitute and is - never used on a host, whatever its version. -* S3-compatible object storage (or local filesystem, or rclone remote) +- Go 1.26 or later +- Docker, with a reachable daemon, to test, lint, check, or commit: + `script/test` and `script/lint` build the `test` and `lint` phases of the + `Dockerfile`, and `make check` and the pre-commit hook both run them. A + `golangci-lint` installed on `PATH` is not a substitute and is never used on a + host, whatever its version. +- S3-compatible object storage (or local filesystem, or rclone remote) ## development workflow @@ -939,7 +932,8 @@ All changes follow this workflow. No exceptions. 5. Fix linting errors (`make lint`). 6. Update documentation and README as required by the change. 7. Format code (`make fmt`). -8. Run `make check` (lint + fmt-check + test). Fix any issues. Repeat until clean. +8. Run `make check` (lint + fmt-check + test). Fix any issues. Repeat until + clean. 9. Commit on the branch. 10. Merge to `main`. 11. Push. @@ -953,123 +947,114 @@ Repository policies for AI agents are in [`AGENTS.md`](AGENTS.md). This repository adheres to the [Scripts to Rule Them All](https://github.com/github/scripts-to-rule-them-all) standard: normalized scripts in `script/` are the entrypoints for the -development workflow, and the Makefile targets are thin shims that call -them. We provide: +development workflow, and the Makefile targets are thin shims that call them. We +provide: -* `script/bootstrap` — install all development dependencies (Go, Go - module download). A host without Go gets the `go.mod` version through - `script/install-go`, in `.tool/go`, which `script/bootstrap` itself, - the `Makefile`, `script/fmt`, `script/fmt-check`, `script/precommit` - and `script/release` add to their `PATH`. It - deliberately does not install `golangci-lint`; see `script/lint` - below. -* `script/setup` — make a fresh clone ready for development: runs +- `script/bootstrap` — install all development dependencies (Go, Go module + download, and node, yarn and `prettier` for Markdown). Node comes from the + host, or else at a pinned version through `nvm`. A host without Go gets the + `go.mod` version through `script/install-go`, in `.tool/go`, which + `script/bootstrap` itself, the `Makefile`, `script/fmt`, `script/fmt-check`, + `script/precommit` and `script/release` add to their `PATH`. It deliberately + does not install `golangci-lint`; see `script/lint` below. +- `script/setup` — make a fresh clone ready for development: runs `script/bootstrap`, then `script/install-precommit` -* `script/projectname` — print the project name (used for the Docker - image tag) -* `script/version` — print the version string to bake into the binary. - The `Makefile`'s `LDFLAGS` call this. See [releasing](#releasing) for - the rules. -* `script/install-goreleaser` — install the pinned `goreleaser` into - `.tool/bin` from a sha256-verified release archive. Idempotent, and - called by `script/bootstrap`; the release workflow calls it directly - because it needs `goreleaser` but not the Docker daemon - `script/bootstrap` insists on. -* `script/install-go` — install the Go toolchain named by `go.mod`'s - `go` directive into `.tool/go` from a sha256-verified `go.dev` - archive, for Linux or macOS on amd64 or arm64. Idempotent. On a CI - runner it also puts `.tool/go/bin` on `PATH` for the steps that - follow. Called by the release workflow, which needs a host Go for - `goreleaser` to shell out to, and by `script/bootstrap` on a host - without Go. `actions/setup-go` is not used because it verifies the - downloaded toolchain against no value in this repo. Bumping Go edits - `go.mod`, the checksums in this script, and the two `golang` digests - in the `Dockerfile` together. -* `script/release` — cross-compile and publish the release artifacts - with the pinned `goreleaser`. Refuses a `goreleaser` on `PATH` whose - version is not the pinned one, because a different version would build - a different release from the same tag. -* `script/release-snapshot` — the same build with no publishing and no - tagging, into `./dist` -* `script/test` — run the test suite by building the `test` phase of - the `Dockerfile` (verbose rerun on failure). This runs *everything*: - there is no separate integration target and no build-tagged subset - held back, so the full round-trip tests in - `internal/vaultik/integration_test.go` run on every invocation. The - 90s `-timeout` is a hang backstop rather than a performance budget; it - applies per test binary, to test execution only. -* `script/lint` — lint by building the `lint` phase of the - `Dockerfile`, which runs `golangci-lint config verify` and then - `golangci-lint run --config .golangci.yml ./...` as build steps in - the digest-pinned `golangci-lint` image. Nothing lints on the host. - That `FROM` line is the only pin of the linter version, and it changes - in the same commit as a re-vendored `.golangci.yml`. -* `script/lint-fix` — apply the linter's autofixes (rewrites files), - using the same pinned image, parsed out of the `lint` phase's `FROM` - line. It cannot be a build step, because fixes have to land in the - worktree, so it bind-mounts the tree into a `docker run` and therefore - needs a *local* daemon. It is a developer convenience and never a - gate: no gate reads its exit status. Run `make lint` afterwards to - find out whether the tree is clean. -* `script/fmt` — format all code (writes) -* `script/fmt-check` — check formatting (read-only). It runs `gofmt` on - the host, over every Go file outside `.tool`. -* `script/check` — run `script/test`, `script/lint`, and - `script/fmt-check`. -* `script/docker` — build the Docker image tagged via - `script/projectname`, stamped with the version - `git describe --tags --always --dirty` gives on the host, or `unknown` - outside a git checkout. The image's build stage depends on the `lint` - and `test` phases, so this lints and tests too. -* `script/cibuild` — CI entrypoint: runs `script/bootstrap`, - `script/check`, and then the same image build as `script/docker`. - `.gitea/workflows/check.yml` runs it on every push. +- `script/projectname` — print the project name (used for the Docker image tag) +- `script/version` — print the version string to bake into the binary. The + `Makefile`'s `LDFLAGS` call this. See [releasing](#releasing) for the rules. +- `script/install-goreleaser` — install the pinned `goreleaser` into `.tool/bin` + from a sha256-verified release archive. Idempotent, and called by + `script/bootstrap`; the release workflow calls it directly because it needs + `goreleaser` but not the Docker daemon `script/bootstrap` insists on. +- `script/install-go` — install the Go toolchain named by `go.mod`'s `go` + directive into `.tool/go` from a sha256-verified `go.dev` archive, for Linux + or macOS on amd64 or arm64. Idempotent. On a CI runner it also puts + `.tool/go/bin` on `PATH` for the steps that follow. Called by the release + workflow, which needs a host Go for `goreleaser` to shell out to, and by + `script/bootstrap` on a host without Go. `actions/setup-go` is not used + because it verifies the downloaded toolchain against no value in this repo. + Bumping Go edits `go.mod`, the checksums in this script, and the two `golang` + digests in the `Dockerfile` together. +- `script/release` — cross-compile and publish the release artifacts with the + pinned `goreleaser`. Refuses a `goreleaser` on `PATH` whose version is not the + pinned one, because a different version would build a different release from + the same tag. +- `script/release-snapshot` — the same build with no publishing and no tagging, + into `./dist` +- `script/test` — run the test suite by building the `test` phase of the + `Dockerfile` (verbose rerun on failure). This runs _everything_: there is no + separate integration target and no build-tagged subset held back, so the full + round-trip tests in `internal/vaultik/integration_test.go` run on every + invocation. The 90s `-timeout` is a hang backstop rather than a performance + budget; it applies per test binary, to test execution only. +- `script/lint` — lint by building the `lint` phase of the `Dockerfile`, which + runs `golangci-lint config verify` and then + `golangci-lint run --config .golangci.yml ./...` as build steps in the + digest-pinned `golangci-lint` image. Nothing lints on the host. That `FROM` + line is the only pin of the linter version, and it changes in the same commit + as a re-vendored `.golangci.yml`. +- `script/lint-fix` — apply the linter's autofixes (rewrites files), using the + same pinned image, parsed out of the `lint` phase's `FROM` line. It cannot be + a build step, because fixes have to land in the worktree, so it bind-mounts + the tree into a `docker run` and therefore needs a _local_ daemon. It is a + developer convenience and never a gate: no gate reads its exit status. Run + `make lint` afterwards to find out whether the tree is clean. +- `script/fmt` — format all code (writes): Go with `go fmt`, Markdown with + `prettier` +- `script/fmt-check` — check formatting (read-only). It runs `gofmt` on the + host, over every Go file outside `.tool`, and `prettier --check` over every + Markdown file. +- `script/check` — run `script/test`, `script/lint`, and `script/fmt-check`. +- `script/docker` — build the Docker image tagged via `script/projectname`, + stamped with the version `git describe --tags --always --dirty` gives on the + host, or `unknown` outside a git checkout. The image's build stage depends on + the `lint` and `test` phases, so this lints and tests too. +- `script/cibuild` — CI entrypoint: runs `script/bootstrap`, `script/check`, and + then the same image build as `script/docker`. `.gitea/workflows/check.yml` + runs it on every push. - Every `docker build` in these scripts passes `--no-cache`, because on - an unchanged tree a cached check layer is replayed without running and - the build still exits 0. A plain `docker build .` is therefore no - evidence that the checks ran. The cost is that `script/cibuild` runs - the `lint` and `test` phases twice: once in `script/check` and again - in the image build. -* `script/precommit` — pre-commit gate: `go mod tidy` + `go fmt` (must - not change files), then `script/check` -* `script/install-precommit` — install the git pre-commit hook that - runs `script/precommit` + Every `docker build` in these scripts passes `--no-cache`, because on an + unchanged tree a cached check layer is replayed without running and the + build still exits 0. A plain `docker build .` is therefore no evidence that + the checks ran. The cost is that `script/cibuild` runs the `lint` and `test` + phases twice: once in `script/check` and again in the image build. + +- `script/precommit` — pre-commit gate: `go mod tidy` + `go fmt` (must not + change files), then `script/check` +- `script/install-precommit` — install the git pre-commit hook that runs + `script/precommit` ## releasing ### version numbers -The version a binary reports comes from git, not from a constant in a -file. It is `git describe --tags --always --dirty`, which -`script/version` runs for the `Makefile`, and `script/docker` and -`script/cibuild` run themselves: +The version a binary reports comes from git, not from a constant in a file. It +is `git describe --tags --always --dirty`, which `script/version` runs for the +`Makefile`, and `script/docker` and `script/cibuild` run themselves: -* `HEAD` is exactly on a tag → that tag, such as `v1.0.0`. -* a commit after a tag → `--g`. -* no tag reachable → the short commit sha. -* any of these, with uncommitted changes to tracked files → a `-dirty` - suffix, because a modified checkout of a tag is not that tag. +- `HEAD` is exactly on a tag → that tag, such as `v1.0.0`. +- a commit after a tag → `--g`. +- no tag reachable → the short commit sha. +- any of these, with uncommitted changes to tracked files → a `-dirty` suffix, + because a modified checkout of a tag is not that tag. A `docker build .` of a clone, with no build arguments, runs the same -`git describe` (without `--dirty`) on the `.git` in its build context, -so it stamps the same value for a clean commit; the build fails if the -context carries `.git` and no version, commit or commit date comes out. -A binary built without +`git describe` (without `--dirty`) on the `.git` in its build context, so it +stamps the same value for a clean commit; the build fails if the context carries +`.git` and no version, commit or commit date comes out. A binary built without git metadata reports `dev`, or `unknown` when `script/docker` or `script/cibuild` built it outside a git checkout. -`goreleaser` stamps a release binary with the tag minus its leading -`v`, so the tag `v1.0.0` produces `vaultik 1.0.0`, matching the archive -name `vaultik_1.0.0_linux_amd64.tar.gz`. `goreleaser --snapshot` stamps -`dev-<12 chars of the commit sha>` rather than inventing the next patch -number. `vaultik version` calls a build a development build when its -version is `dev`, `unknown`, `dev-`, the short commit sha or -`--g`, with or without `-dirty`; only a plain tag, -such as `v1.0.0` or `1.0.0`, is a release. If `script/version` cannot -be run at all, `make` stops with an error instead of building an -unversioned binary, and a binary that somehow carries an empty version -string still reports itself as a development build. +`goreleaser` stamps a release binary with the tag minus its leading `v`, so the +tag `v1.0.0` produces `vaultik 1.0.0`, matching the archive name +`vaultik_1.0.0_linux_amd64.tar.gz`. `goreleaser --snapshot` stamps +`dev-<12 chars of the commit sha>` rather than inventing the next patch number. +`vaultik version` calls a build a development build when its version is `dev`, +`unknown`, `dev-`, the short commit sha or `--g`, with +or without `-dirty`; only a plain tag, such as `v1.0.0` or `1.0.0`, is a +release. If `script/version` cannot be run at all, `make` stops with an error +instead of building an unversioned binary, and a binary that somehow carries an +empty version string still reports itself as a development build. ### cutting a release @@ -1080,13 +1065,12 @@ git tag -a v1.2.3 -m 'v1.2.3' git push origin v1.2.3 ``` -`.gitea/workflows/release.yml` triggers on `v*` tags, installs a Go -toolchain and the pinned `goreleaser`, and runs `script/release`, which -builds -`linux,darwin × amd64,arm64` archives plus `checksums.txt` and publishes -them to this repository's Gitea releases as a draft. `.goreleaser.yaml` -has a `gitea_urls:` block pointing at `https://git.eeqj.de/api/v1`; -without it `goreleaser` would talk to the GitHub API. +`.gitea/workflows/release.yml` triggers on `v*` tags, installs a Go toolchain +and the pinned `goreleaser`, and runs `script/release`, which builds +`linux,darwin × amd64,arm64` archives plus `checksums.txt` and publishes them to +this repository's Gitea releases as a draft. `.goreleaser.yaml` has a +`gitea_urls:` block pointing at `https://git.eeqj.de/api/v1`; without it +`goreleaser` would talk to the GitHub API. The workflow needs one repository Actions secret: @@ -1094,18 +1078,16 @@ The workflow needs one repository Actions secret: | --------------- | ------------------------------------------------------------------------------------------------------- | | `RELEASE_TOKEN` | A Gitea access token with `write:repository` scope, owned by an account that can publish releases here. | -It is passed to `goreleaser` as `GITEA_TOKEN`. The runner's automatic -token is deliberately not used: it is not guaranteed to carry release -write access. +It is passed to `goreleaser` as `GITEA_TOKEN`. The runner's automatic token is +deliberately not used: it is not guaranteed to carry release write access. The Go toolchain that compiles the released binaries is installed by -`script/install-go`, which downloads the version named by `go.mod` -(currently `1.26.1`, the same version the `Dockerfile` builder stage -pins by digest) and refuses the archive unless its sha256 matches the -value committed in the script. `goreleaser` shells out to `go` for every -cross-compile, so without that step the release would either fail -outright or ship binaries built by whatever unpinned toolchain the -runner happened to carry. +`script/install-go`, which downloads the version named by `go.mod` (currently +`1.26.1`, the same version the `Dockerfile` builder stage pins by digest) and +refuses the archive unless its sha256 matches the value committed in the script. +`goreleaser` shells out to `go` for every cross-compile, so without that step +the release would either fail outright or ship binaries built by whatever +unpinned toolchain the runner happened to carry. To rehearse the whole build without publishing or tagging anything: @@ -1115,9 +1097,9 @@ make release-snapshot Artifacts land in `./dist`, which is gitignored. -Release artifacts are not signed, carry no SBOM, and are not built -reproducibly; the archives contain the binary, `LICENSE`, and -`README.md` only (no shell completions or man page). +Release artifacts are not signed, carry no SBOM, and are not built reproducibly; +the archives contain the binary, `LICENSE`, and `README.md` only (no shell +completions or man page). ## license @@ -1125,7 +1107,8 @@ reproducibly; the archives contain the binary, `LICENSE`, and ## author -Made with love and lots of expensive SOTA AI by [sneak](https://sneak.berlin) in Berlin in the summer of 2025. +Made with love and lots of expensive SOTA AI by [sneak](https://sneak.berlin) in +Berlin in the summer of 2025. Released as a free software gift to the world, no strings attached. diff --git a/TODO.md b/TODO.md deleted file mode 100644 index 69d31aa..0000000 --- a/TODO.md +++ /dev/null @@ -1,1331 +0,0 @@ -# Workflow - -* branch (from `main`) -* do the work in Next Step -* move Next Step to the top of Completed Steps -* move the top item of Future Steps into Next Step -* commit (`TODO.md` changes in the same commit as the work) -* merge to `main` if the branch is not protected, otherwise open a PR -* push - -# Status - -pre-1.0 - -# Next Step - -The 1.0 work is complete on `next`: the scope settled on -[issue #125](https://git.eeqj.de/sneak/vaultik/issues/125) has landed, -and so has every fix from the defect hunt before the release candidate -([issue #288](https://git.eeqj.de/sneak/vaultik/issues/288)). What is -left is merging `next` to `main` and tagging the release, both the -owner's; a `v*` tag runs the release build in -`.gitea/workflows/release.yml`. - -# Completed Steps - -- 2026-11-10: Printed the status and progress lines of `remote info` - and `snapshot verify` through `internal/ui`, with its marker and - color, as the README describes - ([issue #410](https://git.eeqj.de/sneak/vaultik/issues/410)). Their - reports stay plain. - -- 2026-11-10: Made `config init` write the `apps` snapshot, which backs - up `/Applications`, only on macOS - ([issue #408](https://git.eeqj.de/sneak/vaultik/issues/408)). On - Linux the first `snapshot create` stopped on the missing directory. - -- 2026-10-15: Stopped `snapshot create --prune` pruning after a backup - in which a volume mounted below a configured path in an earlier - snapshot of the same name was not mounted - ([issue #395](https://git.eeqj.de/sneak/vaultik/issues/395)). Such a - prune could delete every snapshot still holding the volume's files. - Each snapshot now records in the local index the directories it found - on a different filesystem from their parent and found an entry in that - the backup does not exclude. - -- 2026-10-14: Stopped `snapshot create --prune` pruning after a backup - that found nothing in a configured path - ([issue #388](https://git.eeqj.de/sneak/vaultik/issues/388)), as in - the mount point of a volume that is not mounted. Such a prune could - delete every snapshot still holding that path's files. A configured - path that is a symlink whose target is gone, as one into such a - volume, now fails the backup, with or without `--prune`. - -- 2026-10-14: Stopped `snapshot create --prune` pruning after a backup - that skipped files it could not read - ([issue #382](https://git.eeqj.de/sneak/vaultik/issues/382)). Such a - prune could delete the only snapshot still holding those files. - -- 2026-10-14: Made `snapshot create --skip-errors` exit non-zero, - instead of 0, when it skips anything it cannot read - ([issue #310](https://git.eeqj.de/sneak/vaultik/issues/310)). - -- 2026-10-14: Kept the local index when `remote nuke` cannot list or - find the destination store - ([issue #292](https://git.eeqj.de/sneak/vaultik/issues/292)). Nuke - had cleared the local snapshot records anyway; it now fails before - removing anything. - -- 2026-10-14: Stopped counting directories and unchanged symlinks as - files to back up - ([issue #305](https://git.eeqj.de/sneak/vaultik/issues/305)). - -- 2026-10-14: Refused a backup destination that an unplugged volume - left empty, as the owner ruled - ([issue #239](https://git.eeqj.de/sneak/vaultik/issues/239)). Every - backup now writes `vaultik-destination.txt` at the destination root, - and while the local index holds snapshots stored there, a destination - without it is treated as not present. - -- 2026-10-14: Warned about restored ownership only when an entry's - owner or group differs from the recorded one - ([issue #316](https://git.eeqj.de/sneak/vaultik/issues/316)); a - restore by a non-root user had warned even when none did. - -- 2026-10-14: Made `snapshot list` report a changed destination instead - of advising `prune`, which refuses in that case - ([issue #317](https://git.eeqj.de/sneak/vaultik/issues/317)). - -- 2026-10-14: Counted a file as deleted by a backup only if the - previous snapshot of the same name listed it - ([issue #304](https://git.eeqj.de/sneak/vaultik/issues/304)); files - that snapshot did not list had been counted too. - -- 2026-10-14: Named each prefix once in restore, verify and purge - errors, some of which repeated it - ([issue #327](https://git.eeqj.de/sneak/vaultik/issues/327)). A deep - verify log line that named S3 whatever the destination now names - storage. - -- 2026-10-14: Refused credentials in a storage URL's endpoint or rclone - remote name, which were accepted and could then be printed - ([issue #322](https://git.eeqj.de/sneak/vaultik/issues/322)). - -- 2026-10-14: Ran `$EDITOR` through the shell in `config edit`, so a - value with arguments, such as `code --wait`, no longer fails - ([issue #315](https://git.eeqj.de/sneak/vaultik/issues/315)). - -- 2026-10-14: Made `snapshot remove` fail, instead of exiting 0, when - it cannot delete the metadata of a snapshot that is only on the - destination store - ([issue #340](https://git.eeqj.de/sneak/vaultik/issues/340)). The - README and the help now say when it prints the `vaultik prune` - follow-up. - -- 2026-10-14: Labelled the totals in the local index cleanup before - each backup as totals - ([issue #306](https://git.eeqj.de/sneak/vaultik/issues/306)). Each - was shown as `(N remain)`, which read as rows left to clean up. - -- 2026-10-13: Freed a cached blob once no file still to restore needs - it ([issue #324](https://git.eeqj.de/sneak/vaultik/issues/324)); one - also used by a file outside the selected paths had stayed in the - temporary cache until the restore ended. - -- 2026-10-13: Kept the whole startup error when it contains `): ` - ([issue #320](https://git.eeqj.de/sneak/vaultik/issues/320)). Such - an error was cut at its last `): `, so the `blob_size_limit` one lost - the setting's name. - -- 2026-10-13: Silenced the status lines of `prune` and snapshot removal - under `--cron` and `--quiet` - ([issue #294](https://git.eeqj.de/sneak/vaultik/issues/294)). - -- 2026-10-13: Read the rclone config file that `RCLONE_CONFIG` names - ([issue #321](https://git.eeqj.de/sneak/vaultik/issues/321)); a - remote defined only there had been reported as not found. - -- 2026-10-13: Made `/**/` in an exclude pattern match zero directories, - as in gitignore - ([issue #338](https://git.eeqj.de/sneak/vaultik/issues/338)); - `a/**/*.log` had missed `a/x.log`. - -- 2026-10-13: Made the `chunk_size` and `blob_size_limit` defaults and - the `chunk_size` minimum 1000-based, like the size parser and the - docs ([issue #313](https://git.eeqj.de/sneak/vaultik/issues/313)). - -- 2026-10-13: Kept a snapshot's remote metadata when `snapshot purge` - cannot remove it from the local index - ([issue #337](https://git.eeqj.de/sneak/vaultik/issues/337)); the - purge had deleted the metadata anyway and exited 0. - -- 2026-10-13: Made `snapshot restore` fail for a requested path that - matches nothing, which it had ignored - ([issue #309](https://git.eeqj.de/sneak/vaultik/issues/309)). - -- 2026-10-13: Made `remote nuke` delete every object under `metadata/` - and `blobs/` - ([issue #291](https://git.eeqj.de/sneak/vaultik/issues/291)); it had - left some, such as a stray `.DS_Store`, while reporting the store - empty. - -- 2026-10-13: Made `config set` create a list for an index under a - missing key - ([issue #308](https://git.eeqj.de/sneak/vaultik/issues/308)); it had - written a map, after which no command could load the config. - -- 2026-10-13: Listed a `file://` destination through a symlinked - `metadata/` or `blobs/`, which had listed as empty - ([issue #296](https://git.eeqj.de/sneak/vaultik/issues/296)). A link - to a missing target now fails the listing - ([issue #332](https://git.eeqj.de/sneak/vaultik/issues/332)). - -- 2026-10-13: Made `snapshot verify --deep --json` report its blob - counts ([issue #314](https://git.eeqj.de/sneak/vaultik/issues/314)); - a failed run had reported 0 missing and 0 verified. - -- 2026-10-13: Limited and retried the module download in the Docker - build ([issue #351](https://git.eeqj.de/sneak/vaultik/issues/351)), - which had hung for as long as a stalled connection to the module - proxy lasted. - -- 2026-10-13: Recorded each snapshot's uncompressed size when its - backup runs - ([issue #360](https://git.eeqj.de/sneak/vaultik/issues/360)). A later - backup could change an older snapshot's UNCOMPRESSED SIZE in - `snapshot list`. - -- 2026-10-13: Stopped `snapshot restore --skip-errors --verify` - reporting a file that failed to restore again as a checksum failure - ([issue #323](https://git.eeqj.de/sneak/vaultik/issues/323)). - -- 2026-10-13: Recorded the stored size of a blob a backup finds already - stored, not the size of its local copy, which can differ, so - `snapshot verify` could fail on a good snapshot - ([issue #300](https://git.eeqj.de/sneak/vaultik/issues/300)). - -- 2026-10-13: Stopped the local index and the blob upload step ending - the process on a failed close of query results or a failed temp file - cleanup ([issue #345](https://git.eeqj.de/sneak/vaultik/issues/345)); - both are now returned as errors. - -- 2026-10-13: Closed the snapshot database's storage reader too when - restore or deep verify is interrupted - ([issue #356](https://git.eeqj.de/sneak/vaultik/issues/356)). - -- 2026-10-13: Made `prune` and `remote nuke` fail when a delete on the - backup destination store fails - ([issue #290](https://git.eeqj.de/sneak/vaultik/issues/290)). - -- 2026-10-13: Made an S3 listing that the server cuts short an error - ([issue #297](https://git.eeqj.de/sneak/vaultik/issues/297)); `prune` - had taken it as complete and could delete blobs still in use. - -- 2026-10-13: Made shallow `snapshot verify` report a blob it could not - check apart from a missing one - ([issue #318](https://git.eeqj.de/sneak/vaultik/issues/318)); any - error checking a blob had counted as missing, its cause dropped. - -- 2026-10-13: Restored the other files when a file's chunk is in no - blob under `--skip-errors` - ([issue #326](https://git.eeqj.de/sneak/vaultik/issues/326)); that - file had stopped the restore before anything was restored. - -- 2026-10-13: Recorded each snapshot's new chunk size when its backup - runs ([issue #311](https://git.eeqj.de/sneak/vaultik/issues/311)). - `snapshot list` could show a NEW CHUNK SIZE of 0 B for a snapshot - whose change was a modified file. - -- 2026-10-13: Made a backup interrupted during a local index write exit - as interrupted - ([issue #301](https://git.eeqj.de/sneak/vaultik/issues/301)); it could - end with `FATAL: failed to rollback transaction` and exit 1 instead of - 130. - -- 2026-10-13: Printed `snapshot list` and `snapshot purge` sizes like - every other command - ([issue #312](https://git.eeqj.de/sneak/vaultik/issues/312)). They, - and the `bytes` value in terminal log lines, were 1024-based but - labelled KB or MB, and now use 1000-based units. - -- 2026-10-13: Closed each blob's storage reader when restore or deep - verify is interrupted, which ends a stalled read unless it is stuck in - the kernel ([issue #325](https://git.eeqj.de/sneak/vaultik/issues/325)). - -- 2026-10-13: Made a mistyped subcommand under `snapshot`, `config`, - `remote`, `database` or `completion` an error - ([issue #319](https://git.eeqj.de/sneak/vaultik/issues/319)); each had - printed its help and exited 0. - -- 2026-10-13: Made an exclude pattern starting with `**/` match - directly under the snapshot path too, as in gitignore - ([issue #303](https://git.eeqj.de/sneak/vaultik/issues/303)). - -- 2026-10-13: Refused a relative `file://` storage URL and decoded its - percent-escapes - ([issue #299](https://git.eeqj.de/sneak/vaultik/issues/299)); a - relative path had moved with the working directory. - -- 2026-10-13: Removed the blob temp file when a backup stops part-way - ([issue #302](https://git.eeqj.de/sneak/vaultik/issues/302)); the - half-written blob had stayed in `$TMPDIR`. - -- 2026-10-13: Checked `--keep-newer-than` before a backup starts - ([issue #307](https://git.eeqj.de/sneak/vaultik/issues/307)); an - invalid value had been read only by the prune after the backup, so - retention never ran. - -- 2026-10-13: Stopped `remote info` counting a file under `blobs/` that - is not a blob as an orphaned blob - ([issue #295](https://git.eeqj.de/sneak/vaultik/issues/295)). A stray - file such as `.DS_Store` was reported as an orphaned blob and the - report advised running `prune`, which skips such a file and deleted - nothing. `remote info` now takes its blob list from the same listing - `prune` uses, in the table and in `--json`. - -- 2026-10-13: Made `snapshot remove` fail for a snapshot that does not - exist ([issue #293](https://git.eeqj.de/sneak/vaultik/issues/293)). - The command never checked the ID: it reported the snapshot removed - from the local database and from the destination store and exited 0, - under `--json`, `--dry-run` and `--local-only` too. An ID that names - no snapshot in the local index or on the destination store is now an - error; with `--local-only`, the snapshot must be in the local index. - The command now reports a removal from either side only when one - happened, and `remote_removed` is true only when metadata was deleted. - -- 2026-10-12: Bound the local index to the destination an `s3.*` config - names ([issue #298](https://git.eeqj.de/sneak/vaultik/issues/298)). - Only `storage_url` was checked, so after `s3.bucket` or `s3.prefix` - changed, the next backup treated every chunk as already stored, - uploaded nothing, and completed a snapshot that could not be restored. - Without `storage_url`, the local index is now bound to `s3.endpoint`, - `s3.bucket` and `s3.prefix`, and a change is refused as a changed - `storage_url` is. - -- 2026-10-12: Rejected a retention duration longer than about 292 years - ([issue #289](https://git.eeqj.de/sneak/vaultik/issues/289)). The - number given to `--older-than` or `--keep-newer-than` was multiplied - by the length of its unit with no limit, so from `293y`, `15251w`, - `3559mo` or `106752d`, or a sum of parts such as `200y200y`, the - result wrapped to a negative duration. The cutoff then lay in the - future, every snapshot of the name was deleted, the one just made - included, and the command exited 0. Such a duration is now rejected - as invalid and nothing is deleted. - -- 2026-10-08: Made a backup cancelled under `--skip-errors` stop at once - ([issue #286](https://git.eeqj.de/sneak/vaultik/issues/286)). After - Ctrl-C or SIGTERM, phase 2 treated the cancellation error from each - remaining file like an unreadable file: it opened the file, printed an - error line for it, counted it as failed and went on to the next one. - The run now stops at the first file after the cancellation, and no - file is counted as failed because of it. - -- 2026-10-08: Made `remote nuke` delete the `.partial` files that - uploads cut off part-way leave on the destination store - ([issue #281](https://git.eeqj.de/sneak/vaultik/issues/281)). The - file and rclone listings skip such a file, so the command left it in - place and still reported the store empty. It now removes them under - `metadata/` and `blobs/` as its last step. - -- 2026-10-08: Made a local index error while recording a directory or - symlink stop a backup under `--skip-errors` - ([issue #284](https://git.eeqj.de/sneak/vaultik/issues/284)). Phase 2 - only records such an entry in the local index, since it has no data - to open or read, but an error doing so was skipped like an unreadable - file. The snapshot then completed without the entry, and a restore - did not recreate it. The error now stops the backup, as it does - without the flag. - -- 2026-10-08: Counted a file that a backup could not store as failed - ([issue #280](https://git.eeqj.de/sneak/vaultik/issues/280)). A file - that phase 1 counted and phase 2 could not open, because it was - unreadable under `--skip-errors` or removed in between, was reported - in the summary as unchanged with its bytes as backed up, and the - `snapshots` row's `file_count` and `total_size` included it. The - summary now counts it as failed, and its data total and the row leave - it out. - -- 2026-10-08: Made `remote info` report a snapshot's blob count and - blob size as unknown when its manifest cannot be read - ([issue #272](https://git.eeqj.de/sneak/vaultik/issues/272)). The - orphan figures were already unknown in that case, but the snapshot's - row still gave 0 blobs and 0 B, in the table and in `--json`. The row - now reads `unknown` and `--json` gives `null`. A directory with no - manifest still shows 0, since the orphan figures count its blobs as - orphaned. - -- 2026-10-08: Kept the progress line of a snapshot with more than one - path within 100% - ([issue #271](https://git.eeqj.de/sneak/vaultik/issues/271)). The - bytes and files processed counted every path, but the totals they - were divided by held only the current path's, so a second path - smaller than the first showed more than 100% and an ETA of `unknown`. - The totals now add up over the paths scanned so far. The rate behind - the ETA restarts when each path's scan phase ends, so that phase does - not lower the rate while the path is processed; until then the rate - is the previous path's. - -- 2026-10-08: Made a second `snapshot create` of one name succeed when - it starts in the same second as the first - ([issue #270](https://git.eeqj.de/sneak/vaultik/issues/270)). The - timestamp in a snapshot ID is in whole seconds, so the second run got - the first run's ID and failed with `UNIQUE constraint failed: - snapshots.id`. When the local index already has a snapshot with the - ID, the create now waits a second and takes a new timestamp. - -- 2026-10-07: Documented that `--json` skips the confirmation prompt of - `snapshot remove` and `prune` - ([issue #268](https://git.eeqj.de/sneak/vaultik/issues/268)). Both - commands delete without asking under `--json`, since a prompt on stdout - would break the JSON document, but the help and the README described - only `--force` as skipping it. The `--json` help of both commands and - their README entries now say so. - -- 2026-10-07: Made a symlink whose target cannot be read stop the backup - ([issue #269](https://git.eeqj.de/sneak/vaultik/issues/269)). It was - left out of the snapshot with only a debug log line, even without - `--skip-errors`. It now aborts the run, or with `--skip-errors` is - skipped with the `Failed to access` error line that any other entry - the scan cannot read gets. - -- 2026-10-07: Stopped a killed rclone upload from leaving a truncated - object under its key - ([issue #266](https://git.eeqj.de/sneak/vaultik/issues/266)). The - rclone backend wrote each object straight to its key, so killing an - upload to a local or sftp remote left a truncated object there; the - next backup found the key with `Stat`, skipped the upload and recorded - a snapshot that could not be restored. On a remote with a server-side - move, an object is now written under a temporary name ending in - `.partial` and moved into place, and listings skip such names. Remotes - without one are still written in place. - -- 2026-10-07: Made an interrupted command exit 130 and say so - ([issue #267](https://git.eeqj.de/sneak/vaultik/issues/267)). Ctrl-C - or SIGTERM during `snapshot create`, `snapshot restore` or `snapshot - verify` exited 0 with no error line (`snapshot verify --json` exited - 1, also without one), so a `--cron` run that never finished looked - like a success. A command stopped by either signal now exits 130 and - prints `interrupted before the command finished` on stderr, under - `--cron` and `--json` too. - -- 2026-10-07: Corrected documentation, help text and comments that were - false about the code - ([issue #233](https://git.eeqj.de/sneak/vaultik/issues/233)). A blob - is not streamed to storage. The README, `ARCHITECTURE.md` and - `config.example.yml` now say a backup needs free temporary space, - because each blob is written whole to a temporary file before it is - uploaded (up to about `blob_size_limit`; an rclone destination that - cannot stream uploads needs about twice that) and the metadata export - writes copies of the local index. Temporary files go to `$TMPDIR` - (default `/tmp`); with `TMPDIR` unset, SQLite writes one of those - copies to `/var/tmp`. Also corrected: the snapshot ID format, what restore - reads and how incomplete snapshots are removed in `docs/DATAMODEL.md`, - what `source_path` holds, the `index_path` and config file defaults, - what `snapshot remove` cleans up, how the release gets its Go - toolchain, and the `script/release` and `script/fmt-check` comments. - -- 2026-10-07: Cut the time the `internal/vaultik` and `internal/database` - tests take ([issue #235](https://git.eeqj.de/sneak/vaultik/issues/235)). - Most of the `internal/vaultik` time went to 24 tests that ran one at a - time only because they call `log.Initialize`; they now call it before - `t.Parallel()`, as the package's other tests do. `TestLargeDatasets` - committed each of its 1,500 inserts on its own and now makes them in - one transaction. `TestDedupOnlySnapshotRestores` gives its second - backup its own snapshot name instead of sleeping past the one-second - timestamp in the snapshot ID. - -- 2026-10-07: Made two messages say only what is true - ([issue #240](https://git.eeqj.de/sneak/vaultik/issues/240)). A config - file that others can read was warned about as containing S3 - credentials even when it set none, as a `file://` config does. The - warning now says the file may contain S3 credentials only when - `s3.access_key_id` or `s3.secret_access_key` is set, since either may - come from a `${...}` reference rather than the file, and otherwise - says the file is readable by others. `snapshot purge` against a - destination store it could not list gave an error with - `listing remote snapshots:` in it twice; the prefix now appears once. - -- 2026-10-07: Made `s3.part_size` set the multipart upload part size - ([issue #232](https://git.eeqj.de/sneak/vaultik/issues/232)). It was - loaded and defaulted but never passed to the S3 client, whose uploader - used a fixed 10MiB part. It now reaches the uploader for `storage_url` - and for the `s3.*` fields, and a part size S3 refuses, below 5MiB or - above 5GiB, `0` included, fails at config load. A blob too large for - S3's limit of 10,000 parts at the configured size is uploaded in larger - parts. The docs gave the default as `5MB`, which the config file reads - as 5,000,000 bytes, below the minimum; they now say `5MiB`. - -- 2026-10-07: Made per-name retention work when the hostname contains `_` - ([issue #230](https://git.eeqj.de/sneak/vaultik/issues/230)). A - snapshot ID is `hostname_name_timestamp`, and the name was read as - everything between the first and the last `_`, so with - `hostname: my_host` the name `home` came out as `host_home`. - `snapshot purge --keep-latest --snapshot home` then printed "No - snapshots to delete", and `snapshot create --prune` purged nothing - without a message. The name is now read using the hostname the - `snapshots` table stores with each snapshot, cut at its first `.` as it - is in the ID. - -- 2026-10-07: Made `remote info` stop reporting a snapshot's blobs as - orphaned when its manifest cannot be read, and stop printing raw - names from under `metadata/` - ([issue #228](https://git.eeqj.de/sneak/vaultik/issues/228)). A - manifest it failed to read was skipped, so that snapshot's blobs were - counted as orphaned and the report advised running `vaultik prune`. - The orphan figures are now unknown in that case, with no prune - advice, and `--json` gives them as `null` with the unreadable remote - keys in `unreadable_manifests`. A name under `metadata/` that is not - 64 lowercase hex characters is now skipped with a warning instead of - being printed, control characters included. A manifest under a - skipped name is then not read either, so it also leaves the orphan - figures unknown, and `--json` counts such manifests in - `skipped_manifest_count`. A directory with no manifest in it, as left - by an interrupted backup, leaves the figures known. - -- 2026-10-07: Made `config set` keep a string that looks like a number - ([issue #229](https://git.eeqj.de/sneak/vaultik/issues/229)). It wrote - every value unquoted, and `config.Load` reads the file through untyped - YAML, so an access key `00112233` loaded as `38043` and a hostname `007` - as `7`. A value for a string setting in `config.Config` is now tagged as - a YAML string, which the file quotes wherever YAML would read a number or - a boolean; other settings are still written unquoted. - -- 2026-10-07: Made a backup notice a file rewritten with its size - unchanged and a new mtime in the same second as the one in the index - ([issue #226](https://git.eeqj.de/sneak/vaultik/issues/226)). The - `files` table held mtime in whole seconds and the scanner compared - whole seconds, so every later snapshot kept the old content. A new - `mtime_nsec` column holds the nanoseconds within the second that - `mtime` holds, and the scanner compares the full mtime. A local index - created before the change lacks the column and is rebuilt with - `vaultik database delete` and a full backup. - -- 2026-10-07: Made taking the process-wide lock atomic - ([issue #227](https://git.eeqj.de/sneak/vaultik/issues/227)). The lock - read `vaultik.pid`, checked whether that PID was alive and then wrote - its own, so two writers started together could both pass the check and - both run. It is now an `flock` on `vaultik.pid`, held until the run - ends; the kernel drops it when the process exits, so a crash leaves no - lock behind. A clean exit now empties the file instead of deleting it, - because deleting it would let two later runs each lock a different - file. - -- 2026-10-06: Made `snapshot remove --json` write only its document to - stdout when the destination store cannot be reached - ([issue #251](https://git.eeqj.de/sneak/vaultik/issues/251)). Its - warning that the snapshot's metadata was left on the destination store - went to stdout ahead of the document, breaking `| jq` on a command that - exited 0. Under `--json` the warning now reaches stderr only, through - the logger. The warning, the README and the command's help said - `vaultik prune` would finish the cleanup, but `prune` never removes - snapshot metadata; they now say to run `vaultik snapshot remove` for the - snapshot again once the destination store is reachable. - -- 2026-10-06: Made the backup summary and the `snapshots` row count each - file, byte and upload once - ([issue #225](https://git.eeqj.de/sneak/vaultik/issues/225)). The - scanner added a file's bytes again for each new chunk and counted a - file as unchanged for each chunk already stored, so a first backup - reported twice its size and "backed up" could go negative. Upload - figures came from the progress reporter, which `--cron` turns off, and - `blob_count` counted earlier paths' blobs again for each later path. - The scanner now counts uploads itself; `blob_size`, - `blob_uncompressed_size` and `compression_ratio` describe the blobs - the snapshot references, and `docs/DATAMODEL.md` now says - `chunk_count` and `blob_count` count what the run added. - -- 2026-10-06: Made command output follow the README's stdout and stderr - rules ([issue #224](https://git.eeqj.de/sneak/vaultik/issues/224)). The - startup banner went to stdout, so a `completion` script or a - `config get` value started with it; the banner now goes to stderr. A - failing `remote info`, `prune` or `snapshot remove` under `--json` - printed nothing on either stream, and now reports its error on stderr. - `snapshot verify --quiet` printed its whole report; it now prints - none, and a failure still reaches stderr with the same exit status. - -- 2026-10-06: Made a backup without `--cron` of a snapshot with two or - more `paths` complete instead of panicking with `close of closed - channel` ([issue #253](https://git.eeqj.de/sneak/vaultik/issues/253)). - `Scan` runs once per path and started and stopped the progress - reporter each time, and a second stop panics. The reporter is now - started and stopped once per snapshot, around the scans of all its - paths. - -- 2026-10-06: Made a restore path argument select only that path and - what is beneath it - ([issue #223](https://git.eeqj.de/sneak/vaultik/issues/223)). The - lookup matched with SQL `LIKE`, so `/home/u/doc` also restored - `doc2`, `DOC` and `doc.txt.bak`, and a `_` or `%` in the path acted - as a wildcard. A backup used the same lookup to load the known files - of each configured path, so files of a longer sibling path were - counted as deleted. `FileRepository.ListUnderPath`, which replaces - `ListByPrefix`, returns the file at the path and every file whose - path starts with the path plus `/`, compared case-sensitively. - -- 2026-10-06: Made restore return an error instead of panicking on a - malformed snapshot database - ([issue #231](https://git.eeqj.de/sneak/vaultik/issues/231)). A chunk - hash shorter than 16 characters crashed the error message naming it, - and `--verify` dereferenced a missing `chunks` row and allocated - whatever chunk size the database gave. Those messages now go through - `shortHash`, a missing row is an error, and `--verify` rejects a - negative size and hashes each chunk as a stream. - -- 2026-10-06: Made `s3://bucket/prefix` and `s3://bucket/prefix/` the same - destination ([issue #222](https://git.eeqj.de/sneak/vaultik/issues/222)). - The S3 client put the prefix directly in front of each key, so a prefix - without a trailing slash stored `prefixblobs/...`. A non-empty prefix is - now joined to every key with one `/`, giving the README's - `//blobs/...` layout. The `s3.prefix` config setting goes - through the same client and gets the same join. - -- 2026-10-06: Made restore apply owners, modes and times in an order - that keeps them - ([issue #219](https://git.eeqj.de/sneak/vaultik/issues/219)). A - directory got its stored mode and mtime before its contents were - written, so a read-only directory came back without its files and a - non-empty one carried the time of the restore. Directories are now - created owner-only and get their stored owner, mode and mtime once the - restore loop is done, each before its parent. A file's mode is applied - after its chown, which on Linux clears setuid and setgid, and a - symlink gets its stored owner (as root) and mtime on the link itself. - -- 2026-10-06: Made `go.mod` what `go mod tidy` writes, so the - pre-commit hook no longer stops every commit - ([issue #246](https://git.eeqj.de/sneak/vaultik/issues/246)). A test - in `internal/cli` imports `github.com/spf13/pflag` directly, but - `go.mod` still marked it `// indirect`, and `script/precommit` fails - whenever the tidy changes `go.mod`. It is now in the direct `require` - block. - -- 2026-10-06: Made the README's steps for restoring on another machine - work ([issue #221](https://git.eeqj.de/sneak/vaultik/issues/221)). - `config init` wrote a placeholder recipient that `config.Load` - rejects, so every command on the new machine failed before reaching - the store. The file now has an empty `age_recipients` list, - `config.Load` accepts an empty list, and `snapshot create` refuses to - run without a recipient. - -- 2026-10-06: Made `snapshot restore --skip-errors` skip the files that - need a blob it cannot download - ([issue #218](https://git.eeqj.de/sneak/vaultik/issues/218)). A missing - or damaged blob ended the restore even with the flag, after restoring - whichever files happened to come first. Every file that needs such a - blob is now reported as failed, the rest are restored, and the command - still exits non-zero. Without the flag the blob error still aborts. - -- 2026-10-06: Re-vendored the canonical files from `sneak/prompts` at - `dd4027b` ([issue #213](https://git.eeqj.de/sneak/vaultik/issues/213)). - Linting and testing are now the `lint` and `test` phases of the - `Dockerfile`, and the build stage depends on both. `Dockerfile.lint`, - `CHECK_EPOCH` and the tests that checked them are gone; every - `docker build` in `script/` passes `--no-cache` instead. golangci-lint - is v2.14.0, with its new findings fixed in the code, and the rules in - `CLAUDE.md` now live in `AGENTS.md`. - -- 2026-10-06: Made the local index actually run in WAL mode with a busy - timeout ([issue #217](https://git.eeqj.de/sneak/vaultik/issues/217)). - The connection settings were written in a form the SQLite driver - ignores, so the index ran without either and `snapshot list` or `info` - during a backup could make the backup's next write fail with - `database is locked`. They are now `_pragma=` parameters, and the - metadata export copies the open index with `VACUUM INTO`, because a - copy of the file alone misses rows still in the `-wal` file. - -- 2026-10-06: Made a backup record the real uid and gid of files, - directories and symlinks - ([issue #216](https://git.eeqj.de/sneak/vaultik/issues/216)). The - scanner asked the stat result for `Uid()` and `Gid()` methods, which - `*syscall.Stat_t` does not have, so every entry was stored as `0:0` - and a restore as root gave every file to root. It now reads the - `Uid` and `Gid` fields of `*syscall.Stat_t`. - -- 2026-10-06: Made a `file://` destination whose directory is missing - count as one that cannot be listed - ([issue #220](https://git.eeqj.de/sneak/vaultik/issues/220)). The file - backend listed a missing directory as an empty store, so with the - quickstart's USB stick unplugged `snapshot list` reported every local - snapshot as missing from the store, `snapshot remove` claimed to have - removed metadata it never reached, and `prune` dropped every local - snapshot record. Listing a missing destination directory is now an - error; a first backup still creates the directory. - -- 2026-10-06: Made `--older-than` and `--keep-newer-than` reject a - duration with characters outside its number-and-unit parts - ([issue #215](https://git.eeqj.de/sneak/vaultik/issues/215)). The - parser picked out the parts it recognised and skipped the rest, so - `1.0y` became zero and `--prune --keep-newer-than 1.0y` deleted every - snapshot of the backed-up names, the new one included. `1.0y`, - `1,5y`, `30 days`, `x7d` and a bare `0` are now errors; decimals still - work in Go units such as `1.5h`. - -- 2026-10-06: Made a backup re-chunk a known file that lists a chunk no - uploaded blob holds - ([issue #214](https://git.eeqj.de/sneak/vaultik/issues/214)). File - rows are shared by every snapshot and updated in place, so removing or - pruning the only snapshot that referenced a changed file's current - blob left an older snapshot keeping a row that matched the disk while - no blob held its chunks. The next backup skipped the file and - completed a snapshot that could not restore it. - -- 2026-09-22: Routed the last direct-to-stdout command output through - `internal/ui` - ([issue #149](https://git.eeqj.de/sneak/vaultik/issues/149)). The - `version`, `info`, `remote info`, `config`, and `database delete` - commands wrote plain text straight to stdout, so they were unstyled and - ignored `--quiet`. Output now falls in two buckets, both governed by - `internal/ui`: status lines and confirmations go through its message - methods (styled, and `--quiet` silences them), while the data a command - exists to produce — the reports, the `snapshot list` table, `config get` - values, and the `--json` documents — is written plain. `--quiet` - silences the human reports and tables but never the `config get` value - or the `--json` documents, which a script depends on, and the - `database delete` confirmation prompt is always shown. The README - output-style section now states this rule. - -- 2026-09-22: Validated blob hashes, offsets and lengths read back from - the destination before using them - ([issue #155](https://git.eeqj.de/sneak/vaultik/issues/155)). A blob - hash taken from the downloaded database or the store listing was - trusted unchecked, so a hostile remote could drive a decrypted blob to - be written outside the cache directory (a hash like `aa/../../etc`) or - crash a command with a short or negative value. `blobDiskCache.path` - now refuses any key containing a path separator, and `ReadAt` rejects a - negative offset or length and bounds with `length > size-offset` so a - sum cannot overflow past the check. A new `isBlobHash` helper (a plain - function, not a method — the packer stores `temp-placeholder-{uuid}` as - a hash) gates `FetchBlob`, shallow and deep verify; the `blobs/` and - `metadata/` listings skip a non-conforming name with a warning; and - short-hash prefixes in log and error text go through a `shortHash` - helper that cannot panic. `verify`'s chunk reader also rejects a - negative `blob_chunks` length and streams the chunk instead of - allocating a database-supplied size. `restore.go` and - `internal/database` were left untouched to avoid colliding with the - in-flight [issue #156](https://git.eeqj.de/sneak/vaultik/issues/156) - work; the cache-path and `FetchBlob` guards already stop the unsafe - write and fetch, so restore's own `buildBlobIndexes` early check is - deferred as fail-fast defense in depth. - -- 2026-09-21: Stopped an interrupted blob upload from making a later - backup deduplicate against data that was never stored - ([issue #148](https://git.eeqj.de/sneak/vaultik/issues/148)). The - packer commits a blob's `chunks`, `blob_chunks`, and `blobs` rows - before the upload is attempted, so a failed upload left chunk rows - behind and the next run skipped re-uploading them, producing a - snapshot that reported success but could not be restored. A run now - deduplicates only against chunks held by a blob whose `uploaded_ts` is - set, and at startup drops any un-uploaded blob rows (and the chunks - they orphan) so the affected data is re-chunked and re-uploaded. Blobs - recorded with no remote backend are marked uploaded so this invariant - holds uniformly. - -- 2026-09-22: Made restore refuse any snapshot path that would write - outside the target directory - ([issue #154](https://git.eeqj.de/sneak/vaultik/issues/154)). - `restoreFile` and `verifyRestoredFiles` joined the stored path onto the - target with no containment check, so a `..` segment or an absolute path - escaped the target and a restored symlink could redirect a later child - write anywhere on disk. Every stored path is now rejected unless - `filepath.IsLocal` accepts it with the leading separator removed, and - each existing ancestor directory below the target is `Lstat`ed to refuse - descending through a symlink; honest symlinks pointing outside the tree - are still written verbatim. age decryption proves a snapshot is - readable, not honest, and restore usually runs as root. - -- 2026-09-21: Stopped `--json` from silencing stderr diagnostics - ([issue #112](https://git.eeqj.de/sneak/vaultik/issues/112)). `--json` - used to be folded into `Quiet`, which pinned the log level to `WARN`, - so `prune --json` gave a machine consumer no record of the local index - rows it deleted even under `--verbose`. `--json` now quiets only the - stdout UI (the JSON document must stay clean, per - [issue #108](https://git.eeqj.de/sneak/vaultik/issues/108)); the stderr - log level follows `--verbose`/`--debug` again. The coupling was - removed the same way for `snapshot verify`, `snapshot remove`, and - `remote info`, which carried it for the same outdated reason. - -- 2026-09-21: Stopped `prune` from reporting a failed row count as 0 - ([issue #96](https://git.eeqj.de/sneak/vaultik/issues/96)). The seven - `getTableCount` reads in `PruneDatabase` discarded their error, so a - query that could not run became a plausible `0` and the before/after - delta computed from it looked like real work. Each read now logs at - warn on failure and renders as `unknown`, never `0`, so an empty table - is distinguishable from one that could not be queried. The counts have - no `--json` representation — under `--json` the summary is suppressed - entirely — so nothing there can show a false `0`. - -- 2026-09-21: Made the s3 storage backend report a missing object as - `storage.ErrNotFound`, like the `file` and `rclone` backends and as the - `Storer` interface documents. `S3Storer.Get` and `Stat` returned the raw - AWS SDK error, so `errors.Is(err, storage.ErrNotFound)` was false on s3 - and callers branched differently per backend. Added a small `s3.IsNotFound` - helper (reused by `HeadObject`) and a test that a missing key maps to - `ErrNotFound` - ([issue #129](https://git.eeqj.de/sneak/vaultik/issues/129)). -- 2026-09-21: Fixed `verify --deep` reporting healthy snapshots as - corrupt. Its final blob-integrity check hashed the encrypted - downloaded bytes with a single SHA256 and compared that to the blob - ID, which is the double SHA256 of the plaintext, so the two could - never match. It now hashes the decompressed plaintext and compares the - double SHA256. Added a test that backs up a real snapshot, deep-verifies - it, then flips a byte in one stored blob and confirms deep verification - then fails - ([issue #131](https://git.eeqj.de/sneak/vaultik/issues/131)). - -- 2026-09-21: Made `snapshot create` VACUUM the per-snapshot metadata - database through the `modernc.org/sqlite` driver instead of shelling - out to the external `sqlite` command-line binary (issue #120). A - backup no longer needs that binary on `PATH`, so `make check` passes - on a stock `go install` host; `script/bootstrap` and the `Dockerfile` - (both the test-build and the shipped runtime stage) no longer install - it, and a new test asserts the uploaded database keeps no pages from - deleted rows. Dropped the now-false note on the 2026-08-07 entry below - that said bootstrap installs it. -- 2026-09-21: Made `.gitea/workflows/check.yml` run on pushes to `main` - and `next` and on pull requests against either, so unit PRs (whose - base is `next`) and `next` itself get a CI run instead of relying on a - local `make check` - ([issue #122](https://git.eeqj.de/sneak/vaultik/issues/122)). - -- 2026-09-21: Hash-verified the Go toolchain in the release workflow - ([issue #105](https://git.eeqj.de/sneak/vaultik/issues/105)). New - `script/install-go` downloads the exact `go.dev` archive for `go.mod`'s - `go` directive and refuses it unless its sha256 matches a value - committed in the script; `.gitea/workflows/release.yml` calls it - instead of `actions/setup-go`, which verified the downloaded toolchain - against nothing in the repo. `GOTOOLCHAIN: local` on the release step - keeps that exact compiler from auto-switching. Bumping Go now touches - `go.mod`, the checksum, and the `Dockerfile` `golang` digest together. - -- 2026-09-21: Collapsed the two duration parsers into one and fixed the - `--older-than` months example - ([issue #123](https://git.eeqj.de/sneak/vaultik/issues/123)). Two - functions named `parseDuration` existed with different grammars; - `snapshot purge --older-than` and `--keep-newer-than` both already went - through the one in `internal/vaultik`, while the richer copy in - `internal/cli/duration.go` was reachable only from its own test. Kept - the live-path parser and deleted the unused one, so no flag's accepted - grammar changes. The trap the issue was filed over: `README.md` - documented `6m` as the months example for `--older-than`, but `m` is - minutes, so the documented command deleted every snapshot older than - six minutes on a destructive flag. Corrected the doc to `6mo` and put - both flags' help text on one example list that states `m` is minutes - and `mo` is months. The surviving parser now rejects negatives, which - it previously accepted (`-5h`) or silently made positive (`-5d`). - Table-driven tests cover every unit, `6m` as six minutes, `6mo` as 180 - days, and rejection of a bare number, an unknown unit, and a negative. - -- 2026-08-10: Moved every lint run into its own container, as a build - step ([issue #113](https://git.eeqj.de/sneak/vaultik/issues/113)). - New root `Dockerfile.lint`, built by `script/lint`, runs - `golangci-lint run --config .golangci.yml ./...` as a `RUN` - instruction in the digest-pinned `golangci/golangci-lint` image: a - successful build of that file *is* a clean lint, and it works even - where the daemon is remote and bind mounts are impossible. That - `FROM` line is now the only pin of the linter version in the repo. - - This supersedes the per-worktree cache isolation landed for - [issue #99](https://git.eeqj.de/sneak/vaultik/issues/99). Isolation - fixed cross-worktree contamination but not lock contention — two - concurrent runs with entirely separate cache directories still - collided. A container per run has its own cache and its own lock, so - the whole class is gone, and with it the per-worktree cache - machinery, the lock-retry loop, and `script/lint-audit`, which - existed to catch replayed findings from a cache that no longer - exists. The host lint path went too: no escape hatch, no - `VAULTIK_LINT_IN_CONTAINER`, no version detection. Nothing lints on - the host at any version. - - A cached build lints nothing, so the same `CHECK_EPOCH` mechanism the - product `Dockerfile` already used is what makes the green mean - something: `ARG CHECK_EPOCH` with no default below the module layers, - a `RUN [ -n "$CHECK_EPOCH" ] || exit 1` guard, the value expanded - into each check command, and a fresh `$(date +%s%N)$$` per invocation - computed as a bare assignment. `cmd/vaultik/lintdocker_test.go` - parses both Dockerfiles and both scripts and fails if any part of - that is dropped, because every way of losing it is silent. No test - asserts that no script runs the host linter: `script/lint` is the one - lint entry point and runs `golangci-lint` only inside the container, - and keeping it that way is a review matter, not something a test - proves. - - The product `Dockerfile` lost its lint stage rather than gaining a - second linter pin: `make lint` is now `docker build`, so the stage - would have been docker-in-docker with no daemon, and calling - `golangci-lint` directly there would have restored the two-pins drift - of [issue #78](https://git.eeqj.de/sneak/vaultik/issues/78). - `make fmt-check` moved beside `make test` in the builder stage, and - `script/cibuild` now builds `Dockerfile.lint` and then `Dockerfile`, - each with its own fresh epoch. Consequence, stated rather than left - to be found: `script/docker` builds the product image only and no - longer lints; the gates are `script/check` and `script/cibuild`. - - `golangci-lint config verify` runs as its own epoch-keyed layer, - above the lint. `golangci-lint run` rejects a config it cannot parse - but silently ignores an unknown top-level *key*: renaming `linters:` - to `linterz:` discarded `default: all` and every threshold and still - exited 0 on a tree the real config fails. `config verify` catches - that, and it does so with the network off at this pin — checked under - `docker run --network none`, not assumed. An earlier revision omitted - it on the claim that it fetches its schema over live HTTPS; that - claim was false at v2.12.2. - - `script/lint-fix` is kept, reimplemented as a - bind-mounted `docker run` against the image parsed out of - `Dockerfile.lint` — it cannot be a build step, because fixes have to - land in the worktree — and marked in its header as a developer - convenience that no gate reads. - -- 2026-08-09: Finished the `--json` stdout contract and gave `make build` - a rule ([issue #108](https://git.eeqj.de/sneak/vaultik/issues/108), - [issue #110](https://git.eeqj.de/sneak/vaultik/issues/110)). Two - unrelated defects of the same shape — a command reporting something it - did not do — landed together because both are small. - - `CleanupLocalSnapshots` wrote three prose lines to stdout with no - `--json` awareness, covering every branch of the function, so no input - avoided them and `vaultik prune --json | jq` failed even after - [issue #106](https://git.eeqj.de/sneak/vaultik/issues/106) removed the - banner. `-q` never helped either: `printlnStdout` and `stdoutf` write - straight to `Vaultik.Stdout` and never consult `Vaultik.UI`, which is - what `SetQuiet` affects. The issue offered three fixes and asked for a - decision. Taken: thread `*PruneOptions` into the function and gate each - write on `!opts.JSON`, matching `PruneBlobs` (its sibling phase, which - already takes the same struct), `RemoveSnapshot` and `remote info`, so - the package has one pattern rather than two. Rejected: moving the lines - to `log.Info`, because the logger's default level is `slog.LevelWarn`, - so that would not relocate them to stderr — it would delete them from a - plain `vaultik prune`, and the removal of rows from the local index is - not something to narrate only under `--verbose`. Also rejected: putting - the stale-record count into `PruneBlobsResult`, whose every field is - blob-scoped and which is produced by the later phase; a prune document - covering both phases is a reasonable thing to want, but it is a schema - design question and not a stream-hygiene fix. The narration is - duplicated as `log.Info` records, which `PruneBlobs` already does - alongside its own prints, so the events survive on stderr for anyone - running `--verbose`. - - `make build` printed "Nothing to be done for 'build'" and exited 0 - without producing a binary: `build` was listed in `.PHONY` with no - `build:` rule anywhere, and declaring a name phony is exactly what - converts make's "No rule to make target" error into a silent success. - Fixed with `build: vaultik`, keeping `vaultik:` as the file rule. The - audit the issue asked for covers all 19 `.PHONY` names; `build` was the - only one without a rule, and `vaultik` is correctly absent from - `.PHONY`, being a real file target. - - Tests, each verified to fail with the fix reverted rather than assumed - to: `CleanupLocalSnapshots` leaves stdout untouched under `--json` in - all three branches (stale records, none, empty index) and still emits - every line without it, so the guard cannot be satisfied by deleting the - output; `prune --json` run end to end through `Entry`, cobra and fx - over the process's real stdout descriptor against a `file://` store, - asserting exactly one JSON document, in both the stale and non-stale - branches; and a parse of the `Makefile` asserting every `.PHONY` name - has a rule and that `build` reaches the rule that produces the binary, - which keeps the audit true for names added later. That last one is a - parse rather than an invocation of `make`, since `make test` is what - runs it and shelling back into `make build` would nest a build inside - the test run. The property a parse cannot establish — that the recipe - still fails when the build fails — was verified by hand against a - deliberately broken tree: `make build` exits 2 and produces nothing. - `cmd/vaultik` gains its first test file, so `make test` now reports 16 - packages `ok` where it reported 15. - -- 2026-08-09: Stopped the startup banner from contaminating `--json` - documents ([issue #106](https://git.eeqj.de/sneak/vaultik/issues/106)). - `Entry` writes the banner to stdout before cobra parses anything, and - the flag scan that suppresses it knew `--quiet`, `-q` and `--cron` but - not `--json`, so every `--json` document arrived behind two lines of - prose and a blank line, and `vaultik snapshot list --json | jq` failed. - With the logger already on stderr from - [issue #82](https://git.eeqj.de/sneak/vaultik/issues/82), this was the - last writer that could put something on stdout that the caller did not - ask for. The design question the issue raised — extend the raw-argv - scan, or move the banner after parsing — is answered in favour of the - scan: the banner is printed first deliberately, so that it still - appears when cobra rejects the arguments and on `--help`, and after - parsing there is no single place that covers those paths. The stated - cost of the scan, that `--json` is a subcommand flag matched anywhere - in the vector, is a cost `--cron` already carries — it exists only on - `snapshot create` — so this adds an instance of an accepted - imprecision rather than a new kind, and the two error directions are - not symmetric: a false positive loses a decorative banner, a false - negative corrupts a document. Regression tests at the CLI layer, where - `internal/vaultik`'s existing guard cannot reach: one runs `Entry` - itself over the process's real stdout descriptor, through cobra and fx - to the document, made hermetic by `file://` storage; a second covers - the argument vectors of all five `--json` commands; a third asserts the - banner is still printed without a suppressing flag, so the first - cannot be satisfied by deleting the banner. Also corrected `AGENTS.md` - policy 9, which still keyed the structured-log format on stdout's - TTY-ness after #82 moved that decision to stderr — a rules file that - misdescribes the code misleads exactly the readers who trust it most. - Two smaller findings from the same review: `bytesAttrKey`'s - human-readable byte formatting silently stopped applying under an open - group, because the key reaching the comparison is group-qualified - (`transfer.bytes`), now matched on its final segment and tested both - ways; and `listEnv.stderr` in `snapshot_list_test.go`, assigned but - never read since those tests began capturing the process's stderr, is - removed. `Vaultik.Stderr` is kept — nothing writes to it today, which - its comment now says outright. - -- 2026-08-09: Moved the logger to stderr and fixed `TTYHandler`'s - discarded attributes - ([issue #82](https://git.eeqj.de/sneak/vaultik/issues/82), - [issue #97](https://git.eeqj.de/sneak/vaultik/issues/97)). Two defects - in `internal/log`, fixed together because both live in the handler - construction path. The first: both handlers were built over - `os.Stdout`, and `WARN`/`ERROR` are never suppressed, so a config file - with group- or world-readable permissions was enough to put a log - record inside a `--json` document and break `jq`. Diagnostics now go - to stderr, and the TTY/JSON format choice follows stderr rather than - stdout — testing the wrong stream would colorize records on a - redirected stderr whenever stdout happened to be a terminal. This is - user-visible: `--verbose` and `--debug` output moves to stderr too, - which is documented in `README.md` under "stdout and stderr". It also - let the local workaround in `internal/vaultik/snapshot_list.go` go: - `warnWhileListing` had been hand-rolling structured-log formatting to - reach a non-stdout writer, and the `jsonOutput` parameter threaded - through the remote-listing helpers existed only to choose between the - two writers. The collect-then-emit machinery around `listingWarning` - stays, but on its remaining merit — warnings emitted in key order - after `group.Wait()` are deterministic run to run, where emitting from - the fetch workers would order them by network timing. The second - defect: `TTYHandler.WithAttrs` and `WithGroup` discarded their - arguments and returned the receiver while their doc comments claimed - otherwise, so `log.With` attributes vanished on a terminal and - appeared correctly in CI — failing precisely when someone is debugging - interactively. Both now return a new handler (the receiver is never - written to, since `slog` permits concurrent derivation), attributes - persist across records, and grouping is implemented as dotted key - prefixes, which is the only honest rendering for a format with nowhere - to nest. New tests cover both, including one that feeds the same - derivation chain to the TTY and JSON handlers and compares the - attribute sets, so the two paths cannot drift apart again. Found and - filed while verifying: the startup banner is written to stdout and - `--json` does not suppress it - ([issue #106](https://git.eeqj.de/sneak/vaultik/issues/106)), which is - a separate writer on a separate path and the remaining source of - stdout contamination. - -- 2026-08-09: Made the tagged-release path actually work on Gitea - ([issue #65](https://git.eeqj.de/sneak/vaultik/issues/65)). Three - independent blockers, one of which was the whole - release: `.goreleaser.yaml` had no `gitea_urls:` block, so goreleaser - defaulted to the GitHub API and a `goreleaser release` from this repo - would have failed or published where nobody is looking. It now points - at `https://git.eeqj.de/api/v1`. The version is the second: it was a - hardcoded `VERSION := 1.0.0-rc.1` in the `Makefile`, so every local - build claimed to be a release candidate that had never been tagged and - did not exist, while `git tag -l` was empty and `internal/globals` - defaulted to `dev`. Version now comes from git via the new - `script/version` — the exact tag with a leading `v` stripped (so a - `make` build and a goreleaser build of one commit report the same - string, and it matches the archive names), otherwise `dev-<12-char - sha>`, with `-dirty` appended in either case when tracked files are - modified. Untracked files are deliberately not counted, matching - `git describe --dirty`. The same honesty was owed by the snapshot - path: `snapshot.version_template` was `{{ incpatch .Version }}-next`, - which manufactures a release number from the last tag and, with no - tags at all, from goreleaser's fabricated `v0.0.0`; it now emits the - same `dev-`. The one non-obvious consequence is that - `internal/cli/version.go` gated its "this is a development build" - notice on the version being exactly `dev`, so the moment untagged - builds began carrying a commit sha that notice would have gone silent - and an unreleased binary would have read as a release — the gate is - now `globals.IsDevVersion`, which is a predicate over a string rather - than a comparison against a global precisely so it can be tested, and - it is tested at the boundary (`1.0.0-dev` is a release, `dev-` - is not). Release automation is the third blocker: a tag-triggered - `.gitea/workflows/release.yml` runs the build in CI rather than from - a laptop, with `fetch-depth: 0` because a shallow checkout has no - tags and would silently mislabel the release, and with the - `RELEASE_TOKEN` repository secret passed as `GITEA_TOKEN` (documented - in `README.md`; the runner's automatic token is not used because it - is not guaranteed to carry release write scope). `script/release` - unsets any `GITHUB_TOKEN`/`GITLAB_TOKEN` it finds, since goreleaser - chooses its forge from whichever token variable is set and refuses to - run when it sees more than one — a runner-provided token must not get - to decide where these artifacts are published. `make release` and - `make release-snapshot`, the last two Makefile targets that were not - shims, now call `script/release` and `script/release-snapshot`, which - resolve goreleaser exactly the way `script/lint` resolves the linter: - a `PATH` binary is used only at the pinned version, never as a silent - fallback. `script/bootstrap` installs it, from a sha256-verified - GitHub release archive per `REPO_POLICIES.md`, via a separate - `script/install-goreleaser` — separate because `script/bootstrap` - hard-fails without a usable Docker daemon by design, and the release - runner needs goreleaser without needing Docker. Verified by running - the thing rather than reading it: `make release-snapshot` produced - four archives and `checksums.txt`, and the linux/amd64 binary from - `dist/` reports `dev-` with the development-build notice. Tag - handling was exercised in a throwaway repository rather than by - tagging this one; no tag was created here, since that is the owner's - call. Signing, SBOM, reproducible builds, completions and a man page - are out of scope by the issue. - -- 2026-08-09: Isolated the lint cache per worktree and context-gated the - native lint path (issues #99, #80). One defect seen twice: - `script/lint` decided whether it could skip the pinned image by asking - what version was on `PATH` rather than where it was running, and cache - isolation is part of that same question. The cache was one directory - per repo, shared by every worktree on the host, so two checkouts with - identical Go file contents collided and golangci-lint replayed the - stored analysis — paths and all. The loud direction of that failure - (a clean tree failed by a dirty sibling) is the harmless one; the - silent direction, a dirty tree **passed** by a clean sibling, is a - sixth way for a gate here to report a green it did not earn. The cache - is now keyed on a digest of the worktree path, and every run is - audited by the new `script/lint-audit`, which rejects output citing any - file that is not in the tree being linted — a backstop that runs on - clean output too, because that is the case nobody investigates. Caches - record the worktree they belong to and are collected when it - disappears, so throwaway worktrees do not accumulate them; the whole - tree lives under `XDG_CACHE_HOME` and is disposable. The - `parallel golangci-lint is running` refusal is now a bounded retry - rather than a verdict: it is not a lint result, and exiting non-zero - on it is indistinguishable to a caller from real findings (#88 showed - a private cache does not remove that contention). The native path now - requires `VAULTIK_LINT_IN_CONTAINER=1`, set only by the `Dockerfile` - lint stage, in addition to matching the pin, so a developer's locally - installed 2.12.2 no longer bypasses the digest pin; `/.dockerenv` was - rejected as the signal because `dockerd` creates it for `docker run` - and it is not reliably present during a BuildKit `docker build`, which - is the case the exception exists for. Version detection uses - `golangci-lint version --short` with the old banner scrape kept only - as a fallback. `script/bootstrap` no longer prints `bootstrap - complete` on a machine that cannot run the gate: a missing docker, or - one whose daemon is unreachable, is a hard failure naming exactly what - breaks. Verification was by reproduction rather than inspection — two - concurrent lints from two worktrees of differing cleanliness, a real - run made to report an outside path, a matching linter shimmed onto - `PATH`, and a `PATH` with docker removed — and is recorded on the pull - request. -- 2026-08-09: Closed the fifth false-green mechanism (issues #93, #69). - `script/test` omitted `-count=1`, so Go's test result cache could - satisfy the gate outright: a second back-to-back `make test` printed - the full set of 14 `ok` lines, every one marked `(cached)`, having - executed no test at all. Since `ok (cached)` is an `ok` line, - the "14 `ok` lines means the suite ran" signal this repo leans on was - forgeable, one level below the Docker layer cache that #85 addressed. - Fixed with `-count=1` unconditionally rather than only in the - container, because the pre-commit hook runs the same script and a - gate honest only in CI is dishonest where people rely on it most; - `test-coverage` got the same flag, and `script/check` inherits it by - calling `script/test`. In the same area, `make test-integration` was - deleted rather than made real: no file in the repo carried a build - tag, so `-tags=integration` selected nothing and the target was an - exact duplicate of `make test`. Tagging a subset was rejected because - the entire suite runs in well under a minute, and a scheme whose - failure mode is "some tests silently stopped running" is a poor trade - for those seconds in a repo with this particular history. The - `-timeout` was raised from 30s after measuring rather than after - assuming: the standing claim that cold-cache compilation is charged - against `-timeout` is **false**, disproved by a containerised run - that spent 46s compiling and still reported per-package durations - within noise of a warm host run. `-timeout` reaches the test binary - as `-test.timeout` and its clock starts inside `testing.M.Run`, after - the build. The real exposure was margin, not compilation. The 120s - landed on is a **deliberate, documented divergence** from - `REPO_POLICIES.md:192`, which mandates 30s, and from that file's - canonical recipe at `:212-214`; the divergence is recorded in - `script/test`'s comment because `REPO_POLICIES.md` is org-canonical - and not editable here, and issue #101 proposes amending the policy - text upstream. Numbers and the full verification are recorded once, - on the pull request, and are deliberately not restated here. - -- 2026-08-09: Triaged all fifteen stale remote branches (issue #71) and - deleted fourteen of them; the full per-branch disposition with - evidence is recorded on that issue. Method mattered more than the - outcome here: a three-dot `git diff main...branch` diffs from the - merge base, so it replays everything that landed on `main` after the - branch diverged and makes any old branch look like it holds unlanded - work. That artifact is what made `golangci-v2.12.2` appear to carry - 126 files of unpushed changes when its tree was byte-identical to - `main`'s. Every containment claim here therefore rests on two-dot tip - diffs, tree-hash equality, `git cherry`, and `git branch -r --merged`. - Nine branches were plain ancestors of `main` with zero `git cherry` - `+` commits. `golangci-v2.12.2` had landed squashed as `cc58583`, - whose tree hash equals the branch tip's exactly; note the hash - recorded in the issue had gone stale because `main` advanced, so the - check had to be redone rather than repeated. - `fix/sync-snapshot-cleanup` was redundant, its one line already on - `main` in `syncWithRemote`. `feature/restore-progress-bar` was - superseded by `printRestoreProgress` and the disk-backed blob cache, - and had become actively regressive — it would have deleted - `internal/blobgen/compress_test.go`, the #28 regression test that - landed separately. The two branches this issue was filed for both - turned out to be closed questions that `main` had already moved past - by a recorded decision, so neither was landed and no regression test - was owed: `ctime` no longer exists anywhere in the codebase after - `1c72a37` removed the column, the `File.CTime` field and every use - (#54/#55), and change detection compares size, mtime, mode, uid and - gid only, exactly as `ARCHITECTURE.md` documents — so the - silently-skipped-file data-loss risk that made this a 1.0 item does - not exist. The SQL allow-list branch would have reverted `bfd7334`, - which replaced that very allow-list with regex sanitisation on review - feedback, and would have broken `getTableCount("snapshots")` because - its allow-list omits that table. `feature/daemon-mode` is untouched - and deferred to #94 pending an owner decision, so it is the one - branch besides `main` still on the remote. The stale `TODO.md` entry - named in the issue needed no fix: `e496aa3` had already removed it. - No product code changed. -- 2026-08-09: Adopted the remaining upstream `CHECK_EPOCH` hardening - (issue #91), closing the gap #85 knowingly left open. Four changes, - all four decided as adopt upstream in `sneak/prompts` #26. (1) Each - check stage now asserts `[ -n "$CHECK_EPOCH" ] || exit 1` before - running anything, so a build that supplies no `--build-arg` fails - instead of lying. This is the item that mattered: an unset `ARG` is - an empty string and an empty string is a stable cache key, so the - second and every later bare `docker build .` on an unchanged tree - replayed all three check layers and still exited 0 — and `docker - build .` is the command `REPO_POLICIES.md` names verbatim as a thing - that must be green, so the documented command was precisely the one - that lied. Failed steps are never cached, which is what makes the - guard fire on every invocation rather than once. (2) The epoch is now - expanded into each check command rather than left as a bare - declaration, so the cache miss no longer depends on BuildKit's - unreferenced-`ARG` handling staying as it is, and the value appears - in the build log. (3) `script/cibuild` uses - `epoch="$(date +%s%N)$$"`, unique per invocation rather than per - second; `%N` alone is insufficient because busybox drops it silently - and exits 0, and `$$` is what makes the guarantee hold regardless. - The bare-assignment form is kept deliberately — inlined in an - argument, a failing substitution does not abort under `set -eu` and - would yield an empty constant epoch, restoring the exact false green - being fixed. (4) `script/docker` passes the same fresh arg, so the - two entrypoints cannot disagree about whether the tree is green; - local builds are almost always warm, which made it the likelier - fooling in practice. The `ARG` placement from #85 is unchanged, below - `apk add`, `COPY go.mod go.sum` and `go mod download`, so dependency - layers still cache and the build is not cold. Verified by negative - control rather than inspection — a bare `docker build .` run twice - back to back, plus back-to-back pairs of both scripts and a host-side - `make check`; the measurements are recorded once, in the PR - verification comment, rather than restated here. `.golangci.yml`, the - lint-stage `FROM` line and its digest, `script/lint`, - `REPO_POLICIES.md` and `.gitea/workflows/check.yml` are all - untouched. -- 2026-08-09: Stopped `script/cibuild` from reporting a green it did - not earn (issue #85). A bare `docker build .` let Docker serve the - check layers from the layer cache whenever the tree had not changed: - the checks never executed and the build still exited 0. The fix is an - `ARG CHECK_EPOCH` declared immediately above the check `RUN`s in both - the lint stage and the builder stage (`ARG` scope is per-stage, so - each declares its own), with `script/cibuild` assigning - `epoch="$(date +%s)"` and passing `--build-arg CHECK_EPOCH="$epoch"`. - The assignment is separate on purpose: under `set -eu` a command - substitution that fails inside an argument does not abort the script, - which would leave an empty constant `CHECK_EPOCH` and restore the - very false green being fixed. Placement is the rest of the point — - the `ARG` sits below the `apk add`, `COPY go.mod go.sum`, and `go mod - download` layers, so only the checks are invalidated and the - dependency layers still cache. The guarantee is conditional on a - fresh value rather than absolute: a bare `docker build .` gets an - empty `CHECK_EPOCH` and can still serve the check layers from cache, - which `README.md` and the `Dockerfile` now say plainly, with issue - #91 tracking the upstream hardening (expanded `ARG` form, unset - guard, per-invocation epoch, `script/docker`) that would close it. - Verified by re-running the reproduction plus the withheld-`--build-arg` - counterfactual; the measurements are recorded once, in the PR #89 - verification comment, rather than restated here. `.golangci.yml`, the - lint-stage `FROM` line and its digest, `script/lint`, and - `.gitea/workflows/check.yml` are all untouched. -- 2026-08-09: Corrected the `Vaultik.UI` doc comment (issue #84). It - claimed the cli layer replaces the writer with a discarding one in - `--cron` mode; the actual mechanism is `UI.SetQuiet(true)` in - `setupGlobals`, which drops Begin/Complete/Info/Notice/Detail/ - Progress/Banner but still emits Warning and Error. The `--cron` line - in `README.md` said "Silent unless error", which understated what - survives, and now names warnings too. The other `--cron` comments - (`internal/log/log.go`, `internal/cli/snapshot.go`, - `internal/vaultik/snapshot.go`) were audited and already accurate. - Comments and docs only, no behavior change. -- 2026-08-09: Made `snapshot list` list the destination store without - the private key (issue #64). The listing is now the union of the - local index and a single streamed listing of the `metadata/` prefix, - with no `age_secret_key` gate — the manifest is unencrypted, so a - host holding only the public key can enumerate its own backups and a - host that lost its local index can still see them. A remote-only - snapshot's hostname and name are deliberately not recovered (they are - not recoverable without the private key, and making them so would - undo the privacy property tracked in issue #81); such rows are - labelled by an abbreviation of their remote key and carry the real - timestamp and compressed size from the manifest, with `` - in the two columns that require the local index. Local-only snapshots - are reported as drift, and the hint now names `vaultik prune`, which - exists, instead of `vaultik snapshot cleanup`, which does not. - `reportRemoteDrift` collapsed into the merged view. Every remote - manifest read in the codebase now goes through - `downloadManifestByKey`, so issue #81 has one call site to change. - Review rework: snapshot timestamps now normalize to UTC in - `scanSnapshotRows`, the one place they enter the domain, so the merged - TIMESTAMP column cannot show local time for a locally tracked row and - UTC for a remote-only row on a non-UTC host; `GetIncompleteByHostname` - was folded onto that same scanner. `--json` now reports the - unreadable-manifest count and the 1000-row truncation on stderr - instead of returning a silently short document (the document's shape - is unchanged). The two per-snapshot `log.Warn` calls on the listing - path now route through the same JSON-aware writer as the existing - workaround, so one corrupt manifest can no longer put a log line on - stdout ahead of the document and break `| jq` — still a local - workaround pending issue #82. Verified with `script/cibuild` and with - an uncached `make check` (`0 issues.`, no cached test packages), plus - end to end against a `file://` destination with no secret key present. -- 2026-08-09: Closed the gap between `make lint` and CI (issue #78). - `script/lint` now runs the digest-pinned `golangci-lint` image taken - from the `Dockerfile` lint stage, which is the single source of truth - for the linter version; the duplicate pin in the `Makefile` `deps` - target and the unpinned `golangci-lint` install in `script/bootstrap` - are gone. A `golangci-lint` on `PATH` is used only when its version is - exactly the pinned one (which is how the lint stage runs it inside the - container); anything else goes through Docker, and a missing or - unreachable Docker daemon is a hard error rather than a silent - fallback. Only the **lint** leg of `make check` became equivalent to - `script/cibuild`; its tests and `gofmt` still run on the host against - the host toolchain, as `README.md` states. An earlier version of this - entry claimed `make check` was "as trustworthy as `script/cibuild`" - outright, which overstated it; corrected under issue #80. -- 2026-08-09: Finished the lint remediation under the canonical - `.golangci.yml` (issue #61, which also unblocks issue #59). The - remaining findings were fixed behavior-preservingly: `wsl_v5` - whitespace, `sqlclosecheck`, and `prealloc`. The `sqlclosecheck` sites - now close `sql.Rows` in a deferred closure instead of via the - `CloseRows` helper, which the linter could not see through. Only the - `revive` package-name findings remain suppressed, with per-site - `//nolint` directives; the package-rename question behind them is - tracked in issue #76. Verified with `script/cibuild`, which exits 0 — - that is the only trustworthy gate, because `script/lint` runs whatever - `golangci-lint` happens to be on `PATH` rather than the pinned - v2.12.2 that CI and the `Dockerfile` use, so `make check` can report - green on findings CI still fails. That tooling gap is tracked in issue - #78. -- 2026-08-09: The earlier next step "reconcile the uncommitted - `ARCHITECTURE.md` edits on `main`" needed no work: the working tree is - clean and `ARCHITECTURE.md` is committed on `main`. -- 2026-08-07: Updated golangci-lint to v2.12.2 everywhere it is pinned - (`Dockerfile` lint stage, `Makefile` deps target), replaced - `.golangci.yml` with the canonical config (v2 schema, `default: all`), - and remediated the bulk of the lint findings it surfaced (issue #61): - behavior-preserving fixes across every package, 2,990 findings down to - 80. `make test` and `make fmt-check` were green at that point but - `make lint` was still red; the commit message claiming `make check` - was green was wrong. -- 2026-08-07: Added the standard `.golangci.yml` and `.editorconfig` - (issue #59); lint findings under the new config are tracked in issue - #61. -- 2026-07-07 Adopted scripts-to-rule-them-all: `script/` entrypoints, - Makefile shims, README Entrypoints section -- 2026-07-02: Consolidated CLI verbs, retired overlapping commands; bound - the local index to its backup destination URL. -- 2026-06-28: snapshot rm now removes metadata only and prints the prune - command; restore skips chown when running as non-root. -- 2026-06-26: Snapshot IDs hashed at the storage boundary; snapshot list - made resilient to bad remote entries. -- 2026-06-24: Collapsed snapshot prune into vaultik prune; restore streams - blobs to disk and restores files in blob-locality order; cron output - fixes. -- 2026-06-17: Restore overhaul: ReadAt chunk reads from cached blobs, - reference-counted blob sweeper, integration tests; new internal/ui - output layer, banner, and progress lines. -- 2025-12-18: Added ARCHITECTURE.md and godoc coverage for exported API. -- 2025-07-26: End-to-end integration tests; manifest format refactor; - renamed backup to snapshot; afero filesystem abstraction. -- 2025-07-20: Initial design and implementation: cobra + fx CLI skeleton, - SQLite index database, UUID blob storage with streaming chunking. - -# Future Steps - -Work planned after 1.0 is listed in the README -[roadmap](README.md#roadmap). diff --git a/config.example.yml b/configs/config.example.yml similarity index 100% rename from config.example.yml rename to configs/config.example.yml diff --git a/ARCHITECTURE.md b/docs/ARCHITECTURE.md similarity index 83% rename from ARCHITECTURE.md rename to docs/ARCHITECTURE.md index b41dc22..d345555 100644 --- a/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,10 +1,14 @@ # Vaultik Architecture -This document describes the internal architecture of Vaultik, focusing on the data model, type instantiation, and the relationships between core modules. +This document describes the internal architecture of Vaultik, focusing on the +data model, type instantiation, and the relationships between core modules. ## Overview -Vaultik is a backup system that uses content-defined chunking for deduplication and packs chunks into large, compressed, encrypted blobs for efficient cloud storage. The system is built around dependency injection using [uber-go/fx](https://github.com/uber-go/fx). +Vaultik is a backup system that uses content-defined chunking for deduplication +and packs chunks into large, compressed, encrypted blobs for efficient cloud +storage. The system is built around dependency injection using +[uber-go/fx](https://github.com/uber-go/fx). ## Data Flow @@ -53,57 +57,88 @@ The database tracks five primary entities and their relationships: ### Entity Descriptions #### File (`database.File`) -Represents a file, directory, or symlink in the backup system. Stores metadata needed for restoration: + +Represents a file, directory, or symlink in the backup system. Stores metadata +needed for restoration: + - Path, mtime - Size, mode, ownership (uid, gid) - Symlink target (if applicable) -It also stores `source_path`, the source directory the scan found it under, made absolute and with symlinks resolved. Restore does not read it. +It also stores `source_path`, the source directory the scan found it under, made +absolute and with symlinks resolved. Restore does not read it. #### Chunk (`database.Chunk`) -A content-addressed unit of data. Files are split into variable-size chunks using the FastCDC algorithm: + +A content-addressed unit of data. Files are split into variable-size chunks +using the FastCDC algorithm: + - `ChunkHash`: SHA256 hash of chunk content (primary key) - `Size`: Chunk size in bytes -Chunk sizes vary between `avgChunkSize/4` and `avgChunkSize*4` (2.5MB-40MB for the 10MB default average). +Chunk sizes vary between `avgChunkSize/4` and `avgChunkSize*4` (2.5MB-40MB for +the 10MB default average). #### FileChunk (`database.FileChunk`) + Maps files to their constituent chunks: + - `FileID`: Reference to the file - `Idx`: Position of this chunk within the file (0-indexed) - `ChunkHash`: Reference to the chunk #### Blob (`database.Blob`) -The final storage unit uploaded to S3. Contains many compressed and encrypted chunks: + +The final storage unit uploaded to S3. Contains many compressed and encrypted +chunks: + - `ID`: UUID assigned at creation -- `Hash`: `hex(SHA256(SHA256(uncompressed blob contents)))`, computed before compression and encryption (see [docs/REPOSTRUCTURE.md](docs/REPOSTRUCTURE.md#blobs-directory-blobs)) +- `Hash`: `hex(SHA256(SHA256(uncompressed blob contents)))`, computed before + compression and encryption (see + [docs/REPOSTRUCTURE.md](REPOSTRUCTURE.md#blobs-directory-blobs)) - `UncompressedSize`: Total raw chunk data before compression - `CompressedSize`: Size after zstd compression and age encryption - `CreatedTS`, `FinishedTS`, `UploadedTS`: Lifecycle timestamps Blob creation process: + 1. Chunks are accumulated (up to MaxBlobSize, typically 10GB) 2. As each chunk is added, its uncompressed bytes are fed to a running SHA-256 -3. Concurrently, the same bytes are compressed with zstd, then encrypted with age (recipients configured in config), and written to a temporary file -4. On finalize, the blob's name is the double SHA-256 of the uncompressed contents — `hex(SHA256(SHA256(...)))` — not a hash of the compressed, encrypted bytes -5. The finished file is uploaded to `blobs/{hash[0:2]}/{hash[2:4]}/{hash}` and then deleted +3. Concurrently, the same bytes are compressed with zstd, then encrypted with + age (recipients configured in config), and written to a temporary file +4. On finalize, the blob's name is the double SHA-256 of the uncompressed + contents — `hex(SHA256(SHA256(...)))` — not a hash of the compressed, + encrypted bytes +5. The finished file is uploaded to `blobs/{hash[0:2]}/{hash[2:4]}/{hash}` and + then deleted -A backup needs free temporary space, because each blob is written whole to a temporary file before it is uploaded (up to about `blob_size_limit`; an rclone destination that cannot stream uploads needs about twice that) and the metadata export writes copies of the local index. Temporary files go to `$TMPDIR` (default `/tmp`); with `TMPDIR` unset, SQLite writes one of those copies to `/var/tmp`. +A backup needs free temporary space, because each blob is written whole to a +temporary file before it is uploaded (up to about `blob_size_limit`; an rclone +destination that cannot stream uploads needs about twice that) and the metadata +export writes copies of the local index. Temporary files go to `$TMPDIR` +(default `/tmp`); with `TMPDIR` unset, SQLite writes one of those copies to +`/var/tmp`. #### BlobChunk (`database.BlobChunk`) + Maps chunks to their position within blobs: + - `BlobID`: Reference to the blob - `ChunkHash`: Reference to the chunk - `Offset`: Byte offset within the uncompressed blob - `Length`: Chunk size #### Snapshot (`database.Snapshot`) + Represents a point-in-time backup: -- `ID`: Format is `{hostname}_{snapshot-name}_{RFC3339}` (e.g. `server1_home_2025-06-01T12:00:00Z`) + +- `ID`: Format is `{hostname}_{snapshot-name}_{RFC3339}` (e.g. + `server1_home_2025-06-01T12:00:00Z`) - Tracks file count, chunk count, blob count, sizes, compression ratio - `CompletedAt`: Null until snapshot finishes successfully #### SnapshotFile / SnapshotBlob + Join tables linking snapshots to their files and blobs. ### Relationship Summary @@ -140,21 +175,27 @@ fx.New( ### Key Type Instantiation Points #### 1. Config (`config.Config`) + - **Created by**: `config.Module` via `config.LoadConfig()` - **When**: Application startup (fx DI) -- **Contains**: All configuration from YAML file (S3 credentials, encryption keys, paths, etc.) +- **Contains**: All configuration from YAML file (S3 credentials, encryption + keys, paths, etc.) #### 2. Database (`database.DB`) + - **Created by**: `database.Module` via `database.New()` - **When**: Application startup (fx DI) - **Contains**: SQLite connection, path reference #### 3. Repositories (`database.Repositories`) + - **Created by**: `database.Module` via `database.NewRepositories()` - **When**: Application startup (fx DI) -- **Contains**: All repository interfaces (Files, Chunks, Blobs, Snapshots, etc.) +- **Contains**: All repository interfaces (Files, Chunks, Blobs, Snapshots, + etc.) #### 4. Vaultik (`vaultik.Vaultik`) + - **Created by**: `vaultik.New(VaultikParams)` - **When**: Application startup (fx DI) - **Contains**: All dependencies for backup operations @@ -176,11 +217,13 @@ type Vaultik struct { ``` #### 5. SnapshotManager (`snapshot.SnapshotManager`) + - **Created by**: `snapshot.Module` via `snapshot.NewSnapshotManager()` - **When**: Application startup (fx DI) - **Responsibility**: Creates/completes snapshots, exports metadata to S3 #### 6. Scanner (`snapshot.Scanner`) + - **Created by**: `ScannerFactory(ScannerParams)` - **When**: Each `CreateSnapshot()` call - **Contains**: Chunker, Packer, progress reporter @@ -194,20 +237,22 @@ scanner := v.ScannerFactory(snapshot.ScannerParams{ ``` #### 7. Chunker (`chunker.Chunker`) + - **Created by**: `chunker.NewChunker(avgChunkSize)` - **When**: Inside `snapshot.NewScanner()` - **Configuration**: - - `avgChunkSize`: From config (default 10MB) - - `minChunkSize`: avgChunkSize / 4 - - `maxChunkSize`: avgChunkSize * 4 + - `avgChunkSize`: From config (default 10MB) + - `minChunkSize`: avgChunkSize / 4 + - `maxChunkSize`: avgChunkSize \* 4 #### 8. Packer (`blob.Packer`) + - **Created by**: `blob.NewPacker(PackerConfig)` - **When**: Inside `snapshot.NewScanner()` - **Configuration**: - - `MaxBlobSize`: Maximum blob size before finalization (typically 10GB) - - `CompressionLevel`: zstd level (1-19) - - `Recipients`: age public keys for encryption + - `MaxBlobSize`: Maximum blob size before finalization (typically 10GB) + - `CompressionLevel`: zstd level (1-19) + - `Recipients`: age public keys for encryption ```go // snapshot/scanner.go: NewScanner() @@ -224,17 +269,22 @@ packer, err := blob.NewPacker(packerCfg) ## Module Responsibilities ### `internal/cli` -Entry point for fx application. Combines all modules and handles signal interrupts. + +Entry point for fx application. Combines all modules and handles signal +interrupts. Key functions: + - `NewApp(AppOptions)` → Creates fx.App with all modules - `RunApp(ctx, app)` → Starts app, handles graceful shutdown - `RunWithApp(ctx, opts)` → Convenience wrapper ### `internal/vaultik` + Main orchestrator containing all dependencies and command implementations. Key methods: + - `New(VaultikParams)` → Constructor (fx DI) - `CreateSnapshot(opts)` → Main backup operation - `ListSnapshots(jsonOutput)` → List available snapshots @@ -242,27 +292,34 @@ Key methods: - `PurgeSnapshots(...)` → Remove old snapshots ### `internal/chunker` + Content-defined chunking using FastCDC algorithm. Key types: + - `Chunk` → Hash, Data, Offset, Size - `Chunker` → avgChunkSize, minChunkSize, maxChunkSize Key methods: + - `NewChunker(avgChunkSize)` → Constructor -- `ChunkReaderStreaming(reader, callback)` → Stream chunks with callback (preferred) +- `ChunkReaderStreaming(reader, callback)` → Stream chunks with callback + (preferred) - `ChunkReader(reader)` → Return all chunks at once (memory-intensive) ### `internal/blob` + Blob packing: accumulates chunks, compresses, encrypts, tracks metadata. Key types: + - `Packer` → Thread-safe blob accumulator - `ChunkRef` → Hash + Data for adding to packer - `FinishedBlob` → Completed blob ready for upload - `BlobWithReader` → FinishedBlob + io.Reader for streaming upload Key methods: + - `NewPacker(PackerConfig)` → Constructor - `AddChunk(ChunkRef)` → Add chunk to current blob - `FinalizeBlob()` → Compress, encrypt, hash current blob @@ -272,35 +329,48 @@ Key methods: ### `internal/snapshot` #### Scanner + Orchestrates the backup process for a directory. Key methods: + - `NewScanner(ScannerConfig)` → Constructor (creates Chunker + Packer) - `Scan(ctx, path, snapshotID)` → Main scan operation Scan phases: + 1. **Phase 1**: Walk directory, identify files needing processing -2. **Phase 1b**: Count as deleted the files that the previous snapshot of the same name lists, the walk did not find, and are gone from disk; a file that is excluded, or inside an excluded directory, is not counted +2. **Phase 1b**: Count as deleted the files that the previous snapshot of the + same name lists, the walk did not find, and are gone from disk; a file that + is excluded, or inside an excluded directory, is not counted 3. **Phase 2**: Process files (chunk → pack → upload) #### SnapshotManager + Manages snapshot lifecycle and metadata export. Key methods: + - `CreateSnapshot(ctx, hostname, version, commit)` → Create snapshot record -- `PopulateSnapshotBlobs(ctx, snapshotID)` → Record every blob the snapshot references +- `PopulateSnapshotBlobs(ctx, snapshotID)` → Record every blob the snapshot + references - `ExportSnapshotMetadata(ctx, dbPath, snapshotID)` → Export to S3 -- `MarkSnapshotComplete(ctx, snapshotID)` → Record completion, only after a successful export -- `CompleteSnapshot(ctx, snapshotID)` → Convenience: populate blobs, then mark complete (no export between) +- `MarkSnapshotComplete(ctx, snapshotID)` → Record completion, only after a + successful export +- `CompleteSnapshot(ctx, snapshotID)` → Convenience: populate blobs, then mark + complete (no export between) ### `internal/database` + SQLite database for local index. Single-writer mode for thread safety. Key types: + - `DB` → Database connection wrapper - `Repositories` → Collection of all repository interfaces Repository interfaces: + - `FilesRepository` → CRUD for File records - `ChunksRepository` → CRUD for Chunk records - `BlobsRepository` → CRUD for Blob records @@ -359,11 +429,16 @@ CreateSnapshot(opts) ## Deduplication Strategy -1. **File-level**: Files and symlinks unchanged since last backup are skipped (metadata comparison: size, mtime, mode, uid, gid, and a symlink's target), unless the file lists a chunk that no uploaded blob holds; such a file is re-chunked +1. **File-level**: Files and symlinks unchanged since last backup are skipped + (metadata comparison: size, mtime, mode, uid, gid, and a symlink's target), + unless the file lists a chunk that no uploaded blob holds; such a file is + re-chunked -2. **Chunk-level**: Chunks are content-addressed by SHA256 hash. If a chunk hash already exists in the database, the chunk data is not re-uploaded. +2. **Chunk-level**: Chunks are content-addressed by SHA256 hash. If a chunk hash + already exists in the database, the chunk data is not re-uploaded. -3. **Blob-level**: Blobs contain only unique chunks. Duplicate chunks within a blob are skipped. +3. **Blob-level**: Blobs contain only unique chunks. Duplicate chunks within a + blob are skipped. ## Storage Layout in S3 @@ -382,30 +457,30 @@ bucket/ └── manifest.json.zst # Blob list (for pruning/verification) ``` -A destination that answers a look-up of `vaultik-destination.txt` with not -found is treated as not present while the local index holds snapshots stored -there (`checkDestinationMarker` in `internal/vaultik/destination_marker.go`): +A destination that answers a look-up of `vaultik-destination.txt` with not found +is treated as not present while the local index holds snapshots stored there +(`checkDestinationMarker` in `internal/vaultik/destination_marker.go`): `snapshot create` refuses to write to it, `prune`, `snapshot purge` and `remote nuke` fail, and `snapshot list` and `snapshot remove` behave as for a destination that cannot be listed. This keeps those commands from taking an -unplugged volume's empty mount point for a destination whose snapshots are -all gone. When the look-up fails for any reason other than not found, for -example when S3 refuses it to credentials that allow only PUT, the check is -skipped, so a host with such credentials does not notice an emptied -destination; see -[docs/REPOSTRUCTURE.md](docs/REPOSTRUCTURE.md#marker-file-vaultik-destinationtxt). +unplugged volume's empty mount point for a destination whose snapshots are all +gone. When the look-up fails for any reason other than not found, for example +when S3 refuses it to credentials that allow only PUT, the check is skipped, so +a host with such credentials does not notice an emptied destination; see +[docs/REPOSTRUCTURE.md](REPOSTRUCTURE.md#marker-file-vaultik-destinationtxt). The `file://` backend never creates its destination directory, so a write to a missing one fails. The `{remote-key}` directory name is a one-way double SHA-256 hash of the human snapshot ID, so the human ID (hostname, snapshot name, timestamp) is never written to the store as a directory name. See -[docs/REPOSTRUCTURE.md](docs/REPOSTRUCTURE.md#remote-key-derivation) for the +[docs/REPOSTRUCTURE.md](REPOSTRUCTURE.md#remote-key-derivation) for the derivation and a worked example. ## Thread Safety - `Packer`: Thread-safe via mutex. Multiple goroutines can call `AddChunk()`. - `Scanner`: Uses `packerMu` mutex to coordinate blob finalization. -- `Database`: Single-writer mode (`MaxOpenConns=1`) ensures SQLite thread safety. +- `Database`: Single-writer mode (`MaxOpenConns=1`) ensures SQLite thread + safety. - `Repositories.WithTx()`: Handles transaction lifecycle automatically. diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index 3b197e3..5dd2af9 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -2,7 +2,9 @@ ## Overview -Vaultik uses a local SQLite database to track file metadata, chunk mappings, and blob associations during the backup process. This database serves as an index for incremental backups and enables efficient deduplication. +Vaultik uses a local SQLite database to track file metadata, chunk mappings, and +blob associations during the backup process. This database serves as an index +for incremental backups and enables efficient deduplication. **Important Notes:** @@ -25,19 +27,23 @@ recorded `001.sql` as run, so it keeps the old schema and can become unusable; `vaultik database delete` followed by a full backup rebuilds it. **After 1.0** each schema change is a new numbered file, so an existing local -database is migrated the first time an updated vaultik opens it. A file that -has shipped in a release is never edited. +database is migrated the first time an updated vaultik opens it. A file that has +shipped in a release is never edited. ## Database Tables ### 1. `files` + Stores metadata about files in the filesystem being backed up. **Columns:** + - `id` (TEXT PRIMARY KEY) - UUID for the file record - `path` (TEXT NOT NULL UNIQUE) - Absolute file path -- `mtime` (INTEGER NOT NULL) - Modification time, whole seconds since the Unix epoch -- `mtime_nsec` (INTEGER NOT NULL) - Nanoseconds within that second, 0 to 999999999 +- `mtime` (INTEGER NOT NULL) - Modification time, whole seconds since the Unix + epoch +- `mtime_nsec` (INTEGER NOT NULL) - Nanoseconds within that second, 0 to + 999999999 - `size` (INTEGER NOT NULL) - File size in bytes - `mode` (INTEGER NOT NULL) - Unix file permissions and type - `uid` (INTEGER NOT NULL) - User ID of file owner @@ -45,23 +51,30 @@ Stores metadata about files in the filesystem being backed up. - `link_target` (TEXT) - Symlink target path (NULL for regular files) **Indexes:** + - `idx_files_path` on `path` for efficient lookups -**Purpose:** Tracks file metadata to detect changes between backup runs. Used for incremental backup decisions. The UUID primary key provides stable references that don't change if files are moved. +**Purpose:** Tracks file metadata to detect changes between backup runs. Used +for incremental backup decisions. The UUID primary key provides stable +references that don't change if files are moved. ### 2. `chunks` + Stores information about content-defined chunks created from files. **Columns:** + - `chunk_hash` (TEXT PRIMARY KEY) - SHA256 hash of chunk content - `size` (INTEGER NOT NULL) - Chunk size in bytes **Purpose:** Enables deduplication by tracking unique chunks across all files. ### 3. `file_chunks` + Maps files to their constituent chunks in order. **Columns:** + - `file_id` (TEXT) - File ID (FK to files.id) - `idx` (INTEGER) - Chunk index within file (0-based) - `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash) @@ -70,35 +83,49 @@ Maps files to their constituent chunks in order. **Purpose:** Allows reconstruction of files from chunks during restore. ### 4. `chunk_files` + Reverse mapping showing which files contain each chunk. **Columns:** + - `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash) - `file_id` (TEXT) - File ID (FK to files.id) - `file_offset` (INTEGER) - Byte offset of chunk within file - `length` (INTEGER) - Length of chunk in bytes - PRIMARY KEY (`chunk_hash`, `file_id`) -**Purpose:** Supports efficient queries for chunk usage and deduplication statistics. +**Purpose:** Supports efficient queries for chunk usage and deduplication +statistics. ### 5. `blobs` + Stores information about packed, compressed, and encrypted blob files. **Columns:** + - `id` (TEXT PRIMARY KEY) - UUID assigned when blob creation starts -- `blob_hash` (TEXT UNIQUE) - `hex(SHA256(SHA256(uncompressed blob contents)))`, computed before compression and encryption (NULL until finalized); see [REPOSTRUCTURE.md](REPOSTRUCTURE.md#blobs-directory-blobs) +- `blob_hash` (TEXT UNIQUE) - `hex(SHA256(SHA256(uncompressed blob contents)))`, + computed before compression and encryption (NULL until finalized); see + [REPOSTRUCTURE.md](REPOSTRUCTURE.md#blobs-directory-blobs) - `created_ts` (INTEGER NOT NULL) - Creation timestamp - `finished_ts` (INTEGER) - Finalization timestamp (NULL if in progress) -- `uncompressed_size` (INTEGER NOT NULL DEFAULT 0) - Total size of chunks before compression -- `compressed_size` (INTEGER NOT NULL DEFAULT 0) - Size after compression and encryption. Once uploaded, the size of the object in storage: when the blob was already stored, under another compression level or other recipients, this can differ from the size of the local copy +- `uncompressed_size` (INTEGER NOT NULL DEFAULT 0) - Total size of chunks before + compression +- `compressed_size` (INTEGER NOT NULL DEFAULT 0) - Size after compression and + encryption. Once uploaded, the size of the object in storage: when the blob + was already stored, under another compression level or other recipients, this + can differ from the size of the local copy - `uploaded_ts` (INTEGER) - Upload completion timestamp (NULL if not uploaded) -**Purpose:** Tracks blob lifecycle from creation through upload. The UUID primary key allows immediate association of chunks with blobs. +**Purpose:** Tracks blob lifecycle from creation through upload. The UUID +primary key allows immediate association of chunks with blobs. ### 6. `blob_chunks` + Maps chunks to the blobs that contain them. **Columns:** + - `blob_id` (TEXT) - Blob ID (FK to blobs.id) - `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash) - `offset` (INTEGER) - Byte offset of chunk within blob (before compression) @@ -108,34 +135,46 @@ Maps chunks to the blobs that contain them. **Purpose:** Enables chunk retrieval from blobs during restore operations. ### 7. `snapshots` + Tracks backup snapshots. **Columns:** -- `id` (TEXT PRIMARY KEY) - Snapshot ID (format: `hostname_name_timestamp`, e.g. `server1_home_2025-06-01T12:00:00Z`: the hostname up to its first `.`, the snapshot name, and an RFC 3339 UTC timestamp) + +- `id` (TEXT PRIMARY KEY) - Snapshot ID (format: `hostname_name_timestamp`, e.g. + `server1_home_2025-06-01T12:00:00Z`: the hostname up to its first `.`, the + snapshot name, and an RFC 3339 UTC timestamp) - `hostname` (TEXT) - Hostname where backup was created - `vaultik_version` (TEXT) - Version of Vaultik used - `vaultik_git_revision` (TEXT) - Git revision of Vaultik used - `started_at` (INTEGER) - Start timestamp - `completed_at` (INTEGER) - Completion timestamp (NULL if in progress) - `file_count` (INTEGER) - Number of files in snapshot -- `chunk_count` (INTEGER) - Number of chunks this snapshot stored that were not stored before -- `new_chunk_size` (INTEGER) - Total size of those chunks before compression; `snapshot list` shows it as NEW CHUNK SIZE +- `chunk_count` (INTEGER) - Number of chunks this snapshot stored that were not + stored before +- `new_chunk_size` (INTEGER) - Total size of those chunks before compression; + `snapshot list` shows it as NEW CHUNK SIZE - `blob_count` (INTEGER) - Number of blobs this snapshot created - `total_size` (INTEGER) - Total size of all files -- `uncompressed_chunk_size` (INTEGER) - Total size before compression of the distinct chunks the snapshot's files reference, recorded when its backup ran; `snapshot list` shows it as UNCOMPRESSED SIZE +- `uncompressed_chunk_size` (INTEGER) - Total size before compression of the + distinct chunks the snapshot's files reference, recorded when its backup ran; + `snapshot list` shows it as UNCOMPRESSED SIZE - `blob_size` (INTEGER) - Total compressed size of all referenced blobs -- `blob_uncompressed_size` (INTEGER) - Total uncompressed size of all referenced blobs +- `blob_uncompressed_size` (INTEGER) - Total uncompressed size of all referenced + blobs - `compression_ratio` (REAL) - Compression ratio achieved - `compression_level` (INTEGER) - Compression level used for this snapshot - `upload_bytes` (INTEGER) - Total bytes uploaded during this snapshot - `upload_duration_ms` (INTEGER) - Total milliseconds spent uploading to S3 -**Purpose:** Provides snapshot metadata and statistics including version tracking for compatibility. +**Purpose:** Provides snapshot metadata and statistics including version +tracking for compatibility. ### 8. `snapshot_files` + Maps snapshots to the files they contain. **Columns:** + - `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id) - `file_id` (TEXT) - File ID (FK to files.id) - PRIMARY KEY (`snapshot_id`, `file_id`) @@ -143,114 +182,146 @@ Maps snapshots to the files they contain. **Purpose:** Records which files are included in each snapshot. ### 9. `snapshot_blobs` + Maps snapshots to the blobs they reference. **Columns:** + - `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id) - `blob_id` (TEXT) - Blob ID (FK to blobs.id) - `blob_hash` (TEXT) - Denormalized blob hash for manifest generation - PRIMARY KEY (`snapshot_id`, `blob_id`) -**Purpose:** Tracks blob dependencies for snapshots and enables manifest generation. +**Purpose:** Tracks blob dependencies for snapshots and enables manifest +generation. ### 10. `snapshot_mount_points` -The directories at or below a configured path, the configured path itself included, that a snapshot's backup found an entry in and, once it had listed them, found on a different filesystem from their parent directory (a different device number), as a mount point is. An automount point whose volume cannot be mounted is not recorded, because the backup finds no entry in it. + +The directories at or below a configured path, the configured path itself +included, that a snapshot's backup found an entry in and, once it had listed +them, found on a different filesystem from their parent directory (a different +device number), as a mount point is. An automount point whose volume cannot be +mounted is not recorded, because the backup finds no entry in it. **Columns:** + - `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id) - `path` (TEXT) - Absolute path of the directory - PRIMARY KEY (`snapshot_id`, `path`) -**Purpose:** Lets `snapshot create --prune` skip the prune when a backup does not find a mount point that an earlier snapshot of the same name found, as when the volume is not mounted. +**Purpose:** Lets `snapshot create --prune` skip the prune when a backup does +not find a mount point that an earlier snapshot of the same name found, as when +the volume is not mounted. ### 11. `uploads` + Tracks blob upload metrics. **Columns:** + - `blob_hash` (TEXT PRIMARY KEY) - Hash of uploaded blob -- `snapshot_id` (TEXT NOT NULL) - The snapshot that triggered this upload (FK to snapshots.id) +- `snapshot_id` (TEXT NOT NULL) - The snapshot that triggered this upload (FK to + snapshots.id) - `uploaded_at` (INTEGER) - Upload timestamp - `size` (INTEGER) - Size of uploaded blob - `duration_ms` (INTEGER) - Upload duration in milliseconds -**Purpose:** Performance monitoring and tracking which blobs were newly created (uploaded) during each snapshot. +**Purpose:** Performance monitoring and tracking which blobs were newly created +(uploaded) during each snapshot. ## Data Flow and Operations ### 1. Backup Process 1. **File Scanning** - - `INSERT OR REPLACE INTO files` - Update file metadata - - `SELECT * FROM files WHERE path = ?` - Check if file has changed - - `INSERT INTO snapshot_files` - Add file to current snapshot - - `INSERT OR IGNORE INTO snapshot_mount_points` - Record each directory on a different filesystem from its parent that the walk found an entry in + - `INSERT OR REPLACE INTO files` - Update file metadata + - `SELECT * FROM files WHERE path = ?` - Check if file has changed + - `INSERT INTO snapshot_files` - Add file to current snapshot + - `INSERT OR IGNORE INTO snapshot_mount_points` - Record each directory on a + different filesystem from its parent that the walk found an entry in 2. **Chunking** (for changed files) - - `INSERT OR IGNORE INTO chunks` - Store new chunks - - `INSERT INTO file_chunks` - Map chunks to file - - `INSERT INTO chunk_files` - Create reverse mapping + - `INSERT OR IGNORE INTO chunks` - Store new chunks + - `INSERT INTO file_chunks` - Map chunks to file + - `INSERT INTO chunk_files` - Create reverse mapping 3. **Blob Packing** - - `INSERT INTO blobs` - Create blob record with UUID (blob_hash NULL) - - `INSERT INTO blob_chunks` - Associate chunks with blob immediately - - `UPDATE blobs SET blob_hash = ?, finished_ts = ?` - Finalize blob after packing + - `INSERT INTO blobs` - Create blob record with UUID (blob_hash NULL) + - `INSERT INTO blob_chunks` - Associate chunks with blob immediately + - `UPDATE blobs SET blob_hash = ?, finished_ts = ?` - Finalize blob after + packing 4. **Upload** - - `UPDATE blobs SET uploaded_ts = ?, compressed_size = ?` - Mark blob as uploaded, with the size of the object in storage (the upload is skipped when the blob is already stored) - - `INSERT INTO uploads` - Record upload metrics with snapshot_id - - `INSERT INTO snapshot_blobs` - Associate blob with snapshot + - `UPDATE blobs SET uploaded_ts = ?, compressed_size = ?` - Mark blob as + uploaded, with the size of the object in storage (the upload is skipped + when the blob is already stored) + - `INSERT INTO uploads` - Record upload metrics with snapshot_id + - `INSERT INTO snapshot_blobs` - Associate blob with snapshot 5. **Snapshot Completion** - - `UPDATE snapshots SET completed_at = ?, stats...` - Finalize snapshot - - Generate and upload blob manifest from `snapshot_blobs` + - `UPDATE snapshots SET completed_at = ?, stats...` - Finalize snapshot + - Generate and upload blob manifest from `snapshot_blobs` ### 2. Incremental Backup 1. **Change Detection** - - `SELECT * FROM files WHERE path = ?` - Get previous file metadata - - Compare mtime, size, mode to detect changes - - Re-chunk a file that lists a chunk no uploaded blob holds, even when its metadata is unchanged - - Skip unchanged files but still add to `snapshot_files` + - `SELECT * FROM files WHERE path = ?` - Get previous file metadata + - Compare mtime, size, mode to detect changes + - Re-chunk a file that lists a chunk no uploaded blob holds, even when its + metadata is unchanged + - Skip unchanged files but still add to `snapshot_files` 2. **Chunk Reuse** - - `SELECT * FROM blob_chunks WHERE chunk_hash = ?` - Find existing chunks - - `INSERT INTO snapshot_blobs` - Reference existing blobs for unchanged files + - `SELECT * FROM blob_chunks WHERE chunk_hash = ?` - Find existing chunks + - `INSERT INTO snapshot_blobs` - Reference existing blobs for unchanged + files ### 3. Snapshot Metadata Export After a snapshot is completed: + 1. Copy database to temporary file 2. Clean temporary database to contain only current snapshot data 3. VACUUM the trimmed database so deleted rows leave no pages behind 4. Compress with zstd and encrypt with age 5. Upload to S3 as `metadata/{remote-key}/db.zst.age` -6. Generate blob manifest and upload as `metadata/{remote-key}/manifest.json.zst` +6. Generate blob manifest and upload as + `metadata/{remote-key}/manifest.json.zst` -The `{remote-key}` directory name is a one-way hash of the human snapshot ID, so the ID is never written to the store in plaintext. The hash uses no secret, so a guessed hostname and snapshot name can still be confirmed against a listing; see [REPOSTRUCTURE.md](REPOSTRUCTURE.md#remote-key-derivation) and its [Accepted Risks](REPOSTRUCTURE.md#accepted-risks). +The `{remote-key}` directory name is a one-way hash of the human snapshot ID, so +the ID is never written to the store in plaintext. The hash uses no secret, so a +guessed hostname and snapshot name can still be confirmed against a listing; see +[REPOSTRUCTURE.md](REPOSTRUCTURE.md#remote-key-derivation) and its +[Accepted Risks](REPOSTRUCTURE.md#accepted-risks). ### 4. Restore Process The restore process doesn't use the local database. Instead: -1. Downloads and decrypts the snapshot's metadata database (`db.zst.age`) from S3 -2. Downloads the blobs holding the chunks of the files being restored, found through that database's `blob_chunks` table; the manifest is not read + +1. Downloads and decrypts the snapshot's metadata database (`db.zst.age`) from + S3 +2. Downloads the blobs holding the chunks of the files being restored, found + through that database's `blob_chunks` table; the manifest is not read 3. Reconstructs files from decrypted and decompressed chunks ### 5. Pruning 1. **Identify Unreferenced Blobs** - - Query blobs not referenced by any remaining snapshot - - Delete from S3, once older than `prune_grace_period`, and from the local - database + - Query blobs not referenced by any remaining snapshot + - Delete from S3, once older than `prune_grace_period`, and from the local + database 2. **Delete Metadata Directories With No Manifest** - - Delete each directory under `metadata/` that has no `manifest.json.zst` - and no local snapshot record, once every object in it is older than - `prune_grace_period` + - Delete each directory under `metadata/` that has no `manifest.json.zst` + and no local snapshot record, once every object in it is older than + `prune_grace_period` ### 6. Incomplete Snapshot Cleanup Before each backup: + 1. Query incomplete snapshots (where `completed_at IS NULL`) -2. Delete each one and all its associations, without checking S3 for its metadata +2. Delete each one and all its associations, without checking S3 for its + metadata 3. Clean up orphaned files, chunks, and blobs ## Repository Pattern @@ -260,18 +331,20 @@ Vaultik uses a repository pattern for database access: - `FileRepository` - CRUD operations for files and file metadata - `ChunkRepository` - CRUD operations for content chunks - `FileChunkRepository` - Manage file-to-chunk mappings -- `ChunkFileRepository` - Manage chunk-to-file reverse mappings +- `ChunkFileRepository` - Manage chunk-to-file reverse mappings - `BlobRepository` - Manage blob lifecycle (creation, finalization, upload) - `BlobChunkRepository` - Manage blob-to-chunk associations - `SnapshotRepository` - Manage snapshots and their relationships - `UploadRepository` - Track blob upload metrics Each repository provides methods like: + - `Create()` - Insert new record - `GetByID()` / `GetByPath()` / `GetByHash()` - Retrieve records - `Update()` - Update existing records - `Delete()` - Remove records -- Specialized queries for each entity type (e.g., `DeleteOrphaned()`, `GetIncompleteByHostname()`) +- Specialized queries for each entity type (e.g., `DeleteOrphaned()`, + `GetIncompleteByHostname()`) ## Transaction Management @@ -284,25 +357,33 @@ err := repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { ``` This ensures consistency, especially important for operations like: + - Creating file-chunk mappings - Associating chunks with blobs - Updating snapshot statistics ## Performance Considerations -1. **Indexes**: - - Primary keys are automatically indexed - - `idx_files_path` on `files(path)` for efficient file lookups +1. **Indexes**: + - Primary keys are automatically indexed + - `idx_files_path` on `files(path)` for efficient file lookups -2. **Prepared Statements**: All queries use prepared statements for performance and security +2. **Prepared Statements**: All queries use prepared statements for performance + and security -3. **Batch Operations**: Where possible, operations are batched within transactions +3. **Batch Operations**: Where possible, operations are batched within + transactions -4. **Write-Ahead Logging**: The local index runs in SQLite WAL mode with a 10-second busy timeout, so a read-only command such as `snapshot list` can read it while a backup writes to it. Committed rows can sit in the `-wal` file beside the index until a checkpoint, so the metadata export copies the index through SQLite (`VACUUM INTO`), not as a file +4. **Write-Ahead Logging**: The local index runs in SQLite WAL mode with a + 10-second busy timeout, so a read-only command such as `snapshot list` can + read it while a backup writes to it. Committed rows can sit in the `-wal` + file beside the index until a checkpoint, so the metadata export copies the + index through SQLite (`VACUUM INTO`), not as a file ## Data Integrity -1. **Foreign Keys**: Enforced through CASCADE DELETE and application-level repository methods +1. **Foreign Keys**: Enforced through CASCADE DELETE and application-level + repository methods 2. **Unique Constraints**: Chunk hashes, file paths, and blob hashes are unique 3. **Null Handling**: Nullable fields clearly indicate in-progress operations -4. **Timestamp Tracking**: All major operations record timestamps for auditing \ No newline at end of file +4. **Timestamp Tracking**: All major operations record timestamps for auditing diff --git a/docs/REPOSTRUCTURE.md b/docs/REPOSTRUCTURE.md index d2f003a..81f34c9 100644 --- a/docs/REPOSTRUCTURE.md +++ b/docs/REPOSTRUCTURE.md @@ -1,10 +1,13 @@ # Vaultik S3 Repository Structure -This document describes the structure and organization of data stored in the S3 bucket by Vaultik. +This document describes the structure and organization of data stored in the S3 +bucket by Vaultik. ## Overview -Vaultik stores all backup data in an S3-compatible object store. The repository consists of two main components, plus a marker file: +Vaultik stores all backup data in an S3-compatible object store. The repository +consists of two main components, plus a marker file: + 1. **Blobs** - The actual backup data (content-addressed, encrypted) 2. **Metadata** - Snapshot information and manifests (partially encrypted) @@ -23,120 +26,208 @@ Vaultik stores all backup data in an S3-compatible object store. The repository └── manifest.json.zst ``` -The metadata subdirectory is named with the **remote key**, a one-way hash of the snapshot ID, not with the human-readable snapshot ID itself. See [Remote Key Derivation](#remote-key-derivation). +The metadata subdirectory is named with the **remote key**, a one-way hash of +the snapshot ID, not with the human-readable snapshot ID itself. See +[Remote Key Derivation](#remote-key-derivation). ## Marker File (`vaultik-destination.txt`) -Every backup writes this file at the root before it uploads anything. It holds one fixed line of plain text and names no host, path or time. While the local index holds snapshots stored there, a destination that answers a look-up of the marker with not found is treated as not present: `snapshot create` refuses to write to it, and `prune`, `snapshot purge`, `snapshot remove`, `snapshot list` and `remote nuke` behave as for a destination that cannot be listed. An unplugged volume leaves an empty directory at its mount point, and without the marker that directory would read as a destination whose snapshots are all gone. `remote nuke` deletes the marker last. +Every backup writes this file at the root before it uploads anything. It holds +one fixed line of plain text and names no host, path or time. While the local +index holds snapshots stored there, a destination that answers a look-up of the +marker with not found is treated as not present: `snapshot create` refuses to +write to it, and `prune`, `snapshot purge`, `snapshot remove`, `snapshot list` +and `remote nuke` behave as for a destination that cannot be listed. An +unplugged volume leaves an empty directory at its mount point, and without the +marker that directory would read as a destination whose snapshots are all gone. +`remote nuke` deletes the marker last. -When the look-up of the marker fails for any reason other than not found, the check is skipped and the command goes on. S3 refuses it on every run to credentials that allow only PUT, so a host with such credentials does not notice a destination emptied since its last backup, and its next backup would leave out the data its local index records as already stored. After the destination is emptied, run `vaultik database delete` on such a host before it backs up again. +When the look-up of the marker fails for any reason other than not found, the +check is skipped and the command goes on. S3 refuses it on every run to +credentials that allow only PUT, so a host with such credentials does not notice +a destination emptied since its last backup, and its next backup would leave out +the data its local index records as already stored. After the destination is +emptied, run `vaultik database delete` on such a host before it backs up again. ## Blobs Directory (`blobs/`) ### Structure + - **Path format**: `blobs///` -- **Example**: `blobs/ca/fe/cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678` -- **Sharding**: The two-level directory structure (using the first 4 characters of the hash) prevents any single directory from containing too many objects +- **Example**: + `blobs/ca/fe/cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678` +- **Sharding**: The two-level directory structure (using the first 4 characters + of the hash) prevents any single directory from containing too many objects ### Content + - **What it contains**: Packed collections of content-defined chunks from files - **Format**: Zstandard compressed, then Age encrypted - **Encryption**: Always encrypted with Age using the configured recipients -- **Naming**: Content-addressed. The blob's name is `hex(SHA256(SHA256(uncompressed blob contents)))` — the double SHA-256 of the concatenated chunk data, computed before compression and encryption, not a hash of the stored (compressed, encrypted) bytes. One consequence: only a holder of the age private key can check a stored blob's integrity, because matching a blob to its name means decrypting and decompressing it first — which is what `restore` and `verify --deep` do. Implemented in `internal/blobgen` (`DoubleSHA256`). This is the canonical description of blob naming; other documents and comments point here. +- **Naming**: Content-addressed. The blob's name is + `hex(SHA256(SHA256(uncompressed blob contents)))` — the double SHA-256 of the + concatenated chunk data, computed before compression and encryption, not a + hash of the stored (compressed, encrypted) bytes. One consequence: only a + holder of the age private key can check a stored blob's integrity, because + matching a blob to its name means decrypting and decompressing it first — + which is what `restore` and `verify --deep` do. Implemented in + `internal/blobgen` (`DoubleSHA256`). This is the canonical description of blob + naming; other documents and comments point here. ### Why Encrypted -Blobs contain the actual file data from backups and must be encrypted for security. The content-addressing ensures deduplication while the encryption ensures privacy. + +Blobs contain the actual file data from backups and must be encrypted for +security. The content-addressing ensures deduplication while the encryption +ensures privacy. ## Metadata Directory (`metadata/`) -Each snapshot has its own subdirectory. The directory is **not** named with the human-readable snapshot ID; it is named with the remote key — a one-way hash of that ID. The human ID is never written to the destination store as a directory name (see [Remote Key Derivation](#remote-key-derivation)). +Each snapshot has its own subdirectory. The directory is **not** named with the +human-readable snapshot ID; it is named with the remote key — a one-way hash of +that ID. The human ID is never written to the destination store as a directory +name (see [Remote Key Derivation](#remote-key-derivation)). ### Snapshot ID Format -The human-readable snapshot ID is used in CLI arguments, log lines, and the local database. It is not written to the destination store. -- **Format**: `__` (or `_` if no - name was specified) +The human-readable snapshot ID is used in CLI arguments, log lines, and the +local database. It is not written to the destination store. + +- **Format**: `__` (or `_` + if no name was specified) - **Example**: `laptop_home_2024-01-15T14:30:52Z` - **Components**: - - Short hostname (everything before the first dot is stripped from the FQDN) - - Snapshot name from the configured `snapshots:` map (optional) - - RFC3339 UTC timestamp + - Short hostname (everything before the first dot is stripped from the FQDN) + - Snapshot name from the configured `snapshots:` map (optional) + - RFC3339 UTC timestamp -This ID reveals the hostname, the configured snapshot name, and the backup time, so it is never used as the on-disk directory name — the remote key is used instead. +This ID reveals the hostname, the configured snapshot name, and the backup time, +so it is never used as the on-disk directory name — the remote key is used +instead. ### Remote Key Derivation -The remote key is `hex(SHA256(SHA256("vaultik|" + snapshot-id)))`: a double SHA-256 over the snapshot ID, with a `vaultik|` domain-separation prefix. The result is a 64-character hex string. The hash is not reversible, but it uses no secret: an observer who guesses a candidate hostname and snapshot name can hash it the same way and confirm whether that snapshot is present. The remote key keeps names out of a plain listing; it does not hide them from a guess. Implemented in `internal/snapshot/remotekey.go`. +The remote key is `hex(SHA256(SHA256("vaultik|" + snapshot-id)))`: a double +SHA-256 over the snapshot ID, with a `vaultik|` domain-separation prefix. The +result is a 64-character hex string. The hash is not reversible, but it uses no +secret: an observer who guesses a candidate hostname and snapshot name can hash +it the same way and confirm whether that snapshot is present. The remote key +keeps names out of a plain listing; it does not hide them from a guess. +Implemented in `internal/snapshot/remotekey.go`. Worked example: + - Snapshot ID: `server1_home_2025-06-01T12:00:00Z` - Remote key: `17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa` -- Directory: `metadata/17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa/` +- Directory: + `metadata/17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa/` -A plain listing of the destination store therefore shows only these hashes, not the hostname or snapshot name of any backup — but because the hash uses no secret, a guessed hostname and snapshot name can be hashed and confirmed against the listing. The same remote key is stored in the manifest's `snapshot_id` field. +A plain listing of the destination store therefore shows only these hashes, not +the hostname or snapshot name of any backup — but because the hash uses no +secret, a guessed hostname and snapshot name can be hashed and confirmed against +the listing. The same remote key is stored in the manifest's `snapshot_id` +field. ### Files in Each Snapshot Directory #### `db.zst.age` - Encrypted Database + - **What it contains**: Pruned binary SQLite database for this snapshot - **Format**: Binary SQLite → Zstandard compressed → Age encrypted - **Encryption**: Encrypted with Age -- **Purpose**: Contains full file metadata, chunk mappings, and all relationships -- **Why encrypted**: Contains sensitive metadata like file paths, permissions, and ownership +- **Purpose**: Contains full file metadata, chunk mappings, and all + relationships +- **Why encrypted**: Contains sensitive metadata like file paths, permissions, + and ownership #### `manifest.json.zst` - Unencrypted Blob Manifest + - **What it contains**: JSON list of all blob hashes referenced by this snapshot - **Format**: JSON → Zstandard compressed (NOT encrypted) - **Encryption**: NOT encrypted - **Purpose**: Enables pruning operations without requiring decryption keys - **Structure**: + ```json { - "snapshot_id": "17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa", - "timestamp": "2025-06-01T12:00:00Z", - "blob_count": 42, - "total_compressed_size": 1048576, - "blobs": [ - { "hash": "cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678", "compressed_size": 24576 }, - { "hash": "deadbeef1234567890abcdef1234567890abcdef1234567890abcdef12345678", "compressed_size": 32768 } - ] + "snapshot_id": "17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa", + "timestamp": "2025-06-01T12:00:00Z", + "blob_count": 42, + "total_compressed_size": 1048576, + "blobs": [ + { + "hash": "cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678", + "compressed_size": 24576 + }, + { + "hash": "deadbeef1234567890abcdef1234567890abcdef1234567890abcdef12345678", + "compressed_size": 32768 + } + ] } ``` -`snapshot_id` is the remote key (a hash), not the human ID; `timestamp` is written in the clear. + +`snapshot_id` is the remote key (a hash), not the human ID; `timestamp` is +written in the clear. ### Why Manifest is Unencrypted + The manifest must be readable without the private key to enable: + 1. **Pruning operations** - Identifying unreferenced blobs for deletion 2. **Storage analysis** - Understanding space usage without decryption 3. **Verification** - Checking blob existence without decryption -4. **Cross-snapshot deduplication analysis** - Finding shared blobs between snapshots +4. **Cross-snapshot deduplication analysis** - Finding shared blobs between + snapshots -The manifest contains the remote key, the backup timestamp, the blob count and total compressed size, and each blob's hash and compressed size. It contains no file names, paths, or other decrypted metadata. +The manifest contains the remote key, the backup timestamp, the blob count and +total compressed size, and each blob's hash and compressed size. It contains no +file names, paths, or other decrypted metadata. ## Security Considerations ### What's Encrypted + - **All file content** (in blobs) -- **All file metadata** (paths, permissions, timestamps, ownership in db.zst.age) +- **All file metadata** (paths, permissions, timestamps, ownership in + db.zst.age) - **File-to-chunk mappings** (in db.zst.age) ### What's Not Encrypted -- **The remote key** — directory names and the manifest `snapshot_id`, a one-way hash of the snapshot ID (see [Remote Key Derivation](#remote-key-derivation)) + +- **The remote key** — directory names and the manifest `snapshot_id`, a one-way + hash of the snapshot ID (see [Remote Key Derivation](#remote-key-derivation)) - **The backup timestamp** (in manifest.json.zst) - **Blob hashes and their compressed sizes** (in manifest.json.zst) - **Blob count and total compressed size per snapshot** (in manifest.json.zst) ### Privacy Implications -From the unencrypted data, an observer of the destination store can determine: -- **When each backup was taken** — not from the directory name, which is a one-way hash, but from the plaintext `timestamp` field in manifest.json.zst, which is published in the clear -- How many blobs each snapshot references, and the total compressed size -- The compressed size of each blob, and which blobs are shared between snapshots (deduplication patterns) -- **Whether a guessed hostname and snapshot name are present** — the remote key is an unkeyed hash, so an observer holding candidate names can hash each one and match it against the directory listing. The human ID is never published, so it cannot be read off directly, but it can be confirmed by guessing. -Together these give an observer a timing-and-size profile of every snapshot. This is an accepted, documented property of the format, not a defect: the manifest is unencrypted so that pruning can run without the private key, and the timing channel could not be closed by encrypting it anyway — object creation times and per-object sizes stay visible at the storage layer on both `s3://` and `file://` destinations regardless. +From the unencrypted data, an observer of the destination store can determine: + +- **When each backup was taken** — not from the directory name, which is a + one-way hash, but from the plaintext `timestamp` field in manifest.json.zst, + which is published in the clear +- How many blobs each snapshot references, and the total compressed size +- The compressed size of each blob, and which blobs are shared between snapshots + (deduplication patterns) +- **Whether a guessed hostname and snapshot name are present** — the remote key + is an unkeyed hash, so an observer holding candidate names can hash each one + and match it against the directory listing. The human ID is never published, + so it cannot be read off directly, but it can be confirmed by guessing. + +Together these give an observer a timing-and-size profile of every snapshot. +This is an accepted, documented property of the format, not a defect: the +manifest is unencrypted so that pruning can run without the private key, and the +timing channel could not be closed by encrypting it anyway — object creation +times and per-object sizes stay visible at the storage layer on both `s3://` and +`file://` destinations regardless. An observer cannot determine: -- The hostname or snapshot name of any backup by reading it off the store — the directory name and the manifest `snapshot_id` are unkeyed hashes of the human ID, so the text is never published (though a guessed name can be confirmed, as above) + +- The hostname or snapshot name of any backup by reading it off the store — the + directory name and the manifest `snapshot_id` are unkeyed hashes of the human + ID, so the text is never published (though a guessed name can be confirmed, as + above) - File names or paths - File contents - File permissions or ownership @@ -145,40 +236,119 @@ An observer cannot determine: ### Accepted Risks -These are known, deliberate properties of the format and the tooling, recorded so an operator can weigh them rather than discover them. +These are known, deliberate properties of the format and the tooling, recorded +so an operator can weigh them rather than discover them. -1. **No proof of authorship.** Restore and `verify --deep` prove that data decrypts with the age private key and matches its unkeyed content hashes. They do not prove who wrote it: anyone who knows a recipient public key and can replace objects on the destination can substitute a snapshot they built. The recipient string is not stored at the destination, but a compromised backed-up host has it. Defences live on the destination side — bucket versioning or object lock, credentials for the source host that cannot delete or overwrite existing versions, and pruning from a trusted host. Note that S3 `PutObject` overwrites an existing key, so PUT permission alone is not append-only. -2. **Compression reveals sizes.** Blobs and `db.zst.age` are zstd-compressed then age-encrypted; the manifest is compressed only. age does not pad, so an object's size is the exact compressed length of its contents. All new chunks packed into one blob share a single zstd stream (8 MiB window, 4 MiB at compression levels 1-2), and a blob is closed at `blob_size_limit` and at the end of each configured path. Because a stored chunk is never packed again, someone who can write into a backed-up file and watch blob sizes learns something only when their controlled data and a secret land in the same chunk of a file that keeps changing. Advice: back up any outsider-writable directory as its own snapshot. -3. **Chunking uses no secret.** The FastCDC parameters are fixed and public. The default 10 MB average yields chunks between 2.5 MB and 40 MB, and any file of 2.5 MB or less is a single chunk. At the default 10 GB `blob_size_limit` a blob holds hundreds of chunks, so individual chunk lengths are not visible in the blob's size; lowering the limit toward the chunk size begins to expose them. -4. **Decrypted data on local disk.** Several commands stage plaintext under `$TMPDIR`: `snapshot restore` writes decrypted blobs under `vaultik-blobcache-*/` (no size cap) and the decrypted metadata database at `vaultik-restore-*/snapshot.db`; `verify --deep` writes that database at `vaultik-verify-*/snapshot.db`; `snapshot create` keeps a plaintext copy of the index at `vaultik-snapshot-*/snapshot.db`. These files are created `0600` and removed on success, but a `kill -9` or a power loss leaves them behind — delete any leftover `vaultik-*` directory under `$TMPDIR` by hand. `$TMPDIR` should be trusted to the same degree as the restore target. -5. **Store permissions differ per command.** The backed-up host needs only PUT to run `snapshot create`: it writes blobs and metadata and neither reads nor deletes them. Other commands need more — `snapshot verify`, `snapshot restore`, and `prune` list and read; `prune`, `snapshot purge`, `snapshot remove`, and `remote nuke` also delete. The recommended cron line uses `--prune`, which runs `prune` on the backed-up host, so granting that host `--prune` gives it credentials that can delete its own backups. To keep the source host to PUT only, prune from a separate trusted host instead. -6. **Changing recipients does not re-encrypt existing data.** Deduplicated chunks and same-named blobs already on the destination stay encrypted to the recipients in force when they were written. A new snapshot that reuses them cannot be restored with a newly added recipient's key alone, because those reused objects were never encrypted to it. To make everything readable by a new key, run `vaultik database delete` and take a full backup to a fresh destination or prefix. -7. **X25519 recipients only.** vaultik rejects age ssh and plugin recipients. Long-lived ciphertext held by a third party (the destination operator) has no fallback if X25519 is ever broken: there is no second recipient type and no post-quantum option. +1. **No proof of authorship.** Restore and `verify --deep` prove that data + decrypts with the age private key and matches its unkeyed content hashes. + They do not prove who wrote it: anyone who knows a recipient public key and + can replace objects on the destination can substitute a snapshot they built. + The recipient string is not stored at the destination, but a compromised + backed-up host has it. Defences live on the destination side — bucket + versioning or object lock, credentials for the source host that cannot delete + or overwrite existing versions, and pruning from a trusted host. Note that S3 + `PutObject` overwrites an existing key, so PUT permission alone is not + append-only. +2. **Compression reveals sizes.** Blobs and `db.zst.age` are zstd-compressed + then age-encrypted; the manifest is compressed only. age does not pad, so an + object's size is the exact compressed length of its contents. All new chunks + packed into one blob share a single zstd stream (8 MiB window, 4 MiB at + compression levels 1-2), and a blob is closed at `blob_size_limit` and at the + end of each configured path. Because a stored chunk is never packed again, + someone who can write into a backed-up file and watch blob sizes learns + something only when their controlled data and a secret land in the same chunk + of a file that keeps changing. Advice: back up any outsider-writable + directory as its own snapshot. +3. **Chunking uses no secret.** The FastCDC parameters are fixed and public. The + default 10 MB average yields chunks between 2.5 MB and 40 MB, and any file of + 2.5 MB or less is a single chunk. At the default 10 GB `blob_size_limit` a + blob holds hundreds of chunks, so individual chunk lengths are not visible in + the blob's size; lowering the limit toward the chunk size begins to expose + them. +4. **Decrypted data on local disk.** Several commands stage plaintext under + `$TMPDIR`: `snapshot restore` writes decrypted blobs under + `vaultik-blobcache-*/` (no size cap) and the decrypted metadata database at + `vaultik-restore-*/snapshot.db`; `verify --deep` writes that database at + `vaultik-verify-*/snapshot.db`; `snapshot create` keeps a plaintext copy of + the index at `vaultik-snapshot-*/snapshot.db`. These files are created `0600` + and removed on success, but a `kill -9` or a power loss leaves them behind — + delete any leftover `vaultik-*` directory under `$TMPDIR` by hand. `$TMPDIR` + should be trusted to the same degree as the restore target. +5. **Store permissions differ per command.** The backed-up host needs only PUT + to run `snapshot create`: it writes blobs and metadata and neither reads nor + deletes them. Other commands need more — `snapshot verify`, + `snapshot restore`, and `prune` list and read; `prune`, `snapshot purge`, + `snapshot remove`, and `remote nuke` also delete. The recommended cron line + uses `--prune`, which runs `prune` on the backed-up host, so granting that + host `--prune` gives it credentials that can delete its own backups. To keep + the source host to PUT only, prune from a separate trusted host instead. +6. **Changing recipients does not re-encrypt existing data.** Deduplicated + chunks and same-named blobs already on the destination stay encrypted to the + recipients in force when they were written. A new snapshot that reuses them + cannot be restored with a newly added recipient's key alone, because those + reused objects were never encrypted to it. To make everything readable by a + new key, run `vaultik database delete` and take a full backup to a fresh + destination or prefix. +7. **X25519 recipients only.** vaultik rejects age ssh and plugin recipients. + Long-lived ciphertext held by a third party (the destination operator) has no + fallback if X25519 is ever broken: there is no second recipient type and no + post-quantum option. ## Consistency Guarantees 1. **Blobs are immutable** - Once written, a blob is never modified -2. **Blobs are written before metadata** - A snapshot's metadata is only written after all its blobs are successfully uploaded -3. **Metadata is written atomically** - Both db.zst.age and manifest.json.zst are written as complete files -4. **A snapshot is marked complete in the local DB only after its metadata is uploaded** - `finalizeSnapshotMetadata` runs `ExportSnapshotMetadata` first and records completion (`MarkSnapshotComplete`) only once the export succeeds (see the backup data flow in [ARCHITECTURE.md](../ARCHITECTURE.md)). A crash during the export therefore leaves the snapshot incomplete, so the next backup's `PruneDatabase` drops it and re-backs-up its data, rather than leaving a completed-looking row in the local index with no matching metadata on the destination store. (A crash in the brief moment after the export succeeds but before completion is recorded leaves a fully-restorable snapshot on the destination that the local index drops as incomplete on the next run; `snapshot list` then reports it honestly as remote-only, which is the safe direction: the destination copy stays restorable.) +2. **Blobs are written before metadata** - A snapshot's metadata is only written + after all its blobs are successfully uploaded +3. **Metadata is written atomically** - Both db.zst.age and manifest.json.zst + are written as complete files +4. **A snapshot is marked complete in the local DB only after its metadata is + uploaded** - `finalizeSnapshotMetadata` runs `ExportSnapshotMetadata` first + and records completion (`MarkSnapshotComplete`) only once the export succeeds + (see the backup data flow in [ARCHITECTURE.md](ARCHITECTURE.md)). A crash + during the export therefore leaves the snapshot incomplete, so the next + backup's `PruneDatabase` drops it and re-backs-up its data, rather than + leaving a completed-looking row in the local index with no matching metadata + on the destination store. (A crash in the brief moment after the export + succeeds but before completion is recorded leaves a fully-restorable snapshot + on the destination that the local index drops as incomplete on the next run; + `snapshot list` then reports it honestly as remote-only, which is the safe + direction: the destination copy stays restorable.) ## Pruning Safety The prune operation is safe because: -1. It keeps every blob listed in any snapshot's manifest and deletes only blobs that no manifest references. Under `metadata/` it deletes only a directory that has no `manifest.json.zst`, whose name is a remote key, and that no local snapshot record claims + +1. It keeps every blob listed in any snapshot's manifest and deletes only blobs + that no manifest references. Under `metadata/` it deletes only a directory + that has no `manifest.json.zst`, whose name is a remote key, and that no + local snapshot record claims 2. Manifests are unencrypted and can be read without keys -3. If any manifest cannot be downloaded or decoded, prune deletes nothing and exits with an error, rather than treating that snapshot's blobs as unreferenced -4. It deletes an unreferenced blob only once the blob is older than `prune_grace_period` (default `24h`), and a directory under `metadata/` with no manifest only once every object in it is. A backup uploads its blobs and its `db.zst.age` before its manifest, so a prune running meanwhile, on this host or another sharing the destination, leaves them as long as no backup run takes longer than the grace period. The grace period does not protect a blob a backup reuses from an earlier run that stopped before its manifest: the backup skips the upload of a blob already on the destination, so that blob keeps the time of its first upload, and a prune before the backup's manifest is written can delete it; the new snapshot then cannot be restored. `remote nuke` has no such check +3. If any manifest cannot be downloaded or decoded, prune deletes nothing and + exits with an error, rather than treating that snapshot's blobs as + unreferenced +4. It deletes an unreferenced blob only once the blob is older than + `prune_grace_period` (default `24h`), and a directory under `metadata/` with + no manifest only once every object in it is. A backup uploads its blobs and + its `db.zst.age` before its manifest, so a prune running meanwhile, on this + host or another sharing the destination, leaves them as long as no backup run + takes longer than the grace period. The grace period does not protect a blob + a backup reuses from an earlier run that stopped before its manifest: the + backup skips the upload of a blob already on the destination, so that blob + keeps the time of its first upload, and a prune before the backup's manifest + is written can delete it; the new snapshot then cannot be restored. + `remote nuke` has no such check ## Restoration Requirements To restore from a backup, you need: + 1. **The Age private key** - To decrypt blobs and database 2. **The snapshot metadata** - Both files from the snapshot's metadata directory 3. **All referenced blobs** - As listed in the manifest The restoration process: + 1. Download and decrypt the database dump to understand file structure 2. Download and decrypt the required blobs 3. Reconstruct files from their chunks -4. Restore file metadata (permissions, timestamps, etc.) \ No newline at end of file +4. Restore file metadata (permissions, timestamps, etc.) diff --git a/docs/TODO.md b/docs/TODO.md new file mode 100644 index 0000000..fe2b554 --- /dev/null +++ b/docs/TODO.md @@ -0,0 +1,1224 @@ +# Workflow + +- branch (from `main`) +- do the work in Next Step +- move Next Step to the top of Completed Steps +- move the top item of Future Steps into Next Step +- commit (`TODO.md` changes in the same commit as the work) +- merge to `main` if the branch is not protected, otherwise open a PR +- push + +# Status + +pre-1.0 + +# Next Step + +The 1.0 work is complete on `next`: the scope settled on +[issue #125](https://git.eeqj.de/sneak/vaultik/issues/125) has landed, and so +has every fix from the defect hunt before the release candidate +([issue #288](https://git.eeqj.de/sneak/vaultik/issues/288)). What is left is +merging `next` to `main` and tagging the release, both the owner's; a `v*` tag +runs the release build in `.gitea/workflows/release.yml`. + +# Completed Steps + +- 2026-11-10: `script/fmt` and `script/fmt-check` now format and check all + Markdown with `prettier` + ([issue #411](https://git.eeqj.de/sneak/vaultik/issues/411)). The architecture + document and this file moved to `docs/`, and the example config to `configs/`. + +- 2026-11-10: Printed the status and progress lines of `remote info` and + `snapshot verify` through `internal/ui`, with its marker and color, as the + README describes ([issue #410](https://git.eeqj.de/sneak/vaultik/issues/410)). + Their reports stay plain. + +- 2026-11-10: Made `config init` write the `apps` snapshot, which backs up + `/Applications`, only on macOS + ([issue #408](https://git.eeqj.de/sneak/vaultik/issues/408)). On Linux the + first `snapshot create` stopped on the missing directory. + +- 2026-10-15: Stopped `snapshot create --prune` pruning after a backup in which + a volume mounted below a configured path in an earlier snapshot of the same + name was not mounted + ([issue #395](https://git.eeqj.de/sneak/vaultik/issues/395)). Such a prune + could delete every snapshot still holding the volume's files. Each snapshot + now records in the local index the directories it found on a different + filesystem from their parent and found an entry in that the backup does not + exclude. + +- 2026-10-14: Stopped `snapshot create --prune` pruning after a backup that + found nothing in a configured path + ([issue #388](https://git.eeqj.de/sneak/vaultik/issues/388)), as in the mount + point of a volume that is not mounted. Such a prune could delete every + snapshot still holding that path's files. A configured path that is a symlink + whose target is gone, as one into such a volume, now fails the backup, with or + without `--prune`. + +- 2026-10-14: Stopped `snapshot create --prune` pruning after a backup that + skipped files it could not read + ([issue #382](https://git.eeqj.de/sneak/vaultik/issues/382)). Such a prune + could delete the only snapshot still holding those files. + +- 2026-10-14: Made `snapshot create --skip-errors` exit non-zero, instead of 0, + when it skips anything it cannot read + ([issue #310](https://git.eeqj.de/sneak/vaultik/issues/310)). + +- 2026-10-14: Kept the local index when `remote nuke` cannot list or find the + destination store + ([issue #292](https://git.eeqj.de/sneak/vaultik/issues/292)). Nuke had cleared + the local snapshot records anyway; it now fails before removing anything. + +- 2026-10-14: Stopped counting directories and unchanged symlinks as files to + back up ([issue #305](https://git.eeqj.de/sneak/vaultik/issues/305)). + +- 2026-10-14: Refused a backup destination that an unplugged volume left empty, + as the owner ruled + ([issue #239](https://git.eeqj.de/sneak/vaultik/issues/239)). Every backup now + writes `vaultik-destination.txt` at the destination root, and while the local + index holds snapshots stored there, a destination without it is treated as not + present. + +- 2026-10-14: Warned about restored ownership only when an entry's owner or + group differs from the recorded one + ([issue #316](https://git.eeqj.de/sneak/vaultik/issues/316)); a restore by a + non-root user had warned even when none did. + +- 2026-10-14: Made `snapshot list` report a changed destination instead of + advising `prune`, which refuses in that case + ([issue #317](https://git.eeqj.de/sneak/vaultik/issues/317)). + +- 2026-10-14: Counted a file as deleted by a backup only if the previous + snapshot of the same name listed it + ([issue #304](https://git.eeqj.de/sneak/vaultik/issues/304)); files that + snapshot did not list had been counted too. + +- 2026-10-14: Named each prefix once in restore, verify and purge errors, some + of which repeated it + ([issue #327](https://git.eeqj.de/sneak/vaultik/issues/327)). A deep verify + log line that named S3 whatever the destination now names storage. + +- 2026-10-14: Refused credentials in a storage URL's endpoint or rclone remote + name, which were accepted and could then be printed + ([issue #322](https://git.eeqj.de/sneak/vaultik/issues/322)). + +- 2026-10-14: Ran `$EDITOR` through the shell in `config edit`, so a value with + arguments, such as `code --wait`, no longer fails + ([issue #315](https://git.eeqj.de/sneak/vaultik/issues/315)). + +- 2026-10-14: Made `snapshot remove` fail, instead of exiting 0, when it cannot + delete the metadata of a snapshot that is only on the destination store + ([issue #340](https://git.eeqj.de/sneak/vaultik/issues/340)). The README and + the help now say when it prints the `vaultik prune` follow-up. + +- 2026-10-14: Labelled the totals in the local index cleanup before each backup + as totals ([issue #306](https://git.eeqj.de/sneak/vaultik/issues/306)). Each + was shown as `(N remain)`, which read as rows left to clean up. + +- 2026-10-13: Freed a cached blob once no file still to restore needs it + ([issue #324](https://git.eeqj.de/sneak/vaultik/issues/324)); one also used by + a file outside the selected paths had stayed in the temporary cache until the + restore ended. + +- 2026-10-13: Kept the whole startup error when it contains `): ` + ([issue #320](https://git.eeqj.de/sneak/vaultik/issues/320)). Such an error + was cut at its last `): `, so the `blob_size_limit` one lost the setting's + name. + +- 2026-10-13: Silenced the status lines of `prune` and snapshot removal under + `--cron` and `--quiet` + ([issue #294](https://git.eeqj.de/sneak/vaultik/issues/294)). + +- 2026-10-13: Read the rclone config file that `RCLONE_CONFIG` names + ([issue #321](https://git.eeqj.de/sneak/vaultik/issues/321)); a remote defined + only there had been reported as not found. + +- 2026-10-13: Made `/**/` in an exclude pattern match zero directories, as in + gitignore ([issue #338](https://git.eeqj.de/sneak/vaultik/issues/338)); + `a/**/*.log` had missed `a/x.log`. + +- 2026-10-13: Made the `chunk_size` and `blob_size_limit` defaults and the + `chunk_size` minimum 1000-based, like the size parser and the docs + ([issue #313](https://git.eeqj.de/sneak/vaultik/issues/313)). + +- 2026-10-13: Kept a snapshot's remote metadata when `snapshot purge` cannot + remove it from the local index + ([issue #337](https://git.eeqj.de/sneak/vaultik/issues/337)); the purge had + deleted the metadata anyway and exited 0. + +- 2026-10-13: Made `snapshot restore` fail for a requested path that matches + nothing, which it had ignored + ([issue #309](https://git.eeqj.de/sneak/vaultik/issues/309)). + +- 2026-10-13: Made `remote nuke` delete every object under `metadata/` and + `blobs/` ([issue #291](https://git.eeqj.de/sneak/vaultik/issues/291)); it had + left some, such as a stray `.DS_Store`, while reporting the store empty. + +- 2026-10-13: Made `config set` create a list for an index under a missing key + ([issue #308](https://git.eeqj.de/sneak/vaultik/issues/308)); it had written a + map, after which no command could load the config. + +- 2026-10-13: Listed a `file://` destination through a symlinked `metadata/` or + `blobs/`, which had listed as empty + ([issue #296](https://git.eeqj.de/sneak/vaultik/issues/296)). A link to a + missing target now fails the listing + ([issue #332](https://git.eeqj.de/sneak/vaultik/issues/332)). + +- 2026-10-13: Made `snapshot verify --deep --json` report its blob counts + ([issue #314](https://git.eeqj.de/sneak/vaultik/issues/314)); a failed run had + reported 0 missing and 0 verified. + +- 2026-10-13: Limited and retried the module download in the Docker build + ([issue #351](https://git.eeqj.de/sneak/vaultik/issues/351)), which had hung + for as long as a stalled connection to the module proxy lasted. + +- 2026-10-13: Recorded each snapshot's uncompressed size when its backup runs + ([issue #360](https://git.eeqj.de/sneak/vaultik/issues/360)). A later backup + could change an older snapshot's UNCOMPRESSED SIZE in `snapshot list`. + +- 2026-10-13: Stopped `snapshot restore --skip-errors --verify` reporting a file + that failed to restore again as a checksum failure + ([issue #323](https://git.eeqj.de/sneak/vaultik/issues/323)). + +- 2026-10-13: Recorded the stored size of a blob a backup finds already stored, + not the size of its local copy, which can differ, so `snapshot verify` could + fail on a good snapshot + ([issue #300](https://git.eeqj.de/sneak/vaultik/issues/300)). + +- 2026-10-13: Stopped the local index and the blob upload step ending the + process on a failed close of query results or a failed temp file cleanup + ([issue #345](https://git.eeqj.de/sneak/vaultik/issues/345)); both are now + returned as errors. + +- 2026-10-13: Closed the snapshot database's storage reader too when restore or + deep verify is interrupted + ([issue #356](https://git.eeqj.de/sneak/vaultik/issues/356)). + +- 2026-10-13: Made `prune` and `remote nuke` fail when a delete on the backup + destination store fails + ([issue #290](https://git.eeqj.de/sneak/vaultik/issues/290)). + +- 2026-10-13: Made an S3 listing that the server cuts short an error + ([issue #297](https://git.eeqj.de/sneak/vaultik/issues/297)); `prune` had + taken it as complete and could delete blobs still in use. + +- 2026-10-13: Made shallow `snapshot verify` report a blob it could not check + apart from a missing one + ([issue #318](https://git.eeqj.de/sneak/vaultik/issues/318)); any error + checking a blob had counted as missing, its cause dropped. + +- 2026-10-13: Restored the other files when a file's chunk is in no blob under + `--skip-errors` ([issue #326](https://git.eeqj.de/sneak/vaultik/issues/326)); + that file had stopped the restore before anything was restored. + +- 2026-10-13: Recorded each snapshot's new chunk size when its backup runs + ([issue #311](https://git.eeqj.de/sneak/vaultik/issues/311)). `snapshot list` + could show a NEW CHUNK SIZE of 0 B for a snapshot whose change was a modified + file. + +- 2026-10-13: Made a backup interrupted during a local index write exit as + interrupted ([issue #301](https://git.eeqj.de/sneak/vaultik/issues/301)); it + could end with `FATAL: failed to rollback transaction` and exit 1 instead + of 130. + +- 2026-10-13: Printed `snapshot list` and `snapshot purge` sizes like every + other command ([issue #312](https://git.eeqj.de/sneak/vaultik/issues/312)). + They, and the `bytes` value in terminal log lines, were 1024-based but + labelled KB or MB, and now use 1000-based units. + +- 2026-10-13: Closed each blob's storage reader when restore or deep verify is + interrupted, which ends a stalled read unless it is stuck in the kernel + ([issue #325](https://git.eeqj.de/sneak/vaultik/issues/325)). + +- 2026-10-13: Made a mistyped subcommand under `snapshot`, `config`, `remote`, + `database` or `completion` an error + ([issue #319](https://git.eeqj.de/sneak/vaultik/issues/319)); each had printed + its help and exited 0. + +- 2026-10-13: Made an exclude pattern starting with `**/` match directly under + the snapshot path too, as in gitignore + ([issue #303](https://git.eeqj.de/sneak/vaultik/issues/303)). + +- 2026-10-13: Refused a relative `file://` storage URL and decoded its + percent-escapes ([issue #299](https://git.eeqj.de/sneak/vaultik/issues/299)); + a relative path had moved with the working directory. + +- 2026-10-13: Removed the blob temp file when a backup stops part-way + ([issue #302](https://git.eeqj.de/sneak/vaultik/issues/302)); the half-written + blob had stayed in `$TMPDIR`. + +- 2026-10-13: Checked `--keep-newer-than` before a backup starts + ([issue #307](https://git.eeqj.de/sneak/vaultik/issues/307)); an invalid value + had been read only by the prune after the backup, so retention never ran. + +- 2026-10-13: Stopped `remote info` counting a file under `blobs/` that is not a + blob as an orphaned blob + ([issue #295](https://git.eeqj.de/sneak/vaultik/issues/295)). A stray file + such as `.DS_Store` was reported as an orphaned blob and the report advised + running `prune`, which skips such a file and deleted nothing. `remote info` + now takes its blob list from the same listing `prune` uses, in the table and + in `--json`. + +- 2026-10-13: Made `snapshot remove` fail for a snapshot that does not exist + ([issue #293](https://git.eeqj.de/sneak/vaultik/issues/293)). The command + never checked the ID: it reported the snapshot removed from the local database + and from the destination store and exited 0, under `--json`, `--dry-run` and + `--local-only` too. An ID that names no snapshot in the local index or on the + destination store is now an error; with `--local-only`, the snapshot must be + in the local index. The command now reports a removal from either side only + when one happened, and `remote_removed` is true only when metadata was + deleted. + +- 2026-10-12: Bound the local index to the destination an `s3.*` config names + ([issue #298](https://git.eeqj.de/sneak/vaultik/issues/298)). Only + `storage_url` was checked, so after `s3.bucket` or `s3.prefix` changed, the + next backup treated every chunk as already stored, uploaded nothing, and + completed a snapshot that could not be restored. Without `storage_url`, the + local index is now bound to `s3.endpoint`, `s3.bucket` and `s3.prefix`, and a + change is refused as a changed `storage_url` is. + +- 2026-10-12: Rejected a retention duration longer than about 292 years + ([issue #289](https://git.eeqj.de/sneak/vaultik/issues/289)). The number given + to `--older-than` or `--keep-newer-than` was multiplied by the length of its + unit with no limit, so from `293y`, `15251w`, `3559mo` or `106752d`, or a sum + of parts such as `200y200y`, the result wrapped to a negative duration. The + cutoff then lay in the future, every snapshot of the name was deleted, the one + just made included, and the command exited 0. Such a duration is now rejected + as invalid and nothing is deleted. + +- 2026-10-08: Made a backup cancelled under `--skip-errors` stop at once + ([issue #286](https://git.eeqj.de/sneak/vaultik/issues/286)). After Ctrl-C or + SIGTERM, phase 2 treated the cancellation error from each remaining file like + an unreadable file: it opened the file, printed an error line for it, counted + it as failed and went on to the next one. The run now stops at the first file + after the cancellation, and no file is counted as failed because of it. + +- 2026-10-08: Made `remote nuke` delete the `.partial` files that uploads cut + off part-way leave on the destination store + ([issue #281](https://git.eeqj.de/sneak/vaultik/issues/281)). The file and + rclone listings skip such a file, so the command left it in place and still + reported the store empty. It now removes them under `metadata/` and `blobs/` + as its last step. + +- 2026-10-08: Made a local index error while recording a directory or symlink + stop a backup under `--skip-errors` + ([issue #284](https://git.eeqj.de/sneak/vaultik/issues/284)). Phase 2 only + records such an entry in the local index, since it has no data to open or + read, but an error doing so was skipped like an unreadable file. The snapshot + then completed without the entry, and a restore did not recreate it. The error + now stops the backup, as it does without the flag. + +- 2026-10-08: Counted a file that a backup could not store as failed + ([issue #280](https://git.eeqj.de/sneak/vaultik/issues/280)). A file that + phase 1 counted and phase 2 could not open, because it was unreadable under + `--skip-errors` or removed in between, was reported in the summary as + unchanged with its bytes as backed up, and the `snapshots` row's `file_count` + and `total_size` included it. The summary now counts it as failed, and its + data total and the row leave it out. + +- 2026-10-08: Made `remote info` report a snapshot's blob count and blob size as + unknown when its manifest cannot be read + ([issue #272](https://git.eeqj.de/sneak/vaultik/issues/272)). The orphan + figures were already unknown in that case, but the snapshot's row still gave 0 + blobs and 0 B, in the table and in `--json`. The row now reads `unknown` and + `--json` gives `null`. A directory with no manifest still shows 0, since the + orphan figures count its blobs as orphaned. + +- 2026-10-08: Kept the progress line of a snapshot with more than one path + within 100% ([issue #271](https://git.eeqj.de/sneak/vaultik/issues/271)). The + bytes and files processed counted every path, but the totals they were divided + by held only the current path's, so a second path smaller than the first + showed more than 100% and an ETA of `unknown`. The totals now add up over the + paths scanned so far. The rate behind the ETA restarts when each path's scan + phase ends, so that phase does not lower the rate while the path is processed; + until then the rate is the previous path's. + +- 2026-10-08: Made a second `snapshot create` of one name succeed when it starts + in the same second as the first + ([issue #270](https://git.eeqj.de/sneak/vaultik/issues/270)). The timestamp in + a snapshot ID is in whole seconds, so the second run got the first run's ID + and failed with `UNIQUE constraint failed: snapshots.id`. When the local index + already has a snapshot with the ID, the create now waits a second and takes a + new timestamp. + +- 2026-10-07: Documented that `--json` skips the confirmation prompt of + `snapshot remove` and `prune` + ([issue #268](https://git.eeqj.de/sneak/vaultik/issues/268)). Both commands + delete without asking under `--json`, since a prompt on stdout would break the + JSON document, but the help and the README described only `--force` as + skipping it. The `--json` help of both commands and their README entries now + say so. + +- 2026-10-07: Made a symlink whose target cannot be read stop the backup + ([issue #269](https://git.eeqj.de/sneak/vaultik/issues/269)). It was left out + of the snapshot with only a debug log line, even without `--skip-errors`. It + now aborts the run, or with `--skip-errors` is skipped with the + `Failed to access` error line that any other entry the scan cannot read gets. + +- 2026-10-07: Stopped a killed rclone upload from leaving a truncated object + under its key ([issue #266](https://git.eeqj.de/sneak/vaultik/issues/266)). + The rclone backend wrote each object straight to its key, so killing an upload + to a local or sftp remote left a truncated object there; the next backup found + the key with `Stat`, skipped the upload and recorded a snapshot that could not + be restored. On a remote with a server-side move, an object is now written + under a temporary name ending in `.partial` and moved into place, and listings + skip such names. Remotes without one are still written in place. + +- 2026-10-07: Made an interrupted command exit 130 and say so + ([issue #267](https://git.eeqj.de/sneak/vaultik/issues/267)). Ctrl-C or + SIGTERM during `snapshot create`, `snapshot restore` or `snapshot verify` + exited 0 with no error line (`snapshot verify --json` exited 1, also without + one), so a `--cron` run that never finished looked like a success. A command + stopped by either signal now exits 130 and prints + `interrupted before the command finished` on stderr, under `--cron` and + `--json` too. + +- 2026-10-07: Corrected documentation, help text and comments that were false + about the code ([issue #233](https://git.eeqj.de/sneak/vaultik/issues/233)). A + blob is not streamed to storage. The README, `ARCHITECTURE.md` and + `config.example.yml` now say a backup needs free temporary space, because each + blob is written whole to a temporary file before it is uploaded (up to about + `blob_size_limit`; an rclone destination that cannot stream uploads needs + about twice that) and the metadata export writes copies of the local index. + Temporary files go to `$TMPDIR` (default `/tmp`); with `TMPDIR` unset, SQLite + writes one of those copies to `/var/tmp`. Also corrected: the snapshot ID + format, what restore reads and how incomplete snapshots are removed in + `docs/DATAMODEL.md`, what `source_path` holds, the `index_path` and config + file defaults, what `snapshot remove` cleans up, how the release gets its Go + toolchain, and the `script/release` and `script/fmt-check` comments. + +- 2026-10-07: Cut the time the `internal/vaultik` and `internal/database` tests + take ([issue #235](https://git.eeqj.de/sneak/vaultik/issues/235)). Most of the + `internal/vaultik` time went to 24 tests that ran one at a time only because + they call `log.Initialize`; they now call it before `t.Parallel()`, as the + package's other tests do. `TestLargeDatasets` committed each of its 1,500 + inserts on its own and now makes them in one transaction. + `TestDedupOnlySnapshotRestores` gives its second backup its own snapshot name + instead of sleeping past the one-second timestamp in the snapshot ID. + +- 2026-10-07: Made two messages say only what is true + ([issue #240](https://git.eeqj.de/sneak/vaultik/issues/240)). A config file + that others can read was warned about as containing S3 credentials even when + it set none, as a `file://` config does. The warning now says the file may + contain S3 credentials only when `s3.access_key_id` or `s3.secret_access_key` + is set, since either may come from a `${...}` reference rather than the file, + and otherwise says the file is readable by others. `snapshot purge` against a + destination store it could not list gave an error with + `listing remote snapshots:` in it twice; the prefix now appears once. + +- 2026-10-07: Made `s3.part_size` set the multipart upload part size + ([issue #232](https://git.eeqj.de/sneak/vaultik/issues/232)). It was loaded + and defaulted but never passed to the S3 client, whose uploader used a fixed + 10MiB part. It now reaches the uploader for `storage_url` and for the `s3.*` + fields, and a part size S3 refuses, below 5MiB or above 5GiB, `0` included, + fails at config load. A blob too large for S3's limit of 10,000 parts at the + configured size is uploaded in larger parts. The docs gave the default as + `5MB`, which the config file reads as 5,000,000 bytes, below the minimum; they + now say `5MiB`. + +- 2026-10-07: Made per-name retention work when the hostname contains `_` + ([issue #230](https://git.eeqj.de/sneak/vaultik/issues/230)). A snapshot ID is + `hostname_name_timestamp`, and the name was read as everything between the + first and the last `_`, so with `hostname: my_host` the name `home` came out + as `host_home`. `snapshot purge --keep-latest --snapshot home` then printed + "No snapshots to delete", and `snapshot create --prune` purged nothing without + a message. The name is now read using the hostname the `snapshots` table + stores with each snapshot, cut at its first `.` as it is in the ID. + +- 2026-10-07: Made `remote info` stop reporting a snapshot's blobs as orphaned + when its manifest cannot be read, and stop printing raw names from under + `metadata/` ([issue #228](https://git.eeqj.de/sneak/vaultik/issues/228)). A + manifest it failed to read was skipped, so that snapshot's blobs were counted + as orphaned and the report advised running `vaultik prune`. The orphan figures + are now unknown in that case, with no prune advice, and `--json` gives them as + `null` with the unreadable remote keys in `unreadable_manifests`. A name under + `metadata/` that is not 64 lowercase hex characters is now skipped with a + warning instead of being printed, control characters included. A manifest + under a skipped name is then not read either, so it also leaves the orphan + figures unknown, and `--json` counts such manifests in + `skipped_manifest_count`. A directory with no manifest in it, as left by an + interrupted backup, leaves the figures known. + +- 2026-10-07: Made `config set` keep a string that looks like a number + ([issue #229](https://git.eeqj.de/sneak/vaultik/issues/229)). It wrote every + value unquoted, and `config.Load` reads the file through untyped YAML, so an + access key `00112233` loaded as `38043` and a hostname `007` as `7`. A value + for a string setting in `config.Config` is now tagged as a YAML string, which + the file quotes wherever YAML would read a number or a boolean; other settings + are still written unquoted. + +- 2026-10-07: Made a backup notice a file rewritten with its size unchanged and + a new mtime in the same second as the one in the index + ([issue #226](https://git.eeqj.de/sneak/vaultik/issues/226)). The `files` + table held mtime in whole seconds and the scanner compared whole seconds, so + every later snapshot kept the old content. A new `mtime_nsec` column holds the + nanoseconds within the second that `mtime` holds, and the scanner compares the + full mtime. A local index created before the change lacks the column and is + rebuilt with `vaultik database delete` and a full backup. + +- 2026-10-07: Made taking the process-wide lock atomic + ([issue #227](https://git.eeqj.de/sneak/vaultik/issues/227)). The lock read + `vaultik.pid`, checked whether that PID was alive and then wrote its own, so + two writers started together could both pass the check and both run. It is now + an `flock` on `vaultik.pid`, held until the run ends; the kernel drops it when + the process exits, so a crash leaves no lock behind. A clean exit now empties + the file instead of deleting it, because deleting it would let two later runs + each lock a different file. + +- 2026-10-06: Made `snapshot remove --json` write only its document to stdout + when the destination store cannot be reached + ([issue #251](https://git.eeqj.de/sneak/vaultik/issues/251)). Its warning that + the snapshot's metadata was left on the destination store went to stdout ahead + of the document, breaking `| jq` on a command that exited 0. Under `--json` + the warning now reaches stderr only, through the logger. The warning, the + README and the command's help said `vaultik prune` would finish the cleanup, + but `prune` never removes snapshot metadata; they now say to run + `vaultik snapshot remove` for the snapshot again once the destination store is + reachable. + +- 2026-10-06: Made the backup summary and the `snapshots` row count each file, + byte and upload once + ([issue #225](https://git.eeqj.de/sneak/vaultik/issues/225)). The scanner + added a file's bytes again for each new chunk and counted a file as unchanged + for each chunk already stored, so a first backup reported twice its size and + "backed up" could go negative. Upload figures came from the progress reporter, + which `--cron` turns off, and `blob_count` counted earlier paths' blobs again + for each later path. The scanner now counts uploads itself; `blob_size`, + `blob_uncompressed_size` and `compression_ratio` describe the blobs the + snapshot references, and `docs/DATAMODEL.md` now says `chunk_count` and + `blob_count` count what the run added. + +- 2026-10-06: Made command output follow the README's stdout and stderr rules + ([issue #224](https://git.eeqj.de/sneak/vaultik/issues/224)). The startup + banner went to stdout, so a `completion` script or a `config get` value + started with it; the banner now goes to stderr. A failing `remote info`, + `prune` or `snapshot remove` under `--json` printed nothing on either stream, + and now reports its error on stderr. `snapshot verify --quiet` printed its + whole report; it now prints none, and a failure still reaches stderr with the + same exit status. + +- 2026-10-06: Made a backup without `--cron` of a snapshot with two or more + `paths` complete instead of panicking with `close of closed channel` + ([issue #253](https://git.eeqj.de/sneak/vaultik/issues/253)). `Scan` runs once + per path and started and stopped the progress reporter each time, and a second + stop panics. The reporter is now started and stopped once per snapshot, around + the scans of all its paths. + +- 2026-10-06: Made a restore path argument select only that path and what is + beneath it ([issue #223](https://git.eeqj.de/sneak/vaultik/issues/223)). The + lookup matched with SQL `LIKE`, so `/home/u/doc` also restored `doc2`, `DOC` + and `doc.txt.bak`, and a `_` or `%` in the path acted as a wildcard. A backup + used the same lookup to load the known files of each configured path, so files + of a longer sibling path were counted as deleted. + `FileRepository.ListUnderPath`, which replaces `ListByPrefix`, returns the + file at the path and every file whose path starts with the path plus `/`, + compared case-sensitively. + +- 2026-10-06: Made restore return an error instead of panicking on a malformed + snapshot database + ([issue #231](https://git.eeqj.de/sneak/vaultik/issues/231)). A chunk hash + shorter than 16 characters crashed the error message naming it, and `--verify` + dereferenced a missing `chunks` row and allocated whatever chunk size the + database gave. Those messages now go through `shortHash`, a missing row is an + error, and `--verify` rejects a negative size and hashes each chunk as a + stream. + +- 2026-10-06: Made `s3://bucket/prefix` and `s3://bucket/prefix/` the same + destination ([issue #222](https://git.eeqj.de/sneak/vaultik/issues/222)). The + S3 client put the prefix directly in front of each key, so a prefix without a + trailing slash stored `prefixblobs/...`. A non-empty prefix is now joined to + every key with one `/`, giving the README's `//blobs/...` + layout. The `s3.prefix` config setting goes through the same client and gets + the same join. + +- 2026-10-06: Made restore apply owners, modes and times in an order that keeps + them ([issue #219](https://git.eeqj.de/sneak/vaultik/issues/219)). A directory + got its stored mode and mtime before its contents were written, so a read-only + directory came back without its files and a non-empty one carried the time of + the restore. Directories are now created owner-only and get their stored + owner, mode and mtime once the restore loop is done, each before its parent. A + file's mode is applied after its chown, which on Linux clears setuid and + setgid, and a symlink gets its stored owner (as root) and mtime on the link + itself. + +- 2026-10-06: Made `go.mod` what `go mod tidy` writes, so the pre-commit hook no + longer stops every commit + ([issue #246](https://git.eeqj.de/sneak/vaultik/issues/246)). A test in + `internal/cli` imports `github.com/spf13/pflag` directly, but `go.mod` still + marked it `// indirect`, and `script/precommit` fails whenever the tidy + changes `go.mod`. It is now in the direct `require` block. + +- 2026-10-06: Made the README's steps for restoring on another machine work + ([issue #221](https://git.eeqj.de/sneak/vaultik/issues/221)). `config init` + wrote a placeholder recipient that `config.Load` rejects, so every command on + the new machine failed before reaching the store. The file now has an empty + `age_recipients` list, `config.Load` accepts an empty list, and + `snapshot create` refuses to run without a recipient. + +- 2026-10-06: Made `snapshot restore --skip-errors` skip the files that need a + blob it cannot download + ([issue #218](https://git.eeqj.de/sneak/vaultik/issues/218)). A missing or + damaged blob ended the restore even with the flag, after restoring whichever + files happened to come first. Every file that needs such a blob is now + reported as failed, the rest are restored, and the command still exits + non-zero. Without the flag the blob error still aborts. + +- 2026-10-06: Re-vendored the canonical files from `sneak/prompts` at `dd4027b` + ([issue #213](https://git.eeqj.de/sneak/vaultik/issues/213)). Linting and + testing are now the `lint` and `test` phases of the `Dockerfile`, and the + build stage depends on both. `Dockerfile.lint`, `CHECK_EPOCH` and the tests + that checked them are gone; every `docker build` in `script/` passes + `--no-cache` instead. golangci-lint is v2.14.0, with its new findings fixed in + the code, and the rules in `CLAUDE.md` now live in `AGENTS.md`. + +- 2026-10-06: Made the local index actually run in WAL mode with a busy timeout + ([issue #217](https://git.eeqj.de/sneak/vaultik/issues/217)). The connection + settings were written in a form the SQLite driver ignores, so the index ran + without either and `snapshot list` or `info` during a backup could make the + backup's next write fail with `database is locked`. They are now `_pragma=` + parameters, and the metadata export copies the open index with `VACUUM INTO`, + because a copy of the file alone misses rows still in the `-wal` file. + +- 2026-10-06: Made a backup record the real uid and gid of files, directories + and symlinks ([issue #216](https://git.eeqj.de/sneak/vaultik/issues/216)). The + scanner asked the stat result for `Uid()` and `Gid()` methods, which + `*syscall.Stat_t` does not have, so every entry was stored as `0:0` and a + restore as root gave every file to root. It now reads the `Uid` and `Gid` + fields of `*syscall.Stat_t`. + +- 2026-10-06: Made a `file://` destination whose directory is missing count as + one that cannot be listed + ([issue #220](https://git.eeqj.de/sneak/vaultik/issues/220)). The file backend + listed a missing directory as an empty store, so with the quickstart's USB + stick unplugged `snapshot list` reported every local snapshot as missing from + the store, `snapshot remove` claimed to have removed metadata it never + reached, and `prune` dropped every local snapshot record. Listing a missing + destination directory is now an error; a first backup still creates the + directory. + +- 2026-10-06: Made `--older-than` and `--keep-newer-than` reject a duration with + characters outside its number-and-unit parts + ([issue #215](https://git.eeqj.de/sneak/vaultik/issues/215)). The parser + picked out the parts it recognised and skipped the rest, so `1.0y` became zero + and `--prune --keep-newer-than 1.0y` deleted every snapshot of the backed-up + names, the new one included. `1.0y`, `1,5y`, `30 days`, `x7d` and a bare `0` + are now errors; decimals still work in Go units such as `1.5h`. + +- 2026-10-06: Made a backup re-chunk a known file that lists a chunk no uploaded + blob holds ([issue #214](https://git.eeqj.de/sneak/vaultik/issues/214)). File + rows are shared by every snapshot and updated in place, so removing or pruning + the only snapshot that referenced a changed file's current blob left an older + snapshot keeping a row that matched the disk while no blob held its chunks. + The next backup skipped the file and completed a snapshot that could not + restore it. + +- 2026-09-22: Routed the last direct-to-stdout command output through + `internal/ui` ([issue #149](https://git.eeqj.de/sneak/vaultik/issues/149)). + The `version`, `info`, `remote info`, `config`, and `database delete` commands + wrote plain text straight to stdout, so they were unstyled and ignored + `--quiet`. Output now falls in two buckets, both governed by `internal/ui`: + status lines and confirmations go through its message methods (styled, and + `--quiet` silences them), while the data a command exists to produce — the + reports, the `snapshot list` table, `config get` values, and the `--json` + documents — is written plain. `--quiet` silences the human reports and tables + but never the `config get` value or the `--json` documents, which a script + depends on, and the `database delete` confirmation prompt is always shown. The + README output-style section now states this rule. + +- 2026-09-22: Validated blob hashes, offsets and lengths read back from the + destination before using them + ([issue #155](https://git.eeqj.de/sneak/vaultik/issues/155)). A blob hash + taken from the downloaded database or the store listing was trusted unchecked, + so a hostile remote could drive a decrypted blob to be written outside the + cache directory (a hash like `aa/../../etc`) or crash a command with a short + or negative value. `blobDiskCache.path` now refuses any key containing a path + separator, and `ReadAt` rejects a negative offset or length and bounds with + `length > size-offset` so a sum cannot overflow past the check. A new + `isBlobHash` helper (a plain function, not a method — the packer stores + `temp-placeholder-{uuid}` as a hash) gates `FetchBlob`, shallow and deep + verify; the `blobs/` and `metadata/` listings skip a non-conforming name with + a warning; and short-hash prefixes in log and error text go through a + `shortHash` helper that cannot panic. `verify`'s chunk reader also rejects a + negative `blob_chunks` length and streams the chunk instead of allocating a + database-supplied size. `restore.go` and `internal/database` were left + untouched to avoid colliding with the in-flight + [issue #156](https://git.eeqj.de/sneak/vaultik/issues/156) work; the + cache-path and `FetchBlob` guards already stop the unsafe write and fetch, so + restore's own `buildBlobIndexes` early check is deferred as fail-fast defense + in depth. + +- 2026-09-21: Stopped an interrupted blob upload from making a later backup + deduplicate against data that was never stored + ([issue #148](https://git.eeqj.de/sneak/vaultik/issues/148)). The packer + commits a blob's `chunks`, `blob_chunks`, and `blobs` rows before the upload + is attempted, so a failed upload left chunk rows behind and the next run + skipped re-uploading them, producing a snapshot that reported success but + could not be restored. A run now deduplicates only against chunks held by a + blob whose `uploaded_ts` is set, and at startup drops any un-uploaded blob + rows (and the chunks they orphan) so the affected data is re-chunked and + re-uploaded. Blobs recorded with no remote backend are marked uploaded so this + invariant holds uniformly. + +- 2026-09-22: Made restore refuse any snapshot path that would write outside the + target directory ([issue #154](https://git.eeqj.de/sneak/vaultik/issues/154)). + `restoreFile` and `verifyRestoredFiles` joined the stored path onto the target + with no containment check, so a `..` segment or an absolute path escaped the + target and a restored symlink could redirect a later child write anywhere on + disk. Every stored path is now rejected unless `filepath.IsLocal` accepts it + with the leading separator removed, and each existing ancestor directory below + the target is `Lstat`ed to refuse descending through a symlink; honest + symlinks pointing outside the tree are still written verbatim. age decryption + proves a snapshot is readable, not honest, and restore usually runs as root. + +- 2026-09-21: Stopped `--json` from silencing stderr diagnostics + ([issue #112](https://git.eeqj.de/sneak/vaultik/issues/112)). `--json` used to + be folded into `Quiet`, which pinned the log level to `WARN`, so + `prune --json` gave a machine consumer no record of the local index rows it + deleted even under `--verbose`. `--json` now quiets only the stdout UI (the + JSON document must stay clean, per + [issue #108](https://git.eeqj.de/sneak/vaultik/issues/108)); the stderr log + level follows `--verbose`/`--debug` again. The coupling was removed the same + way for `snapshot verify`, `snapshot remove`, and `remote info`, which carried + it for the same outdated reason. + +- 2026-09-21: Stopped `prune` from reporting a failed row count as 0 + ([issue #96](https://git.eeqj.de/sneak/vaultik/issues/96)). The seven + `getTableCount` reads in `PruneDatabase` discarded their error, so a query + that could not run became a plausible `0` and the before/after delta computed + from it looked like real work. Each read now logs at warn on failure and + renders as `unknown`, never `0`, so an empty table is distinguishable from one + that could not be queried. The counts have no `--json` representation — under + `--json` the summary is suppressed entirely — so nothing there can show a + false `0`. + +- 2026-09-21: Made the s3 storage backend report a missing object as + `storage.ErrNotFound`, like the `file` and `rclone` backends and as the + `Storer` interface documents. `S3Storer.Get` and `Stat` returned the raw AWS + SDK error, so `errors.Is(err, storage.ErrNotFound)` was false on s3 and + callers branched differently per backend. Added a small `s3.IsNotFound` helper + (reused by `HeadObject`) and a test that a missing key maps to `ErrNotFound` + ([issue #129](https://git.eeqj.de/sneak/vaultik/issues/129)). +- 2026-09-21: Fixed `verify --deep` reporting healthy snapshots as corrupt. Its + final blob-integrity check hashed the encrypted downloaded bytes with a single + SHA256 and compared that to the blob ID, which is the double SHA256 of the + plaintext, so the two could never match. It now hashes the decompressed + plaintext and compares the double SHA256. Added a test that backs up a real + snapshot, deep-verifies it, then flips a byte in one stored blob and confirms + deep verification then fails + ([issue #131](https://git.eeqj.de/sneak/vaultik/issues/131)). + +- 2026-09-21: Made `snapshot create` VACUUM the per-snapshot metadata database + through the `modernc.org/sqlite` driver instead of shelling out to the + external `sqlite` command-line binary (issue #120). A backup no longer needs + that binary on `PATH`, so `make check` passes on a stock `go install` host; + `script/bootstrap` and the `Dockerfile` (both the test-build and the shipped + runtime stage) no longer install it, and a new test asserts the uploaded + database keeps no pages from deleted rows. Dropped the now-false note on the + 2026-08-07 entry below that said bootstrap installs it. +- 2026-09-21: Made `.gitea/workflows/check.yml` run on pushes to `main` and + `next` and on pull requests against either, so unit PRs (whose base is `next`) + and `next` itself get a CI run instead of relying on a local `make check` + ([issue #122](https://git.eeqj.de/sneak/vaultik/issues/122)). + +- 2026-09-21: Hash-verified the Go toolchain in the release workflow + ([issue #105](https://git.eeqj.de/sneak/vaultik/issues/105)). New + `script/install-go` downloads the exact `go.dev` archive for `go.mod`'s `go` + directive and refuses it unless its sha256 matches a value committed in the + script; `.gitea/workflows/release.yml` calls it instead of `actions/setup-go`, + which verified the downloaded toolchain against nothing in the repo. + `GOTOOLCHAIN: local` on the release step keeps that exact compiler from + auto-switching. Bumping Go now touches `go.mod`, the checksum, and the + `Dockerfile` `golang` digest together. + +- 2026-09-21: Collapsed the two duration parsers into one and fixed the + `--older-than` months example + ([issue #123](https://git.eeqj.de/sneak/vaultik/issues/123)). Two functions + named `parseDuration` existed with different grammars; + `snapshot purge --older-than` and `--keep-newer-than` both already went + through the one in `internal/vaultik`, while the richer copy in + `internal/cli/duration.go` was reachable only from its own test. Kept the + live-path parser and deleted the unused one, so no flag's accepted grammar + changes. The trap the issue was filed over: `README.md` documented `6m` as the + months example for `--older-than`, but `m` is minutes, so the documented + command deleted every snapshot older than six minutes on a destructive flag. + Corrected the doc to `6mo` and put both flags' help text on one example list + that states `m` is minutes and `mo` is months. The surviving parser now + rejects negatives, which it previously accepted (`-5h`) or silently made + positive (`-5d`). Table-driven tests cover every unit, `6m` as six minutes, + `6mo` as 180 days, and rejection of a bare number, an unknown unit, and a + negative. + +- 2026-08-10: Moved every lint run into its own container, as a build step + ([issue #113](https://git.eeqj.de/sneak/vaultik/issues/113)). New root + `Dockerfile.lint`, built by `script/lint`, runs + `golangci-lint run --config .golangci.yml ./...` as a `RUN` instruction in the + digest-pinned `golangci/golangci-lint` image: a successful build of that file + _is_ a clean lint, and it works even where the daemon is remote and bind + mounts are impossible. That `FROM` line is now the only pin of the linter + version in the repo. + + This supersedes the per-worktree cache isolation landed for + [issue #99](https://git.eeqj.de/sneak/vaultik/issues/99). Isolation fixed + cross-worktree contamination but not lock contention — two concurrent runs + with entirely separate cache directories still collided. A container per run + has its own cache and its own lock, so the whole class is gone, and with it + the per-worktree cache machinery, the lock-retry loop, and + `script/lint-audit`, which existed to catch replayed findings from a cache + that no longer exists. The host lint path went too: no escape hatch, no + `VAULTIK_LINT_IN_CONTAINER`, no version detection. Nothing lints on the host + at any version. + + A cached build lints nothing, so the same `CHECK_EPOCH` mechanism the + product `Dockerfile` already used is what makes the green mean something: + `ARG CHECK_EPOCH` with no default below the module layers, a + `RUN [ -n "$CHECK_EPOCH" ] || exit 1` guard, the value expanded into each + check command, and a fresh `$(date +%s%N)$$` per invocation computed as a + bare assignment. `cmd/vaultik/lintdocker_test.go` parses both Dockerfiles + and both scripts and fails if any part of that is dropped, because every way + of losing it is silent. No test asserts that no script runs the host linter: + `script/lint` is the one lint entry point and runs `golangci-lint` only + inside the container, and keeping it that way is a review matter, not + something a test proves. + + The product `Dockerfile` lost its lint stage rather than gaining a second + linter pin: `make lint` is now `docker build`, so the stage would have been + docker-in-docker with no daemon, and calling `golangci-lint` directly there + would have restored the two-pins drift of + [issue #78](https://git.eeqj.de/sneak/vaultik/issues/78). `make fmt-check` + moved beside `make test` in the builder stage, and `script/cibuild` now + builds `Dockerfile.lint` and then `Dockerfile`, each with its own fresh + epoch. Consequence, stated rather than left to be found: `script/docker` + builds the product image only and no longer lints; the gates are + `script/check` and `script/cibuild`. + + `golangci-lint config verify` runs as its own epoch-keyed layer, above the + lint. `golangci-lint run` rejects a config it cannot parse but silently + ignores an unknown top-level _key_: renaming `linters:` to `linterz:` + discarded `default: all` and every threshold and still exited 0 on a tree + the real config fails. `config verify` catches that, and it does so with the + network off at this pin — checked under `docker run --network none`, not + assumed. An earlier revision omitted it on the claim that it fetches its + schema over live HTTPS; that claim was false at v2.12.2. + + `script/lint-fix` is kept, reimplemented as a bind-mounted `docker run` + against the image parsed out of `Dockerfile.lint` — it cannot be a build + step, because fixes have to land in the worktree — and marked in its header + as a developer convenience that no gate reads. + +- 2026-08-09: Finished the `--json` stdout contract and gave `make build` a rule + ([issue #108](https://git.eeqj.de/sneak/vaultik/issues/108), + [issue #110](https://git.eeqj.de/sneak/vaultik/issues/110)). Two unrelated + defects of the same shape — a command reporting something it did not do — + landed together because both are small. + + `CleanupLocalSnapshots` wrote three prose lines to stdout with no `--json` + awareness, covering every branch of the function, so no input avoided them + and `vaultik prune --json | jq` failed even after + [issue #106](https://git.eeqj.de/sneak/vaultik/issues/106) removed the + banner. `-q` never helped either: `printlnStdout` and `stdoutf` write + straight to `Vaultik.Stdout` and never consult `Vaultik.UI`, which is what + `SetQuiet` affects. The issue offered three fixes and asked for a decision. + Taken: thread `*PruneOptions` into the function and gate each write on + `!opts.JSON`, matching `PruneBlobs` (its sibling phase, which already takes + the same struct), `RemoveSnapshot` and `remote info`, so the package has one + pattern rather than two. Rejected: moving the lines to `log.Info`, because + the logger's default level is `slog.LevelWarn`, so that would not relocate + them to stderr — it would delete them from a plain `vaultik prune`, and the + removal of rows from the local index is not something to narrate only under + `--verbose`. Also rejected: putting the stale-record count into + `PruneBlobsResult`, whose every field is blob-scoped and which is produced + by the later phase; a prune document covering both phases is a reasonable + thing to want, but it is a schema design question and not a stream-hygiene + fix. The narration is duplicated as `log.Info` records, which `PruneBlobs` + already does alongside its own prints, so the events survive on stderr for + anyone running `--verbose`. + + `make build` printed "Nothing to be done for 'build'" and exited 0 without + producing a binary: `build` was listed in `.PHONY` with no `build:` rule + anywhere, and declaring a name phony is exactly what converts make's "No + rule to make target" error into a silent success. Fixed with + `build: vaultik`, keeping `vaultik:` as the file rule. The audit the issue + asked for covers all 19 `.PHONY` names; `build` was the only one without a + rule, and `vaultik` is correctly absent from `.PHONY`, being a real file + target. + + Tests, each verified to fail with the fix reverted rather than assumed to: + `CleanupLocalSnapshots` leaves stdout untouched under `--json` in all three + branches (stale records, none, empty index) and still emits every line + without it, so the guard cannot be satisfied by deleting the output; + `prune --json` run end to end through `Entry`, cobra and fx over the + process's real stdout descriptor against a `file://` store, asserting + exactly one JSON document, in both the stale and non-stale branches; and a + parse of the `Makefile` asserting every `.PHONY` name has a rule and that + `build` reaches the rule that produces the binary, which keeps the audit + true for names added later. That last one is a parse rather than an + invocation of `make`, since `make test` is what runs it and shelling back + into `make build` would nest a build inside the test run. The property a + parse cannot establish — that the recipe still fails when the build fails — + was verified by hand against a deliberately broken tree: `make build` exits + 2 and produces nothing. `cmd/vaultik` gains its first test file, so + `make test` now reports 16 packages `ok` where it reported 15. + +- 2026-08-09: Stopped the startup banner from contaminating `--json` documents + ([issue #106](https://git.eeqj.de/sneak/vaultik/issues/106)). `Entry` writes + the banner to stdout before cobra parses anything, and the flag scan that + suppresses it knew `--quiet`, `-q` and `--cron` but not `--json`, so every + `--json` document arrived behind two lines of prose and a blank line, and + `vaultik snapshot list --json | jq` failed. With the logger already on stderr + from [issue #82](https://git.eeqj.de/sneak/vaultik/issues/82), this was the + last writer that could put something on stdout that the caller did not ask + for. The design question the issue raised — extend the raw-argv scan, or move + the banner after parsing — is answered in favour of the scan: the banner is + printed first deliberately, so that it still appears when cobra rejects the + arguments and on `--help`, and after parsing there is no single place that + covers those paths. The stated cost of the scan, that `--json` is a subcommand + flag matched anywhere in the vector, is a cost `--cron` already carries — it + exists only on `snapshot create` — so this adds an instance of an accepted + imprecision rather than a new kind, and the two error directions are not + symmetric: a false positive loses a decorative banner, a false negative + corrupts a document. Regression tests at the CLI layer, where + `internal/vaultik`'s existing guard cannot reach: one runs `Entry` itself over + the process's real stdout descriptor, through cobra and fx to the document, + made hermetic by `file://` storage; a second covers the argument vectors of + all five `--json` commands; a third asserts the banner is still printed + without a suppressing flag, so the first cannot be satisfied by deleting the + banner. Also corrected `AGENTS.md` policy 9, which still keyed the + structured-log format on stdout's TTY-ness after #82 moved that decision to + stderr — a rules file that misdescribes the code misleads exactly the readers + who trust it most. Two smaller findings from the same review: `bytesAttrKey`'s + human-readable byte formatting silently stopped applying under an open group, + because the key reaching the comparison is group-qualified (`transfer.bytes`), + now matched on its final segment and tested both ways; and `listEnv.stderr` in + `snapshot_list_test.go`, assigned but never read since those tests began + capturing the process's stderr, is removed. `Vaultik.Stderr` is kept — nothing + writes to it today, which its comment now says outright. + +- 2026-08-09: Moved the logger to stderr and fixed `TTYHandler`'s discarded + attributes ([issue #82](https://git.eeqj.de/sneak/vaultik/issues/82), + [issue #97](https://git.eeqj.de/sneak/vaultik/issues/97)). Two defects in + `internal/log`, fixed together because both live in the handler construction + path. The first: both handlers were built over `os.Stdout`, and `WARN`/`ERROR` + are never suppressed, so a config file with group- or world-readable + permissions was enough to put a log record inside a `--json` document and + break `jq`. Diagnostics now go to stderr, and the TTY/JSON format choice + follows stderr rather than stdout — testing the wrong stream would colorize + records on a redirected stderr whenever stdout happened to be a terminal. This + is user-visible: `--verbose` and `--debug` output moves to stderr too, which + is documented in `README.md` under "stdout and stderr". It also let the local + workaround in `internal/vaultik/snapshot_list.go` go: `warnWhileListing` had + been hand-rolling structured-log formatting to reach a non-stdout writer, and + the `jsonOutput` parameter threaded through the remote-listing helpers existed + only to choose between the two writers. The collect-then-emit machinery around + `listingWarning` stays, but on its remaining merit — warnings emitted in key + order after `group.Wait()` are deterministic run to run, where emitting from + the fetch workers would order them by network timing. The second defect: + `TTYHandler.WithAttrs` and `WithGroup` discarded their arguments and returned + the receiver while their doc comments claimed otherwise, so `log.With` + attributes vanished on a terminal and appeared correctly in CI — failing + precisely when someone is debugging interactively. Both now return a new + handler (the receiver is never written to, since `slog` permits concurrent + derivation), attributes persist across records, and grouping is implemented as + dotted key prefixes, which is the only honest rendering for a format with + nowhere to nest. New tests cover both, including one that feeds the same + derivation chain to the TTY and JSON handlers and compares the attribute sets, + so the two paths cannot drift apart again. Found and filed while verifying: + the startup banner is written to stdout and `--json` does not suppress it + ([issue #106](https://git.eeqj.de/sneak/vaultik/issues/106)), which is a + separate writer on a separate path and the remaining source of stdout + contamination. + +- 2026-08-09: Made the tagged-release path actually work on Gitea + ([issue #65](https://git.eeqj.de/sneak/vaultik/issues/65)). Three independent + blockers, one of which was the whole release: `.goreleaser.yaml` had no + `gitea_urls:` block, so goreleaser defaulted to the GitHub API and a + `goreleaser release` from this repo would have failed or published where + nobody is looking. It now points at `https://git.eeqj.de/api/v1`. The version + is the second: it was a hardcoded `VERSION := 1.0.0-rc.1` in the `Makefile`, + so every local build claimed to be a release candidate that had never been + tagged and did not exist, while `git tag -l` was empty and `internal/globals` + defaulted to `dev`. Version now comes from git via the new `script/version` — + the exact tag with a leading `v` stripped (so a `make` build and a goreleaser + build of one commit report the same string, and it matches the archive names), + otherwise `dev-<12-char sha>`, with `-dirty` appended in either case when + tracked files are modified. Untracked files are deliberately not counted, + matching `git describe --dirty`. The same honesty was owed by the snapshot + path: `snapshot.version_template` was `{{ incpatch .Version }}-next`, which + manufactures a release number from the last tag and, with no tags at all, from + goreleaser's fabricated `v0.0.0`; it now emits the same `dev-`. The one + non-obvious consequence is that `internal/cli/version.go` gated its "this is a + development build" notice on the version being exactly `dev`, so the moment + untagged builds began carrying a commit sha that notice would have gone silent + and an unreleased binary would have read as a release — the gate is now + `globals.IsDevVersion`, which is a predicate over a string rather than a + comparison against a global precisely so it can be tested, and it is tested at + the boundary (`1.0.0-dev` is a release, `dev-` is not). Release + automation is the third blocker: a tag-triggered + `.gitea/workflows/release.yml` runs the build in CI rather than from a laptop, + with `fetch-depth: 0` because a shallow checkout has no tags and would + silently mislabel the release, and with the `RELEASE_TOKEN` repository secret + passed as `GITEA_TOKEN` (documented in `README.md`; the runner's automatic + token is not used because it is not guaranteed to carry release write scope). + `script/release` unsets any `GITHUB_TOKEN`/`GITLAB_TOKEN` it finds, since + goreleaser chooses its forge from whichever token variable is set and refuses + to run when it sees more than one — a runner-provided token must not get to + decide where these artifacts are published. `make release` and + `make release-snapshot`, the last two Makefile targets that were not shims, + now call `script/release` and `script/release-snapshot`, which resolve + goreleaser exactly the way `script/lint` resolves the linter: a `PATH` binary + is used only at the pinned version, never as a silent fallback. + `script/bootstrap` installs it, from a sha256-verified GitHub release archive + per `REPO_POLICIES.md`, via a separate `script/install-goreleaser` — separate + because `script/bootstrap` hard-fails without a usable Docker daemon by + design, and the release runner needs goreleaser without needing Docker. + Verified by running the thing rather than reading it: `make release-snapshot` + produced four archives and `checksums.txt`, and the linux/amd64 binary from + `dist/` reports `dev-` with the development-build notice. Tag handling + was exercised in a throwaway repository rather than by tagging this one; no + tag was created here, since that is the owner's call. Signing, SBOM, + reproducible builds, completions and a man page are out of scope by the issue. + +- 2026-08-09: Isolated the lint cache per worktree and context-gated the native + lint path (issues #99, #80). One defect seen twice: `script/lint` decided + whether it could skip the pinned image by asking what version was on `PATH` + rather than where it was running, and cache isolation is part of that same + question. The cache was one directory per repo, shared by every worktree on + the host, so two checkouts with identical Go file contents collided and + golangci-lint replayed the stored analysis — paths and all. The loud direction + of that failure (a clean tree failed by a dirty sibling) is the harmless one; + the silent direction, a dirty tree **passed** by a clean sibling, is a sixth + way for a gate here to report a green it did not earn. The cache is now keyed + on a digest of the worktree path, and every run is audited by the new + `script/lint-audit`, which rejects output citing any file that is not in the + tree being linted — a backstop that runs on clean output too, because that is + the case nobody investigates. Caches record the worktree they belong to and + are collected when it disappears, so throwaway worktrees do not accumulate + them; the whole tree lives under `XDG_CACHE_HOME` and is disposable. The + `parallel golangci-lint is running` refusal is now a bounded retry rather than + a verdict: it is not a lint result, and exiting non-zero on it is + indistinguishable to a caller from real findings (#88 showed a private cache + does not remove that contention). The native path now requires + `VAULTIK_LINT_IN_CONTAINER=1`, set only by the `Dockerfile` lint stage, in + addition to matching the pin, so a developer's locally installed 2.12.2 no + longer bypasses the digest pin; `/.dockerenv` was rejected as the signal + because `dockerd` creates it for `docker run` and it is not reliably present + during a BuildKit `docker build`, which is the case the exception exists for. + Version detection uses `golangci-lint version --short` with the old banner + scrape kept only as a fallback. `script/bootstrap` no longer prints + `bootstrap complete` on a machine that cannot run the gate: a missing docker, + or one whose daemon is unreachable, is a hard failure naming exactly what + breaks. Verification was by reproduction rather than inspection — two + concurrent lints from two worktrees of differing cleanliness, a real run made + to report an outside path, a matching linter shimmed onto `PATH`, and a `PATH` + with docker removed — and is recorded on the pull request. +- 2026-08-09: Closed the fifth false-green mechanism (issues #93, #69). + `script/test` omitted `-count=1`, so Go's test result cache could satisfy the + gate outright: a second back-to-back `make test` printed the full set of 14 + `ok` lines, every one marked `(cached)`, having executed no test at all. Since + `ok (cached)` is an `ok` line, the "14 `ok` lines means the suite ran" + signal this repo leans on was forgeable, one level below the Docker layer + cache that #85 addressed. Fixed with `-count=1` unconditionally rather than + only in the container, because the pre-commit hook runs the same script and a + gate honest only in CI is dishonest where people rely on it most; + `test-coverage` got the same flag, and `script/check` inherits it by calling + `script/test`. In the same area, `make test-integration` was deleted rather + than made real: no file in the repo carried a build tag, so + `-tags=integration` selected nothing and the target was an exact duplicate of + `make test`. Tagging a subset was rejected because the entire suite runs in + well under a minute, and a scheme whose failure mode is "some tests silently + stopped running" is a poor trade for those seconds in a repo with this + particular history. The `-timeout` was raised from 30s after measuring rather + than after assuming: the standing claim that cold-cache compilation is charged + against `-timeout` is **false**, disproved by a containerised run that spent + 46s compiling and still reported per-package durations within noise of a warm + host run. `-timeout` reaches the test binary as `-test.timeout` and its clock + starts inside `testing.M.Run`, after the build. The real exposure was margin, + not compilation. The 120s landed on is a **deliberate, documented divergence** + from `REPO_POLICIES.md:192`, which mandates 30s, and from that file's + canonical recipe at `:212-214`; the divergence is recorded in `script/test`'s + comment because `REPO_POLICIES.md` is org-canonical and not editable here, and + issue #101 proposes amending the policy text upstream. Numbers and the full + verification are recorded once, on the pull request, and are deliberately not + restated here. + +- 2026-08-09: Triaged all fifteen stale remote branches (issue #71) and deleted + fourteen of them; the full per-branch disposition with evidence is recorded on + that issue. Method mattered more than the outcome here: a three-dot + `git diff main...branch` diffs from the merge base, so it replays everything + that landed on `main` after the branch diverged and makes any old branch look + like it holds unlanded work. That artifact is what made `golangci-v2.12.2` + appear to carry 126 files of unpushed changes when its tree was byte-identical + to `main`'s. Every containment claim here therefore rests on two-dot tip + diffs, tree-hash equality, `git cherry`, and `git branch -r --merged`. Nine + branches were plain ancestors of `main` with zero `git cherry` `+` commits. + `golangci-v2.12.2` had landed squashed as `cc58583`, whose tree hash equals + the branch tip's exactly; note the hash recorded in the issue had gone stale + because `main` advanced, so the check had to be redone rather than repeated. + `fix/sync-snapshot-cleanup` was redundant, its one line already on `main` in + `syncWithRemote`. `feature/restore-progress-bar` was superseded by + `printRestoreProgress` and the disk-backed blob cache, and had become actively + regressive — it would have deleted `internal/blobgen/compress_test.go`, the + #28 regression test that landed separately. The two branches this issue was + filed for both turned out to be closed questions that `main` had already moved + past by a recorded decision, so neither was landed and no regression test was + owed: `ctime` no longer exists anywhere in the codebase after `1c72a37` + removed the column, the `File.CTime` field and every use (#54/#55), and change + detection compares size, mtime, mode, uid and gid only, exactly as + `ARCHITECTURE.md` documents — so the silently-skipped-file data-loss risk that + made this a 1.0 item does not exist. The SQL allow-list branch would have + reverted `bfd7334`, which replaced that very allow-list with regex + sanitisation on review feedback, and would have broken + `getTableCount("snapshots")` because its allow-list omits that table. + `feature/daemon-mode` is untouched and deferred to #94 pending an owner + decision, so it is the one branch besides `main` still on the remote. The + stale `TODO.md` entry named in the issue needed no fix: `e496aa3` had already + removed it. No product code changed. +- 2026-08-09: Adopted the remaining upstream `CHECK_EPOCH` hardening (issue + #91), closing the gap #85 knowingly left open. Four changes, all four decided + as adopt upstream in `sneak/prompts` #26. (1) Each check stage now asserts + `[ -n "$CHECK_EPOCH" ] || exit 1` before running anything, so a build that + supplies no `--build-arg` fails instead of lying. This is the item that + mattered: an unset `ARG` is an empty string and an empty string is a stable + cache key, so the second and every later bare `docker build .` on an unchanged + tree replayed all three check layers and still exited 0 — and `docker build .` + is the command `REPO_POLICIES.md` names verbatim as a thing that must be + green, so the documented command was precisely the one that lied. Failed steps + are never cached, which is what makes the guard fire on every invocation + rather than once. (2) The epoch is now expanded into each check command rather + than left as a bare declaration, so the cache miss no longer depends on + BuildKit's unreferenced-`ARG` handling staying as it is, and the value appears + in the build log. (3) `script/cibuild` uses `epoch="$(date +%s%N)$$"`, unique + per invocation rather than per second; `%N` alone is insufficient because + busybox drops it silently and exits 0, and `$$` is what makes the guarantee + hold regardless. The bare-assignment form is kept deliberately — inlined in an + argument, a failing substitution does not abort under `set -eu` and would + yield an empty constant epoch, restoring the exact false green being fixed. + (4) `script/docker` passes the same fresh arg, so the two entrypoints cannot + disagree about whether the tree is green; local builds are almost always warm, + which made it the likelier fooling in practice. The `ARG` placement from #85 + is unchanged, below `apk add`, `COPY go.mod go.sum` and `go mod download`, so + dependency layers still cache and the build is not cold. Verified by negative + control rather than inspection — a bare `docker build .` run twice back to + back, plus back-to-back pairs of both scripts and a host-side `make check`; + the measurements are recorded once, in the PR verification comment, rather + than restated here. `.golangci.yml`, the lint-stage `FROM` line and its + digest, `script/lint`, `REPO_POLICIES.md` and `.gitea/workflows/check.yml` are + all untouched. +- 2026-08-09: Stopped `script/cibuild` from reporting a green it did not earn + (issue #85). A bare `docker build .` let Docker serve the check layers from + the layer cache whenever the tree had not changed: the checks never executed + and the build still exited 0. The fix is an `ARG CHECK_EPOCH` declared + immediately above the check `RUN`s in both the lint stage and the builder + stage (`ARG` scope is per-stage, so each declares its own), with + `script/cibuild` assigning `epoch="$(date +%s)"` and passing + `--build-arg CHECK_EPOCH="$epoch"`. The assignment is separate on purpose: + under `set -eu` a command substitution that fails inside an argument does not + abort the script, which would leave an empty constant `CHECK_EPOCH` and + restore the very false green being fixed. Placement is the rest of the point — + the `ARG` sits below the `apk add`, `COPY go.mod go.sum`, and + `go mod download` layers, so only the checks are invalidated and the + dependency layers still cache. The guarantee is conditional on a fresh value + rather than absolute: a bare `docker build .` gets an empty `CHECK_EPOCH` and + can still serve the check layers from cache, which `README.md` and the + `Dockerfile` now say plainly, with issue #91 tracking the upstream hardening + (expanded `ARG` form, unset guard, per-invocation epoch, `script/docker`) that + would close it. Verified by re-running the reproduction plus the + withheld-`--build-arg` counterfactual; the measurements are recorded once, in + the PR #89 verification comment, rather than restated here. `.golangci.yml`, + the lint-stage `FROM` line and its digest, `script/lint`, and + `.gitea/workflows/check.yml` are all untouched. +- 2026-08-09: Corrected the `Vaultik.UI` doc comment (issue #84). It claimed the + cli layer replaces the writer with a discarding one in `--cron` mode; the + actual mechanism is `UI.SetQuiet(true)` in `setupGlobals`, which drops + Begin/Complete/Info/Notice/Detail/ Progress/Banner but still emits Warning and + Error. The `--cron` line in `README.md` said "Silent unless error", which + understated what survives, and now names warnings too. The other `--cron` + comments (`internal/log/log.go`, `internal/cli/snapshot.go`, + `internal/vaultik/snapshot.go`) were audited and already accurate. Comments + and docs only, no behavior change. +- 2026-08-09: Made `snapshot list` list the destination store without the + private key (issue #64). The listing is now the union of the local index and a + single streamed listing of the `metadata/` prefix, with no `age_secret_key` + gate — the manifest is unencrypted, so a host holding only the public key can + enumerate its own backups and a host that lost its local index can still see + them. A remote-only snapshot's hostname and name are deliberately not + recovered (they are not recoverable without the private key, and making them + so would undo the privacy property tracked in issue #81); such rows are + labelled by an abbreviation of their remote key and carry the real timestamp + and compressed size from the manifest, with `` in the two columns + that require the local index. Local-only snapshots are reported as drift, and + the hint now names `vaultik prune`, which exists, instead of + `vaultik snapshot cleanup`, which does not. `reportRemoteDrift` collapsed into + the merged view. Every remote manifest read in the codebase now goes through + `downloadManifestByKey`, so issue #81 has one call site to change. Review + rework: snapshot timestamps now normalize to UTC in `scanSnapshotRows`, the + one place they enter the domain, so the merged TIMESTAMP column cannot show + local time for a locally tracked row and UTC for a remote-only row on a + non-UTC host; `GetIncompleteByHostname` was folded onto that same scanner. + `--json` now reports the unreadable-manifest count and the 1000-row truncation + on stderr instead of returning a silently short document (the document's shape + is unchanged). The two per-snapshot `log.Warn` calls on the listing path now + route through the same JSON-aware writer as the existing workaround, so one + corrupt manifest can no longer put a log line on stdout ahead of the document + and break `| jq` — still a local workaround pending issue #82. Verified with + `script/cibuild` and with an uncached `make check` (`0 issues.`, no cached + test packages), plus end to end against a `file://` destination with no secret + key present. +- 2026-08-09: Closed the gap between `make lint` and CI (issue #78). + `script/lint` now runs the digest-pinned `golangci-lint` image taken from the + `Dockerfile` lint stage, which is the single source of truth for the linter + version; the duplicate pin in the `Makefile` `deps` target and the unpinned + `golangci-lint` install in `script/bootstrap` are gone. A `golangci-lint` on + `PATH` is used only when its version is exactly the pinned one (which is how + the lint stage runs it inside the container); anything else goes through + Docker, and a missing or unreachable Docker daemon is a hard error rather than + a silent fallback. Only the **lint** leg of `make check` became equivalent to + `script/cibuild`; its tests and `gofmt` still run on the host against the host + toolchain, as `README.md` states. An earlier version of this entry claimed + `make check` was "as trustworthy as `script/cibuild`" outright, which + overstated it; corrected under issue #80. +- 2026-08-09: Finished the lint remediation under the canonical `.golangci.yml` + (issue #61, which also unblocks issue #59). The remaining findings were fixed + behavior-preservingly: `wsl_v5` whitespace, `sqlclosecheck`, and `prealloc`. + The `sqlclosecheck` sites now close `sql.Rows` in a deferred closure instead + of via the `CloseRows` helper, which the linter could not see through. Only + the `revive` package-name findings remain suppressed, with per-site `//nolint` + directives; the package-rename question behind them is tracked in issue #76. + Verified with `script/cibuild`, which exits 0 — that is the only trustworthy + gate, because `script/lint` runs whatever `golangci-lint` happens to be on + `PATH` rather than the pinned v2.12.2 that CI and the `Dockerfile` use, so + `make check` can report green on findings CI still fails. That tooling gap is + tracked in issue #78. +- 2026-08-09: The earlier next step "reconcile the uncommitted `ARCHITECTURE.md` + edits on `main`" needed no work: the working tree is clean and + `ARCHITECTURE.md` is committed on `main`. +- 2026-08-07: Updated golangci-lint to v2.12.2 everywhere it is pinned + (`Dockerfile` lint stage, `Makefile` deps target), replaced `.golangci.yml` + with the canonical config (v2 schema, `default: all`), and remediated the bulk + of the lint findings it surfaced (issue #61): behavior-preserving fixes across + every package, 2,990 findings down to 80. `make test` and `make fmt-check` + were green at that point but `make lint` was still red; the commit message + claiming `make check` was green was wrong. +- 2026-08-07: Added the standard `.golangci.yml` and `.editorconfig` (issue + #59); lint findings under the new config are tracked in issue #61. +- 2026-07-07 Adopted scripts-to-rule-them-all: `script/` entrypoints, Makefile + shims, README Entrypoints section +- 2026-07-02: Consolidated CLI verbs, retired overlapping commands; bound the + local index to its backup destination URL. +- 2026-06-28: snapshot rm now removes metadata only and prints the prune + command; restore skips chown when running as non-root. +- 2026-06-26: Snapshot IDs hashed at the storage boundary; snapshot list made + resilient to bad remote entries. +- 2026-06-24: Collapsed snapshot prune into vaultik prune; restore streams blobs + to disk and restores files in blob-locality order; cron output fixes. +- 2026-06-17: Restore overhaul: ReadAt chunk reads from cached blobs, + reference-counted blob sweeper, integration tests; new internal/ui output + layer, banner, and progress lines. +- 2025-12-18: Added ARCHITECTURE.md and godoc coverage for exported API. +- 2025-07-26: End-to-end integration tests; manifest format refactor; renamed + backup to snapshot; afero filesystem abstraction. +- 2025-07-20: Initial design and implementation: cobra + fx CLI skeleton, SQLite + index database, UUID blob storage with streaming chunking. + +# Future Steps + +Work planned after 1.0 is listed in the README [roadmap](../README.md#roadmap). diff --git a/internal/config/config.go b/internal/config/config.go index 01cf8cb..12015f7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -56,7 +56,7 @@ var ( errRecipientNotX25519 = errors.New( "not a valid recipient; only X25519 age1... public keys are supported") errNoSnapshots = errors.New( - "at least one snapshot must be configured (see config.example.yml)") + "at least one snapshot must be configured (see configs/config.example.yml)") errSnapshotNoPaths = errors.New("snapshot must have at least one path") errChunkSizeTooSmall = errors.New("chunk_size must be at least 1MB") errBlobSizeTooSmall = errors.New( diff --git a/internal/config/config_test.go b/internal/config/config_test.go index b1af7cd..8b6f43d 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -90,12 +90,12 @@ func TestConfigLoad(t *testing.T) { } // TestExampleConfigIsScrubbedAndLoads checks that the shipped -// config.example.yml carries only neutral placeholders (no real credentials, -// private addresses, or internal host names) and still parses. +// configs/config.example.yml carries only neutral placeholders (no real +// credentials, private addresses, or internal host names) and still parses. func TestExampleConfigIsScrubbedAndLoads(t *testing.T) { t.Parallel() - examplePath := filepath.Join("..", "..", "config.example.yml") + examplePath := filepath.Join("..", "..", "configs", "config.example.yml") cfg, err := Load(examplePath) if err != nil { @@ -361,7 +361,7 @@ func TestDocumentedSizeDefaults(t *testing.T) { } // TestDocumentedSizeExamples checks the 1MB minimum chunk_size and that -// every size the README, config.example.yml and the config init template +// every size the README, configs/config.example.yml and the config init template // list as an example is accepted. func TestDocumentedSizeExamples(t *testing.T) { t.Parallel() diff --git a/package.json b/package.json new file mode 100644 index 0000000..dc05cde --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "devDependencies": { + "prettier": "3.8.1" + } +} diff --git a/script/bootstrap b/script/bootstrap index c1024a0..db6dd65 100755 --- a/script/bootstrap +++ b/script/bootstrap @@ -3,11 +3,20 @@ # this repo. Idempotent: every install is guarded by a check so already # installed tools are skipped. Base tooling comes from nix, apt, brew, # or apk (detected in that order); assumes NOTHING is present (not git, -# make, or go). +# make, or go). Node is used directly if installed; otherwise it is +# installed at a pinned version via nvm (installing nvm itself first, +# from a hash-verified release archive, never curl | sh). set -eu ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +# Pinned versions, 2026-07-06 +NODE_VERSION="22.17.0" +NVM_VERSION="0.40.3" +# sha256 of https://github.com/nvm-sh/nvm/archive/refs/tags/v0.40.3.tar.gz +NVM_SHA256="5f4d6aaa04a177dc93c985e31dbc411ab6b8c6e1e21d8015dbc1372625fcd1d0" +YARN_VERSION="1.22.22" + PKGMGR="" SUDO="" @@ -48,6 +57,69 @@ missing() { ! command -v "$1" >/dev/null 2>&1 } +# verify_sha256 +verify_sha256() { + if command -v sha256sum >/dev/null 2>&1; then + actual="$(sha256sum "$1" | cut -d' ' -f1)" + else + actual="$(shasum -a 256 "$1" | cut -d' ' -f1)" + fi + if [ "$actual" != "$2" ]; then + echo "bootstrap: sha256 mismatch for $1" >&2 + echo " expected: $2" >&2 + echo " actual: $actual" >&2 + exit 1 + fi +} + +# nvm is a bash script; run a command in a bash with nvm loaded +nvm_sh() { + bash -c ". \"\$HOME/.nvm/nvm.sh\" && $*" +} + +ensure_nvm() { + [ -s "$HOME/.nvm/nvm.sh" ] && return 0 + # nvm prerequisites; nvm itself requires bash + if missing bash; then pkg_install bash bash bash bash; fi + if missing curl; then pkg_install curl curl curl curl; fi + if missing git; then pkg_install git git git git; fi + tmp="$(mktemp -d)" + curl -fsSL -o "$tmp/nvm.tar.gz" \ + "https://github.com/nvm-sh/nvm/archive/refs/tags/v${NVM_VERSION}.tar.gz" + verify_sha256 "$tmp/nvm.tar.gz" "$NVM_SHA256" + mkdir -p "$HOME/.nvm" + tar -xzf "$tmp/nvm.tar.gz" -C "$HOME/.nvm" --strip-components=1 + rm -rf "$tmp" +} + +ensure_node() { + if ! missing node; then return 0; fi + ensure_nvm + nvm_sh "nvm install $NODE_VERSION" +} + +ensure_yarn() { + if ! missing yarn; then return 0; fi + if ! missing corepack; then + corepack enable + corepack prepare "yarn@$YARN_VERSION" --activate + elif [ -s "$HOME/.nvm/nvm.sh" ]; then + nvm_sh "nvm use $NODE_VERSION >/dev/null && corepack enable && \ + corepack prepare yarn@$YARN_VERSION --activate" + else + npm install -g "yarn@$YARN_VERSION" + fi +} + +install_js_deps() { + if missing yarn && [ -s "$HOME/.nvm/nvm.sh" ]; then + nvm_sh "nvm use $NODE_VERSION >/dev/null && cd \"$ROOT\" && \ + yarn install --frozen-lockfile" + else + yarn install --frozen-lockfile + fi +} + # Docker is a hard requirement, not a nice-to-have: script/lint and # script/test build the lint and test phases of the Dockerfile, the only # place the linter and the tests run, and script/check and @@ -103,6 +175,8 @@ main() { # Base tooling (every repo) if missing git; then pkg_install git git git git; fi if missing make; then pkg_install gnumake make make make; fi + # script/install-go, script/install-goreleaser and nvm download with it. + if missing curl; then pkg_install curl curl curl curl; fi # Go toolchain: the host's own, or else the version go.mod names, # hash-verified, in .tool/go. That directory is not on the caller's @@ -131,6 +205,11 @@ main() { go mod download + # prettier, which script/fmt and script/fmt-check run on Markdown. + ensure_node + ensure_yarn + install_js_deps + # Last, so that everything installable is installed before the one # thing this script cannot install decides the outcome. require_docker diff --git a/script/fmt b/script/fmt index f4876e1..1f7ad98 100755 --- a/script/fmt +++ b/script/fmt @@ -4,11 +4,31 @@ set -eu ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +# Must match the pin in script/bootstrap. +NODE_VERSION="22.17.0" + +# script/bootstrap installs node and yarn under nvm and leaves neither +# on the PATH of the shell that called it, so resolve the pinned +# toolchain here the way bootstrap's own install step does. nvm is a +# bash script, hence the subshell. +run_yarn() { + if command -v yarn >/dev/null 2>&1; then + exec yarn "$@" + fi + if [ ! -s "$HOME/.nvm/nvm.sh" ]; then + echo "fmt: no yarn; run script/bootstrap first" >&2 + exit 1 + fi + exec bash -c '. "$HOME/.nvm/nvm.sh" && nvm use "$1" >/dev/null && + shift && exec yarn "$@"' bash "$NODE_VERSION" "$@" +} + main() { cd "$ROOT" # Where script/bootstrap installs Go when the host has none. PATH="$PATH:$ROOT/.tool/go/bin" go fmt ./... + run_yarn run prettier --write '**/*.md' --tab-width 4 --prose-wrap always } main "$@" diff --git a/script/fmt-check b/script/fmt-check index 9a9a333..d0595ba 100755 --- a/script/fmt-check +++ b/script/fmt-check @@ -3,11 +3,30 @@ # writing. It checks every Go file outside .tool, which is more than # script/fmt formats: `go fmt ./...` skips `testdata` directories and # files and directories whose names start with `.` or `_`. Fix a file -# only this reports with `gofmt -w`. +# only this reports with `gofmt -w`. Markdown is checked with prettier. set -eu ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +# Must match the pin in script/bootstrap. +NODE_VERSION="22.17.0" + +# script/bootstrap installs node and yarn under nvm and leaves neither +# on the PATH of the shell that called it, so resolve the pinned +# toolchain here the way bootstrap's own install step does. nvm is a +# bash script, hence the subshell. +run_yarn() { + if command -v yarn >/dev/null 2>&1; then + exec yarn "$@" + fi + if [ ! -s "$HOME/.nvm/nvm.sh" ]; then + echo "fmt-check: no yarn; run script/bootstrap first" >&2 + exit 1 + fi + exec bash -c '. "$HOME/.nvm/nvm.sh" && nvm use "$1" >/dev/null && + shift && exec yarn "$@"' bash "$NODE_VERSION" "$@" +} + main() { cd "$ROOT" # Where script/bootstrap installs Go when the host has none. @@ -23,6 +42,7 @@ main() { echo "$unformatted" >&2 exit 1 fi + run_yarn run prettier --check '**/*.md' --tab-width 4 --prose-wrap always } main "$@" diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 0000000..d846639 --- /dev/null +++ b/yarn.lock @@ -0,0 +1,8 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +prettier@3.8.1: + version "3.8.1" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.8.1.tgz#edf48977cf991558f4fcbd8a3ba6015ba2a3a173" + integrity sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg== From 098ed80990f71119c12309a398d7f2da01c77f7c Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 02:41:30 +0100 Subject: [PATCH 102/121] Keep only open work in docs/TODO.md (closes #440) sneak ruled that TODO is not a history document. docs/TODO.md drops the Completed Steps section and every other record of past work, and keeps the open steps. The Workflow step that moved a finished Next Step into Completed Steps now deletes it. Model: opus-5-5 --- docs/TODO.md | 1208 +------------------------------------------------- 1 file changed, 3 insertions(+), 1205 deletions(-) diff --git a/docs/TODO.md b/docs/TODO.md index fe2b554..6d767c1 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -2,7 +2,7 @@ - branch (from `main`) - do the work in Next Step -- move Next Step to the top of Completed Steps +- delete Next Step from `TODO.md` - move the top item of Future Steps into Next Step - commit (`TODO.md` changes in the same commit as the work) - merge to `main` if the branch is not protected, otherwise open a PR @@ -14,1210 +14,8 @@ pre-1.0 # Next Step -The 1.0 work is complete on `next`: the scope settled on -[issue #125](https://git.eeqj.de/sneak/vaultik/issues/125) has landed, and so -has every fix from the defect hunt before the release candidate -([issue #288](https://git.eeqj.de/sneak/vaultik/issues/288)). What is left is -merging `next` to `main` and tagging the release, both the owner's; a `v*` tag -runs the release build in `.gitea/workflows/release.yml`. - -# Completed Steps - -- 2026-11-10: `script/fmt` and `script/fmt-check` now format and check all - Markdown with `prettier` - ([issue #411](https://git.eeqj.de/sneak/vaultik/issues/411)). The architecture - document and this file moved to `docs/`, and the example config to `configs/`. - -- 2026-11-10: Printed the status and progress lines of `remote info` and - `snapshot verify` through `internal/ui`, with its marker and color, as the - README describes ([issue #410](https://git.eeqj.de/sneak/vaultik/issues/410)). - Their reports stay plain. - -- 2026-11-10: Made `config init` write the `apps` snapshot, which backs up - `/Applications`, only on macOS - ([issue #408](https://git.eeqj.de/sneak/vaultik/issues/408)). On Linux the - first `snapshot create` stopped on the missing directory. - -- 2026-10-15: Stopped `snapshot create --prune` pruning after a backup in which - a volume mounted below a configured path in an earlier snapshot of the same - name was not mounted - ([issue #395](https://git.eeqj.de/sneak/vaultik/issues/395)). Such a prune - could delete every snapshot still holding the volume's files. Each snapshot - now records in the local index the directories it found on a different - filesystem from their parent and found an entry in that the backup does not - exclude. - -- 2026-10-14: Stopped `snapshot create --prune` pruning after a backup that - found nothing in a configured path - ([issue #388](https://git.eeqj.de/sneak/vaultik/issues/388)), as in the mount - point of a volume that is not mounted. Such a prune could delete every - snapshot still holding that path's files. A configured path that is a symlink - whose target is gone, as one into such a volume, now fails the backup, with or - without `--prune`. - -- 2026-10-14: Stopped `snapshot create --prune` pruning after a backup that - skipped files it could not read - ([issue #382](https://git.eeqj.de/sneak/vaultik/issues/382)). Such a prune - could delete the only snapshot still holding those files. - -- 2026-10-14: Made `snapshot create --skip-errors` exit non-zero, instead of 0, - when it skips anything it cannot read - ([issue #310](https://git.eeqj.de/sneak/vaultik/issues/310)). - -- 2026-10-14: Kept the local index when `remote nuke` cannot list or find the - destination store - ([issue #292](https://git.eeqj.de/sneak/vaultik/issues/292)). Nuke had cleared - the local snapshot records anyway; it now fails before removing anything. - -- 2026-10-14: Stopped counting directories and unchanged symlinks as files to - back up ([issue #305](https://git.eeqj.de/sneak/vaultik/issues/305)). - -- 2026-10-14: Refused a backup destination that an unplugged volume left empty, - as the owner ruled - ([issue #239](https://git.eeqj.de/sneak/vaultik/issues/239)). Every backup now - writes `vaultik-destination.txt` at the destination root, and while the local - index holds snapshots stored there, a destination without it is treated as not - present. - -- 2026-10-14: Warned about restored ownership only when an entry's owner or - group differs from the recorded one - ([issue #316](https://git.eeqj.de/sneak/vaultik/issues/316)); a restore by a - non-root user had warned even when none did. - -- 2026-10-14: Made `snapshot list` report a changed destination instead of - advising `prune`, which refuses in that case - ([issue #317](https://git.eeqj.de/sneak/vaultik/issues/317)). - -- 2026-10-14: Counted a file as deleted by a backup only if the previous - snapshot of the same name listed it - ([issue #304](https://git.eeqj.de/sneak/vaultik/issues/304)); files that - snapshot did not list had been counted too. - -- 2026-10-14: Named each prefix once in restore, verify and purge errors, some - of which repeated it - ([issue #327](https://git.eeqj.de/sneak/vaultik/issues/327)). A deep verify - log line that named S3 whatever the destination now names storage. - -- 2026-10-14: Refused credentials in a storage URL's endpoint or rclone remote - name, which were accepted and could then be printed - ([issue #322](https://git.eeqj.de/sneak/vaultik/issues/322)). - -- 2026-10-14: Ran `$EDITOR` through the shell in `config edit`, so a value with - arguments, such as `code --wait`, no longer fails - ([issue #315](https://git.eeqj.de/sneak/vaultik/issues/315)). - -- 2026-10-14: Made `snapshot remove` fail, instead of exiting 0, when it cannot - delete the metadata of a snapshot that is only on the destination store - ([issue #340](https://git.eeqj.de/sneak/vaultik/issues/340)). The README and - the help now say when it prints the `vaultik prune` follow-up. - -- 2026-10-14: Labelled the totals in the local index cleanup before each backup - as totals ([issue #306](https://git.eeqj.de/sneak/vaultik/issues/306)). Each - was shown as `(N remain)`, which read as rows left to clean up. - -- 2026-10-13: Freed a cached blob once no file still to restore needs it - ([issue #324](https://git.eeqj.de/sneak/vaultik/issues/324)); one also used by - a file outside the selected paths had stayed in the temporary cache until the - restore ended. - -- 2026-10-13: Kept the whole startup error when it contains `): ` - ([issue #320](https://git.eeqj.de/sneak/vaultik/issues/320)). Such an error - was cut at its last `): `, so the `blob_size_limit` one lost the setting's - name. - -- 2026-10-13: Silenced the status lines of `prune` and snapshot removal under - `--cron` and `--quiet` - ([issue #294](https://git.eeqj.de/sneak/vaultik/issues/294)). - -- 2026-10-13: Read the rclone config file that `RCLONE_CONFIG` names - ([issue #321](https://git.eeqj.de/sneak/vaultik/issues/321)); a remote defined - only there had been reported as not found. - -- 2026-10-13: Made `/**/` in an exclude pattern match zero directories, as in - gitignore ([issue #338](https://git.eeqj.de/sneak/vaultik/issues/338)); - `a/**/*.log` had missed `a/x.log`. - -- 2026-10-13: Made the `chunk_size` and `blob_size_limit` defaults and the - `chunk_size` minimum 1000-based, like the size parser and the docs - ([issue #313](https://git.eeqj.de/sneak/vaultik/issues/313)). - -- 2026-10-13: Kept a snapshot's remote metadata when `snapshot purge` cannot - remove it from the local index - ([issue #337](https://git.eeqj.de/sneak/vaultik/issues/337)); the purge had - deleted the metadata anyway and exited 0. - -- 2026-10-13: Made `snapshot restore` fail for a requested path that matches - nothing, which it had ignored - ([issue #309](https://git.eeqj.de/sneak/vaultik/issues/309)). - -- 2026-10-13: Made `remote nuke` delete every object under `metadata/` and - `blobs/` ([issue #291](https://git.eeqj.de/sneak/vaultik/issues/291)); it had - left some, such as a stray `.DS_Store`, while reporting the store empty. - -- 2026-10-13: Made `config set` create a list for an index under a missing key - ([issue #308](https://git.eeqj.de/sneak/vaultik/issues/308)); it had written a - map, after which no command could load the config. - -- 2026-10-13: Listed a `file://` destination through a symlinked `metadata/` or - `blobs/`, which had listed as empty - ([issue #296](https://git.eeqj.de/sneak/vaultik/issues/296)). A link to a - missing target now fails the listing - ([issue #332](https://git.eeqj.de/sneak/vaultik/issues/332)). - -- 2026-10-13: Made `snapshot verify --deep --json` report its blob counts - ([issue #314](https://git.eeqj.de/sneak/vaultik/issues/314)); a failed run had - reported 0 missing and 0 verified. - -- 2026-10-13: Limited and retried the module download in the Docker build - ([issue #351](https://git.eeqj.de/sneak/vaultik/issues/351)), which had hung - for as long as a stalled connection to the module proxy lasted. - -- 2026-10-13: Recorded each snapshot's uncompressed size when its backup runs - ([issue #360](https://git.eeqj.de/sneak/vaultik/issues/360)). A later backup - could change an older snapshot's UNCOMPRESSED SIZE in `snapshot list`. - -- 2026-10-13: Stopped `snapshot restore --skip-errors --verify` reporting a file - that failed to restore again as a checksum failure - ([issue #323](https://git.eeqj.de/sneak/vaultik/issues/323)). - -- 2026-10-13: Recorded the stored size of a blob a backup finds already stored, - not the size of its local copy, which can differ, so `snapshot verify` could - fail on a good snapshot - ([issue #300](https://git.eeqj.de/sneak/vaultik/issues/300)). - -- 2026-10-13: Stopped the local index and the blob upload step ending the - process on a failed close of query results or a failed temp file cleanup - ([issue #345](https://git.eeqj.de/sneak/vaultik/issues/345)); both are now - returned as errors. - -- 2026-10-13: Closed the snapshot database's storage reader too when restore or - deep verify is interrupted - ([issue #356](https://git.eeqj.de/sneak/vaultik/issues/356)). - -- 2026-10-13: Made `prune` and `remote nuke` fail when a delete on the backup - destination store fails - ([issue #290](https://git.eeqj.de/sneak/vaultik/issues/290)). - -- 2026-10-13: Made an S3 listing that the server cuts short an error - ([issue #297](https://git.eeqj.de/sneak/vaultik/issues/297)); `prune` had - taken it as complete and could delete blobs still in use. - -- 2026-10-13: Made shallow `snapshot verify` report a blob it could not check - apart from a missing one - ([issue #318](https://git.eeqj.de/sneak/vaultik/issues/318)); any error - checking a blob had counted as missing, its cause dropped. - -- 2026-10-13: Restored the other files when a file's chunk is in no blob under - `--skip-errors` ([issue #326](https://git.eeqj.de/sneak/vaultik/issues/326)); - that file had stopped the restore before anything was restored. - -- 2026-10-13: Recorded each snapshot's new chunk size when its backup runs - ([issue #311](https://git.eeqj.de/sneak/vaultik/issues/311)). `snapshot list` - could show a NEW CHUNK SIZE of 0 B for a snapshot whose change was a modified - file. - -- 2026-10-13: Made a backup interrupted during a local index write exit as - interrupted ([issue #301](https://git.eeqj.de/sneak/vaultik/issues/301)); it - could end with `FATAL: failed to rollback transaction` and exit 1 instead - of 130. - -- 2026-10-13: Printed `snapshot list` and `snapshot purge` sizes like every - other command ([issue #312](https://git.eeqj.de/sneak/vaultik/issues/312)). - They, and the `bytes` value in terminal log lines, were 1024-based but - labelled KB or MB, and now use 1000-based units. - -- 2026-10-13: Closed each blob's storage reader when restore or deep verify is - interrupted, which ends a stalled read unless it is stuck in the kernel - ([issue #325](https://git.eeqj.de/sneak/vaultik/issues/325)). - -- 2026-10-13: Made a mistyped subcommand under `snapshot`, `config`, `remote`, - `database` or `completion` an error - ([issue #319](https://git.eeqj.de/sneak/vaultik/issues/319)); each had printed - its help and exited 0. - -- 2026-10-13: Made an exclude pattern starting with `**/` match directly under - the snapshot path too, as in gitignore - ([issue #303](https://git.eeqj.de/sneak/vaultik/issues/303)). - -- 2026-10-13: Refused a relative `file://` storage URL and decoded its - percent-escapes ([issue #299](https://git.eeqj.de/sneak/vaultik/issues/299)); - a relative path had moved with the working directory. - -- 2026-10-13: Removed the blob temp file when a backup stops part-way - ([issue #302](https://git.eeqj.de/sneak/vaultik/issues/302)); the half-written - blob had stayed in `$TMPDIR`. - -- 2026-10-13: Checked `--keep-newer-than` before a backup starts - ([issue #307](https://git.eeqj.de/sneak/vaultik/issues/307)); an invalid value - had been read only by the prune after the backup, so retention never ran. - -- 2026-10-13: Stopped `remote info` counting a file under `blobs/` that is not a - blob as an orphaned blob - ([issue #295](https://git.eeqj.de/sneak/vaultik/issues/295)). A stray file - such as `.DS_Store` was reported as an orphaned blob and the report advised - running `prune`, which skips such a file and deleted nothing. `remote info` - now takes its blob list from the same listing `prune` uses, in the table and - in `--json`. - -- 2026-10-13: Made `snapshot remove` fail for a snapshot that does not exist - ([issue #293](https://git.eeqj.de/sneak/vaultik/issues/293)). The command - never checked the ID: it reported the snapshot removed from the local database - and from the destination store and exited 0, under `--json`, `--dry-run` and - `--local-only` too. An ID that names no snapshot in the local index or on the - destination store is now an error; with `--local-only`, the snapshot must be - in the local index. The command now reports a removal from either side only - when one happened, and `remote_removed` is true only when metadata was - deleted. - -- 2026-10-12: Bound the local index to the destination an `s3.*` config names - ([issue #298](https://git.eeqj.de/sneak/vaultik/issues/298)). Only - `storage_url` was checked, so after `s3.bucket` or `s3.prefix` changed, the - next backup treated every chunk as already stored, uploaded nothing, and - completed a snapshot that could not be restored. Without `storage_url`, the - local index is now bound to `s3.endpoint`, `s3.bucket` and `s3.prefix`, and a - change is refused as a changed `storage_url` is. - -- 2026-10-12: Rejected a retention duration longer than about 292 years - ([issue #289](https://git.eeqj.de/sneak/vaultik/issues/289)). The number given - to `--older-than` or `--keep-newer-than` was multiplied by the length of its - unit with no limit, so from `293y`, `15251w`, `3559mo` or `106752d`, or a sum - of parts such as `200y200y`, the result wrapped to a negative duration. The - cutoff then lay in the future, every snapshot of the name was deleted, the one - just made included, and the command exited 0. Such a duration is now rejected - as invalid and nothing is deleted. - -- 2026-10-08: Made a backup cancelled under `--skip-errors` stop at once - ([issue #286](https://git.eeqj.de/sneak/vaultik/issues/286)). After Ctrl-C or - SIGTERM, phase 2 treated the cancellation error from each remaining file like - an unreadable file: it opened the file, printed an error line for it, counted - it as failed and went on to the next one. The run now stops at the first file - after the cancellation, and no file is counted as failed because of it. - -- 2026-10-08: Made `remote nuke` delete the `.partial` files that uploads cut - off part-way leave on the destination store - ([issue #281](https://git.eeqj.de/sneak/vaultik/issues/281)). The file and - rclone listings skip such a file, so the command left it in place and still - reported the store empty. It now removes them under `metadata/` and `blobs/` - as its last step. - -- 2026-10-08: Made a local index error while recording a directory or symlink - stop a backup under `--skip-errors` - ([issue #284](https://git.eeqj.de/sneak/vaultik/issues/284)). Phase 2 only - records such an entry in the local index, since it has no data to open or - read, but an error doing so was skipped like an unreadable file. The snapshot - then completed without the entry, and a restore did not recreate it. The error - now stops the backup, as it does without the flag. - -- 2026-10-08: Counted a file that a backup could not store as failed - ([issue #280](https://git.eeqj.de/sneak/vaultik/issues/280)). A file that - phase 1 counted and phase 2 could not open, because it was unreadable under - `--skip-errors` or removed in between, was reported in the summary as - unchanged with its bytes as backed up, and the `snapshots` row's `file_count` - and `total_size` included it. The summary now counts it as failed, and its - data total and the row leave it out. - -- 2026-10-08: Made `remote info` report a snapshot's blob count and blob size as - unknown when its manifest cannot be read - ([issue #272](https://git.eeqj.de/sneak/vaultik/issues/272)). The orphan - figures were already unknown in that case, but the snapshot's row still gave 0 - blobs and 0 B, in the table and in `--json`. The row now reads `unknown` and - `--json` gives `null`. A directory with no manifest still shows 0, since the - orphan figures count its blobs as orphaned. - -- 2026-10-08: Kept the progress line of a snapshot with more than one path - within 100% ([issue #271](https://git.eeqj.de/sneak/vaultik/issues/271)). The - bytes and files processed counted every path, but the totals they were divided - by held only the current path's, so a second path smaller than the first - showed more than 100% and an ETA of `unknown`. The totals now add up over the - paths scanned so far. The rate behind the ETA restarts when each path's scan - phase ends, so that phase does not lower the rate while the path is processed; - until then the rate is the previous path's. - -- 2026-10-08: Made a second `snapshot create` of one name succeed when it starts - in the same second as the first - ([issue #270](https://git.eeqj.de/sneak/vaultik/issues/270)). The timestamp in - a snapshot ID is in whole seconds, so the second run got the first run's ID - and failed with `UNIQUE constraint failed: snapshots.id`. When the local index - already has a snapshot with the ID, the create now waits a second and takes a - new timestamp. - -- 2026-10-07: Documented that `--json` skips the confirmation prompt of - `snapshot remove` and `prune` - ([issue #268](https://git.eeqj.de/sneak/vaultik/issues/268)). Both commands - delete without asking under `--json`, since a prompt on stdout would break the - JSON document, but the help and the README described only `--force` as - skipping it. The `--json` help of both commands and their README entries now - say so. - -- 2026-10-07: Made a symlink whose target cannot be read stop the backup - ([issue #269](https://git.eeqj.de/sneak/vaultik/issues/269)). It was left out - of the snapshot with only a debug log line, even without `--skip-errors`. It - now aborts the run, or with `--skip-errors` is skipped with the - `Failed to access` error line that any other entry the scan cannot read gets. - -- 2026-10-07: Stopped a killed rclone upload from leaving a truncated object - under its key ([issue #266](https://git.eeqj.de/sneak/vaultik/issues/266)). - The rclone backend wrote each object straight to its key, so killing an upload - to a local or sftp remote left a truncated object there; the next backup found - the key with `Stat`, skipped the upload and recorded a snapshot that could not - be restored. On a remote with a server-side move, an object is now written - under a temporary name ending in `.partial` and moved into place, and listings - skip such names. Remotes without one are still written in place. - -- 2026-10-07: Made an interrupted command exit 130 and say so - ([issue #267](https://git.eeqj.de/sneak/vaultik/issues/267)). Ctrl-C or - SIGTERM during `snapshot create`, `snapshot restore` or `snapshot verify` - exited 0 with no error line (`snapshot verify --json` exited 1, also without - one), so a `--cron` run that never finished looked like a success. A command - stopped by either signal now exits 130 and prints - `interrupted before the command finished` on stderr, under `--cron` and - `--json` too. - -- 2026-10-07: Corrected documentation, help text and comments that were false - about the code ([issue #233](https://git.eeqj.de/sneak/vaultik/issues/233)). A - blob is not streamed to storage. The README, `ARCHITECTURE.md` and - `config.example.yml` now say a backup needs free temporary space, because each - blob is written whole to a temporary file before it is uploaded (up to about - `blob_size_limit`; an rclone destination that cannot stream uploads needs - about twice that) and the metadata export writes copies of the local index. - Temporary files go to `$TMPDIR` (default `/tmp`); with `TMPDIR` unset, SQLite - writes one of those copies to `/var/tmp`. Also corrected: the snapshot ID - format, what restore reads and how incomplete snapshots are removed in - `docs/DATAMODEL.md`, what `source_path` holds, the `index_path` and config - file defaults, what `snapshot remove` cleans up, how the release gets its Go - toolchain, and the `script/release` and `script/fmt-check` comments. - -- 2026-10-07: Cut the time the `internal/vaultik` and `internal/database` tests - take ([issue #235](https://git.eeqj.de/sneak/vaultik/issues/235)). Most of the - `internal/vaultik` time went to 24 tests that ran one at a time only because - they call `log.Initialize`; they now call it before `t.Parallel()`, as the - package's other tests do. `TestLargeDatasets` committed each of its 1,500 - inserts on its own and now makes them in one transaction. - `TestDedupOnlySnapshotRestores` gives its second backup its own snapshot name - instead of sleeping past the one-second timestamp in the snapshot ID. - -- 2026-10-07: Made two messages say only what is true - ([issue #240](https://git.eeqj.de/sneak/vaultik/issues/240)). A config file - that others can read was warned about as containing S3 credentials even when - it set none, as a `file://` config does. The warning now says the file may - contain S3 credentials only when `s3.access_key_id` or `s3.secret_access_key` - is set, since either may come from a `${...}` reference rather than the file, - and otherwise says the file is readable by others. `snapshot purge` against a - destination store it could not list gave an error with - `listing remote snapshots:` in it twice; the prefix now appears once. - -- 2026-10-07: Made `s3.part_size` set the multipart upload part size - ([issue #232](https://git.eeqj.de/sneak/vaultik/issues/232)). It was loaded - and defaulted but never passed to the S3 client, whose uploader used a fixed - 10MiB part. It now reaches the uploader for `storage_url` and for the `s3.*` - fields, and a part size S3 refuses, below 5MiB or above 5GiB, `0` included, - fails at config load. A blob too large for S3's limit of 10,000 parts at the - configured size is uploaded in larger parts. The docs gave the default as - `5MB`, which the config file reads as 5,000,000 bytes, below the minimum; they - now say `5MiB`. - -- 2026-10-07: Made per-name retention work when the hostname contains `_` - ([issue #230](https://git.eeqj.de/sneak/vaultik/issues/230)). A snapshot ID is - `hostname_name_timestamp`, and the name was read as everything between the - first and the last `_`, so with `hostname: my_host` the name `home` came out - as `host_home`. `snapshot purge --keep-latest --snapshot home` then printed - "No snapshots to delete", and `snapshot create --prune` purged nothing without - a message. The name is now read using the hostname the `snapshots` table - stores with each snapshot, cut at its first `.` as it is in the ID. - -- 2026-10-07: Made `remote info` stop reporting a snapshot's blobs as orphaned - when its manifest cannot be read, and stop printing raw names from under - `metadata/` ([issue #228](https://git.eeqj.de/sneak/vaultik/issues/228)). A - manifest it failed to read was skipped, so that snapshot's blobs were counted - as orphaned and the report advised running `vaultik prune`. The orphan figures - are now unknown in that case, with no prune advice, and `--json` gives them as - `null` with the unreadable remote keys in `unreadable_manifests`. A name under - `metadata/` that is not 64 lowercase hex characters is now skipped with a - warning instead of being printed, control characters included. A manifest - under a skipped name is then not read either, so it also leaves the orphan - figures unknown, and `--json` counts such manifests in - `skipped_manifest_count`. A directory with no manifest in it, as left by an - interrupted backup, leaves the figures known. - -- 2026-10-07: Made `config set` keep a string that looks like a number - ([issue #229](https://git.eeqj.de/sneak/vaultik/issues/229)). It wrote every - value unquoted, and `config.Load` reads the file through untyped YAML, so an - access key `00112233` loaded as `38043` and a hostname `007` as `7`. A value - for a string setting in `config.Config` is now tagged as a YAML string, which - the file quotes wherever YAML would read a number or a boolean; other settings - are still written unquoted. - -- 2026-10-07: Made a backup notice a file rewritten with its size unchanged and - a new mtime in the same second as the one in the index - ([issue #226](https://git.eeqj.de/sneak/vaultik/issues/226)). The `files` - table held mtime in whole seconds and the scanner compared whole seconds, so - every later snapshot kept the old content. A new `mtime_nsec` column holds the - nanoseconds within the second that `mtime` holds, and the scanner compares the - full mtime. A local index created before the change lacks the column and is - rebuilt with `vaultik database delete` and a full backup. - -- 2026-10-07: Made taking the process-wide lock atomic - ([issue #227](https://git.eeqj.de/sneak/vaultik/issues/227)). The lock read - `vaultik.pid`, checked whether that PID was alive and then wrote its own, so - two writers started together could both pass the check and both run. It is now - an `flock` on `vaultik.pid`, held until the run ends; the kernel drops it when - the process exits, so a crash leaves no lock behind. A clean exit now empties - the file instead of deleting it, because deleting it would let two later runs - each lock a different file. - -- 2026-10-06: Made `snapshot remove --json` write only its document to stdout - when the destination store cannot be reached - ([issue #251](https://git.eeqj.de/sneak/vaultik/issues/251)). Its warning that - the snapshot's metadata was left on the destination store went to stdout ahead - of the document, breaking `| jq` on a command that exited 0. Under `--json` - the warning now reaches stderr only, through the logger. The warning, the - README and the command's help said `vaultik prune` would finish the cleanup, - but `prune` never removes snapshot metadata; they now say to run - `vaultik snapshot remove` for the snapshot again once the destination store is - reachable. - -- 2026-10-06: Made the backup summary and the `snapshots` row count each file, - byte and upload once - ([issue #225](https://git.eeqj.de/sneak/vaultik/issues/225)). The scanner - added a file's bytes again for each new chunk and counted a file as unchanged - for each chunk already stored, so a first backup reported twice its size and - "backed up" could go negative. Upload figures came from the progress reporter, - which `--cron` turns off, and `blob_count` counted earlier paths' blobs again - for each later path. The scanner now counts uploads itself; `blob_size`, - `blob_uncompressed_size` and `compression_ratio` describe the blobs the - snapshot references, and `docs/DATAMODEL.md` now says `chunk_count` and - `blob_count` count what the run added. - -- 2026-10-06: Made command output follow the README's stdout and stderr rules - ([issue #224](https://git.eeqj.de/sneak/vaultik/issues/224)). The startup - banner went to stdout, so a `completion` script or a `config get` value - started with it; the banner now goes to stderr. A failing `remote info`, - `prune` or `snapshot remove` under `--json` printed nothing on either stream, - and now reports its error on stderr. `snapshot verify --quiet` printed its - whole report; it now prints none, and a failure still reaches stderr with the - same exit status. - -- 2026-10-06: Made a backup without `--cron` of a snapshot with two or more - `paths` complete instead of panicking with `close of closed channel` - ([issue #253](https://git.eeqj.de/sneak/vaultik/issues/253)). `Scan` runs once - per path and started and stopped the progress reporter each time, and a second - stop panics. The reporter is now started and stopped once per snapshot, around - the scans of all its paths. - -- 2026-10-06: Made a restore path argument select only that path and what is - beneath it ([issue #223](https://git.eeqj.de/sneak/vaultik/issues/223)). The - lookup matched with SQL `LIKE`, so `/home/u/doc` also restored `doc2`, `DOC` - and `doc.txt.bak`, and a `_` or `%` in the path acted as a wildcard. A backup - used the same lookup to load the known files of each configured path, so files - of a longer sibling path were counted as deleted. - `FileRepository.ListUnderPath`, which replaces `ListByPrefix`, returns the - file at the path and every file whose path starts with the path plus `/`, - compared case-sensitively. - -- 2026-10-06: Made restore return an error instead of panicking on a malformed - snapshot database - ([issue #231](https://git.eeqj.de/sneak/vaultik/issues/231)). A chunk hash - shorter than 16 characters crashed the error message naming it, and `--verify` - dereferenced a missing `chunks` row and allocated whatever chunk size the - database gave. Those messages now go through `shortHash`, a missing row is an - error, and `--verify` rejects a negative size and hashes each chunk as a - stream. - -- 2026-10-06: Made `s3://bucket/prefix` and `s3://bucket/prefix/` the same - destination ([issue #222](https://git.eeqj.de/sneak/vaultik/issues/222)). The - S3 client put the prefix directly in front of each key, so a prefix without a - trailing slash stored `prefixblobs/...`. A non-empty prefix is now joined to - every key with one `/`, giving the README's `//blobs/...` - layout. The `s3.prefix` config setting goes through the same client and gets - the same join. - -- 2026-10-06: Made restore apply owners, modes and times in an order that keeps - them ([issue #219](https://git.eeqj.de/sneak/vaultik/issues/219)). A directory - got its stored mode and mtime before its contents were written, so a read-only - directory came back without its files and a non-empty one carried the time of - the restore. Directories are now created owner-only and get their stored - owner, mode and mtime once the restore loop is done, each before its parent. A - file's mode is applied after its chown, which on Linux clears setuid and - setgid, and a symlink gets its stored owner (as root) and mtime on the link - itself. - -- 2026-10-06: Made `go.mod` what `go mod tidy` writes, so the pre-commit hook no - longer stops every commit - ([issue #246](https://git.eeqj.de/sneak/vaultik/issues/246)). A test in - `internal/cli` imports `github.com/spf13/pflag` directly, but `go.mod` still - marked it `// indirect`, and `script/precommit` fails whenever the tidy - changes `go.mod`. It is now in the direct `require` block. - -- 2026-10-06: Made the README's steps for restoring on another machine work - ([issue #221](https://git.eeqj.de/sneak/vaultik/issues/221)). `config init` - wrote a placeholder recipient that `config.Load` rejects, so every command on - the new machine failed before reaching the store. The file now has an empty - `age_recipients` list, `config.Load` accepts an empty list, and - `snapshot create` refuses to run without a recipient. - -- 2026-10-06: Made `snapshot restore --skip-errors` skip the files that need a - blob it cannot download - ([issue #218](https://git.eeqj.de/sneak/vaultik/issues/218)). A missing or - damaged blob ended the restore even with the flag, after restoring whichever - files happened to come first. Every file that needs such a blob is now - reported as failed, the rest are restored, and the command still exits - non-zero. Without the flag the blob error still aborts. - -- 2026-10-06: Re-vendored the canonical files from `sneak/prompts` at `dd4027b` - ([issue #213](https://git.eeqj.de/sneak/vaultik/issues/213)). Linting and - testing are now the `lint` and `test` phases of the `Dockerfile`, and the - build stage depends on both. `Dockerfile.lint`, `CHECK_EPOCH` and the tests - that checked them are gone; every `docker build` in `script/` passes - `--no-cache` instead. golangci-lint is v2.14.0, with its new findings fixed in - the code, and the rules in `CLAUDE.md` now live in `AGENTS.md`. - -- 2026-10-06: Made the local index actually run in WAL mode with a busy timeout - ([issue #217](https://git.eeqj.de/sneak/vaultik/issues/217)). The connection - settings were written in a form the SQLite driver ignores, so the index ran - without either and `snapshot list` or `info` during a backup could make the - backup's next write fail with `database is locked`. They are now `_pragma=` - parameters, and the metadata export copies the open index with `VACUUM INTO`, - because a copy of the file alone misses rows still in the `-wal` file. - -- 2026-10-06: Made a backup record the real uid and gid of files, directories - and symlinks ([issue #216](https://git.eeqj.de/sneak/vaultik/issues/216)). The - scanner asked the stat result for `Uid()` and `Gid()` methods, which - `*syscall.Stat_t` does not have, so every entry was stored as `0:0` and a - restore as root gave every file to root. It now reads the `Uid` and `Gid` - fields of `*syscall.Stat_t`. - -- 2026-10-06: Made a `file://` destination whose directory is missing count as - one that cannot be listed - ([issue #220](https://git.eeqj.de/sneak/vaultik/issues/220)). The file backend - listed a missing directory as an empty store, so with the quickstart's USB - stick unplugged `snapshot list` reported every local snapshot as missing from - the store, `snapshot remove` claimed to have removed metadata it never - reached, and `prune` dropped every local snapshot record. Listing a missing - destination directory is now an error; a first backup still creates the - directory. - -- 2026-10-06: Made `--older-than` and `--keep-newer-than` reject a duration with - characters outside its number-and-unit parts - ([issue #215](https://git.eeqj.de/sneak/vaultik/issues/215)). The parser - picked out the parts it recognised and skipped the rest, so `1.0y` became zero - and `--prune --keep-newer-than 1.0y` deleted every snapshot of the backed-up - names, the new one included. `1.0y`, `1,5y`, `30 days`, `x7d` and a bare `0` - are now errors; decimals still work in Go units such as `1.5h`. - -- 2026-10-06: Made a backup re-chunk a known file that lists a chunk no uploaded - blob holds ([issue #214](https://git.eeqj.de/sneak/vaultik/issues/214)). File - rows are shared by every snapshot and updated in place, so removing or pruning - the only snapshot that referenced a changed file's current blob left an older - snapshot keeping a row that matched the disk while no blob held its chunks. - The next backup skipped the file and completed a snapshot that could not - restore it. - -- 2026-09-22: Routed the last direct-to-stdout command output through - `internal/ui` ([issue #149](https://git.eeqj.de/sneak/vaultik/issues/149)). - The `version`, `info`, `remote info`, `config`, and `database delete` commands - wrote plain text straight to stdout, so they were unstyled and ignored - `--quiet`. Output now falls in two buckets, both governed by `internal/ui`: - status lines and confirmations go through its message methods (styled, and - `--quiet` silences them), while the data a command exists to produce — the - reports, the `snapshot list` table, `config get` values, and the `--json` - documents — is written plain. `--quiet` silences the human reports and tables - but never the `config get` value or the `--json` documents, which a script - depends on, and the `database delete` confirmation prompt is always shown. The - README output-style section now states this rule. - -- 2026-09-22: Validated blob hashes, offsets and lengths read back from the - destination before using them - ([issue #155](https://git.eeqj.de/sneak/vaultik/issues/155)). A blob hash - taken from the downloaded database or the store listing was trusted unchecked, - so a hostile remote could drive a decrypted blob to be written outside the - cache directory (a hash like `aa/../../etc`) or crash a command with a short - or negative value. `blobDiskCache.path` now refuses any key containing a path - separator, and `ReadAt` rejects a negative offset or length and bounds with - `length > size-offset` so a sum cannot overflow past the check. A new - `isBlobHash` helper (a plain function, not a method — the packer stores - `temp-placeholder-{uuid}` as a hash) gates `FetchBlob`, shallow and deep - verify; the `blobs/` and `metadata/` listings skip a non-conforming name with - a warning; and short-hash prefixes in log and error text go through a - `shortHash` helper that cannot panic. `verify`'s chunk reader also rejects a - negative `blob_chunks` length and streams the chunk instead of allocating a - database-supplied size. `restore.go` and `internal/database` were left - untouched to avoid colliding with the in-flight - [issue #156](https://git.eeqj.de/sneak/vaultik/issues/156) work; the - cache-path and `FetchBlob` guards already stop the unsafe write and fetch, so - restore's own `buildBlobIndexes` early check is deferred as fail-fast defense - in depth. - -- 2026-09-21: Stopped an interrupted blob upload from making a later backup - deduplicate against data that was never stored - ([issue #148](https://git.eeqj.de/sneak/vaultik/issues/148)). The packer - commits a blob's `chunks`, `blob_chunks`, and `blobs` rows before the upload - is attempted, so a failed upload left chunk rows behind and the next run - skipped re-uploading them, producing a snapshot that reported success but - could not be restored. A run now deduplicates only against chunks held by a - blob whose `uploaded_ts` is set, and at startup drops any un-uploaded blob - rows (and the chunks they orphan) so the affected data is re-chunked and - re-uploaded. Blobs recorded with no remote backend are marked uploaded so this - invariant holds uniformly. - -- 2026-09-22: Made restore refuse any snapshot path that would write outside the - target directory ([issue #154](https://git.eeqj.de/sneak/vaultik/issues/154)). - `restoreFile` and `verifyRestoredFiles` joined the stored path onto the target - with no containment check, so a `..` segment or an absolute path escaped the - target and a restored symlink could redirect a later child write anywhere on - disk. Every stored path is now rejected unless `filepath.IsLocal` accepts it - with the leading separator removed, and each existing ancestor directory below - the target is `Lstat`ed to refuse descending through a symlink; honest - symlinks pointing outside the tree are still written verbatim. age decryption - proves a snapshot is readable, not honest, and restore usually runs as root. - -- 2026-09-21: Stopped `--json` from silencing stderr diagnostics - ([issue #112](https://git.eeqj.de/sneak/vaultik/issues/112)). `--json` used to - be folded into `Quiet`, which pinned the log level to `WARN`, so - `prune --json` gave a machine consumer no record of the local index rows it - deleted even under `--verbose`. `--json` now quiets only the stdout UI (the - JSON document must stay clean, per - [issue #108](https://git.eeqj.de/sneak/vaultik/issues/108)); the stderr log - level follows `--verbose`/`--debug` again. The coupling was removed the same - way for `snapshot verify`, `snapshot remove`, and `remote info`, which carried - it for the same outdated reason. - -- 2026-09-21: Stopped `prune` from reporting a failed row count as 0 - ([issue #96](https://git.eeqj.de/sneak/vaultik/issues/96)). The seven - `getTableCount` reads in `PruneDatabase` discarded their error, so a query - that could not run became a plausible `0` and the before/after delta computed - from it looked like real work. Each read now logs at warn on failure and - renders as `unknown`, never `0`, so an empty table is distinguishable from one - that could not be queried. The counts have no `--json` representation — under - `--json` the summary is suppressed entirely — so nothing there can show a - false `0`. - -- 2026-09-21: Made the s3 storage backend report a missing object as - `storage.ErrNotFound`, like the `file` and `rclone` backends and as the - `Storer` interface documents. `S3Storer.Get` and `Stat` returned the raw AWS - SDK error, so `errors.Is(err, storage.ErrNotFound)` was false on s3 and - callers branched differently per backend. Added a small `s3.IsNotFound` helper - (reused by `HeadObject`) and a test that a missing key maps to `ErrNotFound` - ([issue #129](https://git.eeqj.de/sneak/vaultik/issues/129)). -- 2026-09-21: Fixed `verify --deep` reporting healthy snapshots as corrupt. Its - final blob-integrity check hashed the encrypted downloaded bytes with a single - SHA256 and compared that to the blob ID, which is the double SHA256 of the - plaintext, so the two could never match. It now hashes the decompressed - plaintext and compares the double SHA256. Added a test that backs up a real - snapshot, deep-verifies it, then flips a byte in one stored blob and confirms - deep verification then fails - ([issue #131](https://git.eeqj.de/sneak/vaultik/issues/131)). - -- 2026-09-21: Made `snapshot create` VACUUM the per-snapshot metadata database - through the `modernc.org/sqlite` driver instead of shelling out to the - external `sqlite` command-line binary (issue #120). A backup no longer needs - that binary on `PATH`, so `make check` passes on a stock `go install` host; - `script/bootstrap` and the `Dockerfile` (both the test-build and the shipped - runtime stage) no longer install it, and a new test asserts the uploaded - database keeps no pages from deleted rows. Dropped the now-false note on the - 2026-08-07 entry below that said bootstrap installs it. -- 2026-09-21: Made `.gitea/workflows/check.yml` run on pushes to `main` and - `next` and on pull requests against either, so unit PRs (whose base is `next`) - and `next` itself get a CI run instead of relying on a local `make check` - ([issue #122](https://git.eeqj.de/sneak/vaultik/issues/122)). - -- 2026-09-21: Hash-verified the Go toolchain in the release workflow - ([issue #105](https://git.eeqj.de/sneak/vaultik/issues/105)). New - `script/install-go` downloads the exact `go.dev` archive for `go.mod`'s `go` - directive and refuses it unless its sha256 matches a value committed in the - script; `.gitea/workflows/release.yml` calls it instead of `actions/setup-go`, - which verified the downloaded toolchain against nothing in the repo. - `GOTOOLCHAIN: local` on the release step keeps that exact compiler from - auto-switching. Bumping Go now touches `go.mod`, the checksum, and the - `Dockerfile` `golang` digest together. - -- 2026-09-21: Collapsed the two duration parsers into one and fixed the - `--older-than` months example - ([issue #123](https://git.eeqj.de/sneak/vaultik/issues/123)). Two functions - named `parseDuration` existed with different grammars; - `snapshot purge --older-than` and `--keep-newer-than` both already went - through the one in `internal/vaultik`, while the richer copy in - `internal/cli/duration.go` was reachable only from its own test. Kept the - live-path parser and deleted the unused one, so no flag's accepted grammar - changes. The trap the issue was filed over: `README.md` documented `6m` as the - months example for `--older-than`, but `m` is minutes, so the documented - command deleted every snapshot older than six minutes on a destructive flag. - Corrected the doc to `6mo` and put both flags' help text on one example list - that states `m` is minutes and `mo` is months. The surviving parser now - rejects negatives, which it previously accepted (`-5h`) or silently made - positive (`-5d`). Table-driven tests cover every unit, `6m` as six minutes, - `6mo` as 180 days, and rejection of a bare number, an unknown unit, and a - negative. - -- 2026-08-10: Moved every lint run into its own container, as a build step - ([issue #113](https://git.eeqj.de/sneak/vaultik/issues/113)). New root - `Dockerfile.lint`, built by `script/lint`, runs - `golangci-lint run --config .golangci.yml ./...` as a `RUN` instruction in the - digest-pinned `golangci/golangci-lint` image: a successful build of that file - _is_ a clean lint, and it works even where the daemon is remote and bind - mounts are impossible. That `FROM` line is now the only pin of the linter - version in the repo. - - This supersedes the per-worktree cache isolation landed for - [issue #99](https://git.eeqj.de/sneak/vaultik/issues/99). Isolation fixed - cross-worktree contamination but not lock contention — two concurrent runs - with entirely separate cache directories still collided. A container per run - has its own cache and its own lock, so the whole class is gone, and with it - the per-worktree cache machinery, the lock-retry loop, and - `script/lint-audit`, which existed to catch replayed findings from a cache - that no longer exists. The host lint path went too: no escape hatch, no - `VAULTIK_LINT_IN_CONTAINER`, no version detection. Nothing lints on the host - at any version. - - A cached build lints nothing, so the same `CHECK_EPOCH` mechanism the - product `Dockerfile` already used is what makes the green mean something: - `ARG CHECK_EPOCH` with no default below the module layers, a - `RUN [ -n "$CHECK_EPOCH" ] || exit 1` guard, the value expanded into each - check command, and a fresh `$(date +%s%N)$$` per invocation computed as a - bare assignment. `cmd/vaultik/lintdocker_test.go` parses both Dockerfiles - and both scripts and fails if any part of that is dropped, because every way - of losing it is silent. No test asserts that no script runs the host linter: - `script/lint` is the one lint entry point and runs `golangci-lint` only - inside the container, and keeping it that way is a review matter, not - something a test proves. - - The product `Dockerfile` lost its lint stage rather than gaining a second - linter pin: `make lint` is now `docker build`, so the stage would have been - docker-in-docker with no daemon, and calling `golangci-lint` directly there - would have restored the two-pins drift of - [issue #78](https://git.eeqj.de/sneak/vaultik/issues/78). `make fmt-check` - moved beside `make test` in the builder stage, and `script/cibuild` now - builds `Dockerfile.lint` and then `Dockerfile`, each with its own fresh - epoch. Consequence, stated rather than left to be found: `script/docker` - builds the product image only and no longer lints; the gates are - `script/check` and `script/cibuild`. - - `golangci-lint config verify` runs as its own epoch-keyed layer, above the - lint. `golangci-lint run` rejects a config it cannot parse but silently - ignores an unknown top-level _key_: renaming `linters:` to `linterz:` - discarded `default: all` and every threshold and still exited 0 on a tree - the real config fails. `config verify` catches that, and it does so with the - network off at this pin — checked under `docker run --network none`, not - assumed. An earlier revision omitted it on the claim that it fetches its - schema over live HTTPS; that claim was false at v2.12.2. - - `script/lint-fix` is kept, reimplemented as a bind-mounted `docker run` - against the image parsed out of `Dockerfile.lint` — it cannot be a build - step, because fixes have to land in the worktree — and marked in its header - as a developer convenience that no gate reads. - -- 2026-08-09: Finished the `--json` stdout contract and gave `make build` a rule - ([issue #108](https://git.eeqj.de/sneak/vaultik/issues/108), - [issue #110](https://git.eeqj.de/sneak/vaultik/issues/110)). Two unrelated - defects of the same shape — a command reporting something it did not do — - landed together because both are small. - - `CleanupLocalSnapshots` wrote three prose lines to stdout with no `--json` - awareness, covering every branch of the function, so no input avoided them - and `vaultik prune --json | jq` failed even after - [issue #106](https://git.eeqj.de/sneak/vaultik/issues/106) removed the - banner. `-q` never helped either: `printlnStdout` and `stdoutf` write - straight to `Vaultik.Stdout` and never consult `Vaultik.UI`, which is what - `SetQuiet` affects. The issue offered three fixes and asked for a decision. - Taken: thread `*PruneOptions` into the function and gate each write on - `!opts.JSON`, matching `PruneBlobs` (its sibling phase, which already takes - the same struct), `RemoveSnapshot` and `remote info`, so the package has one - pattern rather than two. Rejected: moving the lines to `log.Info`, because - the logger's default level is `slog.LevelWarn`, so that would not relocate - them to stderr — it would delete them from a plain `vaultik prune`, and the - removal of rows from the local index is not something to narrate only under - `--verbose`. Also rejected: putting the stale-record count into - `PruneBlobsResult`, whose every field is blob-scoped and which is produced - by the later phase; a prune document covering both phases is a reasonable - thing to want, but it is a schema design question and not a stream-hygiene - fix. The narration is duplicated as `log.Info` records, which `PruneBlobs` - already does alongside its own prints, so the events survive on stderr for - anyone running `--verbose`. - - `make build` printed "Nothing to be done for 'build'" and exited 0 without - producing a binary: `build` was listed in `.PHONY` with no `build:` rule - anywhere, and declaring a name phony is exactly what converts make's "No - rule to make target" error into a silent success. Fixed with - `build: vaultik`, keeping `vaultik:` as the file rule. The audit the issue - asked for covers all 19 `.PHONY` names; `build` was the only one without a - rule, and `vaultik` is correctly absent from `.PHONY`, being a real file - target. - - Tests, each verified to fail with the fix reverted rather than assumed to: - `CleanupLocalSnapshots` leaves stdout untouched under `--json` in all three - branches (stale records, none, empty index) and still emits every line - without it, so the guard cannot be satisfied by deleting the output; - `prune --json` run end to end through `Entry`, cobra and fx over the - process's real stdout descriptor against a `file://` store, asserting - exactly one JSON document, in both the stale and non-stale branches; and a - parse of the `Makefile` asserting every `.PHONY` name has a rule and that - `build` reaches the rule that produces the binary, which keeps the audit - true for names added later. That last one is a parse rather than an - invocation of `make`, since `make test` is what runs it and shelling back - into `make build` would nest a build inside the test run. The property a - parse cannot establish — that the recipe still fails when the build fails — - was verified by hand against a deliberately broken tree: `make build` exits - 2 and produces nothing. `cmd/vaultik` gains its first test file, so - `make test` now reports 16 packages `ok` where it reported 15. - -- 2026-08-09: Stopped the startup banner from contaminating `--json` documents - ([issue #106](https://git.eeqj.de/sneak/vaultik/issues/106)). `Entry` writes - the banner to stdout before cobra parses anything, and the flag scan that - suppresses it knew `--quiet`, `-q` and `--cron` but not `--json`, so every - `--json` document arrived behind two lines of prose and a blank line, and - `vaultik snapshot list --json | jq` failed. With the logger already on stderr - from [issue #82](https://git.eeqj.de/sneak/vaultik/issues/82), this was the - last writer that could put something on stdout that the caller did not ask - for. The design question the issue raised — extend the raw-argv scan, or move - the banner after parsing — is answered in favour of the scan: the banner is - printed first deliberately, so that it still appears when cobra rejects the - arguments and on `--help`, and after parsing there is no single place that - covers those paths. The stated cost of the scan, that `--json` is a subcommand - flag matched anywhere in the vector, is a cost `--cron` already carries — it - exists only on `snapshot create` — so this adds an instance of an accepted - imprecision rather than a new kind, and the two error directions are not - symmetric: a false positive loses a decorative banner, a false negative - corrupts a document. Regression tests at the CLI layer, where - `internal/vaultik`'s existing guard cannot reach: one runs `Entry` itself over - the process's real stdout descriptor, through cobra and fx to the document, - made hermetic by `file://` storage; a second covers the argument vectors of - all five `--json` commands; a third asserts the banner is still printed - without a suppressing flag, so the first cannot be satisfied by deleting the - banner. Also corrected `AGENTS.md` policy 9, which still keyed the - structured-log format on stdout's TTY-ness after #82 moved that decision to - stderr — a rules file that misdescribes the code misleads exactly the readers - who trust it most. Two smaller findings from the same review: `bytesAttrKey`'s - human-readable byte formatting silently stopped applying under an open group, - because the key reaching the comparison is group-qualified (`transfer.bytes`), - now matched on its final segment and tested both ways; and `listEnv.stderr` in - `snapshot_list_test.go`, assigned but never read since those tests began - capturing the process's stderr, is removed. `Vaultik.Stderr` is kept — nothing - writes to it today, which its comment now says outright. - -- 2026-08-09: Moved the logger to stderr and fixed `TTYHandler`'s discarded - attributes ([issue #82](https://git.eeqj.de/sneak/vaultik/issues/82), - [issue #97](https://git.eeqj.de/sneak/vaultik/issues/97)). Two defects in - `internal/log`, fixed together because both live in the handler construction - path. The first: both handlers were built over `os.Stdout`, and `WARN`/`ERROR` - are never suppressed, so a config file with group- or world-readable - permissions was enough to put a log record inside a `--json` document and - break `jq`. Diagnostics now go to stderr, and the TTY/JSON format choice - follows stderr rather than stdout — testing the wrong stream would colorize - records on a redirected stderr whenever stdout happened to be a terminal. This - is user-visible: `--verbose` and `--debug` output moves to stderr too, which - is documented in `README.md` under "stdout and stderr". It also let the local - workaround in `internal/vaultik/snapshot_list.go` go: `warnWhileListing` had - been hand-rolling structured-log formatting to reach a non-stdout writer, and - the `jsonOutput` parameter threaded through the remote-listing helpers existed - only to choose between the two writers. The collect-then-emit machinery around - `listingWarning` stays, but on its remaining merit — warnings emitted in key - order after `group.Wait()` are deterministic run to run, where emitting from - the fetch workers would order them by network timing. The second defect: - `TTYHandler.WithAttrs` and `WithGroup` discarded their arguments and returned - the receiver while their doc comments claimed otherwise, so `log.With` - attributes vanished on a terminal and appeared correctly in CI — failing - precisely when someone is debugging interactively. Both now return a new - handler (the receiver is never written to, since `slog` permits concurrent - derivation), attributes persist across records, and grouping is implemented as - dotted key prefixes, which is the only honest rendering for a format with - nowhere to nest. New tests cover both, including one that feeds the same - derivation chain to the TTY and JSON handlers and compares the attribute sets, - so the two paths cannot drift apart again. Found and filed while verifying: - the startup banner is written to stdout and `--json` does not suppress it - ([issue #106](https://git.eeqj.de/sneak/vaultik/issues/106)), which is a - separate writer on a separate path and the remaining source of stdout - contamination. - -- 2026-08-09: Made the tagged-release path actually work on Gitea - ([issue #65](https://git.eeqj.de/sneak/vaultik/issues/65)). Three independent - blockers, one of which was the whole release: `.goreleaser.yaml` had no - `gitea_urls:` block, so goreleaser defaulted to the GitHub API and a - `goreleaser release` from this repo would have failed or published where - nobody is looking. It now points at `https://git.eeqj.de/api/v1`. The version - is the second: it was a hardcoded `VERSION := 1.0.0-rc.1` in the `Makefile`, - so every local build claimed to be a release candidate that had never been - tagged and did not exist, while `git tag -l` was empty and `internal/globals` - defaulted to `dev`. Version now comes from git via the new `script/version` — - the exact tag with a leading `v` stripped (so a `make` build and a goreleaser - build of one commit report the same string, and it matches the archive names), - otherwise `dev-<12-char sha>`, with `-dirty` appended in either case when - tracked files are modified. Untracked files are deliberately not counted, - matching `git describe --dirty`. The same honesty was owed by the snapshot - path: `snapshot.version_template` was `{{ incpatch .Version }}-next`, which - manufactures a release number from the last tag and, with no tags at all, from - goreleaser's fabricated `v0.0.0`; it now emits the same `dev-`. The one - non-obvious consequence is that `internal/cli/version.go` gated its "this is a - development build" notice on the version being exactly `dev`, so the moment - untagged builds began carrying a commit sha that notice would have gone silent - and an unreleased binary would have read as a release — the gate is now - `globals.IsDevVersion`, which is a predicate over a string rather than a - comparison against a global precisely so it can be tested, and it is tested at - the boundary (`1.0.0-dev` is a release, `dev-` is not). Release - automation is the third blocker: a tag-triggered - `.gitea/workflows/release.yml` runs the build in CI rather than from a laptop, - with `fetch-depth: 0` because a shallow checkout has no tags and would - silently mislabel the release, and with the `RELEASE_TOKEN` repository secret - passed as `GITEA_TOKEN` (documented in `README.md`; the runner's automatic - token is not used because it is not guaranteed to carry release write scope). - `script/release` unsets any `GITHUB_TOKEN`/`GITLAB_TOKEN` it finds, since - goreleaser chooses its forge from whichever token variable is set and refuses - to run when it sees more than one — a runner-provided token must not get to - decide where these artifacts are published. `make release` and - `make release-snapshot`, the last two Makefile targets that were not shims, - now call `script/release` and `script/release-snapshot`, which resolve - goreleaser exactly the way `script/lint` resolves the linter: a `PATH` binary - is used only at the pinned version, never as a silent fallback. - `script/bootstrap` installs it, from a sha256-verified GitHub release archive - per `REPO_POLICIES.md`, via a separate `script/install-goreleaser` — separate - because `script/bootstrap` hard-fails without a usable Docker daemon by - design, and the release runner needs goreleaser without needing Docker. - Verified by running the thing rather than reading it: `make release-snapshot` - produced four archives and `checksums.txt`, and the linux/amd64 binary from - `dist/` reports `dev-` with the development-build notice. Tag handling - was exercised in a throwaway repository rather than by tagging this one; no - tag was created here, since that is the owner's call. Signing, SBOM, - reproducible builds, completions and a man page are out of scope by the issue. - -- 2026-08-09: Isolated the lint cache per worktree and context-gated the native - lint path (issues #99, #80). One defect seen twice: `script/lint` decided - whether it could skip the pinned image by asking what version was on `PATH` - rather than where it was running, and cache isolation is part of that same - question. The cache was one directory per repo, shared by every worktree on - the host, so two checkouts with identical Go file contents collided and - golangci-lint replayed the stored analysis — paths and all. The loud direction - of that failure (a clean tree failed by a dirty sibling) is the harmless one; - the silent direction, a dirty tree **passed** by a clean sibling, is a sixth - way for a gate here to report a green it did not earn. The cache is now keyed - on a digest of the worktree path, and every run is audited by the new - `script/lint-audit`, which rejects output citing any file that is not in the - tree being linted — a backstop that runs on clean output too, because that is - the case nobody investigates. Caches record the worktree they belong to and - are collected when it disappears, so throwaway worktrees do not accumulate - them; the whole tree lives under `XDG_CACHE_HOME` and is disposable. The - `parallel golangci-lint is running` refusal is now a bounded retry rather than - a verdict: it is not a lint result, and exiting non-zero on it is - indistinguishable to a caller from real findings (#88 showed a private cache - does not remove that contention). The native path now requires - `VAULTIK_LINT_IN_CONTAINER=1`, set only by the `Dockerfile` lint stage, in - addition to matching the pin, so a developer's locally installed 2.12.2 no - longer bypasses the digest pin; `/.dockerenv` was rejected as the signal - because `dockerd` creates it for `docker run` and it is not reliably present - during a BuildKit `docker build`, which is the case the exception exists for. - Version detection uses `golangci-lint version --short` with the old banner - scrape kept only as a fallback. `script/bootstrap` no longer prints - `bootstrap complete` on a machine that cannot run the gate: a missing docker, - or one whose daemon is unreachable, is a hard failure naming exactly what - breaks. Verification was by reproduction rather than inspection — two - concurrent lints from two worktrees of differing cleanliness, a real run made - to report an outside path, a matching linter shimmed onto `PATH`, and a `PATH` - with docker removed — and is recorded on the pull request. -- 2026-08-09: Closed the fifth false-green mechanism (issues #93, #69). - `script/test` omitted `-count=1`, so Go's test result cache could satisfy the - gate outright: a second back-to-back `make test` printed the full set of 14 - `ok` lines, every one marked `(cached)`, having executed no test at all. Since - `ok (cached)` is an `ok` line, the "14 `ok` lines means the suite ran" - signal this repo leans on was forgeable, one level below the Docker layer - cache that #85 addressed. Fixed with `-count=1` unconditionally rather than - only in the container, because the pre-commit hook runs the same script and a - gate honest only in CI is dishonest where people rely on it most; - `test-coverage` got the same flag, and `script/check` inherits it by calling - `script/test`. In the same area, `make test-integration` was deleted rather - than made real: no file in the repo carried a build tag, so - `-tags=integration` selected nothing and the target was an exact duplicate of - `make test`. Tagging a subset was rejected because the entire suite runs in - well under a minute, and a scheme whose failure mode is "some tests silently - stopped running" is a poor trade for those seconds in a repo with this - particular history. The `-timeout` was raised from 30s after measuring rather - than after assuming: the standing claim that cold-cache compilation is charged - against `-timeout` is **false**, disproved by a containerised run that spent - 46s compiling and still reported per-package durations within noise of a warm - host run. `-timeout` reaches the test binary as `-test.timeout` and its clock - starts inside `testing.M.Run`, after the build. The real exposure was margin, - not compilation. The 120s landed on is a **deliberate, documented divergence** - from `REPO_POLICIES.md:192`, which mandates 30s, and from that file's - canonical recipe at `:212-214`; the divergence is recorded in `script/test`'s - comment because `REPO_POLICIES.md` is org-canonical and not editable here, and - issue #101 proposes amending the policy text upstream. Numbers and the full - verification are recorded once, on the pull request, and are deliberately not - restated here. - -- 2026-08-09: Triaged all fifteen stale remote branches (issue #71) and deleted - fourteen of them; the full per-branch disposition with evidence is recorded on - that issue. Method mattered more than the outcome here: a three-dot - `git diff main...branch` diffs from the merge base, so it replays everything - that landed on `main` after the branch diverged and makes any old branch look - like it holds unlanded work. That artifact is what made `golangci-v2.12.2` - appear to carry 126 files of unpushed changes when its tree was byte-identical - to `main`'s. Every containment claim here therefore rests on two-dot tip - diffs, tree-hash equality, `git cherry`, and `git branch -r --merged`. Nine - branches were plain ancestors of `main` with zero `git cherry` `+` commits. - `golangci-v2.12.2` had landed squashed as `cc58583`, whose tree hash equals - the branch tip's exactly; note the hash recorded in the issue had gone stale - because `main` advanced, so the check had to be redone rather than repeated. - `fix/sync-snapshot-cleanup` was redundant, its one line already on `main` in - `syncWithRemote`. `feature/restore-progress-bar` was superseded by - `printRestoreProgress` and the disk-backed blob cache, and had become actively - regressive — it would have deleted `internal/blobgen/compress_test.go`, the - #28 regression test that landed separately. The two branches this issue was - filed for both turned out to be closed questions that `main` had already moved - past by a recorded decision, so neither was landed and no regression test was - owed: `ctime` no longer exists anywhere in the codebase after `1c72a37` - removed the column, the `File.CTime` field and every use (#54/#55), and change - detection compares size, mtime, mode, uid and gid only, exactly as - `ARCHITECTURE.md` documents — so the silently-skipped-file data-loss risk that - made this a 1.0 item does not exist. The SQL allow-list branch would have - reverted `bfd7334`, which replaced that very allow-list with regex - sanitisation on review feedback, and would have broken - `getTableCount("snapshots")` because its allow-list omits that table. - `feature/daemon-mode` is untouched and deferred to #94 pending an owner - decision, so it is the one branch besides `main` still on the remote. The - stale `TODO.md` entry named in the issue needed no fix: `e496aa3` had already - removed it. No product code changed. -- 2026-08-09: Adopted the remaining upstream `CHECK_EPOCH` hardening (issue - #91), closing the gap #85 knowingly left open. Four changes, all four decided - as adopt upstream in `sneak/prompts` #26. (1) Each check stage now asserts - `[ -n "$CHECK_EPOCH" ] || exit 1` before running anything, so a build that - supplies no `--build-arg` fails instead of lying. This is the item that - mattered: an unset `ARG` is an empty string and an empty string is a stable - cache key, so the second and every later bare `docker build .` on an unchanged - tree replayed all three check layers and still exited 0 — and `docker build .` - is the command `REPO_POLICIES.md` names verbatim as a thing that must be - green, so the documented command was precisely the one that lied. Failed steps - are never cached, which is what makes the guard fire on every invocation - rather than once. (2) The epoch is now expanded into each check command rather - than left as a bare declaration, so the cache miss no longer depends on - BuildKit's unreferenced-`ARG` handling staying as it is, and the value appears - in the build log. (3) `script/cibuild` uses `epoch="$(date +%s%N)$$"`, unique - per invocation rather than per second; `%N` alone is insufficient because - busybox drops it silently and exits 0, and `$$` is what makes the guarantee - hold regardless. The bare-assignment form is kept deliberately — inlined in an - argument, a failing substitution does not abort under `set -eu` and would - yield an empty constant epoch, restoring the exact false green being fixed. - (4) `script/docker` passes the same fresh arg, so the two entrypoints cannot - disagree about whether the tree is green; local builds are almost always warm, - which made it the likelier fooling in practice. The `ARG` placement from #85 - is unchanged, below `apk add`, `COPY go.mod go.sum` and `go mod download`, so - dependency layers still cache and the build is not cold. Verified by negative - control rather than inspection — a bare `docker build .` run twice back to - back, plus back-to-back pairs of both scripts and a host-side `make check`; - the measurements are recorded once, in the PR verification comment, rather - than restated here. `.golangci.yml`, the lint-stage `FROM` line and its - digest, `script/lint`, `REPO_POLICIES.md` and `.gitea/workflows/check.yml` are - all untouched. -- 2026-08-09: Stopped `script/cibuild` from reporting a green it did not earn - (issue #85). A bare `docker build .` let Docker serve the check layers from - the layer cache whenever the tree had not changed: the checks never executed - and the build still exited 0. The fix is an `ARG CHECK_EPOCH` declared - immediately above the check `RUN`s in both the lint stage and the builder - stage (`ARG` scope is per-stage, so each declares its own), with - `script/cibuild` assigning `epoch="$(date +%s)"` and passing - `--build-arg CHECK_EPOCH="$epoch"`. The assignment is separate on purpose: - under `set -eu` a command substitution that fails inside an argument does not - abort the script, which would leave an empty constant `CHECK_EPOCH` and - restore the very false green being fixed. Placement is the rest of the point — - the `ARG` sits below the `apk add`, `COPY go.mod go.sum`, and - `go mod download` layers, so only the checks are invalidated and the - dependency layers still cache. The guarantee is conditional on a fresh value - rather than absolute: a bare `docker build .` gets an empty `CHECK_EPOCH` and - can still serve the check layers from cache, which `README.md` and the - `Dockerfile` now say plainly, with issue #91 tracking the upstream hardening - (expanded `ARG` form, unset guard, per-invocation epoch, `script/docker`) that - would close it. Verified by re-running the reproduction plus the - withheld-`--build-arg` counterfactual; the measurements are recorded once, in - the PR #89 verification comment, rather than restated here. `.golangci.yml`, - the lint-stage `FROM` line and its digest, `script/lint`, and - `.gitea/workflows/check.yml` are all untouched. -- 2026-08-09: Corrected the `Vaultik.UI` doc comment (issue #84). It claimed the - cli layer replaces the writer with a discarding one in `--cron` mode; the - actual mechanism is `UI.SetQuiet(true)` in `setupGlobals`, which drops - Begin/Complete/Info/Notice/Detail/ Progress/Banner but still emits Warning and - Error. The `--cron` line in `README.md` said "Silent unless error", which - understated what survives, and now names warnings too. The other `--cron` - comments (`internal/log/log.go`, `internal/cli/snapshot.go`, - `internal/vaultik/snapshot.go`) were audited and already accurate. Comments - and docs only, no behavior change. -- 2026-08-09: Made `snapshot list` list the destination store without the - private key (issue #64). The listing is now the union of the local index and a - single streamed listing of the `metadata/` prefix, with no `age_secret_key` - gate — the manifest is unencrypted, so a host holding only the public key can - enumerate its own backups and a host that lost its local index can still see - them. A remote-only snapshot's hostname and name are deliberately not - recovered (they are not recoverable without the private key, and making them - so would undo the privacy property tracked in issue #81); such rows are - labelled by an abbreviation of their remote key and carry the real timestamp - and compressed size from the manifest, with `` in the two columns - that require the local index. Local-only snapshots are reported as drift, and - the hint now names `vaultik prune`, which exists, instead of - `vaultik snapshot cleanup`, which does not. `reportRemoteDrift` collapsed into - the merged view. Every remote manifest read in the codebase now goes through - `downloadManifestByKey`, so issue #81 has one call site to change. Review - rework: snapshot timestamps now normalize to UTC in `scanSnapshotRows`, the - one place they enter the domain, so the merged TIMESTAMP column cannot show - local time for a locally tracked row and UTC for a remote-only row on a - non-UTC host; `GetIncompleteByHostname` was folded onto that same scanner. - `--json` now reports the unreadable-manifest count and the 1000-row truncation - on stderr instead of returning a silently short document (the document's shape - is unchanged). The two per-snapshot `log.Warn` calls on the listing path now - route through the same JSON-aware writer as the existing workaround, so one - corrupt manifest can no longer put a log line on stdout ahead of the document - and break `| jq` — still a local workaround pending issue #82. Verified with - `script/cibuild` and with an uncached `make check` (`0 issues.`, no cached - test packages), plus end to end against a `file://` destination with no secret - key present. -- 2026-08-09: Closed the gap between `make lint` and CI (issue #78). - `script/lint` now runs the digest-pinned `golangci-lint` image taken from the - `Dockerfile` lint stage, which is the single source of truth for the linter - version; the duplicate pin in the `Makefile` `deps` target and the unpinned - `golangci-lint` install in `script/bootstrap` are gone. A `golangci-lint` on - `PATH` is used only when its version is exactly the pinned one (which is how - the lint stage runs it inside the container); anything else goes through - Docker, and a missing or unreachable Docker daemon is a hard error rather than - a silent fallback. Only the **lint** leg of `make check` became equivalent to - `script/cibuild`; its tests and `gofmt` still run on the host against the host - toolchain, as `README.md` states. An earlier version of this entry claimed - `make check` was "as trustworthy as `script/cibuild`" outright, which - overstated it; corrected under issue #80. -- 2026-08-09: Finished the lint remediation under the canonical `.golangci.yml` - (issue #61, which also unblocks issue #59). The remaining findings were fixed - behavior-preservingly: `wsl_v5` whitespace, `sqlclosecheck`, and `prealloc`. - The `sqlclosecheck` sites now close `sql.Rows` in a deferred closure instead - of via the `CloseRows` helper, which the linter could not see through. Only - the `revive` package-name findings remain suppressed, with per-site `//nolint` - directives; the package-rename question behind them is tracked in issue #76. - Verified with `script/cibuild`, which exits 0 — that is the only trustworthy - gate, because `script/lint` runs whatever `golangci-lint` happens to be on - `PATH` rather than the pinned v2.12.2 that CI and the `Dockerfile` use, so - `make check` can report green on findings CI still fails. That tooling gap is - tracked in issue #78. -- 2026-08-09: The earlier next step "reconcile the uncommitted `ARCHITECTURE.md` - edits on `main`" needed no work: the working tree is clean and - `ARCHITECTURE.md` is committed on `main`. -- 2026-08-07: Updated golangci-lint to v2.12.2 everywhere it is pinned - (`Dockerfile` lint stage, `Makefile` deps target), replaced `.golangci.yml` - with the canonical config (v2 schema, `default: all`), and remediated the bulk - of the lint findings it surfaced (issue #61): behavior-preserving fixes across - every package, 2,990 findings down to 80. `make test` and `make fmt-check` - were green at that point but `make lint` was still red; the commit message - claiming `make check` was green was wrong. -- 2026-08-07: Added the standard `.golangci.yml` and `.editorconfig` (issue - #59); lint findings under the new config are tracked in issue #61. -- 2026-07-07 Adopted scripts-to-rule-them-all: `script/` entrypoints, Makefile - shims, README Entrypoints section -- 2026-07-02: Consolidated CLI verbs, retired overlapping commands; bound the - local index to its backup destination URL. -- 2026-06-28: snapshot rm now removes metadata only and prints the prune - command; restore skips chown when running as non-root. -- 2026-06-26: Snapshot IDs hashed at the storage boundary; snapshot list made - resilient to bad remote entries. -- 2026-06-24: Collapsed snapshot prune into vaultik prune; restore streams blobs - to disk and restores files in blob-locality order; cron output fixes. -- 2026-06-17: Restore overhaul: ReadAt chunk reads from cached blobs, - reference-counted blob sweeper, integration tests; new internal/ui output - layer, banner, and progress lines. -- 2025-12-18: Added ARCHITECTURE.md and godoc coverage for exported API. -- 2025-07-26: End-to-end integration tests; manifest format refactor; renamed - backup to snapshot; afero filesystem abstraction. -- 2025-07-20: Initial design and implementation: cobra + fx CLI skeleton, SQLite - index database, UUID blob storage with streaming chunking. +Fix the open bugs on the issue tracker that block the release. Merging `next` +into `main` is the owner's. # Future Steps From 88a2aa795355e5ed4455875dd5b0a5e0abd0d933 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 03:25:41 +0100 Subject: [PATCH 103/121] Shorten internal/vaultik tests under the race detector (closes #416) The internal/vaultik tests took 36 to 56 seconds under go test -race and ran past the 90-second timeout when the host was busy. Tests that built the same backup now copy one shared backup, and the interruption tests use smaller sources. No assertion is weakened and no test is removed. Measured back to back on next under the same load, the package takes 55% of its former time. Model: opus-5-5 --- internal/vaultik/missing_destination_test.go | 96 ++++++++++++++++--- internal/vaultik/restore_locality_test.go | 14 +-- .../restore_sweeper_integration_test.go | 18 ++-- internal/vaultik/snapshot_list_test.go | 35 ++++++- 4 files changed, 130 insertions(+), 33 deletions(-) diff --git a/internal/vaultik/missing_destination_test.go b/internal/vaultik/missing_destination_test.go index 1ab5a5c..3f3bfa2 100644 --- a/internal/vaultik/missing_destination_test.go +++ b/internal/vaultik/missing_destination_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "strings" + "sync" "testing" "github.com/spf13/afero" @@ -24,19 +25,28 @@ import ( // that is not plugged in, cannot be listed. It is not an empty store, so // no command may conclude from it that the local snapshots are gone. -// newFileDestinationVaultik returns a Vaultik that backs up the -// snapshot named "first" to a file:// destination at storeDir. +// newFileDestinationVaultik writes the fault source tree and returns a +// Vaultik that backs it up to a file:// destination at storeDir. func newFileDestinationVaultik( ctx context.Context, t *testing.T, storeDir string, ) (*vaultik.Vaultik, *database.Repositories) { t.Helper() - osFs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - dbPath := filepath.Join(tempDir, "index.sqlite") + writeFaultSourceTree(t, afero.NewOsFs(), dataDir) - writeFaultSourceTree(t, osFs, dataDir) + return openFileDestinationVaultik(ctx, t, storeDir, dataDir, + filepath.Join(tempDir, "index.sqlite")) +} + +// openFileDestinationVaultik returns a Vaultik that backs up dataDir to a +// file:// destination at storeDir, with its local index at dbPath. The +// index is closed when the test ends. +func openFileDestinationVaultik( + ctx context.Context, t *testing.T, storeDir, dataDir, dbPath string, +) (*vaultik.Vaultik, *database.Repositories) { + t.Helper() store, err := storage.NewFileStorer(storeDir) require.NoError(t, err) @@ -48,22 +58,84 @@ func newFileDestinationVaultik( repos := database.NewRepositories(db) cfg := changedFileConfig(dataDir, dbPath) - return newBackupVaultik(ctx, cfg, store, repos, db, osFs), repos + return newBackupVaultik(ctx, cfg, store, repos, db, afero.NewOsFs()), repos +} + +// firstBackup is one backup of the snapshot named "first" to a file:// +// destination. dir holds its source tree in src, its store in store and +// its closed local index in index/index.sqlite. The first test that +// needs it makes it, and TestMain removes it. Every test that copies it +// backs up the same source tree, so no test may change that tree. +// +//nolint:gochecknoglobals // made once and shared by the tests that copy it +var firstBackup struct { + once sync.Once + dir string + ready bool +} + +// TestMain removes firstBackup once every test has run. +func TestMain(m *testing.M) { + code := m.Run() + + _ = os.RemoveAll(firstBackup.dir) + + os.Exit(code) +} + +// makeFirstBackup writes the fault source tree and backs it up as the +// snapshot named "first", all in a new directory that it records in +// firstBackup. +func makeFirstBackup(ctx context.Context, t *testing.T) { + t.Helper() + + dir, err := os.MkdirTemp("", "vaultik-first-backup-") + require.NoError(t, err) + + firstBackup.dir = dir + storeDir := filepath.Join(dir, "store") + dataDir := filepath.Join(dir, "src") + indexDir := filepath.Join(dir, "index") + + require.NoError(t, os.Mkdir(storeDir, 0o750)) + require.NoError(t, os.Mkdir(indexDir, 0o750)) + writeFaultSourceTree(t, afero.NewOsFs(), dataDir) + + v, _ := openFileDestinationVaultik(ctx, t, storeDir, dataDir, + filepath.Join(indexDir, "index.sqlite")) + require.NoError(t, backUp(v, "first")) + require.NoError(t, v.DB.Close()) + + firstBackup.ready = true } // backUpToFileDestination creates the directory storeDir, as a user must -// before the first backup, and backs up the snapshot named "first" to a -// file:// destination there. Everything the returned Vaultik prints -// after the backup goes to the returned buffer. +// before the first backup, and returns a Vaultik whose file:// +// destination there holds a backup of the snapshot named "first". The +// store and the local index are copies of firstBackup's, which is faster +// than backing up in every test. The returned Vaultik backs up a source +// tree shared with every other caller, so no test may change that tree. +// Everything the returned Vaultik prints after the backup goes to the +// returned buffer. func backUpToFileDestination( ctx context.Context, t *testing.T, storeDir string, ) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer) { t.Helper() - require.NoError(t, os.MkdirAll(storeDir, 0o750)) + firstBackup.once.Do(func() { makeFirstBackup(ctx, t) }) + require.True(t, firstBackup.ready, "another test failed to make firstBackup") - v, repos := newFileDestinationVaultik(ctx, t, storeDir) - require.NoError(t, backUp(v, "first")) + require.NoError(t, os.MkdirAll(storeDir, 0o750)) + require.NoError(t, os.CopyFS(storeDir, + os.DirFS(filepath.Join(firstBackup.dir, "store")))) + + indexDir := t.TempDir() + require.NoError(t, os.CopyFS(indexDir, + os.DirFS(filepath.Join(firstBackup.dir, "index")))) + + v, repos := openFileDestinationVaultik(ctx, t, storeDir, + filepath.Join(firstBackup.dir, "src"), + filepath.Join(indexDir, "index.sqlite")) out := &bytes.Buffer{} v.Stdout = out diff --git a/internal/vaultik/restore_locality_test.go b/internal/vaultik/restore_locality_test.go index 19e03e6..e57778e 100644 --- a/internal/vaultik/restore_locality_test.go +++ b/internal/vaultik/restore_locality_test.go @@ -46,11 +46,11 @@ import ( // slice out a few KB — currently the dominant cost in restore. // // The test deliberately constructs an adversarial scenario: three -// blobs A/B/C of ~6 MB each, nine files distributed across them, and -// path-ordered names that interleave the blobs (a1, b1, c1, a2, b2, -// c2, …) so naive path-order processing would touch every blob before -// finishing any of them. -// localitySource is one 1 MiB fixture file used by the locality test. +// blobs A/B/C of five 64 KiB chunks each, nine files distributed across +// them, and path-ordered names that interleave the blobs (a1, b1, c1, +// a2, b2, c2, …) so naive path-order processing would touch every blob +// before finishing any of them. +// localitySource is one 64 KiB fixture file used by the locality test. type localitySource struct { path string data []byte @@ -65,10 +65,10 @@ type localityCopy struct { // localitySourceBytes is the size of each source file of the locality // fixture. -const localitySourceBytes = 1024 * 1024 +const localitySourceBytes = 64 * 1024 // buildLocalityFixture writes the adversarial source layout described -// in TestRestoreLocalityAndReadAt: 15 sources of 1 MiB each (which the +// in TestRestoreLocalityAndReadAt: 15 sources of 64 KiB each (which the // backup packs into 3 blobs of 5 chunks) plus 9 interleaved-name copies // (3 per blob group). func buildLocalityFixture( diff --git a/internal/vaultik/restore_sweeper_integration_test.go b/internal/vaultik/restore_sweeper_integration_test.go index 57b8563..d723bef 100644 --- a/internal/vaultik/restore_sweeper_integration_test.go +++ b/internal/vaultik/restore_sweeper_integration_test.go @@ -27,10 +27,10 @@ import ( // TestRestoreSweeperEvictsBlobs exercises the reference-counted blob // disk cache eviction during restore. // -// The scenario: 30 unique 1 MB random files plus 10 duplicates of those -// (40 files total, 30 MB of unique content) get backed up with a 10 MB -// blob_size_limit. After backup the snapshot's encrypted blobs are -// restored through Vaultik.Restore, and per-key Get counts on the +// The scenario: 30 unique 128 KiB random files plus 10 duplicates of +// those (40 files total, 3.75 MiB of unique content) get backed up with +// a 1 MiB blob_size_limit. After backup the snapshot's encrypted blobs +// are restored through Vaultik.Restore, and per-key Get counts on the // storage layer are recorded. Each blob in the snapshot MUST be // downloaded exactly once — re-downloads would mean the sweeper either // evicted a blob that was still needed (LRU regression) or that the @@ -41,7 +41,7 @@ import ( // original AND every duplicate referencing its chunks have been // restored. // buildSweeperFixture writes the source layout for the sweeper test: 30 -// unique 1 MB random files plus 10 duplicates of a random subset. The +// unique 128 KiB random files plus 10 duplicates of a random subset. The // PRNG seed is fixed so failures are reproducible; the entropy is what // matters here — the FastCDC chunker needs realistic-looking data to // pick chunk boundaries naturally. Returns the expected content by @@ -51,7 +51,7 @@ func buildSweeperFixture( ) map[string][]byte { t.Helper() - const fileSize = 1 * 1024 * 1024 + const fileSize = 128 * 1024 rng := rand.New(rand.NewSource(42)) //nolint:gosec // G404: fixture data only @@ -159,7 +159,7 @@ func runSweeperBackup( require.NoError(t, err) require.Equal(t, uniqueFiles+duplicateFiles, scanResult.FilesScanned) require.Greater(t, scanResult.BlobsCreated, 1, - "30 MB of unique data at 10 MB blob size should yield multiple blobs") + "3.75 MiB of unique data at 1 MiB blob size should yield multiple blobs") require.NoError(t, sm.CompleteSnapshot(ctx, snapshotID)) require.NoError(t, sm.ExportSnapshotMetadata(ctx, dbPath, snapshotID)) @@ -199,8 +199,8 @@ func TestRestoreSweeperEvictsBlobs(t *testing.T) { expected := buildSweeperFixture(t, fs, dataDir, uniqueFiles, duplicateFiles) - chunkSize := int64(64 * 1024) - maxBlobSize := int64(10 * 1024 * 1024) + chunkSize := int64(16 * 1024) + maxBlobSize := int64(1024 * 1024) storer, err := storage.NewFileStorer(storeDir) require.NoError(t, err) diff --git a/internal/vaultik/snapshot_list_test.go b/internal/vaultik/snapshot_list_test.go index 811d545..fa3083e 100644 --- a/internal/vaultik/snapshot_list_test.go +++ b/internal/vaultik/snapshot_list_test.go @@ -187,6 +187,17 @@ func (e *listEnv) addRemoteRawTimestamp( t.Helper() remoteKey := snapshot.RemoteSnapshotKey(snapshotID) + e.putRemoteManifest(t, remoteKey, + encodeRemoteManifest(t, remoteKey, timestamp)) + + return remoteKey +} + +// encodeRemoteManifest returns the encoded manifest of a one-blob +// snapshot whose remote key is remoteKey. +func encodeRemoteManifest(t *testing.T, remoteKey, timestamp string) []byte { + t.Helper() + manifest := &snapshot.Manifest{ // Note: the hashed key, never the human ID. That is precisely // why a remote-only snapshot cannot be named. @@ -202,11 +213,17 @@ func (e *listEnv) addRemoteRawTimestamp( data, err := snapshot.EncodeManifest(manifest, 3) require.NoError(t, err) - err = e.store.Put(context.Background(), + return data +} + +// putRemoteManifest stores an encoded manifest on the destination store +// under remoteKey. +func (e *listEnv) putRemoteManifest(t *testing.T, remoteKey string, data []byte) { + t.Helper() + + err := e.store.Put(context.Background(), "metadata/"+remoteKey+"/manifest.json.zst", bytes.NewReader(data)) require.NoError(t, err) - - return remoteKey } // Fixtures shared across the listing tests. @@ -791,9 +808,17 @@ func TestListSnapshots_JSONReportsTruncation(t *testing.T) { timestamp := time.Date(2026, 3, 2, 11, 22, 33, 0, time.UTC) - // One past the cap, so exactly one snapshot is omitted. + // One past the cap, so exactly one snapshot is omitted. The listing + // names a snapshot by the key its manifest is stored under, never by + // the manifest's own ID. So all of them share one encoded manifest: + // encoding 1001 took seconds. + data := encodeRemoteManifest(t, + snapshot.RemoteSnapshotKey("otherhost_bulk"), + timestamp.Format(time.RFC3339)) + for i := range maxRemoteOnlyRowsForTest + 1 { - env.addRemote(t, fmt.Sprintf("otherhost_bulk_%04d", i), timestamp) + env.putRemoteManifest(t, snapshot.RemoteSnapshotKey( + fmt.Sprintf("otherhost_bulk_%04d", i)), data) } stderr := captureProcessStderr(t, func() { From 0d0c76fa244d02a3e26163b312adcb78eb71545b Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 04:09:45 +0100 Subject: [PATCH 104/121] Exit 1 when a deletion prompt is not confirmed (closes #423) prune, snapshot purge, snapshot remove and database delete exited 0 when their confirmation prompt was declined or left unanswered, so a script could not tell that nothing was deleted. They now end with "deletion not confirmed" and exit 1. The [y/N] prompts accept y or Y; database delete still asks for yes. Model: opus-5-5 --- internal/cli/database.go | 7 +-- internal/cli/database_test.go | 48 +++++++++++++++++++++ internal/vaultik/prune.go | 2 +- internal/vaultik/prune_metadata_dir_test.go | 3 +- internal/vaultik/remove_quiet_test.go | 8 ++-- internal/vaultik/remove_snapshot_test.go | 21 +++++++++ internal/vaultik/snapshot.go | 13 ++---- internal/vaultik/snapshot_list_test.go | 5 ++- internal/vaultik/vaultik.go | 7 +++ 9 files changed, 95 insertions(+), 19 deletions(-) create mode 100644 internal/cli/database_test.go diff --git a/internal/cli/database.go b/internal/cli/database.go index 1ae477b..93b330c 100644 --- a/internal/cli/database.go +++ b/internal/cli/database.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/cobra" "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/vaultik" ) // NewDatabaseCommand creates the database command group @@ -90,12 +91,12 @@ Use --force to skip the confirmation prompt.`, var confirm string - _, err = fmt.Scanln(&confirm) + // A failure to read the answer means no confirmation. + _, err = fmt.Fscanln(cmd.InOrStdin(), &confirm) if err != nil || confirm != "yes" { _, _ = fmt.Fprintln(w, "Aborted.") - //nolint:nilerr // a failed/aborted confirmation is a clean abort - return nil + return vaultik.ErrNotConfirmed } } diff --git a/internal/cli/database_test.go b/internal/cli/database_test.go new file mode 100644 index 0000000..be88674 --- /dev/null +++ b/internal/cli/database_test.go @@ -0,0 +1,48 @@ +package cli //nolint:testpackage // sets the unexported rootFlags directly + +import ( + "bytes" + "errors" + "io" + "os" + "strings" + "testing" + + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestDatabaseDeleteDeclinedIsError checks that answering anything but +// "yes" keeps the database and returns ErrNotConfirmed, so the command +// exits non-zero. +// +//nolint:paralleltest // mutates the process-global rootFlags +func TestDatabaseDeleteDeclinedIsError(t *testing.T) { + dir := t.TempDir() + dbPath, cfgPath := seedDatabaseDeleteConfig(t, dir) + + setRootFlags(t, RootFlags{ConfigPath: cfgPath}) + + var out bytes.Buffer + + cmd := newDatabaseDeleteCommand() + cmd.SetOut(&out) + cmd.SetErr(io.Discard) + cmd.SetIn(strings.NewReader("no\n")) + cmd.SetArgs(nil) + + err := cmd.Execute() + if !errors.Is(err, vaultik.ErrNotConfirmed) { + t.Errorf("declined database delete returned %v, want %v", + err, vaultik.ErrNotConfirmed) + } + + _, err = os.Stat(dbPath) + if err != nil { + t.Errorf("declined database delete removed the file: %v", err) + } + + if !strings.Contains(out.String(), "Aborted.") { + t.Errorf("declined database delete printed %q, want Aborted.", + out.String()) + } +} diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index dcffb0e..25cebb4 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -267,7 +267,7 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { if !v.confirmPrune(opts, len(unreferencedBlobs), totalSize, dirsWithoutManifest) { - return nil + return ErrNotConfirmed } v.deleteUnreferencedBlobs(unreferencedBlobs, allBlobs, result) diff --git a/internal/vaultik/prune_metadata_dir_test.go b/internal/vaultik/prune_metadata_dir_test.go index 3bf5210..d21988d 100644 --- a/internal/vaultik/prune_metadata_dir_test.go +++ b/internal/vaultik/prune_metadata_dir_test.go @@ -176,7 +176,8 @@ func TestPruneDeclinedKeepsMetadataDirWithoutManifest(t *testing.T) { env.v.Stdin = strings.NewReader("n\n") - require.NoError(t, env.v.PruneBlobs(&vaultik.PruneOptions{})) + require.ErrorIs(t, env.v.PruneBlobs(&vaultik.PruneOptions{}), + vaultik.ErrNotConfirmed) assert.True(t, env.store.hasKey(leftDB), "a declined prune must keep the directory") diff --git a/internal/vaultik/remove_quiet_test.go b/internal/vaultik/remove_quiet_test.go index 4116780..adfd465 100644 --- a/internal/vaultik/remove_quiet_test.go +++ b/internal/vaultik/remove_quiet_test.go @@ -54,9 +54,10 @@ func TestPurgeSnapshots_QuietPromptListsSnapshots(t *testing.T) { v.UI.SetQuiet(true) // Stdin is empty, so the prompt reads no answer and cancels. - require.NoError(t, v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, - })) + }) + require.ErrorIs(t, err, vaultik.ErrNotConfirmed) assert.Contains(t, out.String(), snapHomeT0) assert.Contains(t, out.String(), "Delete 1 snapshot(s)? [y/N]") @@ -77,7 +78,8 @@ func TestPruneBlobs_QuietPromptShowsBlobTotal(t *testing.T) { addBlob(t, env.store.testStorer, testBlobHashA) // Stdin is empty, so the prompt reads no answer and cancels. - require.NoError(t, env.v.PruneBlobs(&vaultik.PruneOptions{})) + require.ErrorIs(t, env.v.PruneBlobs(&vaultik.PruneOptions{}), + vaultik.ErrNotConfirmed) assert.Contains(t, env.stdout.String(), "Found 1 unreferenced blob(s) totaling") diff --git a/internal/vaultik/remove_snapshot_test.go b/internal/vaultik/remove_snapshot_test.go index 9d43aec..ea88183 100644 --- a/internal/vaultik/remove_snapshot_test.go +++ b/internal/vaultik/remove_snapshot_test.go @@ -337,6 +337,27 @@ func TestRemoveSnapshot_DefaultRemovesMetadataNotBlobs(t *testing.T) { assert.Contains(t, out, "vaultik prune") } +// TestRemoveSnapshot_DeclinedIsError checks that answering no to the +// prompt keeps the snapshot and returns ErrNotConfirmed, so the command +// exits non-zero. +func TestRemoveSnapshot_DeclinedIsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001") + tv.Stdin.WriteString("n\n") + + _, err := tv.RemoveSnapshot("snapshot-001", &vaultik.RemoveOptions{}) + + require.ErrorIs(t, err, vaultik.ErrNotConfirmed) + assert.True(t, store.hasKey(remoteKeyPath("snapshot-001"))) + assert.Contains(t, tv.Stdout.String(), "Cancelled") +} + func TestRemoveSnapshot_DryRun(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 663656e..2dc25a2 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -881,17 +881,12 @@ func (v *Vaultik) confirmAndExecutePurge( var confirm string + // A failure to read the answer means no confirmation. _, err := v.scanStdin(&confirm) - if err != nil { + if err != nil || strings.ToLower(confirm) != "y" { v.printlnStdout("Cancelled") - return nil //nolint:nilerr // treat EOF or read error as "no" - } - - if strings.ToLower(confirm) != "y" { - v.printlnStdout("Cancelled") - - return nil + return ErrNotConfirmed } } else if !quiet { v.UI.Infof("The following snapshots will be deleted:") @@ -1490,7 +1485,7 @@ func (v *Vaultik) RemoveSnapshot( } if !v.confirmRemoveSnapshot(snapshotID, opts) { - return result, nil + return result, ErrNotConfirmed } // Checked before the local record is deleted: it may be the last diff --git a/internal/vaultik/snapshot_list_test.go b/internal/vaultik/snapshot_list_test.go index fa3083e..0e468a0 100644 --- a/internal/vaultik/snapshot_list_test.go +++ b/internal/vaultik/snapshot_list_test.go @@ -362,8 +362,9 @@ func TestSnapshotListAndPurgePrintSizesLikeRemoteInfo(t *testing.T) { // Without --force and with nothing on stdin the purge lists what it // would delete, reads no confirmation, and deletes nothing. env.stdout.Reset() - require.NoError(t, env.v.PurgeSnapshotsWithOptions( - &vaultik.SnapshotPurgeOptions{OlderThan: "1d"})) + require.ErrorIs(t, env.v.PurgeSnapshotsWithOptions( + &vaultik.SnapshotPurgeOptions{OlderThan: "1d"}), + vaultik.ErrNotConfirmed) assert.Contains(t, findTableRow(t, env.stdout.String(), listLocalID), wantSize, "snapshot purge") } diff --git a/internal/vaultik/vaultik.go b/internal/vaultik/vaultik.go index 3105147..7e85218 100644 --- a/internal/vaultik/vaultik.go +++ b/internal/vaultik/vaultik.go @@ -5,6 +5,7 @@ package vaultik import ( "bytes" "context" + "errors" "fmt" "io" "os" @@ -184,6 +185,12 @@ func (v *Vaultik) printlnStdout(args ...any) { _, _ = fmt.Fprintln(v.Stdout, args...) } +// ErrNotConfirmed is returned when a confirmation prompt gets any answer +// but the one it asks for (`y` or `Y`, or `yes` for `database delete`), or +// stdin ends first. Nothing the prompt asked about is deleted, and the +// command exits non-zero. +var ErrNotConfirmed = errors.New("deletion not confirmed") + // scanStdin reads a line of input from stdin. func (v *Vaultik) scanStdin(a ...any) (int, error) { return fmt.Fscanln(v.Stdin, a...) From 1df1d230941d92f7928f163fac1fc192297e2da8 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 04:40:18 +0100 Subject: [PATCH 105/121] restore and verify report an unknown snapshot ID as not found (closes #426) snapshot restore and snapshot verify given an ID that names no snapshot in the local index or at the destination failed with "object not found" on a hashed metadata path. They now look the ID up the way snapshot remove does and say that no such snapshot exists, before printing anything else. Model: opus-5-5 --- internal/vaultik/restore.go | 22 ++++---- internal/vaultik/snapshot.go | 46 ++++++++--------- internal/vaultik/snapshot_identifier.go | 10 +++- internal/vaultik/unknown_snapshot_test.go | 62 +++++++++++++++++++++++ internal/vaultik/verify.go | 23 ++++----- 5 files changed, 113 insertions(+), 50 deletions(-) create mode 100644 internal/vaultik/unknown_snapshot_test.go diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index f02caeb..86ee32d 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -128,10 +128,15 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error { "paths", opts.Paths, ) + remoteKey, err := v.resolveSnapshotRemoteKey(opts.SnapshotID) + if err != nil { + return err + } + // Step 1: Download and decrypt the snapshot metadata database log.Info("Downloading snapshot metadata...") - tempDB, tempDir, err := v.downloadSnapshotDB(opts.SnapshotID, identities) + tempDB, tempDir, err := v.downloadSnapshotDB(opts.SnapshotID, remoteKey, identities) if err != nil { return fmt.Errorf("downloading snapshot database: %w", err) } @@ -754,19 +759,12 @@ func (v *Vaultik) handleRestoreVerification( return nil } -// downloadSnapshotDB downloads and decrypts the snapshot metadata -// database. The identifier is resolved to the snapshot's remote key: a -// human ID is hashed, and a remote key (or its abbreviation, as printed -// for a remote-only snapshot) is used as-is, so a host with no local -// index can restore the snapshots it can only see on the store. +// downloadSnapshotDB downloads and decrypts the metadata database of the +// snapshot at remoteKey, which resolveSnapshotRemoteKey returned for +// snapshotID. func (v *Vaultik) downloadSnapshotDB( - snapshotID string, identities []age.Identity, + snapshotID, remoteKey string, identities []age.Identity, ) (*database.DB, string, error) { - remoteKey, err := v.resolveSnapshotRemoteKey(snapshotID) - if err != nil { - return nil, "", err - } - // Download encrypted database from storage dbKey := fmt.Sprintf("metadata/%s/db.zst.age", remoteKey) diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 2dc25a2..f11a76d 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -964,25 +964,22 @@ func (v *Vaultik) VerifySnapshotWithOptions( Mode: "shallow", } - v.printVerifyHeader(snapshotID, opts) - - // Resolve the identifier to the snapshot's remote key. A human ID is - // hashed; a remote key (or its abbreviation, as printed for a - // remote-only snapshot) is used as-is, so a host with no local index - // can verify a snapshot it can only see on the store. The key is kept - // so we can also check for the snapshot's encrypted database below. + // The key is kept so we can also check for the snapshot's encrypted + // database below. remoteKey, err := v.resolveSnapshotRemoteKey(snapshotID) if err != nil { if opts.JSON { result.Status = verifyStatusFailed - result.ErrorMessage = fmt.Sprintf("resolving snapshot identifier: %v", err) + result.ErrorMessage = err.Error() return v.outputVerifyJSON(result) } - return fmt.Errorf("resolving snapshot identifier: %w", err) + return err } + v.printVerifyHeader(snapshotID, opts) + manifest, err := v.downloadManifestByKey(remoteKey) if err != nil { if opts.JSON { @@ -1475,7 +1472,7 @@ func (v *Vaultik) RemoveSnapshot( return result, err } - inLocalIndex, err := v.findSnapshotToRemove(snapshotID, opts) + inLocalIndex, err := v.checkSnapshotExists(snapshotID, opts.LocalOnly) if err != nil { return result, err } @@ -1538,17 +1535,20 @@ func (v *Vaultik) RemoveSnapshot( return result, nil } -// findSnapshotToRemove reports whether the local index has a row for -// snapshotID, and returns errSnapshotNotFound when there is nothing to -// remove: no row and, unless LocalOnly is set, no metadata on the -// destination store either. The destination store is consulted only -// when the local index has no row, so a snapshot in the local index can -// still be removed from it while the destination store is unreachable, -// and only after checkDestinationMarker passes, so an unplugged volume's -// empty mount point is not taken for a store without the snapshot. -func (v *Vaultik) findSnapshotToRemove( - snapshotID string, opts *RemoveOptions, -) (bool, error) { +// checkSnapshotExists returns errSnapshotNotFound when the local index +// has no row for snapshotID and, unless localOnly is set, the +// destination store has no metadata for it either. inLocalIndex reports +// whether the local index has that row. The destination store is +// consulted only when the local index has no row, so a snapshot in the +// local index can still be removed from it while the destination store +// is unreachable, and only after checkDestinationMarker passes, so an +// unplugged volume's empty mount point is not taken for a store without +// the snapshot. +// +//nolint:nonamedreturns // the result name says what the bool means +func (v *Vaultik) checkSnapshotExists( + snapshotID string, localOnly bool, +) (inLocalIndex bool, err error) { if v.Repositories != nil { snap, err := v.Repositories.Snapshots.GetByID(v.ctx, snapshotID) if err != nil { @@ -1560,12 +1560,12 @@ func (v *Vaultik) findSnapshotToRemove( } } - if opts.LocalOnly { + if localOnly { return false, fmt.Errorf("%w in the local index: %s", errSnapshotNotFound, snapshotID) } - err := v.checkDestinationMarker() + err = v.checkDestinationMarker() if err != nil { return false, err } diff --git a/internal/vaultik/snapshot_identifier.go b/internal/vaultik/snapshot_identifier.go index a65cf3f..5420168 100644 --- a/internal/vaultik/snapshot_identifier.go +++ b/internal/vaultik/snapshot_identifier.go @@ -28,8 +28,9 @@ var ( // Two forms are accepted, matching the two things a host can know: // // - A human snapshot ID (hostname_name_timestamp), which a host holding -// the local index has. It is hashed to its remote key; the store is -// not consulted. +// the local index has. It is hashed to its remote key. An ID that +// names no snapshot in the local index or on the destination store +// is an error (see checkSnapshotExists). // - A remote key, or the leading part of one, which is all a host with // no local index can know — it is exactly what `snapshot list` prints // for a remote-only snapshot (see formatRemoteOnlyID). It is resolved @@ -41,6 +42,11 @@ var ( // RFC3339 timestamp). func (v *Vaultik) resolveSnapshotRemoteKey(identifier string) (string, error) { if !isRemoteKeyOrPrefix(identifier) { + _, err := v.checkSnapshotExists(identifier, false) + if err != nil { + return "", err + } + return snapshot.RemoteSnapshotKey(identifier), nil } diff --git a/internal/vaultik/unknown_snapshot_test.go b/internal/vaultik/unknown_snapshot_test.go new file mode 100644 index 0000000..33246ef --- /dev/null +++ b/internal/vaultik/unknown_snapshot_test.go @@ -0,0 +1,62 @@ +package vaultik_test + +import ( + "bytes" + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestUnknownSnapshotID checks that restore and verify, given an ID that +// names no snapshot in the local index or on the destination store, say +// so in the words `snapshot remove` uses and print nothing else. +func TestUnknownSnapshotID(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const unknownID = "host1_home_2026-01-01T00:00:00Z" + + commands := map[string]func(v *vaultik.Vaultik) error{ + "restore": func(v *vaultik.Vaultik) error { + return v.Restore(&vaultik.RestoreOptions{ + SnapshotID: unknownID, + TargetDir: t.TempDir(), + }) + }, + "verify": func(v *vaultik.Vaultik) error { + return v.VerifySnapshotWithOptions(unknownID, &vaultik.VerifyOptions{}) + }, + "verify --deep": func(v *vaultik.Vaultik) error { + return v.VerifySnapshotWithOptions(unknownID, + &vaultik.VerifyOptions{Deep: true}) + }, + } + + for name, run := range commands { + t.Run(name, func(t *testing.T) { + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + + tv := vaultik.NewForTesting(store) + tv.Config = &config.Config{AgeSecretKey: testAgeSecretKey} + tv.Repositories = newLocalIndex(t, "snapshot-001") + + err := run(tv.Vaultik) + + require.EqualError(t, err, "snapshot not found in the local "+ + "index or on the destination store: "+unknownID) + assert.Empty(t, tv.Stdout.String()) + }) + } +} diff --git a/internal/vaultik/verify.go b/internal/vaultik/verify.go index ba6c2d3..c8f9ff5 100644 --- a/internal/vaultik/verify.go +++ b/internal/vaultik/verify.go @@ -120,12 +120,17 @@ func (v *Vaultik) RunDeepVerify(snapshotID string, opts *VerifyOptions) error { log.Info("Starting snapshot verification", "snapshot_id", snapshotID, "mode", "deep") + remoteKey, err := v.resolveSnapshotRemoteKey(snapshotID) + if err != nil { + return v.deepVerifyFailure(result, opts, err.Error(), err) + } + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Deep verification of snapshot: %s\n\n", snapshotID) } manifest, tempDB, dbBlobs, err := v.loadVerificationData( - snapshotID, opts, result, identities) + snapshotID, remoteKey, opts, result, identities) if err != nil { return err } @@ -170,21 +175,13 @@ func (v *Vaultik) RunDeepVerify(snapshotID string, opts *VerifyOptions) error { return nil } -// loadVerificationData downloads manifest, database, and blob list for verification +// loadVerificationData downloads manifest, database, and blob list for +// verification of the snapshot at remoteKey, which +// resolveSnapshotRemoteKey returned for snapshotID. func (v *Vaultik) loadVerificationData( - snapshotID string, opts *VerifyOptions, result *VerifyResult, + snapshotID, remoteKey string, opts *VerifyOptions, result *VerifyResult, identities []age.Identity, ) (*snapshot.Manifest, *tempDB, []snapshot.BlobInfo, error) { - // Resolve the identifier to the snapshot's remote key. A human ID is - // hashed; a remote key (or its abbreviation, as printed for a - // remote-only snapshot) is used as-is, so a host with no local index - // can verify a snapshot it can only see on the store. - remoteKey, err := v.resolveSnapshotRemoteKey(snapshotID) - if err != nil { - return nil, nil, nil, v.deepVerifyFailure(result, opts, - fmt.Sprintf("resolving snapshot identifier: %v", err), err) - } - // Download manifest. downloadManifestByKey is the single reader for // remote manifests; see its doc comment. log.Info("Downloading manifest", "remote_key", remoteKey) From c07db21b45c267a6b431cdbfc9a44bb2c060e31e Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 04:49:11 +0100 Subject: [PATCH 106/121] Bind the local index only after a backup writes the marker (closes #420) A first backup that failed before writing anything, on a missing bucket, a refused credential or missing recipients, still bound the local index to the configured destination, so correcting a mistyped storage_url was refused afterwards. A backup now records the binding only after it has written the marker file at the destination. prune, snapshot purge, snapshot remove and remote nuke only refuse a different binding and leave an unbound index unbound. Model: opus-5-5 --- internal/vaultik/destination_marker.go | 20 +++-- internal/vaultik/prune.go | 4 +- internal/vaultik/snapshot.go | 15 ++-- internal/vaultik/storage_bind.go | 65 ++++++++------ internal/vaultik/storage_bind_test.go | 118 +++++++++++++++++++++++++ 5 files changed, 178 insertions(+), 44 deletions(-) diff --git a/internal/vaultik/destination_marker.go b/internal/vaultik/destination_marker.go index af28fcf..66d3420 100644 --- a/internal/vaultik/destination_marker.go +++ b/internal/vaultik/destination_marker.go @@ -51,7 +51,7 @@ func (v *Vaultik) checkDestinationMarker() error { } // Config is nil only in tests, which then record no binding (see - // EnsureStorageBinding). + // checkStorageBinding). if v.Config != nil { stored, configured, err := v.storageBinding() if err != nil { @@ -83,11 +83,19 @@ func (v *Vaultik) checkDestinationMarker() error { return nil } -// markDestination checks the backup destination store with -// checkDestinationMarker and then writes the marker, so a first backup -// marks its destination and a later one writes the same text again. +// markDestination refuses a local index bound to a different +// destination, checks the backup destination store for its marker, +// writes the marker, and then records the binding. A first backup marks +// its destination and a later one writes the same text again. The +// binding is recorded last, so a first backup that cannot write to the +// destination leaves the local index unbound. func (v *Vaultik) markDestination() error { - err := v.checkDestinationMarker() + err := v.checkStorageBinding() + if err != nil { + return err + } + + err = v.checkDestinationMarker() if err != nil { return err } @@ -99,5 +107,5 @@ func (v *Vaultik) markDestination() error { destinationMarkerKey, err) } - return nil + return v.EnsureStorageBinding() } diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index 25cebb4..453f347 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -68,7 +68,7 @@ func (v *Vaultik) NukeRemote(force bool) error { // the same way, so the advice below must not follow these errors. // The listing also fails on a destination that answers that it has // no marker while the local index holds snapshots. - err := v.EnsureStorageBinding() + err := v.checkStorageBinding() if err != nil { return err } @@ -192,7 +192,7 @@ type PruneBlobsResult struct { // PruneDatabase or PruneBlobs individually unless it specifically wants // one half. func (v *Vaultik) Prune(opts *PruneOptions) error { - err := v.EnsureStorageBinding() + err := v.checkStorageBinding() if err != nil { return err } diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index f11a76d..34c7827 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -115,14 +115,9 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { "index_path", v.Config.IndexPath, ) - err := v.EnsureStorageBinding() - if err != nil { - return err - } - // Before PruneDatabase: it drops incomplete snapshots, which could // leave the local index without one and so skip the marker check. - err = v.markDestination() + err := v.markDestination() if err != nil { return err } @@ -749,7 +744,7 @@ type SnapshotPurgeOptions struct { // snapshot name, not the latest globally. This prevents `home` and `system` // snapshots from cannibalizing each other. func (v *Vaultik) PurgeSnapshotsWithOptions(opts *SnapshotPurgeOptions) error { - err := v.EnsureStorageBinding() + err := v.checkStorageBinding() if err != nil { return err } @@ -1277,7 +1272,7 @@ func (v *Vaultik) outputVerifyJSON(result *VerifyResult) error { // jq` fail (issue #108). The narration is duplicated as log records, // which go to stderr and so cannot corrupt the document. func (v *Vaultik) CleanupLocalSnapshots(opts *PruneOptions) error { - err := v.EnsureStorageBinding() + err := v.checkStorageBinding() if err != nil { return err } @@ -1467,7 +1462,7 @@ func (v *Vaultik) RemoveSnapshot( SnapshotID: snapshotID, } - err := v.EnsureStorageBinding() + err := v.checkStorageBinding() if err != nil { return result, err } @@ -1707,7 +1702,7 @@ func (v *Vaultik) removeSnapshotRemote( // before it removes anything when the destination store cannot be // listed or is not present by checkDestinationMarker. func (v *Vaultik) RemoveAllSnapshots(opts *RemoveOptions) (*RemoveResult, error) { - err := v.EnsureStorageBinding() + err := v.checkStorageBinding() if err != nil { return nil, err } diff --git a/internal/vaultik/storage_bind.go b/internal/vaultik/storage_bind.go index c3dcc83..878ed69 100644 --- a/internal/vaultik/storage_bind.go +++ b/internal/vaultik/storage_bind.go @@ -13,35 +13,30 @@ import ( var errStorageBindingMismatch = errors.New( "local index is bound to a different backup destination") -// EnsureStorageBinding guarantees that the local index database is -// bound to the currently-configured storage destination. Every mutating -// command must call this before touching either the local index or the -// destination store, because the two live in lockstep: the local index -// records which chunks/blobs already exist at the destination, and -// mismatched destination + local index produces silent corruption (the -// scanner sees "known" chunks and skips uploads, then writes snapshots -// whose manifests reference blobs that aren't on the new destination). +// checkStorageBinding refuses when the local index database is bound to +// a different destination than the configured one, with an error that +// tells the user how to recover (revert the config, or run `vaultik +// database delete`). Every mutating command calls it before touching +// either the local index or the destination store, because the two live +// in lockstep: the local index records which chunks/blobs already exist +// at the destination, and a mismatched pair produces silent corruption +// (the scanner sees "known" chunks and skips uploads, then writes +// snapshots whose manifests reference blobs that aren't on the new +// destination). // -// Behaviour: -// - On first use (empty stored value), record the configured -// destination (storage_url, or the s3.* endpoint, bucket and -// prefix) and log the binding. -// - When the stored value matches the configured destination, do -// nothing and return nil. -// - When the two differ, refuse with an error that tells the user -// how to recover (revert the config, or run `vaultik database -// delete` to discard the local index and rebuild against the new -// destination on the next backup). +// It records nothing. Only a backup binds the local index, through +// EnsureStorageBinding, and it does so before adding anything to it. An +// unbound local index therefore holds nothing from any destination. // // Read-only inspection commands (remote info, snapshot list, etc.) // deliberately don't call this: they can be run against a bare // destination store without any binding state. -func (v *Vaultik) EnsureStorageBinding() error { +func (v *Vaultik) checkStorageBinding() error { if v.Repositories == nil || v.Config == nil { // NewForTesting builds a Vaultik with no DB or config; - // there's nothing to bind and no binding to check. Callers - // exercising the bind path use a real DB and populate Config - // explicitly (see storage_bind_test.go). + // there's no binding to check. Callers exercising the bind + // path use a real DB and populate Config explicitly (see + // storage_bind_test.go). return nil } @@ -50,6 +45,24 @@ func (v *Vaultik) EnsureStorageBinding() error { return err } + if stored == "" || stored == configured { + return nil + } + + return fmt.Errorf("%w\n%s", + errStorageBindingMismatch, buildBindingMismatchMessage(stored, configured)) +} + +// EnsureStorageBinding records the configured destination (storage_url, +// or the s3.* endpoint, bucket and prefix) as the binding of an unbound +// local index. It refuses as checkStorageBinding does when the local +// index is bound to a different destination. +func (v *Vaultik) EnsureStorageBinding() error { + stored, configured, err := v.storageBinding() + if err != nil { + return err + } + if stored == "" { err = v.Repositories.LocalMeta.Set( v.ctx, database.LocalMetaKeyStorageURL, configured) @@ -62,12 +75,12 @@ func (v *Vaultik) EnsureStorageBinding() error { return nil } - if stored == configured { - return nil + if stored != configured { + return fmt.Errorf("%w\n%s", + errStorageBindingMismatch, buildBindingMismatchMessage(stored, configured)) } - return fmt.Errorf("%w\n%s", - errStorageBindingMismatch, buildBindingMismatchMessage(stored, configured)) + return nil } // storageBinding returns the destination the local index is bound to diff --git a/internal/vaultik/storage_bind_test.go b/internal/vaultik/storage_bind_test.go index 69d97b6..e517a9e 100644 --- a/internal/vaultik/storage_bind_test.go +++ b/internal/vaultik/storage_bind_test.go @@ -2,6 +2,7 @@ package vaultik_test import ( "context" + "path/filepath" "testing" "github.com/stretchr/testify/assert" @@ -9,9 +10,126 @@ import ( "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" "sneak.berlin/go/vaultik/internal/vaultik" ) +// storageBindingOf returns the destination the local index is bound to, +// or "" when it is not bound. +func storageBindingOf( + ctx context.Context, t *testing.T, repos *database.Repositories, +) string { + t.Helper() + + got, err := repos.LocalMeta.Get(ctx, database.LocalMetaKeyStorageURL) + require.NoError(t, err) + + return got +} + +// TestFailedFirstBackupLeavesIndexUnbound checks that a first backup +// the destination refuses, as a mistyped bucket would, leaves the local +// index unbound, so a backup with the corrected destination succeeds. +func TestFailedFirstBackupLeavesIndexUnbound(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := t.TempDir() + v, repos := newFileDestinationVaultik(ctx, t, storeDir) + working := v.Storage + + refusing := faultstore.New(working) + refusing.OnPut = func(string) faultstore.PutAction { return faultstore.PutFail } + refusing.OnStat = func(string) bool { return true } + v.Storage = refusing + v.Config.StorageURL = "file://" + filepath.Join(t.TempDir(), "typo") + + require.ErrorIs(t, backUp(v, "first"), faultstore.ErrInjectedUpload) + assert.Empty(t, storageBindingOf(ctx, t, repos)) + + v.Storage = working + v.Config.StorageURL = "file://" + storeDir + + require.NoError(t, backUp(v, "first")) + assert.Equal(t, "file://"+storeDir, storageBindingOf(ctx, t, repos)) +} + +// TestBackupToOtherDestinationWritesNoMarker checks that a backup +// refuses a local index bound to a different destination before it +// writes the marker to the configured one. +func TestBackupToOtherDestinationWritesNoMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + firstDir := t.TempDir() + v, _ := newFileDestinationVaultik(ctx, t, firstDir) + v.Config.StorageURL = "file://" + firstDir + + require.NoError(t, backUp(v, "first")) + + secondDir := t.TempDir() + secondStore, err := storage.NewFileStorer(secondDir) + require.NoError(t, err) + + v.Storage = secondStore + v.Config.StorageURL = "file://" + secondDir + + require.ErrorContains(t, backUp(v, "first"), + "local index is bound to a different backup destination") + assert.NoFileExists(t, filepath.Join(secondDir, markerFile)) +} + +// TestCommandsOtherThanBackupLeaveIndexUnbound checks that commands +// other than a backup do not bind an unbound local index, whether or not +// they fail. Each runs on a fresh local index. +func TestCommandsOtherThanBackupLeaveIndexUnbound(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + tests := []struct { + name string + run func(v *vaultik.Vaultik) error + }{ + {"prune", func(v *vaultik.Vaultik) error { + return v.Prune(&vaultik.PruneOptions{Force: true}) + }}, + {"snapshot purge", func(v *vaultik.Vaultik) error { + return v.PurgeSnapshotsWithOptions( + &vaultik.SnapshotPurgeOptions{KeepLatest: true, Force: true}) + }}, + {"snapshot remove", func(v *vaultik.Vaultik) error { + _, err := v.RemoveSnapshot("host_first_2026-01-02T03:04:05Z", + &vaultik.RemoveOptions{Force: true}) + + return err + }}, + {"snapshot remove --all", func(v *vaultik.Vaultik) error { + _, err := v.RemoveAllSnapshots(&vaultik.RemoveOptions{Force: true}) + + return err + }}, + {"remote nuke", func(v *vaultik.Vaultik) error { + return v.NukeRemote(true) + }}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + v, repos := newFileDestinationVaultik(ctx, t, t.TempDir()) + + _ = tt.run(v) + + assert.Empty(t, storageBindingOf(ctx, t, repos)) + }) + } +} + // buildBindTestVaultik returns a minimal Vaultik wired with a real // in-memory DB and a config carrying the given StorageURL. Enough to // exercise EnsureStorageBinding without spinning up storage or fx. From 028a166256eb1b13d20b9ed8a7119bd35cfe9c98 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 04:56:31 +0100 Subject: [PATCH 107/121] Report an unreadable blob without its bytes, once (closes #424) A blob that is not a valid age stream made restore print age's error, which quotes the blob's raw bytes, once for every file that needed it. The error now says the blob is not a valid age stream and names its hash, without quoting any bytes. Under --skip-errors a blob that failed is reported once, with the number of files it affected, and is not downloaded again for each file. Model: opus-5-5 --- internal/blobgen/negative_test.go | 34 ++++++ internal/blobgen/reader.go | 42 +++++++- internal/vaultik/restore.go | 66 ++++++++++-- internal/vaultik/restore_skip_errors_test.go | 104 ++++++++++++++++--- 4 files changed, 217 insertions(+), 29 deletions(-) diff --git a/internal/blobgen/negative_test.go b/internal/blobgen/negative_test.go index ef24723..bd712e7 100644 --- a/internal/blobgen/negative_test.go +++ b/internal/blobgen/negative_test.go @@ -2,8 +2,10 @@ package blobgen_test import ( "bytes" + "errors" "fmt" "testing" + "testing/iotest" "filippo.io/age" "github.com/stretchr/testify/assert" @@ -120,6 +122,38 @@ func TestNewReaderTrailingAndGarbage(t *testing.T) { }) } +// TestNewReaderGarbageErrorQuotesNoBytes checks that lines of text in +// place of a blob fail with ErrNotAgeStream, and that the error carries +// none of their bytes. The lines end in a newline because age's own error +// quotes the data's first line only when it reads a whole line. +func TestNewReaderGarbageErrorQuotesNoBytes(t *testing.T) { + t.Parallel() + + id, _ := makeIdentity(t) + garbage := bytes.Repeat([]byte("garbage-bytes-\n"), 100) + + _, err := blobgen.NewReader(bytes.NewReader(garbage), id) + + require.ErrorIs(t, err, blobgen.ErrNotAgeStream) + assert.NotContains(t, err.Error(), "garbage-bytes-") +} + +// errConnectionReset stands for a storage read that fails. +var errConnectionReset = errors.New("connection reset") + +// TestNewReaderReadFailure checks that a failed read of the age header is +// returned as that read error, not as ErrNotAgeStream. +func TestNewReaderReadFailure(t *testing.T) { + t.Parallel() + + id, _ := makeIdentity(t) + + _, err := blobgen.NewReader(iotest.ErrReader(errConnectionReset), id) + + require.ErrorIs(t, err, errConnectionReset) + assert.NotErrorIs(t, err, blobgen.ErrNotAgeStream) +} + // TestNewWriterInvalidLevel covers the rejected end of issue case 9: an // out-of-range compression level errors and writes nothing to the destination. func TestNewWriterInvalidLevel(t *testing.T) { diff --git a/internal/blobgen/reader.go b/internal/blobgen/reader.go index 27bad18..9886361 100644 --- a/internal/blobgen/reader.go +++ b/internal/blobgen/reader.go @@ -11,6 +11,11 @@ import ( "github.com/klauspost/compress/zstd" ) +// ErrNotAgeStream is returned by NewReader when the data cannot be opened +// as an age stream, for example because its header is malformed. It +// replaces age's own error, which can quote the data's first bytes. +var ErrNotAgeStream = errors.New("not a valid age stream") + // Reader wraps decompression and decryption with SHA256 verification type Reader struct { reader io.Reader @@ -24,11 +29,25 @@ type Reader struct { // NewReader creates a new Reader that decrypts, decompresses, and verifies // data. Every supplied identity is offered to age.Decrypt, so a blob // encrypted to any one of them can be read. +// +// A failure to read r is returned as that error, and a blob encrypted to +// none of the identities as age.NoIdentityMatchError. Any other failure +// to open the age stream is ErrNotAgeStream. func NewReader(r io.Reader, identities ...age.Identity) (*Reader, error) { - // Create decryption reader - decReader, err := age.Decrypt(r, identities...) + src := &readErrorRecorder{reader: r} + + decReader, err := age.Decrypt(src, identities...) if err != nil { - return nil, fmt.Errorf("creating decryption reader: %w", err) + var noMatch *age.NoIdentityMatchError + + switch { + case src.err != nil: + return nil, fmt.Errorf("reading age header: %w", src.err) + case errors.As(err, &noMatch): + return nil, fmt.Errorf("creating decryption reader: %w", err) + default: + return nil, ErrNotAgeStream + } } // Create decompression reader @@ -52,6 +71,23 @@ func NewReader(r io.Reader, identities ...age.Identity) (*Reader, error) { }, nil } +// readErrorRecorder passes reads through to reader and keeps the first +// error other than io.EOF, so NewReader can tell a failed read from bad +// data. +type readErrorRecorder struct { + reader io.Reader + err error +} + +func (r *readErrorRecorder) Read(p []byte) (int, error) { + n, err := r.reader.Read(p) + if err != nil && !errors.Is(err, io.EOF) && r.err == nil { + r.err = err + } + + return n, err +} + // Read implements io.Reader func (r *Reader) Read(p []byte) (int, error) { n, err := r.teeReader.Read(p) diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index 86ee32d..daedba2 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -106,7 +106,12 @@ type RestoreResult struct { BytesDownloaded int64 Duration time.Duration FilesFailed int - FailedFiles []string // Paths of files that failed to restore + FailedFiles []string // Paths of files that failed to restore for their own reason + // Blobs that could not be downloaded, and the paths of the files + // skipped because they need one of them. Those files are counted in + // FilesFailed but not listed in the summary. + BlobsFailed int + FilesNeedingFailedBlob []string // Verification results (only populated if Verify option is set) FilesVerified int BytesVerified int64 @@ -231,6 +236,11 @@ func (v *Vaultik) finishRestore( if result.FilesFailed > 0 { v.UI.Warningf("%d file(s) failed to restore:", result.FilesFailed) + if result.BlobsFailed > 0 { + v.UI.Detailf("%d of them need a blob that could not be read (%d blob(s) in all).", + len(result.FilesNeedingFailedBlob), result.BlobsFailed) + } + for _, path := range result.FailedFiles { v.UI.Detailf("%s", v.UI.Path(path)) } @@ -499,8 +509,8 @@ func (v *Vaultik) runRestoreLoop( // Returns false when nothing is pending download (the caller stops). // // A blob that cannot be downloaded is reported through -// handleRestoreFileError for every pending file that references it, so -// it aborts the restore unless --skip-errors is set. +// handleRestoreBlobError, so it aborts the restore unless --skip-errors +// is set. func (s *restoreSession) downloadNextBlobSet( plan *restorePlan, filesByID map[types.FileID]*database.File, ) (bool, error) { @@ -533,12 +543,11 @@ func (s *restoreSession) downloadNextBlobSet( return false, err } - for _, fileID := range plan.filesReferencingBlob(hash) { - fileErr := s.v.handleRestoreFileError( - plan, s.opts, s.result, filesByID[fileID], fileID, err) - if fileErr != nil { - return false, fileErr - } + blobErr := s.v.handleRestoreBlobError( + plan, s.opts, s.result, filesByID, + plan.filesReferencingBlob(hash), err) + if blobErr != nil { + return false, blobErr } // next is among the failed files, so the rest of its blob set @@ -653,6 +662,41 @@ func (v *Vaultik) handleRestoreFileError( return nil } +// handleRestoreBlobError records a blob that could not be downloaded. +// fileIDs are the pending files that need it, never empty. Without +// --skip-errors the first of them fails the restore. With it, the blob is +// reported once, and its files are counted as failed and dropped from +// the plan without being reported one by one. +func (v *Vaultik) handleRestoreBlobError( + plan *restorePlan, opts *RestoreOptions, result *RestoreResult, + filesByID map[types.FileID]*database.File, fileIDs []types.FileID, + err error, +) error { + if !opts.SkipErrors { + return v.handleRestoreFileError( + plan, opts, result, filesByID[fileIDs[0]], fileIDs[0], err) + } + + log.Error("Failed to restore files", "files", len(fileIDs), "error", err) + v.UI.Errorf("Failed to restore %d file(s): %v. Skipping them (--skip-errors).", + len(fileIDs), err) + + result.BlobsFailed++ + + for _, fileID := range fileIDs { + path := filesByID[fileID].Path.String() + + log.Debug("Skipped file that needs a failed blob", "path", path) + + result.FilesFailed++ + result.FilesNeedingFailedBlob = append(result.FilesNeedingFailedBlob, path) + + plan.finishFile(fileID) + } + + return nil +} + // printRestoreProgress emits a periodic restore-phase status line via // the UI writer, mirroring scanner.printProcessingProgress so the two // long-running commands have the same on-screen rhythm. @@ -724,8 +768,8 @@ func (v *Vaultik) handleRestoreVerification( ) error { // A file that failed to restore was not written and is already // reported as such, so it is not verified. - failedToRestore := make(map[string]bool, len(result.FailedFiles)) - for _, path := range result.FailedFiles { + failedToRestore := make(map[string]bool, result.FilesFailed) + for _, path := range slices.Concat(result.FailedFiles, result.FilesNeedingFailedBlob) { failedToRestore[path] = true } diff --git a/internal/vaultik/restore_skip_errors_test.go b/internal/vaultik/restore_skip_errors_test.go index 8c3bcf1..5de3e2b 100644 --- a/internal/vaultik/restore_skip_errors_test.go +++ b/internal/vaultik/restore_skip_errors_test.go @@ -51,27 +51,72 @@ func TestRestoreSkipErrorsSkipsFilesOfMissingBlob(t *testing.T) { t.Parallel() ctx := context.Background() - assertRestoreSkipsLostFiles(ctx, t, backupThenDeleteOneBlob(ctx, t)) + backup := backupThenDeleteOneBlob(ctx, t) + out := assertRestoreSkipsLostFiles(ctx, t, backup) + + assertLostFilesCountedNotListed(t, backup, out) +} + +// TestRestoreSkipErrorsReportsUnreadableBlobOnce restores with SkipErrors +// after one blob of a two-blob snapshot was overwritten with other bytes +// of the same size. The blob must be reported once, by its hash, as not a +// valid age stream, without quoting its bytes, and its files must be +// counted, not listed. +func TestRestoreSkipErrorsReportsUnreadableBlobOnce(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + backup, lostBlob := backupThenOverwriteOneBlob(ctx, t) + out := assertRestoreSkipsLostFiles(ctx, t, backup) + + assert.Equal(t, 1, strings.Count(out, "not a valid age stream"), out) + assert.Contains(t, out, lostBlob[:16]) + assert.NotContains(t, out, overwriteBlobPattern) + assertLostFilesCountedNotListed(t, backup, out) } // TestRestoreSkipErrorsSkipsFilesWithChunkInNoBlob restores with // SkipErrors a snapshot whose metadata lists chunks that no blob holds, as -// earlier backup defects left behind. +// earlier backup defects left behind. Each such file fails for its own +// reason, so each is listed. func TestRestoreSkipErrorsSkipsFilesWithChunkInNoBlob(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() ctx := context.Background() - assertRestoreSkipsLostFiles(ctx, t, backupThenDropOneBlobFromMetadata(ctx, t)) + backup := backupThenDropOneBlobFromMetadata(ctx, t) + out := assertRestoreSkipsLostFiles(ctx, t, backup) + + for path := range backup.lost { + assert.Containsf(t, out, path, "%s must be reported", path) + } } -// assertRestoreSkipsLostFiles restores backup with SkipErrors. Every file -// stored in the lost blob must be reported as failed and left absent, -// every other file must be restored intact, and Restore must still return -// an error. +// assertLostFilesCountedNotListed checks that the restore output out +// counts the files of the lost blob and names none of them. +func assertLostFilesCountedNotListed( + t *testing.T, backup *missingBlobBackup, out string, +) { + t.Helper() + + assert.Contains(t, out, fmt.Sprintf( + "%d of them need a blob that could not be read (1 blob(s) in all)", + len(backup.lost))) + + for path := range backup.lost { + assert.NotContainsf(t, out, path, + "%s needs the lost blob and must be counted, not listed", path) + } +} + +// assertRestoreSkipsLostFiles restores backup with SkipErrors and returns +// what it printed. Every file stored in the lost blob must be left +// absent, every other file must be restored intact, and Restore must +// still return an error. func assertRestoreSkipsLostFiles( ctx context.Context, t *testing.T, backup *missingBlobBackup, -) { +) string { t.Helper() var out bytes.Buffer @@ -93,8 +138,6 @@ func assertRestoreSkipsLostFiles( restored := filepath.Join(backup.restoreDir, path) if backup.lost[path] { - assert.Containsf(t, out.String(), path, - "%s needs the lost blob and must be reported", path) assert.NoFileExists(t, restored) continue @@ -104,6 +147,8 @@ func assertRestoreSkipsLostFiles( require.NoErrorf(t, err, "%s does not need the lost blob", path) assert.Equalf(t, content, got, "%s restored with wrong content", path) } + + return out.String() } // TestRestoreSkipErrorsVerifyChecksOnlyRestoredFiles restores with @@ -144,9 +189,9 @@ func TestRestoreSkipErrorsVerifyChecksOnlyRestoredFiles(t *testing.T) { // TestRestoreSkipErrorsVerifyReportsFailuresApart restores with // SkipErrors and Verify after one blob of a two-blob snapshot was // deleted, while one file that does restore is written one byte too long. -// The restore warning must list only the files of the deleted blob, the -// verification summary only the long file, each path once, and Restore -// must return an error. +// The restore warning must count the files of the deleted blob without +// listing them, the verification summary must list only the long file, +// once, and Restore must return an error. func TestRestoreSkipErrorsVerifyReportsFailuresApart(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -186,9 +231,9 @@ func TestRestoreSkipErrorsVerifyReportsFailuresApart(t *testing.T) { "Verification failed: 1 files did not match") require.Truef(t, found, "no verification summary in:\n%s", out.String()) + assertLostFilesCountedNotListed(t, backup, warning) + for path := range backup.lost { - assert.Equalf(t, 1, strings.Count(warning, path), - "%s must be listed once as failed to restore", path) assert.NotContainsf(t, summary, path, "%s was not restored and must not fail verification", path) } @@ -292,6 +337,35 @@ func backupThenDeleteOneBlob( return backup } +// overwriteBlobPattern repeats, each time followed by a newline, through +// the bytes that backupThenOverwriteOneBlob writes over a blob. age's own +// error quotes the data's first line only when it reads a whole line. +const overwriteBlobPattern = "overwritten-blob-bytes-" + +// backupThenOverwriteOneBlob backs up missingBlobFileCount single-chunk +// files, then overwrites the blob holding the first of them with as many +// bytes of overwriteBlobPattern lines. It also returns that blob's hash. +func backupThenOverwriteOneBlob( + ctx context.Context, t *testing.T, +) (*missingBlobBackup, string) { + t.Helper() + + backup, db, lostBlob := backupSingleChunkFiles(ctx, t) + require.NoError(t, db.Close()) + + key := fmt.Sprintf("blobs/%s/%s/%s", lostBlob[:2], lostBlob[2:4], lostBlob) + + info, err := backup.storer.Stat(ctx, key) + require.NoError(t, err) + + line := overwriteBlobPattern + "\n" + pattern := bytes.Repeat([]byte(line), int(info.Size)/len(line)+1) + require.NoError(t, backup.storer.Put( + ctx, key, bytes.NewReader(pattern[:info.Size]))) + + return backup, lostBlob +} + // backupThenDropOneBlobFromMetadata backs up missingBlobFileCount // single-chunk files, then removes the blob holding the first of them from // the snapshot and exports the snapshot metadata again. The exported From d8d13d1c8beaa3a97011e815e55f7a567c70ab9d Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 05:05:24 +0100 Subject: [PATCH 108/121] Refuse config keys that no setting has (closes #419) A misspelled or unknown config key was accepted silently, so a typo in exclude backed up everything it meant to leave out. Loading now refuses a key that no setting has, at any depth, naming its dotted path and, when it is in the file, its line; keys brought in by ${...} references are checked too. config set refuses an unknown key. A top-level env: section stays accepted, since the config library uses it. Anchors that contain themselves fail with an error. Model: opus-5-5 --- README.md | 10 +- internal/cli/config.go | 52 +++------ internal/cli/config_test.go | 43 ++++++- internal/config/config.go | 27 ++++- internal/config/keys.go | 214 +++++++++++++++++++++++++++++++++++ internal/config/keys_test.go | 163 ++++++++++++++++++++++++++ 6 files changed, 462 insertions(+), 47 deletions(-) create mode 100644 internal/config/keys.go create mode 100644 internal/config/keys_test.go diff --git a/README.md b/README.md index be62a24..002180c 100644 --- a/README.md +++ b/README.md @@ -313,12 +313,10 @@ when the next path element is a number (so `vaultik config set age_recipients.0 age1...` works on a file without `age_recipients`), otherwise as a map. If the config loads, a change after which it would not, such as `vaultik config set compression_level 99`, is refused and -the file is left unchanged. A config that does not load, such as the one -`config init` writes before `storage_url` is set or one with a `${ENV:...}` -reference to a variable not set in this shell, is checked one setting at a time: -only a change after which the changed setting cannot be read, such as one giving -it the wrong type (a single value where a list belongs or a word where a number -belongs), is refused. +the file is left unchanged. A config that does not load is checked one setting +at a time. Examples are the file `config init` writes before `storage_url` is +set, and one with a `${ENV:...}` reference to a variable not set in this shell. +In such a config, an unknown key or a value of the wrong type is refused. **`snapshot create`**: Perform incremental backup of configured snapshots. diff --git a/internal/cli/config.go b/internal/cli/config.go index 96976aa..806a78a 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -443,11 +443,10 @@ number, otherwise as a map. If the config loads, a change after which it would not, such as compression_level 99, is refused and the file is left unchanged. A -config that does not load, such as the one config init writes before -storage_url is set or one with a ${ENV:...} reference to a variable -not set here, is checked one setting at a time: only a change after -which the changed setting cannot be read, such as one giving it the -wrong type, is refused. +config that does not load is checked one setting at a time. Examples +are the file config init writes before storage_url is set, and one +with a ${ENV:...} reference to a variable not set in this shell. In +such a config, an unknown key or a value of the wrong type is refused. Examples: vaultik config set storage_url "file:///mnt/backups" @@ -484,6 +483,13 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error { keys := strings.Split(key, ".") + if keys[0] != config.EnvSection { + _, err = config.SettingType(keys) + if err != nil { + return err + } + } + err = yamlPathSet(root, keys, value) if err != nil { return err @@ -739,41 +745,11 @@ func yamlPathSet(root *yaml.Node, keys []string, value string) error { } // configKeyIsString reports whether the dotted key names a string in -// config.Config, following the fields' yaml tags, as s3.access_key_id and -// snapshots.home.exclude.0 do. +// config.Config, as s3.access_key_id and snapshots.home.exclude.0 do. func configKeyIsString(keys []string) bool { - typ := reflect.TypeFor[config.Config]() + typ, err := config.SettingType(keys) - for _, key := range keys { - switch { - case typ.Kind() == reflect.Map || typ.Kind() == reflect.Slice: - // The key is a snapshot name or a list index. - typ = typ.Elem() - case typ.Kind() == reflect.Struct: - field, ok := yamlField(typ, key) - if !ok { - return false - } - - typ = field.Type - default: - return false - } - } - - return typ.Kind() == reflect.String -} - -// yamlField returns the field of struct type typ whose yaml tag names key. -func yamlField(typ reflect.Type, key string) (reflect.StructField, bool) { - for field := range typ.Fields() { - name, _, _ := strings.Cut(field.Tag.Get("yaml"), ",") - if name == key { - return field, true - } - } - - return reflect.StructField{}, false + return err == nil && typ.Kind() == reflect.String } // yamlSetInMapping resolves (creating if needed) the value node for the diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go index 7f7d390..6eb45cb 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -225,7 +225,7 @@ func TestConfigSetIndexUnderMissingKey(t *testing.T) { // change after which the config would not load, with an error giving the // reason, and leaves the file as it was. On the file `config init` writes, // which does not load until storage_url is set, and on one that cannot be -// read here, only a value of the wrong type is refused. +// read here, only an unknown key or a value of the wrong type is refused. func TestConfigSetKeepsFileThatWouldNotLoad(t *testing.T) { t.Parallel() @@ -237,6 +237,14 @@ func TestConfigSetKeepsFileThatWouldNotLoad(t *testing.T) { value string reason string }{ + // Keys that no setting has, on a config that loads and on one + // that does not. + {configWithoutRecipients, "nosuchkey", "1", + `unknown config key "nosuchkey"`}, + {configWithoutRecipients, "snapshots.home.exlude", "/tmp", + `unknown config key "snapshots.home.exlude"`}, + {defaultConfigText(macOS), "compression_lvl", "9", + `unknown config key "compression_lvl"`}, // Index 1 of the empty list the missing key gives. {configWithoutRecipients, "age_recipients.1", testRecipient, "index out of range"}, @@ -335,6 +343,39 @@ func TestConfigSetRefusesOnlyItsOwnFailure(t *testing.T) { } } +// TestConfigSetWritesEnvSection checks that config set writes a key under +// the top-level env section, whose keys are not settings, on a config that +// loads. +func TestConfigSetWritesEnvSection(t *testing.T) { + const name = "VAULTIK_TEST_CONFIG_SET_ENV" + + // Loading the changed config sets the variable; t.Setenv restores it + // after the test. + t.Setenv(name, "") + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(configWithoutRecipients), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, "env."+name, "value") + if err != nil { + t.Fatalf("config set env.%s: %v", name, err) + } + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("read config: %v", err) + } + + if !strings.Contains(string(data), "env:\n "+name+": value\n") { + t.Errorf("config set env.%s wrote:\n%s", name, data) + } +} + // TestConfigSetStringLooksLikeNumber sets string settings to values that // YAML reads as numbers or booleans when they are unquoted, and checks that // config.Load returns each one unchanged. diff --git a/internal/config/config.go b/internal/config/config.go index 12015f7..8b79f88 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -9,6 +9,7 @@ import ( "fmt" "os" "path/filepath" + "reflect" "sort" "strings" "time" @@ -286,15 +287,37 @@ func Load(path string) (*Config, error) { } // Parse reads YAML config data as Load does, without validating it. It -// applies default values for optional fields, fills in ${...} references -// using smartconfig, and expands ~ in paths. +// refuses a key that no setting has, applies default values for optional +// fields, fills in ${...} references using smartconfig, and expands ~ in +// paths. func Parse(data []byte) (*Config, error) { + // smartconfig drops line numbers, so keys are checked in the data as + // written. + var root yaml.Node + + err := yaml.Unmarshal(data, &root) + if err != nil { + return nil, fmt.Errorf("failed to parse config: %w", err) + } + + err = checkKeys(&root, reflect.TypeFor[Config](), "", + map[*yaml.Node]bool{}, map[nodeAndType]bool{}) + if err != nil { + return nil, err + } + // Load config using smartconfig for interpolation sc, err := smartconfig.NewFromReader(bytes.NewReader(data)) if err != nil { return nil, fmt.Errorf("failed to load config file: %w", err) } + // A ${...} reference can bring in keys that are not in the file. + err = checkFilledKeys(sc.Data()) + if err != nil { + return nil, err + } + cfg := &Config{ // Set defaults BlobSizeLimit: defaultBlobSizeLimit, diff --git a/internal/config/keys.go b/internal/config/keys.go new file mode 100644 index 0000000..8e51543 --- /dev/null +++ b/internal/config/keys.go @@ -0,0 +1,214 @@ +package config + +import ( + "errors" + "fmt" + "reflect" + "strconv" + "strings" + + "gopkg.in/yaml.v3" +) + +// yamlMergeTag is the tag YAML gives a merge key (<<), which adds the keys +// of the map it names to the map it sits in. +const yamlMergeTag = "!!merge" + +// EnvSection is the top-level key of a map of environment variables that +// smartconfig sets while it loads the config. It is not a vaultik setting, +// so its keys are not checked. +const EnvSection = "env" + +var ( + errUnknownKey = errors.New("unknown config key") + errAnchorContainsItself = errors.New("anchor contains itself") +) + +// nodeAndType is a node of a parsed config and the setting type it is +// checked against. +type nodeAndType struct { + node *yaml.Node + typ reflect.Type +} + +// SettingType returns the type of the setting that the dotted key names in +// Config, following the fields' yaml tags, as for s3.bucket or +// snapshots.home.exclude.0. A snapshot name or a list index may be any +// word. It returns an unknown key error when no setting has that key. +func SettingType(keys []string) (reflect.Type, error) { + typ := reflect.TypeFor[Config]() + + for _, key := range keys { + switch { + case typ.Kind() == reflect.Map || typ.Kind() == reflect.Slice: + typ = typ.Elem() + case typ.Kind() == reflect.Struct: + field, ok := yamlField(typ, key) + if !ok { + return nil, fmt.Errorf("%w %q", errUnknownKey, strings.Join(keys, ".")) + } + + typ = field.Type + default: + return nil, fmt.Errorf("%w %q", errUnknownKey, strings.Join(keys, ".")) + } + } + + return typ, nil +} + +// yamlField returns the field of struct type typ whose yaml tag names key. +func yamlField(typ reflect.Type, key string) (reflect.StructField, bool) { + for field := range typ.Fields() { + name, _, _ := strings.Cut(field.Tag.Get("yaml"), ",") + if name == key && name != "-" { + return field, true + } + } + + return reflect.StructField{}, false +} + +// checkKeys returns an error naming the first key in node, a parsed config +// or part of one at the dotted path, that no setting in typ has. The error +// gives the key's line in the file, when it has one. A value of the wrong +// type is left for the YAML decoder to report. following holds the aliases +// the walk is inside. Meeting one of them again means its anchor contains +// itself, which is an error. checked holds each anchored node the walk has +// checked completely, with the type it was checked against. An alias to +// that node is not followed again for that type. +func checkKeys(node *yaml.Node, typ reflect.Type, path string, + following map[*yaml.Node]bool, checked map[nodeAndType]bool, +) error { + switch node.Kind { + case yaml.DocumentNode: + for _, child := range node.Content { + err := checkKeys(child, typ, path, following, checked) + if err != nil { + return err + } + } + case yaml.AliasNode: + if following[node] { + return fmt.Errorf("%w: %q on line %d", + errAnchorContainsItself, node.Value, node.Line) + } + + target := nodeAndType{node.Alias, typ} + if checked[target] { + return nil + } + + following[node] = true + defer delete(following, node) + + err := checkKeys(node.Alias, typ, path, following, checked) + if err != nil { + return err + } + + checked[target] = true + case yaml.SequenceNode: + if typ.Kind() != reflect.Slice { + return nil + } + + for i, child := range node.Content { + err := checkKeys(child, typ.Elem(), joinKey(path, strconv.Itoa(i)), + following, checked) + if err != nil { + return err + } + } + case yaml.MappingNode: + return checkMappingKeys(node, typ, path, following, checked) + case yaml.ScalarNode: + // A scalar has no keys. + } + + return nil +} + +// checkFilledKeys is checkKeys for data, the config after smartconfig has +// filled in its ${...} references. A key that a reference brings in is not +// in the file, and the copy that Encode makes has no line numbers. +func checkFilledKeys(data map[string]any) error { + var filled yaml.Node + + err := filled.Encode(data) + if err != nil { + return fmt.Errorf("failed to marshal config data: %w", err) + } + + return checkKeys(&filled, reflect.TypeFor[Config](), "", + map[*yaml.Node]bool{}, map[nodeAndType]bool{}) +} + +// checkMappingKeys is checkKeys for a map. +func checkMappingKeys(node *yaml.Node, typ reflect.Type, path string, + following map[*yaml.Node]bool, checked map[nodeAndType]bool, +) error { + for i := 0; i+1 < len(node.Content); i += 2 { + key, value := node.Content[i], node.Content[i+1] + + if key.Tag == yamlMergeTag { + // The value is one map or a list of maps. + merged := []*yaml.Node{value} + if value.Kind == yaml.SequenceNode { + merged = value.Content + } + + for _, m := range merged { + err := checkKeys(m, typ, path, following, checked) + if err != nil { + return err + } + } + + continue + } + + keyPath := joinKey(path, key.Value) + if keyPath == EnvSection { + continue + } + + var valueType reflect.Type + + switch { + case typ.Kind() == reflect.Map: + valueType = typ.Elem() + case typ.Kind() == reflect.Struct: + field, ok := yamlField(typ, key.Value) + if !ok && key.Line == 0 { + // A key that a ${...} reference brought in has no line. + return fmt.Errorf("%w %q", errUnknownKey, keyPath) + } + + if !ok { + return fmt.Errorf("%w %q on line %d", + errUnknownKey, keyPath, key.Line) + } + + valueType = field.Type + default: + return nil + } + + err := checkKeys(value, valueType, keyPath, following, checked) + if err != nil { + return err + } + } + + return nil +} + +// joinKey appends key to the dotted path. +func joinKey(path, key string) string { + if path == "" { + return key + } + + return path + "." + key +} diff --git a/internal/config/keys_test.go b/internal/config/keys_test.go new file mode 100644 index 0000000..f67e875 --- /dev/null +++ b/internal/config/keys_test.go @@ -0,0 +1,163 @@ +package config //nolint:testpackage // checks the unexported errUnknownKey + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" +) + +// keysTestConfig loads; each case below adds one line to it. +const keysTestConfig = "storage_url: file:///tmp/vaultik-test-storage\n" + + "s3:\n" + + " region: us-east-1\n" + + "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + +// TestParseRefusesUnknownKey checks that a key no setting has, at any +// depth, fails the parse with an error naming the key and its line. A key +// that a ${...} reference brings in is not in the file, so its error gives +// no line. +func TestParseRefusesUnknownKey(t *testing.T) { + t.Parallel() + + snapshotPath := filepath.Join(t.TempDir(), "snapshot.yml") + + err := os.WriteFile(snapshotPath, []byte("other:\n"+ + " paths: [/tmp/vaultik-test-source]\n"+ + " exlude: [/tmp/cache]\n"), 0o600) + if err != nil { + t.Fatalf("write snapshot: %v", err) + } + + tests := []struct { + name string + yaml string + want string + }{ + {"top level", keysTestConfig + "compression_lvl: 9\n", + `unknown config key "compression_lvl" on line 7`}, + {"in a snapshot", keysTestConfig + " exlude: [/tmp/cache]\n", + `unknown config key "snapshots.test.exlude" on line 7`}, + {"in s3", strings.Replace(keysTestConfig, " region:", + " bukcet: b\n region:", 1), + `unknown config key "s3.bukcet" on line 3`}, + {"from a reference", + keysTestConfig + " other: ${YAML:" + snapshotPath + ":other}\n", + `unknown config key "snapshots.other.exlude"`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + _, err := Parse([]byte(tt.yaml)) + if !errors.Is(err, errUnknownKey) { + t.Fatalf("Parse() error = %v, want errUnknownKey", err) + } + + if err.Error() != tt.want { + t.Errorf("Parse() error = %q, want %q", err.Error(), tt.want) + } + }) + } +} + +// TestParseRefusesAnchorThatContainsItself checks that a YAML merge key (<<) +// naming the anchor of the map it sits in fails the parse with an error. +func TestParseRefusesAnchorThatContainsItself(t *testing.T) { + t.Parallel() + + data := strings.Replace(keysTestConfig, " test:", " test: &test", 1) + + " <<: *test\n" + + _, err := Parse([]byte(data)) + if !errors.Is(err, errAnchorContainsItself) { + t.Fatalf("Parse() error = %v, want errAnchorContainsItself", err) + } + + want := `anchor contains itself: "test" on line 7` + if err.Error() != want { + t.Errorf("Parse() error = %q, want %q", err.Error(), want) + } +} + +// TestParseRefusesExcessiveAliasing checks that Parse returns an error for +// a file whose merge keys (<<) fan out. Each of eight snapshots merges the +// one before it ten times. A key check that followed every alias would walk +// the first snapshot over 10^8 times and run past the package's test +// timeout. +func TestParseRefusesExcessiveAliasing(t *testing.T) { + t.Parallel() + + const snapshots, merges = 8, 10 + + var data strings.Builder + + data.WriteString(strings.Replace(keysTestConfig, " test:", " test: &s0", 1)) + + for i := 1; i <= snapshots; i++ { + aliases := slices.Repeat([]string{"*s" + strconv.Itoa(i-1)}, merges) + fmt.Fprintf(&data, " s%d: &s%d\n <<: [%s]\n", + i, i, strings.Join(aliases, ", ")) + } + + _, err := Parse([]byte(data.String())) + if err == nil { + t.Fatal("Parse() returned no error") + } +} + +// TestParseAcceptsKnownKeys checks that a config with a ${...} reference +// and a YAML merge key (<<) still parses. +func TestParseAcceptsKnownKeys(t *testing.T) { + t.Parallel() + + levelPath := filepath.Join(t.TempDir(), "level") + + err := os.WriteFile(levelPath, []byte("9"), 0o600) + if err != nil { + t.Fatalf("write level: %v", err) + } + + data := strings.Replace(keysTestConfig, " test:", " test: &test", 1) + + " other:\n" + + " <<: *test\n" + + " exclude: [/tmp/vaultik-test-source/cache]\n" + + "compression_level: ${FILE:" + levelPath + "}\n" + + cfg, err := Parse([]byte(data)) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } + + if cfg.CompressionLevel != 9 { + t.Errorf("compression_level = %d, want 9", cfg.CompressionLevel) + } + + other := cfg.Snapshots["other"] + if len(other.Paths) != 1 || len(other.Exclude) != 1 { + t.Errorf("snapshot other = %+v, want the paths of test and one exclude", + other) + } +} + +// TestParseAcceptsEnvSection checks that a config with a top-level env +// section still parses. smartconfig sets the environment variables it +// lists, so its keys are not settings. +func TestParseAcceptsEnvSection(t *testing.T) { + const name = "VAULTIK_TEST_ENV_SECTION" + + // Parse sets the variable; t.Setenv restores it after the test. + t.Setenv(name, "") + + _, err := Parse([]byte(keysTestConfig + "env:\n " + name + ": set\n")) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } +} From 1a478ef2750a1899f2a7b0f44e05455757333295 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 05:24:30 +0100 Subject: [PATCH 109/121] Say plainly when the private key cannot decrypt a snapshot (closes #427) With a private key the backup was not encrypted to, restore and deep verify failed with age's "no identity matched any of the recipients" behind a doubled prefix. They now say in one sentence that the key from VAULTIK_AGE_SECRET_KEY or age_secret_key is not one of the keys the snapshot, or a blob, was encrypted to. A blob reused after a recipient change gets the same message. Model: opus-5-5 --- internal/vaultik/blob_fetch.go | 32 +++- internal/vaultik/restore.go | 33 ++++- internal/vaultik/restore_wrong_key_test.go | 161 +++++++++++++++++++++ internal/vaultik/verify.go | 14 +- 4 files changed, 234 insertions(+), 6 deletions(-) create mode 100644 internal/vaultik/restore_wrong_key_test.go diff --git a/internal/vaultik/blob_fetch.go b/internal/vaultik/blob_fetch.go index 4672921..4a2ccc1 100644 --- a/internal/vaultik/blob_fetch.go +++ b/internal/vaultik/blob_fetch.go @@ -22,6 +22,10 @@ var errBlobHashMismatch = errors.New("blob hash mismatch") var errBlobNotFullyRead = errors.New( "blob closed before fully read; hash not verified") +// errWrongPrivateKeyForBlob is returned when the configured key parses +// but is not one of the keys a blob was encrypted to. +var errWrongPrivateKeyForBlob = errors.New("cannot decrypt this blob") + // hashVerifyReader wraps a blobgen.Reader and verifies the double-SHA-256 hash // of decrypted plaintext when Close is called. It reuses the hash that // blobgen.Reader already computes internally via its TeeReader, avoiding @@ -87,10 +91,14 @@ func (v *Vaultik) FetchAndDecryptBlob( return nil, err } - reader, err := blobgen.NewReader(rc, identities...) + reader, err := v.newBlobReader(rc, identities) if err != nil { _ = rc.Close() + if errors.Is(err, errWrongPrivateKeyForBlob) { + return nil, err + } + return nil, fmt.Errorf("creating blob reader: %w", err) } @@ -102,6 +110,28 @@ func (v *Vaultik) FetchAndDecryptBlob( }, nil } +// newBlobReader opens the decrypting reader for a blob. When none of the +// identities can decrypt it, the error says in plain words that the +// configured private key is not one of the keys the blob was encrypted +// to and names where the key was configured. +func (v *Vaultik) newBlobReader( + r io.Reader, identities []age.Identity, +) (*blobgen.Reader, error) { + blobReader, err := blobgen.NewReader(r, identities...) + + if _, ok := errors.AsType[*age.NoIdentityMatchError](err); ok { + return nil, fmt.Errorf( + "%w: the private key in %s is not one of the keys the blob was encrypted to", + errWrongPrivateKeyForBlob, v.Config.AgeSecretKeySourceName()) + } + + if err != nil { + return nil, err + } + + return blobReader, nil +} + // FetchBlob downloads a blob and returns a reader for the encrypted data. // The reader is closed as soon as ctx is cancelled, which ends a read // blocked inside it. A storage error is returned as is: restore and deep diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index daedba2..928ca20 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -40,6 +40,9 @@ var ( // which is secret, so the message is safe to print and log. errInvalidAgeSecretKey = errors.New( "configured age secret key holds no usable age identity") + // errWrongPrivateKey is returned when the configured key parses but + // is not one of the keys the snapshot was encrypted to. + errWrongPrivateKey = errors.New("cannot decrypt this snapshot") errBlobMissingFromIndex = errors.New("blob hash missing from blob index") errChunkNotInAnyBlob = errors.New("chunk not found in any blob") errBlobIDNotInHashIndex = errors.New("blob id missing from hash index") @@ -142,6 +145,10 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error { log.Info("Downloading snapshot metadata...") tempDB, tempDir, err := v.downloadSnapshotDB(opts.SnapshotID, remoteKey, identities) + if errors.Is(err, errWrongPrivateKey) { + return err + } + if err != nil { return fmt.Errorf("downloading snapshot database: %w", err) } @@ -338,6 +345,28 @@ func (v *Vaultik) restoreIdentities() ([]age.Identity, error) { return identities, nil } +// newSnapshotDBReader opens the decrypting reader for a snapshot +// database. When none of the identities can decrypt it, the error says +// in plain words that the configured private key is the wrong one and +// names where it was configured. +func (v *Vaultik) newSnapshotDBReader( + r io.Reader, identities []age.Identity, +) (*blobgen.Reader, error) { + blobReader, err := blobgen.NewReader(r, identities...) + + if _, ok := errors.AsType[*age.NoIdentityMatchError](err); ok { + return nil, fmt.Errorf( + "%w: the private key in %s is not one of the keys the backup was encrypted to", + errWrongPrivateKey, v.Config.AgeSecretKeySourceName()) + } + + if err != nil { + return nil, err + } + + return blobReader, nil +} + // restoreAllFiles processes files in blob-locality order: drain every // file whose blob set is on disk, download the missing blobs for the // pending file with the smallest uncached count, repeat. This keeps @@ -825,9 +854,9 @@ func (v *Vaultik) downloadSnapshotDB( // the plaintext to a temp file. Neither the encrypted bytes nor the // decrypted database is ever held whole in memory; a snapshot database // can be large. - blobReader, err := blobgen.NewReader(reader, identities...) + blobReader, err := v.newSnapshotDBReader(reader, identities) if err != nil { - return nil, "", fmt.Errorf("creating decryption reader: %w", err) + return nil, "", err } defer func() { _ = blobReader.Close() }() diff --git a/internal/vaultik/restore_wrong_key_test.go b/internal/vaultik/restore_wrong_key_test.go new file mode 100644 index 0000000..05d88ba --- /dev/null +++ b/internal/vaultik/restore_wrong_key_test.go @@ -0,0 +1,161 @@ +package vaultik_test + +import ( + "bytes" + "context" + "io" + "path" + "path/filepath" + "testing" + + "filippo.io/age" + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/blobgen" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestWrongPrivateKeyError checks that restore and deep verify, given a +// valid private key the backup was not encrypted to, fail with one plain +// sentence that names where the key was configured. +func TestWrongPrivateKeyError(t *testing.T) { + t.Parallel() + + ctx := context.Background() + store := NewMockStorer() + + const snapshotID = "test-host_2026-01-01T00:00:00Z" + + remoteKey := snapshot.RemoteSnapshotKey(snapshotID) + + manifest, err := snapshot.EncodeManifest( + &snapshot.Manifest{SnapshotID: remoteKey}, 3) + require.NoError(t, err) + require.NoError(t, store.Put(ctx, + "metadata/"+remoteKey+"/manifest.json.zst", bytes.NewReader(manifest))) + + // The database is encrypted to the test recipient only. + var db bytes.Buffer + + writer, err := blobgen.NewWriter(&db, 1, []string{testAgePublicKey}) + require.NoError(t, err) + + _, err = writer.Write([]byte("snapshot database")) + require.NoError(t, err) + require.NoError(t, writer.Close()) + require.NoError(t, store.Put(ctx, + "metadata/"+remoteKey+"/db.zst.age", &db)) + + otherKey, err := age.GenerateX25519Identity() + require.NoError(t, err) + + v := &vaultik.Vaultik{ + Config: &config.Config{AgeSecretKey: otherKey.String()}, + Storage: store, + Fs: afero.NewMemMapFs(), + Stdout: io.Discard, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + v.SetContext(ctx) + + // A Config built directly has no recorded source, so the error names + // the config-file field. + const want = "cannot decrypt this snapshot: the private key in " + + "age_secret_key is not one of the keys the backup was encrypted to" + + err = v.Restore(&vaultik.RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: t.TempDir(), + }) + require.EqualError(t, err, want) + + err = v.RunDeepVerify(snapshotID, &vaultik.VerifyOptions{Deep: true}) + require.EqualError(t, err, want) +} + +// TestWrongPrivateKeyForBlobError backs up a file, then backs it up again +// from an empty local index with a second recipient added. The second +// snapshot reuses the stored blob, which stays encrypted to the first +// recipient only. With only the added key configured, restore and deep +// verify read the database but fail on the blob with one plain sentence +// that names where the key was configured. +func TestWrongPrivateKeyForBlobError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "source") + dataPath := filepath.Join(dataDir, "data.bin") + storeDir := t.TempDir() + secondDBPath := filepath.Join(tempDir, "second.sqlite") + + chunkSize := int64(64 * 1024) + maxBlobSize := int64(512 * 1024) + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, dataPath, + bytesPattern("key-", int(chunkSize)), 0o644)) + + ctx := context.Background() + + runFileStorageBackup(ctx, t, fs, dataDir, storeDir, + filepath.Join(tempDir, "first.sqlite"), chunkSize, maxBlobSize) + + env := setupDedupBackupEnv( + ctx, t, fs, storeDir, secondDBPath, chunkSize, maxBlobSize) + + defer func() { _ = env.db.Close() }() + + addedKey, err := age.GenerateX25519Identity() + require.NoError(t, err) + + env.cfg.AgeRecipients = append(env.cfg.AgeRecipients, + addedKey.Recipient().String()) + + snapshotID, result := runDedupSnapshot(ctx, t, env.sm, env.makeScanner(), + env.cfg.Hostname, "second", dataDir, secondDBPath) + require.Zero(t, result.BlobsUploaded, + "the second backup should reuse the stored blob") + + require.NoError(t, env.db.Close()) + + blobKeys, err := env.storer.List(ctx, "blobs/") + require.NoError(t, err) + require.Len(t, blobKeys, 1) + + blobHash := path.Base(blobKeys[0]) + + env.cfg.AgeSecretKey = addedKey.String() + + v := &vaultik.Vaultik{ + Config: env.cfg, + Storage: env.storer, + Fs: fs, + Stdout: io.Discard, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + v.SetContext(ctx) + + const sentence = "cannot decrypt this blob: the private key in " + + "age_secret_key is not one of the keys the blob was encrypted to" + + // Restore names the blob by the first 16 characters of its hash. + err = v.Restore(&vaultik.RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: t.TempDir(), + }) + require.EqualError(t, err, "restoring "+dataPath+": downloading blob "+ + blobHash[:16]+": "+sentence+ + " (pass --skip-errors to continue past restore failures)") + + err = v.RunDeepVerify(snapshotID, &vaultik.VerifyOptions{Deep: true}) + require.EqualError(t, err, + "blob "+blobHash+" verification failed: "+sentence) +} diff --git a/internal/vaultik/verify.go b/internal/vaultik/verify.go index c8f9ff5..0284e4a 100644 --- a/internal/vaultik/verify.go +++ b/internal/vaultik/verify.go @@ -264,6 +264,10 @@ func (v *Vaultik) downloadVerifiedSnapshotDB( defer func() { _ = dbReader.Close() }() tdb, err := v.decryptAndLoadDatabase(dbReader, identities) + if errors.Is(err, errWrongPrivateKey) { + return nil, v.deepVerifyFailure(result, opts, err.Error(), err) + } + if err != nil { return nil, v.deepVerifyFailure(result, opts, fmt.Sprintf("failed to decrypt database: %v", err), @@ -348,9 +352,9 @@ func (v *Vaultik) decryptAndLoadDatabase( reader io.ReadCloser, identities []age.Identity, ) (*tempDB, error) { // Decrypt and decompress through the shared blobgen reader. - blobReader, err := blobgen.NewReader(reader, identities...) + blobReader, err := v.newSnapshotDBReader(reader, identities) if err != nil { - return nil, fmt.Errorf("failed to create decryption reader: %w", err) + return nil, err } defer func() { _ = blobReader.Close() }() @@ -423,7 +427,11 @@ func (v *Vaultik) verifyBlob( // the plaintext as it is read. A blob's hash — its remote name — is the // double SHA-256 of that plaintext (see blobgen.DoubleSHA256), not of the // encrypted bytes. - blobReader, err := blobgen.NewReader(reader, identities...) + blobReader, err := v.newBlobReader(reader, identities) + if errors.Is(err, errWrongPrivateKeyForBlob) { + return err + } + if err != nil { return fmt.Errorf("failed to create blob reader: %w", err) } From cdcbe8adfde745a31ddf0ebc6d973fa8c5d67bfb Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 05:30:02 +0100 Subject: [PATCH 110/121] Do not log an upload stopped by Ctrl-C as an error (closes #434) Pressing Ctrl-C or sending SIGTERM during a backup logged the interrupted blob upload as an ERROR before the interrupted message. The upload step now skips that record when the backup's context has been cancelled, whatever error the storage returned. An upload that fails for any other reason is still logged. Model: opus-5-5 --- internal/snapshot/scanner.go | 6 +- internal/snapshot/upload_cancel_log_test.go | 135 ++++++++++++++++++++ 2 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 internal/snapshot/upload_cancel_log_test.go diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index de8db7e..d87fb9a 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -1861,7 +1861,11 @@ func (s *Scanner) uploadBlobIfNeeded( err = s.storage.PutWithProgress(ctx, blobPath, blobWithReader.Reader, finishedBlob.Compressed, progressCallback) if err != nil { - log.Error("Failed to upload blob", "hash", finishedBlob.Hash, "error", err) + // Only an interrupt cancels ctx, and the user is told about it, + // so an upload it stopped is not logged as a storage failure. + if ctx.Err() == nil { + log.Error("Failed to upload blob", "hash", finishedBlob.Hash, "error", err) + } return 0, false, fmt.Errorf("uploading blob to storage: %w", err) } diff --git a/internal/snapshot/upload_cancel_log_test.go b/internal/snapshot/upload_cancel_log_test.go new file mode 100644 index 0000000..1ae97a7 --- /dev/null +++ b/internal/snapshot/upload_cancel_log_test.go @@ -0,0 +1,135 @@ +//nolint:testpackage // exercises the unexported uploadBlobIfNeeded +package snapshot + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "sneak.berlin/go/vaultik/internal/blob" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/ui" +) + +const uploadFailedLogMessage = "Failed to upload blob" + +// uploadTestBlob uploads a small blob through store. +func uploadTestBlob(ctx context.Context, store storage.Storer) error { + data := []byte("blob data") + s := &Scanner{storage: store, ui: ui.NewWithColor(io.Discard, false)} + + _, _, err := s.uploadBlobIfNeeded(ctx, "blobs/test", &blob.WithReader{ + FinishedBlob: &blob.FinishedBlob{ + Hash: "test", + Compressed: int64(len(data)), + }, + Reader: bytes.NewReader(data), + }, time.Now(), &ScanResult{}) + + return err +} + +// captureLog runs fn and returns what the logger wrote to stderr +// meanwhile. The logger writes to the os.Stderr it finds when it is +// initialized, so os.Stderr is pointed at a file first. Not +// parallel-safe: os.Stderr and the logger are process-global. +func captureLog(t *testing.T, fn func()) string { + t.Helper() + + stderrPath := filepath.Join(t.TempDir(), "stderr") + + stderrFile, err := os.Create(stderrPath) //nolint:gosec // G304: test temp path + if err != nil { + t.Fatalf("creating stderr file: %v", err) + } + + previous := os.Stderr + os.Stderr = stderrFile + + log.Initialize(log.Config{}) + + fn() + + os.Stderr = previous + + log.Initialize(log.Config{}) + + _ = stderrFile.Close() + + captured, err := os.ReadFile(stderrPath) //nolint:gosec // G304: test temp path + if err != nil { + t.Fatalf("reading stderr file: %v", err) + } + + return string(captured) +} + +// An upload stopped by Ctrl-C or SIGTERM is not logged as an error; the +// interrupted message is all the user sees. See +// https://git.eeqj.de/sneak/vaultik/issues/434. +// +//nolint:paralleltest // captureLog replaces os.Stderr +func TestInterruptedUploadIsNotLoggedAsError(t *testing.T) { + inner, err := storage.NewFileStorer(t.TempDir()) + if err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + // The user interrupts mid-upload. The injected error does not wrap + // context.Canceled, so only ctx shows why the upload failed. + store := faultstore.New(inner) + store.OnPut = func(string) faultstore.PutAction { + cancel() + + return faultstore.PutFail + } + + var uploadErr error + + stderr := captureLog(t, func() { uploadErr = uploadTestBlob(ctx, store) }) + + if uploadErr == nil { + t.Fatal("expected the upload to fail") + } + + if strings.Contains(stderr, uploadFailedLogMessage) { + t.Errorf("interrupted upload logged as a failure: %q", stderr) + } +} + +// An upload that fails for any other reason is still logged as an error. +// +//nolint:paralleltest // captureLog replaces os.Stderr +func TestFailedUploadIsLoggedAsError(t *testing.T) { + inner, err := storage.NewFileStorer(t.TempDir()) + if err != nil { + t.Fatal(err) + } + + store := faultstore.New(inner) + store.OnPut = func(string) faultstore.PutAction { return faultstore.PutFail } + + var uploadErr error + + stderr := captureLog(t, func() { + uploadErr = uploadTestBlob(context.Background(), store) + }) + + if uploadErr == nil { + t.Fatal("expected the upload to fail") + } + + if !strings.Contains(stderr, uploadFailedLogMessage) { + t.Errorf("failed upload not logged: %q", stderr) + } +} From d6eed26482985009f055d6be3ca86d0cee8b1bd3 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 05:35:53 +0100 Subject: [PATCH 111/121] Report the Go build info version when linker flags set none (closes #422) A binary from go install, the README's first command, reported itself as version dev, a development build, although Go had recorded the tag it was built from. When the linker flags leave the version, commit or commit date unset, they are now filled in from the Go build info, so such a binary reports its tag and counts as a release. Builds through make, script/docker and goreleaser are unchanged. Model: opus-5-5 --- README.md | 35 ++++++--- go.mod | 1 + internal/cli/entry.go | 3 + internal/globals/globals.go | 68 ++++++++++++++++-- internal/globals/globals_test.go | 117 +++++++++++++++++++++++++++++-- script/version | 4 +- 6 files changed, 207 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 002180c..06a531b 100644 --- a/README.md +++ b/README.md @@ -1039,20 +1039,37 @@ is `git describe --tags --always --dirty`, which `script/version` runs for the A `docker build .` of a clone, with no build arguments, runs the same `git describe` (without `--dirty`) on the `.git` in its build context, so it stamps the same value for a clean commit; the build fails if the context carries -`.git` and no version, commit or commit date comes out. A binary built without -git metadata reports `dev`, or `unknown` when `script/docker` or -`script/cibuild` built it outside a git checkout. +`.git` and no version, commit or commit date comes out. `make` outside a git +checkout and `docker build .` without `.git` both stamp `dev`. `script/docker` +and `script/cibuild` stamp `unknown` when they run outside a git checkout. + +A binary built by plain `go install` or `go build` carries no stamped version. +It reports the version Go recorded in it instead: + +- a `go install` of the tag `v1.0.0` → `v1.0.0`. +- a `go build` of an untagged commit → a Go pseudo-version, such as + `v1.0.1-0.20261110231226-0123456789ab`. +- a build where Go recorded no version → `dev`. `goreleaser` stamps a release binary with the tag minus its leading `v`, so the tag `v1.0.0` produces `vaultik 1.0.0`, matching the archive name `vaultik_1.0.0_linux_amd64.tar.gz`. `goreleaser --snapshot` stamps `dev-<12 chars of the commit sha>` rather than inventing the next patch number. -`vaultik version` calls a build a development build when its version is `dev`, -`unknown`, `dev-`, the short commit sha or `--g`, with -or without `-dirty`; only a plain tag, such as `v1.0.0` or `1.0.0`, is a -release. If `script/version` cannot be run at all, `make` stops with an error -instead of building an unversioned binary, and a binary that somehow carries an -empty version string still reports itself as a development build. + +`vaultik version` calls a build a development build when its version is one of +these: + +- `dev` or `unknown`. +- `dev-`. +- the short commit sha. +- `--g`. +- a Go pseudo-version. +- any version with a `-dirty` or `+dirty` suffix. + +Only a plain tag, such as `v1.0.0` or `1.0.0`, is a release. If `script/version` +cannot be run at all, `make` stops with an error instead of building an +unversioned binary. A binary stamped with an empty version reports the version +Go recorded in it; if Go recorded none, it is a development build. ### cutting a release diff --git a/go.mod b/go.mod index 3acb01e..8942241 100644 --- a/go.mod +++ b/go.mod @@ -24,6 +24,7 @@ require ( github.com/stretchr/testify v1.11.1 go.uber.org/dig v1.19.0 go.uber.org/fx v1.24.0 + golang.org/x/mod v0.29.0 golang.org/x/sync v0.18.0 golang.org/x/sys v0.38.0 golang.org/x/term v0.37.0 diff --git a/internal/cli/entry.go b/internal/cli/entry.go index e9d3a6c..8760ba5 100644 --- a/internal/cli/entry.go +++ b/internal/cli/entry.go @@ -21,6 +21,8 @@ const shortCommitLen = 12 const exitCodeInterrupted = 130 // Entry is the main entry point for the CLI application. +// It first calls globals.FillUnsetFromBuildInfo, which fills in the +// version, commit and commit date that the linker flags did not set. // It prints the startup banner to stderr (unless a banner-suppressing // flag is present in os.Args — see bannerSuppressedInArgs), executes the // root cobra command, and routes any returned error through the @@ -33,6 +35,7 @@ const exitCodeInterrupted = 130 // deferred profile writers run before the process ends. See run in // cmd/vaultik/main.go. func Entry() int { + globals.FillUnsetFromBuildInfo() emitStartupBanner(os.Args[1:], os.Stderr) rootCmd := NewRootCommand() diff --git a/internal/globals/globals.go b/internal/globals/globals.go index 984b8a0..017cda0 100644 --- a/internal/globals/globals.go +++ b/internal/globals/globals.go @@ -1,19 +1,24 @@ // Package globals holds application-wide metadata (name, version, -// commit) that is populated at build time via linker flags. +// commit) that is populated at build time via linker flags, or from the +// build info Go records in the binary when the linker flags set none. package globals import ( "regexp" + "runtime/debug" "strings" "time" + + "golang.org/x/mod/module" ) // Appname is the application name, populated from main(). var Appname = "vaultik" //nolint:gochecknoglobals // set via -ldflags at build time // DevVersion is the version a binary reports when it was built without -// git metadata: script/version emits it outside a git checkout, and an -// unstamped `go build` keeps it. goreleaser's snapshot template stamps +// git metadata: script/version emits it outside a git checkout, and a +// binary keeps it when neither its linker flags nor its Go build info +// name a version. goreleaser's snapshot template stamps // it followed by "-" and the commit it was built from. It is // deliberately not a number. const DevVersion = "dev" @@ -32,6 +37,54 @@ var Commit = Unknown //nolint:gochecknoglobals // set via -ldflags at build time // CommitDate is the ISO-8601 date of the commit, populated from main(). var CommitDate = Unknown //nolint:gochecknoglobals // set via -ldflags at build time +// develVersion is the main module version Go records when it cannot +// tell which version it built. +const develVersion = "(devel)" + +// FillUnsetFromBuildInfo applies FillUnset to Version, Commit and +// CommitDate, with the build info of the running binary. +func FillUnsetFromBuildInfo() { + info, ok := debug.ReadBuildInfo() + if !ok { + return + } + + Version, Commit, CommitDate = FillUnset( + info, Version, Commit, CommitDate) +} + +// FillUnset returns version, commit and commitDate. Each one that +// still holds its default ("dev" or empty for the version, "unknown" +// for the others) is replaced by the value Go recorded in info. A +// `go install` of a tag sets no linker flags, but Go records the tag +// as the main module's version. Go records the commit and its time +// only when it builds from a git checkout. The time is cut to a date, +// as the Makefile stamps it. +func FillUnset( + info *debug.BuildInfo, version, commit, commitDate string, +) (string, string, string) { + if (version == "" || version == DevVersion) && + info.Main.Version != "" && info.Main.Version != develVersion { + version = info.Main.Version + } + + for _, s := range info.Settings { + switch s.Key { + case "vcs.revision": + if commit == Unknown { + commit = s.Value + } + case "vcs.time": + t, err := time.Parse(time.RFC3339, s.Value) + if commitDate == Unknown && err == nil { + commitDate = t.UTC().Format(time.DateOnly) + } + } + } + + return version, commit, commitDate +} + // Author identifies the upstream author of vaultik. const Author = "Jeffrey Paul " @@ -68,8 +121,10 @@ func New() (*Globals, error) { // a release. "dev" and goreleaser's snapshot "dev-" count, and so // does what `git describe --tags --always --dirty` gives a make or // docker build of an untagged commit: the bare short commit, or -// tag-N-gHASH on a commit after a tag. Any version ending in "-dirty" -// counts, a modified checkout of a tag ("v1.0.0-dirty") included. +// tag-N-gHASH on a commit after a tag. A Go pseudo-version counts: Go +// records one for a build of an untagged commit without linker flags. +// Any version ending in "-dirty" or "+dirty" counts, a modified +// checkout of a tag ("v1.0.0-dirty", "v1.0.0+dirty") included. // A plain tag such as "v1.0.0" or "1.0.0" is a release. // // The empty string counts too. Nothing that knows its version reports @@ -82,7 +137,8 @@ func New() (*Globals, error) { func IsDevVersion(v string) bool { if v == "" || v == Unknown || v == DevVersion || strings.HasPrefix(v, DevVersion+"-") || - strings.HasSuffix(v, "-dirty") { + strings.HasSuffix(v, "-dirty") || strings.HasSuffix(v, "+dirty") || + module.IsPseudoVersion(v) { return true } diff --git a/internal/globals/globals_test.go b/internal/globals/globals_test.go index fd05e4a..6a82a30 100644 --- a/internal/globals/globals_test.go +++ b/internal/globals/globals_test.go @@ -1,6 +1,7 @@ package globals_test import ( + "runtime/debug" "testing" "sneak.berlin/go/vaultik/internal/globals" @@ -59,12 +60,20 @@ func TestIsDevVersion(t *testing.T) { {"1.0.0-rc.1-12-g877eb2f", true}, // A tagged commit with uncommitted changes is not that tag. {"v1.0.0-dirty", true}, + // What Go records for a build without linker flags: a + // pseudo-version for an untagged commit, "+dirty" for a + // modified checkout. + {"v1.0.0-rc3.0.20261111001226-abcdefabcdef", true}, + {"v0.0.0-20261111001226-abcdefabcdef", true}, + {"v1.0.1-0.20261111001226-abcdefabcdef", true}, + {"v1.0.0+dirty", true}, // What a tagged build produces (goreleaser's .Version strips // the leading "v"; script/version keeps it). {"1.0.0", false}, {"0.1.0", false}, {"1.0.0-rc.1", false}, {"v1.0.0", false}, + {"v1.0.0-rc3", false}, // A release must not be mistaken for a dev build just because // the string happens to contain "dev". {"1.0.0-dev", false}, @@ -86,10 +95,9 @@ func TestIsDevVersion(t *testing.T) { } } -// TestDefaultVersionIsDev pins the linker-flag contract: an unstamped -// binary (no -ldflags at all, which is what `go build ./...` and `go -// install` produce) must report itself as a development build rather -// than as some default release number. +// TestDefaultVersionIsDev pins the default: a binary whose linker flags +// and build info name no version must report itself as a development +// build rather than as some default release number. func TestDefaultVersionIsDev(t *testing.T) { t.Parallel() @@ -98,3 +106,104 @@ func TestDefaultVersionIsDev(t *testing.T) { globals.DevVersion) } } + +// buildInfo returns build info with the given main module version and, +// when revision is not empty, the commit settings Go records for a +// build from a git checkout. +func buildInfo(version, revision string) *debug.BuildInfo { + info := &debug.BuildInfo{ + Main: debug.Module{Path: "sneak.berlin/go/vaultik", Version: version}, + } + + if revision != "" { + info.Settings = []debug.BuildSetting{ + {Key: "vcs.revision", Value: revision}, + {Key: "vcs.time", Value: "2026-11-10T23:12:26Z"}, + } + } + + return info +} + +// TestFillUnset covers a binary from `go install` of a tag, which +// carries no linker flags: it must report the tag. Values the linker +// flags set are kept. +func TestFillUnset(t *testing.T) { + t.Parallel() + + const ( + tag = "v1.0.0-rc3" + rev = "0123456789abcdef0123456789abcdef01234567" + ) + + cases := []struct { + name string + info *debug.BuildInfo + version, commit, date string + wantVersion, wantCommit string + wantDate string + }{ + { + name: "go install of a tag", + info: buildInfo(tag, ""), + version: globals.DevVersion, + commit: globals.Unknown, + date: globals.Unknown, + wantVersion: tag, + wantCommit: globals.Unknown, + wantDate: globals.Unknown, + }, + { + name: "empty version", + info: buildInfo(tag, ""), + version: "", + commit: globals.Unknown, + date: globals.Unknown, + wantVersion: tag, + wantCommit: globals.Unknown, + wantDate: globals.Unknown, + }, + { + name: "go build in a git checkout", + info: buildInfo(tag, rev), + version: globals.DevVersion, + commit: globals.Unknown, + date: globals.Unknown, + wantVersion: tag, + wantCommit: rev, + wantDate: "2026-11-10", + }, + { + name: "Go could not tell the version", + info: buildInfo("(devel)", ""), + version: globals.DevVersion, + commit: globals.Unknown, + date: globals.Unknown, + wantVersion: globals.DevVersion, + wantCommit: globals.Unknown, + wantDate: globals.Unknown, + }, + { + name: "linker flags set", + info: buildInfo(tag, rev), + version: "v1.0.0-rc2-4-gabcdef1", + commit: "abcdef1", + date: "2026-11-01", + wantVersion: "v1.0.0-rc2-4-gabcdef1", + wantCommit: "abcdef1", + wantDate: "2026-11-01", + }, + } + + for _, tc := range cases { + version, commit, date := globals.FillUnset( + tc.info, tc.version, tc.commit, tc.date) + + if version != tc.wantVersion || commit != tc.wantCommit || + date != tc.wantDate { + t.Errorf("%s: got %q, %q, %q; want %q, %q, %q", tc.name, + version, commit, date, + tc.wantVersion, tc.wantCommit, tc.wantDate) + } + } +} diff --git a/script/version b/script/version index 4006043..569ae5d 100755 --- a/script/version +++ b/script/version @@ -11,8 +11,8 @@ # when no tag is reachable, each with a "-dirty" suffix when tracked # files have uncommitted changes. Untracked files are ignored: a stray # scratch file does not change what was compiled. Outside a git checkout -# (release tarball, `go install`), or in one with no commits, it is -# "dev". +# (such as an unpacked release tarball), or in one with no commits, it +# is "dev". # # Nothing here ever invents a version number. set -eu From 7aae6e4ff39856090a81d649ab7128298b2a0c3b Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 05:42:16 +0100 Subject: [PATCH 112/121] Skip vaultik's own index and PID file in a backup (closes #421) The default config backs up the home directory, which holds vaultik's local index and PID file, so a backup stored a torn copy of the index it was writing. The scan now skips the index, its SQLite side files and the PID file whatever the config says, including when index_path or its directory is a symlink. database purge removes the same list of index files. Model: opus-5-5 --- internal/cli/app.go | 5 +- internal/cli/database.go | 19 +++-- internal/cli/database_test.go | 27 ++++++++ ...apshot_create_index_and_lock_files_test.go | 69 +++++++++++++++++++ internal/database/module.go | 11 +++ internal/pidlock/pidlock.go | 15 +++- .../snapshot/index_and_lock_files_test.go | 65 +++++++++++++++++ internal/snapshot/module.go | 45 ++++++++++++ internal/snapshot/module_test.go | 32 +++++++++ internal/snapshot/scanner.go | 24 ++++++- 10 files changed, 295 insertions(+), 17 deletions(-) create mode 100644 internal/cli/entry_snapshot_create_index_and_lock_files_test.go create mode 100644 internal/snapshot/index_and_lock_files_test.go create mode 100644 internal/snapshot/module_test.go diff --git a/internal/cli/app.go b/internal/cli/app.go index bd54f1d..71d1159 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -7,11 +7,9 @@ import ( "context" "errors" "fmt" - "path/filepath" "sync" "time" - "github.com/adrg/xdg" "github.com/spf13/cobra" "go.uber.org/dig" "go.uber.org/fx" @@ -351,8 +349,7 @@ func runVaultikApp( // only one runs at a time; a read-only command runs without it and is not // blocked while a mutator holds the lock (opts.Mode). func RunWithApp(ctx context.Context, opts AppOptions) error { - release, err := acquireLockIfMutating(opts.Mode, - filepath.Join(xdg.DataHome, "vaultik")) + release, err := acquireLockIfMutating(opts.Mode, pidlock.Dir()) if err != nil { return err } diff --git a/internal/cli/database.go b/internal/cli/database.go index 93b330c..93c7911 100644 --- a/internal/cli/database.go +++ b/internal/cli/database.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -100,18 +101,16 @@ Use --force to skip the confirmation prompt.`, } } - // Delete the database file - err = os.Remove(dbPath) - if err != nil { - return fmt.Errorf("failed to delete database: %w", err) + // Delete the database file and its side files. A side file + // may not exist, so only failing to delete the database file + // is an error. + for _, indexFile := range database.IndexFiles(dbPath) { + err = os.Remove(indexFile) + if err != nil && indexFile == dbPath { + return fmt.Errorf("failed to delete database: %w", err) + } } - // Also delete WAL and SHM files if they exist - walPath := dbPath + "-wal" - shmPath := dbPath + "-shm" - _ = os.Remove(walPath) // Ignore errors - files may not exist - _ = os.Remove(shmPath) - out.Infof("Local state database deleted: %s.", dbPath) log.Info("Local state database deleted", "path", dbPath) diff --git a/internal/cli/database_test.go b/internal/cli/database_test.go index be88674..fcb1ba5 100644 --- a/internal/cli/database_test.go +++ b/internal/cli/database_test.go @@ -5,9 +5,11 @@ import ( "errors" "io" "os" + "path/filepath" "strings" "testing" + "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -46,3 +48,28 @@ func TestDatabaseDeleteDeclinedIsError(t *testing.T) { out.String()) } } + +// TestDatabaseDeleteRemovesSideFiles checks that the side files SQLite +// keeps beside the database file are deleted with it. +// +//nolint:paralleltest // mutates the process-global rootFlags +func TestDatabaseDeleteRemovesSideFiles(t *testing.T) { + dir := t.TempDir() + dbPath, cfgPath := seedDatabaseDeleteConfig(t, dir) + + indexFiles := database.IndexFiles(dbPath) + for _, indexFile := range indexFiles { + seedFile(t, dir, filepath.Base(indexFile), "data") + } + + setRootFlags(t, RootFlags{ConfigPath: cfgPath}) + + mustExecute(t, newDatabaseDeleteCommand(), "--force") + + for _, indexFile := range indexFiles { + _, err := os.Stat(indexFile) + if !os.IsNotExist(err) { + t.Errorf("database delete left %s: stat err = %v", indexFile, err) + } + } +} diff --git a/internal/cli/entry_snapshot_create_index_and_lock_files_test.go b/internal/cli/entry_snapshot_create_index_and_lock_files_test.go new file mode 100644 index 0000000..8cf32cc --- /dev/null +++ b/internal/cli/entry_snapshot_create_index_and_lock_files_test.go @@ -0,0 +1,69 @@ +package cli //nolint:testpackage // shares runEntry and the hermetic config helpers + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/adrg/xdg" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestEntrySnapshotCreateSkipsIndexAndLockFiles backs up a directory +// that holds vaultik's index and PID file beside one other file, with no +// exclude pattern set. The summary counts only the other file. See +// https://git.eeqj.de/sneak/vaultik/issues/421. +// +// Not parallel: it replaces os.Args, os.Stdout, os.Stderr and the xdg +// globals. +func TestEntrySnapshotCreateSkipsIndexAndLockFiles(t *testing.T) { + for _, testCase := range []struct { + name string + // linked sets index_path to a symlink outside the backed-up + // directory that points to the index inside it. + linked bool + }{ + {name: "index in the backed-up directory"}, + {name: "index_path links into the backed-up directory", linked: true}, + } { + t.Run(testCase.name, func(t *testing.T) { + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yml") + sourceDir := filepath.Join(dir, "source") + storeDir := filepath.Join(dir, "store") + + indexPath := filepath.Join(sourceDir, "index.sqlite") + + if testCase.linked { + link := filepath.Join(dir, "index.sqlite") + require.NoError(t, os.Symlink(indexPath, link)) + + indexPath = link + } + + contents := fmt.Sprintf(hermeticConfig, + sourceDir, storeDir, indexPath) + require.NoError(t, + os.WriteFile(configPath, []byte(contents), configFileMode)) + require.NoError(t, os.Mkdir(storeDir, 0o750)) + require.NoError(t, os.Mkdir(sourceDir, 0o750)) + require.NoError(t, os.WriteFile( + filepath.Join(sourceDir, "file.txt"), []byte("hello"), 0o600)) + + // The PID file goes in a directory under XDG_DATA_HOME, which + // xdg reads at package init. + t.Setenv("XDG_DATA_HOME", filepath.Join(sourceDir, "data")) + xdg.Reload() + t.Cleanup(xdg.Reload) + + code, stdout, _ := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate) + + require.Equal(t, 0, code) + assert.Contains(t, stdout, + "Files: 1 examined, 1 backed up, 0 unchanged.") + }) + } +} diff --git a/internal/database/module.go b/internal/database/module.go index 65b04b0..b4035be 100644 --- a/internal/database/module.go +++ b/internal/database/module.go @@ -20,6 +20,17 @@ const indexDirPerm = 0o700 // backed-up path and chunk hash and must stay private. const indexFilePerm = 0o600 +// IndexFiles returns the path of the index at indexPath and the paths of +// the side files SQLite keeps beside it while it writes. +func IndexFiles(indexPath string) []string { + return []string{ + indexPath, + indexPath + "-wal", + indexPath + "-shm", + indexPath + "-journal", + } +} + // ensureIndexFileMode makes the index file owner-only before the SQLite // driver opens it: it creates the file 0600 if absent, or chmods an existing // one to 0600. Doing this first matters because SQLite creates its -wal and diff --git a/internal/pidlock/pidlock.go b/internal/pidlock/pidlock.go index 279b233..1d7145b 100644 --- a/internal/pidlock/pidlock.go +++ b/internal/pidlock/pidlock.go @@ -11,6 +11,7 @@ import ( "strconv" "strings" + "github.com/adrg/xdg" "golang.org/x/sys/unix" ) @@ -29,8 +30,20 @@ const ( lockDirPerm = 0o700 // pidFilePerm is the mode for the PID file (owner-only). pidFilePerm = 0o600 + // pidFileName is the name of the PID file in the lock directory. + pidFileName = "vaultik.pid" ) +// Dir returns the directory that holds vaultik's PID file. +func Dir() string { + return filepath.Join(xdg.DataHome, "vaultik") +} + +// Path returns the path of the PID file that Acquire uses in lockDir. +func Path(lockDir string) string { + return filepath.Join(lockDir, pidFileName) +} + // Acquire attempts to acquire a PID lock in the specified directory. // If another process holds the lock, it returns ErrAlreadyRunning with // that process's PID. On success, it writes the current PID to the lock @@ -42,7 +55,7 @@ func Acquire(lockDir string) (*Lock, error) { return nil, fmt.Errorf("creating lock directory: %w", err) } - lockPath := filepath.Join(lockDir, "vaultik.pid") + lockPath := Path(lockDir) // No O_TRUNC: the file may hold the PID of the process that has the // lock, which the error below reports. diff --git a/internal/snapshot/index_and_lock_files_test.go b/internal/snapshot/index_and_lock_files_test.go new file mode 100644 index 0000000..3e07045 --- /dev/null +++ b/internal/snapshot/index_and_lock_files_test.go @@ -0,0 +1,65 @@ +package snapshot_test + +import ( + "context" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/snapshot" +) + +// A backup of the directory that holds vaultik's index and PID file +// stores neither, with no exclude pattern set, and still stores the +// files beside them. See https://git.eeqj.de/sneak/vaultik/issues/421. +func TestScanSkipsIndexAndLockFiles(t *testing.T) { + t.Parallel() + + const dataDir = "/home/user/.local/share/vaultik" + + indexAndLockFiles := append(database.IndexFiles(dataDir+"/index.sqlite"), + dataDir+"/vaultik.pid") + + fs := afero.NewMemMapFs() + for _, p := range append(indexAndLockFiles, dataDir+"/notes.txt") { + require.NoError(t, afero.WriteFile(fs, p, []byte("data"), 0o600)) + } + + db, err := database.NewTestDB() + require.NoError(t, err) + + defer func() { _ = db.Close() }() + + repos := database.NewRepositories(db) + + scanner := snapshot.NewScanner(snapshot.ScannerConfig{ + FS: fs, + ChunkSize: 64 * 1024, + Repositories: repos, + MaxBlobSize: 1024 * 1024, + CompressionLevel: 3, + AgeRecipients: []string{ + "age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p"}, + IndexAndLockFiles: indexAndLockFiles, + }) + require.NotNil(t, scanner) + + ctx := context.Background() + createSnapshotRecord(ctx, t, repos, "test-snapshot") + + result, err := scanner.Scan(ctx, "/home/user", "test-snapshot") + require.NoError(t, err) + + require.Equal(t, 1, result.FilesScanned) + + stored, err := repos.Files.GetByPath(ctx, dataDir+"/notes.txt") + require.NoError(t, err) + require.NotNil(t, stored, "a file beside the index is stored") + + for _, p := range indexAndLockFiles { + f, err := repos.Files.GetByPath(ctx, p) + require.NoError(t, err) + require.Nil(t, f, "%s is not stored", p) + } +} diff --git a/internal/snapshot/module.go b/internal/snapshot/module.go index f83ac07..9edd50b 100644 --- a/internal/snapshot/module.go +++ b/internal/snapshot/module.go @@ -2,11 +2,13 @@ package snapshot import ( "os" + "path/filepath" "github.com/spf13/afero" "go.uber.org/fx" "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/pidlock" "sneak.berlin/go/vaultik/internal/storage" "sneak.berlin/go/vaultik/internal/ui" ) @@ -62,9 +64,52 @@ func provideScannerFactory( EnableProgress: params.EnableProgress, UI: params.UI, Exclude: excludes, + IndexAndLockFiles: indexAndLockFiles(cfg.IndexPath, pidlock.Dir()), SkipErrors: params.SkipErrors, PreviousSnapshotID: params.PreviousSnapshotID, DeviceNumber: params.DeviceNumber, }) } } + +// indexAndLockFiles returns the paths of the index at indexPath, its side +// files and the PID file in lockDir. Symlinks in their directories are +// resolved, as they are in the snapshot's source paths, so the scan finds +// them under the same names. If indexPath is a symlink, the file it points +// to and that file's side files are returned too. +func indexAndLockFiles(indexPath, lockDir string) []string { + paths := append(database.IndexFiles(indexPath), pidlock.Path(lockDir)) + for i, p := range paths { + paths[i] = resolveParentDir(p) + } + + // SQLite writes the file a symlinked index points to and keeps the + // side files beside that file. The database package creates the index + // before the scanner is built, so the link resolves. + index := resolveParentDir(indexPath) + + target, err := filepath.EvalSymlinks(index) + if err == nil && target != index { + paths = append(paths, database.IndexFiles(target)...) + } + + return paths +} + +// resolveParentDir returns the absolute form of path with the symlinks in +// its parent directory resolved. If the parent directory cannot be +// resolved, it returns the absolute form unresolved. If path has no +// absolute form, it returns path. +func resolveParentDir(path string) string { + abs, err := filepath.Abs(path) + if err != nil { + return path + } + + dir, err := filepath.EvalSymlinks(filepath.Dir(abs)) + if err != nil { + return abs + } + + return filepath.Join(dir, filepath.Base(abs)) +} diff --git a/internal/snapshot/module_test.go b/internal/snapshot/module_test.go new file mode 100644 index 0000000..dff9b7f --- /dev/null +++ b/internal/snapshot/module_test.go @@ -0,0 +1,32 @@ +//nolint:testpackage // exercises the unexported indexAndLockFiles helper +package snapshot + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +// The scan walks source paths with symlinks resolved, so vaultik's own +// files are named the same way, or a symlinked home would back them up. +func TestIndexAndLockFilesResolvesSymlinkedDirectory(t *testing.T) { + t.Parallel() + + realDir, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + + link := filepath.Join(t.TempDir(), "link") + require.NoError(t, os.Symlink(realDir, link)) + + paths := indexAndLockFiles(filepath.Join(link, "index.sqlite"), link) + + require.Equal(t, []string{ + filepath.Join(realDir, "index.sqlite"), + filepath.Join(realDir, "index.sqlite-wal"), + filepath.Join(realDir, "index.sqlite-shm"), + filepath.Join(realDir, "index.sqlite-journal"), + filepath.Join(realDir, "vaultik.pid"), + }, paths) +} diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index d87fb9a..624a006 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -67,6 +67,9 @@ type Scanner struct { currentSourcePath string exclude []string // Glob patterns for files/directories to exclude compiledExclude []compiledPattern // Compiled glob patterns + // indexAndLockFiles holds the paths of vaultik's own working files, + // which the scan treats as excluded (ScannerConfig.IndexAndLockFiles). + indexAndLockFiles map[string]struct{} progress *ProgressReporter // skipErrors skips files that cannot be opened or read (logged loudly); // packer, database, encryption, and upload errors still abort the run. @@ -133,6 +136,11 @@ type ScannerConfig struct { EnableProgress bool // Enable the live progress reporter (ETAs, throughput) UI *ui.Writer // Where user-facing scanner messages go; nil = discard Exclude []string // Glob patterns for files/directories to exclude + // IndexAndLockFiles are the absolute paths of vaultik's own working + // files: the index, its side files and the PID file. The scan treats + // them as excluded, whatever Exclude says, since a copy taken while + // they are being written is torn. + IndexAndLockFiles []string // SkipErrors skips files that cannot be opened or read (log loudly but // continue); packer, database, encryption, and upload errors still abort. SkipErrors bool @@ -226,6 +234,11 @@ func NewScanner(cfg ScannerConfig) *Scanner { deviceNumber = deviceNumberFromStat } + indexAndLockFiles := make(map[string]struct{}, len(cfg.IndexAndLockFiles)) + for _, p := range cfg.IndexAndLockFiles { + indexAndLockFiles[filepath.Clean(p)] = struct{}{} + } + return &Scanner{ fs: cfg.FS, chunker: chunker.NewChunker(cfg.ChunkSize), @@ -237,6 +250,7 @@ func NewScanner(cfg ScannerConfig) *Scanner { ageRecipient: strings.Join(cfg.AgeRecipients, ","), exclude: cfg.Exclude, compiledExclude: compiledExclude, + indexAndLockFiles: indexAndLockFiles, progress: progress, skipErrors: cfg.SkipErrors, previousSnapshotID: cfg.PreviousSnapshotID, @@ -2252,8 +2266,9 @@ func (s *Scanner) detectDeletedFiles( // excludedOrInExcludedDir reports whether filePath, which is at or // beneath rootPath, or any directory between rootPath and it, matches an -// exclude pattern. A pattern such as */.local/share/Trash matches the -// directory but not the files inside it, which the walk skips too. +// exclude pattern or is one of vaultik's own files. A pattern such as +// */.local/share/Trash matches the directory but not the files inside it, +// which the walk skips too. func (s *Scanner) excludedOrInExcludedDir(filePath, rootPath string) bool { for p := filePath; len(p) > len(rootPath); p = filepath.Dir(p) { if s.shouldExclude(p, rootPath) { @@ -2377,9 +2392,14 @@ func doubleStarVariants(pattern string) []string { } // shouldExclude checks if a path should be excluded based on exclude patterns +// or because it is one of vaultik's own working files. // filePath is the full path to the file // rootPath is the root of the backup source directory func (s *Scanner) shouldExclude(filePath, rootPath string) bool { + if _, ok := s.indexAndLockFiles[filePath]; ok { + return true + } + if len(s.compiledExclude) == 0 { return false } From f6df500ba26342d9c71e3f69bd1e10c26c333482 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 06:06:54 +0100 Subject: [PATCH 113/121] Refuse a relative index_path (closes #430) A relative index_path, or VAULTIK_INDEX_PATH, was accepted and resolved against whatever directory vaultik ran in. Loading the config now refuses a relative or empty value, quoting it, with the same wording as the file:// check; ~ is still expanded first. Model: opus-5-5 --- configs/config.example.yml | 1 + internal/cli/config.go | 3 +- internal/config/config.go | 9 +++++ internal/config/config_test.go | 61 ++++++++++++++++++++++++++++++++++ 4 files changed, 73 insertions(+), 1 deletion(-) diff --git a/configs/config.example.yml b/configs/config.example.yml index b23252f..e8fe7b9 100644 --- a/configs/config.example.yml +++ b/configs/config.example.yml @@ -295,6 +295,7 @@ storage_url: "rclone://myremote/path/to/backups" # Path to local SQLite index database # This database tracks file state for incremental backups +# It must be an absolute path; ~ is expanded # Default: the platform data directory, e.g. # macOS: ~/Library/Application Support/vaultik/index.sqlite # Linux: ~/.local/share/vaultik/index.sqlite diff --git a/internal/cli/config.go b/internal/cli/config.go index 806a78a..ccfd944 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -276,7 +276,8 @@ storage_url: "" # Hostname used in snapshot IDs. Default: system hostname. # hostname: myserver -# Path to the local SQLite index database. +# Path to the local SQLite index database. It must be an absolute path; +# ~ is expanded. # Default: the platform data directory, e.g. # macOS: ~/Library/Application Support/vaultik/index.sqlite # Linux: ~/.local/share/vaultik/index.sqlite diff --git a/internal/config/config.go b/internal/config/config.go index 8b79f88..a615400 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -70,6 +70,9 @@ var ( errFileURLNotAbsolute = errors.New( "a file:// storage_url needs an absolute path, " + "as in file:///path/to/backup") + errIndexPathNotAbsolute = errors.New( + "index_path and VAULTIK_INDEX_PATH need an absolute path, " + + "as in ~/.local/share/vaultik/index.sqlite") errNegativePruneGracePeriod = errors.New( "prune_grace_period must not be negative") errStorageNotConfigured = errors.New( @@ -387,6 +390,8 @@ func Parse(data []byte) (*Config, error) { // create needs a recipient and it checks for one itself // - At least one snapshot must be configured with at least one path // - Storage must be configured (either storage_url or s3.* fields) +// - The index path must be absolute: a relative one would resolve against +// the working directory, so each directory would get its own index // - Chunk size must be at least 1MB // - Blob size limit must be at least the largest chunk the chunker can emit // (chunk_size times chunker.ChunkSizeSpread), so a single-chunk blob never @@ -420,6 +425,10 @@ func (c *Config) Validate() error { return err } + if !filepath.IsAbs(c.IndexPath) { + return fmt.Errorf("%w: %q", errIndexPathNotAbsolute, c.IndexPath) + } + if c.ChunkSize.Int64() < minChunkSize { return errChunkSizeTooSmall } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 8b6f43d..186ea5a 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -165,6 +165,7 @@ func TestValidateBlobSizeLimit(t *testing.T) { AgeRecipients: []string{testSneakAgePublicKey}, Snapshots: map[string]SnapshotConfig{"test": {Paths: []string{"/tmp/src"}}}, StorageURL: "file:///tmp/vaultik-test-store", + IndexPath: "/tmp/vaultik-test-index.sqlite", ChunkSize: chunkSize, BlobSizeLimit: blobLimit, CompressionLevel: 3, @@ -510,6 +511,65 @@ func TestLoadRejectsRelativeFileURL(t *testing.T) { } } +// TestLoadIndexPath checks that a relative index_path fails at load, naming +// the value. Accepted, it would resolve against the working directory, so a +// backup run from another directory would start from an empty index. A path +// starting with ~ is expanded and loads. +func TestLoadIndexPath(t *testing.T) { + t.Parallel() + + home, err := os.UserHomeDir() + if err != nil { + t.Fatalf("home directory: %v", err) + } + + load := func(t *testing.T, indexPath string) (*Config, error) { + t.Helper() + + data := "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file:///tmp/vaultik-test-storage\n" + + "index_path: " + indexPath + "\n" + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(data), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) + } + + return Load(path) + } + + t.Run("relative path is rejected", func(t *testing.T) { + t.Parallel() + + _, err := load(t, "relative/index.sqlite") + if !errors.Is(err, errIndexPathNotAbsolute) { + t.Fatalf("Load() error = %v, want errIndexPathNotAbsolute", err) + } + + if !strings.Contains(err.Error(), `"relative/index.sqlite"`) { + t.Errorf("error %q does not name the value", err.Error()) + } + }) + + t.Run("path starting with ~ is expanded", func(t *testing.T) { + t.Parallel() + + cfg, err := load(t, "~/vaultik/index.sqlite") + if err != nil { + t.Fatalf("Load() unexpected error: %v", err) + } + + want := filepath.Join(home, "vaultik", "index.sqlite") + if cfg.IndexPath != want { + t.Errorf("IndexPath = %q, want %q", cfg.IndexPath, want) + } + }) +} + // TestValidateAgeRecipients checks that recipients are parsed at config load // (a bad entry fails immediately, not mid-backup) and that no invalid entry — // least of all a pasted secret key — is echoed in the error. An empty list @@ -522,6 +582,7 @@ func TestValidateAgeRecipients(t *testing.T) { AgeRecipients: recipients, Snapshots: map[string]SnapshotConfig{"test": {Paths: []string{"/tmp/src"}}}, StorageURL: "file:///tmp/vaultik-test-store", + IndexPath: "/tmp/vaultik-test-index.sqlite", ChunkSize: Size(10 * 1024 * 1024), BlobSizeLimit: Size(10 * 1024 * 1024 * 1024), CompressionLevel: 3, From e8ab13b526da872a24d0d8ee4ec53c1d87eff37b Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 06:42:45 +0100 Subject: [PATCH 114/121] Name the setting and value when a size setting does not parse (closes #429) A non-numeric chunk_size or blob_size_limit failed with an error that named neither the setting nor the value. Every size setting now fails at load with its name and the quoted value, for example chunk_size: "banana" is not a size; use a number of bytes or a unit such as 10MB. A value too large for a size says so, with the setting name. Model: opus-5-5 --- internal/cli/config_test.go | 2 +- internal/config/config.go | 8 ++- internal/config/keys.go | 16 +++-- internal/config/size.go | 88 +++++++++++++++++++++---- internal/config/size_test.go | 120 +++++++++++++++++++++++++++++++++++ 5 files changed, 214 insertions(+), 20 deletions(-) create mode 100644 internal/config/size_test.go diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go index 6eb45cb..3553c0c 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -252,7 +252,7 @@ func TestConfigSetKeepsFileThatWouldNotLoad(t *testing.T) { {configWithoutRecipients, "snapshots.home.paths", "/srv", "into []string"}, {configWithoutRecipients, "chunk_size", "fast", - "invalid size format"}, + `chunk_size: "fast" is not a size`}, // Values of the right type that fail validation. {configWithoutRecipients, "compression_level", "99", "compression_level must be between 1 and 19"}, diff --git a/internal/config/config.go b/internal/config/config.go index a615400..c04e464 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -290,7 +290,8 @@ func Load(path string) (*Config, error) { } // Parse reads YAML config data as Load does, without validating it. It -// refuses a key that no setting has, applies default values for optional +// refuses a key that no setting has and a size setting whose value is not a +// size, naming the setting. It applies default values for optional // fields, fills in ${...} references using smartconfig, and expands ~ in // paths. func Parse(data []byte) (*Config, error) { @@ -315,8 +316,9 @@ func Parse(data []byte) (*Config, error) { return nil, fmt.Errorf("failed to load config file: %w", err) } - // A ${...} reference can bring in keys that are not in the file. - err = checkFilledKeys(sc.Data()) + // A ${...} reference can bring in keys that are not in the file, and + // is the value of a size setting only once it is filled in. + err = checkFilledConfig(sc.Data()) if err != nil { return nil, err } diff --git a/internal/config/keys.go b/internal/config/keys.go index 8e51543..b9ff171 100644 --- a/internal/config/keys.go +++ b/internal/config/keys.go @@ -129,10 +129,11 @@ func checkKeys(node *yaml.Node, typ reflect.Type, path string, return nil } -// checkFilledKeys is checkKeys for data, the config after smartconfig has -// filled in its ${...} references. A key that a reference brings in is not -// in the file, and the copy that Encode makes has no line numbers. -func checkFilledKeys(data map[string]any) error { +// checkFilledConfig checks data, the config after smartconfig has filled in +// its ${...} references: its keys with checkKeys, then its size settings +// with checkSizes. A key that a reference brings in is not in the file, and +// the copy that Encode makes has no line numbers. +func checkFilledConfig(data map[string]any) error { var filled yaml.Node err := filled.Encode(data) @@ -140,8 +141,13 @@ func checkFilledKeys(data map[string]any) error { return fmt.Errorf("failed to marshal config data: %w", err) } - return checkKeys(&filled, reflect.TypeFor[Config](), "", + err = checkKeys(&filled, reflect.TypeFor[Config](), "", map[*yaml.Node]bool{}, map[nodeAndType]bool{}) + if err != nil { + return err + } + + return checkSizes(&filled, nil) } // checkMappingKeys is checkKeys for a map. diff --git a/internal/config/size.go b/internal/config/size.go index 23b77b6..12cc5b0 100644 --- a/internal/config/size.go +++ b/internal/config/size.go @@ -4,13 +4,20 @@ import ( "errors" "fmt" "math" + "reflect" + "slices" + "strconv" + "strings" "github.com/dustin/go-humanize" + "gopkg.in/yaml.v3" ) var ( errSizeType = errors.New("size must be a number or string") errSizeTooLarge = errors.New("size exceeds maximum supported value") + errNotASize = errors.New( + "is not a size; use a number of bytes or a unit such as 10MB") ) // Size represents a byte size that can be specified in configuration files. @@ -32,6 +39,15 @@ func (s *Size) UnmarshalYAML(unmarshal func(any) error) error { return nil } + // A number too large for an int64 decodes as a float64. Its text can be + // 1e+20, which is not a size string. + var floatVal float64 + + err = unmarshal(&floatVal) + if err == nil && floatVal > math.MaxInt64 { + return errSizeTooLarge + } + // Try to unmarshal as string var strVal string @@ -40,17 +56,66 @@ func (s *Size) UnmarshalYAML(unmarshal func(any) error) error { return errSizeType } - // Parse the string using go-humanize - bytes, err := humanize.ParseBytes(strVal) + size, err := ParseSize(strVal) if err != nil { - return fmt.Errorf("invalid size format: %w", err) + return err } - if bytes > math.MaxInt64 { - return fmt.Errorf("%w: %s", errSizeTooLarge, strVal) + *s = size + + return nil +} + +// checkSizes returns an error naming the first size setting in node whose +// value is not a size. node is the config, or the part of it at the dotted +// keys, after smartconfig has filled in its ${...} references. +func checkSizes(node *yaml.Node, keys []string) error { + typ, err := SettingType(keys) + if err != nil { + // Unknown keys are refused before this check, so keys is in one of + // two places. The env section holds no settings. A value of the + // wrong shape, such as a map given for hostname or inside exclude, + // is reported later by the YAML decoder. + return nil //nolint:nilerr // not an error here } - *s = Size(bytes) + if typ == reflect.TypeFor[Size]() { + var size Size + + err = node.Decode(&size) + if err != nil { + return fmt.Errorf("%s: %w", strings.Join(keys, "."), err) + } + + return nil + } + + switch node.Kind { + case yaml.DocumentNode: + for _, child := range node.Content { + err = checkSizes(child, keys) + if err != nil { + return err + } + } + case yaml.MappingNode: + for i := 0; i+1 < len(node.Content); i += 2 { + err = checkSizes(node.Content[i+1], + slices.Concat(keys, []string{node.Content[i].Value})) + if err != nil { + return err + } + } + case yaml.SequenceNode: + for i, child := range node.Content { + err = checkSizes(child, slices.Concat(keys, []string{strconv.Itoa(i)})) + if err != nil { + return err + } + } + case yaml.ScalarNode, yaml.AliasNode: + // A scalar holds no settings, and the filled config has no aliases. + } return nil } @@ -70,16 +135,17 @@ func (s Size) String() string { return humanize.Bytes(uint64(s)) } -// ParseSize parses a size string into a Size value +// ParseSize parses a size string, such as "10MB", into a Size value. An +// error quotes s. func ParseSize(s string) (Size, error) { - bytes, err := humanize.ParseBytes(s) + bytes, err := humanize.ParseBigBytes(s) if err != nil { - return 0, fmt.Errorf("invalid size format: %w", err) + return 0, fmt.Errorf("%q %w", s, errNotASize) } - if bytes > math.MaxInt64 { + if !bytes.IsInt64() { return 0, fmt.Errorf("%w: %s", errSizeTooLarge, s) } - return Size(bytes), nil + return Size(bytes.Int64()), nil } diff --git a/internal/config/size_test.go b/internal/config/size_test.go new file mode 100644 index 0000000..5265ed4 --- /dev/null +++ b/internal/config/size_test.go @@ -0,0 +1,120 @@ +package config //nolint:testpackage // checks errNotASize and errSizeTooLarge + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// TestParseRefusesValueThatIsNotASize checks that a size setting whose +// value is not a size fails the parse with an error naming the setting and +// quoting the value, also when a ${...} reference fills the value in. +func TestParseRefusesValueThatIsNotASize(t *testing.T) { + t.Parallel() + + sizePath := filepath.Join(t.TempDir(), "size") + + err := os.WriteFile(sizePath, []byte("lots"), 0o600) + if err != nil { + t.Fatalf("write size: %v", err) + } + + tests := []struct { + name string + yaml string + want string + }{ + {"chunk_size", keysTestConfig + "chunk_size: banana\n", + `chunk_size: "banana" is not a size; ` + + "use a number of bytes or a unit such as 10MB"}, + {"blob_size_limit", keysTestConfig + "blob_size_limit: 10XB\n", + `blob_size_limit: "10XB" is not a size; ` + + "use a number of bytes or a unit such as 10MB"}, + {"s3.part_size", strings.Replace(keysTestConfig, " region:", + " part_size: big\n region:", 1), + `s3.part_size: "big" is not a size; ` + + "use a number of bytes or a unit such as 10MB"}, + {"from a reference", + keysTestConfig + "chunk_size: ${FILE:" + sizePath + "}\n", + `chunk_size: "lots" is not a size; ` + + "use a number of bytes or a unit such as 10MB"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + _, err := Parse([]byte(tt.yaml)) + if !errors.Is(err, errNotASize) { + t.Fatalf("Parse() error = %v, want errNotASize", err) + } + + if err.Error() != tt.want { + t.Errorf("Parse() error = %q, want %q", err.Error(), tt.want) + } + }) + } +} + +// TestParseRefusesSizeTooLarge checks that a size setting whose value is +// too large for a size fails the parse with an error naming the setting. +// YAML reads the second value as a float. +func TestParseRefusesSizeTooLarge(t *testing.T) { + t.Parallel() + + tests := []struct { + value string + want string + }{ + {"100EB", "chunk_size: size exceeds maximum supported value: 100EB"}, + {"99999999999999999999", + "chunk_size: size exceeds maximum supported value"}, + } + + for _, tt := range tests { + t.Run(tt.value, func(t *testing.T) { + t.Parallel() + + _, err := Parse([]byte(keysTestConfig + "chunk_size: " + tt.value + "\n")) + if !errors.Is(err, errSizeTooLarge) { + t.Fatalf("Parse() error = %v, want errSizeTooLarge", err) + } + + if err.Error() != tt.want { + t.Errorf("Parse() error = %q, want %q", err.Error(), tt.want) + } + }) + } +} + +// TestParseAcceptsSizes checks that size settings given as a number of +// bytes, as a unit, and through a ${...} reference still parse. +func TestParseAcceptsSizes(t *testing.T) { + t.Parallel() + + sizePath := filepath.Join(t.TempDir(), "size") + + err := os.WriteFile(sizePath, []byte("20MB"), 0o600) + if err != nil { + t.Fatalf("write size: %v", err) + } + + data := strings.Replace(keysTestConfig, " region:", + " part_size: 6000000\n region:", 1) + + "chunk_size: ${FILE:" + sizePath + "}\n" + + "blob_size_limit: 1GB\n" + + cfg, err := Parse([]byte(data)) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } + + if cfg.ChunkSize != 20_000_000 || cfg.BlobSizeLimit != 1_000_000_000 || + cfg.S3.PartSize != 6_000_000 { + t.Errorf("chunk_size, blob_size_limit, s3.part_size = %d, %d, %d, "+ + "want 20000000, 1000000000, 6000000", + cfg.ChunkSize, cfg.BlobSizeLimit, cfg.S3.PartSize) + } +} From 5f1f8c4f66819ca01fba2a820c10d82e42f5cba8 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 06:48:46 +0100 Subject: [PATCH 115/121] Tell the user to set the S3 keys before an s3:// storage_url (closes #428) config set storage_url to an s3:// URL was refused, without saying why, when s3.access_key_id and s3.secret_access_key were not yet set. The refusal now names both keys and says to set them first. config set still refuses any change that leaves the config unable to load, and clearing a key gets the plain refusal. Model: opus-5-5 --- internal/cli/config.go | 23 ++++++++- internal/cli/config_test.go | 94 +++++++++++++++++++++++++++++++++++++ internal/config/config.go | 17 ++++--- 3 files changed, 127 insertions(+), 7 deletions(-) diff --git a/internal/cli/config.go b/internal/cli/config.go index ccfd944..fe0face 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -49,8 +49,14 @@ var ( errWouldNotLoad = errors.New( "vaultik would not load the config after this change, " + "so the file was not changed") + errSetS3KeysFirst = errors.New( + "set s3.access_key_id and s3.secret_access_key first, " + + "then storage_url") ) +// storageURLKey is the config key that selects the storage backend. +const storageURLKey = "storage_url" + // macOS is the value of runtime.GOOS on macOS. const macOS = "darwin" @@ -513,7 +519,7 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error { err = checkConfigChange(oldData, data, settingData) if err != nil { - return fmt.Errorf("%w: %w", errWouldNotLoad, err) + return wouldNotLoadError(key, err) } err = os.WriteFile(path, data, configFileMode) @@ -537,6 +543,21 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error { return nil } +// wouldNotLoadError returns the refusal of a change to key that vaultik +// would not load for reason. When storage_url moves to s3:// before the S3 +// credentials are set, it says to set them first: they can be set while +// the old storage_url is still in place. +func wouldNotLoadError(key string, reason error) error { + if key == storageURLKey && + (errors.Is(reason, config.ErrS3KeyIDRequired) || + errors.Is(reason, config.ErrS3SecretRequired)) { + return fmt.Errorf("%w: %w; %w", errWouldNotLoad, reason, + errSetS3KeysFirst) + } + + return fmt.Errorf("%w: %w", errWouldNotLoad, reason) +} + // checkConfigChange returns the reason vaultik would not load newData, the // config after a change, if the change brings that failure in. If oldData, // the config before it, loads, the new one must load too. A config that diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go index 3553c0c..1eb657f 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -2,6 +2,7 @@ package cli //nolint:testpackage // exercises unexported yamlPathGet/yamlPathSet import ( "bytes" + "errors" "os" "path/filepath" "strconv" @@ -152,6 +153,21 @@ snapshots: - "~" ` +// testS3URL is an S3 storage_url, which needs credentials to load. +const testS3URL = "s3://bucket/prefix?endpoint=https://s3.example.com" + +// configWithS3Keys loads: its storage_url is testS3URL and both S3 keys are +// set. +const configWithS3Keys = storageURLKey + ": " + testS3URL + ` +s3: + access_key_id: AKIAEXAMPLE + secret_access_key: example-secret +snapshots: + home: + paths: + - "~" +` + // configWithUnsetReference loads only where VAULTIK_TEST_UNSET_SECRET is // set, as a backup job's environment might set it. No test sets it. const configWithUnsetReference = configWithoutRecipients + `s3: @@ -258,6 +274,14 @@ func TestConfigSetKeepsFileThatWouldNotLoad(t *testing.T) { "compression_level must be between 1 and 19"}, {configWithoutRecipients, "chunk_size", "1KB", "chunk_size must be at least 1MB"}, + // An s3:// URL before its credentials names them. + {configWithoutRecipients, storageURLKey, testS3URL, + "s3.access_key_id is required for s3:// URLs; " + + "set s3.access_key_id and s3.secret_access_key first"}, + {configWithoutRecipients + "s3:\n access_key_id: AKIAEXAMPLE\n", + storageURLKey, testS3URL, + "s3.secret_access_key is required for s3:// URLs; " + + "set s3.access_key_id and s3.secret_access_key first"}, // With its reference filled in, the config loads. {levelReference, "blob_size_limit", "1MB", "blob_size_limit must be at least"}, @@ -343,6 +367,76 @@ func TestConfigSetRefusesOnlyItsOwnFailure(t *testing.T) { } } +// TestConfigSetS3KeysBeforeStorageURL checks that the order the refusal +// gives works on a config that loads with a file:// storage_url. +func TestConfigSetS3KeysBeforeStorageURL(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(configWithoutRecipients), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + for _, set := range [][2]string{ + {"s3.access_key_id", "AKIAEXAMPLE"}, + {"s3.secret_access_key", "example-secret"}, + {storageURLKey, testS3URL}, + } { + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, set[0], set[1]) + if err != nil { + t.Fatalf("config set %s: %v", set[0], err) + } + } + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("read config: %v", err) + } + + if !strings.Contains(string(data), storageURLKey+": "+testS3URL) { + t.Errorf("config set storage_url wrote:\n%s", data) + } +} + +// TestConfigSetRefusesClearingS3Key checks that clearing s3.access_key_id on +// a config with an s3:// storage_url is refused without saying to set the +// S3 keys first. That advice is only for a change to storage_url. +func TestConfigSetRefusesClearingS3Key(t *testing.T) { + t.Parallel() + + const key = "s3.access_key_id" + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(configWithS3Keys), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), path, key, "") + if !errors.Is(err, errWouldNotLoad) { + t.Errorf("clearing %s gives error %v, want one saying %q", + key, err, errWouldNotLoad) + } + + if errors.Is(err, errSetS3KeysFirst) { + t.Errorf("clearing %s gives error %v, want one not saying %q", + key, err, errSetS3KeysFirst) + } + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("read config: %v", err) + } + + if string(data) != configWithS3Keys { + t.Errorf("clearing %s changed the file to:\n%s", key, data) + } +} + // TestConfigSetWritesEnvSection checks that config set writes a key under // the top-level env section, whose keys are not settings, on a config that // loads. diff --git a/internal/config/config.go b/internal/config/config.go index c04e464..4f97544 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -79,8 +79,13 @@ var ( "storage not configured; set storage_url or provide s3.endpoint + " + "s3.bucket + credentials") errS3BucketRequired = errors.New("s3.bucket is required (or set storage_url)") - errS3KeyIDRequired = errors.New("s3.access_key_id is required") - errS3SecretRequired = errors.New("s3.secret_access_key is required") +) + +// Validate returns these when S3 storage is configured without its +// credentials. +var ( + ErrS3KeyIDRequired = errors.New("s3.access_key_id is required") + ErrS3SecretRequired = errors.New("s3.secret_access_key is required") ) // expandTilde expands ~ at the start of a path to the user's home directory. @@ -524,11 +529,11 @@ func (c *Config) validateStorage() error { } if c.S3.AccessKeyID == "" { - return errS3KeyIDRequired + return ErrS3KeyIDRequired } if c.S3.SecretAccessKey == "" { - return errS3SecretRequired + return ErrS3SecretRequired } return nil @@ -555,11 +560,11 @@ func (c *Config) validateStorageURL() error { case strings.HasPrefix(c.StorageURL, "s3://"): // S3 storage needs credentials if c.S3.AccessKeyID == "" { - return fmt.Errorf("%w for s3:// URLs", errS3KeyIDRequired) + return fmt.Errorf("%w for s3:// URLs", ErrS3KeyIDRequired) } if c.S3.SecretAccessKey == "" { - return fmt.Errorf("%w for s3:// URLs", errS3SecretRequired) + return fmt.Errorf("%w for s3:// URLs", ErrS3SecretRequired) } return nil From 6a8bb2f389a18e10c1358f08ab6071e2e18fdcc2 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 07:38:11 +0100 Subject: [PATCH 116/121] Print a failed command's error once on stderr (closes #433) A failed command printed its error twice on stderr: as an ERROR log record and as the final ERROR: line the README documents. The command handlers, a restore failure that ends the command and a failed blob upload now log that error at info level or not at all, so without --verbose or --debug only the final line appears. Model: opus-5-5 --- internal/cli/app.go | 2 +- internal/cli/entry.go | 4 + internal/cli/entry_failure_once_test.go | 205 ++++++++++++++++++ .../cli/entry_snapshot_create_prune_test.go | 19 +- internal/cli/info.go | 2 +- internal/cli/prune.go | 2 +- internal/cli/remote.go | 2 +- internal/cli/snapshot.go | 8 +- internal/cli/snapshot_restore.go | 2 +- internal/snapshot/scanner.go | 8 +- internal/snapshot/upload_cancel_log_test.go | 12 +- internal/vaultik/restore.go | 6 +- 12 files changed, 247 insertions(+), 25 deletions(-) create mode 100644 internal/cli/entry_failure_once_test.go diff --git a/internal/cli/app.go b/internal/cli/app.go index 71d1159..35f8e2d 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -337,7 +337,7 @@ func runVaultikApp( }, Mode: mode, }, op, func(err error) { - log.Error(failMsg, "error", err) + log.Info(failMsg, "error", err) ReportErrorf("%s: %v", failMsg, err) }) } diff --git a/internal/cli/entry.go b/internal/cli/entry.go index 8760ba5..d332071 100644 --- a/internal/cli/entry.go +++ b/internal/cli/entry.go @@ -85,6 +85,10 @@ func emitStartupBanner(args []string, w io.Writer) { // 🛑 ERROR: format. Use it from goroutine error paths (where returning // an error to cobra isn't an option) and anywhere else a CLI command // must surface a failure outside the normal RunE return path. +// +// This line is the one report of the failure. A caller that also logs +// the failure logs it at info level, so the record appears only under +// --verbose or --debug and the error is not printed twice. func ReportErrorf(format string, args ...any) { ui.New(os.Stderr).Errorf(format, args...) } diff --git a/internal/cli/entry_failure_once_test.go b/internal/cli/entry_failure_once_test.go new file mode 100644 index 0000000..734f814 --- /dev/null +++ b/internal/cli/entry_failure_once_test.go @@ -0,0 +1,205 @@ +package cli //nolint:testpackage // shares the fixtures and capture helpers + +import ( + "context" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "filippo.io/age" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/ui" +) + +const ( + // errorLinePrefix starts the final line that reports a failed command. + errorLinePrefix = "ERROR: " + + flagVerbose = "--verbose" + cmdRestore = "restore" + + // blobsDir is the directory of a destination store that holds the + // blobs. + blobsDir = "blobs" +) + +// TestEntryFailureIsPrintedOnce runs commands that fail after startup +// against a destination they cannot use. `info` is not among them: it +// cannot fail after startup. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntryFailureIsPrintedOnce(t *testing.T) { + for _, command := range [][]string{ + {cmdSnapshot, cmdCreate}, + {cmdSnapshot, cmdRemove, someSnapshotID}, + {cmdSnapshot, cmdVerify, someSnapshotID}, + {cmdRemote, cmdInfo}, + {cmdPrune, flagJSON}, + } { + for _, verbose := range []bool{false, true} { + name := fmt.Sprintf("%s verbose=%t", strings.Join(command, " "), verbose) + + t.Run(name, func(t *testing.T) { + requireErrorPrintedOnce(t, verbose, append([]string{flagConfig, + writeUnusableDestinationConfig(t)}, command...)...) + }) + } + } +} + +// TestEntryBlobUploadFailureIsPrintedOnce backs up to a destination +// whose blobs directory is a file, so the blob upload fails. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntryBlobUploadFailureIsPrintedOnce(t *testing.T) { + for _, verbose := range []bool{false, true} { + t.Run(fmt.Sprintf("verbose=%t", verbose), func(t *testing.T) { + configPath, storeDir := writeBackupConfig(t) + + require.NoError(t, os.WriteFile( + filepath.Join(storeDir, blobsDir), nil, 0o600)) + + requireErrorPrintedOnce(t, verbose, + flagConfig, configPath, cmdSnapshot, cmdCreate) + }) + } +} + +// TestEntryBlobDownloadFailureIsPrintedOnce backs up, deletes the blobs +// from the destination, and restores, so the blob download fails. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntryBlobDownloadFailureIsPrintedOnce(t *testing.T) { + for _, verbose := range []bool{false, true} { + t.Run(fmt.Sprintf("verbose=%t", verbose), func(t *testing.T) { + configPath, storeDir := writeBackupConfigWithPrivateKey(t) + + code, _, _ := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate) + require.Equal(t, 0, code) + + require.NoError(t, os.RemoveAll(filepath.Join(storeDir, blobsDir))) + + requireErrorPrintedOnce(t, verbose, flagConfig, configPath, + cmdSnapshot, cmdRestore, onlySnapshotID(t, configPath), t.TempDir()) + }) + } +} + +// requireErrorPrintedOnce runs Entry with args, adding --verbose when +// verbose is set. The command must fail, and stderr must carry its error +// once, as the final ERROR: line. A log record carrying the same error +// appears only under --verbose. +func requireErrorPrintedOnce(t *testing.T, verbose bool, args ...string) { + t.Helper() + + if verbose { + args = append(args, flagVerbose) + } + + code, _, stderr := runEntry(t, args...) + require.Equal(t, 1, code) + + errorLine, records := failureOutput(t, stderr) + + if !verbose { + assert.Zero(t, records, + "without --verbose no log record repeats the error:\n%s", stderr) + + return + } + + assert.NotZero(t, records, + "--verbose must keep the log record of %q", errorLine) +} + +// failureOutput requires stderr to hold exactly one ERROR: line and +// returns it, with the number of log records whose error attribute is +// the error that line reports. stderr is a pipe here, so every log +// record is a JSON object on its own line. +func failureOutput(t *testing.T, stderr string) (string, int) { + t.Helper() + + var ( + errorLines []string + records []map[string]any + ) + + for line := range strings.Lines(stderr) { + var record map[string]any + if json.Unmarshal([]byte(line), &record) == nil { + records = append(records, record) + + continue + } + + if strings.Contains(line, errorLinePrefix) { + errorLines = append(errorLines, strings.TrimSpace(line)) + } + } + + require.Len(t, errorLines, 1, + "the error must be printed once as an ERROR: line:\n%s", stderr) + + // An error can run over several lines; the ERROR: line holds the + // first of them. + repeats := 0 + + for _, record := range records { + failure, ok := record["error"].(string) + firstLine, _, _ := strings.Cut(failure, "\n") + + if ok && strings.Contains(errorLines[0], firstLine) { + repeats++ + } + } + + return errorLines[0], repeats +} + +// writeBackupConfigWithPrivateKey builds what writeBackupConfig builds, +// with a generated key pair in place of its recipient. The config also +// holds the private key, so that restore can decrypt the backup. Returns +// the config path and the store directory. +func writeBackupConfigWithPrivateKey(t *testing.T) (string, string) { + t.Helper() + + configPath, storeDir := writeBackupConfig(t) + + identity, err := age.GenerateX25519Identity() + require.NoError(t, err) + + out := ui.NewWithColor(io.Discard, false) + + require.NoError(t, writeConfigSet(out, configPath, + "age_recipients.0", identity.Recipient().String())) + require.NoError(t, writeConfigSet(out, configPath, + "age_secret_key", identity.String())) + + return configPath, storeDir +} + +// onlySnapshotID returns the ID of the one snapshot in the local index +// that writeBackupConfig puts beside the config file. +func onlySnapshotID(t *testing.T, configPath string) string { + t.Helper() + + ctx := context.Background() + + db, err := database.New(ctx, + filepath.Join(filepath.Dir(configPath), "index.sqlite")) + require.NoError(t, err) + + defer func() { require.NoError(t, db.Close()) }() + + backedUp, err := database.NewRepositories(db).Snapshots.GetOnlySnapshot(ctx) + require.NoError(t, err) + + return backedUp.ID.String() +} diff --git a/internal/cli/entry_snapshot_create_prune_test.go b/internal/cli/entry_snapshot_create_prune_test.go index 6f64997..60b0846 100644 --- a/internal/cli/entry_snapshot_create_prune_test.go +++ b/internal/cli/entry_snapshot_create_prune_test.go @@ -61,8 +61,8 @@ func TestEntrySnapshotCreateRejectsKeepNewerThanBeforeBackup(t *testing.T) { // TestEntrySnapshotCreateReportsPostBackupPruneFailure makes the // post-backup prune fail after a good backup, by planting a manifest -// that cannot be decoded, and checks that the failure is reported as the -// prune's and not as a failed snapshot creation. +// that cannot be decoded, and checks that the failure is reported once, +// as the prune's and not as a failed snapshot creation. // //nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals func TestEntrySnapshotCreateReportsPostBackupPruneFailure(t *testing.T) { @@ -83,6 +83,9 @@ func TestEntrySnapshotCreateReportsPostBackupPruneFailure(t *testing.T) { assert.Contains(t, stderr, "Backup completed, but post-backup prune failed") assert.NotContains(t, stderr, "Snapshot creation failed") + _, repeats := failureOutput(t, stderr) + assert.Zero(t, repeats, "no log record may repeat the error:\n%s", stderr) + snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata")) require.NoError(t, err) assert.Len(t, snapshots, 2, @@ -93,7 +96,8 @@ func TestEntrySnapshotCreateReportsPostBackupPruneFailure(t *testing.T) { // empties the source directory, as a volume that is not mounted leaves // its mount point, and runs `snapshot create --prune`. The command exits // non-zero and reports the backup as completed, not as a failed snapshot -// creation. See https://git.eeqj.de/sneak/vaultik/issues/388. +// creation. The error is printed once. See +// https://git.eeqj.de/sneak/vaultik/issues/388. // //nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals func TestEntrySnapshotCreatePruneExitsNonZeroWhenSourceIsEmpty(t *testing.T) { @@ -114,6 +118,9 @@ func TestEntrySnapshotCreatePruneExitsNonZeroWhenSourceIsEmpty(t *testing.T) { "Backup completed, but 1 source path(s) were empty") assert.NotContains(t, stderr, "Snapshot creation failed") + _, repeats := failureOutput(t, stderr) + assert.Zero(t, repeats, "no log record may repeat the error:\n%s", stderr) + snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata")) require.NoError(t, err) assert.Len(t, snapshots, 2, "the older snapshot is kept") @@ -124,7 +131,8 @@ func TestEntrySnapshotCreatePruneExitsNonZeroWhenSourceIsEmpty(t *testing.T) { // directory as a mount point, and runs `snapshot create --prune`, which // does not find it as one. The command exits non-zero, reports the // backup as completed, not as a failed snapshot creation, and keeps the -// older snapshot. See https://git.eeqj.de/sneak/vaultik/issues/395. +// older snapshot. The error is printed once. See +// https://git.eeqj.de/sneak/vaultik/issues/395. // //nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals func TestEntrySnapshotCreatePruneExitsNonZeroWhenMountPointIsMissing( @@ -159,6 +167,9 @@ func TestEntrySnapshotCreatePruneExitsNonZeroWhenMountPointIsMissing( "an earlier snapshot recorded were not found") assert.NotContains(t, stderr, "Snapshot creation failed") + _, repeats := failureOutput(t, stderr) + assert.Zero(t, repeats, "no log record may repeat the error:\n%s", stderr) + snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata")) require.NoError(t, err) assert.Len(t, snapshots, 2, "the older snapshot is kept") diff --git a/internal/cli/info.go b/internal/cli/info.go index 27d40de..5430656 100644 --- a/internal/cli/info.go +++ b/internal/cli/info.go @@ -39,7 +39,7 @@ func NewInfoCommand() *cobra.Command { }, func(v *vaultik.Vaultik) error { return v.ShowInfo() }, func(err error) { - log.Error("Failed to show info", "error", err) + log.Info("Failed to show info", "error", err) ReportErrorf("Failed to show info: %v", err) }) }, diff --git a/internal/cli/prune.go b/internal/cli/prune.go index 6b6843a..6063e7a 100644 --- a/internal/cli/prune.go +++ b/internal/cli/prune.go @@ -60,7 +60,7 @@ referenced.`, }, func(v *vaultik.Vaultik) error { return v.Prune(opts) }, func(err error) { - log.Error("Prune operation failed", "error", err) + log.Info("Prune operation failed", "error", err) ReportErrorf("Prune failed: %v", err) }) }, diff --git a/internal/cli/remote.go b/internal/cli/remote.go index 4bf403f..f46bb26 100644 --- a/internal/cli/remote.go +++ b/internal/cli/remote.go @@ -98,7 +98,7 @@ func newRemoteInfoCommand() *cobra.Command { }, func(v *vaultik.Vaultik) error { return v.RemoteInfo(jsonOutput) }, func(err error) { - log.Error("Failed to get remote info", "error", err) + log.Info("Failed to get remote info", "error", err) ReportErrorf("Failed to get remote info: %v", err) }) }, diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 8996d35..27056fc 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -109,7 +109,7 @@ on Linux), then /etc/vaultik/config.yml.`, return v.CreateSnapshot(opts) }, func(err error) { if errors.Is(err, vaultik.ErrPostBackupPruneFailed) { - log.Error("Post-backup prune failed", "error", err) + log.Info("Post-backup prune failed", "error", err) ReportErrorf("Backup completed, but %v", err) return @@ -118,13 +118,13 @@ on Linux), then /etc/vaultik/config.yml.`, if errors.Is(err, vaultik.ErrFilesUnreadable) || errors.Is(err, vaultik.ErrSourcePathEmpty) || errors.Is(err, vaultik.ErrVolumeNotMounted) { - log.Error("Backup completed with an error", "error", err) + log.Info("Backup completed with an error", "error", err) ReportErrorf("Backup completed, but %v", err) return } - log.Error("Snapshot creation failed", "error", err) + log.Info("Snapshot creation failed", "error", err) ReportErrorf("Snapshot creation failed: %v", err) }) }, @@ -258,7 +258,7 @@ func newSnapshotVerifyCommand() *cobra.Command { return } - log.Error("Verification failed", "error", err) + log.Info("Verification failed", "error", err) ReportErrorf("Verification failed: %v", err) }) }, diff --git a/internal/cli/snapshot_restore.go b/internal/cli/snapshot_restore.go index 8609b90..6e75ffc 100644 --- a/internal/cli/snapshot_restore.go +++ b/internal/cli/snapshot_restore.go @@ -104,7 +104,7 @@ func runRestore(cmd *cobra.Command, args []string, opts *RestoreOptions) error { SkipErrors: rootFlags.SkipErrors, }) }, func(err error) { - log.Error("Restore operation failed", "error", err) + log.Info("Restore operation failed", "error", err) ReportErrorf("Restore failed: %v", err) }) } diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 624a006..9bd36b7 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -1875,10 +1875,12 @@ func (s *Scanner) uploadBlobIfNeeded( err = s.storage.PutWithProgress(ctx, blobPath, blobWithReader.Reader, finishedBlob.Compressed, progressCallback) if err != nil { - // Only an interrupt cancels ctx, and the user is told about it, - // so an upload it stopped is not logged as a storage failure. + // The record is at info level: the returned error ends the backup + // and is printed as its ERROR: line. Only an interrupt cancels + // ctx, and the user is told about it, so an upload it stopped is + // not logged as a storage failure. if ctx.Err() == nil { - log.Error("Failed to upload blob", "hash", finishedBlob.Hash, "error", err) + log.Info("Failed to upload blob", "hash", finishedBlob.Hash, "error", err) } return 0, false, fmt.Errorf("uploading blob to storage: %w", err) diff --git a/internal/snapshot/upload_cancel_log_test.go b/internal/snapshot/upload_cancel_log_test.go index 1ae97a7..f17f5ee 100644 --- a/internal/snapshot/upload_cancel_log_test.go +++ b/internal/snapshot/upload_cancel_log_test.go @@ -37,9 +37,9 @@ func uploadTestBlob(ctx context.Context, store storage.Storer) error { } // captureLog runs fn and returns what the logger wrote to stderr -// meanwhile. The logger writes to the os.Stderr it finds when it is -// initialized, so os.Stderr is pointed at a file first. Not -// parallel-safe: os.Stderr and the logger are process-global. +// meanwhile, at the --verbose level. The logger writes to the os.Stderr +// it finds when it is initialized, so os.Stderr is pointed at a file +// first. Not parallel-safe: os.Stderr and the logger are process-global. func captureLog(t *testing.T, fn func()) string { t.Helper() @@ -53,7 +53,7 @@ func captureLog(t *testing.T, fn func()) string { previous := os.Stderr os.Stderr = stderrFile - log.Initialize(log.Config{}) + log.Initialize(log.Config{Verbose: true}) fn() @@ -107,10 +107,10 @@ func TestInterruptedUploadIsNotLoggedAsError(t *testing.T) { } } -// An upload that fails for any other reason is still logged as an error. +// An upload that fails for any other reason is still logged. // //nolint:paralleltest // captureLog replaces os.Stderr -func TestFailedUploadIsLoggedAsError(t *testing.T) { +func TestFailedUploadIsLogged(t *testing.T) { inner, err := storage.NewFileStorer(t.TempDir()) if err != nil { t.Fatal(err) diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index 928ca20..5f41d96 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -667,19 +667,19 @@ func (v *Vaultik) restoreProgressTick( // handleRestoreFileError records a per-file restore failure: fatal unless // --skip-errors is set, in which case the file is counted as failed and -// dropped from the plan. +// dropped from the plan. A fatal failure is not logged here: the returned +// error is printed as the command's ERROR: line. func (v *Vaultik) handleRestoreFileError( plan *restorePlan, opts *RestoreOptions, result *RestoreResult, file *database.File, fileID types.FileID, err error, ) error { - log.Error("Failed to restore file", "path", file.Path, "error", err) - if !opts.SkipErrors { return fmt.Errorf( "restoring %s: %w (pass --skip-errors to continue past "+ "restore failures)", file.Path, err) } + log.Error("Failed to restore file", "path", file.Path, "error", err) v.UI.Errorf("Failed to restore %s: %v. Skipping (--skip-errors).", v.UI.Path(file.Path.String()), err) From 5ca0d4693267ecc25b6f80866221abb073ad3876 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Wed, 11 Nov 2026 10:58:54 +0100 Subject: [PATCH 117/121] Refuse an exclude pattern that does not compile when the config loads (closes #455) An exclude pattern that did not compile was skipped with a log warning during the backup, which then stored what it meant to leave out. Config.Validate now refuses such a pattern, global or per snapshot, naming the setting and quoting the pattern. The compile step moves to a new package, internal/exclude, which both the config and the scanner call. Model: opus-5-5 --- internal/config/config.go | 32 ++++++++++--- internal/config/exclude.go | 39 ++++++++++++++++ internal/config/exclude_test.go | 65 +++++++++++++++++++++++++++ internal/exclude/exclude.go | 77 ++++++++++++++++++++++++++++++++ internal/exclude/exclude_test.go | 73 ++++++++++++++++++++++++++++++ internal/snapshot/scanner.go | 77 +++++++------------------------- 6 files changed, 294 insertions(+), 69 deletions(-) create mode 100644 internal/config/exclude.go create mode 100644 internal/config/exclude_test.go create mode 100644 internal/exclude/exclude.go create mode 100644 internal/exclude/exclude_test.go diff --git a/internal/config/config.go b/internal/config/config.go index 4f97544..ba8b259 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -396,6 +396,8 @@ func Parse(data []byte) (*Config, error) { // never the value. An empty list is accepted, because only snapshot // create needs a recipient and it checks for one itself // - At least one snapshot must be configured with at least one path +// - Every exclude pattern, global or in a snapshot, must compile; errors +// name the setting and quote the pattern // - Storage must be configured (either storage_url or s3.* fields) // - The index path must be absolute: a relative one would resolve against // the working directory, so each directory would get its own index @@ -416,18 +418,18 @@ func (c *Config) Validate() error { } } - if len(c.Snapshots) == 0 { - return errNoSnapshots + err := c.validateSnapshots() + if err != nil { + return err } - for name, snap := range c.Snapshots { - if len(snap.Paths) == 0 { - return fmt.Errorf("%w: %q", errSnapshotNoPaths, name) - } + err = c.validateExcludes() + if err != nil { + return err } // Validate storage configuration - err := c.validateStorage() + err = c.validateStorage() if err != nil { return err } @@ -466,6 +468,22 @@ func (c *Config) Validate() error { return nil } +// validateSnapshots refuses a config with no snapshot or with a snapshot +// that has no path. +func (c *Config) validateSnapshots() error { + if len(c.Snapshots) == 0 { + return errNoSnapshots + } + + for name, snap := range c.Snapshots { + if len(snap.Paths) == 0 { + return fmt.Errorf("%w: %q", errSnapshotNoPaths, name) + } + } + + return nil +} + // validateAgeRecipient parses one age_recipients entry with the age library // and returns a value-free error on failure. A recipient string can be // sensitive (an operator may paste a secret key by mistake), so neither the diff --git a/internal/config/exclude.go b/internal/config/exclude.go new file mode 100644 index 0000000..d2271b3 --- /dev/null +++ b/internal/config/exclude.go @@ -0,0 +1,39 @@ +package config + +import ( + "fmt" + + "sneak.berlin/go/vaultik/internal/exclude" +) + +// validateExcludes refuses an exclude pattern, global or in a snapshot, +// that does not compile, naming the setting and quoting the pattern. +func (c *Config) validateExcludes() error { + err := validateExcludeList("exclude", c.Exclude) + if err != nil { + return err + } + + for _, name := range c.SnapshotNames() { + err = validateExcludeList("snapshots."+name+".exclude", + c.Snapshots[name].Exclude) + if err != nil { + return err + } + } + + return nil +} + +// validateExcludeList refuses the first pattern in patterns that does not +// compile. setting is the name of the list, as in "exclude". +func validateExcludeList(setting string, patterns []string) error { + for i, pattern := range patterns { + _, _, err := exclude.Compile(pattern) + if err != nil { + return fmt.Errorf("%s[%d]: %w", setting, i, err) + } + } + + return nil +} diff --git a/internal/config/exclude_test.go b/internal/config/exclude_test.go new file mode 100644 index 0000000..8a3e0d4 --- /dev/null +++ b/internal/config/exclude_test.go @@ -0,0 +1,65 @@ +package config_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "sneak.berlin/go/vaultik/internal/config" +) + +// TestLoadRefusesBadExcludePattern checks that an exclude pattern that does +// not compile, global or in a snapshot, fails at load with the setting and +// the pattern named, rather than the backup storing what it meant to leave +// out. +func TestLoadRefusesBadExcludePattern(t *testing.T) { + t.Parallel() + + const storage = "storage_url: file:///tmp/vaultik-test-storage\n" + + tests := []struct { + name string + config string + wantErr string + }{ + { + name: "global", + config: "exclude: ['*.tmp', '.cache', 'build[']\n" + + "snapshots:\n" + + " home:\n" + + " paths: [/tmp/vaultik-test-source]\n" + storage, + wantErr: `exclude[2]: "build[" is not a valid exclude pattern`, + }, + { + name: "snapshot", + config: "snapshots:\n" + + " home:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + " exclude: ['/a/**/x[']\n" + storage, + wantErr: `snapshots.home.exclude[0]: "/a/**/x[" is not a valid exclude pattern`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(tt.config), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) + } + + _, err = config.Load(path) + if err == nil { + t.Fatalf("Load() returned nil, want an error containing %q", tt.wantErr) + } + + if !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("Load() error = %q, want it to contain %q", err, tt.wantErr) + } + }) + } +} diff --git a/internal/exclude/exclude.go b/internal/exclude/exclude.go new file mode 100644 index 0000000..e386cc9 --- /dev/null +++ b/internal/exclude/exclude.go @@ -0,0 +1,77 @@ +// Package exclude compiles exclude patterns into globs. +package exclude + +import ( + "errors" + "fmt" + "strings" + + "github.com/gobwas/glob" +) + +var errBadExcludePattern = errors.New("is not a valid exclude pattern") + +// Compile compiles one exclude pattern into the globs that match it. +// anchored reports whether the pattern matches only from the root of the +// source directory. An empty pattern yields no globs. Config.Validate and +// the scanner both compile patterns with it, so a pattern that loads is one +// the scanner can use. +func Compile(pattern string) ([]glob.Glob, bool, error) { + if pattern == "" { + return nil, false, nil + } + + // A leading "/" anchors the pattern to the source directory. + trimmed, anchored := strings.CutPrefix(pattern, "/") + + // A trailing "/" marks a directory and is not matched. + trimmed = strings.TrimSuffix(trimmed, "/") + + // A leading "**/" demands a "/" before the name and so misses an + // entry directly under the source path. It means "at every depth", + // which is what an unanchored pattern already does, so drop the + // prefix and match unanchored: as in gitignore, "**/x" and + // "/**/x" then also match a top-level "x". + if rest, found := strings.CutPrefix(trimmed, "**/"); found { + trimmed = rest + anchored = false + } + + // Likewise "/**/" inside a pattern demands two slashes, so + // "a/**/*.log" misses "a/x.log". As in gitignore it stands for + // zero or more directories, so also compile the pattern with it + // made a single "/". The glob library's {a,b} is no help: with a + // "**" inside it in mid-pattern, it misses paths it should match. + var globs []glob.Glob + + for _, variant := range doubleStarVariants(trimmed) { + g, err := glob.Compile(variant, '/') + if err != nil { + return nil, false, fmt.Errorf("%q %w: %w", + pattern, errBadExcludePattern, err) + } + + globs = append(globs, g) + } + + return globs, anchored, nil +} + +// doubleStarVariants returns pattern once for every way of keeping each +// "/**/" in it or making it a single "/". +func doubleStarVariants(pattern string) []string { + const doubleStar = "/**/" + + before, after, found := strings.Cut(pattern, doubleStar) + if !found { + return []string{pattern} + } + + var variants []string + + for _, rest := range doubleStarVariants(after) { + variants = append(variants, before+doubleStar+rest, before+"/"+rest) + } + + return variants +} diff --git a/internal/exclude/exclude_test.go b/internal/exclude/exclude_test.go new file mode 100644 index 0000000..a49b657 --- /dev/null +++ b/internal/exclude/exclude_test.go @@ -0,0 +1,73 @@ +package exclude_test + +import ( + "slices" + "strings" + "testing" + + "github.com/gobwas/glob" + "sneak.berlin/go/vaultik/internal/exclude" +) + +// TestCompile checks the error, the anchoring and the globs that Compile +// returns for one exclude pattern. +func TestCompile(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + pattern string + wantErr string + wantAnchored bool + // wantMatches lists paths that one of the globs must match. When + // it is empty, Compile must return no globs. + wantMatches []string + }{ + {name: "does not compile", pattern: "build[", + wantErr: `"build[" is not a valid exclude pattern`}, + {name: "empty", pattern: ""}, + {name: "leading slash anchors", pattern: "/build", + wantAnchored: true, wantMatches: []string{"build"}}, + {name: "double star after the slash clears anchoring", + pattern: "/**/build", wantMatches: []string{"build"}}, + {name: "double star in the middle", pattern: "a/**/*.log", + wantMatches: []string{"a/x.log", "a/b/x.log"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + globs, anchored, err := exclude.Compile(tt.pattern) + if tt.wantErr == "" && err != nil { + t.Fatalf("Compile(%q) error = %v, want none", tt.pattern, err) + } + + if tt.wantErr != "" && + (err == nil || !strings.HasPrefix(err.Error(), tt.wantErr)) { + t.Fatalf("Compile(%q) error = %v, want one starting with %q", + tt.pattern, err, tt.wantErr) + } + + if anchored != tt.wantAnchored { + t.Errorf("Compile(%q) anchored = %t, want %t", + tt.pattern, anchored, tt.wantAnchored) + } + + if len(tt.wantMatches) == 0 && len(globs) != 0 { + t.Errorf("Compile(%q) returned %d globs, want none", + tt.pattern, len(globs)) + } + + for _, path := range tt.wantMatches { + matched := slices.ContainsFunc(globs, func(g glob.Glob) bool { + return g.Match(path) + }) + if !matched { + t.Errorf("Compile(%q) globs do not match %q", + tt.pattern, path) + } + } + }) + } +} diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 9bd36b7..7cc6ea3 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -20,6 +20,7 @@ import ( "sneak.berlin/go/vaultik/internal/blob" "sneak.berlin/go/vaultik/internal/chunker" "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/exclude" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/storage" "sneak.berlin/go/vaultik/internal/types" @@ -221,8 +222,12 @@ func NewScanner(cfg ScannerConfig) *Scanner { progress = NewProgressReporter() } - // Compile exclude patterns - compiledExclude := compileExcludePatterns(cfg.Exclude) + compiledExclude, err := compileExcludePatterns(cfg.Exclude) + if err != nil { + log.Error("Failed to compile exclude patterns", "error", err) + + return nil + } uiw := cfg.UI if uiw == nil { @@ -2318,51 +2323,18 @@ func wrapPermissionError(path string, err error) error { "with --skip-errors to continue past unreadable files)", path, err) } -// compileExcludePatterns compiles the exclude patterns into glob matchers -func compileExcludePatterns(patterns []string) []compiledPattern { +// compileExcludePatterns compiles the exclude patterns into glob matchers. +// Config.Validate has already refused a pattern that does not compile. +func compileExcludePatterns(patterns []string) ([]compiledPattern, error) { var compiled []compiledPattern for _, p := range patterns { - if p == "" { - continue + globs, anchored, err := exclude.Compile(p) + if err != nil { + return nil, err } - // Check if pattern is anchored (starts with /) - anchored := strings.HasPrefix(p, "/") - - pattern := p - if anchored { - pattern = p[1:] // Remove leading / - } - - // Remove trailing slash if present (directory indicator) - pattern = strings.TrimSuffix(pattern, "/") - - // A leading "**/" demands a "/" before the name and so misses an - // entry directly under the source path. It means "at every depth", - // which is what an unanchored pattern already does, so drop the - // prefix and match unanchored: as in gitignore, "**/x" and - // "/**/x" then also match a top-level "x". - if rest, found := strings.CutPrefix(pattern, "**/"); found { - pattern = rest - anchored = false - } - - // Likewise "/**/" inside a pattern demands two slashes, so - // "a/**/*.log" misses "a/x.log". As in gitignore it stands for - // zero or more directories, so also compile the pattern with it - // made a single "/". The glob library's {a,b} is no help: with a - // "**" inside it in mid-pattern, it misses paths it should match. - for _, variant := range doubleStarVariants(pattern) { - // For patterns without path separators, we need to match them as components - // e.g., ".git" should match ".git" anywhere in the path - g, err := glob.Compile(variant, '/') - if err != nil { - log.Warn("Invalid exclude pattern, skipping", "pattern", p, "error", err) - - break - } - + for _, g := range globs { compiled = append(compiled, compiledPattern{ pattern: g, anchored: anchored, @@ -2371,26 +2343,7 @@ func compileExcludePatterns(patterns []string) []compiledPattern { } } - return compiled -} - -// doubleStarVariants returns pattern once for every way of keeping each -// "/**/" in it or making it a single "/". -func doubleStarVariants(pattern string) []string { - const doubleStar = "/**/" - - before, after, found := strings.Cut(pattern, doubleStar) - if !found { - return []string{pattern} - } - - var variants []string - - for _, rest := range doubleStarVariants(after) { - variants = append(variants, before+doubleStar+rest, before+"/"+rest) - } - - return variants + return compiled, nil } // shouldExclude checks if a path should be excluded based on exclude patterns From 1df6867cd4e7b14e199f05289e4c3d23feb1f479 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Fri, 13 Nov 2026 23:01:16 +0100 Subject: [PATCH 118/121] Add snapshot files to list a snapshot's files without restoring it (closes #435) `vaultik snapshot files [path] [--json]` downloads and decrypts the snapshot database, as restore does, and prints mode, size, modification time and path for every file at or under the path. A path that matches nothing is an error. It needs the private key. The mode is in Go's file-mode notation, which the README spells out. The table quotes a path that holds a non-printable character. Named `files` because `ls` is already the alias of `snapshot list`. The missing-key error no longer says "for restore", since this command and deep verify return it too. The README opening now states the private-key rule first. Model: opus-5-5 --- README.md | 89 +++++++--- docs/REPOSTRUCTURE.md | 26 ++- internal/cli/app.go | 11 +- internal/cli/entry_snapshot_files_test.go | 47 ++++++ internal/cli/entry_test.go | 2 +- internal/cli/snapshot.go | 43 +++++ internal/database/database.go | 21 +-- internal/database/snapshots.go | 9 +- internal/ui/ui.go | 16 +- internal/vaultik/blob_fetch.go | 3 +- internal/vaultik/restore.go | 52 +++--- internal/vaultik/snapshot_files.go | 115 +++++++++++++ internal/vaultik/snapshot_files_test.go | 197 ++++++++++++++++++++++ internal/vaultik/snapshot_list.go | 3 +- 14 files changed, 552 insertions(+), 82 deletions(-) create mode 100644 internal/cli/entry_snapshot_files_test.go create mode 100644 internal/vaultik/snapshot_files.go create mode 100644 internal/vaultik/snapshot_files_test.go diff --git a/README.md b/README.md index 06a531b..9879211 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ `vaultik` is an incremental backup tool written in Go. It encrypts data using an `age` public key and uploads each encrypted blob directly to a remote -S3-compatible object store. It requires no private keys, secrets, or credentials -(other than those required to PUT to encrypted object storage, such as S3 API -keys) stored on the backed-up system. +S3-compatible object store. The backed-up system never needs the private key. A +backup needs only the public key and the credentials to write to the object +store, such as S3 API keys. ## quickstart @@ -171,6 +171,7 @@ vaultik [--config ] config get vaultik [--config ] config set vaultik [--config ] snapshot create [snapshot-names...] [--cron] [--prune] [--keep-newer-than ] vaultik [--config ] snapshot list [--json] # alias: ls +vaultik [--config ] snapshot files [path] [--json] vaultik [--config ] snapshot verify [--deep] [--json] vaultik [--config ] snapshot purge [--keep-latest | --older-than ] [--snapshot ...] [--force] vaultik [--config ] snapshot remove [--dry-run] [--force] [--local-only] [--json] # alias: rm @@ -223,12 +224,24 @@ the backup can delete it; the new snapshot then cannot be restored. `remote nuke` deletes everything regardless. To not depend on the grace period, give each host or user its own prefix (or directory) on the destination. -Read-only commands — `info`, `snapshot list`, `snapshot verify`, and -`remote info` — do not take the lock and are never blocked, so they run even -while a backup is in progress. `snapshot restore` does not take the lock either: -it writes only to the target directory you name, not the local index or the -destination store. `config`, `database delete`, `completion`, and `version` do -not take the lock. +These read-only commands do not take the lock, so they are never blocked, even +while a backup is in progress: + +- `info` +- `snapshot list` +- `snapshot files` +- `snapshot verify` +- `remote info` + +`snapshot restore` does not take the lock either: it writes only to the target +directory you name, not the local index or the destination store. + +These commands do not take the lock either: + +- `config` +- `database delete` +- `completion` +- `version` ### stdout and stderr @@ -261,9 +274,9 @@ work as written. ### environment variables - `VAULTIK_AGE_SECRET_KEY`: Age private key for decryption (required for - `snapshot restore` and `snapshot verify --deep`). May hold the whole - `age-keygen` file — comments and every identity in it are accepted. Set it - from the file, e.g. + `snapshot restore`, `snapshot files` and `snapshot verify --deep`). May hold + the whole `age-keygen` file — comments and every identity in it are accepted. + Set it from the file, e.g. `export VAULTIK_AGE_SECRET_KEY="$(cat vaultik_backup_private_key.txt)"`, so the key is not typed into your shell history. - `VAULTIK_CONFIG`: Path to config file (overridden by `--config`) @@ -408,6 +421,26 @@ point behind. truncated listing all go to stderr through the logger, so stdout stays a single parseable document. +**`snapshot files`**: List the files in a snapshot without restoring it. Each +row of the table shows mode, size in bytes, modification time and path, sorted +by path. + +- Requires `VAULTIK_AGE_SECRET_KEY`: the file list is only in the snapshot's + encrypted database, which the command downloads and decrypts. +- Accepts the same identifiers as `snapshot restore`. +- An optional path limits the list to that path and what is under it. A path + that matches nothing in the snapshot is an error. +- `--json`: Output an array of objects with `path`, `size`, `mode` and `mtime`. +- In the table, a path that holds a newline or another non-printable character + is shown in double quotes, with that character escaped, as in `"a\nb"`. +- The mode is in Go's file-mode notation, in the table and in `--json`. Letters + before the nine permission characters show the file type and any special bit, + as in `dtrwxrwxrwx` for a sticky directory. These letters differ from `ls -l`: + - `L`: a symbolic link, which `ls -l` shows as `l`. + - `u`: setuid, which `ls -l` shows as `s` in place of the owner's `x`. + - `g`: setgid, which `ls -l` shows as `s` in place of the group's `x`. + - `t`: sticky, which `ls -l` shows as `t` in place of the others' `x`. + **`snapshot verify`**: Verify snapshot integrity. - Default (shallow): checks that every blob the manifest lists is present in @@ -722,7 +755,7 @@ annotated example also lives in | Field | Default | Description | | -------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `age_recipients` | (required by `snapshot create`) | Age public keys for encryption. Other commands run without one, so a machine that only restores can leave it empty | -| `age_secret_key` | (unset) | Age private key for decryption (`snapshot restore`, `snapshot verify --deep`). Setting it in the config file places the private key on the backed-up host, defeating the public-key-only design (see "why" above). Prefer the `VAULTIK_AGE_SECRET_KEY` environment variable, supplied only on the machine you restore from. | +| `age_secret_key` | (unset) | Age private key for decryption (`snapshot restore`, `snapshot files`, `snapshot verify --deep`). Setting it in the config file places the private key on the backed-up host, defeating the public-key-only design (see "why" above). Prefer the `VAULTIK_AGE_SECRET_KEY` environment variable, supplied only on the machine you restore from. | | `snapshots` | (required) | Named snapshot definitions with paths and excludes | | `storage_url` | | Storage backend URL (`s3://`, `file://`, `rclone://`) | | `s3.*` | | Legacy S3 configuration (endpoint, bucket, credentials) | @@ -839,15 +872,27 @@ environment variable is unset (https://no-color.org/). `database delete`. - **The data a command exists to produce** is written plain, with no marker and no color, because a marker would corrupt a table or a parsed document. This - covers the `version`, `info`, `remote info` and `snapshot verify` reports, the - `snapshot list` table, `config get` values, and every `--json` document. - `--quiet` silences the human reports and tables (`version`, `info`, - `remote info`, `snapshot verify`, `snapshot list`) but never the - machine-consumed `config get` value or the `--json` documents, which a script - depends on. The confirmation prompts of `database delete`, `prune`, - `snapshot purge` and `snapshot remove`, each with what it asks to delete, are - also written this way and always shown: they are an interactive exchange the - operator must see. + covers the report or table of each of these commands: + - `version` + - `info` + - `remote info` + - `snapshot verify` + - `snapshot list` + - `snapshot files` + + `config get` values and every `--json` document are written plain too. + `--quiet` silences the reports and tables above, but never a `config get` + value or a `--json` document, which a script depends on. + + These commands write their confirmation prompt plain too, with what it asks + to delete: + - `database delete` + - `prune` + - `snapshot purge` + - `snapshot remove` + + `--quiet` never silences these prompts: each is an interactive exchange the + operator must see. `internal/ui` writes to stdout; it is the output the user asked for. The exceptions are the startup banner and the error a failed command ends with, diff --git a/docs/REPOSTRUCTURE.md b/docs/REPOSTRUCTURE.md index 81f34c9..856d63f 100644 --- a/docs/REPOSTRUCTURE.md +++ b/docs/REPOSTRUCTURE.md @@ -265,15 +265,23 @@ so an operator can weigh them rather than discover them. blob holds hundreds of chunks, so individual chunk lengths are not visible in the blob's size; lowering the limit toward the chunk size begins to expose them. -4. **Decrypted data on local disk.** Several commands stage plaintext under - `$TMPDIR`: `snapshot restore` writes decrypted blobs under - `vaultik-blobcache-*/` (no size cap) and the decrypted metadata database at - `vaultik-restore-*/snapshot.db`; `verify --deep` writes that database at - `vaultik-verify-*/snapshot.db`; `snapshot create` keeps a plaintext copy of - the index at `vaultik-snapshot-*/snapshot.db`. These files are created `0600` - and removed on success, but a `kill -9` or a power loss leaves them behind — - delete any leftover `vaultik-*` directory under `$TMPDIR` by hand. `$TMPDIR` - should be trusted to the same degree as the restore target. +4. **Decrypted data on local disk.** These commands stage plaintext under + `$TMPDIR`: + - `snapshot restore`: decrypted blobs under `vaultik-blobcache-*/`, with no + size cap, and the decrypted metadata database at + `vaultik-restore-*/snapshot.db`. + - `snapshot files`: the decrypted metadata database at + `vaultik-restore-*/snapshot.db`. + - `verify --deep`: the decrypted metadata database at + `vaultik-verify-*/snapshot.db`. + - `snapshot create`: a plaintext copy of the index at + `vaultik-snapshot-*/snapshot.db`. + + These files are created `0600` and removed on success, but a `kill -9` or a + power loss leaves them behind — delete any leftover `vaultik-*` directory + under `$TMPDIR` by hand. `$TMPDIR` should be trusted to the same degree as + the restore target. + 5. **Store permissions differ per command.** The backed-up host needs only PUT to run `snapshot create`: it writes blobs and metadata and neither reads nor deletes them. Other commands need more — `snapshot verify`, diff --git a/internal/cli/app.go b/internal/cli/app.go index 35f8e2d..e264bc8 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -38,10 +38,11 @@ const ( // prune, remote nuke) write the local index or the remote store. They // hold the PID lock so that at most one runs at a time. mutating lockMode = iota - // readOnly commands (info, snapshot list, snapshot verify, remote info, - // snapshot restore) do not write the local index or the remote store, - // so they run without the lock and are never blocked by a running - // mutator. restore writes only to the target directory it is given. + // readOnly commands (info, snapshot list, snapshot files, snapshot + // verify, remote info, snapshot restore) do not write the local index + // or the remote store, so they run without the lock and are never + // blocked by a running mutator. restore writes only to the target + // directory it is given. readOnly ) @@ -310,7 +311,7 @@ func RunOperation( } // runVaultikApp runs the standard single-operation command lifecycle -// shared by the snapshot list/purge/remove and remote nuke subcommands: +// shared by the snapshot list/files/purge/remove and remote nuke subcommands: // resolve the config, then run op against the Vaultik instance through // RunOperation, reporting a failure prefixed with failMsg on stderr. mode // says whether the command takes the PID lock. jsonOutput marks a command diff --git a/internal/cli/entry_snapshot_files_test.go b/internal/cli/entry_snapshot_files_test.go new file mode 100644 index 0000000..c534f3d --- /dev/null +++ b/internal/cli/entry_snapshot_files_test.go @@ -0,0 +1,47 @@ +package cli //nolint:testpackage // shares runEntry and the backup config helpers + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// cmdFiles is the word of `snapshot files`, used to build argument +// vectors below. +const cmdFiles = "files" + +// TestEntrySnapshotFilesListsOnlyThePath backs up two files and runs +// `snapshot files` with the snapshot ID and the path of one of them, +// which must be the only file listed. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotFilesListsOnlyThePath(t *testing.T) { + configPath, _ := writeBackupConfigWithPrivateKey(t) + + // writeBackupConfig puts file.txt in the source directory beside the + // config file. + sourceDir := filepath.Join(filepath.Dir(configPath), "source") + listed := filepath.Join(sourceDir, "file.txt") + + require.NoError(t, os.WriteFile( + filepath.Join(sourceDir, "other.txt"), []byte("other"), 0o600)) + + code, _, stderr := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate) + require.Equal(t, 0, code, stderr) + + code, stdout, stderr := runEntry(t, flagConfig, configPath, cmdSnapshot, + cmdFiles, onlySnapshotID(t, configPath), listed, flagJSON) + require.Equal(t, 0, code, stderr) + + var entries []vaultik.ListedFile + + require.NoError(t, json.Unmarshal([]byte(stdout), &entries)) + require.Len(t, entries, 1, "only the path given may be listed") + assert.Equal(t, listed, entries[0].Path) +} diff --git a/internal/cli/entry_test.go b/internal/cli/entry_test.go index 60877ed..a2f103d 100644 --- a/internal/cli/entry_test.go +++ b/internal/cli/entry_test.go @@ -48,7 +48,7 @@ func TestCLIEntry(t *testing.T) { } else { // Check snapshot subcommands expectedSubCommands := []string{ - "create", "list", "purge", "verify", "remove", "restore", + "create", "list", "files", "purge", "verify", "remove", "restore", } for _, expected := range expectedSubCommands { found := false diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 27056fc..5fb5278 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -9,6 +9,10 @@ import ( "sneak.berlin/go/vaultik/internal/vaultik" ) +// filesMaxArgs is the maximum positional argument count of +// `snapshot files [path]`. +const filesMaxArgs = 2 + var ( errSnapshotIDRequired = errors.New("snapshot ID required") errWrongArgCount = errors.New("wrong argument count") @@ -52,6 +56,7 @@ func NewSnapshotCommand() *cobra.Command { // Add subcommands cmd.AddCommand(newSnapshotCreateCommand()) cmd.AddCommand(newSnapshotListCommand()) + cmd.AddCommand(newSnapshotFilesCommand()) cmd.AddCommand(newSnapshotPurgeCommand()) cmd.AddCommand(newSnapshotVerifyCommand()) cmd.AddCommand(newSnapshotRemoveCommand()) @@ -172,6 +177,44 @@ func newSnapshotListCommand() *cobra.Command { return cmd } +// newSnapshotFilesCommand creates the 'snapshot files' subcommand +func newSnapshotFilesCommand() *cobra.Command { + var jsonOutput bool + + cmd := &cobra.Command{ + Use: "files [path]", + Short: "List the files in a snapshot", + Long: `Lists the path, size, mode and modification time of every file in a +snapshot, without restoring it. With a path, lists only that path and +what is under it; a path that matches nothing is an error. + +The snapshot may be named by its ID or, on a host with no local index, +by the remote key that 'snapshot list' prints for a remote-only snapshot +(an unambiguous leading part is enough). + +The file list is only in the snapshot's encrypted database, so this +downloads and decrypts it, and requires the age private key in the +VAULTIK_AGE_SECRET_KEY environment variable, as 'snapshot restore' does.`, + Args: cobra.RangeArgs(1, filesMaxArgs), + RunE: func(cmd *cobra.Command, args []string) error { + path := "" + if len(args) == filesMaxArgs { + path = args[1] + } + + return runVaultikApp(cmd, readOnly, jsonOutput, + "Failed to list snapshot files", + func(v *vaultik.Vaultik) error { + return v.ListSnapshotFiles(args[0], path, jsonOutput) + }) + }, + } + + cmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format") + + return cmd +} + // newSnapshotPurgeCommand creates the 'snapshot purge' subcommand func newSnapshotPurgeCommand() *cobra.Command { opts := &vaultik.SnapshotPurgeOptions{} diff --git a/internal/database/database.go b/internal/database/database.go index 5e680c5..8f0ee05 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -219,7 +219,8 @@ func retryOpen(ctx context.Context, path string) (*DB, error) { // errUntrustedSnapshotSchema is returned when a downloaded snapshot // database carries schema objects the real schema never defines, or is -// missing a table the restore and deep-verify queries read. +// missing a table the restore, deep-verify and `snapshot files` queries +// read. var errUntrustedSnapshotSchema = errors.New( "downloaded snapshot database has an untrusted schema") @@ -241,12 +242,12 @@ func snapshotReadOnlyDSN(path string) string { // OpenReadOnly opens an already-materialized SQLite file for read-only // querying of a snapshot database downloaded from the store, used by -// restore and deep verify. Unlike New it never applies schema migrations -// and never writes: the connection is opened read-only with query_only -// and trusted_schema=OFF. It refuses any file whose schema carries a -// trigger, view or virtual table, or lacks an expected table, so a forged -// file cannot redefine what the restore queries return. The caller owns -// the file and must remove it. +// restore, deep verify and `snapshot files`. Unlike New it never applies +// schema migrations and never writes: the connection is opened read-only +// with query_only and trusted_schema=OFF. It refuses any file whose schema +// carries a trigger, view or virtual table, or lacks an expected table, so +// a forged file cannot redefine what the restore queries return. The +// caller owns the file and must remove it. func OpenReadOnly(ctx context.Context, path string) (*DB, error) { conn, err := sql.Open("sqlite", snapshotReadOnlyDSN(path)) if err != nil { @@ -276,9 +277,9 @@ func OpenReadOnly(ctx context.Context, path string) (*DB, error) { // the plain table set the real schema defines. Any trigger, view or // virtual table, or a missing expected table, fails the open. func verifySnapshotSchema(ctx context.Context, conn *sql.DB) error { - // expectedSnapshotTables are the tables the restore and deep-verify - // queries read. A downloaded database missing any of them is not a - // genuine snapshot database and is refused. + // expectedSnapshotTables are the tables the restore, deep-verify and + // `snapshot files` queries read. A downloaded database missing any of + // them is not a genuine snapshot database and is refused. expectedSnapshotTables := []string{ "blob_chunks", "blobs", diff --git a/internal/database/snapshots.go b/internal/database/snapshots.go index 7ada98c..61b97a0 100644 --- a/internal/database/snapshots.go +++ b/internal/database/snapshots.go @@ -238,10 +238,11 @@ func (r *SnapshotRepository) GetByID( // GetOnlySnapshot returns the sole snapshot in an exported per-snapshot // metadata database. The backup path writes each snapshot's database with -// exactly one snapshot row (see cleanSnapshotDB), so restore and deep -// verify expect exactly one. Zero rows return ErrNoSnapshotInDatabase and -// more than one returns ErrMultipleSnapshotsInDatabase; callers treat -// either as a failed identity check on the downloaded database. +// exactly one snapshot row (see cleanSnapshotDB), so restore, deep verify +// and `snapshot files` expect exactly one. Zero rows return +// ErrNoSnapshotInDatabase and more than one returns +// ErrMultipleSnapshotsInDatabase; callers treat either as a failed +// identity check on the downloaded database. func (r *SnapshotRepository) GetOnlySnapshot(ctx context.Context) (*Snapshot, error) { query := ` SELECT id, hostname, vaultik_version, vaultik_git_revision, diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 7a08d53..0584777 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -17,6 +17,9 @@ // Count, Percent) return ANSI-colored strings the caller composes into // the message body. When color is disabled (non-TTY output or NO_COLOR // set) all formatters return plain text. +// +// QuoteUnprintable is the same escaping without colour, for plain tables +// that print paths from the snapshot database. package ui import ( @@ -227,17 +230,17 @@ func (w *Writer) Hex(s string) string { short = s[:hexAbbrevLen] + "..." } - return w.paint(ansiCyan, sanitize(short)) + return w.paint(ansiCyan, QuoteUnprintable(short)) } // Snapshot colorizes a snapshot ID (full, no abbreviation). func (w *Writer) Snapshot(id string) string { - return w.paint(ansiCyan+ansiBold, sanitize(id)) + return w.paint(ansiCyan+ansiBold, QuoteUnprintable(id)) } // Path colorizes a filesystem path. func (w *Writer) Path(p string) string { - return w.paint(ansiBlue, sanitize(p)) + return w.paint(ansiBlue, QuoteUnprintable(p)) } // Size colorizes a byte count using humanize.Bytes. @@ -312,14 +315,15 @@ func (w *Writer) paint(color, s string) string { return color + s + ansiReset } -// sanitize returns s unchanged when every rune in it is printable, and a -// double-quoted, backslash-escaped form (\n, \x1b, …) otherwise. The +// QuoteUnprintable returns s unchanged when every rune in it is printable, +// and a double-quoted, backslash-escaped form (\n, \x1b, …) otherwise. The // string value formatters escape their argument through this before // painting: identifiers, paths and symlink targets they render come from // the snapshot database, which is not trusted, and escaping must happen // before colour is applied — the painted result already contains the // escape codes the raw text would otherwise be indistinguishable from. -func sanitize(s string) string { +// Plain tables call it directly. +func QuoteUnprintable(s string) string { for _, r := range s { if !unicode.IsPrint(r) { return strconv.Quote(s) diff --git a/internal/vaultik/blob_fetch.go b/internal/vaultik/blob_fetch.go index 4a2ccc1..8e7ffdb 100644 --- a/internal/vaultik/blob_fetch.go +++ b/internal/vaultik/blob_fetch.go @@ -160,7 +160,8 @@ func (v *Vaultik) FetchBlob( // Not every backend's reader stops on cancel by itself (the file // backend's does not), and a read stalled on a slow or hung source would // otherwise outlast the shutdown timeout, so the process would exit -// before restore or deep verify removed its decrypted temporary files. +// before restore, deep verify or `snapshot files` removed its decrypted +// temporary files. type closeOnCancelReader struct { io.ReadCloser diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index 5f41d96..8855aeb 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -31,7 +31,7 @@ var ( errPathsNotInSnapshot = errors.New("requested path(s) not in the snapshot") errFilesFailedVerify = errors.New("files failed verification") errDecryptionKeyRequired = errors.New( - "decryption key required for restore\n\n" + + "decryption key required\n\n" + "Set the VAULTIK_AGE_SECRET_KEY environment variable to your " + "age private key file:\n" + " export VAULTIK_AGE_SECRET_KEY=\"$(cat vaultik_backup_private_key.txt)\"") @@ -153,18 +153,7 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error { return fmt.Errorf("downloading snapshot database: %w", err) } - defer func() { - err := tempDB.Close() - if err != nil { - log.Debug("Failed to close temp database", "error", err) - } - // Remove the whole private directory, so the decrypted database - // and any SQLite side files it produced are gone on every path. - err = v.Fs.RemoveAll(tempDir) - if err != nil { - log.Debug("Failed to remove temp database directory", "error", err) - } - }() + defer v.closeSnapshotDB(tempDB, tempDir) repos := database.NewRepositories(tempDB) @@ -325,9 +314,10 @@ func (v *Vaultik) reportUnmatchedPaths(unmatched []string) error { // identity it contains. The value may be a single key line or a whole // age-keygen file with several identities; all of them are returned so // blobgen (via age.Decrypt) can read a blob encrypted to any of their -// recipients. This is the first step of both restore and deep verify, so -// a missing or unparseable key fails before anything is downloaded. The -// error names the configuration source but never the key value. +// recipients. This is the first step of restore, deep verify and +// `snapshot files`, so a missing or unparseable key fails before anything +// is downloaded. The error names the configuration source but never the +// key value. func (v *Vaultik) restoreIdentities() ([]age.Identity, error) { if v.Config.AgeSecretKey == "" { return nil, errDecryptionKeyRequired @@ -880,18 +870,34 @@ func (v *Vaultik) downloadSnapshotDB( return db, tempDir, nil } +// closeSnapshotDB closes a database returned by downloadSnapshotDB and +// removes its private directory, so the decrypted database and any SQLite +// side files it produced are gone. +func (v *Vaultik) closeSnapshotDB(db *database.DB, tempDir string) { + err := db.Close() + if err != nil { + log.Debug("Failed to close temp database", "error", err) + } + + err = v.Fs.RemoveAll(tempDir) + if err != nil { + log.Debug("Failed to remove temp database directory", "error", err) + } +} + // verifySnapshotDBIdentity confirms the decrypted metadata database really // is the snapshot named by remoteKey. age decryption proves the database // is readable, not that the object served at // metadata//db.zst.age is the snapshot that was requested: an // attacker who swaps in another valid db.zst.age (which needs no key -// material) would otherwise redirect restore and deep verify to a -// different snapshot's contents. The exported per-snapshot database holds -// exactly one snapshot row, and a snapshot's remote key is derived from -// that row's ID, so the database is the requested one exactly when its -// sole snapshot hashes back to remoteKey. Comparing the requested -// identifier directly would not do: it may be a remote-key prefix a -// recovery host uses in place of a human snapshot ID it cannot know. +// material) would otherwise redirect restore, deep verify and +// `snapshot files` to a different snapshot's contents. The exported +// per-snapshot database holds exactly one snapshot row, and a snapshot's +// remote key is derived from that row's ID, so the database is the +// requested one exactly when its sole snapshot hashes back to remoteKey. +// Comparing the requested identifier directly would not do: it may be a +// remote-key prefix a recovery host uses in place of a human snapshot ID +// it cannot know. func (v *Vaultik) verifySnapshotDBIdentity( db *database.DB, requested, remoteKey string, ) error { diff --git a/internal/vaultik/snapshot_files.go b/internal/vaultik/snapshot_files.go new file mode 100644 index 0000000..ec4dc46 --- /dev/null +++ b/internal/vaultik/snapshot_files.go @@ -0,0 +1,115 @@ +package vaultik + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "text/tabwriter" + "time" + + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/ui" +) + +// ListedFile is one entry printed by `snapshot files`. Mode is the Go +// file mode string, which shows the entry type and the permission bits +// (for example -rw-r--r-- or drwxr-xr-x). +type ListedFile struct { + Path string `json:"path"` + Size int64 `json:"size"` + Mode string `json:"mode"` + MTime time.Time `json:"mtime"` +} + +// ListSnapshotFiles prints the path, size, mode and modification time of +// every file the snapshot holds at or under path, or of every file when +// path is empty. The file list is only in the snapshot's encrypted +// database, so this downloads and decrypts it as restore does, and needs +// the private key. +func (v *Vaultik) ListSnapshotFiles(snapshotID, path string, jsonOutput bool) error { + identities, err := v.restoreIdentities() + if err != nil { + return err + } + + remoteKey, err := v.resolveSnapshotRemoteKey(snapshotID) + if err != nil { + return err + } + + db, tempDir, err := v.downloadSnapshotDB(snapshotID, remoteKey, identities) + if errors.Is(err, errWrongPrivateKey) { + return err + } + + if err != nil { + return fmt.Errorf("downloading snapshot database: %w", err) + } + + defer v.closeSnapshotDB(db, tempDir) + + repos := database.NewRepositories(db) + + var files []*database.File + + if path == "" { + files, err = repos.Files.ListAll(v.ctx) + } else { + files, err = repos.Files.ListUnderPath(v.ctx, filepath.Clean(path)) + } + + if err != nil { + return fmt.Errorf("listing files: %w", err) + } + + if path != "" && len(files) == 0 { + return fmt.Errorf("%w: %s", errPathsNotInSnapshot, path) + } + + entries := make([]ListedFile, 0, len(files)) + + for _, file := range files { + entries = append(entries, ListedFile{ + Path: file.Path.String(), + Size: file.Size, + Mode: os.FileMode(file.Mode).String(), + MTime: file.MTime, + }) + } + + if jsonOutput { + encoder := json.NewEncoder(v.Stdout) + encoder.SetIndent("", " ") + + return encoder.Encode(entries) + } + + if v.UI.Quiet() { + return nil + } + + return v.printListedFileTable(entries) +} + +// printListedFileTable writes the entries as a plain table to stdout. +func (v *Vaultik) printListedFileTable(entries []ListedFile) error { + w := tabwriter.NewWriter(v.Stdout, 0, 0, tabPadding, ' ', 0) + + _, err := fmt.Fprintln(w, "MODE\tSIZE\tMODIFIED\tPATH") + if err != nil { + return err + } + + for _, entry := range entries { + _, err = fmt.Fprintf(w, "%s\t%d\t%s\t%s\n", + entry.Mode, entry.Size, + entry.MTime.Format(time.RFC3339), ui.QuoteUnprintable(entry.Path)) + if err != nil { + return err + } + } + + return w.Flush() +} diff --git a/internal/vaultik/snapshot_files_test.go b/internal/vaultik/snapshot_files_test.go new file mode 100644 index 0000000..e23eafb --- /dev/null +++ b/internal/vaultik/snapshot_files_test.go @@ -0,0 +1,197 @@ +package vaultik_test + +import ( + "bytes" + "context" + "encoding/json" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/435: +// `snapshot files` lists what a snapshot holds without restoring it. + +// unprintableFileName is a file name holding a newline and an escape +// sequence, which the table must not print raw. +const unprintableFileName = "odd\nname\x1b[31m" + +// backUpForFileListing backs up the fault source tree, plus a file named +// unprintableFileName at its top, and returns a reader whose stdout is +// out, the snapshot ID, and the source directory. +func backUpForFileListing( + t *testing.T, out *bytes.Buffer, +) (*vaultik.Vaultik, string, string) { + t.Helper() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + cfg := faultTestConfig() + + writeFaultSourceTree(t, fs, dataDir) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, unprintableFileName), []byte("odd"), 0o644)) + + store, err := storage.NewFileStorer(t.TempDir()) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + id := fullFaultBackup(ctx, t, fs, store, cfg, + database.NewRepositories(db), dataDir, dbPath, "files") + require.NoError(t, db.Close()) + + v := newReaderVaultik(ctx, cfg, store, nil, fs) + v.Stdout = out + + return v, id, dataDir +} + +func TestSnapshotFilesJSONListsEveryFileWithItsMetadata(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, dataDir := backUpForFileListing(t, &out) + + require.NoError(t, v.ListSnapshotFiles(id, "", true)) + + var entries []vaultik.ListedFile + + require.NoError(t, json.Unmarshal(out.Bytes(), &entries)) + + byPath := make(map[string]vaultik.ListedFile, len(entries)) + for _, entry := range entries { + byPath[entry.Path] = entry + } + + for _, rel := range []string{"small.txt", "a.bin", "sub", "sub/b.bin", "sub/c.bin"} { + path := filepath.Join(dataDir, rel) + + entry, ok := byPath[path] + require.True(t, ok, "%s must be listed", path) + + info, err := afero.NewOsFs().Stat(path) + require.NoError(t, err) + + assert.Equal(t, info.Mode().String(), entry.Mode, path) + assert.True(t, info.ModTime().Equal(entry.MTime), + "%s: mtime %v, listed %v", path, info.ModTime(), entry.MTime) + + if !info.IsDir() { + assert.Equal(t, info.Size(), entry.Size, path) + } + } +} + +func TestSnapshotFilesListsOnlyWhatIsUnderThePath(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, dataDir := backUpForFileListing(t, &out) + + require.NoError(t, v.ListSnapshotFiles(id, filepath.Join(dataDir, "sub"), false)) + + text := out.String() + assert.Contains(t, text, filepath.Join(dataDir, "sub", "b.bin")) + assert.Contains(t, text, filepath.Join(dataDir, "sub", "c.bin")) + assert.NotContains(t, text, filepath.Join(dataDir, "small.txt")) + assert.True(t, strings.HasPrefix(text, "MODE"), "the table must have a header") +} + +// TestSnapshotFilesTableEscapesAnUnprintablePath checks that the table +// prints a path holding a newline and an escape sequence quoted and +// escaped on one row: the newline must not start a forged row, and the +// escape sequence must not reach the terminal. +func TestSnapshotFilesTableEscapesAnUnprintablePath(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, dataDir := backUpForFileListing(t, &out) + + require.NoError(t, v.ListSnapshotFiles(id, "", false)) + + text := out.String() + assert.Contains(t, text, + strconv.Quote(filepath.Join(dataDir, unprintableFileName))) + assert.NotContains(t, text, "\x1b", "no escape byte may reach the output") + + for line := range strings.SplitSeq(text, "\n") { + assert.False(t, strings.HasPrefix(line, "name"), + "the newline in the name must not start a row: %q", line) + } +} + +// TestSnapshotFilesQuietSuppressesTableNotJSON is the --quiet contract +// for `snapshot files`: the table is silenced, but the --json document a +// script depends on is still written. +func TestSnapshotFilesQuietSuppressesTableNotJSON(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, _ := backUpForFileListing(t, &out) + v.UI.SetQuiet(true) + + require.NoError(t, v.ListSnapshotFiles(id, "", false)) + require.Empty(t, out.String(), "the table must be silenced under --quiet") + + require.NoError(t, v.ListSnapshotFiles(id, "", true)) + + var entries []vaultik.ListedFile + + require.NoError(t, json.Unmarshal(out.Bytes(), &entries)) + assert.NotEmpty(t, entries, + "the --json document must still be written under --quiet") +} + +func TestSnapshotFilesFailsOnAPathThatMatchesNothing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, dataDir := backUpForFileListing(t, &out) + missing := filepath.Join(dataDir, "typo.txt") + + err := v.ListSnapshotFiles(id, missing, false) + + require.Error(t, err) + assert.Contains(t, err.Error(), missing, "the error must name the path") + assert.Empty(t, out.String(), "nothing must be printed") +} + +func TestSnapshotFilesRequiresThePrivateKey(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, _ := backUpForFileListing(t, &out) + v.Config.AgeSecretKey = "" + + err := v.ListSnapshotFiles(id, "", false) + + require.Error(t, err) + assert.Contains(t, err.Error(), "VAULTIK_AGE_SECRET_KEY") +} diff --git a/internal/vaultik/snapshot_list.go b/internal/vaultik/snapshot_list.go index 7862e2e..0f2ca48 100644 --- a/internal/vaultik/snapshot_list.go +++ b/internal/vaultik/snapshot_list.go @@ -39,7 +39,8 @@ const maxRemoteOnlyRows = 1000 // manifest reads need throttling. const remoteManifestFetchConcurrency = 8 -// tabPadding is the tabwriter cell padding for the snapshot table. +// tabPadding is the tabwriter cell padding for the `snapshot list` and +// `snapshot files` tables. const tabPadding = 3 // ListSnapshots prints the table of snapshots known to this host: the From d747ddef3a168582eda012a6660daf4645a94600 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Tue, 17 Nov 2026 01:18:19 +0100 Subject: [PATCH 119/121] Let snapshot remove accept a remote-only snapshot's remote key (closes #400) snapshot remove hashed its argument into a remote key, so the remote key that snapshot list shows for a remote-only snapshot never matched. A remote key or a leading part of it is now resolved with resolveSnapshotRemoteKey, as snapshot verify and snapshot restore do. Model: opus-5-5 --- README.md | 10 ++-- internal/cli/snapshot.go | 6 ++- internal/vaultik/remove_snapshot_test.go | 62 ++++++++++++++++++++++++ internal/vaultik/snapshot.go | 49 ++++++++++++++++--- 4 files changed, 114 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 9879211..d6d7601 100644 --- a/README.md +++ b/README.md @@ -468,10 +468,12 @@ destination store. Blobs are NOT touched — deleting blobs requires reading eve remaining remote manifest (the destination store may hold snapshots this host doesn't know about), which is what `vaultik prune` does. The command prints the `vaultik prune` invocation to run as a follow-up only when it removed the -snapshot's metadata from the destination store, and never under `--json`. An ID -that names no snapshot in the local index or on the destination store is an -error; with `--local-only`, the snapshot must be in the local index. Local row -cleanup (files, chunks, blobs the snapshot was the last referrer for) runs +snapshot's metadata from the destination store, and never under `--json`. It +accepts the same identifiers as `snapshot restore`: a snapshot ID, or a +remote-only snapshot's remote key (or an unambiguous leading part of it). An +identifier that names no snapshot in the local index or on the destination store +is an error; with `--local-only`, the snapshot must be in the local index. Local +row cleanup (files, chunks, blobs the snapshot was the last referrer for) runs automatically. If removing the snapshot's metadata from the destination store fails (for example because the store is unreachable, or the local index holds snapshots and the destination answers that it has no `vaultik-destination.txt`), diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 5fb5278..86ac329 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -331,8 +331,10 @@ know about), which is what 'vaultik prune' does. The command prints the 'vaultik prune' invocation to run as a follow-up only when it removed the snapshot's metadata from the destination store, and never under --json. -An ID that names no snapshot in the local index or on the destination -store is an error. +The snapshot may be named by its ID or by its remote key, which +'snapshot list' prints for a remote-only snapshot. An unambiguous +leading part of the key is enough. An identifier that names no snapshot +in the local index or on the destination store is an error. Use --local-only to skip the remote half (e.g. when you want to forget a snapshot locally without touching the destination store); the snapshot diff --git a/internal/vaultik/remove_snapshot_test.go b/internal/vaultik/remove_snapshot_test.go index ea88183..df0f202 100644 --- a/internal/vaultik/remove_snapshot_test.go +++ b/internal/vaultik/remove_snapshot_test.go @@ -472,6 +472,68 @@ func TestRemoveSnapshot_NotInLocalIndex(t *testing.T) { assert.Contains(t, out, "Removed snapshot metadata from remote storage") } +// TestRemoveSnapshot_ByRemoteKey checks that a snapshot only the +// destination store holds can be removed by the remote key that +// `snapshot list` shows for it, or by a leading part of that key. +func TestRemoveSnapshot_ByRemoteKey(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + remoteKey := snapshot.RemoteSnapshotKey("snapshot-001") + + for name, identifier := range map[string]string{ + "full key": remoteKey, + "leading part": remoteKey[:8], + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t) + + result, err := tv.RemoveSnapshot(identifier, + &vaultik.RemoveOptions{Force: true}) + + require.NoError(t, err) + assert.True(t, result.RemoteRemoved) + assert.False(t, store.hasKey(remoteKeyPath("snapshot-001"))) + }) + } +} + +// TestRemoveSnapshot_ByRemoteKeyInLocalIndex checks that a snapshot the +// local index holds, named by its remote key, is removed from the local +// index as well as from the destination store. +func TestRemoveSnapshot_ByRemoteKeyInLocalIndex(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001") + + result, err := tv.RemoveSnapshot(snapshot.RemoteSnapshotKey("snapshot-001"), + &vaultik.RemoveOptions{Force: true}) + + require.NoError(t, err) + assert.True(t, result.RemoteRemoved) + assert.False(t, store.hasKey(remoteKeyPath("snapshot-001"))) + + snap, err := tv.Repositories.Snapshots.GetByID(context.Background(), + "snapshot-001") + require.NoError(t, err) + assert.Nil(t, snap) +} + // TestRemoveSnapshot_NotInLocalIndexDeleteFails checks that removing a // snapshot only the destination store holds fails when its metadata // cannot be deleted there, under --force and under --json: nothing was diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 34c7827..ae95c93 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -1467,7 +1467,8 @@ func (v *Vaultik) RemoveSnapshot( return result, err } - inLocalIndex, err := v.checkSnapshotExists(snapshotID, opts.LocalOnly) + snapshotID, remoteKey, inLocalIndex, err := v.findSnapshotToRemove( + snapshotID, opts.LocalOnly) if err != nil { return result, err } @@ -1498,7 +1499,7 @@ func (v *Vaultik) RemoveSnapshot( } result.RemoteRemoved, err = v.removeSnapshotRemote( - snapshotID, inLocalIndex, markerErr, opts) + snapshotID, remoteKey, inLocalIndex, markerErr, opts) if err != nil { return result, err } @@ -1530,6 +1531,41 @@ func (v *Vaultik) RemoveSnapshot( return result, nil } +// findSnapshotToRemove returns the ID of the snapshot that identifier +// names, its remote key, and whether the local index holds it. A remote +// key, or the leading part of one, is resolved on the destination store; +// when the local index holds the snapshot with that key, its ID is +// returned, so it is removed from both. +func (v *Vaultik) findSnapshotToRemove( + identifier string, localOnly bool, +) (string, string, bool, error) { + if !isRemoteKeyOrPrefix(identifier) || localOnly { + inLocalIndex, err := v.checkSnapshotExists(identifier, localOnly) + + return identifier, snapshot.RemoteSnapshotKey(identifier), + inLocalIndex, err + } + + remoteKey, err := v.resolveSnapshotRemoteKey(identifier) + if err != nil { + return "", "", false, err + } + + localIDs, err := v.localSnapshotIDs() + if err != nil { + return "", "", false, fmt.Errorf( + "looking up snapshot in local index: %w", err) + } + + for _, id := range localIDs { + if snapshot.RemoteSnapshotKey(id) == remoteKey { + return id, remoteKey, true, nil + } + } + + return identifier, remoteKey, false, nil +} + // checkSnapshotExists returns errSnapshotNotFound when the local index // has no row for snapshotID and, unless localOnly is set, the // destination store has no metadata for it either. inLocalIndex reports @@ -1638,8 +1674,8 @@ func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) return true } -// removeSnapshotRemote strips the snapshot's metadata from the -// destination store. It returns true only when the delete finished +// removeSnapshotRemote strips the snapshot's metadata, under remoteKey, +// from the destination store. It returns true only when the delete finished // without an error and removed at least one object; under LocalOnly it // does nothing. markerErr is the result of checkDestinationMarker; when // it is set, nothing is deleted and it is the failure. When the snapshot @@ -1651,7 +1687,7 @@ func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) // (`vaultik prune` never removes snapshot metadata that has its // manifest). func (v *Vaultik) removeSnapshotRemote( - snapshotID string, inLocalIndex bool, markerErr error, + snapshotID, remoteKey string, inLocalIndex bool, markerErr error, opts *RemoveOptions, ) (bool, error) { if opts.LocalOnly { @@ -1665,8 +1701,7 @@ func (v *Vaultik) removeSnapshotRemote( err := markerErr if err == nil { - deleted, err = v.deleteRemoteSnapshotByKey( - snapshot.RemoteSnapshotKey(snapshotID)) + deleted, err = v.deleteRemoteSnapshotByKey(remoteKey) } if err != nil && !inLocalIndex { From 9fedcbeb0af1655ffa7d9905e24153e020330f10 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 19 Nov 2026 09:24:16 +0100 Subject: [PATCH 120/121] Refuse a relative path on an rclone remote of type local (closes #465) rclone resolves a relative path on its local backend against the working directory, so rclone://localfs/srv/backup wrote under whatever directory vaultik ran from. Opening such a destination now fails with an error that shows the absolute form, rclone://localfs//srv/backup. Other remotes keep relative paths, which rclone resolves on the remote. The README says how to write an absolute rclone path. Model: opus-5-5 --- README.md | 6 ++- internal/storage/rclone.go | 23 +++++++++++ internal/storage/rclone_test.go | 73 +++++++++++++++++++++++++++++++++ 3 files changed, 101 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d6d7601..8d9e77e 100644 --- a/README.md +++ b/README.md @@ -602,7 +602,11 @@ only `vaultik-destination.txt` stops such a backup, and only while the local index holds snapshots. **Rclone** (`rclone://remote/path`): Uses rclone's 70+ supported cloud -providers. Requires rclone to be configured separately (`rclone config`). +providers. Requires rclone to be configured separately (`rclone config`). The +path after the remote name is relative: rclone resolves it on the remote, for +example against the login directory on sftp. A second slash makes it absolute, +as in `rclone://remote//srv/backup`. A remote of type `local` needs an absolute +path; a relative one is refused. An upload cut off part-way leaves nothing under the object's name on S3, which shows an object only once its upload has completed, and on the local filesystem diff --git a/internal/storage/rclone.go b/internal/storage/rclone.go index 39413cb..d4d45fc 100644 --- a/internal/storage/rclone.go +++ b/internal/storage/rclone.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "os" + "path/filepath" "strings" "time" @@ -23,6 +24,15 @@ import ( // ErrRemoteNotFound is returned when an rclone remote is not configured. var ErrRemoteNotFound = errors.New("rclone remote not found in config") +// ErrRcloneRelativeLocalPath is returned when the path on an rclone remote +// of type local is relative. rclone would resolve it against the working +// directory, so the destination would move with it. +var ErrRcloneRelativeLocalPath = errors.New( + "the path on an rclone remote of type local must be absolute") + +// rcloneLocalBackend is the type of rclone's local disk backend. +const rcloneLocalBackend = "local" + // RcloneStorer implements Storer using rclone's filesystem abstraction. // This allows vaultik to use any of rclone's 70+ supported storage providers. type RcloneStorer struct { @@ -53,6 +63,19 @@ func NewRcloneStorer(ctx context.Context, remote, path string) (*RcloneStorer, e rclonePath += path } + // A remote rclone cannot find is reported by fs.NewFs below. Only the + // backend of what fs.ParseRemote returns is needed here. + backend, _, _, _, err := fs.ParseRemote(rclonePath) //nolint:dogsled + if err == nil && backend.Name == rcloneLocalBackend && !filepath.IsAbs(path) { + example := path + if example == "" { + example = "path/to/backup" + } + + return nil, fmt.Errorf("%w: use rclone://%s//%s", + ErrRcloneRelativeLocalPath, remote, example) + } + // On S3, Swift and some other remotes rclone keeps a time of its own in // each object's metadata, which costs one request per object to read. // rclone's use_server_modtime setting makes ModTime the time the diff --git a/internal/storage/rclone_test.go b/internal/storage/rclone_test.go index 32ac7a2..9eaf238 100644 --- a/internal/storage/rclone_test.go +++ b/internal/storage/rclone_test.go @@ -436,6 +436,79 @@ func TestNewRcloneStorerReadsRcloneConfigEnv(t *testing.T) { } } +// useRcloneConfig points rclone at a config file holding contents for the +// rest of the test. +func useRcloneConfig(t *testing.T, contents string) { + t.Helper() + + previous := config.GetConfigPath() + + t.Cleanup(func() { _ = config.SetConfigPath(previous) }) + + confFile := filepath.Join(t.TempDir(), "rclone.conf") + + err := os.WriteFile(confFile, []byte(contents), 0o600) + if err != nil { + t.Fatalf("writing rclone config: %v", err) + } + + t.Setenv("RCLONE_CONFIG", confFile) +} + +// TestNewRcloneStorerRefusesRelativeLocalPath checks that a relative path +// on a remote of type local is refused, with the absolute form in the +// error, and that nothing is created under the working directory. rclone +// would otherwise resolve the path against the working directory. +// +//nolint:paralleltest // changes the working directory and the rclone config +func TestNewRcloneStorerRefusesRelativeLocalPath(t *testing.T) { + useRcloneConfig(t, "[localfs]\ntype = local\n") + + workdir := t.TempDir() + t.Chdir(workdir) + + for path, wantInError := range map[string]string{ + "srv/backup": "rclone://localfs//srv/backup", + "": "rclone://localfs//path/to/backup", + } { + _, err := storage.NewRcloneStorer(context.Background(), "localfs", path) + if !errors.Is(err, storage.ErrRcloneRelativeLocalPath) { + t.Errorf("path %q: error = %v, want ErrRcloneRelativeLocalPath", + path, err) + + continue + } + + if !strings.Contains(err.Error(), wantInError) { + t.Errorf("path %q: error %q does not show %q", + path, err, wantInError) + } + } + + entries, err := os.ReadDir(workdir) + if err != nil { + t.Fatalf("reading working directory: %v", err) + } + + if len(entries) != 0 { + t.Errorf("working directory holds %d entries, want none", len(entries)) + } +} + +// TestNewRcloneStorerKeepsRelativePathOnOtherRemotes checks that a relative +// path is accepted on a remote not of type local, where rclone resolves it +// on the remote itself, as sftp does against the login directory. +// +//nolint:paralleltest // changes the process-global rclone config +func TestNewRcloneStorerKeepsRelativePathOnOtherRemotes(t *testing.T) { + useRcloneConfig(t, "[mem]\ntype = memory\n") + + _, err := storage.NewRcloneStorer(context.Background(), "mem", "backups") + if err != nil { + t.Errorf("NewRcloneStorer: %v", err) + } +} + // TestRcloneListStreamOnS3MakesNoRequestPerObject checks that listing an // rclone S3 remote takes each object's time from the listing itself. By // default rclone reads the time it keeps in each object's metadata, one From 5b0927175103738e1a3bbc870a682abd057c9032 Mon Sep 17 00:00:00 2001 From: clawbot <35+clawbot@noreply.example.org> Date: Thu, 19 Nov 2026 09:53:18 +0100 Subject: [PATCH 121/121] Report no device number for a zeroed stat (closes #462) deviceNumberFromStat returned device 0 and true for a stat whose device and inode numbers are both zero. afero's unreleased master gives such a stat for every in-memory file; the pinned v1.15.0 gives none. It now returns false for it, as its comment says, and a test covers both in-memory shapes. Model: opus-5-5 --- internal/snapshot/device_number_test.go | 35 +++++++++++++++++++++++++ internal/snapshot/scanner.go | 7 ++--- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/internal/snapshot/device_number_test.go b/internal/snapshot/device_number_test.go index 85fd8f8..85a074b 100644 --- a/internal/snapshot/device_number_test.go +++ b/internal/snapshot/device_number_test.go @@ -4,8 +4,10 @@ package snapshot import ( "os" "path/filepath" + "syscall" "testing" + "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -38,3 +40,36 @@ func TestDeviceNumberFromStat(t *testing.T) { // /dev is a different filesystem from the temp dir on Linux, macOS and in Docker. assert.NotEqual(t, deviceOf(dir), deviceOf("/dev")) } + +// fileInfoWithStat is a file's info whose Sys returns stat. +type fileInfoWithStat struct { + os.FileInfo + + stat *syscall.Stat_t +} + +func (i fileInfoWithStat) Sys() any { return i.stat } + +// The in-memory test filesystem has no device numbers. The pinned afero +// gives no stat; its unreleased master gives a stat holding only uid, gid +// and size. See https://git.eeqj.de/sneak/vaultik/issues/462. +func TestDeviceNumberFromStatInMemory(t *testing.T) { + t.Parallel() + + fs := afero.NewMemMapFs() + require.NoError(t, afero.WriteFile(fs, "/file.txt", []byte("data"), 0o600)) + + info, err := fs.Stat("/file.txt") + require.NoError(t, err) + + _, ok := deviceNumberFromStat(info) + assert.False(t, ok, "device number read from a file info with no stat") + + zeroed := fileInfoWithStat{ + FileInfo: info, + stat: &syscall.Stat_t{Uid: 1000, Gid: 1000, Size: 4}, + } + + _, ok = deviceNumberFromStat(zeroed) + assert.False(t, ok, "device number read from a stat with no device or inode number") +} diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index 7cc6ea3..a8b3123 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -1438,11 +1438,12 @@ func (s *Scanner) deviceNumberAt(path string) (uint64, bool) { } // deviceNumberFromStat returns the number of the device that holds the -// file info describes, and false when info carries no stat, as from the -// in-memory test filesystem. +// file info describes, and false when info carries no stat from a real +// filesystem. The in-memory test filesystem gives either no stat or one +// whose device and inode numbers are both zero, which no real file has. func deviceNumberFromStat(info os.FileInfo) (uint64, bool) { stat, ok := info.Sys().(*syscall.Stat_t) - if !ok { + if !ok || (stat.Dev == 0 && stat.Ino == 0) { return 0, false }