From cb35bd1a8d64badac013a04a72b6b4ba23226ed0 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Wed, 23 Sep 2026 22:24:05 +0200 Subject: [PATCH 01/61] design: propose the native mirror layout on one shared planner One planner computes the index changes since a destination's last confirmed run for every layout; layouts turn them into operations; a small transport (local, sftp) carries the bytes. The mirror on local and plain sftp moves off rclone, with every displaced version kept in history and every move recorded before it happens. Also records a live bug the planner fixes: a wiped root with upload records still on file is treated as a fresh start, so the next content-addressed push skips everything and reports success. --- design/README.md | 3 + design/native-mirror.md | 586 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 589 insertions(+) create mode 100644 design/native-mirror.md diff --git a/design/README.md b/design/README.md index fa12273..3eca205 100644 --- a/design/README.md +++ b/design/README.md @@ -14,6 +14,9 @@ each time. every supported destination type in play. - [`testbed.md`](testbed.md) — how the reference setup is simulated on one development machine with real commands and no containers. +- [`native-mirror.md`](native-mirror.md) — *proposed*: one planner shared + by every layout, a small transport, and the mirror layout on `local` and + `sftp` without rclone. ## How to use this folder diff --git a/design/native-mirror.md b/design/native-mirror.md new file mode 100644 index 0000000..0f79a24 --- /dev/null +++ b/design/native-mirror.md @@ -0,0 +1,586 @@ +# Native mirror layout: one planner, three layouts, a small transport + +*Proposed, not adopted.* This is step 2 of replacing rclone with squirrel's own +transports. Peer sync dropped rclone in #210. #211 made the mirror's evidence +honest. Step 3 is S3 for the packed and content-addressed layouts. + +## Summary + +Today a mirror push hands the whole job to `rclone copy`. Rclone lists both +sides, compares them, transfers what differs, and moves overwritten files into +`--backup-dir`. This design replaces that for `local` mirrors and plain `sftp` +mirrors. The replacement has three layers: + +1. **Planner**, shared by every layout: the index changes since the + destination's last confirmed run. +2. **Layout**: turns those changes into operations. Content-addressed uploads + an object per hash. Packed adds small content to a pack. Mirror writes the + path and first moves the previous version into history. +3. **Transport**: byte-level access to one destination root (stat, list, get, + put, rename). There is a `local` implementation and an `sftp` one. + +The planner lands first. It is a refactor of the content-addressed and packed +handlers, which already share this logic in duplicated form. It changes no +behaviour except a bug fix it exposes (see "Watermark rule"). The mirror then +plugs in as a third layout. + +## Scope + +**In scope:** + +- the planner refactor; +- the transport, with its local and sftp implementations; +- the mirror layout on `local`, and on `sftp` without `crypt`; +- marker, snapshot ride-along, recover and restore for those destinations. + +**Out of scope, and still on rclone:** + +- **Crypt mirrors, including cloudbox.** They wait for the crypt + byte-compatibility decision (open question 1). In this design, crypt is a + wrapper around a transport. So that decision changes neither the planner nor + the layout. +- **Mirrors on s3, b2 and gcs.** A mirror needs rename, and object stores have + none (see "Transport"). +- **Peer sync.** It keeps its negotiated plan, where the receiver decides. +- **Kopia.** + +In the [reference setup](reference-setup.md), `usb` moves with this work. +`cloudbox` is an encrypted sftp mirror, so it moves when crypt does. + +## What changes for the operator + +- **A push plans from the index.** It sends what the index recorded, not what + a live walk finds. This already holds for the content-addressed and packed + layouts. A file created after the last index run reaches the mirror on the + first push after it gets indexed. +- **A push checks only the paths it plans to write.** Each one gets a single + `Lstat`. Anything found at such a path is moved into `.squirrel-history/` + before the new version lands, whatever it holds. So a remote change can cost + an extra copy in history, never an overwrite. Changes elsewhere on the + destination are found by the verify pass (`verify_every`, extended to + mirrors in the evidence step). +- **Each push leaves a receipt** at `/.squirrel-index/run-`. It is + the same manifest segment the content-addressed and packed layouts write + (see [formats](../docs/src/content/docs/reference/formats.md)). The mirror + stays browsable. The receipts make it verifiable without the index. +- **New reserved directory** `/.squirrel-staging/` holds in-flight + writes. +- **sftp host keys are always verified** (see "Configuration"). +- **`--shallow` is refused for a native mirror.** A push decides from + squirrel's records, confirms each planned path's size and mtime, and moves + whatever is there aside before writing. Its safety comes from that move, not + from a content comparison. Content is checked by hashing the source as it + streams, by the read-back in the evidence step, and by the verify pass. + None of those is optional, so the flag has nothing to switch off. + +## 1. The planner + +`contentAddressedHandler.Push` and `packedHandler.Push` each carry the same +sequence: + +1. indexed-volume check; +2. markers; +3. run allocation; +4. watermark; +5. advance snapshot; +6. delta; +7. finish; +8. ride-along. + +They differ only in their landing evidence (segment or placement map) and in +what they transfer. The planner is that shared sequence, extracted once: + +```go +// pushPlan is what one push must land: the volume's index changes since the +// destination's last confirmed run, and the durability snapshot the push +// advances to once they land. +type pushPlan struct { + volumeID int64 + watermark int64 // last confirmed run; 0 for a fresh destination + delta []store.PathDelta // ListPathDeltaSince(volumeID, watermark) + advance []store.OriginComponent // captured before any transfer +} + +// layout is one destination layout's part of a push. +type layout interface { + // landed reports whether runID left this layout's landing evidence. + landed(ctx context.Context, runID int64) (bool, error) + // translate turns the plan into this layout's operations. It reads + // squirrel's records and writes nothing: a dry run is translate alone. + translate(ctx context.Context, p pushPlan) (operations, error) + // execute performs the operations and records each confirmed one. + execute(ctx context.Context, rep *Report, runID int64, ops operations) error + // seal writes the run's landing evidence once every operation is confirmed. + seal(ctx context.Context, runID int64, p pushPlan) error + // advanceMethod names the evidence the confirmed landing earns. + advanceMethod(ctx context.Context, p pushPlan) (string, error) +} +``` + +One driver runs every layout: + + requireIndexedVolume → markers → begin run → plan → translate → execute → seal → advance → finish → ride-along + +A dry run stops after translate and reports `operations`' summary. Today's +separate `previewDryRun` in each handler becomes that summary. + +### Watermark rule + +This rule is shared by all three layouts: + +1. If there is no successful sync of this (volume, destination), the + watermark is 0. +2. If the last success left its landing evidence at the destination, the + watermark is that run's id. +3. The watermark is also 0 (a fresh start) when all three of these hold: + - the landing evidence is absent; + - the destination root is empty apart from its markers; + - squirrel holds **no upload records** for the destination. +4. In every other case, refuse with `ErrRefused`. The message points at a + fresh root or `squirrel destination reset`. + +Each layout's landing evidence lives at a different place: + +| Layout | Landing evidence | +|---|---| +| content-addressed | `/index/run-` | +| packed | `packs/map-` | +| mirror | `/.squirrel-index/run-` | + +No two layouts share a location, so a destination switched from one layout to +another is refused. + +**The last condition in rule 3 is new, and it fixes a live bug.** Today +`freshStartOnEmptyRoot` checks only that the remote root is empty. +Consider a content-addressed destination whose root was wiped without a +`destination reset`, then re-marked with `--init`: + +1. The next push takes the fresh-start branch. +2. `uploadObjects` skips every content that `remote_objects` still records. +3. It writes a segment mapping paths to objects that no longer exist. +4. The run closes as `success` and advances the durability vector. If the old + fingerprints were verified, it advances as `fingerprint-verified`. + +A throwaway test confirmed this. It ran one push, wiped the fake remote, +re-seeded the marker and ran a second push. The second push reported +`success` with `transferred=0 checked=1`, and the object was absent. Only a +later verify pass would notice. The planner has to fail closed here, because +the mirror's records would repeat the same mistake. + +### Repairs: the planner's second input + +This input arrives with the evidence step. A verify pass that finds a +recorded artifact missing or changed marks that record `lost`. The next +push then plans the record's content again, even though the index didn't +change: + + work = delta since watermark ∪ records marked lost + +Today the content layouts only raise an alarm in this case. With repairs, the +same push that raised the alarm also heals it. + +## 2. Layouts translate changes into operations + +| Layout | Operations from one delta | +|---|---| +| content-addressed | one object upload per present content with no upload record on the destination | +| packed | object uploads for content at or above `pack_threshold`; pack members for the rest | +| mirror | one path write per present path whose live record doesn't hold that content | + +Rows that are `missing`, `offloaded` or `superseded` produce no transfer in any +layout. A destination keeps content the source no longer has. + +Translate reads only squirrel's own records. That makes each layout's +decisions table-testable without a transport. For the mirror, those decisions +include the destructive one: which existing entry gets moved into history. + +## 3. Transport + +```go +// transport is byte-level access to one destination root. Names are +// slash-separated and relative to the root; symlinks are never followed. +type transport interface { + Stat(ctx context.Context, name string) (entry, error) // fs.ErrNotExist when absent + List(ctx context.Context, dir string) ([]entry, error) + Get(ctx context.Context, name string) (io.ReadCloser, error) + // Put creates name exclusively (fs.ErrExist if present), streams r into + // it, sets its mtime, and syncs it to stable storage before returning. + Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error + // Rename moves from to to, creating to's parents; fs.ErrExist if to exists. + Rename(ctx context.Context, from, to string) error + Remove(ctx context.Context, name string) error + Close() error +} +``` + +### Contract + +- **Nothing replaces an existing name.** `Put` creates exclusively and + `Rename` never replaces its target. So no transport call can overwrite + bytes. +- **Only a name guard decides what may move or disappear.** Layouts never + hold the raw transport. They get a wrapper whose one small function, with + its own table test, allows: + - `Remove` only on squirrel's own staging names from runs that have + finished (`.squirrel-staging/run-/`), and on ride-along snapshots + (`.squirrel-index/index-*.db`, which rotation already deletes today). + Anything else found in staging is reported and left alone; + - `Rename` only from staging to a live name (commit), or from a live name + to `.squirrel-history/run-/` (displacement). + + That function is the whole audit surface for destroying or moving bytes on + a destination. +- **Object stores implement everything except `Rename`.** S3 can create + exclusively with a conditional put. That is enough for the + content-addressed and packed layouts in step 3. A mirror needs `Rename`, + which is why mirrors on s3, b2 and gcs are out of scope. + +### Local implementation + +- Built on `os.Root` (Go 1.25+). It resolves every name inside the root and + refuses to follow symlinks out of it. +- `Put` opens with `O_CREATE|O_EXCL`, copies, sets the times, then syncs. +- `Rename` avoids replacing its target in one of two ways: + - **Preferred:** the platform's no-replace rename (`renameat2` with + `RENAME_NOREPLACE` on Linux, `renamex_np` with `RENAME_EXCL` on macOS), + or `Link` followed by `Remove`. + - **Fallback:** where the filesystem supports neither (exFAT, common on + USB disks), squirrel checks with `Lstat` and then renames. A concurrent + writer from outside squirrel could still slip in between the check and + the rename. Squirrel can't collide with itself here, because the run guard + and the volume marker already exclude a second squirrel writer. +- After a rename, the parent directories are synced. + +### sftp implementation + +- Built on `golang.org/x/crypto/ssh`, already a dependency, and + `github.com/pkg/sftp`, which is new. +- `Put` opens with `SSH_FXF_CREAT|SSH_FXF_EXCL` and uses concurrent writes, so + high latency doesn't cap throughput. It syncs through `fsync@openssh.com` + when the server offers it. +- **mtime is whole seconds.** Protocol version 3 carries only seconds, so the + records store the mtime the server reports. +- **`Rename` checks first.** The protocol's rename fails when the target + exists. Servers don't all honour that, so the transport also runs `Lstat` + first. The contract suite pins the behaviour against the testbed's server. +- **Nothing runs a program on the server.** The cloudbox shape allows none. + +## 4. The mirror layout + +### On disk + +The tree keeps the shape it has today and gains two reserved entries: + +``` +// + 2024/cat.jpg + .squirrel-volume + .squirrel-history/run-7/2024/cat.jpg # prior version, moved aside by run 7 + .squirrel-index/run-7 # receipt: run 7's manifest segment + .squirrel-index/index-…-run-7.db # ride-along index snapshot + .squirrel-staging/ # in-flight writes, squirrel-owned +``` + +`.squirrel-staging` joins the reserved names in `reservedSubtreeFilter`, +`isReservedSyncPath` and the walker's warning. + +### Destination records + +The mirror's counterpart of `remote_objects` is one row per version squirrel +wrote at a path. The row is keyed on the `files` row it came from: + +```sql +CREATE TABLE remote_paths ( + id INTEGER PRIMARY KEY, + destination TEXT NOT NULL, + folder_id INTEGER NOT NULL, + name TEXT NOT NULL, + content_id INTEGER NOT NULL, + written_run_id INTEGER NOT NULL REFERENCES runs(id), + state TEXT NOT NULL + CHECK (state IN ('committing', 'live', 'displacing', 'displaced', 'lost')), + displaced_run_id INTEGER REFERENCES runs(id), + mtime_ns INTEGER NOT NULL, + checksum_algo TEXT, + checksum TEXT, + verified_at_ns INTEGER, + FOREIGN KEY (folder_id, name, content_id) REFERENCES files (folder_id, name, content_id), + CHECK (state NOT IN ('committing', 'live') OR displaced_run_id IS NULL), + CHECK (state NOT IN ('displacing', 'displaced') OR displaced_run_id IS NOT NULL), + CHECK ((checksum_algo IS NULL) = (checksum IS NULL)) +) STRICT; +CREATE UNIQUE INDEX uniq_remote_paths_live ON remote_paths (destination, folder_id, name) + WHERE state IN ('committing', 'live'); +CREATE INDEX idx_remote_paths_unsettled ON remote_paths (destination) + WHERE state IN ('committing', 'displacing'); +``` + +- **A displaced version has a derived location.** It sits at + `.squirrel-history/run-/`. +- **Directory moves keep that rule true.** When a directory is displaced + because a file replaced it, every live row under the directory moves with it + and gets the same `displaced_run_id`. +- **Rows are never deleted.** The one exception is `squirrel destination + reset`, which clears `remote_paths` the same way it clears + `remote_objects`. +- **Foreign files are preserved but not recorded.** Bytes squirrel didn't + write have no content id. When squirrel displaces them, they are kept in + history, reported as a run warning, and listed in a runs_audit note. +- **A row is `lost` when its bytes are no longer where it says.** A push or a + verify pass found other bytes there, or nothing. The row keeps its history + but stops vouching for its content. +- **The upload-once check sees mirror copies.** `ContentPresentOnDestination` + gains `remote_paths` rows in the `live` and `displaced` states as a third + source. `lost` rows never count. + +### Translation rules + +| Delta row | Live record for the path | Operation | +|---|---|---| +| present, content C | holds C | none (counted as already correct) | +| present, content C | holds other content | write C, displacing the recorded version | +| present, content C | none | write C, displacing any unrecorded entry found at the path | +| missing, offloaded, superseded | any | none | +| repair: a live record the verify pass marked `lost` | | write C, displacing whatever is there | + +Execute confirms each planned path with a single `Lstat`, never a listing. If +an "already correct" path's size or mtime disagrees with its record, the path +is treated as changed behind squirrel's back: its row becomes `lost` and the path is written again, with a warning. + +### Writing one path + +1. **Reconcile** (once, at push start). Squirrel settles every `committing` + and `displacing` row for this destination by checking both locations + (next table). Staging left by finished runs is removed. +2. **Stage.** The source is streamed into `.squirrel-staging/run-/`, + and BLAKE3 is computed over the same bytes. If the hash doesn't match the + indexed hash, the staged file is removed and the run fails before its seal, + so the watermark stays put. That is the `errContentDrift` contract. Here the + hash covers exactly the bytes sent, which closes the re-hash-then-read gap + noted on `uploadOneObject`. +3. **Displace.** If `Lstat` finds an entry at the path: + - **The entry's size and mtime match the live row:** + 1. mark the row `displacing` with this run; + 2. rename the entry to `.squirrel-history/run-/`; + 3. mark the row `displaced`. + - **They don't match** (the file changed behind squirrel's back): + 1. mark the row `lost`; + 2. displace the entry as unrecorded bytes, which a warning and a + runs_audit note report. + + A record never claims history holds bytes it doesn't. +4. **Commit:** + 1. insert the new row as `committing`; + 2. rename the staged file to the path; + 3. mark the row `live`. + +Each move is recorded before it happens. Reconcile then finishes the record or +withdraws it, based on where the bytes actually are. The destination never +lacks a copy of something it held. Displaced bytes reach history before the +new version is committed, and the new version stays in staging until then. +Between steps 3 and 4 the live path is briefly empty. That costs availability +until the next push, never content. + +### Crash points + +| Crash after | Destination | Reconcile at the next push | +|---|---|---| +| staging write | partial file in staging | removed with the finished run's staging | +| `displacing` recorded | old version still at the path | size matches the record, so the row goes back to `live` | +| displace rename | old version in history | history entry present, so the row becomes `displaced` | +| `committing` recorded | new version in staging, path empty | the intent is withdrawn, the staging file removed, and the path planned again (no seal, so it's still in the delta) | +| commit rename | new version at the path | staging gone and path present, so the row becomes `live` | +| every write, before the seal | tree complete, no receipt | the watermark holds, and the next push translates every path to "already correct" | + +### What the tests must cover + +A native mirror loses the independence rclone's own walk gave it (see "What we +give up"). So its tests for destroying and moving bytes carry more weight than +usual: + +- **Crash injection at every transport call** of a push, using a + fault-injecting transport wrapper, then a clean push. The invariants below + must hold afterwards. +- **A model-based test.** It generates random index histories: add, modify, + delete, re-add, file↔directory swaps, names that collide by case. It then + pushes with random crash points and compares the results against a + reference model. +- **File↔directory swaps**, in both directions and nested. +- **Unexpected entries at a target:** + - an unrecorded file (a foreign write, or a tree rclone wrote); + - a recorded file changed behind squirrel's back: it is displaced as + unrecorded bytes, and its row becomes `lost`, never `displaced`; + - a file placed in `.squirrel-staging/` from outside squirrel: it is + reported and never removed; + - a symlink anywhere along a target's parent chain, which must not be + followed. +- **Case-insensitive destinations** (APFS or exFAT USB disks): + - When `a.jpg` and `A.jpg` both exist at the source, the second write is + refused for that path, and nothing is displaced. + - Destinations that ignore Unicode normalization get the same treatment, + for names that differ only in composed versus decomposed form. + - The first push probes the destination's case and normalization behaviour + inside staging. +- **Failures:** + - the disk fills up or the quota runs out mid-write; + - the history directory can't be written; + - the source drifts while streaming. +- **Rename onto an existing target** must fail on both implementations and on + the testbed's sftp server. + +**Invariants:** + +1. Every `live` row's bytes are at its path. Every `displaced` row's bytes are + at its history path. In both cases their BLAKE3 matches. +2. Outside `.squirrel-staging/`, the set of files on the destination only + grows. +3. After a clean push, every path present in the index has a `live` row + holding its current content. + +The suite runs against the local transport. It runs against the sftp +transport through an in-process `pkg/sftp` server. And it runs against both +wrapped in the fault injector. + +## 5. Evidence and verification (reverses #216) + +Until this step, a native mirror push advances its vector as `presence+size`. +Every fingerprint stays pending, so the mirror still can't gate offload. +That's the same as today, only the method name changes. This step changes it. + +- **Read-back at write time.** After staging and syncing, squirrel re-reads + the staged file and hashes it with BLAKE3 before committing: + - **Local:** a cache-bypassing read (`POSIX_FADV_DONTNEED` on Linux, + `F_NOCACHE` on macOS). It is best effort: a USB bridge's own cache is out + of reach. + - **sftp:** a download over the same session. + + A match records `checksum_algo = blake3` and `verified_at_ns` on the row. + `CountVolumeContentsPendingFingerprint` and `ContentFingerprintVerified` + consult `remote_paths`. So a push can advance as `fingerprint-verified` + through the existing gate path, which requires a verify cadence. +- **Cost.** Read-back is a safety property, so it's always on. On a USB disk, + every written byte is read once more, roughly 1.5 to 2 times the push time. + On sftp, every uploaded byte is downloaded once. +- **Verify pass for mirrors.** `verify_every` becomes valid on native mirrors. + Each pass does two things: + - It checks the size and mtime of every `live` and `displaced` row with + `Lstat`. Both states count as stored content, so both are checked. This is + cheap and catches deletion, truncation and replacement. + - It re-hashes a slice of rows, oldest `verified_at_ns` first, within a + budget per pass. So every byte is re-read within a known period. Kopia's + `verify_files_percent` is the precedent for sampled read-back. + + Findings latch the existing destination alarm and mark the affected rows + `lost`. `lost` live rows whose content is still the index's current content + become the planner's repairs. +- **Documents amended in the same PR:** + - `CanEverGateOffload` becomes true for native mirrors, and + `offload_requires` accepts them; + - reference-setup.md's "Offload gate" paragraph; + - guides/offloading.md and layouts/mirror.md; + - the F21 entry in friction-log.md; + - SAFETY-AUDIT.md. + +## 6. Restore, ride-along, recover + +- **Mirror restore with an index** uses the archive restore pipeline: + 1. resolve the present paths; + 2. `Get` each one by path; + 3. BLAKE3 while streaming; + 4. place it. + + Placing goes through a temporary file in the target directory, a sync and a + rename. Today's archive restore writes with `O_TRUNC` in place. Both get + fixed together. +- **Mirror restore without an index** (a fresh machine) walks the mirror with + `List` and skips the reserved directories. When receipts are present, each + file is checked against them, and files that can't be checked are counted. +- **The marker gate, the snapshot ride-along and its rotation, and `recover + --from` discovery** become transport calls. That removes the rclone-specific + helpers `statRemoteExists`, `catRemote`, `copyTo`, `listSnapshots`, + `deleteFile` and `remoteRootEmpty` for these destinations. + +## 7. Configuration and dispatch + +- **Dispatch.** `HandlerFor` sends mirrors on `local`, and on `sftp` without + `crypt`, to the native handler. Every other pair is unchanged. +- **sftp settings.** `host`, `port`, `user`, `password`, `key_file`, + `known_hosts_file` and `host_key_algorithms` map onto `ssh.ClientConfig`. + When there is neither password nor key file, squirrel uses ssh-agent, as + rclone does. +- **Host key verification is always on.** Without `known_hosts_file`, + squirrel reads `~/.ssh/known_hosts`. An unknown host is refused, and the + message gives the presented fingerprint and how to trust it. + - **Migration cost:** a config that relied on rclone accepting any host key + stops connecting until the key is pinned. +- **Rclone-only keys are rejected** on native destinations: `checkers`, and + `hash_algo` (the key for rclone's server-side hash). No key is added. + Concurrency is fixed: a few parallel writes on sftp, and one or two on a + local disk. + +## 8. What we give up + +- **Implementation independence.** Today rclone walks the source itself. A + file the indexer misses still reaches cloudbox and usb. Once native, every + mirror inherits indexer bugs, and kopia remains the only independent leg. + - reference-setup.md already claims that every copy comes from the same + walker. With a native mirror that becomes literally true. The + kopia-leg section gets amended in the mirror PR to say what the mirrors + no longer cover. + - Open question 5 proposes a cheap mitigation. +- **Rclone's tuning and backend know-how.** Rclone brings parallel transfers, + multi-threaded streams, and years of workarounds for sftp servers. The + switch should wait for a benchmark on the testbed against rclone. +- **A new dependency:** `github.com/pkg/sftp`. + +## 9. Order of work + +Items 1 to 6 land together on one branch, in this order. The pull request's +checklist splits them into sections for separate sessions: + +1. **Planner.** Extract `pushPlan` and the layout driver from the + content-addressed and packed handlers, and fix the wiped-root rule. Nothing + else changes. The existing tests pass untouched, and a new wiped-root test + is added. +2. **Local.** + - The transport, the name guard and the local implementation. + - The fault-injecting wrapper and the contract suite. + - The native mirror layout with `remote_paths`, and the `usb` push. + - Amend reference-setup.md (the kopia leg, and the `usb` topology arrow) + and layouts/mirror.md. +3. **sftp.** The sftp implementation, host key handling, and plain sftp + mirrors. +4. **Restore, ride-along and recover** on the transport. Once this lands, + `local` and plain `sftp` mirrors are free of rclone. +5. **Evidence.** Read-back fingerprints, the mirror verify pass, and repairs + in the planner. This reverses #216 and amends the design and docs listed in + section 5. +6. **Content-addressed and packed on `local` and `sftp`** move to the + transport. +7. **S3 transport**: step 3 of the plan, on its own branch afterwards. + +The crypt decision is independent of this order. Once made, it becomes a +crypt transport wrapper, and then cloudbox moves. + +## 10. Open questions + +1. **Crypt byte-compatibility with rclone.** This blocks cloudbox only. + Undecided, and to be discussed separately. +2. **sftp and the offload gate.** Is a stat on every row, plus a rotating + read-back, enough for an sftp mirror to gate offload? Or should an sftp + mirror stay non-gating? +3. **Adopting an existing mirror tree.** Unrecorded entries are displaced + into history, so pointing a native mirror at an rclone-era tree re-uploads + everything. The alternative is an adopt pass that hashes existing files and + records the ones that match. Recommendation: use fresh roots (nothing is in + production), and build adoption only if the testbed shows the re-upload + hurts. +4. **Receipt location.** Keep mirror receipts in `.squirrel-index/`. Or move + every layout's segments there, which gives one landing-evidence location + for all three. +5. **Regaining some independence.** A periodic source-completeness audit + would compare a plain directory walk of each volume with the index's + present set. It would catch indexer skips for every layout, not only + mirrors. +6. **Case-folding collisions.** Refuse only the colliding path (as proposed), + or refuse the whole destination for that volume? From 9d86c4ed6b3ccc09dde80a011038d77dd76811bf Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Wed, 23 Sep 2026 22:51:21 +0200 Subject: [PATCH 02/61] design: record the native mirror decisions sftp gating goes through an optional server hash for content-addressed and packed artifacts only; host keys are always checked against known_hosts; read-back runs on local disks only; rclone-era mirror trees are refused rather than adopted. Crypt stays the one open question. --- design/native-mirror.md | 104 ++++++++++++++++++++++++---------------- 1 file changed, 63 insertions(+), 41 deletions(-) diff --git a/design/native-mirror.md b/design/native-mirror.md index 0f79a24..bd2cc46 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -70,7 +70,8 @@ In the [reference setup](reference-setup.md), `usb` moves with this work. squirrel's records, confirms each planned path's size and mtime, and moves whatever is there aside before writing. Its safety comes from that move, not from a content comparison. Content is checked by hashing the source as it - streams, by the read-back in the evidence step, and by the verify pass. + streams, by the read-back on local disks, and by the verify pass (both from the + evidence step). None of those is optional, so the flag has nothing to switch off. ## 1. The planner @@ -263,7 +264,16 @@ type transport interface { - **`Rename` checks first.** The protocol's rename fails when the target exists. Servers don't all honour that, so the transport also runs `Lstat` first. The contract suite pins the behaviour against the testbed's server. -- **Nothing runs a program on the server.** The cloudbox shape allows none. +- **One optional server-side command: a hash.** Content-addressed and packed + artifacts get their fingerprint confirmed, and re-confirmed, by a hash + command run on the server. That is `sha256sum` by default, chosen by + `hash_algo`, as rclone runs today. + - The command line is built only from the configured root and hex artifact + names. A root holding anything beyond letters, digits, `.`, `_`, `-` and + `/` is never hashed on the server. + - The transport probes for the command once per push. On a server that runs + no programs, like the cloudbox shape, fingerprints stay pending, as today. + - Mirror paths are user filenames, so they never go on a command line. ## 4. The mirror layout @@ -445,28 +455,31 @@ wrapped in the fault injector. Until this step, a native mirror push advances its vector as `presence+size`. Every fingerprint stays pending, so the mirror still can't gate offload. -That's the same as today, only the method name changes. This step changes it. +That's the same as today, only the method name changes. This step changes it +for local mirrors. -- **Read-back at write time.** After staging and syncing, squirrel re-reads - the staged file and hashes it with BLAKE3 before committing: - - **Local:** a cache-bypassing read (`POSIX_FADV_DONTNEED` on Linux, - `F_NOCACHE` on macOS). It is best effort: a USB bridge's own cache is out - of reach. - - **sftp:** a download over the same session. +- **Read-back at write time, on local disks.** After staging and syncing, + squirrel re-reads the staged file and hashes it with BLAKE3 before + committing. The read bypasses the cache (`POSIX_FADV_DONTNEED` on Linux, + `F_NOCACHE` on macOS). It is best effort: a USB bridge's own cache is out of + reach. A match records `checksum_algo = blake3` and `verified_at_ns` on the row. `CountVolumeContentsPendingFingerprint` and `ContentFingerprintVerified` consult `remote_paths`. So a push can advance as `fingerprint-verified` through the existing gate path, which requires a verify cadence. -- **Cost.** Read-back is a safety property, so it's always on. On a USB disk, - every written byte is read once more, roughly 1.5 to 2 times the push time. - On sftp, every uploaded byte is downloaded once. +- **sftp mirrors stay non-gating.** An sftp push skips read-back, and mirror + paths never go on a server command line, so their fingerprints stay + pending. +- **Cost.** Read-back is a safety property, so it's always on for local + disks. Every written byte is read once more, roughly 1.5 to 2 times the push + time on a USB disk. - **Verify pass for mirrors.** `verify_every` becomes valid on native mirrors. Each pass does two things: - It checks the size and mtime of every `live` and `displaced` row with `Lstat`. Both states count as stored content, so both are checked. This is cheap and catches deletion, truncation and replacement. - - It re-hashes a slice of rows, oldest `verified_at_ns` first, within a + - On local mirrors, it re-hashes a slice of rows, oldest `verified_at_ns` first, within a budget per pass. So every byte is re-read within a known period. Kopia's `verify_files_percent` is the precedent for sampled read-back. @@ -474,8 +487,9 @@ That's the same as today, only the method name changes. This step changes it. `lost`. `lost` live rows whose content is still the index's current content become the planner's repairs. - **Documents amended in the same PR:** - - `CanEverGateOffload` becomes true for native mirrors, and - `offload_requires` accepts them; + - `CanEverGateOffload` becomes true for native local mirrors, and + `offload_requires` accepts them. sftp mirrors keep refusing, and the + refusal names the reason; - reference-setup.md's "Offload gate" paragraph; - guides/offloading.md and layouts/mirror.md; - the F21 entry in friction-log.md; @@ -513,8 +527,10 @@ That's the same as today, only the method name changes. This step changes it. message gives the presented fingerprint and how to trust it. - **Migration cost:** a config that relied on rclone accepting any host key stops connecting until the key is pinned. -- **Rclone-only keys are rejected** on native destinations: `checkers`, and - `hash_algo` (the key for rclone's server-side hash). No key is added. +- **Rclone-only keys are rejected** on native destinations: `checkers` + everywhere, and `hash_algo` on sftp mirrors. On content-addressed and packed + sftp destinations, `hash_algo` still chooses the hash, which now names the + command the transport runs on the server. No key is added. Concurrency is fixed: a few parallel writes on sftp, and one or two on a local disk. @@ -527,7 +543,7 @@ That's the same as today, only the method name changes. This step changes it. walker. With a native mirror that becomes literally true. The kopia-leg section gets amended in the mirror PR to say what the mirrors no longer cover. - - Open question 5 proposes a cheap mitigation. + - Decision 7 keeps a cheap mitigation as a candidate. - **Rclone's tuning and backend know-how.** Rclone brings parallel transfers, multi-threaded streams, and years of workarounds for sftp servers. The switch should wait for a benchmark on the testbed against rclone. @@ -552,7 +568,7 @@ checklist splits them into sections for separate sessions: mirrors. 4. **Restore, ride-along and recover** on the transport. Once this lands, `local` and plain `sftp` mirrors are free of rclone. -5. **Evidence.** Read-back fingerprints, the mirror verify pass, and repairs +5. **Evidence.** Read-back fingerprints on local mirrors, the mirror verify pass, and repairs in the planner. This reverses #216 and amends the design and docs listed in section 5. 6. **Content-addressed and packed on `local` and `sftp`** move to the @@ -562,25 +578,31 @@ checklist splits them into sections for separate sessions: The crypt decision is independent of this order. Once made, it becomes a crypt transport wrapper, and then cloudbox moves. -## 10. Open questions - -1. **Crypt byte-compatibility with rclone.** This blocks cloudbox only. - Undecided, and to be discussed separately. -2. **sftp and the offload gate.** Is a stat on every row, plus a rotating - read-back, enough for an sftp mirror to gate offload? Or should an sftp - mirror stay non-gating? -3. **Adopting an existing mirror tree.** Unrecorded entries are displaced - into history, so pointing a native mirror at an rclone-era tree re-uploads - everything. The alternative is an adopt pass that hashes existing files and - records the ones that match. Recommendation: use fresh roots (nothing is in - production), and build adoption only if the testbed shows the re-upload - hurts. -4. **Receipt location.** Keep mirror receipts in `.squirrel-index/`. Or move - every layout's segments there, which gives one landing-evidence location - for all three. -5. **Regaining some independence.** A periodic source-completeness audit - would compare a plain directory walk of each volume with the index's - present set. It would catch indexer skips for every layout, not only - mirrors. -6. **Case-folding collisions.** Refuse only the colliding path (as proposed), - or refuse the whole destination for that volume? +## 10. Decisions and open questions + +Decided on 2026-09-23: + +1. **Offload gating on sftp.** Content-addressed and packed sftp destinations + gate through the optional server hash command (section 3), as they do + through rclone today. sftp mirrors stay non-gating, and so does any server + that runs no programs. +2. **Host keys.** They are always verified against `known_hosts_file`, or + against `~/.ssh/known_hosts` when that's unset. Unknown hosts are refused. + Configs that relied on rclone accepting any key must pin it first. +3. **Read-back** runs on local disks only (section 5). +4. **Existing mirror trees aren't adopted.** The watermark rule refuses an + rclone-era mirror: the tree isn't empty, and its runs left no receipts. A + native mirror needs a fresh or emptied root. Adoption gets built only if the + testbed shows that hurts. +5. **Receipts** for mirrors live in `.squirrel-index/`. The content layouts + keep their segments where they are. +6. **Case-folding and normalization collisions** refuse only the colliding + path. +7. **No source-completeness audit in this branch.** It stays a candidate. A + periodic check would compare a plain directory walk with the index's + present set, which would restore some independence for every layout. + +Open: + +1. **Crypt byte-compatibility with rclone.** This blocks cloudbox only, and is + to be discussed separately. From 54243d2cc6d9120d52b88dc8aa58ca81f5db211b Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Wed, 23 Sep 2026 23:37:33 +0200 Subject: [PATCH 03/61] sync: extract the push planner shared by the content layouts The content-addressed and packed handlers each carried the same push sequence. sync/push.go now holds it once: pushPlan, a layout interface generic over each layout's operations, and the pushThrough driver that runs requireIndexedVolume, markers, run allocation, the watermark rule, translate, execute, seal and the durability advance for every layout. A dry run is translate plus the operations' preview, replacing each handler's previewDryRun. A packed run whose vector advance fails now closes as failed, like content-addressed. The layout-evidence probe uses statRemoteExists, so an unreachable destination fails the run instead of being read as a foreign history. --- design/native-mirror.md | 35 +++-- sync/content_addressed.go | 269 +++++++++++++----------------------- sync/packed.go | 279 ++++++++++++++------------------------ sync/push.go | 210 ++++++++++++++++++++++++++++ sync/sync.go | 16 --- 5 files changed, 431 insertions(+), 378 deletions(-) create mode 100644 sync/push.go diff --git a/design/native-mirror.md b/design/native-mirror.md index bd2cc46..47d2441 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -102,19 +102,27 @@ type pushPlan struct { advance []store.OriginComponent // captured before any transfer } -// layout is one destination layout's part of a push. -type layout interface { +// layout is one destination layout's part of a push. O is the layout's +// own operations type; a dry run reports its preview. +type layout[O operations] interface { + // markers gates the push on the destination's markers (writes them + // under --init; a dry run only checks). + markers(ctx context.Context, rep *Report, volumeID int64, opts Options) error // landed reports whether runID left this layout's landing evidence. landed(ctx context.Context, runID int64) (bool, error) + // rootEmpty and foreignHistory complete the watermark rule below. + rootEmpty(ctx context.Context) (bool, error) + foreignHistory(runID int64) error // translate turns the plan into this layout's operations. It reads // squirrel's records and writes nothing: a dry run is translate alone. - translate(ctx context.Context, p pushPlan) (operations, error) + translate(ctx context.Context, p pushPlan) (O, error) // execute performs the operations and records each confirmed one. - execute(ctx context.Context, rep *Report, runID int64, ops operations) error + execute(ctx context.Context, rep *Report, runID int64, ops O) error // seal writes the run's landing evidence once every operation is confirmed. - seal(ctx context.Context, runID int64, p pushPlan) error - // advanceMethod names the evidence the confirmed landing earns. - advanceMethod(ctx context.Context, p pushPlan) (string, error) + seal(ctx context.Context, rep *Report, runID int64, p pushPlan, ops O) error + // advanceMethod names the evidence the confirmed landing earns; an + // empty method holds the vector (packed, while a fingerprint is pending). + advanceMethod(ctx context.Context, rep *Report, p pushPlan) (string, error) } ``` @@ -122,8 +130,13 @@ One driver runs every layout: requireIndexedVolume → markers → begin run → plan → translate → execute → seal → advance → finish → ride-along -A dry run stops after translate and reports `operations`' summary. Today's -separate `previewDryRun` in each handler becomes that summary. +A dry run stops after translate and reports the operations' preview. The +separate `previewDryRun` each handler carried became that preview +(`sync/push.go`). + +The driver promotes a run to success only after the vector advanced, for +every layout. Before the refactor a packed run whose advance failed still +closed as success; it now closes as failed, like content-addressed. ### Watermark rule @@ -140,6 +153,10 @@ This rule is shared by all three layouts: 4. In every other case, refuse with `ErrRefused`. The message points at a fresh root or `squirrel destination reset`. +A probe that fails, for the evidence or for the root's emptiness, fails the run +with its error instead: it can't tell either way, so it neither refuses nor +starts fresh. + Each layout's landing evidence lives at a different place: | Layout | Landing evidence | diff --git a/sync/content_addressed.go b/sync/content_addressed.go index a06fa05..663fde8 100644 --- a/sync/content_addressed.go +++ b/sync/content_addressed.go @@ -125,6 +125,27 @@ func (h *contentPusher) ensureMarkers(ctx context.Context, init bool) error { return ensureRemoteDestinationMarker(ctx, h.store, h.rcl, h.dest, h.vol.Name, init) } +// markers is the content layouts' marker gate. A dry run checks the naming +// scheme read-only and writes nothing. +func (h *contentPusher) markers(ctx context.Context, _ *Report, _ int64, opts Options) error { + if opts.DryRun { + _, err := h.checkNamingScheme(ctx) + return err + } + return h.ensureMarkers(ctx, opts.Init) +} + +// rootEmpty reports whether the destination root holds no files beyond +// squirrel's markers — a wiped or repointed destination, or one whose +// recorded state was cleared by `squirrel destination reset`. +func (h *contentPusher) rootEmpty(ctx context.Context) (bool, error) { + return h.rcl.remoteRootEmpty(ctx, remoteSubpathURI(h.dest, ""), rootMarkerNames(h.dest), checkersArgs(h.dest)...) +} + +func (h *contentPusher) target() pushTarget { + return pushTarget{store: h.store, vol: h.vol, dest: h.dest} +} + // contentAddressedHandler pushes a volume to a content-addressed rclone // destination: per-hash `rclone copyto` for each content object the // destination lacks, then the run's manifest segment. The landing is @@ -141,136 +162,44 @@ type contentAddressedHandler struct { func (h *contentAddressedHandler) TargetName() string { return h.dest.Name } func (h *contentAddressedHandler) Push(ctx context.Context, opts Options) (Report, error) { - rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} - // Stamped up front so output renderers key content-addressed - // formatting off the method even when the push fails early. - rep.Verification.Method = VerifyMethodPresenceSize if h.vol.Name == ObjectsDirName { + rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} + rep.Verification.Method = VerifyMethodPresenceSize return rep, fmt.Errorf("volume %q: the name collides with the destination-root %s/ directory of content-addressed destination %q — rename the volume or use a mirrored destination", h.vol.Name, ObjectsDirName, h.dest.Name) } - volID, err := requireIndexedVolume(ctx, h.store, h.vol) - if err != nil { - return rep, err - } - if opts.DryRun { - if _, err := h.checkNamingScheme(ctx); err != nil { - return rep, err - } - return rep, h.previewDryRun(ctx, &rep, volID) - } - if err := h.ensureMarkers(ctx, opts.Init); err != nil { - return rep, err - } - // shallow=true on the runs row: the per-object transfers carry no - // BLAKE3 end-to-end check (crypt remotes expose no hashes), and the - // audit trail stays honest about that. - runID, err := beginSyncRunGuarded(ctx, h.store, false, store.SyncRunSpec{ - VolumeID: volID, - Destination: h.dest.Name, - Shallow: true, - }, h.vol.Name) - if err != nil { - return rep, err - } - rep.RunID = runID - if opts.OnRunID != nil { - opts.OnRunID(runID) - } - - err = h.push(ctx, &rep, volID, runID) - finishHandlerRun(ctx, h.store, &rep, err) - opts.Snapshot.afterSync(ctx, &rep, h.vol, h.dest) - return rep, err + return pushThrough(ctx, h.target(), h, opts) } func (h *contentAddressedHandler) sealed() {} -// previewDryRun reports what a real push would upload without transferring -// anything or writing a runs row: rep.RunID stays 0, no objects land, and -// no remote_objects or manifest-segment rows are written. It computes the -// same delta and new-content selection the real push does (watermark → -// delta → plannedUploads), so the preview matches what the next real run -// would land. The watermark check still reads the destination, so a -// layout-flip is refused here too — a dry-run is an honest rehearsal. -func (h *contentAddressedHandler) previewDryRun(ctx context.Context, rep *Report, volID int64) error { - watermark, err := h.watermark(ctx, volID) - if err != nil { - return err - } - delta, err := h.store.ListPathDeltaSince(ctx, volID, watermark) - if err != nil { - return fmt.Errorf("compute path delta since run %d: %w", watermark, err) - } - rep.Verification.Files = int64(len(delta)) - if err := h.previewObjectUploads(ctx, rep, plannedUploads(delta)); err != nil { - return err - } - rep.Status = store.RunStatusSuccess - return nil +// translate selects the delta's present content, one source path per hash, +// and splits it by whether the destination already records it. +func (h *contentAddressedHandler) translate(ctx context.Context, p pushPlan) (objectUploads, error) { + return h.splitRecorded(ctx, plannedUploads(p.delta)) } -// push runs the transactional landing: delta → objects → segment → -// vector. rep.Status starts failed and is promoted to success only at -// the end, after the destination vector advanced — a confirmed landing -// whose evidence failed to record must not present as success, or the -// next run's watermark would skip past it. -func (h *contentAddressedHandler) push(ctx context.Context, rep *Report, volID, runID int64) error { - rep.Status = store.RunStatusFailed - watermark, err := h.watermark(ctx, volID) - if err != nil { - return err - } - advance, err := captureDurabilityAdvance(ctx, h.store, volID) - if err != nil { - return err - } - delta, err := h.store.ListPathDeltaSince(ctx, volID, watermark) - if err != nil { - return fmt.Errorf("compute path delta since run %d: %w", watermark, err) - } - rep.Verification.Files = int64(len(delta)) - // The delta is exactly what this push changes at the destination: the - // paths whose content the manifest segment newly maps. An empty delta - // is a genuine no-op, which is what the runs fold keys on (#182). - rep.Changed = knownChanged(int64(len(delta))) - if err := h.uploadObjects(ctx, rep, runID, plannedUploads(delta)); err != nil { - return err - } - if err := h.uploadSegment(ctx, delta, runID); err != nil { - return err - } - // presence+size is not a content-verified method (crypt remotes expose - // no hashes): the component advances so the offload gate's per-object - // scan-back can back it locally. When this run's capture leaves the - // whole (volume, destination) pair with a verified fingerprint behind - // every present content, the advance is instead stamped - // fingerprint-verified — the content-verified method that also relays - // over the durability pull (see the durability-vector upgrade in - // store). A single still-pending object holds it at presence+size. - method, err := h.advanceMethod(ctx, volID, len(advance)) - if err != nil { - return err - } - if err := h.store.AdvanceDestinationVectorTo(ctx, volID, h.dest.Name, method, advance); err != nil { - return fmt.Errorf("advance destination vector for %s: %w", h.dest.Name, err) - } - rep.Status = store.RunStatusSuccess - rep.Verification.Bytes = rep.RcloneResult.Bytes - return nil +// execute lands every object the destination has no record of. +func (h *contentAddressedHandler) execute(ctx context.Context, rep *Report, runID int64, ops objectUploads) error { + return h.uploadObjects(ctx, rep, runID, ops) } -// advanceMethod chooses the method the content-addressed push advances its -// durability vector with: fingerprint-verified when every present content -// of the volume already carries a verified provider fingerprint on this +// seal writes the run's manifest segment, the layout's landing evidence. +func (h *contentAddressedHandler) seal(ctx context.Context, _ *Report, runID int64, p pushPlan, _ objectUploads) error { + return h.uploadSegment(ctx, p.delta, runID) +} + +// advanceMethod chooses fingerprint-verified when every present content of +// the volume already carries a verified provider fingerprint on this // destination (the whole-state check, not just this run's uploads), and -// presence+size otherwise. advanceLen is the size of the advance snapshot; -// an empty snapshot advances nothing, so the method is immaterial and the -// pending query is skipped. -func (h *contentPusher) advanceMethod(ctx context.Context, volID int64, advanceLen int) (string, error) { - if advanceLen == 0 { +// presence+size otherwise: presence+size is not content-verified (crypt +// remotes expose no hashes), so the offload gate's per-object scan-back +// backs it locally, and a single still-pending object holds the upgrade. +// An empty advance advances nothing, so the pending query is skipped. +func (h *contentAddressedHandler) advanceMethod(ctx context.Context, _ *Report, p pushPlan) (string, error) { + if len(p.advance) == 0 { return store.VerifyMethodPresenceSize, nil } - pending, err := h.store.CountVolumeContentsPendingFingerprint(ctx, volID, h.dest.Name) + pending, err := h.store.CountVolumeContentsPendingFingerprint(ctx, p.volumeID, h.dest.Name) if err != nil { return "", err } @@ -280,64 +209,65 @@ func (h *contentPusher) advanceMethod(ctx context.Context, volID int64, advanceL return store.VerifyMethodPresenceSize, nil } -// watermark resolves the run id the delta starts after: the last -// successful sync of this (volume, destination), or 0 for a fresh -// destination. The last success must still have its manifest segment at -// the destination — every successful content-addressed run uploads one, -// so its absence means the recorded history belongs to a different -// layout (a destination flipped from mirror) and a delta computed -// against it would silently skip everything the mirror era covered. -func (h *contentAddressedHandler) watermark(ctx context.Context, volID int64) (int64, error) { - last, err := h.store.LatestSuccessfulSyncRun(ctx, volID, h.dest.Name) - if store.IsNotFound(err) { - return 0, nil - } - if err != nil { - return 0, fmt.Errorf("lookup last successful sync of %s: %w", h.dest.Name, err) - } - segURI := h.segmentURI(last.ID) - if _, err := h.rcl.statRemote(ctx, segURI, checkersArgs(h.dest)...); err != nil { - if freshStartOnEmptyRoot(ctx, h.rcl, h.dest) { - return 0, nil - } - return 0, fmt.Errorf("destination %q: the last successful sync (run %d) left no manifest segment at %s — its history does not look content-addressed; point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w: %w", h.dest.Name, last.ID, segURI, h.dest.Name, err, ErrRefused) +// landed reports whether runID's manifest segment is at the destination. +// Every successful content-addressed run uploads one, so its absence means +// the recorded history belongs to a different layout or a wiped root. +func (h *contentAddressedHandler) landed(ctx context.Context, runID int64) (bool, error) { + return h.rcl.statRemoteExists(ctx, h.segmentURI(runID), checkersArgs(h.dest)...) +} + +func (h *contentAddressedHandler) foreignHistory(runID int64) error { + return fmt.Errorf("destination %q: the last successful sync (run %d) left no manifest segment at %s — its history does not look content-addressed; point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w", h.dest.Name, runID, h.segmentURI(runID), h.dest.Name, ErrRefused) +} + +// objectUploads is the object side of a content push: the planned content +// the destination has no upload record for, and how many planned contents +// it already records (as a per-hash object or a pack member). +type objectUploads struct { + needed []store.PathDelta + recorded int64 +} + +// preview counts the split uploadObjects would record: needed content as +// Transferred + Bytes, recorded content as Checked. +func (o objectUploads) preview(rep *Report) { + rep.RcloneResult.Checked += o.recorded + for _, d := range o.needed { + rep.RcloneResult.Transferred++ + rep.RcloneResult.Bytes += d.SizeBytes } - return last.ID, nil } -// previewObjectUploads counts, without uploading, the split uploadObjects -// would record: planned content the destination has no record of lands on -// rep.RcloneResult as Transferred + Bytes, content already offsite (as a -// per-hash object or a pack member) as Checked. It writes nothing and -// touches no object. Both layouts' dry-run preview use it — the packed -// layout passes only its object-routed (large) content. -func (h *contentPusher) previewObjectUploads(ctx context.Context, rep *Report, planned []store.PathDelta) error { +// splitRecorded splits planned content by whether the destination already +// records it offsite, as a per-hash object or a pack member, so a threshold +// change that reclassifies content never re-uploads bytes the destination +// already holds in the other form. Both content layouts translate their +// object side through it. +func (h *contentPusher) splitRecorded(ctx context.Context, planned []store.PathDelta) (objectUploads, error) { + var out objectUploads for _, d := range planned { recorded, err := h.store.ContentPresentOnDestination(ctx, d.ContentID, h.dest.Name) if err != nil { - return fmt.Errorf("lookup upload record for %s: %w", d.Path, err) + return objectUploads{}, fmt.Errorf("lookup upload record for %s: %w", d.Path, err) } if recorded { - rep.RcloneResult.Checked++ + out.recorded++ continue } - rep.RcloneResult.Transferred++ - rep.RcloneResult.Bytes += d.SizeBytes + out.needed = append(out.needed, d) } - return nil + return out, nil } -// uploadObjects lands every planned content object that the destination -// has no upload record for. planned is the deduplicated, present-only -// upload set (plannedUploads) — the content-addressed layout passes its -// whole delta's uploads, the packed layout passes only the files at or -// above its pack threshold. Counters land on -// rep.RcloneResult so the run report reads like the other rclone -// flows: Transferred = objects uploaded, Checked = objects skipped as -// already recorded, Errors/FailedFiles = per-object failures. Per-object -// failures don't stop the loop — every object that lands now is recorded -// and saves work on the retry — but any failure fails the run before -// the segment is written. +// uploadObjects lands every planned content object the destination has +// no upload record for. The content-addressed layout passes its whole +// delta's uploads, the packed layout only the files at or above its pack +// threshold. Counters land on rep.RcloneResult so the run report reads +// like the other rclone flows: Transferred = objects uploaded, Checked = +// objects skipped as already recorded, Errors/FailedFiles = per-object +// failures. Per-object failures don't stop the loop — every object that +// lands now is recorded and saves work on the retry — but any failure +// fails the run before the segment is written. // // A source whose bytes drifted from the indexed hash is refused without a // remote_objects row (errContentDrift): it is surfaced as a warning and @@ -345,22 +275,11 @@ func (h *contentPusher) previewObjectUploads(ctx context.Context, rep *Report, p // advance. The next run recomputes the same delta and re-offers the // object, letting the honest bytes land once they are restored — without // the drifted bytes ever being recorded under the hash. -func (h *contentPusher) uploadObjects(ctx context.Context, rep *Report, runID int64, planned []store.PathDelta) error { +func (h *contentPusher) uploadObjects(ctx context.Context, rep *Report, runID int64, ops objectUploads) error { + rep.RcloneResult.Checked += ops.recorded var confirmed []store.PathDelta var drifted int - for _, d := range planned { - // Two-source presence: skip content already offsite as a per-hash - // object or bundled in a pack already uploaded to this destination, - // so a threshold change that reclassifies content never re-uploads - // bytes the destination already holds in the other form. - recorded, err := h.store.ContentPresentOnDestination(ctx, d.ContentID, h.dest.Name) - if err != nil { - return fmt.Errorf("lookup upload record for %s: %w", d.Path, err) - } - if recorded { - rep.RcloneResult.Checked++ - continue - } + for _, d := range ops.needed { if err := h.uploadOneObject(ctx, runID, d); err != nil { if errors.Is(err, errContentDrift) { drifted++ diff --git a/sync/packed.go b/sync/packed.go index 384d58e..8f56d58 100644 --- a/sync/packed.go +++ b/sync/packed.go @@ -107,13 +107,12 @@ type PackPreview struct { // // Durability: this handler uploads packs, records them in the local // packs/pack_members tables, reads each pack's scan-back fingerprint into -// remote_packs, and advances the destination durability vector at -// presence+size only once every pack this run assembled is -// fingerprint-verified alongside the placement map and manifest segment -// (see certifyPacked). The offload gate then certifies a packed content -// through its pack's verified remote_packs row. Large files reuse the -// content-addressed object path and keep its per-object remote_objects -// record and fingerprint capture. +// remote_packs, and advances the destination durability vector — as +// fingerprint-verified, never presence+size — only once every present +// content of the pair is fingerprint-verified (see advanceMethod). The +// offload gate then certifies a packed content through its pack's verified +// remote_packs row. Large files reuse the content-addressed object path and +// keep its per-object remote_objects record and fingerprint capture. type packedHandler struct { contentPusher } @@ -123,86 +122,44 @@ func (h *packedHandler) TargetName() string { return h.dest.Name } func (h *packedHandler) sealed() {} func (h *packedHandler) Push(ctx context.Context, opts Options) (Report, error) { - rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} - // Presence+size is the strongest check the packed push claims; it is - // not content-verified (crypt remotes expose no hashes, and packs carry - // no fingerprint until PR 3), so results stay unverified. - rep.Verification.Method = VerifyMethodPresenceSize if h.vol.Name == ObjectsDirName || h.vol.Name == PacksDirName { + rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} + rep.Verification.Method = VerifyMethodPresenceSize return rep, fmt.Errorf("volume %q: the name collides with the destination-root %s/ directory of packed destination %q — rename the volume or use a mirrored destination", h.vol.Name, h.vol.Name, h.dest.Name) } - volID, err := requireIndexedVolume(ctx, h.store, h.vol) - if err != nil { - return rep, err - } - if opts.DryRun { - if _, err := h.checkNamingScheme(ctx); err != nil { - return rep, err - } - return rep, h.previewDryRun(ctx, &rep, volID) - } - if err := h.ensureMarkers(ctx, opts.Init); err != nil { - return rep, err - } - // shallow=true: neither the per-object copyto nor the pack copyto - // carries a BLAKE3 end-to-end check, and the audit trail stays honest. - runID, err := beginSyncRunGuarded(ctx, h.store, false, store.SyncRunSpec{ - VolumeID: volID, - Destination: h.dest.Name, - Shallow: true, - }, h.vol.Name) - if err != nil { - return rep, err - } - rep.RunID = runID - if opts.OnRunID != nil { - opts.OnRunID(runID) - } - - err = h.push(ctx, &rep, volID, runID) - finishHandlerRun(ctx, h.store, &rep, err) - opts.Snapshot.afterSync(ctx, &rep, h.vol, h.dest) - return rep, err -} - -// previewDryRun reports what a real packed push would do — which content -// would upload as per-hash objects vs. be bundled into packs — without -// assembling or uploading any pack and without writing a runs row: -// rep.RunID stays 0 and no packs, pack_members, remote_*, objects, or -// pack artifacts are written. It computes the same delta and routing the -// real push does (watermark → delta → routeBySize); the object side lands -// on rep.RcloneResult exactly as the content-addressed preview reports it, -// the pack side on rep.PackPreview. The watermark check still reads the -// destination, so a layout-flip is refused here too. -func (h *packedHandler) previewDryRun(ctx context.Context, rep *Report, volID int64) error { - watermark, err := h.watermark(ctx, volID) - if err != nil { - return err - } - delta, err := h.store.ListPathDeltaSince(ctx, volID, watermark) - if err != nil { - return fmt.Errorf("compute path delta since run %d: %w", watermark, err) - } - rep.Verification.Files = int64(len(delta)) - large, small, err := h.routeBySize(ctx, rep, plannedUploads(delta)) - if err != nil { - return err - } - if err := h.previewObjectUploads(ctx, rep, large); err != nil { - return err - } - rep.PackPreview = h.previewPacks(small) - rep.Status = store.RunStatusSuccess - return nil + return pushThrough(ctx, h.target(), h, opts) } -// previewPacks summarises the small (pack-routed) content routeBySize -// selected, without assembling a pack. small is already hash-sorted, so -// the size-band walk mirrors buildOnePack's — accumulate members until the -// running total reaches PackSize, then close a pack — but over uncompressed -// sizes, yielding an estimated (not bounded) pack count (see PackPreview). -func (h *packedHandler) previewPacks(small []store.PathDelta) PackPreview { - p := PackPreview{SizeBand: h.dest.PackSize} +// packedOps is the packed translation of a plan: the large content routed +// to per-hash objects, the small content still to be packed (hash-sorted, +// so assembly is deterministic), and how much small content an earlier +// pack already holds. execute fills in the packs it assembled, which seal +// records. +type packedOps struct { + objects objectUploads + members []store.PathDelta + alreadyInPack int64 + packSize int64 + + writes []store.PackWrite + placements []PlacementEntry +} + +// preview reports the object side on rep.RcloneResult, exactly as the +// content-addressed preview does, and the pack side on rep.PackPreview. +func (o *packedOps) preview(rep *Report) { + o.objects.preview(rep) + rep.RcloneResult.Checked += o.alreadyInPack + rep.PackPreview = previewPacks(o.members, o.packSize) +} + +// previewPacks summarises the small (pack-routed) content without +// assembling a pack. small is already hash-sorted, so the size-band walk +// mirrors buildOnePack's — accumulate members until the running total +// reaches packSize, then close a pack — but over uncompressed sizes, +// yielding an estimated (not bounded) pack count (see PackPreview). +func previewPacks(small []store.PathDelta, packSize int64) PackPreview { + p := PackPreview{SizeBand: packSize} for i := 0; i < len(small); { var packBytes int64 for i < len(small) { @@ -210,7 +167,7 @@ func (h *packedHandler) previewPacks(small []store.PathDelta) PackPreview { p.Contents++ p.Bytes += small[i].SizeBytes i++ - if packBytes >= h.dest.PackSize { + if packBytes >= packSize { break } } @@ -219,65 +176,58 @@ func (h *packedHandler) previewPacks(small []store.PathDelta) PackPreview { return p } -// push runs the transactional landing: delta → objects (large) + packs -// (small) → placement map → manifest segment → local pack rows → per-pack -// fingerprints → vector advance. rep.Status starts failed and is promoted -// only after every piece is confirmed present, so a partial landing never -// presents as success. -func (h *packedHandler) push(ctx context.Context, rep *Report, volID, runID int64) error { - rep.Status = store.RunStatusFailed - watermark, err := h.watermark(ctx, volID) +// translate routes the delta's present content by dest.PackThreshold (see +// routeBySize) and splits the large side by upload record. +func (h *packedHandler) translate(ctx context.Context, p pushPlan) (*packedOps, error) { + large, small, alreadyInPack, err := h.routeBySize(ctx, plannedUploads(p.delta)) if err != nil { - return err + return nil, err } - // Snapshot the advance before any transfer so a row committed mid-push - // is never folded into it — the same discipline the content-addressed - // handler uses. - advance, err := captureDurabilityAdvance(ctx, h.store, volID) + objects, err := h.splitRecorded(ctx, large) if err != nil { - return err + return nil, err } - delta, err := h.store.ListPathDeltaSince(ctx, volID, watermark) - if err != nil { - return fmt.Errorf("compute path delta since run %d: %w", watermark, err) - } - rep.Verification.Files = int64(len(delta)) - // Same reading as the content-addressed push: the delta is what this - // run changes at the destination, so an empty one folds as a no-op. - rep.Changed = knownChanged(int64(len(delta))) - large, small, err := h.routeBySize(ctx, rep, plannedUploads(delta)) - if err != nil { - return err - } - if err := h.uploadObjects(ctx, rep, runID, large); err != nil { + return &packedOps{objects: objects, members: small, alreadyInPack: alreadyInPack, packSize: h.dest.PackSize}, nil +} + +// execute lands the large content as objects, then assembles and uploads +// the small content's packs. Nothing about the packs is recorded in the +// store yet: seal does that once the map and segment landed. +func (h *packedHandler) execute(ctx context.Context, rep *Report, runID int64, ops *packedOps) error { + rep.RcloneResult.Checked += ops.alreadyInPack + if err := h.uploadObjects(ctx, rep, runID, ops.objects); err != nil { return err } - writes, placements, err := h.assembleAndUploadPacks(ctx, rep, runID, small) + writes, placements, err := h.assembleAndUploadPacks(ctx, rep, runID, ops.members) if err != nil { return err } - if err := h.uploadPlacementMap(ctx, placements, runID); err != nil { + ops.writes, ops.placements = writes, placements + return nil +} + +// seal writes the placement map (the layout's landing evidence) and the +// manifest segment, then records the packs and reads their fingerprints. +// A pack_members row therefore always has its bytes, and their location, +// offsite, and a run that failed earlier left nothing here to re-pack. +func (h *packedHandler) seal(ctx context.Context, rep *Report, runID int64, p pushPlan, ops *packedOps) error { + if err := h.uploadPlacementMap(ctx, ops.placements, runID); err != nil { return err } - if err := h.uploadSegment(ctx, delta, runID); err != nil { + if err := h.uploadSegment(ctx, p.delta, runID); err != nil { return err } - // Recorded only after every pack, the map, and the segment confirmed - // landing: a pack_members row always has its bytes (and their location) - // offsite, and a run that failed earlier left nothing here to re-pack. - if err := h.store.InsertPacks(ctx, writes); err != nil { + if err := h.store.InsertPacks(ctx, ops.writes); err != nil { return fmt.Errorf("record packs for run %d: %w", runID, err) } - rep.Status = store.RunStatusSuccess - rep.Verification.Bytes = rep.RcloneResult.Bytes - return h.certifyPacked(ctx, rep, volID, runID, writes, advance) + h.capturePackFingerprints(ctx, rep, runID, ops.writes) + return nil } -// certifyPacked closes the durability seam: it records a remote_packs row -// per landed pack, reads each pack's scan-back fingerprint, and advances -// the destination vector to fingerprint-verified only once the whole -// (volume, destination) pair carries a verified fingerprint behind every -// present file content. That whole-state check is +// advanceMethod closes the durability seam: the vector advances as +// fingerprint-verified only once the whole (volume, destination) pair +// carries a verified fingerprint behind every present file content, and is +// held otherwise. That whole-state check is // CountVolumeContentsPendingFingerprint, which counts present contents // lacking a verified remote_objects (per-hash object) or remote_packs (pack // member) fingerprint on this destination — so it covers packs and per-hash @@ -285,11 +235,8 @@ func (h *packedHandler) push(ctx context.Context, rep *Report, volID, runID int6 // // The placement map and manifest segment are deliberately NOT in that // pending set: they are re-derivable squirrel-written metadata that carry -// no scan-back fingerprint. Their durability before this advance is handled -// upstream in push, which uploads and confirms both landed at their -// expected size before promoting the run to success — a run whose map or -// segment failed to land returns failed and never reaches certifyPacked, so -// the vector is untouched. +// no scan-back fingerprint, and seal confirmed both landed at their +// expected size before this runs. // // Gating on the whole pending set rather than this run's writes is the // friction-log F13 fix: a run that packs nothing no longer advances @@ -297,26 +244,17 @@ func (h *packedHandler) push(ctx context.Context, rep *Report, volID, runID int6 // anywhere in the pair holds the whole advance. `squirrel verify` fills a // pending fingerprint later and re-attempts this advance itself (see the // store upgrade), so the vector no longer stalls until the next -// content-writing sync. rep.Verification stays unverified (presence+size is -// not content-verified), so RunPair does not advance the vector a second -// time. -func (h *packedHandler) certifyPacked(ctx context.Context, rep *Report, volID, runID int64, writes []store.PackWrite, advance []store.OriginComponent) error { - h.capturePackFingerprints(ctx, rep, runID, writes) - pending, err := h.store.CountVolumeContentsPendingFingerprint(ctx, volID, h.dest.Name) +// content-writing sync. +func (h *packedHandler) advanceMethod(ctx context.Context, rep *Report, p pushPlan) (string, error) { + pending, err := h.store.CountVolumeContentsPendingFingerprint(ctx, p.volumeID, h.dest.Name) if err != nil { - return fmt.Errorf("count pending fingerprints for %s: %w", h.dest.Name, err) + return "", fmt.Errorf("count pending fingerprints for %s: %w", h.dest.Name, err) } if pending > 0 { rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination %q: %d content(s) are not yet fingerprint-verified; the durability vector was not advanced — run `squirrel verify` to certify them", h.dest.Name, pending)) - return nil + return "", nil } - if len(advance) == 0 { - return nil - } - if err := h.store.AdvanceDestinationVectorTo(ctx, volID, h.dest.Name, store.VerifyMethodFingerprint, advance); err != nil { - return fmt.Errorf("advance destination vector for %s: %w", h.dest.Name, err) - } - return nil + return store.VerifyMethodFingerprint, nil } // capturePackFingerprints records a per-destination upload row for each @@ -327,7 +265,7 @@ func (h *packedHandler) certifyPacked(ctx context.Context, rep *Report, volID, r // backends read `rclone lsjson --hash`. A pack whose fingerprint could not // be read stays pending (checksum NULL) with a warning — never a fabricated // value. The whole-pair pending tally (CountVolumeContentsPendingFingerprint) -// is what certifyPacked gates the vector advance on, so this returns nothing. +// is what advanceMethod gates the vector advance on, so this returns nothing. func (h *packedHandler) capturePackFingerprints(ctx context.Context, rep *Report, runID int64, writes []store.PackWrite) { targets := make([]captureTarget, 0, len(writes)) for _, w := range writes { @@ -354,41 +292,26 @@ func (h *packedHandler) capturePackFingerprints(ctx context.Context, rep *Report h.captureScanBackFingerprints(ctx, rep, PacksDirName, targets) } -// watermark resolves the run id the delta starts after: the last -// successful sync of this (volume, destination), or 0 for a fresh -// destination. The last success must still have its placement map at the -// destination — every successful packed run uploads one (empty when no -// small content was new) — so its absence means the recorded history -// belongs to a different layout (a mirror leaves no map, a -// content-addressed root leaves objects and segments but no packs/ map) and -// a delta computed against it would silently skip everything that era -// covered. This is the packed analogue of the content-addressed watermark -// guard, strengthened to also refuse an object-per-hash history. -func (h *packedHandler) watermark(ctx context.Context, volID int64) (int64, error) { - last, err := h.store.LatestSuccessfulSyncRun(ctx, volID, h.dest.Name) - if store.IsNotFound(err) { - return 0, nil - } - if err != nil { - return 0, fmt.Errorf("lookup last successful sync of %s: %w", h.dest.Name, err) - } - mapURI := h.mapURI(last.ID) - if _, err := h.rcl.statRemote(ctx, mapURI, checkersArgs(h.dest)...); err != nil { - if freshStartOnEmptyRoot(ctx, h.rcl, h.dest) { - return 0, nil - } - return 0, fmt.Errorf("destination %q: the last successful sync (run %d) left no pack placement map at %s — its history is not packed (a mirror or content-addressed root); point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w: %w", h.dest.Name, last.ID, mapURI, h.dest.Name, err, ErrRefused) - } - return last.ID, nil +// landed reports whether runID's placement map is at the destination. +// Every successful packed run uploads one (empty when no small content was +// new), so its absence means the recorded history belongs to a different +// layout — a mirror leaves no map, a content-addressed root leaves objects +// and segments but no packs/ map — or a wiped root. +func (h *packedHandler) landed(ctx context.Context, runID int64) (bool, error) { + return h.rcl.statRemoteExists(ctx, h.mapURI(runID), checkersArgs(h.dest)...) +} + +func (h *packedHandler) foreignHistory(runID int64) error { + return fmt.Errorf("destination %q: the last successful sync (run %d) left no pack placement map at %s — its history is not packed (a mirror or content-addressed root); point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w", h.dest.Name, runID, h.mapURI(runID), h.dest.Name, ErrRefused) } // routeBySize splits the planned uploads by dest.PackThreshold: content at // or above it becomes a per-hash object (large), content below it becomes a // pack member (small) unless it is already packed — a pack is // content-global and assembled once, so already-packed content is skipped -// and counted as checked. small is returned sorted by hash so pack -// assembly is deterministic. -func (h *packedHandler) routeBySize(ctx context.Context, rep *Report, planned []store.PathDelta) (large, small []store.PathDelta, err error) { +// and counted. small is returned sorted by hash so pack assembly is +// deterministic. +func (h *packedHandler) routeBySize(ctx context.Context, planned []store.PathDelta) (large, small []store.PathDelta, alreadyInPack int64, err error) { for _, d := range planned { if d.SizeBytes >= h.dest.PackThreshold { large = append(large, d) @@ -396,10 +319,10 @@ func (h *packedHandler) routeBySize(ctx context.Context, rep *Report, planned [] } packed, err := h.store.HasPackMember(ctx, d.ContentID) if err != nil { - return nil, nil, fmt.Errorf("lookup pack member for %s: %w", d.Path, err) + return nil, nil, 0, fmt.Errorf("lookup pack member for %s: %w", d.Path, err) } if packed { - rep.RcloneResult.Checked++ + alreadyInPack++ continue } small = append(small, d) @@ -407,7 +330,7 @@ func (h *packedHandler) routeBySize(ctx context.Context, rep *Report, planned [] slices.SortFunc(small, func(a, b store.PathDelta) int { return bytes.Compare(a.Blake3, b.Blake3) }) - return large, small, nil + return large, small, alreadyInPack, nil } // assembleAndUploadPacks bundles the sorted small content into tar.zst diff --git a/sync/push.go b/sync/push.go new file mode 100644 index 0000000..10763c0 --- /dev/null +++ b/sync/push.go @@ -0,0 +1,210 @@ +package sync + +import ( + "context" + "fmt" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" +) + +// pushPlan is what one push must land: the volume's index changes since the +// destination's last confirmed run, and the durability snapshot the push +// advances to once they land. +type pushPlan struct { + volumeID int64 + watermark int64 // last confirmed run; 0 for a fresh destination + delta []store.PathDelta // ListPathDeltaSince(volumeID, watermark) + advance []store.OriginComponent // captured before any transfer; nil on a dry run +} + +// operations is one layout's translation of a plan into work. +type operations interface { + // preview records on rep what executing the operations would transfer. + // It is all a dry run reports. + preview(rep *Report) +} + +// layout is one destination layout's part of a push. pushThrough runs every +// layout through the same sequence, so the watermark rule, run allocation +// and durability advance are decided once for all of them. +type layout[O operations] interface { + // markers gates the push on the destination's markers, writing missing + // ones under opts.Init. A dry run only checks. + markers(ctx context.Context, rep *Report, volumeID int64, opts Options) error + // landed reports whether runID left this layout's landing evidence. + landed(ctx context.Context, runID int64) (bool, error) + // rootEmpty reports whether the destination root holds nothing beyond + // squirrel's markers. + rootEmpty(ctx context.Context) (bool, error) + // foreignHistory is the refusal for a last success at runID that left + // no landing evidence on a destination that is no fresh start. + foreignHistory(runID int64) error + // translate turns the plan into this layout's operations. It reads + // squirrel's records and writes nothing: a dry run is translate alone. + translate(ctx context.Context, p pushPlan) (O, error) + // execute performs the operations and records each confirmed one. + execute(ctx context.Context, rep *Report, runID int64, ops O) error + // seal writes the run's landing evidence once every operation is + // confirmed. + seal(ctx context.Context, rep *Report, runID int64, p pushPlan, ops O) error + // advanceMethod names the evidence the confirmed landing earns. An + // empty method holds the durability vector where it is. + advanceMethod(ctx context.Context, rep *Report, p pushPlan) (string, error) +} + +// pushTarget is the (volume, destination) pair one layout push serves. +type pushTarget struct { + store *store.Store + vol *config.Volume + dest *config.Destination +} + +// pushThrough is the single push driver every layout shares: +// +// requireIndexedVolume → markers → begin run → plan → translate → execute → seal → advance → finish → ride-along +// +// A dry run stops after translate and reports the operations' preview; it +// writes no runs row. The runs row records shallow=true: no layout reads +// the landed bytes back through BLAKE3, and the audit trail says so. +func pushThrough[O operations](ctx context.Context, t pushTarget, l layout[O], opts Options) (Report, error) { + rep := Report{Volume: t.vol.Name, Destination: t.dest.Name} + // Stamped up front so output renderers key their formatting off the + // method even when the push fails early. + rep.Verification.Method = VerifyMethodPresenceSize + volID, err := requireIndexedVolume(ctx, t.store, t.vol) + if err != nil { + return rep, err + } + if err := l.markers(ctx, &rep, volID, opts); err != nil { + return rep, err + } + if opts.DryRun { + return rep, previewPush(ctx, t, l, &rep, volID) + } + runID, err := beginSyncRunGuarded(ctx, t.store, false, store.SyncRunSpec{ + VolumeID: volID, + Destination: t.dest.Name, + Shallow: true, + }, t.vol.Name) + if err != nil { + return rep, err + } + rep.RunID = runID + if opts.OnRunID != nil { + opts.OnRunID(runID) + } + err = landPush(ctx, t, l, &rep, volID, runID) + finishHandlerRun(ctx, t.store, &rep, err) + opts.Snapshot.afterSync(ctx, &rep, t.vol, t.dest) + return rep, err +} + +// previewPush computes the same plan and translation a real push would, +// then reports the translation's preview. The watermark rule still reads +// the destination, so a dry run refuses exactly what a push would. +func previewPush[O operations](ctx context.Context, t pushTarget, l layout[O], rep *Report, volID int64) error { + p, err := planPush(ctx, t, l, volID, false) + if err != nil { + return err + } + rep.Verification.Files = int64(len(p.delta)) + ops, err := l.translate(ctx, p) + if err != nil { + return err + } + ops.preview(rep) + rep.Status = store.RunStatusSuccess + return nil +} + +// landPush is the transactional landing: plan → operations → evidence → +// vector. rep.Status starts failed and is promoted only after the vector +// advanced: a confirmed landing whose evidence failed to record must not +// present as success, or the next watermark would skip past it. +func landPush[O operations](ctx context.Context, t pushTarget, l layout[O], rep *Report, volID, runID int64) error { + rep.Status = store.RunStatusFailed + p, err := planPush(ctx, t, l, volID, true) + if err != nil { + return err + } + rep.Verification.Files = int64(len(p.delta)) + // The delta is what this push newly records at the destination, so an + // empty one is a genuine no-op, which is what the runs fold keys on + // (#182). + rep.Changed = knownChanged(int64(len(p.delta))) + ops, err := l.translate(ctx, p) + if err != nil { + return err + } + if err := l.execute(ctx, rep, runID, ops); err != nil { + return err + } + if err := l.seal(ctx, rep, runID, p, ops); err != nil { + return err + } + method, err := l.advanceMethod(ctx, rep, p) + if err != nil { + return err + } + if method != "" && len(p.advance) > 0 { + if err := t.store.AdvanceDestinationVectorTo(ctx, volID, t.dest.Name, method, p.advance); err != nil { + return fmt.Errorf("advance destination vector for %s: %w", t.dest.Name, err) + } + } + rep.Status = store.RunStatusSuccess + rep.Verification.Bytes = rep.RcloneResult.Bytes + return nil +} + +// planPush resolves the watermark and the delta after it. A real push also +// captures the durability advance, before the delta, so a row committed +// mid-push is never folded into it. +func planPush[O operations](ctx context.Context, t pushTarget, l layout[O], volID int64, captureAdvance bool) (pushPlan, error) { + watermark, err := pushWatermark(ctx, t, l, volID) + if err != nil { + return pushPlan{}, err + } + p := pushPlan{volumeID: volID, watermark: watermark} + if captureAdvance { + if p.advance, err = captureDurabilityAdvance(ctx, t.store, volID); err != nil { + return pushPlan{}, err + } + } + if p.delta, err = t.store.ListPathDeltaSince(ctx, volID, watermark); err != nil { + return pushPlan{}, fmt.Errorf("compute path delta since run %d: %w", watermark, err) + } + return p, nil +} + +// pushWatermark applies the watermark rule every layout shares: +// +// 1. no successful sync of this (volume, destination): 0; +// 2. the last success left its landing evidence: that run's id; +// 3. the evidence is absent but the destination is a fresh start: 0; +// 4. otherwise refuse, because a delta computed against a history this +// destination no longer shows would silently skip content. +func pushWatermark[O operations](ctx context.Context, t pushTarget, l layout[O], volID int64) (int64, error) { + last, err := t.store.LatestSuccessfulSyncRun(ctx, volID, t.dest.Name) + if store.IsNotFound(err) { + return 0, nil + } + if err != nil { + return 0, fmt.Errorf("lookup last successful sync of %s: %w", t.dest.Name, err) + } + landed, err := l.landed(ctx, last.ID) + if err != nil { + return 0, fmt.Errorf("destination %q: look up the landing evidence of run %d: %w", t.dest.Name, last.ID, err) + } + if landed { + return last.ID, nil + } + fresh, err := l.rootEmpty(ctx) + if err != nil { + return 0, fmt.Errorf("destination %q: check whether the root is empty: %w", t.dest.Name, err) + } + if fresh { + return 0, nil + } + return 0, l.foreignHistory(last.ID) +} diff --git a/sync/sync.go b/sync/sync.go index b43907a..f592bc6 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -857,22 +857,6 @@ func remoteSubpathURI(dest *config.Destination, subpath string) string { } } -// freshStartOnEmptyRoot reports whether a missing layout marker (a manifest -// segment or pack placement map absent at the last recorded success) should -// be read as a fresh start rather than a layout conflict. It is true only -// when dest's configured root holds no files on the remote — a wiped or -// repointed destination, or one whose recorded state was cleared by -// `squirrel destination reset` — so the name-keyed run history no longer -// describes anything on disk and a fresh full push is safe (it skips -// nothing). A non-empty root, or any error probing it, returns false so the -// caller keeps its refusal: fail-closed, because refusing a real -// layout-switch is recoverable while a delta against a stale watermark -// silently skips content. -func freshStartOnEmptyRoot(ctx context.Context, rcl *Rclone, dest *config.Destination) bool { - empty, err := rcl.remoteRootEmpty(ctx, remoteSubpathURI(dest, ""), rootMarkerNames(dest), checkersArgs(dest)...) - return err == nil && empty -} - // destinationVolumeURI returns the rclone destination spec for the given // volume under dest. func destinationVolumeURI(dest *config.Destination, volumeName string) string { From a1be793d546bff95f4718653951372e83309da14 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Wed, 23 Sep 2026 23:39:29 +0200 Subject: [PATCH 04/61] sync: refuse a wiped root whose upload records remain The watermark rule read an empty destination root as a fresh start even when squirrel still recorded uploads to it. A root wiped without `squirrel destination reset` and re-marked therefore skipped every recorded object, wrote a manifest segment mapping paths onto bytes that were gone, and closed the run as success. A fresh start now also requires that the destination has no upload records (store.DestinationHasUploadRecords). Otherwise the push refuses and points at a fresh root or destination reset. --- design/native-mirror.md | 15 +++++------ store/content_presence.go | 18 +++++++++++++ sync/push.go | 28 ++++++++++++++++++--- sync/push_test.go | 53 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 104 insertions(+), 10 deletions(-) create mode 100644 sync/push_test.go diff --git a/design/native-mirror.md b/design/native-mirror.md index 47d2441..5e45af5 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -168,8 +168,8 @@ Each layout's landing evidence lives at a different place: No two layouts share a location, so a destination switched from one layout to another is refused. -**The last condition in rule 3 is new, and it fixes a live bug.** Today -`freshStartOnEmptyRoot` checks only that the remote root is empty. +**The last condition in rule 3 is new, and it fixes a live bug.** Before the +planner, `freshStartOnEmptyRoot` checked only that the remote root was empty. Consider a content-addressed destination whose root was wiped without a `destination reset`, then re-marked with `--init`: @@ -179,11 +179,12 @@ Consider a content-addressed destination whose root was wiped without a 4. The run closes as `success` and advances the durability vector. If the old fingerprints were verified, it advances as `fingerprint-verified`. -A throwaway test confirmed this. It ran one push, wiped the fake remote, -re-seeded the marker and ran a second push. The second push reported -`success` with `transferred=0 checked=1`, and the object was absent. Only a -later verify pass would notice. The planner has to fail closed here, because -the mirror's records would repeat the same mistake. +`TestPushRefusesWipedRootWithUploadRecords` pins it. It runs one push, wipes +the fake remote, re-seeds the markers and runs a second push. Before the fix +that push reported `success` with `transferred=0 checked=1`, and the object +was absent; only a later verify pass would have noticed. The planner now fails +closed here (`DestinationHasUploadRecords`), because the mirror's records would +repeat the same mistake. ### Repairs: the planner's second input diff --git a/store/content_presence.go b/store/content_presence.go index e4e7035..bfa9e98 100644 --- a/store/content_presence.go +++ b/store/content_presence.go @@ -104,3 +104,21 @@ func (s *Store) ContentFingerprintVerified(ctx context.Context, contentID int64, } return verified != 0, nil } + +// DestinationHasUploadRecords reports whether the index records any upload +// to the destination, in any volume: a per-hash object or a pack. The push +// watermark rule reads an empty root as a fresh start only when this is +// false; otherwise the root was wiped behind squirrel's back, and a push +// would skip content these records still claim is there. +func (s *Store) DestinationHasUploadRecords(ctx context.Context, destination string) (bool, error) { + var has int + err := s.db.QueryRowContext(ctx, ` + SELECT + EXISTS (SELECT 1 FROM remote_objects WHERE destination = ?) + OR EXISTS (SELECT 1 FROM remote_packs WHERE destination = ?) + `, destination, destination).Scan(&has) + if err != nil { + return false, fmt.Errorf("lookup upload records on %q: %w", destination, err) + } + return has != 0, nil +} diff --git a/sync/push.go b/sync/push.go index 10763c0..68cc48c 100644 --- a/sync/push.go +++ b/sync/push.go @@ -181,7 +181,8 @@ func planPush[O operations](ctx context.Context, t pushTarget, l layout[O], volI // // 1. no successful sync of this (volume, destination): 0; // 2. the last success left its landing evidence: that run's id; -// 3. the evidence is absent but the destination is a fresh start: 0; +// 3. the evidence is absent but the destination is a fresh start +// (freshStart): 0; // 4. otherwise refuse, because a delta computed against a history this // destination no longer shows would silently skip content. func pushWatermark[O operations](ctx context.Context, t pushTarget, l layout[O], volID int64) (int64, error) { @@ -199,12 +200,33 @@ func pushWatermark[O operations](ctx context.Context, t pushTarget, l layout[O], if landed { return last.ID, nil } - fresh, err := l.rootEmpty(ctx) + fresh, err := freshStart(ctx, t, l) if err != nil { - return 0, fmt.Errorf("destination %q: check whether the root is empty: %w", t.dest.Name, err) + return 0, err } if fresh { return 0, nil } return 0, l.foreignHistory(last.ID) } + +// freshStart reports whether a destination whose last success left no +// landing evidence may start over from watermark 0: its root holds nothing +// beyond squirrel's markers, and squirrel holds no upload records for it. +// An empty root with records left behind was wiped without a `squirrel +// destination reset`; starting over would skip every upload those records +// still claim and close the run as success. +func freshStart[O operations](ctx context.Context, t pushTarget, l layout[O]) (bool, error) { + empty, err := l.rootEmpty(ctx) + if err != nil { + return false, fmt.Errorf("destination %q: check whether the root is empty: %w", t.dest.Name, err) + } + if !empty { + return false, nil + } + recorded, err := t.store.DestinationHasUploadRecords(ctx, t.dest.Name) + if err != nil { + return false, err + } + return !recorded, nil +} diff --git a/sync/push_test.go b/sync/push_test.go new file mode 100644 index 0000000..2e61861 --- /dev/null +++ b/sync/push_test.go @@ -0,0 +1,53 @@ +package sync + +import ( + "context" + "errors" + "slices" + "strings" + "testing" + + "github.com/mbertschler/squirrel/store" +) + +// TestPushRefusesWipedRootWithUploadRecords: a root wiped without a +// `squirrel destination reset` and re-marked looks like a fresh start, but +// the upload records still claim its content. Starting over would skip +// every recorded object, write a segment mapping paths onto bytes that are +// gone, and close the run as success, so the push refuses instead. A reset +// clears the records and lifts the refusal. +func TestPushRefusesWipedRootWithUploadRecords(t *testing.T) { + for layout, setup := range keyedArchiveFixtures() { + t.Run(layout, func(t *testing.T) { + f := setup(t) + f.write(t, "a.txt", "alpha") + f.index(t) + if _, err := f.sync(t); err != nil { + t.Fatalf("first push: %v", err) + } + + f.wipeRemote(t) + f.seedNamingMarker(t) + f.seedMarker(t, "pics") + markersOnly := f.remoteEntries(t) + rep, err := f.sync(t) + if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "destination reset") { + t.Fatalf("push to a wiped root: err = %v, want a refusal naming `destination reset`", err) + } + if rep.Status != store.RunStatusRefused { + t.Fatalf("Status = %q, want refused", rep.Status) + } + if after := f.remoteEntries(t); !slices.Equal(after, markersOnly) { + t.Fatalf("the refused push wrote to the root: %v, want only the markers %v", after, markersOnly) + } + + if _, _, err := f.store.ResetDestination(context.Background(), "offsite"); err != nil { + t.Fatalf("ResetDestination: %v", err) + } + rep, err = f.sync(t) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("push after reset: status=%q err=%v", rep.Status, err) + } + }) + } +} From e9888a35e3d104fee139bc1d3d58b39b1e0704e8 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Wed, 23 Sep 2026 23:45:58 +0200 Subject: [PATCH 05/61] store: add remote_paths, the native mirror's destination record Schema v32 adds remote_paths: one STRICT row per version squirrel wrote at a mirror path, keyed on its files row, in one of the states committing, live, displacing, displaced and lost. A partial unique index keeps at most one committing-or-live row per path, and a partial index serves the reconcile, which reads only unsettled rows. Each move has its own transition function, which applies only to rows in the move's source state. ContentPresentOnDestination counts live and displaced mirror copies, DestinationHasUploadRecords counts every row, and destination reset clears the table and reports it. PathDelta carries the files row's folder id so a push can key its rows. --- cmd/squirrel/destination_reset.go | 4 +- docs/src/content/docs/guides/recovery.md | 12 +- docs/src/content/docs/reference/cli.md | 4 +- store/content_presence.go | 30 +-- store/destination_reset.go | 25 +-- store/migrate_v27_test.go | 12 +- store/migrations.go | 59 +++++- store/path_delta.go | 7 +- store/remote_paths.go | 188 +++++++++++++++++++ store/remote_paths_test.go | 223 +++++++++++++++++++++++ store/schema.sql | 28 ++- 11 files changed, 553 insertions(+), 39 deletions(-) create mode 100644 store/remote_paths.go create mode 100644 store/remote_paths_test.go diff --git a/cmd/squirrel/destination_reset.go b/cmd/squirrel/destination_reset.go index 88e649b..9b469c0 100644 --- a/cmd/squirrel/destination_reset.go +++ b/cmd/squirrel/destination_reset.go @@ -107,11 +107,11 @@ func printResetPreview(out io.Writer, name string, c store.DestinationResetCount func printResetResult(out io.Writer, name string, c store.DestinationResetCounts, runID int64) { fmt.Fprintf(out, "reset destination %q (run %d):\n", name, runID) printResetCounts(out, c) - fmt.Fprintf(out, "next: the next sync re-uploads to %q; for a content-addressed or packed layout, wipe or repoint the remote root so the layout guard sees a fresh start\n", name) + fmt.Fprintf(out, "next: the next sync re-uploads to %q; for a content-addressed, packed or native mirror layout, wipe or repoint the remote root so the layout guard sees a fresh start\n", name) } func printResetCounts(out io.Writer, c store.DestinationResetCounts) { - fmt.Fprintf(out, " upload records: %d objects, %d packs\n", c.RemoteObjects, c.RemotePacks) + fmt.Fprintf(out, " upload records: %d objects, %d packs, %d mirror paths\n", c.RemoteObjects, c.RemotePacks, c.RemotePaths) fmt.Fprintf(out, " durability vector: %d component(s)\n", c.VectorComponents) fmt.Fprintf(out, " push freshness: %d row(s)\n", c.FreshnessRows) } diff --git a/docs/src/content/docs/guides/recovery.md b/docs/src/content/docs/guides/recovery.md index 534783a..53bcca2 100644 --- a/docs/src/content/docs/guides/recovery.md +++ b/docs/src/content/docs/guides/recovery.md @@ -11,9 +11,9 @@ an opt-in operator command. This page collects the recovery paths. ## Resetting a wrecked destination `squirrel destination reset ` forgets everything the index records about -a destination's remote state — its per-content and per-pack upload ledgers, its -live durability vector, and its push-freshness maxima — so the next sync treats -the destination as fresh and re-uploads. +a destination's remote state — its per-content, per-pack and per-mirror-path +upload ledgers, its live durability vector, and its push-freshness maxima — so +the next sync treats the destination as fresh and re-uploads. Use it when a destination's recorded state no longer matches reality and a sync refuses to proceed. The classic case: after wiping a remote, or pointing an @@ -21,7 +21,9 @@ existing destination name at a fresh `root`, the [content-addressed](/squirrel/layouts/content-addressed/) or [packed](/squirrel/layouts/packed/) layout guard refuses — its recorded history under that destination name expects a manifest segment or placement map that is -no longer there. Before this verb, the only escape was hand-editing SQLite or +no longer there. An emptied root is refused too while its upload records remain: +a push would otherwise skip everything those records claim is still there. +Before this verb, the only escape was hand-editing SQLite or renaming the destination across every machine's config. ```sh @@ -36,7 +38,7 @@ clear, and refuses without `--yes` (or a `--dry-run` preview). Cleared (derived state only): -- `remote_objects` and `remote_packs` — the upload ledgers. +- `remote_objects`, `remote_packs` and `remote_paths` — the upload ledgers. - the destination's durability vector and push-freshness rows. Preserved (the audit trail): diff --git a/docs/src/content/docs/reference/cli.md b/docs/src/content/docs/reference/cli.md index b7199a0..89d1e50 100644 --- a/docs/src/content/docs/reference/cli.md +++ b/docs/src/content/docs/reference/cli.md @@ -477,8 +477,8 @@ On its own it prints help. See [Recovery & disaster runbooks](/squirrel/guides/r squirrel destination reset ``` -One positional — the destination name. Clears the `remote_objects`/`remote_packs` -upload ledgers, the durability vector, and the push-freshness rows for the +One positional — the destination name. Clears the +`remote_objects`/`remote_packs`/`remote_paths` upload ledgers, the durability vector, and the push-freshness rows for the destination, so the next sync treats it as fresh and re-uploads. The runs table and the append-only durability advance log are preserved, and the reset is recorded as an audit run; the remote bytes are untouched. diff --git a/store/content_presence.go b/store/content_presence.go index bfa9e98..dfb500a 100644 --- a/store/content_presence.go +++ b/store/content_presence.go @@ -6,14 +6,16 @@ import ( ) // ContentPresentOnDestination reports whether the content is recorded as -// uploaded to the destination by either offsite layout: a remote_objects -// row (the content-addressed per-hash object) or a remote_packs row for a -// pack this content belongs to (the packed layout bundles it). Fingerprint -// state is ignored — this is the upload-once dedup gate, the two-source -// generalisation of HasRemoteObject, so a push never re-uploads bytes -// already offsite in either form. Both branches are per-destination: a pack -// this content sits in counts only when that pack was uploaded to *this* -// destination, so a pack landed elsewhere never suppresses a needed upload. +// stored on the destination by any layout: a remote_objects row (the +// content-addressed per-hash object), a remote_packs row for a pack this +// content belongs to (the packed layout bundles it), or a mirror copy — a +// remote_paths row that is live or displaced (a lost row stopped vouching +// for its bytes). Fingerprint state is ignored — this is the upload-once +// dedup gate, the generalisation of HasRemoteObject, so a push never +// re-uploads bytes already offsite in any form. Every branch is +// per-destination: a pack this content sits in counts only when that pack +// was uploaded to *this* destination, so a pack landed elsewhere never +// suppresses a needed upload. func (s *Store) ContentPresentOnDestination(ctx context.Context, contentID int64, destination string) (bool, error) { var present int err := s.db.QueryRowContext(ctx, ` @@ -24,7 +26,11 @@ func (s *Store) ContentPresentOnDestination(ctx context.Context, contentID int64 JOIN remote_packs rp ON rp.pack_id = pm.pack_id WHERE pm.content_id = ? AND rp.destination = ? ) - `, contentID, destination, contentID, destination).Scan(&present) + OR EXISTS ( + SELECT 1 FROM remote_paths + WHERE content_id = ? AND destination = ? AND state IN ('live', 'displaced') + ) + `, contentID, destination, contentID, destination, contentID, destination).Scan(&present) if err != nil { return false, fmt.Errorf("lookup content presence on %q: %w", destination, err) } @@ -106,7 +112,8 @@ func (s *Store) ContentFingerprintVerified(ctx context.Context, contentID int64, } // DestinationHasUploadRecords reports whether the index records any upload -// to the destination, in any volume: a per-hash object or a pack. The push +// to the destination, in any volume: a per-hash object, a pack, or a +// mirror path in any state. The push // watermark rule reads an empty root as a fresh start only when this is // false; otherwise the root was wiped behind squirrel's back, and a push // would skip content these records still claim is there. @@ -116,7 +123,8 @@ func (s *Store) DestinationHasUploadRecords(ctx context.Context, destination str SELECT EXISTS (SELECT 1 FROM remote_objects WHERE destination = ?) OR EXISTS (SELECT 1 FROM remote_packs WHERE destination = ?) - `, destination, destination).Scan(&has) + OR EXISTS (SELECT 1 FROM remote_paths WHERE destination = ?) + `, destination, destination, destination).Scan(&has) if err != nil { return false, fmt.Errorf("lookup upload records on %q: %w", destination, err) } diff --git a/store/destination_reset.go b/store/destination_reset.go index 198f731..19eb59a 100644 --- a/store/destination_reset.go +++ b/store/destination_reset.go @@ -7,22 +7,23 @@ import ( ) // DestinationResetCounts reports how many recorded-state rows a destination -// reset cleared (or, on a dry run, would clear). The four categories are the -// full derived record squirrel keeps about a destination: the per-content -// and per-pack upload ledgers, the live durability vector, and the -// push-freshness maxima. They span every volume — a destination's recorded +// reset cleared (or, on a dry run, would clear). The five categories are the +// full derived record squirrel keeps about a destination: the per-content, +// per-pack and per-mirror-path upload ledgers, the live durability vector, +// and the push-freshness maxima. They span every volume — a destination's recorded // state is not volume-scoped — so the counts are totals across the index. type DestinationResetCounts struct { RemoteObjects int64 RemotePacks int64 + RemotePaths int64 VectorComponents int64 FreshnessRows int64 } -// Total is the sum of all four categories, used as the reset run's +// Total is the sum of all five categories, used as the reset run's // file_count so the audit trail carries the magnitude at a glance. func (c DestinationResetCounts) Total() int64 { - return c.RemoteObjects + c.RemotePacks + c.VectorComponents + c.FreshnessRows + return c.RemoteObjects + c.RemotePacks + c.RemotePaths + c.VectorComponents + c.FreshnessRows } // Empty reports whether the destination has no recorded state at all — the @@ -56,6 +57,7 @@ func countDestinationRecordedState(ctx context.Context, q rowQuerier, destinatio }{ {&c.RemoteObjects, `SELECT COUNT(*) FROM remote_objects WHERE destination = ?`}, {&c.RemotePacks, `SELECT COUNT(*) FROM remote_packs WHERE destination = ?`}, + {&c.RemotePaths, `SELECT COUNT(*) FROM remote_paths WHERE destination = ?`}, {&c.VectorComponents, `SELECT COUNT(*) FROM destination_run_ids WHERE destination = ?`}, {&c.FreshnessRows, `SELECT COUNT(*) FROM destination_push_freshness WHERE destination = ?`}, } @@ -68,8 +70,8 @@ func countDestinationRecordedState(ctx context.Context, q rowQuerier, destinatio } // ResetDestination forgets everything the index records about a destination's -// remote state — its per-content and per-pack upload ledgers, its live -// durability vector, and its push-freshness maxima — so the next sync treats +// remote state — its per-content, per-pack and per-mirror-path upload +// ledgers, its live durability vector, and its push-freshness maxima — so the next sync treats // the destination as fresh and re-uploads. It is the supported recovery for a // wrecked or repointed destination (friction log F20): before it, a fresh // `root` still refused because the layout guard keyed on run history by @@ -110,8 +112,8 @@ func (s *Store) ResetDestination(ctx context.Context, destination string) (int64 if err := deleteDestinationRecordedStateTx(ctx, tx, destination); err != nil { return 0, DestinationResetCounts{}, err } - note := fmt.Sprintf("destination=%q objects=%d packs=%d vector=%d freshness=%d", - destination, counts.RemoteObjects, counts.RemotePacks, counts.VectorComponents, counts.FreshnessRows) + note := fmt.Sprintf("destination=%q objects=%d packs=%d paths=%d vector=%d freshness=%d", + destination, counts.RemoteObjects, counts.RemotePacks, counts.RemotePaths, counts.VectorComponents, counts.FreshnessRows) if err := appendRunAuditTx(ctx, tx, RunAuditEntry{RunID: runID, Transition: TransitionResetDestination, Note: note}, atNs); err != nil { return 0, DestinationResetCounts{}, err @@ -144,13 +146,14 @@ func insertResetRunTx(ctx context.Context, tx *sql.Tx, atNs int64) (int64, error return id, nil } -// deleteDestinationRecordedStateTx clears the four derived-state tables for +// deleteDestinationRecordedStateTx clears the five derived-state tables for // destination. The append-only destination_run_ids_history and the runs // table are deliberately absent — the reset preserves the audit trail. func deleteDestinationRecordedStateTx(ctx context.Context, tx *sql.Tx, destination string) error { stmts := []string{ `DELETE FROM remote_objects WHERE destination = ?`, `DELETE FROM remote_packs WHERE destination = ?`, + `DELETE FROM remote_paths WHERE destination = ?`, `DELETE FROM destination_run_ids WHERE destination = ?`, `DELETE FROM destination_push_freshness WHERE destination = ?`, } diff --git a/store/migrate_v27_test.go b/store/migrate_v27_test.go index 628411c..4c7cdb5 100644 --- a/store/migrate_v27_test.go +++ b/store/migrate_v27_test.go @@ -138,7 +138,10 @@ func TestMigrateV26ToV27PreservesEveryRow(t *testing.T) { // by later migrations are legitimately present after the rebuild and // absent from the v26 fixture. Naming them keeps the count assertion // exact — a table the rebuild itself invented would still fail here. - addedAfterV27 := []string{"config_drift"} // v29 (#191) + addedAfterV27 := []string{ + "config_drift", // v29 (#191) + "remote_paths", // v32 + } if got, want := len(countsAfter), len(countsBefore)+len(addedAfterV27); got != want { t.Errorf("table count = %d after migration, want %d", got, want) } @@ -147,8 +150,11 @@ func TestMigrateV26ToV27PreservesEveryRow(t *testing.T) { t.Errorf("table %s missing after migration to v%d", table, SchemaVersion) } } - if after := schemaObjectNames(t, s.db); !equalStrings(after, objectsBefore) { - t.Errorf("indexes/triggers after migration = %v, want %v", after, objectsBefore) + indexesAddedAfterV27 := []string{"idx_remote_paths_unsettled", "uniq_remote_paths_live"} // v32 + wantObjects := append(append([]string{}, objectsBefore...), indexesAddedAfterV27...) + sort.Strings(wantObjects) + if after := schemaObjectNames(t, s.db); !equalStrings(after, wantObjects) { + t.Errorf("indexes/triggers after migration = %v, want %v", after, wantObjects) } assertContentRowIntact(t, s) diff --git a/store/migrations.go b/store/migrations.go index e7353c0..68cc3fe 100644 --- a/store/migrations.go +++ b/store/migrations.go @@ -10,7 +10,7 @@ import ( ) // SchemaVersion is the schema version this binary writes and reads. -const SchemaVersion = 31 +const SchemaVersion = 32 // freshSchemaBaseline is the version applied to a brand-new database. The // chain in `migrations` continues from here. v1 is no longer reachable from @@ -74,6 +74,7 @@ func buildMigrations(mctx migrationCtx) []migration { {version: 29, up: migrateV28ToV29}, {version: 30, up: migrateV29ToV30}, {version: 31, up: migrateV30ToV31}, + {version: 32, up: migrateV31ToV32}, } } @@ -2449,3 +2450,59 @@ func relabelBlake3ComponentsV31(ctx context.Context, tx *sql.Tx) error { } return nil } + +// --- v31 → v32 --- + +// migrateV31ToV32 adds remote_paths, the native mirror's destination +// record and its counterpart of remote_objects: one row per version +// squirrel wrote at a mirror path, keyed on the files row it came from. +// The state column records each move before it happens (committing → +// live, live → displacing → displaced, anything → lost), so a push that +// crashed mid-move is settled by the next one from where the bytes are. +// A displaced version's location is derived: +// .squirrel-history/run-/. +// +// At most one committing-or-live row per (destination, path), enforced by +// a partial unique index; the unsettled index serves the reconcile at push +// start, which reads only committing and displacing rows. STRICT per the +// new-table convention; additive, so no existing table is rebuilt. +func migrateV31ToV32(ctx context.Context, db *sql.DB) error { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + + stmts := []string{ + `CREATE TABLE remote_paths ( + id INTEGER PRIMARY KEY, + destination TEXT NOT NULL, + folder_id INTEGER NOT NULL, + name TEXT NOT NULL, + content_id INTEGER NOT NULL, + written_run_id INTEGER NOT NULL REFERENCES runs(id), + state TEXT NOT NULL + CHECK (state IN ('committing', 'live', 'displacing', 'displaced', 'lost')), + displaced_run_id INTEGER REFERENCES runs(id), + mtime_ns INTEGER NOT NULL, + checksum_algo TEXT, + checksum TEXT, + verified_at_ns INTEGER, + FOREIGN KEY (folder_id, name, content_id) REFERENCES files (folder_id, name, content_id), + CHECK (state NOT IN ('committing', 'live') OR displaced_run_id IS NULL), + CHECK (state NOT IN ('displacing', 'displaced') OR displaced_run_id IS NOT NULL), + CHECK ((checksum_algo IS NULL) = (checksum IS NULL)) + ) STRICT`, + `CREATE UNIQUE INDEX uniq_remote_paths_live ON remote_paths (destination, folder_id, name) + WHERE state IN ('committing', 'live')`, + `CREATE INDEX idx_remote_paths_unsettled ON remote_paths (destination) + WHERE state IN ('committing', 'displacing')`, + `INSERT INTO schema_version (version) VALUES (32)`, + } + for _, stmt := range stmts { + if _, err := tx.ExecContext(ctx, stmt); err != nil { + return fmt.Errorf("migrate to schema v32: %w", err) + } + } + return tx.Commit() +} diff --git a/store/path_delta.go b/store/path_delta.go index 075246c..97a6b32 100644 --- a/store/path_delta.go +++ b/store/path_delta.go @@ -13,6 +13,7 @@ import ( // bytes gone — unexpectedly or intentionally). type PathDelta struct { Path string + FolderID int64 // with the path's last component, the files row key ContentID int64 Blake3 []byte // raw 32-byte BLAKE3-256 digest SizeBytes int64 @@ -39,7 +40,7 @@ const reservedSubtreeFilter = `fo.path != '.squirrel-history' AND fo.pat // coordinate). func (s *Store) ListPathDeltaSince(ctx context.Context, volumeID, sinceRunID int64) ([]PathDelta, error) { return queryRows(ctx, s.db, ` - SELECT `+pathFromFolderAndName+`, f.content_id, c.blake3, c.size_bytes, f.mtime_ns, f.status + SELECT `+pathFromFolderAndName+`, f.folder_id, f.content_id, c.blake3, c.size_bytes, f.mtime_ns, f.status FROM `+fileFromJoin+` WHERE fo.volume_id = ? AND COALESCE(f.status_changed_run_id, f.first_seen_run_id) > ? @@ -57,7 +58,7 @@ func (s *Store) ListPathDeltaSince(ctx context.Context, volumeID, sinceRunID int // content hash it must fetch from objects/ or a pack. func (s *Store) ListPresentContent(ctx context.Context, volumeID int64) ([]PathDelta, error) { return queryRows(ctx, s.db, ` - SELECT `+pathFromFolderAndName+`, f.content_id, c.blake3, c.size_bytes, f.mtime_ns, f.status + SELECT `+pathFromFolderAndName+`, f.folder_id, f.content_id, c.blake3, c.size_bytes, f.mtime_ns, f.status FROM `+fileFromJoin+` WHERE fo.volume_id = ? AND f.status = 'present' @@ -68,6 +69,6 @@ func (s *Store) ListPresentContent(ctx context.Context, volumeID int64) ([]PathD func scanPathDelta(s rowScanner) (PathDelta, error) { var d PathDelta - err := s.Scan(&d.Path, &d.ContentID, &d.Blake3, &d.SizeBytes, &d.MtimeNs, &d.Status) + err := s.Scan(&d.Path, &d.FolderID, &d.ContentID, &d.Blake3, &d.SizeBytes, &d.MtimeNs, &d.Status) return d, err } diff --git a/store/remote_paths.go b/store/remote_paths.go new file mode 100644 index 0000000..ef6ed9a --- /dev/null +++ b/store/remote_paths.go @@ -0,0 +1,188 @@ +package store + +import ( + "context" + "database/sql" + "fmt" +) + +// The states of a remote_paths row. Each move on the destination is +// recorded before it happens, so a crash leaves the row naming the move in +// flight and the next push settles it from where the bytes actually are. +const ( + // RemotePathCommitting: the version is staged and about to be renamed + // onto its path. + RemotePathCommitting = "committing" + // RemotePathLive: the version is at its path. + RemotePathLive = "live" + // RemotePathDisplacing: the version is about to move into history. + RemotePathDisplacing = "displacing" + // RemotePathDisplaced: the version sits at + // .squirrel-history/run-/. + RemotePathDisplaced = "displaced" + // RemotePathLost: the bytes are no longer where the row says. The row + // keeps its history but stops vouching for its content. + RemotePathLost = "lost" +) + +// RemotePath is one version squirrel wrote at a mirror path on a +// destination, keyed on the files row (FolderID, Name, ContentID) it came +// from. Path and SizeBytes are read through that row's folder and content. +// MtimeNs is the mtime the destination reported for the written version. +type RemotePath struct { + ID int64 + Destination string + FolderID int64 + Name string + ContentID int64 + WrittenRunID int64 + State string + DisplacedRunID sql.NullInt64 + MtimeNs int64 + + Path string + SizeBytes int64 +} + +// RemotePathWrite is the intent to commit one version at a mirror path. +type RemotePathWrite struct { + Destination string + FolderID int64 + Name string + ContentID int64 + RunID int64 + MtimeNs int64 +} + +// BeginRemotePathCommit records the intent to rename a staged version onto +// its path, as a committing row. The path's previous live row must already +// be displacing, displaced or lost: at most one committing-or-live row per +// (destination, path) exists, and the insert fails on that unique index +// otherwise. +func (s *Store) BeginRemotePathCommit(ctx context.Context, w RemotePathWrite) (int64, error) { + if w.Destination == "" { + return 0, fmt.Errorf("BeginRemotePathCommit: destination must be non-empty") + } + res, err := s.db.ExecContext(ctx, ` + INSERT INTO remote_paths (destination, folder_id, name, content_id, written_run_id, state, mtime_ns) + VALUES (?, ?, ?, ?, ?, 'committing', ?) + `, w.Destination, w.FolderID, w.Name, w.ContentID, w.RunID, w.MtimeNs) + if err != nil { + return 0, fmt.Errorf("record commit of %q on %q: %w", w.Name, w.Destination, err) + } + return res.LastInsertId() +} + +// ConfirmRemotePathsLive moves committing rows to live once their versions +// are at their paths. +func (s *Store) ConfirmRemotePathsLive(ctx context.Context, ids ...int64) error { + return s.transitionRemotePaths(ctx, ids, RemotePathLive, ` + UPDATE remote_paths SET state = 'live' WHERE id = ? AND state = 'committing'`) +} + +// BeginRemotePathsDisplace records that live rows are about to move into +// .squirrel-history/run-/. A directory displaced because a file +// replaced it moves every live row under it, all in one call. +func (s *Store) BeginRemotePathsDisplace(ctx context.Context, runID int64, ids ...int64) error { + return s.transitionRemotePaths(ctx, ids, RemotePathDisplacing, ` + UPDATE remote_paths SET state = 'displacing', displaced_run_id = ? + WHERE id = ? AND state = 'live'`, runID) +} + +// ConfirmRemotePathsDisplaced moves displacing rows to displaced once their +// versions are in history. +func (s *Store) ConfirmRemotePathsDisplaced(ctx context.Context, ids ...int64) error { + return s.transitionRemotePaths(ctx, ids, RemotePathDisplaced, ` + UPDATE remote_paths SET state = 'displaced' WHERE id = ? AND state = 'displacing'`) +} + +// RevertRemotePathsLive withdraws a displacement that never happened: the +// version is still at its path, so the row goes back to live. +func (s *Store) RevertRemotePathsLive(ctx context.Context, ids ...int64) error { + return s.transitionRemotePaths(ctx, ids, RemotePathLive, ` + UPDATE remote_paths SET state = 'live', displaced_run_id = NULL + WHERE id = ? AND state = 'displacing'`) +} + +// MarkRemotePathsLost records that the rows' bytes are no longer where the +// rows say: other bytes are there, or nothing. A withdrawn commit ends +// here too, because its version never reached its path. +func (s *Store) MarkRemotePathsLost(ctx context.Context, ids ...int64) error { + return s.transitionRemotePaths(ctx, ids, RemotePathLost, ` + UPDATE remote_paths SET state = 'lost' WHERE id = ? AND state != 'lost'`) +} + +// transitionRemotePaths applies one state transition to every id in one +// transaction. update takes the prefix args followed by the row id; a row +// that is not in the transition's source state fails the whole batch, so +// a record never jumps a move it did not witness. +func (s *Store) transitionRemotePaths(ctx context.Context, ids []int64, to, update string, prefix ...any) error { + if len(ids) == 0 { + return nil + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin remote path transition to %s: %w", to, err) + } + defer func() { _ = tx.Rollback() }() + for _, id := range ids { + res, err := tx.ExecContext(ctx, update, append(append([]any{}, prefix...), id)...) + if err != nil { + return fmt.Errorf("move remote path %d to %s: %w", id, to, err) + } + n, err := res.RowsAffected() + if err != nil { + return fmt.Errorf("move remote path %d to %s: %w", id, to, err) + } + if n != 1 { + return fmt.Errorf("move remote path %d to %s: the row is not in the state this move starts from", id, to) + } + } + return tx.Commit() +} + +// remotePathSelect reads remote_paths rows with their volume-relative path +// and content size (table aliases rp, fo, c). +const remotePathSelect = ` + SELECT rp.id, rp.destination, rp.folder_id, rp.name, rp.content_id, rp.written_run_id, + rp.state, rp.displaced_run_id, rp.mtime_ns, + CASE fo.path WHEN '' THEN rp.name ELSE fo.path || '/' || rp.name END, + c.size_bytes + FROM remote_paths rp + JOIN folders fo ON fo.id = rp.folder_id + JOIN contents c ON c.id = rp.content_id` + +func scanRemotePath(s rowScanner) (RemotePath, error) { + var r RemotePath + err := s.Scan(&r.ID, &r.Destination, &r.FolderID, &r.Name, &r.ContentID, &r.WrittenRunID, + &r.State, &r.DisplacedRunID, &r.MtimeNs, &r.Path, &r.SizeBytes) + return r, err +} + +// ListLiveRemotePaths returns the volume's live rows on the destination, +// ordered by path: what the destination's mirror tree holds by squirrel's +// records. +func (s *Store) ListLiveRemotePaths(ctx context.Context, destination string, volumeID int64) ([]RemotePath, error) { + return queryRows(ctx, s.db, remotePathSelect+` + WHERE rp.destination = ? AND fo.volume_id = ? AND rp.state = 'live' + ORDER BY 10 + `, scanRemotePath, destination, volumeID) +} + +// ListUnsettledRemotePaths returns the volume's committing and displacing +// rows on the destination: the moves a crashed push left in flight. +func (s *Store) ListUnsettledRemotePaths(ctx context.Context, destination string, volumeID int64) ([]RemotePath, error) { + return queryRows(ctx, s.db, remotePathSelect+` + WHERE rp.destination = ? AND fo.volume_id = ? AND rp.state IN ('committing', 'displacing') + ORDER BY rp.id + `, scanRemotePath, destination, volumeID) +} + +// ListRemotePaths returns every row of the volume on the destination, in +// insertion order. +func (s *Store) ListRemotePaths(ctx context.Context, destination string, volumeID int64) ([]RemotePath, error) { + return queryRows(ctx, s.db, remotePathSelect+` + WHERE rp.destination = ? AND fo.volume_id = ? + ORDER BY rp.id + `, scanRemotePath, destination, volumeID) +} diff --git a/store/remote_paths_test.go b/store/remote_paths_test.go new file mode 100644 index 0000000..f79a166 --- /dev/null +++ b/store/remote_paths_test.go @@ -0,0 +1,223 @@ +package store + +import ( + "context" + "testing" +) + +// remotePathFixture indexes one path, "2024/cat.jpg", and returns its +// PathDelta (which carries the files row key) and the observing run. +func remotePathFixture(t *testing.T, s *Store) (PathDelta, int64, int64) { + t.Helper() + ctx := context.Background() + vID := makeVolume(t, s, "/v") + runID := makeRun(t, s, vID) + if err := s.Upsert(ctx, FileRow{ + VolumeID: vID, Path: "2024/cat.jpg", Blake3: digest(0xaa), SizeBytes: 3, MtimeNs: 1, + Status: StatusPresent, FirstSeenRunID: runID, LastSeenRunID: runID, IndexedAtNs: 1, + }, nil); err != nil { + t.Fatalf("Upsert: %v", err) + } + delta, err := s.ListPathDeltaSince(ctx, vID, 0) + if err != nil || len(delta) != 1 { + t.Fatalf("ListPathDeltaSince = %v, %v; want one row", delta, err) + } + return delta[0], vID, runID +} + +func commitWrite(d PathDelta, runID int64) RemotePathWrite { + return RemotePathWrite{Destination: "usb", FolderID: d.FolderID, Name: "cat.jpg", ContentID: d.ContentID, RunID: runID, MtimeNs: 42} +} + +// TestRemotePathLifecycle walks one version through every recorded move — +// committing, live, displacing, displaced — and checks that each read sees +// it where the move left it, with its path and size resolved. +func TestRemotePathLifecycle(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + + id, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)) + if err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + unsettled, err := s.ListUnsettledRemotePaths(ctx, "usb", vID) + if err != nil || len(unsettled) != 1 || unsettled[0].State != RemotePathCommitting { + t.Fatalf("unsettled after commit intent = %+v, %v", unsettled, err) + } + if got := unsettled[0]; got.Path != "2024/cat.jpg" || got.SizeBytes != 3 || got.MtimeNs != 42 { + t.Fatalf("row = %+v, want path 2024/cat.jpg size 3 mtime 42", got) + } + + if err := s.ConfirmRemotePathsLive(ctx, id); err != nil { + t.Fatalf("ConfirmRemotePathsLive: %v", err) + } + live, err := s.ListLiveRemotePaths(ctx, "usb", vID) + if err != nil || len(live) != 1 || live[0].ID != id { + t.Fatalf("live = %+v, %v", live, err) + } + + if err := s.BeginRemotePathsDisplace(ctx, runID, id); err != nil { + t.Fatalf("BeginRemotePathsDisplace: %v", err) + } + if err := s.ConfirmRemotePathsDisplaced(ctx, id); err != nil { + t.Fatalf("ConfirmRemotePathsDisplaced: %v", err) + } + rows, err := s.ListRemotePaths(ctx, "usb", vID) + if err != nil || len(rows) != 1 { + t.Fatalf("ListRemotePaths = %+v, %v", rows, err) + } + if rows[0].State != RemotePathDisplaced || rows[0].DisplacedRunID.Int64 != runID { + t.Fatalf("row = %+v, want displaced by run %d", rows[0], runID) + } + if live, _ := s.ListLiveRemotePaths(ctx, "usb", vID); len(live) != 0 { + t.Fatalf("a displaced row still reads as live: %+v", live) + } +} + +// TestRemotePathTransitionsNeedTheirSourceState: a move applies only to a +// row in the state it starts from, and a batch with one wrong row changes +// nothing, so a record never claims a move it did not witness. +func TestRemotePathTransitionsNeedTheirSourceState(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + id, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)) + if err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + + if err := s.ConfirmRemotePathsDisplaced(ctx, id); err == nil { + t.Fatal("a committing row was confirmed displaced") + } + if err := s.BeginRemotePathsDisplace(ctx, runID, id); err == nil { + t.Fatal("a committing row began a displacement") + } + if err := s.RevertRemotePathsLive(ctx, id); err == nil { + t.Fatal("a committing row was reverted to live") + } + if err := s.ConfirmRemotePathsLive(ctx, id, id+1); err == nil { + t.Fatal("a batch naming a missing row succeeded") + } + rows, _ := s.ListRemotePaths(ctx, "usb", vID) + if len(rows) != 1 || rows[0].State != RemotePathCommitting { + t.Fatalf("a failed batch changed the row: %+v", rows) + } + + if err := s.MarkRemotePathsLost(ctx, id); err != nil { + t.Fatalf("MarkRemotePathsLost: %v", err) + } + if err := s.MarkRemotePathsLost(ctx, id); err == nil { + t.Fatal("a lost row was marked lost twice") + } +} + +// TestRemotePathOneLiveVersionPerPath: while a version is live, no second +// commit may start at its path; once the live one is displacing, it may. +// A displacement that never happened reverts to live. +func TestRemotePathOneLiveVersionPerPath(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + first, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)) + if err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + if err := s.ConfirmRemotePathsLive(ctx, first); err != nil { + t.Fatalf("ConfirmRemotePathsLive: %v", err) + } + if _, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)); err == nil { + t.Fatal("a second commit started at a path with a live version") + } + // Another destination is independent. + other := commitWrite(d, runID) + other.Destination = "nas" + if _, err := s.BeginRemotePathCommit(ctx, other); err != nil { + t.Fatalf("commit on another destination: %v", err) + } + + if err := s.BeginRemotePathsDisplace(ctx, runID, first); err != nil { + t.Fatalf("BeginRemotePathsDisplace: %v", err) + } + if err := s.RevertRemotePathsLive(ctx, first); err != nil { + t.Fatalf("RevertRemotePathsLive: %v", err) + } + rows, _ := s.ListLiveRemotePaths(ctx, "usb", vID) + if len(rows) != 1 || rows[0].DisplacedRunID.Valid { + t.Fatalf("reverted row = %+v, want live with no displacing run", rows) + } +} + +// TestContentPresentOnDestinationSeesMirrorCopies: a live or displaced +// mirror copy counts as the content being on the destination; a committing +// or lost one does not. +func TestContentPresentOnDestinationSeesMirrorCopies(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, _, runID := remotePathFixture(t, s) + present := func() bool { + t.Helper() + ok, err := s.ContentPresentOnDestination(ctx, d.ContentID, "usb") + if err != nil { + t.Fatalf("ContentPresentOnDestination: %v", err) + } + return ok + } + id, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)) + if err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + if present() { + t.Fatal("a committing copy counts as present") + } + if err := s.ConfirmRemotePathsLive(ctx, id); err != nil { + t.Fatal(err) + } + if !present() { + t.Fatal("a live copy does not count as present") + } + if err := s.BeginRemotePathsDisplace(ctx, runID, id); err != nil { + t.Fatal(err) + } + if err := s.ConfirmRemotePathsDisplaced(ctx, id); err != nil { + t.Fatal(err) + } + if !present() { + t.Fatal("a displaced copy does not count as present") + } + if err := s.MarkRemotePathsLost(ctx, id); err != nil { + t.Fatal(err) + } + if present() { + t.Fatal("a lost copy counts as present") + } +} + +// TestResetDestinationClearsRemotePaths: a reset clears the mirror ledger +// with the others, counts it, and leaves the destination without upload +// records. +func TestResetDestinationClearsRemotePaths(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + if _, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)); err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + if has, err := s.DestinationHasUploadRecords(ctx, "usb"); err != nil || !has { + t.Fatalf("DestinationHasUploadRecords = %t, %v; want true", has, err) + } + + _, counts, err := s.ResetDestination(ctx, "usb") + if err != nil { + t.Fatalf("ResetDestination: %v", err) + } + if counts.RemotePaths != 1 { + t.Fatalf("counts = %+v, want one remote path", counts) + } + if rows, _ := s.ListRemotePaths(ctx, "usb", vID); len(rows) != 0 { + t.Fatalf("rows after reset = %+v", rows) + } + if has, err := s.DestinationHasUploadRecords(ctx, "usb"); err != nil || has { + t.Fatalf("DestinationHasUploadRecords after reset = %t, %v; want false", has, err) + } +} diff --git a/store/schema.sql b/store/schema.sql index bfff9aa..3c27b50 100644 --- a/store/schema.sql +++ b/store/schema.sql @@ -1,6 +1,6 @@ -- Generated by `go test ./store -update-schema` — DO NOT EDIT. -- --- Flattened snapshot of the squirrel index schema at version 31, for humans +-- Flattened snapshot of the squirrel index schema at version 32, for humans -- and agents who want the current shape without replaying the migration -- chain in migrations.go. It is NOT used to create or migrate databases — -- a fresh DB is built by applyV5 plus the migration registry. The golden @@ -211,6 +211,32 @@ CREATE TABLE "remote_packs" ( CHECK ((checksum_algo IS NULL) = (checksum IS NULL)) ) STRICT; +CREATE TABLE remote_paths ( + id INTEGER PRIMARY KEY, + destination TEXT NOT NULL, + folder_id INTEGER NOT NULL, + name TEXT NOT NULL, + content_id INTEGER NOT NULL, + written_run_id INTEGER NOT NULL REFERENCES runs(id), + state TEXT NOT NULL + CHECK (state IN ('committing', 'live', 'displacing', 'displaced', 'lost')), + displaced_run_id INTEGER REFERENCES runs(id), + mtime_ns INTEGER NOT NULL, + checksum_algo TEXT, + checksum TEXT, + verified_at_ns INTEGER, + FOREIGN KEY (folder_id, name, content_id) REFERENCES files (folder_id, name, content_id), + CHECK (state NOT IN ('committing', 'live') OR displaced_run_id IS NULL), + CHECK (state NOT IN ('displacing', 'displaced') OR displaced_run_id IS NOT NULL), + CHECK ((checksum_algo IS NULL) = (checksum IS NULL)) + ) STRICT; + +CREATE INDEX idx_remote_paths_unsettled ON remote_paths (destination) + WHERE state IN ('committing', 'displacing'); + +CREATE UNIQUE INDEX uniq_remote_paths_live ON remote_paths (destination, folder_id, name) + WHERE state IN ('committing', 'live'); + CREATE TABLE "runs" ( id INTEGER PRIMARY KEY, kind TEXT NOT NULL CHECK (kind IN ('index','sync','restore','audit','offload')), From f690057f7c1badb902e97a2bb04bc6255ab0a5b6 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Wed, 23 Sep 2026 23:47:22 +0200 Subject: [PATCH 06/61] sync: reserve .squirrel-staging for a native mirror's in-flight writes The name joins the other reserved directories everywhere they are listed: the store's destination-facing reads, the peer-sync filters on both ends, the rclone mirror's transfer and restore filters, and the source-tree warning. --- agent/sync.go | 19 ++++++------ agent/sync_test.go | 4 ++- .../content/docs/reference/on-disk-layout.md | 7 +++-- store/path_delta.go | 3 +- store/path_delta_test.go | 1 + sync/node.go | 5 ++-- sync/snapshot_test.go | 12 ++++---- sync/sync.go | 29 ++++++++++++++----- 8 files changed, 51 insertions(+), 29 deletions(-) diff --git a/agent/sync.go b/agent/sync.go index 7bf96e0..7de3f5d 100644 --- a/agent/sync.go +++ b/agent/sync.go @@ -38,18 +38,19 @@ const HistoryDirName = ".squirrel-history" // (conflicts) without parsing run-id semantics. const ConflictsDirName = ".squirrel-conflicts" -// RestoreHistoryDirName and IndexDirName mirror sync.RestoreHistoryDirName -// and sync.IndexDirName at the agent side (lowercase-duplicated for the -// same reason as HistoryDirName). The receiver never writes into either -// itself, but a peer's wire path can name them; the path validators -// reject them so the initiator-side reserved filter -// (sync.isReservedSyncPath / isReservedFolderPath) and the receiver -// allow-list cover the same four names. A wire path under +// RestoreHistoryDirName, IndexDirName and StagingDirName mirror their sync +// package namesakes at the agent side (duplicated for the same reason as +// HistoryDirName). The receiver never writes into any of them itself, but +// a peer's wire path can name them; the path validators reject them so the +// initiator-side reserved filter (sync.isReservedSyncPath / +// isReservedFolderPath) and the receiver allow-list cover the same five +// names. A wire path under // .squirrel-restore-history could otherwise overwrite the receiver's // only pre-restore backup. const ( RestoreHistoryDirName = ".squirrel-restore-history" IndexDirName = ".squirrel-index" + StagingDirName = ".squirrel-staging" ) // maxPlanBodyBytes caps a decoded request body. decodeJSON applies it to @@ -807,14 +808,14 @@ func validateRelPath(p string) error { } // isReservedSyncDir reports whether a cleaned, slash-separated path is -// one of the four reserved sync directories or lives under one. The +// one of the five reserved sync directories or lives under one. The // allow-list matches the initiator-side filter // (sync.isReservedSyncPath / isReservedFolderPath) so the receiver // can't be made to write where the initiator would never publish — // including .squirrel-restore-history, whose contents are the // receiver's only pre-restore backup. func isReservedSyncDir(cleaned string) bool { - for _, dir := range []string{HistoryDirName, ConflictsDirName, RestoreHistoryDirName, IndexDirName} { + for _, dir := range []string{HistoryDirName, ConflictsDirName, RestoreHistoryDirName, IndexDirName, StagingDirName} { if cleaned == dir || strings.HasPrefix(cleaned, dir+"/") { return true } diff --git a/agent/sync_test.go b/agent/sync_test.go index 393fcb7..508dcaa 100644 --- a/agent/sync_test.go +++ b/agent/sync_test.go @@ -584,7 +584,7 @@ func TestPreStageTransferPreservesOutOfBandFile(t *testing.T) { } // TestValidateRelPathRejectsAllReservedDirs (#106b): the receiver's wire -// path allow-list must reject all four reserved sync directories, matching +// path allow-list must reject all five reserved sync directories, matching // the initiator-side filter. A path under .squirrel-restore-history or // .squirrel-index could otherwise let a peer overwrite the receiver's only // pre-restore backup or its index ride-along. @@ -594,8 +594,10 @@ func TestValidateRelPathRejectsAllReservedDirs(t *testing.T) { ConflictsDirName + "/run-1/x", RestoreHistoryDirName + "/run-1/x", IndexDirName + "/index.db", + StagingDirName + "/run-1/x", RestoreHistoryDirName, IndexDirName, + StagingDirName, } for _, p := range reserved { t.Run(p, func(t *testing.T) { diff --git a/docs/src/content/docs/reference/on-disk-layout.md b/docs/src/content/docs/reference/on-disk-layout.md index 7f4d074..0028d4c 100644 --- a/docs/src/content/docs/reference/on-disk-layout.md +++ b/docs/src/content/docs/reference/on-disk-layout.md @@ -80,7 +80,7 @@ names](/squirrel/reference/formats/#deriving-the-stored-names-on-an-encrypted-de ## Reserved directories -Three directory names are reserved and **filtered out** of all sync and restore +Four directory names are reserved and **filtered out** of all sync and restore transfers (and from peer-sync), so squirrel's own bookkeeping is never mistaken for user content: @@ -89,6 +89,7 @@ for user content: | `.squirrel-history/run-/` | rclone's `--backup-dir` target — prior bytes of overwritten files ([mirror](/squirrel/layouts/mirror/)). | | `.squirrel-index/` | Ride-along [index snapshots](/squirrel/configuration/index-snapshots/). | | `.squirrel-restore-history/run-/` | Files displaced by an [`--in-place` restore](/squirrel/guides/restore/). | +| `.squirrel-staging/run-/` | A native [mirror](/squirrel/layouts/mirror/)'s in-flight writes, renamed onto their paths once complete. | One reserved **file** sits at the destination root rather than in a volume tree: `.squirrel-naming`, which records the artifact-naming scheme of an @@ -96,8 +97,8 @@ One reserved **file** sits at the destination root rather than in a volume tree: the gate that stops two naming schemes from being mixed into one root, and it never carries key material. -A directory literally called `.squirrel-history` in your **source** volume is -also filtered (with a warning) to keep the reserved name out of the destination +A directory literally called `.squirrel-history` or `.squirrel-staging` in your +**source** volume is also filtered (with a warning) to keep the reserved name out of the destination tree by accident. ## Related formats diff --git a/store/path_delta.go b/store/path_delta.go index 97a6b32..1b2cc71 100644 --- a/store/path_delta.go +++ b/store/path_delta.go @@ -28,7 +28,8 @@ type PathDelta struct { const reservedSubtreeFilter = `fo.path != '.squirrel-history' AND fo.path NOT LIKE '.squirrel-history/%' AND fo.path != '.squirrel-conflicts' AND fo.path NOT LIKE '.squirrel-conflicts/%' AND fo.path != '.squirrel-restore-history' AND fo.path NOT LIKE '.squirrel-restore-history/%' - AND fo.path != '.squirrel-index' AND fo.path NOT LIKE '.squirrel-index/%'` + AND fo.path != '.squirrel-index' AND fo.path NOT LIKE '.squirrel-index/%' + AND fo.path != '.squirrel-staging' AND fo.path NOT LIKE '.squirrel-staging/%'` // ListPathDeltaSince returns every row in the volume whose status last // changed after sinceRunID, ordered by (path, status) so the export is diff --git a/store/path_delta_test.go b/store/path_delta_test.go index 97f3948..63f03c0 100644 --- a/store/path_delta_test.go +++ b/store/path_delta_test.go @@ -106,6 +106,7 @@ func TestListPathDeltaSinceExcludesReservedSubtrees(t *testing.T) { ".squirrel-conflicts/run-2/x.txt", ".squirrel-restore-history/run-3/y.txt", ".squirrel-index/index-snapshot.db", + ".squirrel-staging/run-4/z", } for i, p := range reserved { if err := s.Upsert(ctx, FileRow{ diff --git a/sync/node.go b/sync/node.go index d3ac559..5c25c24 100644 --- a/sync/node.go +++ b/sync/node.go @@ -662,7 +662,8 @@ func isReservedSyncPath(p string) bool { return strings.HasPrefix(p, HistoryDirName+"/") || strings.HasPrefix(p, ConflictsDirName+"/") || strings.HasPrefix(p, RestoreHistoryDirName+"/") || - strings.HasPrefix(p, IndexDirName+"/") + strings.HasPrefix(p, IndexDirName+"/") || + strings.HasPrefix(p, StagingDirName+"/") } // isReservedFolderPath is the folder-path variant of @@ -674,7 +675,7 @@ func isReservedSyncPath(p string) bool { // rejects, aborting the whole walk. func isReservedFolderPath(p string) bool { return p == HistoryDirName || p == ConflictsDirName || p == RestoreHistoryDirName || - p == IndexDirName || isReservedSyncPath(p) + p == IndexDirName || p == StagingDirName || isReservedSyncPath(p) } // phaseTransfer streams every content object the plan asked for to the diff --git a/sync/snapshot_test.go b/sync/snapshot_test.go index bf263e6..2fbb7a8 100644 --- a/sync/snapshot_test.go +++ b/sync/snapshot_test.go @@ -357,11 +357,13 @@ func TestSyncFiltersOutIndexDirFromSource(t *testing.T) { // reserved-path predicates exclude .squirrel-index, so a node whose index // carries rows there never re-publishes them. func TestReservedSyncPathCoversIndexDir(t *testing.T) { - if !isReservedSyncPath(IndexDirName + "/index-x-run-1.db") { - t.Fatalf("isReservedSyncPath does not cover %s/", IndexDirName) - } - if !isReservedFolderPath(IndexDirName) { - t.Fatalf("isReservedFolderPath does not cover bare %s", IndexDirName) + for _, dir := range []string{IndexDirName, StagingDirName} { + if !isReservedSyncPath(dir + "/run-1/x") { + t.Fatalf("isReservedSyncPath does not cover %s/", dir) + } + if !isReservedFolderPath(dir) { + t.Fatalf("isReservedFolderPath does not cover bare %s", dir) + } } } diff --git a/sync/sync.go b/sync/sync.go index f592bc6..5e4019e 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -50,6 +50,13 @@ const RestoreHistoryDirName = ".squirrel-restore-history" // and from peer-sync so a snapshot is never mistaken for user content. const IndexDirName = ".squirrel-index" +// StagingDirName is the per-volume directory at a native mirror destination +// that holds in-flight writes: //.squirrel-staging/ +// run-/. A version is staged there, hashed while it streams, +// and renamed onto its path only once its predecessor is in history. Like +// the other reserved directories it never travels as user content. +const StagingDirName = ".squirrel-staging" + // ErrRefused marks a preflight safety refusal: a gate that declined to // proceed before any transfer began — a missing or mismatched // .squirrel-volume marker, a kopia connect that found no repository @@ -565,16 +572,18 @@ func finishRunRow(ctx context.Context, s *store.Store, runID int64, status, errM } // historyDirInSourceWarning returns a one-line advisory when the source -// volume already contains a literal .squirrel-history directory. Sync -// filters it out of the rclone transfer so it can't pollute the -// destination tree, but the user should know that some local content is -// being silently skipped under the reserved name. +// volume already contains a literal .squirrel-history or .squirrel-staging +// directory. Sync filters them out of the transfer so they can't pollute +// the destination tree, but the user should know that some local content +// is being silently skipped under a reserved name. func historyDirInSourceWarning(vol *config.Volume) string { - if _, err := os.Stat(filepath.Join(vol.Path, HistoryDirName)); err != nil { - return "" + for _, dir := range []string{HistoryDirName, StagingDirName} { + if _, err := os.Stat(filepath.Join(vol.Path, dir)); err == nil { + return fmt.Sprintf("volume %q contains a reserved %s/ directory in its source tree — its contents will not be uploaded; rename or move the directory if you want it synced", + vol.Name, dir) + } } - return fmt.Sprintf("volume %q contains a reserved %s/ directory in its source tree — its contents will not be uploaded; rename or move the directory if you want it synced", - vol.Name, HistoryDirName) + return "" } // localVolumeHasContent reports whether vol.Path contains anything @@ -820,6 +829,9 @@ func buildRcloneArgs(vol *config.Volume, dest *config.Destination, runID int64, // dir from being treated as user content (re-uploaded, or pulled // back down on restore). "--filter", "- /" + IndexDirName + "/**", + // .squirrel-staging holds a native mirror's in-flight writes; + // the name is reserved on every layout. + "--filter", "- /" + StagingDirName + "/**", } args = append(args, checkersArgs(dest)...) if !EffectiveShallow(dest, opts.Shallow) { @@ -1180,6 +1192,7 @@ func buildRestoreArgs(vol *config.Volume, dest *config.Destination, runID int64, args = append(args, "--filter", "- /"+volmark.MarkerName) args = append(args, "--filter", "- /"+RestoreHistoryDirName+"/**") args = append(args, "--filter", "- /"+IndexDirName+"/**") + args = append(args, "--filter", "- /"+StagingDirName+"/**") } args = append(args, checkersArgs(dest)...) if !EffectiveShallow(dest, opts.Shallow) { From a7efc49dbc3df5c2e4533ed0c8bc4eb6f51bd22d Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Wed, 23 Sep 2026 23:54:10 +0200 Subject: [PATCH 07/61] sync: add the transport, its name guard and the local implementation transport is byte-level access to one destination root: Stat, List, Get, Put, Rename and Remove, where Put creates exclusively and Rename never replaces its target, so no call can overwrite bytes. The local implementation sits on os.Root and refuses a symlink anywhere along a name's parent chain, because os.Root follows symlinks that stay inside the root. Rename uses renameat2 RENAME_NOREPLACE on Linux and renamex_np RENAME_EXCL on macOS, falling back to Lstat then rename on filesystems without them (exFAT) and elsewhere; parent directories are synced after every change. The name guard is the one function deciding what may move or disappear: removal of finished runs' staging and of ride-along snapshots, commits from this run's staging, and displacement into this run's history. A contract suite pins the behaviour any transport must show. --- go.mod | 2 +- sync/transport.go | 89 +++++++++++ sync/transport_contract_test.go | 267 ++++++++++++++++++++++++++++++++ sync/transport_guard.go | 124 +++++++++++++++ sync/transport_guard_test.go | 60 +++++++ sync/transport_local.go | 257 ++++++++++++++++++++++++++++++ sync/transport_local_darwin.go | 29 ++++ sync/transport_local_linux.go | 29 ++++ sync/transport_local_other.go | 15 ++ 9 files changed, 871 insertions(+), 1 deletion(-) create mode 100644 sync/transport.go create mode 100644 sync/transport_contract_test.go create mode 100644 sync/transport_guard.go create mode 100644 sync/transport_guard_test.go create mode 100644 sync/transport_local.go create mode 100644 sync/transport_local_darwin.go create mode 100644 sync/transport_local_linux.go create mode 100644 sync/transport_local_other.go diff --git a/go.mod b/go.mod index dcd6e08..b70d2f3 100644 --- a/go.mod +++ b/go.mod @@ -17,6 +17,7 @@ require ( github.com/wailsapp/wails/v3 v3.0.0-alpha.95 github.com/zeebo/blake3 v0.2.4 golang.org/x/crypto v0.51.0 + golang.org/x/sys v0.44.0 modernc.org/sqlite v1.50.1 ) @@ -82,7 +83,6 @@ require ( github.com/zeebo/xxh3 v1.1.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/net v0.53.0 // indirect - golang.org/x/sys v0.44.0 // indirect golang.org/x/text v0.37.0 // indirect gopkg.in/ini.v1 v1.67.2 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect diff --git a/sync/transport.go b/sync/transport.go new file mode 100644 index 0000000..6df2e42 --- /dev/null +++ b/sync/transport.go @@ -0,0 +1,89 @@ +package sync + +import ( + "context" + "errors" + "io" + "io/fs" + "time" +) + +// transport is byte-level access to one destination root. Names are +// slash-separated and relative to the root; symlinks are never followed. +// Nothing replaces an existing name: Put creates exclusively and Rename +// never replaces its target, so no transport call can overwrite bytes. +type transport interface { + // Stat describes name without following a symlink there; + // fs.ErrNotExist when absent. + Stat(ctx context.Context, name string) (entry, error) + // List describes the entries directly in dir ("." is the root). + List(ctx context.Context, dir string) ([]entry, error) + // Get opens the regular file at name for reading. + Get(ctx context.Context, name string) (io.ReadCloser, error) + // Put creates name exclusively (fs.ErrExist if present), creating its + // parents, streams r into it, sets its mtime, and syncs it to stable + // storage before returning. + Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error + // Rename moves from to to, creating to's parents; fs.ErrExist if to + // exists. + Rename(ctx context.Context, from, to string) error + // Remove deletes the file or empty directory at name. + Remove(ctx context.Context, name string) error + Close() error +} + +// entry describes one name on a destination as the transport found it. +type entry struct { + name string // base name + kind entryKind + size int64 + mtime time.Time +} + +// entryKind is what a name on a destination is. +type entryKind int + +const ( + kindFile entryKind = iota + kindDir + kindSymlink + kindOther +) + +func kindOf(mode fs.FileMode) entryKind { + switch { + case mode.IsRegular(): + return kindFile + case mode.IsDir(): + return kindDir + case mode&fs.ModeSymlink != 0: + return kindSymlink + default: + return kindOther + } +} + +// errSymlinkInPath refuses a name whose parent chain crosses a symlink, +// which the transport never follows. +var errSymlinkInPath = errors.New("a directory along the path is a symlink") + +// errParentNotDir reports that a name's parent chain crosses something +// that is not a directory, so the name cannot exist. +var errParentNotDir = errors.New("a parent along the path is not a directory") + +// errInvalidName refuses a name that is not a clean slash-separated path +// inside the root. +var errInvalidName = errors.New("invalid destination name") + +// ctxReader stops a streaming copy once its context is done. +type ctxReader struct { + ctx context.Context + r io.Reader +} + +func (c ctxReader) Read(p []byte) (int, error) { + if err := c.ctx.Err(); err != nil { + return 0, err + } + return c.r.Read(p) +} diff --git a/sync/transport_contract_test.go b/sync/transport_contract_test.go new file mode 100644 index 0000000..7ca19ac --- /dev/null +++ b/sync/transport_contract_test.go @@ -0,0 +1,267 @@ +package sync + +import ( + "bytes" + "context" + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +// transportHarness opens a fresh, empty destination root for one contract +// case. plant puts a symlink named name, pointing at target, on the +// destination — something no transport call creates. +type transportHarness func(t *testing.T) (tr transport, plant func(target, name string)) + +// runTransportContract is the behaviour every transport implementation +// must show. It pins the two properties the layouts' safety rests on — +// nothing replaces an existing name, and no symlink is ever followed — +// plus the plain semantics of each call. +func runTransportContract(t *testing.T, open transportHarness) { + cases := []struct { + name string + run func(t *testing.T, tr transport, plant func(target, name string)) + }{ + {"PutThenStatListGet", contractPutThenStatListGet}, + {"PutNeverReplaces", contractPutNeverReplaces}, + {"StatAbsent", contractStatAbsent}, + {"RenameMovesAndCreatesParents", contractRenameMoves}, + {"RenameNeverReplaces", contractRenameNeverReplaces}, + {"RenameMovesDirectories", contractRenameDirectory}, + {"RemoveFilesAndEmptyDirectoriesOnly", contractRemove}, + {"RefusesInvalidNames", contractInvalidNames}, + {"NeverFollowsSymlinks", contractNoSymlinks}, + {"ParentThatIsAFile", contractParentNotDir}, + {"PutStopsOnCancel", contractPutCancel}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + tr, plant := open(t) + t.Cleanup(func() { _ = tr.Close() }) + c.run(t, tr, plant) + }) + } +} + +func TestLocalTransportContract(t *testing.T) { + runTransportContract(t, func(t *testing.T) (transport, func(target, name string)) { + dir := t.TempDir() + tr, err := openLocalTransport(dir) + if err != nil { + t.Fatalf("openLocalTransport: %v", err) + } + return tr, func(target, name string) { + p := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, p); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + } + }) +} + +var contractMtime = time.Date(2024, 5, 6, 7, 8, 9, 0, time.UTC) + +func mustPut(t *testing.T, tr transport, name, body string) { + t.Helper() + if err := tr.Put(context.Background(), name, strings.NewReader(body), contractMtime); err != nil { + t.Fatalf("Put %s: %v", name, err) + } +} + +func mustRead(t *testing.T, tr transport, name string) string { + t.Helper() + rc, err := tr.Get(context.Background(), name) + if err != nil { + t.Fatalf("Get %s: %v", name, err) + } + defer func() { _ = rc.Close() }() + b, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + return string(b) +} + +func contractPutThenStatListGet(t *testing.T, tr transport, _ func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "a/b/c.txt", "hello") + e, err := tr.Stat(ctx, "a/b/c.txt") + if err != nil { + t.Fatalf("Stat: %v", err) + } + if e.kind != kindFile || e.size != 5 || e.name != "c.txt" { + t.Fatalf("Stat = %+v, want file c.txt of 5 bytes", e) + } + // sftp carries whole seconds, so the contract allows truncation. + if d := contractMtime.Sub(e.mtime); d < 0 || d >= time.Second { + t.Fatalf("mtime = %v, want %v to the second", e.mtime, contractMtime) + } + list, err := tr.List(ctx, "a/b") + if err != nil || len(list) != 1 || list[0].name != "c.txt" { + t.Fatalf("List = %+v, %v; want [c.txt]", list, err) + } + root, err := tr.List(ctx, ".") + if err != nil || len(root) != 1 || root[0].name != "a" || root[0].kind != kindDir { + t.Fatalf("List(.) = %+v, %v; want the directory a", root, err) + } + if got := mustRead(t, tr, "a/b/c.txt"); got != "hello" { + t.Fatalf("Get = %q, want hello", got) + } +} + +func contractPutNeverReplaces(t *testing.T, tr transport, _ func(string, string)) { + mustPut(t, tr, "x", "first") + err := tr.Put(context.Background(), "x", strings.NewReader("second"), contractMtime) + if !errors.Is(err, fs.ErrExist) { + t.Fatalf("Put over an existing name = %v, want fs.ErrExist", err) + } + if got := mustRead(t, tr, "x"); got != "first" { + t.Fatalf("bytes after a refused Put = %q, want first", got) + } +} + +func contractStatAbsent(t *testing.T, tr transport, _ func(string, string)) { + for _, name := range []string{"nope", "a/nope/x"} { + if _, err := tr.Stat(context.Background(), name); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("Stat %s = %v, want fs.ErrNotExist", name, err) + } + } +} + +func contractRenameMoves(t *testing.T, tr transport, _ func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "x", "body") + if err := tr.Rename(ctx, "x", "d/e/y"); err != nil { + t.Fatalf("Rename: %v", err) + } + if _, err := tr.Stat(ctx, "x"); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("source after Rename: %v, want gone", err) + } + if got := mustRead(t, tr, "d/e/y"); got != "body" { + t.Fatalf("target = %q, want body", got) + } +} + +func contractRenameNeverReplaces(t *testing.T, tr transport, _ func(string, string)) { + mustPut(t, tr, "x", "from") + mustPut(t, tr, "y", "to") + if err := tr.Rename(context.Background(), "x", "y"); !errors.Is(err, fs.ErrExist) { + t.Fatalf("Rename onto an existing name = %v, want fs.ErrExist", err) + } + if mustRead(t, tr, "x") != "from" || mustRead(t, tr, "y") != "to" { + t.Fatal("a refused Rename changed either side") + } +} + +func contractRenameDirectory(t *testing.T, tr transport, _ func(string, string)) { + mustPut(t, tr, "d/f", "inside") + if err := tr.Rename(context.Background(), "d", "h/d"); err != nil { + t.Fatalf("Rename directory: %v", err) + } + if got := mustRead(t, tr, "h/d/f"); got != "inside" { + t.Fatalf("moved file = %q, want inside", got) + } +} + +func contractRemove(t *testing.T, tr transport, _ func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "d/f", "x") + if err := tr.Remove(ctx, "d"); err == nil { + t.Fatal("Remove of a non-empty directory succeeded") + } + if err := tr.Remove(ctx, "d/f"); err != nil { + t.Fatalf("Remove file: %v", err) + } + if err := tr.Remove(ctx, "d"); err != nil { + t.Fatalf("Remove empty directory: %v", err) + } + if _, err := tr.Stat(ctx, "d"); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("removed directory: %v, want gone", err) + } +} + +func contractInvalidNames(t *testing.T, tr transport, _ func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "ok", "x") + for _, name := range []string{"", ".", "../x", "/abs", "a/../b", "a//b", "a/"} { + if _, err := tr.Stat(ctx, name); !errors.Is(err, errInvalidName) { + t.Errorf("Stat %q = %v, want errInvalidName", name, err) + } + if err := tr.Put(ctx, name, strings.NewReader("x"), contractMtime); !errors.Is(err, errInvalidName) { + t.Errorf("Put %q = %v, want errInvalidName", name, err) + } + if err := tr.Rename(ctx, "ok", name); !errors.Is(err, errInvalidName) { + t.Errorf("Rename onto %q = %v, want errInvalidName", name, err) + } + } +} + +func contractNoSymlinks(t *testing.T, tr transport, plant func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "real/file", "target bytes") + plant("real", "link") + plant("file", "real/filelink") + + if e, err := tr.Stat(ctx, "link"); err != nil || e.kind != kindSymlink { + t.Fatalf("Stat of the link = %+v, %v; want the symlink itself", e, err) + } + if _, err := tr.Stat(ctx, "link/file"); !errors.Is(err, errSymlinkInPath) { + t.Fatalf("Stat through the link = %v, want errSymlinkInPath", err) + } + if err := tr.Put(ctx, "link/new", strings.NewReader("x"), contractMtime); !errors.Is(err, errSymlinkInPath) { + t.Fatalf("Put through the link = %v, want errSymlinkInPath", err) + } + if _, err := tr.Stat(ctx, "real/new"); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("a Put through the link landed in its target: %v", err) + } + mustPut(t, tr, "x", "moving") + if err := tr.Rename(ctx, "x", "link/x"); !errors.Is(err, errSymlinkInPath) { + t.Fatalf("Rename through the link = %v, want errSymlinkInPath", err) + } + if _, err := tr.Get(ctx, "real/filelink"); err == nil { + t.Fatal("Get followed a symlink to a file") + } + if _, err := tr.List(ctx, "link"); err == nil { + t.Fatal("List followed a symlink to a directory") + } + // Renaming the link itself moves the link, never its target. + if err := tr.Rename(ctx, "link", "moved"); err != nil { + t.Fatalf("Rename the link: %v", err) + } + if got := mustRead(t, tr, "real/file"); got != "target bytes" { + t.Fatalf("the link's target changed: %q", got) + } +} + +func contractParentNotDir(t *testing.T, tr transport, _ func(string, string)) { + ctx := context.Background() + mustPut(t, tr, "f", "a file") + if _, err := tr.Stat(ctx, "f/x"); !errors.Is(err, errParentNotDir) { + t.Fatalf("Stat under a file = %v, want errParentNotDir", err) + } + if err := tr.Put(ctx, "f/x", strings.NewReader("x"), contractMtime); !errors.Is(err, errParentNotDir) { + t.Fatalf("Put under a file = %v, want errParentNotDir", err) + } +} + +func contractPutCancel(t *testing.T, tr transport, _ func(string, string)) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + body := bytes.NewReader(bytes.Repeat([]byte("x"), 1<<20)) + if err := tr.Put(ctx, "big", body, contractMtime); !errors.Is(err, context.Canceled) { + t.Fatalf("Put with a cancelled context = %v, want context.Canceled", err) + } + list, _ := tr.List(context.Background(), ".") + if i := slices.IndexFunc(list, func(e entry) bool { return e.name == "big" && e.size == 1<<20 }); i >= 0 { + t.Fatal("a cancelled Put landed the whole body") + } +} diff --git a/sync/transport_guard.go b/sync/transport_guard.go new file mode 100644 index 0000000..699d611 --- /dev/null +++ b/sync/transport_guard.go @@ -0,0 +1,124 @@ +package sync + +import ( + "errors" + "fmt" + "io/fs" + "path" + "strconv" + "strings" + + "github.com/mbertschler/squirrel/volmark" +) + +// errGuardRefused marks a move or removal the name guard does not permit. +var errGuardRefused = errors.New("the name guard refuses this operation") + +// nameGuard is the only gate on what may move or disappear on a +// destination. Layouts never hold the raw transport: they get a +// guardedTransport, whose Rename and Remove pass through permit first. +type nameGuard struct { + volumeDir string // the volume's directory under the destination root + runID int64 // the push holding the guard + // finished reports whether a run has ended, so its staging may go. + finished func(runID int64) bool +} + +type guardOp int + +const ( + opRemove guardOp = iota + opRename +) + +// permit is the whole audit surface for destroying or moving bytes on a +// destination. It allows: +// +// - Remove of a staging entry, or an emptied staging run directory, +// of a run that has finished: /.squirrel-staging/run-[/]; +// - Remove of a ride-along snapshot: /.squirrel-index/index-*.db; +// - Rename from this run's staging onto a live name (a commit); +// - Rename of a live name to the same path under this run's history +// (a displacement): /.squirrel-history/run-/. +func (g nameGuard) permit(op guardOp, name, to string) error { + switch { + case g.runID == 0: + // A guard no run holds allows nothing; a dry run moves no bytes. + case op == opRemove: + if g.removable(name) { + return nil + } + case op == opRename: + if rel, ok := g.liveRel(name); ok && to == g.historyName(g.runID, rel) { + return nil + } + if _, ok := g.liveRel(to); ok && g.stagedByThisRun(name) { + return nil + } + } + return fmt.Errorf("%w: %s %q → %q", errGuardRefused, [...]string{"remove", "rename"}[op], name, to) +} + +func (g nameGuard) removable(name string) bool { + if rel, ok := strings.CutPrefix(name, g.volumeDir+"/"+IndexDirName+"/"); ok { + return !strings.Contains(rel, "/") && strings.HasPrefix(rel, snapshotPrefix) && strings.HasSuffix(rel, ".db") + } + runID, key, ok := g.stagingParts(name) + if !ok || runID == g.runID || !g.finished(runID) { + return false + } + return key == "" || isStagingKey(key) +} + +func (g nameGuard) stagedByThisRun(name string) bool { + runID, key, ok := g.stagingParts(name) + return ok && runID == g.runID && isStagingKey(key) +} + +// stagingParts splits /.squirrel-staging/run-[/]. +func (g nameGuard) stagingParts(name string) (runID int64, key string, ok bool) { + rest, found := strings.CutPrefix(name, g.volumeDir+"/"+StagingDirName+"/run-") + if !found { + return 0, "", false + } + idText, key, _ := strings.Cut(rest, "/") + id, err := strconv.ParseInt(idText, 10, 64) + if err != nil || id <= 0 || strconv.FormatInt(id, 10) != idText || strings.Contains(key, "/") { + return 0, "", false + } + return id, key, true +} + +// liveRel returns the volume-relative path of a name in the mirrored tree: +// inside the volume directory, outside every reserved directory, and not +// the volume marker. +func (g nameGuard) liveRel(name string) (string, bool) { + rel, found := strings.CutPrefix(name, g.volumeDir+"/") + if !found || !fs.ValidPath(rel) || rel == "." || rel == volmark.MarkerName { + return "", false + } + top, _, _ := strings.Cut(rel, "/") + if isReservedFolderPath(top) { + return "", false + } + return rel, true +} + +func (g nameGuard) historyName(runID int64, rel string) string { + return path.Join(g.volumeDir, HistoryDirName, "run-"+strconv.FormatInt(runID, 10), rel) +} + +// isStagingKey reports whether key is the staging name of one path: the +// lowercase hex BLAKE3 of the volume-relative path, so it stays unique on a +// destination that folds case. +func isStagingKey(key string) bool { + if len(key) != 64 { + return false + } + for _, c := range key { + if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + return false + } + } + return true +} diff --git a/sync/transport_guard_test.go b/sync/transport_guard_test.go new file mode 100644 index 0000000..1846f56 --- /dev/null +++ b/sync/transport_guard_test.go @@ -0,0 +1,60 @@ +package sync + +import ( + "errors" + "strings" + "testing" +) + +// TestNameGuardPermits is the table behind the name guard, the whole audit +// surface for moving or destroying bytes on a destination. +func TestNameGuardPermits(t *testing.T) { + key := strings.Repeat("ab", 32) + g := nameGuard{volumeDir: "pics", runID: 7, finished: func(id int64) bool { return id != 9 }} + cases := []struct { + name string + op guardOp + from, to string + want bool + }{ + {"commit from this run's staging", opRename, "pics/.squirrel-staging/run-7/" + key, "pics/2024/cat.jpg", true}, + {"commit from another run's staging", opRename, "pics/.squirrel-staging/run-6/" + key, "pics/2024/cat.jpg", false}, + {"commit of a foreign staging name", opRename, "pics/.squirrel-staging/run-7/notes.txt", "pics/2024/cat.jpg", false}, + {"commit onto the marker", opRename, "pics/.squirrel-staging/run-7/" + key, "pics/.squirrel-volume", false}, + {"commit into history", opRename, "pics/.squirrel-staging/run-7/" + key, "pics/.squirrel-history/run-7/cat.jpg", false}, + {"commit into another volume", opRename, "pics/.squirrel-staging/run-7/" + key, "docs/cat.jpg", false}, + {"displace into this run's history", opRename, "pics/2024/cat.jpg", "pics/.squirrel-history/run-7/2024/cat.jpg", true}, + {"displace a directory", opRename, "pics/2024", "pics/.squirrel-history/run-7/2024", true}, + {"displace into another run's history", opRename, "pics/2024/cat.jpg", "pics/.squirrel-history/run-6/2024/cat.jpg", false}, + {"displace under another path", opRename, "pics/2024/cat.jpg", "pics/.squirrel-history/run-7/dog.jpg", false}, + {"move history back out", opRename, "pics/.squirrel-history/run-3/cat.jpg", "pics/.squirrel-history/run-7/.squirrel-history/run-3/cat.jpg", false}, + {"displace the marker", opRename, "pics/.squirrel-volume", "pics/.squirrel-history/run-7/.squirrel-volume", false}, + {"rename between live names", opRename, "pics/a.jpg", "pics/b.jpg", false}, + {"escape the volume", opRename, "pics/../x", "pics/.squirrel-history/run-7/../x", false}, + {"remove a finished run's staging", opRemove, "pics/.squirrel-staging/run-6/" + key, "", true}, + {"remove a finished run's staging directory", opRemove, "pics/.squirrel-staging/run-6", "", true}, + {"remove this run's staging", opRemove, "pics/.squirrel-staging/run-7/" + key, "", false}, + {"remove a running run's staging", opRemove, "pics/.squirrel-staging/run-9/" + key, "", false}, + {"remove a foreign file in staging", opRemove, "pics/.squirrel-staging/run-6/notes.txt", "", false}, + {"remove a malformed run directory", opRemove, "pics/.squirrel-staging/run-06/" + key, "", false}, + {"remove a snapshot", opRemove, "pics/.squirrel-index/index-20260101T000000.000Z-run-6.db", "", true}, + {"remove a receipt", opRemove, "pics/.squirrel-index/run-6", "", false}, + {"remove a live file", opRemove, "pics/2024/cat.jpg", "", false}, + {"remove history", opRemove, "pics/.squirrel-history/run-6/cat.jpg", "", false}, + {"remove another volume's staging", opRemove, "docs/.squirrel-staging/run-6/" + key, "", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if err := (nameGuard{volumeDir: "pics", finished: g.finished}).permit(c.op, c.from, c.to); err == nil { + t.Fatal("a guard no run holds permitted the operation") + } + err := g.permit(c.op, c.from, c.to) + if got := err == nil; got != c.want { + t.Fatalf("permit = %v, want allowed=%t", err, c.want) + } + if err != nil && !errors.Is(err, errGuardRefused) { + t.Fatalf("refusal %v does not wrap errGuardRefused", err) + } + }) + } +} diff --git a/sync/transport_local.go b/sync/transport_local.go new file mode 100644 index 0000000..fa4f752 --- /dev/null +++ b/sync/transport_local.go @@ -0,0 +1,257 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "runtime" + "strings" + "time" +) + +// localTransport is the transport onto a directory of this machine's +// filesystem. os.Root confines every name to the root; on top of that each +// operation checks its name's parent chain with Lstat and refuses a +// symlink anywhere along it, because os.Root follows symlinks that stay +// inside the root. +type localTransport struct { + root *os.Root +} + +func openLocalTransport(dir string) (*localTransport, error) { + root, err := os.OpenRoot(dir) + if err != nil { + return nil, fmt.Errorf("open destination root %s: %w", dir, err) + } + return &localTransport{root: root}, nil +} + +func (t *localTransport) Close() error { return t.root.Close() } + +func (t *localTransport) Stat(_ context.Context, name string) (entry, error) { + if err := t.checkName(name); err != nil { + return entry{}, err + } + fi, err := t.root.Lstat(filepath.FromSlash(name)) + if err != nil { + return entry{}, err + } + return entryOf(fi), nil +} + +func (t *localTransport) List(_ context.Context, dir string) ([]entry, error) { + if dir != "." { + if err := t.checkName(dir); err != nil { + return nil, err + } + if err := t.requireKind(dir, kindDir); err != nil { + return nil, err + } + } + f, err := t.root.Open(filepath.FromSlash(dir)) + if err != nil { + return nil, err + } + defer f.Close() + des, err := f.ReadDir(-1) + if err != nil { + return nil, fmt.Errorf("list %s: %w", dir, err) + } + out := make([]entry, 0, len(des)) + for _, de := range des { + fi, err := de.Info() + if err != nil { + return nil, fmt.Errorf("list %s: %w", dir, err) + } + out = append(out, entryOf(fi)) + } + return out, nil +} + +func (t *localTransport) Get(_ context.Context, name string) (io.ReadCloser, error) { + if err := t.checkName(name); err != nil { + return nil, err + } + if err := t.requireKind(name, kindFile); err != nil { + return nil, err + } + return t.root.Open(filepath.FromSlash(name)) +} + +func (t *localTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if err := t.checkName(name); err != nil { + return err + } + if err := t.mkdirParents(name); err != nil { + return err + } + f, err := t.root.OpenFile(filepath.FromSlash(name), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) + if err != nil { + return err + } + if err := t.fill(ctx, f, name, r, mtime); err != nil { + _ = f.Close() + return err + } + if err := f.Close(); err != nil { + return fmt.Errorf("close %s: %w", name, err) + } + return t.syncDir(path.Dir(name)) +} + +// fill streams r into the freshly created f, stamps mtime, and syncs. +func (t *localTransport) fill(ctx context.Context, f *os.File, name string, r io.Reader, mtime time.Time) error { + if _, err := io.Copy(f, ctxReader{ctx: ctx, r: r}); err != nil { + return fmt.Errorf("write %s: %w", name, err) + } + if err := t.root.Chtimes(filepath.FromSlash(name), mtime, mtime); err != nil { + return fmt.Errorf("set mtime of %s: %w", name, err) + } + if err := f.Sync(); err != nil { + return fmt.Errorf("sync %s: %w", name, err) + } + return nil +} + +func (t *localTransport) Rename(_ context.Context, from, to string) error { + if err := t.checkName(from); err != nil { + return err + } + if err := t.checkName(to); err != nil { + return err + } + if _, err := t.root.Lstat(filepath.FromSlash(from)); err != nil { + return err + } + if err := t.mkdirParents(to); err != nil { + return err + } + if err := renameNoReplace(t.root, from, to); err != nil { + return err + } + if err := t.syncDir(path.Dir(from)); err != nil { + return err + } + return t.syncDir(path.Dir(to)) +} + +func (t *localTransport) Remove(_ context.Context, name string) error { + if err := t.checkName(name); err != nil { + return err + } + return t.root.Remove(filepath.FromSlash(name)) +} + +// checkName refuses a name that is not a clean path below the root, or +// whose parent chain crosses a symlink or a non-directory. +func (t *localTransport) checkName(name string) error { + if !fs.ValidPath(name) || name == "." || (runtime.GOOS == "windows" && strings.ContainsRune(name, '\\')) { + return fmt.Errorf("%w: %q", errInvalidName, name) + } + dir := path.Dir(name) + if dir == "." { + return nil + } + parts := strings.Split(dir, "/") + for i := range parts { + p := strings.Join(parts[:i+1], "/") + fi, err := t.root.Lstat(filepath.FromSlash(p)) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return err + } + switch kindOf(fi.Mode()) { + case kindDir: + case kindSymlink: + return fmt.Errorf("%s: %w", p, errSymlinkInPath) + default: + return fmt.Errorf("%s: %w", p, errParentNotDir) + } + } + return nil +} + +// requireKind refuses name unless it exists and is of kind want. +func (t *localTransport) requireKind(name string, want entryKind) error { + fi, err := t.root.Lstat(filepath.FromSlash(name)) + if err != nil { + return err + } + if kindOf(fi.Mode()) != want { + return fmt.Errorf("%s: %w", name, errUnexpectedKind) + } + return nil +} + +func (t *localTransport) mkdirParents(name string) error { + dir := path.Dir(name) + if dir == "." { + return nil + } + if err := t.root.MkdirAll(filepath.FromSlash(dir), 0o755); err != nil { + return fmt.Errorf("create %s: %w", dir, err) + } + return nil +} + +// syncDir flushes a directory, so a name created or moved in it survives +// a power cut. +func (t *localTransport) syncDir(dir string) error { + f, err := t.root.Open(filepath.FromSlash(dir)) + if err != nil { + return fmt.Errorf("open %s to sync it: %w", dir, err) + } + defer f.Close() + if err := f.Sync(); err != nil && !dirSyncUnsupported(err) { + return fmt.Errorf("sync %s: %w", dir, err) + } + return nil +} + +// errUnexpectedKind refuses an operation on a name that is not the kind of +// entry the operation reads. +var errUnexpectedKind = errors.New("unexpected kind of entry") + +func entryOf(fi fs.FileInfo) entry { + return entry{name: fi.Name(), kind: kindOf(fi.Mode()), size: fi.Size(), mtime: fi.ModTime()} +} + +// renameCheckThenMove is the rename for a filesystem without a no-replace +// rename, exFAT for one: an Lstat, then a plain rename. A writer outside +// squirrel could slip a file in between the two; squirrel cannot collide +// with itself there, because the run guard and the volume marker already +// exclude a second squirrel writer. +func renameCheckThenMove(root *os.Root, from, to string) error { + _, err := root.Lstat(filepath.FromSlash(to)) + if err == nil { + return &os.LinkError{Op: "rename", Old: from, New: to, Err: fs.ErrExist} + } + if !errors.Is(err, fs.ErrNotExist) { + return err + } + return root.Rename(filepath.FromSlash(from), filepath.FromSlash(to)) +} + +// withParentDirs opens the parent directories of from and to inside root +// and hands fn their handles and the two base names, for the directory +// relative system calls a no-replace rename needs. +func withParentDirs(root *os.Root, from, to string, fn func(fromDir, toDir *os.File, fromBase, toBase string) error) error { + fromDir, err := root.Open(filepath.FromSlash(path.Dir(from))) + if err != nil { + return err + } + defer fromDir.Close() + toDir, err := root.Open(filepath.FromSlash(path.Dir(to))) + if err != nil { + return err + } + defer toDir.Close() + return fn(fromDir, toDir, path.Base(from), path.Base(to)) +} diff --git a/sync/transport_local_darwin.go b/sync/transport_local_darwin.go new file mode 100644 index 0000000..a65f861 --- /dev/null +++ b/sync/transport_local_darwin.go @@ -0,0 +1,29 @@ +package sync + +import ( + "errors" + "os" + + "golang.org/x/sys/unix" +) + +// renameNoReplace moves from to to inside root with renameatx_np's +// RENAME_EXCL, which fails with EEXIST instead of replacing to. A +// filesystem that does not support the flag gets renameCheckThenMove. +func renameNoReplace(root *os.Root, from, to string) error { + err := withParentDirs(root, from, to, func(fromDir, toDir *os.File, fromBase, toBase string) error { + return unix.RenameatxNp(int(fromDir.Fd()), fromBase, int(toDir.Fd()), toBase, unix.RENAME_EXCL) + }) + if errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOTSUP) { + return renameCheckThenMove(root, from, to) + } + if err != nil { + return &os.LinkError{Op: "rename", Old: from, New: to, Err: err} + } + return nil +} + +// dirSyncUnsupported reports a filesystem that cannot flush a directory. +func dirSyncUnsupported(err error) bool { + return errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOTSUP) +} diff --git a/sync/transport_local_linux.go b/sync/transport_local_linux.go new file mode 100644 index 0000000..83df1ea --- /dev/null +++ b/sync/transport_local_linux.go @@ -0,0 +1,29 @@ +package sync + +import ( + "errors" + "os" + + "golang.org/x/sys/unix" +) + +// renameNoReplace moves from to to inside root with renameat2's +// RENAME_NOREPLACE, which fails with EEXIST instead of replacing to. A +// filesystem that does not support the flag gets renameCheckThenMove. +func renameNoReplace(root *os.Root, from, to string) error { + err := withParentDirs(root, from, to, func(fromDir, toDir *os.File, fromBase, toBase string) error { + return unix.Renameat2(int(fromDir.Fd()), fromBase, int(toDir.Fd()), toBase, unix.RENAME_NOREPLACE) + }) + if errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOSYS) || errors.Is(err, unix.ENOTSUP) { + return renameCheckThenMove(root, from, to) + } + if err != nil { + return &os.LinkError{Op: "rename", Old: from, New: to, Err: err} + } + return nil +} + +// dirSyncUnsupported reports a filesystem that cannot flush a directory. +func dirSyncUnsupported(err error) bool { + return errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOTSUP) +} diff --git a/sync/transport_local_other.go b/sync/transport_local_other.go new file mode 100644 index 0000000..9c26a77 --- /dev/null +++ b/sync/transport_local_other.go @@ -0,0 +1,15 @@ +//go:build !linux && !darwin + +package sync + +import "os" + +// renameNoReplace moves from to to inside root. This platform offers +// squirrel no no-replace rename, so it checks, then renames. +func renameNoReplace(root *os.Root, from, to string) error { + return renameCheckThenMove(root, from, to) +} + +// dirSyncUnsupported: a directory cannot be flushed through a handle on +// this platform, so the sync is best effort. +func dirSyncUnsupported(error) bool { return true } From fe36baa7aeeed27c10b6209242afc042e36f9cdc Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 00:10:08 +0200 Subject: [PATCH 08/61] sync: push local mirrors natively through the transport HandlerFor sends every local destination that is not content-addressed or packed to a native mirror handler, which runs on the shared planner and needs no rclone: - translate decides from squirrel's records alone: a present path whose live record holds its content is confirmed, any other present path is written; - execute stages each path under .squirrel-staging/run-/, hashing the bytes it sends, moves whatever the path and its parents hold into .squirrel-history/run-/ (as the recorded version when size and mtime match its record, as unrecorded bytes with a warning and an audit note otherwise), then commits with a no-replace rename; - every move is recorded in remote_paths before it happens, and the next push's reconcile settles it from where the bytes are, then removes the staging finished runs left; - seal writes the receipt, the run's manifest segment, at /.squirrel-index/run-, and the vector advances as presence+size. --shallow is refused. Every transport call is bounded by a no-progress timeout, and a push refuses while a call an earlier push gave up on is still inside the system. Progress events report paths and bytes. The rclone local-mirror vector tests give way to the native ones; the CLI summary keys its layout formatting on the new Report.Layout. --- cmd/squirrel/sync.go | 6 +- design/native-mirror.md | 4 +- store/remote_paths.go | 19 + store/runs_audit.go | 7 + sync/content_addressed.go | 4 + sync/handler.go | 7 + sync/handler_test.go | 16 +- sync/mirror.go | 205 +++++++++ sync/mirror_reconcile.go | 198 +++++++++ sync/mirror_test.go | 816 +++++++++++++++++++++++++++++++++++ sync/mirror_translate.go | 73 ++++ sync/mirror_write.go | 337 +++++++++++++++ sync/push.go | 10 +- sync/sync.go | 8 +- sync/transport_fault_test.go | 98 +++++ sync/transport_guard.go | 36 +- sync/transport_local.go | 17 - sync/transport_local_dirs.go | 26 ++ sync/transport_stall.go | 135 ++++++ sync/vector_wiring_test.go | 51 --- 20 files changed, 1991 insertions(+), 82 deletions(-) create mode 100644 sync/mirror.go create mode 100644 sync/mirror_reconcile.go create mode 100644 sync/mirror_test.go create mode 100644 sync/mirror_translate.go create mode 100644 sync/mirror_write.go create mode 100644 sync/transport_fault_test.go create mode 100644 sync/transport_local_dirs.go create mode 100644 sync/transport_stall.go diff --git a/cmd/squirrel/sync.go b/cmd/squirrel/sync.go index 9099c98..73b7ef5 100644 --- a/cmd/squirrel/sync.go +++ b/cmd/squirrel/sync.go @@ -264,8 +264,8 @@ func printSyncReport(w io.Writer, rep sync.Report, runErr error, reverse bool) { // an empty one — transferred=0 alone is ambiguous (friction F7). func printSyncSummaryLine(w io.Writer, rep sync.Report, src, dst string) { r := rep.RcloneResult - switch rep.Verification.Method { - case sync.VerifyMethodKopia: + switch { + case rep.Verification.Method == sync.VerifyMethodKopia: // Kopia pushes have no rclone counters; render the snapshot's // own numbers instead. fmt.Fprintf(w, "%s → %s status=%s files=%d bytes=%d snapshot=%s verified=%t run=%d\n", @@ -273,7 +273,7 @@ func printSyncSummaryLine(w io.Writer, rep sync.Report, src, dst string) { rep.Verification.Files, rep.Verification.Bytes, rep.Verification.SnapshotID, rep.Verification.Verified(), rep.RunID, ) - case sync.VerifyMethodPresenceSize: + case rep.Layout == config.LayoutContentAddressed || rep.Layout == config.LayoutPacked: // Content-addressed pushes count objects, with skipped = hashes // the destination already recorded, entries = manifest segment // lines, and fingerprints = provider checksums captured for the diff --git a/design/native-mirror.md b/design/native-mirror.md index 5e45af5..1c179ae 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -113,6 +113,8 @@ type layout[O operations] interface { // rootEmpty and foreignHistory complete the watermark rule below. rootEmpty(ctx context.Context) (bool, error) foreignHistory(runID int64) error + // reconcile settles what an earlier push left in flight (mirror only). + reconcile(ctx context.Context, rep *Report, volumeID, runID int64) error // translate turns the plan into this layout's operations. It reads // squirrel's records and writes nothing: a dry run is translate alone. translate(ctx context.Context, p pushPlan) (O, error) @@ -128,7 +130,7 @@ type layout[O operations] interface { One driver runs every layout: - requireIndexedVolume → markers → begin run → plan → translate → execute → seal → advance → finish → ride-along + requireIndexedVolume → markers → begin run → reconcile → plan → translate → execute → seal → advance → finish → ride-along A dry run stops after translate and reports the operations' preview. The separate `previewDryRun` each handler carried became that preview diff --git a/store/remote_paths.go b/store/remote_paths.go index ef6ed9a..494d427 100644 --- a/store/remote_paths.go +++ b/store/remote_paths.go @@ -186,3 +186,22 @@ func (s *Store) ListRemotePaths(ctx context.Context, destination string, volumeI ORDER BY rp.id `, scanRemotePath, destination, volumeID) } + +// CountInSyncRemotePaths counts the volume's live rows on the destination +// whose files row is still present: paths the destination holds with +// their current content by squirrel's records, the mirror's "already +// correct". +func (s *Store) CountInSyncRemotePaths(ctx context.Context, destination string, volumeID int64) (int64, error) { + var n int64 + err := s.db.QueryRowContext(ctx, ` + SELECT COUNT(*) + FROM remote_paths rp + JOIN folders fo ON fo.id = rp.folder_id + JOIN files f ON f.folder_id = rp.folder_id AND f.name = rp.name AND f.content_id = rp.content_id + WHERE rp.destination = ? AND fo.volume_id = ? AND rp.state = 'live' AND f.status = 'present' + `, destination, volumeID).Scan(&n) + if err != nil { + return 0, fmt.Errorf("count in-sync mirror paths on %q: %w", destination, err) + } + return n, nil +} diff --git a/store/runs_audit.go b/store/runs_audit.go index 43212e4..23edb77 100644 --- a/store/runs_audit.go +++ b/store/runs_audit.go @@ -97,6 +97,13 @@ const ( // recovered, and the volume restores that follow would appear in the // history with no explanation of where the catalog came from. TransitionRecoverIndex = "recover-index" + // TransitionDisplaceUnrecorded records bytes a native mirror push found + // at a path it was about to write and moved into history although + // squirrel had not written them there: a foreign write, a tree another + // tool wrote, or a recorded version changed behind squirrel's back. The + // note carries the path and where the bytes now are, so the trail lists + // what squirrel preserved without vouching for it. + TransitionDisplaceUnrecorded = "displace-unrecorded" ) // RunAudit is one row of the insert-only runs_audit log: a single diff --git a/sync/content_addressed.go b/sync/content_addressed.go index 663fde8..9bc1943 100644 --- a/sync/content_addressed.go +++ b/sync/content_addressed.go @@ -142,6 +142,10 @@ func (h *contentPusher) rootEmpty(ctx context.Context) (bool, error) { return h.rcl.remoteRootEmpty(ctx, remoteSubpathURI(h.dest, ""), rootMarkerNames(h.dest), checkersArgs(h.dest)...) } +// reconcile has nothing to settle: every content-layout artifact is +// written once under its own name and recorded only after it landed. +func (h *contentPusher) reconcile(context.Context, *Report, int64, int64) error { return nil } + func (h *contentPusher) target() pushTarget { return pushTarget{store: h.store, vol: h.vol, dest: h.dest} } diff --git a/sync/handler.go b/sync/handler.go index 803d61b..520e6ab 100644 --- a/sync/handler.go +++ b/sync/handler.go @@ -134,6 +134,8 @@ func HandlerFor(s *store.Store, tools Tools, p Pair) (Handler, error) { return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) } return &contentAddressedHandler{contentPusher{store: s, rcl: tools.Rclone, vol: p.Volume, dest: p.Destination}}, nil + case p.Destination.Type == "local": + return &mirrorHandler{store: s, vol: p.Volume, dest: p.Destination, openTransport: openLocalDestination, stallTimeout: DefaultStallTimeout}, nil default: if tools.Rclone == nil { return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) @@ -142,6 +144,11 @@ func HandlerFor(s *store.Store, tools Tools, p Pair) (Handler, error) { } } +// openLocalDestination opens a local destination's root directory. +func openLocalDestination(dest *config.Destination) (transport, error) { + return openLocalTransport(dest.Root) +} + // rcloneHandler pushes to an rclone-backed bucket destination via Sync. type rcloneHandler struct { store *store.Store diff --git a/sync/handler_test.go b/sync/handler_test.go index 02c4af8..378e049 100644 --- a/sync/handler_test.go +++ b/sync/handler_test.go @@ -9,7 +9,8 @@ import ( func TestHandlerForDispatch(t *testing.T) { vol := &config.Volume{Name: "pics", Path: "/tmp/pics"} - bucket := &config.Destination{Name: "scratch", Type: "local", Root: "/tmp/dst"} + bucket := &config.Destination{Name: "offsite", Type: "sftp", Root: "/data"} + usb := &config.Destination{Name: "usb", Type: "local", Root: "/tmp/dst"} node := &config.Node{Name: "nas"} tools := Tools{Rclone: &Rclone{Binary: "rclone"}} @@ -17,8 +18,17 @@ func TestHandlerForDispatch(t *testing.T) { if err != nil { t.Fatalf("bucket pair: %v", err) } - if _, ok := h.(*rcloneHandler); !ok || h.TargetName() != "scratch" { - t.Fatalf("bucket pair resolved to %T (%q), want *rcloneHandler scratch", h, h.TargetName()) + if _, ok := h.(*rcloneHandler); !ok || h.TargetName() != "offsite" { + t.Fatalf("bucket pair resolved to %T (%q), want *rcloneHandler offsite", h, h.TargetName()) + } + + // A local mirror is native, and needs no rclone wrapper. + h, err = HandlerFor(nil, Tools{}, Pair{Volume: vol, Destination: usb}) + if err != nil { + t.Fatalf("local mirror pair: %v", err) + } + if _, ok := h.(*mirrorHandler); !ok || h.TargetName() != "usb" { + t.Fatalf("local mirror pair resolved to %T (%q), want *mirrorHandler usb", h, h.TargetName()) } h, err = HandlerFor(nil, tools, Pair{Volume: vol, Node: node}) diff --git a/sync/mirror.go b/sync/mirror.go new file mode 100644 index 0000000..c95fca2 --- /dev/null +++ b/sync/mirror.go @@ -0,0 +1,205 @@ +package sync + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "io/fs" + "path" + "strconv" + "time" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/runevents" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// mirrorHandler pushes a volume to a native mirror: the volume's tree at +// //, written through a transport instead of rclone. +// It plans from the index like the content layouts, writes each changed +// path through .squirrel-staging/, moves whatever the path held into +// .squirrel-history/run-/ first, and records every version it wrote +// in remote_paths. Each run leaves a receipt, the same manifest segment the +// content layouts write, at /.squirrel-index/run-. +type mirrorHandler struct { + store *store.Store + vol *config.Volume + dest *config.Destination + // openTransport opens the destination root; tests wrap it to inject + // faults. + openTransport func(*config.Destination) (transport, error) + // stallTimeout bounds every transport call by progress. + stallTimeout time.Duration + + raw transport // opened by root on first use, closed when Push returns + progress func(runevents.Progress) // this push's Options.Progress +} + +func (h *mirrorHandler) TargetName() string { return h.dest.Name } + +func (h *mirrorHandler) sealed() {} + +func (h *mirrorHandler) Push(ctx context.Context, opts Options) (Report, error) { + rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} + rep.Verification.Method = VerifyMethodPresenceSize + if opts.Shallow { + return rep, fmt.Errorf("destination %q is a native mirror: a push already decides from squirrel's records, confirms each planned path's size and mtime, and moves whatever is there aside before writing, so --shallow has nothing to switch off", h.dest.Name) + } + if n := stalledCounter(h.dest.Name).Load(); n > 0 { + return rep, fmt.Errorf("destination %q: %d transport call(s) an earlier push gave up on have not returned — the disk or server may be hung; wait, or restart squirrel once it is reachable again", h.dest.Name, n) + } + h.progress = opts.Progress + defer h.closeRoot() + return pushThrough(ctx, pushTarget{store: h.store, vol: h.vol, dest: h.dest}, h, opts) +} + +// root is the destination root as a layout may hold it: guarded, so only +// runID's own moves pass (none when runID is 0), and bounded by progress. +func (h *mirrorHandler) root(runID int64) (transport, error) { + if h.raw == nil { + raw, err := h.openTransport(h.dest) + if err != nil { + return nil, err + } + h.raw = raw + } + guard := nameGuard{volumeDir: h.vol.Name, runID: runID, finished: h.runFinished} + return stallTransport{ + transport: guardedTransport{transport: h.raw, guard: guard}, + timeout: h.stallTimeout, + stalled: stalledCounter(h.dest.Name), + }, nil +} + +func (h *mirrorHandler) closeRoot() { + if h.raw != nil { + _ = h.raw.Close() + h.raw = nil + } +} + +// runFinished reports whether runID has ended, so its staging may be +// removed. A run squirrel cannot look up is left alone. +func (h *mirrorHandler) runFinished(runID int64) bool { + r, err := h.store.GetRun(context.Background(), runID) + return err == nil && r.Status != store.RunStatusRunning +} + +// markers gates the push on the per-volume .squirrel-volume marker, the +// guard against pushing to an unmounted disk or a mistyped root. A refusal +// is recorded as its own refused run, so a disk that stays unplugged shows +// up in `squirrel runs` and the TUI. A dry run skips the gate: it writes +// nothing. +func (h *mirrorHandler) markers(ctx context.Context, rep *Report, volumeID int64, opts Options) error { + if opts.DryRun { + return nil + } + merr := ensureLocalDestinationMarker(ctx, h.store, h.dest, h.vol.Name, opts.Init) + if merr == nil { + return nil + } + _, err := recordSyncRefusal(ctx, h.store, volumeID, h.dest.Name, rep, merr) + return err +} + +// landed reports whether runID left its receipt at the destination. +func (h *mirrorHandler) landed(ctx context.Context, runID int64) (bool, error) { + tr, err := h.root(0) + if err != nil { + return false, err + } + e, err := tr.Stat(ctx, h.receiptName(runID)) + if errors.Is(err, fs.ErrNotExist) || errors.Is(err, errParentNotDir) { + return false, nil + } + if err != nil { + return false, err + } + return e.kind == kindFile, nil +} + +// rootEmpty reports whether the destination root holds no file beyond +// the volume markers, walking it until the first one. +func (h *mirrorHandler) rootEmpty(ctx context.Context) (bool, error) { + tr, err := h.root(0) + if err != nil { + return false, err + } + return treeEmpty(ctx, tr, ".") +} + +func treeEmpty(ctx context.Context, tr transport, dir string) (bool, error) { + entries, err := tr.List(ctx, dir) + if err != nil { + return false, err + } + for _, e := range entries { + switch { + case e.kind == kindDir: + empty, err := treeEmpty(ctx, tr, path.Join(dir, e.name)) + if err != nil || !empty { + return false, err + } + case e.kind == kindFile && e.name == volmark.MarkerName: + default: + return false, nil + } + } + return true, nil +} + +func (h *mirrorHandler) foreignHistory(runID int64) error { + return fmt.Errorf("destination %q: the last successful sync (run %d) left no receipt at %s — the tree was written by rclone or another layout, and a native mirror does not adopt an existing tree; point the destination at a fresh or emptied root, or (after emptying it) run `squirrel destination reset %s`: %w", h.dest.Name, runID, h.receiptName(runID), h.dest.Name, ErrRefused) +} + +// seal writes the run's receipt, the manifest segment of its delta, and +// confirms it landed at its size. +func (h *mirrorHandler) seal(ctx context.Context, _ *Report, runID int64, p pushPlan, _ *mirrorOps) error { + body, err := encodeManifestSegment(p.delta) + if err != nil { + return err + } + tr, err := h.root(runID) + if err != nil { + return err + } + name := h.receiptName(runID) + if err := tr.Put(ctx, name, bytes.NewReader(body), time.Now()); err != nil { + return fmt.Errorf("write receipt %s: %w", name, err) + } + e, err := tr.Stat(ctx, name) + if err != nil { + return fmt.Errorf("confirm receipt %s: %w", name, err) + } + if e.size != int64(len(body)) { + return fmt.Errorf("receipt %s landed with size %d, want %d", name, e.size, len(body)) + } + return nil +} + +// advanceMethod is presence+size: every path's bytes were hashed as they +// streamed out and confirmed present at their size, but nothing read the +// landed bytes back. +func (h *mirrorHandler) advanceMethod(context.Context, *Report, pushPlan) (string, error) { + return store.VerifyMethodPresenceSize, nil +} + +func (h *mirrorHandler) receiptName(runID int64) string { + return path.Join(h.vol.Name, IndexDirName, "run-"+strconv.FormatInt(runID, 10)) +} + +// liveName is where a volume-relative path lives on the destination. +func (h *mirrorHandler) liveName(rel string) string { return path.Join(h.vol.Name, rel) } + +// stagingKey names a path's staging file: the lowercase hex BLAKE3 of the +// volume-relative path, unique per path and unchanged by a destination +// that folds case. +func stagingKey(rel string) string { + sum := blake3.Sum256([]byte(rel)) + return hex.EncodeToString(sum[:]) +} diff --git a/sync/mirror_reconcile.go b/sync/mirror_reconcile.go new file mode 100644 index 0000000..a90d438 --- /dev/null +++ b/sync/mirror_reconcile.go @@ -0,0 +1,198 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io/fs" + "path" + "strconv" + "strings" + + "github.com/mbertschler/squirrel/store" +) + +// reconcile settles, once at push start, every move an earlier push +// recorded but may not have finished, deciding each from where the bytes +// actually are, then removes the staging finished runs left behind. +func (h *mirrorHandler) reconcile(ctx context.Context, rep *Report, volumeID, runID int64) error { + tr, err := h.root(runID) + if err != nil { + return err + } + rows, err := h.store.ListUnsettledRemotePaths(ctx, h.dest.Name, volumeID) + if err != nil { + return fmt.Errorf("list unsettled mirror paths on %q: %w", h.dest.Name, err) + } + for _, r := range rows { + if err := h.settle(ctx, tr, r); err != nil { + return fmt.Errorf("reconcile %s on %q: %w", r.Path, h.dest.Name, err) + } + } + return h.clearFinishedStaging(ctx, rep, tr) +} + +// settlement is how reconcile resolves one unsettled row. +type settlement int + +const ( + settleLive settlement = iota + settleDisplaced + settleLost +) + +// settle looks at both places an unsettled row's version can be and +// records where it is. +func (h *mirrorHandler) settle(ctx context.Context, tr transport, r store.RemotePath) error { + at, err := statMatch(ctx, tr, h.liveName(r.Path), r) + if err != nil { + return err + } + var s settlement + switch r.State { + case store.RemotePathCommitting: + staged, err := present(ctx, tr, stagingName(h.vol.Name, r.WrittenRunID, stagingKey(r.Path))) + if err != nil { + return err + } + s = settleCommitting(staged, at) + case store.RemotePathDisplacing: + inHistory, err := statMatch(ctx, tr, historyName(h.vol.Name, r.DisplacedRunID.Int64, r.Path), r) + if err != nil { + return err + } + s = settleDisplacing(inHistory, at) + default: + return nil + } + return h.recordSettlement(ctx, r, s) +} + +// settleCommitting decides a committing row: its version is live once the +// staged file is gone and the path holds the recorded version. Otherwise +// the commit never happened, so the intent is withdrawn — the path stays +// in the delta, since no receipt sealed the run, and is planned again. +func settleCommitting(staged, atPath bool) settlement { + if !staged && atPath { + return settleLive + } + return settleLost +} + +// settleDisplacing decides a displacing row: displaced once history holds +// the version, back to live while the path still holds it, lost when +// neither does. +func settleDisplacing(inHistory, atPath bool) settlement { + switch { + case inHistory: + return settleDisplaced + case atPath: + return settleLive + default: + return settleLost + } +} + +func (h *mirrorHandler) recordSettlement(ctx context.Context, r store.RemotePath, s settlement) error { + switch { + case s == settleLost: + return h.store.MarkRemotePathsLost(ctx, r.ID) + case r.State == store.RemotePathCommitting: + return h.store.ConfirmRemotePathsLive(ctx, r.ID) + case s == settleDisplaced: + return h.store.ConfirmRemotePathsDisplaced(ctx, r.ID) + default: + return h.store.RevertRemotePathsLive(ctx, r.ID) + } +} + +// statMatch reports whether name holds the version r records. +func statMatch(ctx context.Context, tr transport, name string, r store.RemotePath) (bool, error) { + e, err := tr.Stat(ctx, name) + if errors.Is(err, fs.ErrNotExist) || errors.Is(err, errParentNotDir) { + return false, nil + } + if err != nil { + return false, err + } + return matchesRecord(e, r), nil +} + +func present(ctx context.Context, tr transport, name string) (bool, error) { + _, err := tr.Stat(ctx, name) + if errors.Is(err, fs.ErrNotExist) || errors.Is(err, errParentNotDir) { + return false, nil + } + return err == nil, err +} + +// clearFinishedStaging removes what finished runs left in staging: +// partial files from a crash, and a drifted source's staged copy. +// Anything in staging squirrel did not name is reported and left alone. +func (h *mirrorHandler) clearFinishedStaging(ctx context.Context, rep *Report, tr transport) error { + dir := path.Join(h.vol.Name, StagingDirName) + runs, err := tr.List(ctx, dir) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("list %s: %w", dir, err) + } + for _, e := range runs { + runID, ok := stagingRunID(e) + if !ok { + h.warnForeignStaging(rep, path.Join(dir, e.name)) + continue + } + if !h.runFinished(runID) { + continue + } + if err := h.clearStagingRun(ctx, rep, tr, path.Join(dir, e.name)); err != nil { + return err + } + } + return nil +} + +func (h *mirrorHandler) clearStagingRun(ctx context.Context, rep *Report, tr transport, runDir string) error { + entries, err := tr.List(ctx, runDir) + if err != nil { + return fmt.Errorf("list %s: %w", runDir, err) + } + foreign := false + for _, e := range entries { + name := path.Join(runDir, e.name) + if e.kind != kindFile || !isStagingKey(e.name) { + foreign = true + h.warnForeignStaging(rep, name) + continue + } + if err := tr.Remove(ctx, name); err != nil { + return fmt.Errorf("remove finished staging %s: %w", name, err) + } + } + if foreign { + return nil + } + if err := tr.Remove(ctx, runDir); err != nil { + return fmt.Errorf("remove finished staging %s: %w", runDir, err) + } + return nil +} + +// stagingRunID reads the run id of a staging run directory, run-. +func stagingRunID(e entry) (int64, bool) { + idText, ok := strings.CutPrefix(e.name, "run-") + if !ok || e.kind != kindDir { + return 0, false + } + id, err := strconv.ParseInt(idText, 10, 64) + if err != nil || id <= 0 || strconv.FormatInt(id, 10) != idText { + return 0, false + } + return id, true +} + +func (h *mirrorHandler) warnForeignStaging(rep *Report, name string) { + rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination %q: %s is in squirrel's staging but squirrel did not write it; it is left alone", h.dest.Name, name)) +} diff --git a/sync/mirror_test.go b/sync/mirror_test.go new file mode 100644 index 0000000..2983d55 --- /dev/null +++ b/sync/mirror_test.go @@ -0,0 +1,816 @@ +package sync + +import ( + "context" + "encoding/hex" + "errors" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/index" + "github.com/mbertschler/squirrel/runevents" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// mirrorFixture is one volume, "pics", mirrored to a native local +// destination, "usb", with the destination's volume marker in place. +type mirrorFixture struct { + store *store.Store + pair Pair + src string // the volume's source directory + dst string // the destination root +} + +func setupMirrorFixture(t *testing.T) *mirrorFixture { + t.Helper() + root := t.TempDir() + f := &mirrorFixture{src: filepath.Join(root, "src"), dst: filepath.Join(root, "usb")} + for _, d := range []string{f.src, filepath.Join(f.dst, "pics")} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + if err := volmark.Write(filepath.Join(f.dst, "pics"), volmark.Marker{Volume: "pics"}); err != nil { + t.Fatalf("seed marker: %v", err) + } + s, err := store.Open(filepath.Join(root, "test.db")) + if err != nil { + t.Fatalf("store.Open: %v", err) + } + t.Cleanup(func() { s.Close() }) + f.store = s + cfgPath := filepath.Join(root, "config.toml") + body := "[destinations.usb]\ntype = \"local\"\nroot = \"" + f.dst + "\"\n\n" + + "[volumes.pics]\npath = \"" + f.src + "\"\nsync_to = [\"usb\"]\n" + if err := os.WriteFile(cfgPath, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := config.Load(cfgPath) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + f.pair = Pair{Volume: cfg.Volumes["pics"], Destination: cfg.Destinations["usb"]} + return f +} + +func (f *mirrorFixture) write(t *testing.T, rel, body string) { + t.Helper() + p := filepath.Join(f.src, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +func (f *mirrorFixture) index(t *testing.T) { + t.Helper() + if _, err := index.Index(context.Background(), f.store, f.src, index.Options{Name: "pics"}); err != nil { + t.Fatalf("index: %v", err) + } +} + +// push runs one push with no rclone wrapper at all. +func (f *mirrorFixture) push(t *testing.T, opts Options) (Report, error) { + t.Helper() + return RunPair(context.Background(), f.store, Tools{}, f.pair, opts) +} + +func (f *mirrorFixture) mustPush(t *testing.T) Report { + t.Helper() + rep, err := f.push(t, Options{}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("push: status=%q err=%v warnings=%v", rep.Status, err, rep.Warnings) + } + return rep +} + +// pushCrashing runs one push whose transport crashes at the first call +// crashAt selects. +func (f *mirrorFixture) pushCrashing(t *testing.T, crashAt func(transportCall) bool, mode crashMode) (Report, error) { + t.Helper() + h := f.handler(t) + h.openTransport = func(d *config.Destination) (transport, error) { + raw, err := openLocalDestination(d) + if err != nil { + return nil, err + } + return &faultTransport{transport: raw, crashAt: crashAt, mode: mode}, nil + } + return h.Push(context.Background(), Options{}) +} + +func (f *mirrorFixture) handler(t *testing.T) *mirrorHandler { + t.Helper() + h, err := HandlerFor(f.store, Tools{}, f.pair) + if err != nil { + t.Fatalf("HandlerFor: %v", err) + } + return h.(*mirrorHandler) +} + +func (f *mirrorFixture) volumeID(t *testing.T) int64 { + t.Helper() + v, err := f.store.GetVolumeByName(context.Background(), "pics") + if err != nil { + t.Fatalf("GetVolumeByName: %v", err) + } + return v.ID +} + +// dest is the path of rel under the destination's volume directory. +func (f *mirrorFixture) dest(rel string) string { + return filepath.Join(f.dst, "pics", filepath.FromSlash(rel)) +} + +func (f *mirrorFixture) readDest(t *testing.T, rel string) string { + t.Helper() + b, err := os.ReadFile(f.dest(rel)) + if err != nil { + t.Fatalf("read destination %s: %v", rel, err) + } + return string(b) +} + +func (f *mirrorFixture) rows(t *testing.T) []store.RemotePath { + t.Helper() + rows, err := f.store.ListRemotePaths(context.Background(), "usb", f.volumeID(t)) + if err != nil { + t.Fatalf("ListRemotePaths: %v", err) + } + return rows +} + +// rowsAt returns the states of rel's rows, oldest first. +func (f *mirrorFixture) rowsAt(t *testing.T, rel string) []string { + t.Helper() + var states []string + for _, r := range f.rows(t) { + if r.Path == rel { + states = append(states, r.State) + } + } + return states +} + +// contentHashes collects the BLAKE3 of every file under the destination +// root outside staging: what invariant 2 says only grows. +func (f *mirrorFixture) contentHashes(t *testing.T) map[string]bool { + t.Helper() + out := map[string]bool{} + err := filepath.WalkDir(f.dst, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() && d.Name() == StagingDirName { + return filepath.SkipDir + } + if d.Type().IsRegular() { + out[fileHash(t, p)] = true + } + return nil + }) + if err != nil { + t.Fatalf("walk destination: %v", err) + } + return out +} + +func fileHash(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatalf("read %s: %v", p, err) + } + sum := blake3.Sum256(b) + return hex.EncodeToString(sum[:]) +} + +// checkInvariants asserts the design's three invariants after a clean +// push, given the content the destination held before it. +func (f *mirrorFixture) checkInvariants(t *testing.T, before map[string]bool) { + t.Helper() + ctx := context.Background() + volID := f.volumeID(t) + liveContent := map[string]int64{} + for _, r := range f.rows(t) { + want := f.contentHashOf(t, volID, r) + switch r.State { + case store.RemotePathLive: + liveContent[r.Path] = r.ContentID + if got := fileHash(t, f.dest(r.Path)); got != want { + t.Errorf("live %s holds %s, want %s", r.Path, got, want) + } + case store.RemotePathDisplaced: + p := filepath.Join(f.dst, filepath.FromSlash(historyName("pics", r.DisplacedRunID.Int64, r.Path))) + if got := fileHash(t, p); got != want { + t.Errorf("displaced %s holds %s at %s, want %s", r.Path, got, p, want) + } + case store.RemotePathCommitting, store.RemotePathDisplacing: + t.Errorf("%s row %d is still %s after a clean push", r.Path, r.ID, r.State) + } + } + after := f.contentHashes(t) + for h := range before { + if !after[h] { + t.Errorf("content %s left the destination", h) + } + } + present, err := f.store.ListPresentContent(ctx, volID) + if err != nil { + t.Fatalf("ListPresentContent: %v", err) + } + for _, d := range present { + if liveContent[d.Path] != d.ContentID { + t.Errorf("present %s has no live row holding content %d", d.Path, d.ContentID) + } + } +} + +func (f *mirrorFixture) contentHashOf(t *testing.T, volID int64, r store.RemotePath) string { + t.Helper() + hist, err := f.store.ListHistoryByPath(context.Background(), volID, r.Path) + if err != nil { + t.Fatalf("ListHistoryByPath %s: %v", r.Path, err) + } + for _, h := range hist { + if h.ContentID == r.ContentID { + return hex.EncodeToString(h.Blake3) + } + } + t.Fatalf("no files row holds content %d at %s", r.ContentID, r.Path) + return "" +} + +// TestMirrorPushWithoutRclone: a local mirror pushes through the native +// handler with no rclone wrapper, lands every present path with its bytes +// and mtime, records each one live, writes the run's receipt, and advances +// the vector as presence+size. An unchanged second push writes nothing and +// still leaves a receipt. +func TestMirrorPushWithoutRclone(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.write(t, "2024/cat.jpg", "meow") + f.index(t) + + rep := f.mustPush(t) + if rep.RcloneResult.Transferred != 2 || rep.RcloneResult.Bytes != int64(len("alpha")+len("meow")) { + t.Fatalf("counters = %+v, want 2 paths, 9 bytes", rep.RcloneResult) + } + if f.readDest(t, "a.txt") != "alpha" || f.readDest(t, "2024/cat.jpg") != "meow" { + t.Fatal("destination bytes differ from the source") + } + srcInfo, _ := os.Stat(filepath.Join(f.src, "a.txt")) + dstInfo, _ := os.Stat(f.dest("a.txt")) + if !dstInfo.ModTime().Equal(srcInfo.ModTime()) { + t.Fatalf("mtime = %v, want the source's %v", dstInfo.ModTime(), srcInfo.ModTime()) + } + for _, rel := range []string{"a.txt", "2024/cat.jpg"} { + if got := f.rowsAt(t, rel); len(got) != 1 || got[0] != store.RemotePathLive { + t.Fatalf("%s rows = %v, want one live", rel, got) + } + } + delta, err := f.store.ListPathDeltaSince(context.Background(), f.volumeID(t), 0) + if err != nil { + t.Fatal(err) + } + want, _ := encodeManifestSegment(delta) + if got := f.readDest(t, ".squirrel-index/run-"+strconv.FormatInt(rep.RunID, 10)); got != string(want) { + t.Fatalf("receipt = %q, want the delta's manifest segment %q", got, want) + } + comps := volumeComponents(t, f.store, "pics", "usb") + if len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodPresenceSize { + t.Fatalf("vector = %+v, want one presence+size component", comps) + } + run, err := f.store.GetRun(context.Background(), rep.RunID) + if err != nil || !run.Shallow.Valid || !run.Shallow.Bool { + t.Fatalf("run = %+v, %v; want recorded shallow", run, err) + } + + if rep.AlreadyCorrect != 0 { + t.Fatalf("first push already_correct = %d, want 0", rep.AlreadyCorrect) + } + again := f.mustPush(t) + if again.RcloneResult.Transferred != 0 || !again.Changed.Valid || again.Changed.Int64 != 0 || again.AlreadyCorrect != 2 { + t.Fatalf("unchanged push: counters=%+v changed=%+v already_correct=%d, want nothing written and both paths correct", again.RcloneResult, again.Changed, again.AlreadyCorrect) + } + if got := f.readDest(t, ".squirrel-index/run-"+strconv.FormatInt(again.RunID, 10)); got != "" { + t.Fatalf("unchanged push's receipt = %q, want empty", got) + } + f.checkInvariants(t, nil) +} + +// TestMirrorTranslationRules is the design's translation table, decided +// from squirrel's records alone. After one push, a changed path, an added +// one, a missing one and an offloaded one are re-planned against the full +// delta: only present paths produce an operation, and a path whose live +// record already holds its content is only confirmed. +func TestMirrorTranslationRules(t *testing.T) { + f := setupMirrorFixture(t) + for _, rel := range []string{"same.txt", "changed.txt", "gone.txt", "offloaded.txt"} { + f.write(t, rel, "v1 "+rel) + } + f.index(t) + f.mustPush(t) + f.write(t, "changed.txt", "v2 changed") + f.write(t, "new.txt", "new") + if err := os.Remove(filepath.Join(f.src, "gone.txt")); err != nil { + t.Fatal(err) + } + f.index(t) + ctx := context.Background() + volID := f.volumeID(t) + off, err := f.store.GetByPath(ctx, volID, "offloaded.txt") + if err != nil { + t.Fatal(err) + } + if err := f.store.MarkOffloaded(ctx, volID, "offloaded.txt", off.ContentID, off.LastSeenRunID); err != nil { + t.Fatalf("MarkOffloaded: %v", err) + } + delta, err := f.store.ListPathDeltaSince(ctx, volID, 0) + if err != nil { + t.Fatal(err) + } + + ops, err := f.handler(t).translate(ctx, pushPlan{volumeID: volID, delta: delta}) + if err != nil { + t.Fatalf("translate: %v", err) + } + got := map[string]string{} + for _, p := range ops.paths { + got[p.delta.Path] = map[bool]string{true: "confirm", false: "write"}[p.current] + } + want := map[string]string{ + "same.txt": "confirm", // present, live record holds C + "changed.txt": "write", // present, live record holds other content + "new.txt": "write", // present, no live record + // gone.txt (missing), offloaded.txt (offloaded) and changed.txt's + // superseded row produce nothing. + } + if len(got) != len(want) { + t.Fatalf("operations = %v, want %v", got, want) + } + for rel, op := range want { + if got[rel] != op { + t.Errorf("%s: %s, want %s", rel, got[rel], op) + } + } +} + +// TestMirrorWriteDisplacesWhatThePathHolds carries the translation table's +// destructive decisions to the disk: a recorded version moves into the +// run's history as its record, an entry squirrel never wrote moves there as +// unrecorded bytes with a warning and an audit note, and a path deleted at +// the source stays on the destination. +func TestMirrorWriteDisplacesWhatThePathHolds(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "changed.txt", "v1") + f.write(t, "gone.txt", "kept") + f.index(t) + f.mustPush(t) + f.write(t, "changed.txt", "v2") + f.write(t, "new.txt", "ours") + if err := os.Remove(filepath.Join(f.src, "gone.txt")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("new.txt"), []byte("foreign"), 0o644); err != nil { + t.Fatal(err) + } + f.index(t) + before := f.contentHashes(t) + + rep := f.mustPush(t) + run := strconv.FormatInt(rep.RunID, 10) + if f.readDest(t, "changed.txt") != "v2" || f.readDest(t, ".squirrel-history/run-"+run+"/changed.txt") != "v1" { + t.Fatal("the recorded version did not move into this run's history") + } + if got := f.rowsAt(t, "changed.txt"); len(got) != 2 || got[0] != store.RemotePathDisplaced || got[1] != store.RemotePathLive { + t.Fatalf("changed.txt rows = %v, want displaced then live", got) + } + if f.readDest(t, "new.txt") != "ours" || f.readDest(t, ".squirrel-history/run-"+run+"/new.txt") != "foreign" { + t.Fatal("the foreign entry was not preserved in history") + } + if !warned(rep, "new.txt held bytes squirrel did not write") { + t.Fatalf("warnings = %v, want one about the foreign new.txt", rep.Warnings) + } + audit, err := f.store.ListRunAudit(context.Background(), rep.RunID) + if err != nil { + t.Fatal(err) + } + if !auditHas(audit, store.TransitionDisplaceUnrecorded, "new.txt") { + t.Fatalf("audit = %+v, want a displace-unrecorded note for new.txt", audit) + } + if f.readDest(t, "gone.txt") != "kept" { + t.Fatal("a path deleted at the source left the destination") + } + f.checkInvariants(t, before) +} + +// TestMirrorRecordChangedBehindSquirrelsBack: an already-correct path +// whose bytes changed on the destination loses its record, is displaced as +// unrecorded bytes, and is written again. The first push crashes before its +// receipt, so the next one re-plans every path. +func TestMirrorRecordChangedBehindSquirrelsBack(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "ours") + f.index(t) + if rep, err := f.pushCrashing(t, isReceiptPut, crashBefore); !crashedOn(rep, err) { + t.Fatalf("crashing push = %v, want the injected crash", err) + } + if err := os.WriteFile(f.dest("a.txt"), []byte("tampered"), 0o644); err != nil { + t.Fatal(err) + } + before := f.contentHashes(t) + + rep := f.mustPush(t) + if f.readDest(t, "a.txt") != "ours" { + t.Fatal("the tampered path was not written again") + } + if got := f.rowsAt(t, "a.txt"); len(got) != 2 || got[0] != store.RemotePathLost || got[1] != store.RemotePathLive { + t.Fatalf("a.txt rows = %v, want lost then live — never displaced", got) + } + if !warned(rep, "behind squirrel's back") { + t.Fatalf("warnings = %v, want one about the changed path", rep.Warnings) + } + f.checkInvariants(t, before) +} + +func warned(rep Report, substr string) bool { + for _, w := range rep.Warnings { + if strings.Contains(w, substr) { + return true + } + } + return false +} + +func auditHas(audit []store.RunAudit, transition, substr string) bool { + for _, a := range audit { + if a.Transition == transition && strings.Contains(a.Note.String, substr) { + return true + } + } + return false +} + +func isReceiptPut(c transportCall) bool { + return c.op == "put" && strings.Contains(c.name, IndexDirName+"/run-") +} + +// TestMirrorCrashTable is the design's crash table: a push that dies at +// each point of writing one changed path, then a clean push. Each row pins +// what the crash leaves recorded and how reconcile settles it; afterwards +// the three invariants hold. +func TestMirrorCrashTable(t *testing.T) { + staged := func(c transportCall) bool { return strings.Contains(c.name, StagingDirName+"/") } + intoHistory := func(c transportCall) bool { return c.op == "rename" && strings.Contains(c.to, HistoryDirName+"/") } + commitRename := func(c transportCall) bool { return c.op == "rename" && staged(c) } + cases := []struct { + name string + crashAt func(transportCall) bool + mode crashMode + // rows after the crash, oldest first + crashed []string + check func(t *testing.T, f *mirrorFixture, clean Report) + }{ + {"staging write", func(c transportCall) bool { return c.op == "put" && staged(c) }, crashMidway, + []string{store.RemotePathLive}, nil}, + {"displacing recorded", intoHistory, crashBefore, + []string{store.RemotePathDisplacing}, nil}, + {"displace rename", intoHistory, crashAfter, + []string{store.RemotePathDisplacing}, nil}, + {"committing recorded", commitRename, crashBefore, + []string{store.RemotePathDisplaced, store.RemotePathCommitting}, nil}, + {"commit rename", commitRename, crashAfter, + []string{store.RemotePathDisplaced, store.RemotePathCommitting}, nil}, + {"every write, before the seal", isReceiptPut, crashBefore, + []string{store.RemotePathDisplaced, store.RemotePathLive}, + func(t *testing.T, _ *mirrorFixture, clean Report) { + if clean.RcloneResult.Transferred != 0 || clean.RcloneResult.Checked != 1 || clean.AlreadyCorrect != 2 { + t.Fatalf("clean push counters = %+v already_correct=%d, want the planned path confirmed and both paths correct", clean.RcloneResult, clean.AlreadyCorrect) + } + }}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "keep.txt", "untouched") + f.write(t, "a.txt", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2 is longer") + f.index(t) + before := f.contentHashes(t) + + if rep, err := f.pushCrashing(t, c.crashAt, c.mode); !crashedOn(rep, err) { + t.Fatalf("crashing push = %v (failures %+v), want the injected crash", err, rep.RcloneResult.FailedFiles) + } + if got := f.rowsAt(t, "a.txt"); !slicesEqual(got, c.crashed) { + t.Fatalf("rows after the crash = %v, want %v", got, c.crashed) + } + clean := f.mustPush(t) + if f.readDest(t, "a.txt") != "v2 is longer" { + t.Fatal("the clean push did not land the new version") + } + if c.check != nil { + c.check(t, f, clean) + } + f.checkInvariants(t, before) + f.checkStagingEmpty(t, clean.RunID) + }) + } +} + +// crashedOn reports whether a push failed on the injected crash, directly +// or on one of its paths. +func crashedOn(rep Report, err error) bool { + if errors.Is(err, errInjectedCrash) { + return true + } + for _, ff := range rep.RcloneResult.FailedFiles { + if strings.Contains(ff.Message, errInjectedCrash.Error()) { + return err != nil + } + } + return false +} + +func slicesEqual(a, b []string) bool { + return strings.Join(a, ",") == strings.Join(b, ",") +} + +// checkStagingEmpty asserts that only the latest run's staging directory +// is left, and that it holds nothing: every earlier run's staging was +// removed by reconcile. +func (f *mirrorFixture) checkStagingEmpty(t *testing.T, latest int64) { + t.Helper() + dir := f.dest(StagingDirName) + entries, err := os.ReadDir(dir) + if errors.Is(err, fs.ErrNotExist) { + return + } + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if e.Name() != "run-"+strconv.FormatInt(latest, 10) { + t.Errorf("staging still holds %s", e.Name()) + continue + } + if left, _ := os.ReadDir(filepath.Join(dir, e.Name())); len(left) != 0 { + t.Errorf("the latest run's staging holds %d entries", len(left)) + } + } +} + +// TestMirrorRefusesShallow: --shallow has nothing to switch off on a +// native mirror, so it is refused before any run starts. +func TestMirrorRefusesShallow(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + _, err := f.push(t, Options{Shallow: true}) + if err == nil || !strings.Contains(err.Error(), "--shallow") { + t.Fatalf("shallow push = %v, want a refusal naming --shallow", err) + } + if runs := mustListSyncRuns(t, f.store); len(runs) != 0 { + t.Fatalf("a refused shallow push wrote runs: %+v", runs) + } +} + +func mustListSyncRuns(t *testing.T, s *store.Store) []store.Run { + t.Helper() + runs, err := s.ListRuns(context.Background(), store.ListRunsOpts{}) + if err != nil { + t.Fatal(err) + } + var out []store.Run + for _, r := range runs { + if r.Kind == store.RunKindSync { + out = append(out, r) + } + } + return out +} + +// TestMirrorDryRunWritesNothing: a dry run previews what a push would +// write and changes nothing — no runs row, no files, no records. +func TestMirrorDryRunWritesNothing(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "alpha two") + f.write(t, "b.txt", "beta") + f.index(t) + before := len(f.rows(t)) + + rep, err := f.push(t, Options{DryRun: true}) + if err != nil || rep.RunID != 0 { + t.Fatalf("dry run: run=%d err=%v", rep.RunID, err) + } + if rep.RcloneResult.Transferred != 2 || rep.RcloneResult.Bytes != int64(len("alpha two")+len("beta")) { + t.Fatalf("preview = %+v, want 2 paths", rep.RcloneResult) + } + if _, err := os.Stat(f.dest("b.txt")); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the dry run wrote b.txt: %v", err) + } + if len(f.rows(t)) != before || len(mustListSyncRuns(t, f.store)) != 1 { + t.Fatal("the dry run recorded something") + } +} + +// TestMirrorMarkerRefusalIsRecorded: without the volume marker — an +// unplugged disk, a mistyped root — the push refuses and records the +// refusal as its own run. +func TestMirrorMarkerRefusalIsRecorded(t *testing.T) { + f := setupMirrorFixture(t) + if err := os.Remove(filepath.Join(f.dst, "pics", volmark.MarkerName)); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "alpha") + f.index(t) + rep, err := f.push(t, Options{}) + if !errors.Is(err, ErrRefused) || rep.Status != store.RunStatusRefused { + t.Fatalf("push without a marker: status=%q err=%v, want a recorded refusal", rep.Status, err) + } + if runs := mustListSyncRuns(t, f.store); len(runs) != 1 || runs[0].Status != store.RunStatusRefused { + t.Fatalf("sync runs = %+v, want one refused", runs) + } +} + +// TestMirrorWatermarkRule: a native mirror adopts no existing tree. An +// rclone-era success with its tree still there is refused; once the root +// is emptied it is a fresh start; and a root emptied behind squirrel's back +// while its records remain is refused again. +func TestMirrorWatermarkRule(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + ctx := context.Background() + rcloneRun, err := f.store.BeginRun(ctx, store.RunKindSync, f.volumeID(t), "usb", false) + if err != nil { + t.Fatal(err) + } + if err := f.store.FinishRun(ctx, rcloneRun, store.RunStatusSuccess, "", 1); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("a.txt"), []byte("alpha"), 0o644); err != nil { + t.Fatal(err) + } + + _, err = f.push(t, Options{}) + if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "does not adopt") { + t.Fatalf("push over an rclone-era tree = %v, want a refusal", err) + } + + if err := os.Remove(f.dest("a.txt")); err != nil { + t.Fatal(err) + } + f.mustPush(t) + if f.readDest(t, "a.txt") != "alpha" { + t.Fatal("the fresh start did not write the tree") + } + + if err := os.RemoveAll(filepath.Join(f.dst, "pics")); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(f.dst, "pics"), 0o755); err != nil { + t.Fatal(err) + } + if err := volmark.Write(filepath.Join(f.dst, "pics"), volmark.Marker{Volume: "pics"}); err != nil { + t.Fatal(err) + } + _, err = f.push(t, Options{}) + if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "destination reset") { + t.Fatalf("push to a wiped root with records = %v, want a refusal", err) + } +} + +// TestMirrorForeignStagingIsLeftAlone: something in staging squirrel did +// not name is reported and never removed. +func TestMirrorForeignStagingIsLeftAlone(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + first := f.mustPush(t) + foreign := f.dest(filepath.Join(StagingDirName, "run-"+strconv.FormatInt(first.RunID, 10), "notes.txt")) + if err := os.WriteFile(foreign, []byte("mine"), 0o644); err != nil { + t.Fatal(err) + } + rep := f.mustPush(t) + if !warned(rep, "notes.txt is in squirrel's staging") { + t.Fatalf("warnings = %v, want the foreign file reported", rep.Warnings) + } + if _, err := os.Stat(foreign); err != nil { + t.Fatalf("the foreign file was removed: %v", err) + } +} + +// TestMirrorFileDirectorySwap: a file that became a directory, and a +// directory that became a file, each move the old entry into history — +// the directory with every version recorded in it — before the new one +// lands. +func TestMirrorFileDirectorySwap(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a", "file a") + f.write(t, "d/x", "inside d") + f.index(t) + f.mustPush(t) + for _, rel := range []string{"a", "d"} { + if err := os.RemoveAll(filepath.Join(f.src, rel)); err != nil { + t.Fatal(err) + } + } + f.write(t, "a/b", "under a") + f.write(t, "d", "file d") + f.index(t) + before := f.contentHashes(t) + + rep := f.mustPush(t) + run := strconv.FormatInt(rep.RunID, 10) + if f.readDest(t, "a/b") != "under a" || f.readDest(t, "d") != "file d" { + t.Fatal("the swapped paths did not land") + } + if f.readDest(t, ".squirrel-history/run-"+run+"/a") != "file a" || f.readDest(t, ".squirrel-history/run-"+run+"/d/x") != "inside d" { + t.Fatal("the replaced entries are not in history") + } + if got := f.rowsAt(t, "d/x"); len(got) != 1 || got[0] != store.RemotePathDisplaced { + t.Fatalf("d/x rows = %v, want displaced with its directory", got) + } + f.checkInvariants(t, before) +} + +// TestMirrorProgressEvents: a push reports one progress event per planned +// path. +func TestMirrorProgressEvents(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.write(t, "b.txt", "beta") + f.index(t) + var events []runevents.Progress + _, err := f.push(t, Options{Progress: func(p runevents.Progress) { events = append(events, p) }}) + if err != nil { + t.Fatal(err) + } + if len(events) != 2 || events[1].Done != 2 || events[1].Total != 2 || events[1].BytesDone != 9 { + t.Fatalf("events = %+v, want two ending at 2/2 paths and 9 bytes", events) + } +} + +// blockingTransport holds every Stat until release is closed. +type blockingTransport struct { + transport + release chan struct{} +} + +func (b blockingTransport) Stat(ctx context.Context, name string) (entry, error) { + <-b.release + return b.transport.Stat(ctx, name) +} + +// TestMirrorStallFailsThePush: a transport call that makes no progress +// fails the push after the stall timeout, and a later push to the same +// destination refuses while that call is still inside the system. +func TestMirrorStallFailsThePush(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "alpha two") + f.index(t) + + release := make(chan struct{}) + h := f.handler(t) + h.stallTimeout = 50 * time.Millisecond + h.openTransport = func(d *config.Destination) (transport, error) { + raw, err := openLocalDestination(d) + return blockingTransport{transport: raw, release: release}, err + } + if _, err := h.Push(context.Background(), Options{}); !errors.Is(err, errTransportStalled) { + t.Fatalf("stalled push = %v, want errTransportStalled", err) + } + if _, err := f.push(t, Options{}); err == nil || !strings.Contains(err.Error(), "have not returned") { + t.Fatalf("push while a call is stuck = %v, want a refusal", err) + } + close(release) + deadline := time.Now().Add(5 * time.Second) + for stalledCounter("usb").Load() > 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + f.mustPush(t) + if f.readDest(t, "a.txt") != "alpha two" { + t.Fatal("the push after the stall cleared did not land") + } + f.checkInvariants(t, nil) +} diff --git a/sync/mirror_translate.go b/sync/mirror_translate.go new file mode 100644 index 0000000..67b62e9 --- /dev/null +++ b/sync/mirror_translate.go @@ -0,0 +1,73 @@ +package sync + +import ( + "context" + "fmt" + + "github.com/mbertschler/squirrel/store" +) + +// mirrorOps is the mirror translation of a plan: one operation per present +// delta path, and the live records the operations were decided against. +// execute keeps live current as it moves versions. +type mirrorOps struct { + paths []mirrorPath + live map[string]store.RemotePath // volume-relative path → live row + // inSync counts the live rows that hold their path's present content, + // in the delta or not: what the report calls already correct. + inSync int64 +} + +// mirrorPath is one planned path. When the live record already holds the +// delta's content, the path is only confirmed; otherwise the content is +// written, displacing whatever the path holds. +type mirrorPath struct { + delta store.PathDelta + // current: the path's live record holds the delta's content. + current bool +} + +// translate applies the mirror's translation rules to the delta. Rows +// that are missing, offloaded or superseded produce nothing: a +// destination keeps content the source no longer has. +// +// present, live record holds C → confirm (already correct) +// present, live record holds other → write C, displacing the recorded version +// present, no live record → write C, displacing any unrecorded entry +func (h *mirrorHandler) translate(ctx context.Context, p pushPlan) (*mirrorOps, error) { + rows, err := h.store.ListLiveRemotePaths(ctx, h.dest.Name, p.volumeID) + if err != nil { + return nil, fmt.Errorf("list live mirror paths on %q: %w", h.dest.Name, err) + } + inSync, err := h.store.CountInSyncRemotePaths(ctx, h.dest.Name, p.volumeID) + if err != nil { + return nil, err + } + ops := &mirrorOps{live: make(map[string]store.RemotePath, len(rows)), inSync: inSync} + for _, r := range rows { + ops.live[r.Path] = r + } + for _, d := range p.delta { + if d.Status != store.StatusPresent { + continue + } + live, ok := ops.live[d.Path] + ops.paths = append(ops.paths, mirrorPath{delta: d, current: ok && live.ContentID == d.ContentID}) + } + return ops, nil +} + +// preview counts what execute would do: written paths as Transferred and +// Bytes, confirmed ones as Checked, and every in-sync path as already +// correct. +func (o *mirrorOps) preview(rep *Report) { + rep.AlreadyCorrect = o.inSync + for _, p := range o.paths { + if p.current { + rep.RcloneResult.Checked++ + continue + } + rep.RcloneResult.Transferred++ + rep.RcloneResult.Bytes += p.delta.SizeBytes + } +} diff --git a/sync/mirror_write.go b/sync/mirror_write.go new file mode 100644 index 0000000..0650f0f --- /dev/null +++ b/sync/mirror_write.go @@ -0,0 +1,337 @@ +package sync + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "strings" + "time" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/runevents" + "github.com/mbertschler/squirrel/store" +) + +// mirrorWriter carries one run's execution: the guarded transport, the +// live records it keeps current, and the tally for the report. +type mirrorWriter struct { + h *mirrorHandler + rep *Report + runID int64 + tr transport + live map[string]store.RemotePath + + progress func(runevents.Progress) + total int + done int + drifted int +} + +// execute confirms or writes every planned path. A failure on one path +// is counted and the rest still run — every version that lands now is +// recorded and saves work on the retry — but any failure fails the run +// before its receipt is written, so the watermark holds. +func (h *mirrorHandler) execute(ctx context.Context, rep *Report, runID int64, ops *mirrorOps) error { + tr, err := h.root(runID) + if err != nil { + return err + } + w := &mirrorWriter{h: h, rep: rep, runID: runID, tr: tr, live: ops.live, progress: h.progress, total: len(ops.paths)} + rep.AlreadyCorrect = ops.inSync + for _, p := range ops.paths { + if err := ctx.Err(); err != nil { + return err + } + if err := w.apply(ctx, p); err != nil { + w.fail(p.delta.Path, err) + if errors.Is(err, errTransportStalled) { + break + } + } + w.done++ + w.emitProgress() + } + return w.result() +} + +func (w *mirrorWriter) apply(ctx context.Context, p mirrorPath) error { + if p.current { + ok, err := w.confirm(ctx, p.delta) + if err != nil || ok { + return err + } + } + return w.write(ctx, p.delta) +} + +// confirm checks an already-correct path with one Lstat. A path whose size +// or mtime disagrees with its record was changed behind squirrel's back: +// the record becomes lost, and the path is written again. +func (w *mirrorWriter) confirm(ctx context.Context, d store.PathDelta) (bool, error) { + live := w.live[d.Path] + e, err := w.tr.Stat(ctx, w.h.liveName(d.Path)) + if err != nil && !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, errParentNotDir) { + return false, err + } + if err == nil && matchesRecord(e, live) { + w.rep.RcloneResult.Checked++ + return true, nil + } + w.rep.AlreadyCorrect-- + if err := w.loseRecord(ctx, live, "no longer matches its record"); err != nil { + return false, err + } + return false, nil +} + +// write lands one path: stage the content while hashing it, clear the way +// (displacing whatever the path and its parents hold), then commit. +func (w *mirrorWriter) write(ctx context.Context, d store.PathDelta) error { + staged, mtime, err := w.stage(ctx, d) + if err != nil { + return err + } + if err := w.clearParents(ctx, d.Path); err != nil { + return err + } + if err := w.displace(ctx, d.Path); err != nil { + return err + } + return w.commit(ctx, d, staged, mtime) +} + +// stage streams the source into this run's staging and hashes the same +// bytes. A source that drifted from its indexed hash fails the path with +// errContentDrift; its staged file stays until the next push's reconcile +// removes it with this run's staging. +func (w *mirrorWriter) stage(ctx context.Context, d store.PathDelta) (string, time.Time, error) { + src := filepath.Join(w.h.vol.Path, filepath.FromSlash(d.Path)) + f, err := os.Open(src) + if err != nil { + return "", time.Time{}, fmt.Errorf("open source %s: %w", src, err) + } + defer f.Close() + staged := stagingName(w.h.vol.Name, w.runID, stagingKey(d.Path)) + hasher := blake3.New() + counted := &countWriter{w: hasher} + if err := w.tr.Put(ctx, staged, io.TeeReader(f, counted), time.Unix(0, d.MtimeNs)); err != nil { + return "", time.Time{}, fmt.Errorf("stage %s: %w", d.Path, err) + } + if counted.n != d.SizeBytes || !bytes.Equal(hasher.Sum(nil), d.Blake3) { + return "", time.Time{}, fmt.Errorf("%w: %s sent %d bytes hashing to %s, indexed as %d bytes %s — run `squirrel index %s` and sync again", + errContentDrift, d.Path, counted.n, hex.EncodeToString(hasher.Sum(nil)), d.SizeBytes, hex.EncodeToString(d.Blake3), w.h.vol.Name) + } + e, err := w.tr.Stat(ctx, staged) + if err != nil { + return "", time.Time{}, fmt.Errorf("confirm staged %s: %w", d.Path, err) + } + if e.size != d.SizeBytes { + return "", time.Time{}, fmt.Errorf("staged %s landed with size %d, want %d", d.Path, e.size, d.SizeBytes) + } + return staged, e.mtime, nil +} + +// clearParents displaces the first parent of rel that is not a directory +// — a file, a symlink — so rel's directory can be created. +func (w *mirrorWriter) clearParents(ctx context.Context, rel string) error { + parts := strings.Split(rel, "/") + for i := 1; i < len(parts); i++ { + parent := strings.Join(parts[:i], "/") + e, err := w.tr.Stat(ctx, w.h.liveName(parent)) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return err + } + if e.kind != kindDir { + return w.displace(ctx, parent) + } + } + return nil +} + +// displace moves whatever rel holds into this run's history. A version +// whose size and mtime match its live record moves as that record; a +// directory moves with every live record under it; anything else moves as +// unrecorded bytes, and a record they contradict becomes lost. A record +// never claims history holds bytes it doesn't. +func (w *mirrorWriter) displace(ctx context.Context, rel string) error { + e, err := w.tr.Stat(ctx, w.h.liveName(rel)) + if errors.Is(err, fs.ErrNotExist) { + return w.loseRecordAt(ctx, rel, "is gone from the destination") + } + if err != nil { + return err + } + if live, ok := w.live[rel]; ok { + if matchesRecord(e, live) { + return w.moveRecorded(ctx, rel, []int64{live.ID}) + } + if err := w.loseRecord(ctx, live, "no longer matches its record"); err != nil { + return err + } + } + if e.kind == kindDir { + return w.displaceDir(ctx, rel) + } + return w.moveUnrecorded(ctx, rel, e) +} + +// displaceDir moves a directory a file replaced, with every live record +// under it; a record whose bytes changed becomes lost first. +func (w *mirrorWriter) displaceDir(ctx context.Context, dir string) error { + var ids []int64 + for rel, live := range w.live { + if !strings.HasPrefix(rel, dir+"/") { + continue + } + e, err := w.tr.Stat(ctx, w.h.liveName(rel)) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + if err == nil && matchesRecord(e, live) { + ids = append(ids, live.ID) + continue + } + if err := w.loseRecord(ctx, live, "no longer matches its record"); err != nil { + return err + } + } + w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: directory %s was replaced by a file; it moved into %s with the %d version(s) squirrel recorded in it", + w.h.dest.Name, dir, w.historyName(dir), len(ids))) + return w.moveRecorded(ctx, dir, ids) +} + +// moveRecorded records the move of ids, renames rel into history, and +// confirms. If the rename fails the rows stay displacing, and the next +// push's reconcile settles them from where the bytes are. +func (w *mirrorWriter) moveRecorded(ctx context.Context, rel string, ids []int64) error { + if err := w.h.store.BeginRemotePathsDisplace(ctx, w.runID, ids...); err != nil { + return err + } + if err := w.tr.Rename(ctx, w.h.liveName(rel), w.historyName(rel)); err != nil { + return fmt.Errorf("displace %s: %w", rel, err) + } + if err := w.h.store.ConfirmRemotePathsDisplaced(ctx, ids...); err != nil { + return err + } + for r := range w.live { + if r == rel || strings.HasPrefix(r, rel+"/") { + delete(w.live, r) + } + } + return nil +} + +// moveUnrecorded moves bytes squirrel did not write into history, +// reporting them as a warning and in the run's audit trail. +func (w *mirrorWriter) moveUnrecorded(ctx context.Context, rel string, e entry) error { + to := w.historyName(rel) + if err := w.tr.Rename(ctx, w.h.liveName(rel), to); err != nil { + return fmt.Errorf("displace unrecorded %s: %w", rel, err) + } + w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: %s held bytes squirrel did not write (%d bytes); they are preserved at %s", w.h.dest.Name, rel, e.size, to)) + return w.h.store.AppendRunAudit(ctx, store.RunAuditEntry{ + RunID: w.runID, + Transition: store.TransitionDisplaceUnrecorded, + Note: fmt.Sprintf("path=%q size=%d moved-to=%q", rel, e.size, to), + }) +} + +// commit records the intent, renames the staged version onto rel, and +// confirms. If the rename fails the row stays committing, and the next +// push's reconcile withdraws it. +func (w *mirrorWriter) commit(ctx context.Context, d store.PathDelta, staged string, mtime time.Time) error { + id, err := w.h.store.BeginRemotePathCommit(ctx, store.RemotePathWrite{ + Destination: w.h.dest.Name, + FolderID: d.FolderID, + Name: path.Base(d.Path), + ContentID: d.ContentID, + RunID: w.runID, + MtimeNs: mtime.UnixNano(), + }) + if err != nil { + return err + } + if err := w.tr.Rename(ctx, staged, w.h.liveName(d.Path)); err != nil { + return fmt.Errorf("commit %s: %w", d.Path, err) + } + if err := w.h.store.ConfirmRemotePathsLive(ctx, id); err != nil { + return err + } + w.live[d.Path] = store.RemotePath{ID: id, Destination: w.h.dest.Name, FolderID: d.FolderID, Name: path.Base(d.Path), + ContentID: d.ContentID, WrittenRunID: w.runID, State: store.RemotePathLive, MtimeNs: mtime.UnixNano(), Path: d.Path, SizeBytes: d.SizeBytes} + w.rep.RcloneResult.Transferred++ + w.rep.RcloneResult.Bytes += d.SizeBytes + return nil +} + +// loseRecordAt marks the live record at rel lost, if there is one. +func (w *mirrorWriter) loseRecordAt(ctx context.Context, rel, why string) error { + if live, ok := w.live[rel]; ok { + return w.loseRecord(ctx, live, why) + } + return nil +} + +func (w *mirrorWriter) loseRecord(ctx context.Context, live store.RemotePath, why string) error { + if err := w.h.store.MarkRemotePathsLost(ctx, live.ID); err != nil { + return err + } + delete(w.live, live.Path) + w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: %s %s — it was changed behind squirrel's back, so it is written again", w.h.dest.Name, live.Path, why)) + return nil +} + +func (w *mirrorWriter) historyName(rel string) string { + return historyName(w.h.vol.Name, w.runID, rel) +} + +func (w *mirrorWriter) fail(rel string, err error) { + if errors.Is(err, errContentDrift) { + w.drifted++ + w.rep.Warnings = append(w.rep.Warnings, err.Error()) + return + } + w.rep.RcloneResult.Errors++ + if int64(len(w.rep.RcloneResult.FailedFiles)) < maxFailedFiles { + w.rep.RcloneResult.FailedFiles = append(w.rep.RcloneResult.FailedFiles, FailedFile{Object: rel, Message: err.Error()}) + } +} + +func (w *mirrorWriter) result() error { + if n := w.rep.RcloneResult.Errors; n > 0 { + return fmt.Errorf("%d path(s) failed to land on %q; the receipt for run %d was not written and the durability vector did not advance", n, w.h.dest.Name, w.runID) + } + if w.drifted > 0 { + return fmt.Errorf("%d path(s) on %q were refused for drifting from their indexed hash; re-index the volume and sync again — the receipt for run %d was not written and the durability vector did not advance", w.drifted, w.h.dest.Name, w.runID) + } + return nil +} + +func (w *mirrorWriter) emitProgress() { + if w.progress == nil { + return + } + w.progress(runevents.Progress{ + Stage: runevents.StageUploading, + Done: int64(w.done), + Total: int64(w.total), + BytesDone: w.rep.RcloneResult.Bytes, + }) +} + +// matchesRecord reports whether an entry found at a path is the version +// its live record describes, by kind, size and mtime. +func matchesRecord(e entry, live store.RemotePath) bool { + return e.kind == kindFile && e.size == live.SizeBytes && e.mtime.UnixNano() == live.MtimeNs +} diff --git a/sync/push.go b/sync/push.go index 68cc48c..f61b2e3 100644 --- a/sync/push.go +++ b/sync/push.go @@ -40,6 +40,9 @@ type layout[O operations] interface { // foreignHistory is the refusal for a last success at runID that left // no landing evidence on a destination that is no fresh start. foreignHistory(runID int64) error + // reconcile settles, once at push start, whatever an earlier push left + // in flight on the destination, so translate reads settled records. + reconcile(ctx context.Context, rep *Report, volumeID, runID int64) error // translate turns the plan into this layout's operations. It reads // squirrel's records and writes nothing: a dry run is translate alone. translate(ctx context.Context, p pushPlan) (O, error) @@ -62,13 +65,13 @@ type pushTarget struct { // pushThrough is the single push driver every layout shares: // -// requireIndexedVolume → markers → begin run → plan → translate → execute → seal → advance → finish → ride-along +// requireIndexedVolume → markers → begin run → reconcile → plan → translate → execute → seal → advance → finish → ride-along // // A dry run stops after translate and reports the operations' preview; it // writes no runs row. The runs row records shallow=true: no layout reads // the landed bytes back through BLAKE3, and the audit trail says so. func pushThrough[O operations](ctx context.Context, t pushTarget, l layout[O], opts Options) (Report, error) { - rep := Report{Volume: t.vol.Name, Destination: t.dest.Name} + rep := Report{Volume: t.vol.Name, Destination: t.dest.Name, Layout: t.dest.Layout} // Stamped up front so output renderers key their formatting off the // method even when the push fails early. rep.Verification.Method = VerifyMethodPresenceSize @@ -124,6 +127,9 @@ func previewPush[O operations](ctx context.Context, t pushTarget, l layout[O], r // present as success, or the next watermark would skip past it. func landPush[O operations](ctx context.Context, t pushTarget, l layout[O], rep *Report, volID, runID int64) error { rep.Status = store.RunStatusFailed + if err := l.reconcile(ctx, rep, volID, runID); err != nil { + return err + } p, err := planPush(ctx, t, l, volID, true) if err != nil { return err diff --git a/sync/sync.go b/sync/sync.go index 5e4019e..a205dbb 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -122,8 +122,12 @@ type Options struct { // was inserted; zero in dry-run mode. RcloneResult is the parsed rclone // summary, surfaced verbatim so callers can render whatever they need. type Report struct { - Volume string - Destination string + Volume string + Destination string + // Layout is the destination's layout for a push through the shared + // planner (config.Layout*), so output renderers can tell a native + // mirror from a content layout; empty for every other push. + Layout string RunID int64 RcloneResult RunResult Status string // success / partial / failed diff --git a/sync/transport_fault_test.go b/sync/transport_fault_test.go new file mode 100644 index 0000000..9cda2f0 --- /dev/null +++ b/sync/transport_fault_test.go @@ -0,0 +1,98 @@ +package sync + +import ( + "context" + "errors" + "io" + "time" +) + +// errInjectedCrash is the failure a faultTransport reports once it has +// crashed. +var errInjectedCrash = errors.New("injected crash") + +// transportCall names one call a faultTransport saw. +type transportCall struct { + op, name, to string +} + +// crashMode is how the crashing call behaves. +type crashMode int + +const ( + crashBefore crashMode = iota // the call never happens + crashAfter // the call completes, then reports failure + crashMidway // a Put lands one byte of its body +) + +// faultTransport stands in for a process that dies at one transport call: +// the first call crashAt selects behaves as mode says, and every call after +// it fails, as if nothing were left to make it. +type faultTransport struct { + transport + crashAt func(transportCall) bool + mode crashMode + crashed bool + calls []transportCall +} + +// do runs one call through the crash point. call receives whether it +// should land only part of its effect. +func (f *faultTransport) do(c transportCall, call func(midway bool) error) error { + f.calls = append(f.calls, c) + if f.crashed { + return errInjectedCrash + } + if f.crashAt == nil || !f.crashAt(c) { + return call(false) + } + f.crashed = true + switch f.mode { + case crashAfter: + _ = call(false) + case crashMidway: + _ = call(true) + } + return errInjectedCrash +} + +func (f *faultTransport) Stat(ctx context.Context, name string) (entry, error) { + var e entry + err := f.do(transportCall{op: "stat", name: name}, func(bool) error { + var err error + e, err = f.transport.Stat(ctx, name) + return err + }) + return e, err +} + +func (f *faultTransport) List(ctx context.Context, dir string) ([]entry, error) { + var es []entry + err := f.do(transportCall{op: "list", name: dir}, func(bool) error { + var err error + es, err = f.transport.List(ctx, dir) + return err + }) + return es, err +} + +func (f *faultTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + return f.do(transportCall{op: "put", name: name}, func(midway bool) error { + if midway { + r = io.LimitReader(r, 1) + } + return f.transport.Put(ctx, name, r, mtime) + }) +} + +func (f *faultTransport) Rename(ctx context.Context, from, to string) error { + return f.do(transportCall{op: "rename", name: from, to: to}, func(bool) error { + return f.transport.Rename(ctx, from, to) + }) +} + +func (f *faultTransport) Remove(ctx context.Context, name string) error { + return f.do(transportCall{op: "remove", name: name}, func(bool) error { + return f.transport.Remove(ctx, name) + }) +} diff --git a/sync/transport_guard.go b/sync/transport_guard.go index 699d611..6af1403 100644 --- a/sync/transport_guard.go +++ b/sync/transport_guard.go @@ -1,6 +1,7 @@ package sync import ( + "context" "errors" "fmt" "io/fs" @@ -49,7 +50,7 @@ func (g nameGuard) permit(op guardOp, name, to string) error { return nil } case op == opRename: - if rel, ok := g.liveRel(name); ok && to == g.historyName(g.runID, rel) { + if rel, ok := g.liveRel(name); ok && to == historyName(g.volumeDir, g.runID, rel) { return nil } if _, ok := g.liveRel(to); ok && g.stagedByThisRun(name) { @@ -104,8 +105,16 @@ func (g nameGuard) liveRel(name string) (string, bool) { return rel, true } -func (g nameGuard) historyName(runID int64, rel string) string { - return path.Join(g.volumeDir, HistoryDirName, "run-"+strconv.FormatInt(runID, 10), rel) +// historyName is where a displacement by runID moves the volume-relative +// path rel: /.squirrel-history/run-/. +func historyName(volumeDir string, runID int64, rel string) string { + return path.Join(volumeDir, HistoryDirName, "run-"+strconv.FormatInt(runID, 10), rel) +} + +// stagingName is where runID stages the path whose key is key: +// /.squirrel-staging/run-/. +func stagingName(volumeDir string, runID int64, key string) string { + return path.Join(volumeDir, StagingDirName, "run-"+strconv.FormatInt(runID, 10), key) } // isStagingKey reports whether key is the staging name of one path: the @@ -122,3 +131,24 @@ func isStagingKey(key string) bool { } return true } + +// guardedTransport is the transport a layout holds: every Rename and +// Remove passes the name guard first. +type guardedTransport struct { + transport + guard nameGuard +} + +func (t guardedTransport) Rename(ctx context.Context, from, to string) error { + if err := t.guard.permit(opRename, from, to); err != nil { + return err + } + return t.transport.Rename(ctx, from, to) +} + +func (t guardedTransport) Remove(ctx context.Context, name string) error { + if err := t.guard.permit(opRemove, name, ""); err != nil { + return err + } + return t.transport.Remove(ctx, name) +} diff --git a/sync/transport_local.go b/sync/transport_local.go index fa4f752..364aa7a 100644 --- a/sync/transport_local.go +++ b/sync/transport_local.go @@ -238,20 +238,3 @@ func renameCheckThenMove(root *os.Root, from, to string) error { } return root.Rename(filepath.FromSlash(from), filepath.FromSlash(to)) } - -// withParentDirs opens the parent directories of from and to inside root -// and hands fn their handles and the two base names, for the directory -// relative system calls a no-replace rename needs. -func withParentDirs(root *os.Root, from, to string, fn func(fromDir, toDir *os.File, fromBase, toBase string) error) error { - fromDir, err := root.Open(filepath.FromSlash(path.Dir(from))) - if err != nil { - return err - } - defer fromDir.Close() - toDir, err := root.Open(filepath.FromSlash(path.Dir(to))) - if err != nil { - return err - } - defer toDir.Close() - return fn(fromDir, toDir, path.Base(from), path.Base(to)) -} diff --git a/sync/transport_local_dirs.go b/sync/transport_local_dirs.go new file mode 100644 index 0000000..4bcb3f6 --- /dev/null +++ b/sync/transport_local_dirs.go @@ -0,0 +1,26 @@ +//go:build linux || darwin + +package sync + +import ( + "os" + "path" + "path/filepath" +) + +// withParentDirs opens the parent directories of from and to inside root +// and hands fn their handles and the two base names, for the directory +// relative system calls a no-replace rename needs. +func withParentDirs(root *os.Root, from, to string, fn func(fromDir, toDir *os.File, fromBase, toBase string) error) error { + fromDir, err := root.Open(filepath.FromSlash(path.Dir(from))) + if err != nil { + return err + } + defer fromDir.Close() + toDir, err := root.Open(filepath.FromSlash(path.Dir(to))) + if err != nil { + return err + } + defer toDir.Close() + return fn(fromDir, toDir, path.Base(from), path.Base(to)) +} diff --git a/sync/transport_stall.go b/sync/transport_stall.go new file mode 100644 index 0000000..619cc22 --- /dev/null +++ b/sync/transport_stall.go @@ -0,0 +1,135 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io" + "sync" + "sync/atomic" + "time" +) + +// errTransportStalled marks a transport call that made no progress for +// its allowance: a hung disk, or a server that stopped answering. +var errTransportStalled = errors.New("transport call made no progress") + +// stalledCalls counts, per destination name, the transport calls a push +// gave up on that have not returned yet. A local call blocked in the +// kernel cannot be interrupted, so it may still complete a move after its +// push failed; a later push to the same destination refuses while any +// remain, so it never reconciles against a move still in flight. +var stalledCalls sync.Map // destination name → *atomic.Int64 + +func stalledCounter(destination string) *atomic.Int64 { + c, _ := stalledCalls.LoadOrStore(destination, new(atomic.Int64)) + return c.(*atomic.Int64) +} + +// stallBytesPerSecond is the slowest flush rate the allowance for a +// Put's final sync assumes, after its body has been read. +const stallBytesPerSecond = 1 << 20 + +// stallTransport bounds every call of the transport it wraps by progress +// rather than wall-clock: a call that makes none for timeout fails with +// errTransportStalled. A Put makes progress with every chunk it reads. +type stallTransport struct { + transport + timeout time.Duration + stalled *atomic.Int64 +} + +// bounded runs call on its own goroutine and returns its result, or +// errTransportStalled once call went timeout without calling progress. A +// call given up on keeps its result to itself when it finally returns. +// progress resets the allowance to the duration it is given. +func bounded[T any](ctx context.Context, s stallTransport, what string, call func(ctx context.Context, progress func(time.Duration)) (T, error)) (T, error) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + allowance := make(chan time.Duration, 1) + progress := func(d time.Duration) { + select { + case <-allowance: + default: + } + allowance <- d + } + type result struct { + v T + err error + } + done := make(chan result, 1) + go func() { + v, err := call(ctx, progress) + done <- result{v, err} + }() + timer := time.NewTimer(s.timeout) + defer timer.Stop() + for { + select { + case r := <-done: + return r.v, r.err + case d := <-allowance: + timer.Reset(d) + case <-timer.C: + s.stalled.Add(1) + go func() { <-done; s.stalled.Add(-1) }() + var zero T + return zero, fmt.Errorf("%w: %s, none for %s", errTransportStalled, what, s.timeout) + } + } +} + +func (s stallTransport) Stat(ctx context.Context, name string) (entry, error) { + return bounded(ctx, s, "stat "+name, func(ctx context.Context, _ func(time.Duration)) (entry, error) { + return s.transport.Stat(ctx, name) + }) +} + +func (s stallTransport) List(ctx context.Context, dir string) ([]entry, error) { + return bounded(ctx, s, "list "+dir, func(ctx context.Context, _ func(time.Duration)) ([]entry, error) { + return s.transport.List(ctx, dir) + }) +} + +func (s stallTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + _, err := bounded(ctx, s, "put "+name, func(ctx context.Context, progress func(time.Duration)) (struct{}, error) { + return struct{}{}, s.transport.Put(ctx, name, &progressingReader{r: r, timeout: s.timeout, progress: progress}, mtime) + }) + return err +} + +func (s stallTransport) Rename(ctx context.Context, from, to string) error { + _, err := bounded(ctx, s, "rename "+from, func(ctx context.Context, _ func(time.Duration)) (struct{}, error) { + return struct{}{}, s.transport.Rename(ctx, from, to) + }) + return err +} + +func (s stallTransport) Remove(ctx context.Context, name string) error { + _, err := bounded(ctx, s, "remove "+name, func(ctx context.Context, _ func(time.Duration)) (struct{}, error) { + return struct{}{}, s.transport.Remove(ctx, name) + }) + return err +} + +// progressingReader reports each chunk it reads as progress, and at the +// end of the body allows the final sync time to flush what it read. +type progressingReader struct { + r io.Reader + timeout time.Duration + progress func(time.Duration) + n int64 +} + +func (p *progressingReader) Read(b []byte) (int, error) { + n, err := p.r.Read(b) + p.n += int64(n) + switch { + case errors.Is(err, io.EOF): + p.progress(p.timeout + time.Duration(p.n/stallBytesPerSecond)*time.Second) + case n > 0: + p.progress(p.timeout) + } + return n, err +} diff --git a/sync/vector_wiring_test.go b/sync/vector_wiring_test.go index 3c923a5..003f2c0 100644 --- a/sync/vector_wiring_test.go +++ b/sync/vector_wiring_test.go @@ -2,8 +2,6 @@ package sync import ( "context" - "os" - "path/filepath" "testing" "github.com/mbertschler/squirrel/store" @@ -28,55 +26,6 @@ func volumeComponents(t *testing.T, s *store.Store, volName, dest string) []stor return out } -// TestRunPairAdvancesVectorOnVerifiedPush: a checksum-verified successful -// mirror push advances the destination's durability vector for the -// volume's origins. -func TestRunPairAdvancesVectorOnVerifiedPush(t *testing.T) { - f := setupFixture(t) - if err := os.WriteFile(filepath.Join(f.vol.Path, "a.txt"), []byte("alpha"), 0o644); err != nil { - t.Fatal(err) - } - f.runIndex(t) - - p := Pair{Volume: f.vol, Destination: f.dest} - rep, err := RunPair(context.Background(), f.store, Tools{Rclone: f.rcl}, p, Options{}) - if err != nil { - t.Fatalf("RunPair: %v (rep=%+v)", err, rep) - } - if !rep.Verification.Verified() { - t.Fatalf("Verification = %+v, want verified", rep.Verification) - } - comps := volumeComponents(t, f.store, f.vol.Name, f.dest.Name) - if len(comps) != 1 { - t.Fatalf("components = %+v, want exactly one self component", comps) - } - if comps[0].OriginRunID < 1 { - t.Fatalf("origin_run_id = %d, want >= 1", comps[0].OriginRunID) - } -} - -// TestRunPairShallowPushLeavesVectorAlone: a shallow push is not -// content-verified, so the vector keeps its prior state. -func TestRunPairShallowPushLeavesVectorAlone(t *testing.T) { - f := setupFixture(t) - if err := os.WriteFile(filepath.Join(f.vol.Path, "a.txt"), []byte("alpha"), 0o644); err != nil { - t.Fatal(err) - } - f.runIndex(t) - - p := Pair{Volume: f.vol, Destination: f.dest} - rep, err := RunPair(context.Background(), f.store, Tools{Rclone: f.rcl}, p, Options{Shallow: true}) - if err != nil { - t.Fatalf("RunPair: %v (rep=%+v)", err, rep) - } - if rep.Verification.Verified() { - t.Fatalf("Verification = %+v, want unverified for shallow", rep.Verification) - } - if comps := volumeComponents(t, f.store, f.vol.Name, f.dest.Name); len(comps) != 0 { - t.Fatalf("components = %+v, want none after shallow push", comps) - } -} - // TestKopiaPushAdvancesVector: a kopia push whose snapshot verify // succeeds advances the vector exactly like a verified bucket push. func TestKopiaPushAdvancesVector(t *testing.T) { From de05fa12366fca8ce310585b49adab556a245dc8 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 00:13:29 +0200 Subject: [PATCH 09/61] docs: describe the native local mirror Local mirrors are now written by squirrel itself. The mirror layout page, the syncing guide, the CLI reference, the on-disk layout and formats references and the README describe how a local push stages, displaces and commits, the receipt it leaves, why it starts on a fresh or emptied root, and that --shallow is refused there. The offload refusal names the local mirror's actual gap. The design doc records what the implementation settled: the staging key, a drifted file's staging left for the next reconcile, parent displacement, directory displacement, withdrawn commits becoming lost, the per-call no-progress bound, and the parent-chain symlink check on top of os.Root. --- README.md | 6 +- cmd/squirrel/sync.go | 6 +- config/destinations.go | 12 ++-- design/native-mirror.md | 42 ++++++++++--- docs/src/content/docs/guides/syncing.md | 36 ++++++----- docs/src/content/docs/layouts/mirror.md | 62 ++++++++++++++----- docs/src/content/docs/reference/cli.md | 6 +- docs/src/content/docs/reference/formats.md | 4 ++ .../content/docs/reference/on-disk-layout.md | 5 +- 9 files changed, 127 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 43bbd09..352ecc1 100644 --- a/README.md +++ b/README.md @@ -384,7 +384,7 @@ squirrel sync pictures --to nas # just one squirrel sync # every (volume, destination) pair in config ``` -Sync compares every file with its copy on a mirror destination by checksum (rclone's `--checksum`), under the first hash both ends support — MD5 on local disks and S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an error, so the runs row is not marked success. The run records the `checksum` method, which the offload gate does not accept: a mirror can never be named in `offload_requires`. Use `--shallow` to fall back to rclone's default size+mtime comparison if you want speed over integrity for a big initial push. Encrypted (`crypt`) destinations always use the size+mtime comparison (see [Encrypted destinations](#encrypted-destinations)). +A mirror on a `local` disk is written by squirrel itself: it hashes every file with BLAKE3 as it streams out, confirms each written path's size and mtime, and records the `presence+size` method; `--shallow` is refused there, since there is no comparison to skip. Sync compares every file with its copy on a remote mirror destination by checksum (rclone's `--checksum`), under the first hash both ends support — MD5 on S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an error, so the runs row is not marked success, and the run records the `checksum` method. The offload gate accepts neither: a mirror can never be named in `offload_requires`. Use `--shallow` to fall back to rclone's default size+mtime comparison on a remote mirror if you want speed over integrity for a big initial push. Encrypted (`crypt`) destinations always use the size+mtime comparison (see [Encrypted destinations](#encrypted-destinations)). ### First use and the `.squirrel-volume` marker @@ -470,13 +470,15 @@ Each mirrored destination (`layout = "mirror"`, the default) is a tree shaped li pictures/ 2024/cat.jpg .squirrel-history/run-7/2024/cat.jpg # prior content of cat.jpg + .squirrel-index/run-12 # receipt for run 12 (local disks) .squirrel-index/index-20260604T120000.000Z-run-12.db # global index snapshot (ride-along) + .squirrel-staging/ # in-flight writes (local disks) docs/ invoice.pdf .squirrel-history/run-9/invoice.pdf ``` -`.squirrel-history/run-/` is rclone's `--backup-dir` target for that sync run. It is filtered out of all subsequent comparisons so it does not grow rclone's listing time or get uploaded back. A directory literally called `.squirrel-history` in your source volume is also filtered (with a warning), to keep the reserved name out of the destination tree by accident. +`.squirrel-history/run-/` holds the prior bytes of every file that sync run replaced, moved there first and never deleted. On a local disk squirrel writes the mirror itself: each file is staged under `.squirrel-staging/`, whatever its path held moves into history, and the staged copy is renamed into place; each run leaves a receipt of its changes at `.squirrel-index/run-`, and a local mirror starts on a fresh or emptied root. Remote mirrors are written by rclone, with history as its `--backup-dir`. History is filtered out of all subsequent comparisons so it does not grow listing time or get uploaded back. A directory literally called `.squirrel-history` in your source volume is also filtered (with a warning), to keep the reserved name out of the destination tree by accident. `.squirrel-index/` holds the index snapshots ridden along after each successful sync (see [Index snapshots](#index-snapshots)). Like `.squirrel-history`, it is filtered out of all sync and restore transfers and from peer-sync, so a snapshot is never mistaken for user content. diff --git a/cmd/squirrel/sync.go b/cmd/squirrel/sync.go index 73b7ef5..b309f1e 100644 --- a/cmd/squirrel/sync.go +++ b/cmd/squirrel/sync.go @@ -26,7 +26,7 @@ func newSyncCmd() *cobra.Command { ) cmd := &cobra.Command{ Use: "sync []", - Short: "Push configured volumes to their rclone destinations", + Short: "Push configured volumes to their destinations", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { volumeName := "" @@ -41,8 +41,8 @@ func newSyncCmd() *cobra.Command { }, } cmd.Flags().StringVar(&to, "to", "", "limit to this destination name (default: every destination declared on the volume)") - cmd.Flags().BoolVar(&shallow, "shallow", false, "skip the checksum comparison; trust rclone's default size+mtime comparison") - cmd.Flags().BoolVar(&dryRun, "dry-run", false, "preview rclone actions without transferring; no runs row is written") + cmd.Flags().BoolVar(&shallow, "shallow", false, "skip the checksum comparison on a remote mirror; trust rclone's default size+mtime comparison (refused on a local mirror)") + cmd.Flags().BoolVar(&dryRun, "dry-run", false, "preview what a push would transfer without transferring; no runs row is written") cmd.Flags().BoolVar(&initDst, "init", false, "authorise first-use destination bootstrap: write a .squirrel-volume marker, or create a kopia repository when connect finds none (refused without --init so a typo or outage can't mint a fresh empty target)") cmd.Flags().BoolVarP(&progress, "progress", "P", false, "show live transfer progress (auto-enabled on a terminal; use --progress=false to force off)") return cmd diff --git a/config/destinations.go b/config/destinations.go index 24f24b2..2f4b680 100644 --- a/config/destinations.go +++ b/config/destinations.go @@ -847,8 +847,10 @@ func layoutHidesArtifactNames(layout string) bool { // reason names the structural gap for the caller's message; it is empty // when capable. // -// The structurally-incapable shape is an rclone mirror, plain or crypt. Its -// sync compares source against destination by rclone's --checksum — under +// The structurally-incapable shape is a mirror. A native local mirror hashes +// each file as it sends it but reads nothing back, so it advances with +// presence+size and nothing upgrades it. An rclone mirror, plain or crypt, +// compares source against destination by rclone's --checksum — under // a hash rclone picks, unrelated to the index's BLAKE3 — or, behind a crypt // overlay, by size+mtime alone (sync.EffectiveShallow); and the mirror // layout records no scan-back fingerprint that a later `squirrel verify` @@ -861,9 +863,11 @@ func (d *Destination) CanEverGateOffload() (bool, string) { if d.Type == "kopia" { return true, "" } - switch d.Layout { - case LayoutContentAddressed, LayoutPacked: + switch { + case d.Layout == LayoutContentAddressed || d.Layout == LayoutPacked: return true, "" + case d.Type == "local": + return false, "local mirror destination: a push hashes each file as it sends it but reads nothing back from the disk, so its evidence stays presence+size, which is not content-verified" } return false, "mirror destination: a sync compares it with the source by rclone's checksum or by size+mtime, never against the index's BLAKE3, and the mirror layout records no scan-back fingerprint to upgrade" } diff --git a/design/native-mirror.md b/design/native-mirror.md index 1c179ae..8aca216 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -259,18 +259,26 @@ type transport interface { ### Local implementation - Built on `os.Root` (Go 1.25+). It resolves every name inside the root and - refuses to follow symlinks out of it. + refuses to follow symlinks out of it. `os.Root` does follow symlinks that + stay inside the root, so every call also checks its name's parent chain with + `Lstat` and refuses a symlink anywhere along it (`sync/transport_local.go`). - `Put` opens with `O_CREATE|O_EXCL`, copies, sets the times, then syncs. - `Rename` avoids replacing its target in one of two ways: - **Preferred:** the platform's no-replace rename (`renameat2` with `RENAME_NOREPLACE` on Linux, `renamex_np` with `RENAME_EXCL` on macOS), - or `Link` followed by `Remove`. + called on the parent directories' handles. - **Fallback:** where the filesystem supports neither (exFAT, common on - USB disks), squirrel checks with `Lstat` and then renames. A concurrent + USB disks), and on every other platform, squirrel checks with `Lstat` and + then renames. A concurrent writer from outside squirrel could still slip in between the check and the rename. Squirrel can't collide with itself here, because the run guard and the volume marker already exclude a second squirrel writer. - After a rename, the parent directories are synced. +- **Every call is bounded by progress.** A call that makes none for + `DefaultStallTimeout` (a `Put` progresses with every chunk it reads) fails the + push. A local call blocked in the kernel can't be interrupted and may still + finish a move later, so a push refuses while a call an earlier push gave up + on is still outstanding (`sync/transport_stall.go`). ### sftp implementation @@ -382,13 +390,19 @@ is treated as changed behind squirrel's back: its row becomes `lost` and the pat 1. **Reconcile** (once, at push start). Squirrel settles every `committing` and `displacing` row for this destination by checking both locations (next table). Staging left by finished runs is removed. -2. **Stage.** The source is streamed into `.squirrel-staging/run-/`, - and BLAKE3 is computed over the same bytes. If the hash doesn't match the - indexed hash, the staged file is removed and the run fails before its seal, - so the watermark stays put. That is the `errContentDrift` contract. Here the +2. **Stage.** The source is streamed into + `.squirrel-staging/run-/`, and BLAKE3 is computed over the same + bytes. The path key is the lowercase hex BLAKE3 of the volume-relative path: + the row doesn't exist yet (step 4 inserts it), and hex stays unique on a + destination that folds case. If the hash doesn't match the indexed hash, the + path fails and the run fails before its seal, so the watermark stays put. The + staged file stays until the next push's reconcile removes it with the + finished run's staging: the name guard removes no running run's staging. That is the `errContentDrift` contract. Here the hash covers exactly the bytes sent, which closes the re-hash-then-read gap noted on `uploadOneObject`. -3. **Displace.** If `Lstat` finds an entry at the path: +3. **Displace.** First any parent of the path that isn't a directory (a + file↔directory swap, a symlink) is displaced the same way. Then, if `Lstat` + finds an entry at the path: - **The entry's size and mtime match the live row:** 1. mark the row `displacing` with this run; 2. rename the entry to `.squirrel-history/run-/`; @@ -399,6 +413,9 @@ is treated as changed behind squirrel's back: its row becomes `lost` and the pat runs_audit note report. A record never claims history holds bytes it doesn't. + - **It is a directory** a file replaced: every live row under it becomes + `displacing`, the directory moves, and they become `displaced`; a row whose + bytes changed becomes `lost` first. 4. **Commit:** 1. insert the new row as `committing`; 2. rename the staged file to the path; @@ -418,10 +435,17 @@ until the next push, never content. | staging write | partial file in staging | removed with the finished run's staging | | `displacing` recorded | old version still at the path | size matches the record, so the row goes back to `live` | | displace rename | old version in history | history entry present, so the row becomes `displaced` | -| `committing` recorded | new version in staging, path empty | the intent is withdrawn, the staging file removed, and the path planned again (no seal, so it's still in the delta) | +| `committing` recorded | new version in staging, path empty | the intent is withdrawn (the row becomes `lost`: its version never reached the path), the staging file removed, and the path planned again (no seal, so it's still in the delta) | | commit rename | new version at the path | staging gone and path present, so the row becomes `live` | | every write, before the seal | tree complete, no receipt | the watermark holds, and the next push translates every path to "already correct" | +`TestMirrorCrashTable` runs each row above; `TestMirrorTranslationRules` and +`TestMirrorWriteDisplacesWhatThePathHolds` run the translation table. + +A native push reports as `already_correct` every path whose live row holds its +present content, planned or not, so an unchanged push still reads as in sync +(friction F7). + ### What the tests must cover A native mirror loses the independence rclone's own walk gave it (see "What we diff --git a/docs/src/content/docs/guides/syncing.md b/docs/src/content/docs/guides/syncing.md index c3a2f1c..32e60ec 100644 --- a/docs/src/content/docs/guides/syncing.md +++ b/docs/src/content/docs/guides/syncing.md @@ -3,8 +3,7 @@ title: Syncing & first use description: Push configured volumes to their destinations with checksum verification, and bootstrap first-use destinations safely with --init. --- -`squirrel sync` pushes configured volumes to their rclone (or kopia) -destinations. +`squirrel sync` pushes configured volumes to their destinations. ```sh squirrel sync pictures # all destinations declared on pictures @@ -18,30 +17,37 @@ squirrel sync # every (volume, destination) pair in config ## Verification -Sync compares every file with its copy on a mirror destination by checksum -(rclone's `--checksum`), under the first hash both ends support — MD5 on local -disks and S3, independent of the BLAKE3 in the index. A copy that fails the check -after transfer is an error, so the runs row is **not** marked success. The run is -recorded with the `checksum` method, which the offload gate does not accept, so a -mirror cannot back an offload. Peer syncs are different: both ends hash every -byte with BLAKE3 (see [Peer sync](/squirrel/guides/peer-sync/)). +A mirror on a `local` disk is written by squirrel itself: it hashes every file +with BLAKE3 as it streams out, confirms each written path's size and mtime, and +records the run with the `presence+size` method (see +[Mirror](/squirrel/layouts/mirror/)). -Use `--shallow` to fall back to rclone's default size+mtime comparison if you -want speed over integrity for a big initial push. Encrypted +Sync compares every file with its copy on a remote mirror destination by +checksum (rclone's `--checksum`), under the first hash both ends support — MD5 +on S3, independent of the BLAKE3 in the index. A copy that fails the check after +transfer is an error, so the runs row is **not** marked success. The run is +recorded with the `checksum` method. + +The offload gate accepts neither method, so a mirror cannot back an offload. +Peer syncs are different: both ends hash every byte with BLAKE3 (see +[Peer sync](/squirrel/guides/peer-sync/)). + +Use `--shallow` to fall back to rclone's default size+mtime comparison on a +remote mirror if you want speed over integrity for a big initial push. A local +mirror refuses it: there is no comparison to switch off. Encrypted ([`crypt`](/squirrel/layouts/encrypted/)) destinations always use the size+mtime comparison, and content-addressed/packed destinations use presence+size plus the [scan-back fingerprint](/squirrel/guides/verification/). -Sync runs do **not** pass `--delete-*` to rclone. Files removed locally remain at -the destination. +Sync never deletes at a destination: files removed locally remain there. ## Flags | Flag | Default | Meaning | |---|---|---| | `--to ` | all | Limit to this destination name. | -| `--shallow` | off | Skip the checksum comparison; trust rclone's size+mtime comparison. | -| `--dry-run` | off | Preview rclone actions without transferring; no runs row is written. | +| `--shallow` | off | Skip the checksum comparison on a remote mirror; trust rclone's size+mtime comparison. Refused on a local mirror. | +| `--dry-run` | off | Preview what a push would transfer without transferring; no runs row is written. | | `--init` | off | Authorise first-use destination bootstrap (see below). | | `--progress`, `-P` | auto on a TTY | Show a live transfer progress line (files, bytes, rate, ETA). | diff --git a/docs/src/content/docs/layouts/mirror.md b/docs/src/content/docs/layouts/mirror.md index 765368c..0336389 100644 --- a/docs/src/content/docs/layouts/mirror.md +++ b/docs/src/content/docs/layouts/mirror.md @@ -12,44 +12,78 @@ destination without a `layout` key. pictures/ 2024/cat.jpg .squirrel-history/run-7/2024/cat.jpg # prior content of cat.jpg + .squirrel-index/run-12 # receipt: what run 12 changed (local disks) .squirrel-index/index-20260604T120000.000Z-run-12.db # global index snapshot (ride-along) + .squirrel-staging/ # in-flight writes (local disks) docs/ invoice.pdf .squirrel-history/run-9/invoice.pdf ``` +## How a mirror is written + +On a `local` destination squirrel writes the mirror itself. A push plans from +the index: it sends the changes recorded since the destination's last confirmed +run, not what a fresh walk of the disk finds. For each changed path it: + +1. streams the file into `.squirrel-staging/run-/`, hashing the bytes as they + go, and refuses the path if they no longer match the index; +2. moves whatever the path holds into `.squirrel-history/run-/`; +3. renames the staged copy onto the path. The rename never replaces a file. + +squirrel records each move before making it, so the next push finishes or +withdraws whatever a crashed or unplugged push left half done. Every successful +push leaves a **receipt** at `.squirrel-index/run-`: the run's changes in the +[manifest segment format](/squirrel/reference/formats/), so the mirror can be +checked without the index. A push that finds no receipt for the last success it +recorded refuses, unless the root is empty and squirrel holds no records for it. +So a local mirror starts on a fresh or emptied root: squirrel does not adopt a +tree some other tool wrote. + +Mirrors on remote destinations (`sftp`, `s3`, `b2`, `gcs`) are written by rclone, +which compares both trees and moves overwritten files into its `--backup-dir`. + ## Append-only history -`.squirrel-history/run-/` is rclone's `--backup-dir` target for that -sync run. When a file at the destination is about to be overwritten, its prior -bytes are moved here first — never deleted. +`.squirrel-history/run-/` holds the prior bytes of every file a sync run +replaced. They are moved there first, never deleted. +- On a local mirror, anything found at a path squirrel is about to write moves + there, including bytes squirrel did not write. The run names each one in a + warning and in its audit trail. - It is **filtered out** of all subsequent comparisons, so it does not grow - rclone's listing time or get uploaded back. + listing time or get uploaded back. - A directory literally called `.squirrel-history` in your source volume is also filtered (with a warning), to keep the reserved name out of the destination tree by accident. -Sync runs do **not** pass `--delete-*` to rclone. Files removed locally remain -at the destination. +Files removed locally remain at the destination. ## Verification -Sync compares every file with its copy by checksum (rclone's `--checksum`), -under the first hash both ends support — MD5 on local disks and S3, independent +A local mirror push hashes every file with BLAKE3 as it streams out and +confirms each written path's size and mtime. Nothing reads the landed bytes back +yet, so the run advances the destination's durability evidence under the +`presence+size` method. `--shallow` is refused on a local mirror: there is no +comparison to switch off. + +A remote mirror compares every file with its copy by checksum (rclone's +`--checksum`), under the first hash both ends support — MD5 on S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an -error, so the run is not marked success. The run advances the destination's -durability evidence under the `checksum` method, which -[`squirrel status`](/squirrel/reference/cli/) shows but the offload gate does not -accept: a mirror cannot be named in +error, so the run is not marked success, and the run advances the evidence under +the `checksum` method. + +[`squirrel status`](/squirrel/reference/cli/) shows either method, but the +offload gate accepts neither: a mirror cannot be named in [`offload_requires`](/squirrel/guides/offloading/). See [Syncing & first use](/squirrel/guides/syncing/). ## Index snapshots `.squirrel-index/` holds the [index snapshots](/squirrel/configuration/index-snapshots/) -ridden along after each successful sync. Like `.squirrel-history`, it is filtered -out of all sync and restore transfers and from peer-sync. +ridden along after each successful sync, and a local mirror's receipts. Like +`.squirrel-history`, it is filtered out of all sync and restore transfers and +from peer-sync. ## When to use another layout diff --git a/docs/src/content/docs/reference/cli.md b/docs/src/content/docs/reference/cli.md index 89d1e50..ac0cfd9 100644 --- a/docs/src/content/docs/reference/cli.md +++ b/docs/src/content/docs/reference/cli.md @@ -95,7 +95,7 @@ Indexing by raw path is not supported. See [Indexing](/squirrel/guides/indexing/ ## squirrel sync -**Push configured volumes to their rclone destinations.** +**Push configured volumes to their destinations.** ``` squirrel sync [] @@ -108,8 +108,8 @@ Optional single positional. No arg = every `(volume, destination)` pair; one arg | Flag | Default | Meaning | |---|---|---| | `--to` | all | Limit to this destination name. | -| `--shallow` | `false` | Skip the checksum comparison on mirror destinations; trust rclone's size+mtime comparison. A peer sync hashes every byte on both ends regardless. | -| `--dry-run` | `false` | Preview rclone actions without transferring; no runs row is written. | +| `--shallow` | `false` | Skip the checksum comparison on remote mirror destinations; trust rclone's size+mtime comparison. Refused on a local mirror, which has no comparison to skip. A peer sync hashes every byte on both ends regardless. | +| `--dry-run` | `false` | Preview what a push would transfer without transferring; no runs row is written. | | `--init` | `false` | Authorise first-use destination bootstrap. | | `--progress`, `-P` | auto on a TTY | Show live transfer progress (files, bytes, rate, ETA). | diff --git a/docs/src/content/docs/reference/formats.md b/docs/src/content/docs/reference/formats.md index e215e3f..79fcfef 100644 --- a/docs/src/content/docs/reference/formats.md +++ b/docs/src/content/docs/reference/formats.md @@ -25,6 +25,10 @@ sorted by `(path, status)`: | `size_bytes` | File size as indexed. | | `mtime_ns` | Modification time (nanoseconds) as indexed. | +A [mirror](/squirrel/layouts/mirror/) on a local disk writes the same format as +its receipt, at `/.squirrel-index/run-`; there the bytes of a +`present` path are at the path itself. + ### Replaying segments Process segments in **ascending run id**; each line with status `present`, diff --git a/docs/src/content/docs/reference/on-disk-layout.md b/docs/src/content/docs/reference/on-disk-layout.md index 0028d4c..8620b2e 100644 --- a/docs/src/content/docs/reference/on-disk-layout.md +++ b/docs/src/content/docs/reference/on-disk-layout.md @@ -16,6 +16,7 @@ A tree shaped like the local volumes: pictures/ 2024/cat.jpg .squirrel-history/run-7/2024/cat.jpg # prior content of cat.jpg + .squirrel-index/run-12 # receipt for run 12 (local disks) .squirrel-index/index-20260604T120000.000Z-run-12.db # global index snapshot (ride-along) docs/ invoice.pdf @@ -86,8 +87,8 @@ for user content: | Directory | Purpose | |---|---| -| `.squirrel-history/run-/` | rclone's `--backup-dir` target — prior bytes of overwritten files ([mirror](/squirrel/layouts/mirror/)). | -| `.squirrel-index/` | Ride-along [index snapshots](/squirrel/configuration/index-snapshots/). | +| `.squirrel-history/run-/` | Prior bytes of the files a sync run replaced on a [mirror](/squirrel/layouts/mirror/). | +| `.squirrel-index/` | Ride-along [index snapshots](/squirrel/configuration/index-snapshots/), and a local mirror's receipts. | | `.squirrel-restore-history/run-/` | Files displaced by an [`--in-place` restore](/squirrel/guides/restore/). | | `.squirrel-staging/run-/` | A native [mirror](/squirrel/layouts/mirror/)'s in-flight writes, renamed onto their paths once complete. | From 5d74066bcf285f4e412f21cf9930ebf5625f2677 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 00:15:05 +0200 Subject: [PATCH 10/61] sync: tighten the mirror's record type and comments RemotePath drops the fields no reader uses, and the transport, guard and planner comments state what the code does. --- store/remote_paths.go | 21 +++++++++------------ sync/mirror.go | 5 ++--- sync/mirror_write.go | 8 ++++---- sync/push.go | 4 ++-- sync/transport.go | 10 +++++----- sync/transport_guard.go | 4 ++-- 6 files changed, 24 insertions(+), 28 deletions(-) diff --git a/store/remote_paths.go b/store/remote_paths.go index 494d427..654fe7b 100644 --- a/store/remote_paths.go +++ b/store/remote_paths.go @@ -26,14 +26,11 @@ const ( ) // RemotePath is one version squirrel wrote at a mirror path on a -// destination, keyed on the files row (FolderID, Name, ContentID) it came -// from. Path and SizeBytes are read through that row's folder and content. -// MtimeNs is the mtime the destination reported for the written version. +// destination, keyed on the files row it came from. Path and SizeBytes are +// read through that row's folder and content. MtimeNs is the mtime the +// destination reported for the written version. type RemotePath struct { ID int64 - Destination string - FolderID int64 - Name string ContentID int64 WrittenRunID int64 State string @@ -113,9 +110,9 @@ func (s *Store) MarkRemotePathsLost(ctx context.Context, ids ...int64) error { } // transitionRemotePaths applies one state transition to every id in one -// transaction. update takes the prefix args followed by the row id; a row -// that is not in the transition's source state fails the whole batch, so -// a record never jumps a move it did not witness. +// transaction. update takes the prefix args followed by the row id. Each +// row must be in the transition's source state or the whole batch fails, +// so a record moves only through the moves it witnessed. func (s *Store) transitionRemotePaths(ctx context.Context, ids []int64, to, update string, prefix ...any) error { if len(ids) == 0 { return nil @@ -144,7 +141,7 @@ func (s *Store) transitionRemotePaths(ctx context.Context, ids []int64, to, upda // remotePathSelect reads remote_paths rows with their volume-relative path // and content size (table aliases rp, fo, c). const remotePathSelect = ` - SELECT rp.id, rp.destination, rp.folder_id, rp.name, rp.content_id, rp.written_run_id, + SELECT rp.id, rp.content_id, rp.written_run_id, rp.state, rp.displaced_run_id, rp.mtime_ns, CASE fo.path WHEN '' THEN rp.name ELSE fo.path || '/' || rp.name END, c.size_bytes @@ -154,7 +151,7 @@ const remotePathSelect = ` func scanRemotePath(s rowScanner) (RemotePath, error) { var r RemotePath - err := s.Scan(&r.ID, &r.Destination, &r.FolderID, &r.Name, &r.ContentID, &r.WrittenRunID, + err := s.Scan(&r.ID, &r.ContentID, &r.WrittenRunID, &r.State, &r.DisplacedRunID, &r.MtimeNs, &r.Path, &r.SizeBytes) return r, err } @@ -165,7 +162,7 @@ func scanRemotePath(s rowScanner) (RemotePath, error) { func (s *Store) ListLiveRemotePaths(ctx context.Context, destination string, volumeID int64) ([]RemotePath, error) { return queryRows(ctx, s.db, remotePathSelect+` WHERE rp.destination = ? AND fo.volume_id = ? AND rp.state = 'live' - ORDER BY 10 + ORDER BY 7 `, scanRemotePath, destination, volumeID) } diff --git a/sync/mirror.go b/sync/mirror.go index c95fca2..118ee9e 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -182,9 +182,8 @@ func (h *mirrorHandler) seal(ctx context.Context, _ *Report, runID int64, p push return nil } -// advanceMethod is presence+size: every path's bytes were hashed as they -// streamed out and confirmed present at their size, but nothing read the -// landed bytes back. +// advanceMethod is presence+size: the push hashed every path's bytes as +// they streamed out and confirmed each landed at its size. func (h *mirrorHandler) advanceMethod(context.Context, *Report, pushPlan) (string, error) { return store.VerifyMethodPresenceSize, nil } diff --git a/sync/mirror_write.go b/sync/mirror_write.go index 0650f0f..8b86047 100644 --- a/sync/mirror_write.go +++ b/sync/mirror_write.go @@ -162,8 +162,8 @@ func (w *mirrorWriter) clearParents(ctx context.Context, rel string) error { // displace moves whatever rel holds into this run's history. A version // whose size and mtime match its live record moves as that record; a // directory moves with every live record under it; anything else moves as -// unrecorded bytes, and a record they contradict becomes lost. A record -// never claims history holds bytes it doesn't. +// unrecorded bytes, and a record they contradict becomes lost, so a +// record in history always vouches for the bytes there. func (w *mirrorWriter) displace(ctx context.Context, rel string) error { e, err := w.tr.Stat(ctx, w.h.liveName(rel)) if errors.Is(err, fs.ErrNotExist) { @@ -268,8 +268,8 @@ func (w *mirrorWriter) commit(ctx context.Context, d store.PathDelta, staged str if err := w.h.store.ConfirmRemotePathsLive(ctx, id); err != nil { return err } - w.live[d.Path] = store.RemotePath{ID: id, Destination: w.h.dest.Name, FolderID: d.FolderID, Name: path.Base(d.Path), - ContentID: d.ContentID, WrittenRunID: w.runID, State: store.RemotePathLive, MtimeNs: mtime.UnixNano(), Path: d.Path, SizeBytes: d.SizeBytes} + w.live[d.Path] = store.RemotePath{ID: id, ContentID: d.ContentID, WrittenRunID: w.runID, State: store.RemotePathLive, + MtimeNs: mtime.UnixNano(), Path: d.Path, SizeBytes: d.SizeBytes} w.rep.RcloneResult.Transferred++ w.rep.RcloneResult.Bytes += d.SizeBytes return nil diff --git a/sync/push.go b/sync/push.go index f61b2e3..7eded82 100644 --- a/sync/push.go +++ b/sync/push.go @@ -68,8 +68,8 @@ type pushTarget struct { // requireIndexedVolume → markers → begin run → reconcile → plan → translate → execute → seal → advance → finish → ride-along // // A dry run stops after translate and reports the operations' preview; it -// writes no runs row. The runs row records shallow=true: no layout reads -// the landed bytes back through BLAKE3, and the audit trail says so. +// writes no runs row. The runs row records shallow=true: every layout +// confirms what landed by presence and size, and the audit trail says so. func pushThrough[O operations](ctx context.Context, t pushTarget, l layout[O], opts Options) (Report, error) { rep := Report{Volume: t.vol.Name, Destination: t.dest.Name, Layout: t.dest.Layout} // Stamped up front so output renderers key their formatting off the diff --git a/sync/transport.go b/sync/transport.go index 6df2e42..24e105e 100644 --- a/sync/transport.go +++ b/sync/transport.go @@ -9,12 +9,12 @@ import ( ) // transport is byte-level access to one destination root. Names are -// slash-separated and relative to the root; symlinks are never followed. -// Nothing replaces an existing name: Put creates exclusively and Rename -// never replaces its target, so no transport call can overwrite bytes. +// slash-separated and relative to the root, and a name whose path crosses +// a symlink is refused. Put creates exclusively and Rename fails on an +// existing target, so every call leaves bytes already there in place. type transport interface { - // Stat describes name without following a symlink there; - // fs.ErrNotExist when absent. + // Stat describes name itself, a symlink as a symlink; fs.ErrNotExist + // when absent. Stat(ctx context.Context, name string) (entry, error) // List describes the entries directly in dir ("." is the root). List(ctx context.Context, dir string) ([]entry, error) diff --git a/sync/transport_guard.go b/sync/transport_guard.go index 6af1403..5e01d9c 100644 --- a/sync/transport_guard.go +++ b/sync/transport_guard.go @@ -33,7 +33,8 @@ const ( ) // permit is the whole audit surface for destroying or moving bytes on a -// destination. It allows: +// destination. A guard held by no run (runID 0, a dry run's reads) refuses +// everything; otherwise it allows: // // - Remove of a staging entry, or an emptied staging run directory, // of a run that has finished: /.squirrel-staging/run-[/]; @@ -44,7 +45,6 @@ const ( func (g nameGuard) permit(op guardOp, name, to string) error { switch { case g.runID == 0: - // A guard no run holds allows nothing; a dry run moves no bytes. case op == opRemove: if g.removable(name) { return nil From b47961e035b8b1b242934cb6c1bbec7465013d65 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 00:30:27 +0200 Subject: [PATCH 11/61] sync: keep mirror copies out of the content layouts' upload check ContentPresentOnDestination's only callers are the content-addressed and packed upload-once checks, and a mirror copy is not where those layouts read their bytes. Counting it would let a destination whose mirror records outlived a switch to a content layout skip the objects and still seal the run; it also scanned remote_paths on every call. The check stays with objects and packs, and the design records why. A native mirror now notes each move of unrecorded bytes in the run's audit trail before making it, including a replaced directory, and its refusal for a root without receipts names both causes: a tree it did not write, or a root emptied while records remain. --- design/native-mirror.md | 11 ++++++++--- store/content_presence.go | 26 +++++++++++-------------- store/remote_paths_test.go | 39 ++++++++++---------------------------- sync/mirror.go | 2 +- sync/mirror_write.go | 24 ++++++++++++++++++----- 5 files changed, 49 insertions(+), 53 deletions(-) diff --git a/design/native-mirror.md b/design/native-mirror.md index 8aca216..0339b5b 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -367,9 +367,14 @@ CREATE INDEX idx_remote_paths_unsettled ON remote_paths (destination) - **A row is `lost` when its bytes are no longer where it says.** A push or a verify pass found other bytes there, or nothing. The row keeps its history but stops vouching for its content. -- **The upload-once check sees mirror copies.** `ContentPresentOnDestination` - gains `remote_paths` rows in the `live` and `displaced` states as a third - source. `lost` rows never count. +- **The upload-once check leaves mirror copies out.** The plan was for + `ContentPresentOnDestination` to gain `remote_paths` rows in the `live` and + `displaced` states as a third source. Its only callers are the content + layouts' upload-once checks, and a mirror copy isn't at `objects/`: a + destination whose mirror records outlived a switch to a content layout would + skip those objects and still seal. So the check stays with objects and packs, + and the mirror decides from its own records. `DestinationHasUploadRecords` + does count every `remote_paths` row. ### Translation rules diff --git a/store/content_presence.go b/store/content_presence.go index dfb500a..8718e98 100644 --- a/store/content_presence.go +++ b/store/content_presence.go @@ -6,16 +6,16 @@ import ( ) // ContentPresentOnDestination reports whether the content is recorded as -// stored on the destination by any layout: a remote_objects row (the -// content-addressed per-hash object), a remote_packs row for a pack this -// content belongs to (the packed layout bundles it), or a mirror copy — a -// remote_paths row that is live or displaced (a lost row stopped vouching -// for its bytes). Fingerprint state is ignored — this is the upload-once -// dedup gate, the generalisation of HasRemoteObject, so a push never -// re-uploads bytes already offsite in any form. Every branch is -// per-destination: a pack this content sits in counts only when that pack -// was uploaded to *this* destination, so a pack landed elsewhere never -// suppresses a needed upload. +// uploaded to the destination by either offsite layout: a remote_objects +// row (the content-addressed per-hash object) or a remote_packs row for a +// pack this content belongs to (the packed layout bundles it). Fingerprint +// state is ignored — this is the upload-once dedup gate, the two-source +// generalisation of HasRemoteObject, so a push never re-uploads bytes +// already offsite in either form. Both branches are per-destination: a pack +// this content sits in counts only when that pack was uploaded to *this* +// destination, so a pack landed elsewhere never suppresses a needed upload. +// A mirror copy is at its path rather than where these layouts read their +// bytes, so remote_paths is left to the mirror's own records. func (s *Store) ContentPresentOnDestination(ctx context.Context, contentID int64, destination string) (bool, error) { var present int err := s.db.QueryRowContext(ctx, ` @@ -26,11 +26,7 @@ func (s *Store) ContentPresentOnDestination(ctx context.Context, contentID int64 JOIN remote_packs rp ON rp.pack_id = pm.pack_id WHERE pm.content_id = ? AND rp.destination = ? ) - OR EXISTS ( - SELECT 1 FROM remote_paths - WHERE content_id = ? AND destination = ? AND state IN ('live', 'displaced') - ) - `, contentID, destination, contentID, destination, contentID, destination).Scan(&present) + `, contentID, destination, contentID, destination).Scan(&present) if err != nil { return false, fmt.Errorf("lookup content presence on %q: %w", destination, err) } diff --git a/store/remote_paths_test.go b/store/remote_paths_test.go index f79a166..a47dc01 100644 --- a/store/remote_paths_test.go +++ b/store/remote_paths_test.go @@ -148,48 +148,29 @@ func TestRemotePathOneLiveVersionPerPath(t *testing.T) { } } -// TestContentPresentOnDestinationSeesMirrorCopies: a live or displaced -// mirror copy counts as the content being on the destination; a committing -// or lost one does not. -func TestContentPresentOnDestinationSeesMirrorCopies(t *testing.T) { +// TestContentPresentOnDestinationCountsContentLayoutsOnly: the content +// layouts' upload-once check counts only bytes where they read them. A +// live mirror copy sits at its path, so a destination whose mirror records +// outlived a switch to a content layout still uploads the object. +func TestContentPresentOnDestinationCountsContentLayoutsOnly(t *testing.T) { s := openTestStore(t) ctx := context.Background() d, _, runID := remotePathFixture(t, s) - present := func() bool { - t.Helper() - ok, err := s.ContentPresentOnDestination(ctx, d.ContentID, "usb") - if err != nil { - t.Fatalf("ContentPresentOnDestination: %v", err) - } - return ok - } id, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)) if err != nil { t.Fatalf("BeginRemotePathCommit: %v", err) } - if present() { - t.Fatal("a committing copy counts as present") - } if err := s.ConfirmRemotePathsLive(ctx, id); err != nil { t.Fatal(err) } - if !present() { - t.Fatal("a live copy does not count as present") - } - if err := s.BeginRemotePathsDisplace(ctx, runID, id); err != nil { - t.Fatal(err) - } - if err := s.ConfirmRemotePathsDisplaced(ctx, id); err != nil { - t.Fatal(err) + if ok, err := s.ContentPresentOnDestination(ctx, d.ContentID, "usb"); err != nil || ok { + t.Fatalf("ContentPresentOnDestination with only a mirror copy = %t, %v; want false", ok, err) } - if !present() { - t.Fatal("a displaced copy does not count as present") - } - if err := s.MarkRemotePathsLost(ctx, id); err != nil { + if err := s.InsertRemoteObject(ctx, RemoteObject{ContentID: d.ContentID, Destination: "usb", UploadedRunID: runID}); err != nil { t.Fatal(err) } - if present() { - t.Fatal("a lost copy counts as present") + if ok, err := s.ContentPresentOnDestination(ctx, d.ContentID, "usb"); err != nil || !ok { + t.Fatalf("ContentPresentOnDestination with an object = %t, %v; want true", ok, err) } } diff --git a/sync/mirror.go b/sync/mirror.go index 118ee9e..94e0700 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -154,7 +154,7 @@ func treeEmpty(ctx context.Context, tr transport, dir string) (bool, error) { } func (h *mirrorHandler) foreignHistory(runID int64) error { - return fmt.Errorf("destination %q: the last successful sync (run %d) left no receipt at %s — the tree was written by rclone or another layout, and a native mirror does not adopt an existing tree; point the destination at a fresh or emptied root, or (after emptying it) run `squirrel destination reset %s`: %w", h.dest.Name, runID, h.receiptName(runID), h.dest.Name, ErrRefused) + return fmt.Errorf("destination %q: the last successful sync (run %d) left no receipt at %s, so the root holds a tree this mirror did not write (by rclone, or another layout) or was emptied while squirrel still records uploads to it; a native mirror does not adopt an existing tree: point the destination at a fresh or emptied root, and after emptying it run `squirrel destination reset %s`: %w", h.dest.Name, runID, h.receiptName(runID), h.dest.Name, ErrRefused) } // seal writes the run's receipt, the manifest segment of its delta, and diff --git a/sync/mirror_write.go b/sync/mirror_write.go index 8b86047..cd7b805 100644 --- a/sync/mirror_write.go +++ b/sync/mirror_write.go @@ -206,9 +206,15 @@ func (w *mirrorWriter) displaceDir(ctx context.Context, dir string) error { return err } } - w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: directory %s was replaced by a file; it moved into %s with the %d version(s) squirrel recorded in it", + if err := w.noteUnrecordedMove(ctx, fmt.Sprintf("directory=%q recorded-versions=%d moving-to=%q", dir, len(ids), w.historyName(dir))); err != nil { + return err + } + if err := w.moveRecorded(ctx, dir, ids); err != nil { + return err + } + w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: directory %s was replaced by a file; it moved into %s with the %d version(s) squirrel recorded in it and anything else it held", w.h.dest.Name, dir, w.historyName(dir), len(ids))) - return w.moveRecorded(ctx, dir, ids) + return nil } // moveRecorded records the move of ids, renames rel into history, and @@ -232,18 +238,26 @@ func (w *mirrorWriter) moveRecorded(ctx context.Context, rel string, ids []int64 return nil } -// moveUnrecorded moves bytes squirrel did not write into history, -// reporting them as a warning and in the run's audit trail. +// moveUnrecorded moves bytes squirrel did not write into history. The +// move is noted in the run's audit trail before it happens, and reported +// as a warning once it did. func (w *mirrorWriter) moveUnrecorded(ctx context.Context, rel string, e entry) error { to := w.historyName(rel) + if err := w.noteUnrecordedMove(ctx, fmt.Sprintf("path=%q size=%d moving-to=%q", rel, e.size, to)); err != nil { + return err + } if err := w.tr.Rename(ctx, w.h.liveName(rel), to); err != nil { return fmt.Errorf("displace unrecorded %s: %w", rel, err) } w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: %s held bytes squirrel did not write (%d bytes); they are preserved at %s", w.h.dest.Name, rel, e.size, to)) + return nil +} + +func (w *mirrorWriter) noteUnrecordedMove(ctx context.Context, note string) error { return w.h.store.AppendRunAudit(ctx, store.RunAuditEntry{ RunID: w.runID, Transition: store.TransitionDisplaceUnrecorded, - Note: fmt.Sprintf("path=%q size=%d moved-to=%q", rel, e.size, to), + Note: note, }) } From 0a5e785c454e698ae1b619c15f1a923d49ac2bd7 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 00:59:36 +0200 Subject: [PATCH 12/61] config: reject rclone-only keys on native mirrors A plain sftp mirror is about to be written by squirrel itself, like a local one. checkers tunes rclone and hash_algo names the hash command rclone runs on the server; neither applies there, so both are refused. Destination.NativeMirror names the destinations squirrel writes itself. --- config/destinations.go | 35 ++++++++++++++----- config/fingerprint_knobs_test.go | 33 ++++++++++++++--- .../content/docs/reference/configuration.md | 4 +-- 3 files changed, 57 insertions(+), 15 deletions(-) diff --git a/config/destinations.go b/config/destinations.go index 2f4b680..906f62a 100644 --- a/config/destinations.go +++ b/config/destinations.go @@ -146,11 +146,12 @@ func resolveDestination(name string, raw map[string]any) (*Destination, error) { if err != nil { return nil, err } - hashAlgo, err := resolveHashAlgo(raw, typ, layout) + native := nativeMirror(typ, layout, crypt != nil) + hashAlgo, err := resolveHashAlgo(raw, typ, layout, native) if err != nil { return nil, err } - checkers, err := resolveCheckers(raw, typ) + checkers, err := resolveCheckers(raw, typ, native) if err != nil { return nil, err } @@ -262,10 +263,11 @@ var sftpHashAlgos = map[string]bool{ // resolveHashAlgo validates the optional `hash_algo` key. sftp is the // one backend where rclone must be told which server-side hash command // to run; every other type exposes a fixed checksum, so the key is -// rejected there. Content-addressed sftp destinations default to +// rejected there, and so is it on a native sftp mirror, which runs no +// command on the server. Content-addressed sftp destinations default to // "sha256" so scan-back fingerprints get a strong checksum without // relying on rclone's md5/sha1 preference. -func resolveHashAlgo(raw map[string]any, typ, layout string) (string, error) { +func resolveHashAlgo(raw map[string]any, typ, layout string, native bool) (string, error) { v, err := optionalString(raw, "hash_algo") if err != nil { return "", err @@ -279,6 +281,9 @@ func resolveHashAlgo(raw map[string]any, typ, layout string) (string, error) { if typ != "sftp" { return "", fmt.Errorf(`hash_algo is only supported on type "sftp" destinations; type %q exposes a fixed checksum`, typ) } + if native { + return "", errors.New("hash_algo names the hash command run on the sftp server, and a mirror without crypt runs none: squirrel writes it itself and hashes every file as it sends it") + } if !sftpHashAlgos[v] { return "", fmt.Errorf("unknown hash_algo %q (supported: %v)", v, sortedKeys(sftpHashAlgos)) } @@ -286,14 +291,17 @@ func resolveHashAlgo(raw map[string]any, typ, layout string) (string, error) { } // resolveCheckers validates the optional `checkers` key: a positive -// integer cap on rclone's concurrent checkers for this destination. -func resolveCheckers(raw map[string]any, typ string) (int, error) { +// integer cap on rclone's concurrent checkers for this destination. A +// native mirror runs no rclone, so the key is rejected there. +func resolveCheckers(raw map[string]any, typ string, native bool) (int, error) { v, ok := raw["checkers"] if !ok { return 0, nil } - switch typ { - case "local", "kopia": + switch { + case native: + return 0, fmt.Errorf("checkers caps rclone's checkers, and a type %q mirror without crypt is written by squirrel itself, without rclone", typ) + case typ == "kopia": return 0, fmt.Errorf("checkers requires an rclone-remote destination type, not %q", typ) } n, isInt := v.(int64) @@ -825,6 +833,17 @@ func sortedSubset(in []string) []string { return out } +// NativeMirror reports whether squirrel writes this destination itself, +// through its own transport, instead of driving rclone: a mirror on a +// local disk, or on an sftp server without crypt. +func (d *Destination) NativeMirror() bool { + return nativeMirror(d.Type, d.Layout, d.Crypt != nil) +} + +func nativeMirror(typ, layout string, crypt bool) bool { + return layout == LayoutMirror && !crypt && (typ == "local" || typ == "sftp") +} + // HidesArtifactNames reports whether this destination names its content // objects, packs, and per-volume directories by a keyed BLAKE3 hash derived // from its crypt passwords, so the remote discloses neither a path nor a diff --git a/config/fingerprint_knobs_test.go b/config/fingerprint_knobs_test.go index 65576e4..778b5cd 100644 --- a/config/fingerprint_knobs_test.go +++ b/config/fingerprint_knobs_test.go @@ -44,7 +44,7 @@ root = "/data" } // TestLoadHashAlgoExplicit: an explicit hash_algo overrides the default -// and renders on mirrored sftp destinations too. +// and renders on an encrypted sftp mirror, which rclone still writes. func TestLoadHashAlgoExplicit(t *testing.T) { cfg, err := Load(writeConfig(t, ` [destinations.archive] @@ -61,6 +61,9 @@ host = "host.example" user = "u" root = "/data" hash_algo = "sha256" + +[destinations.mirror.crypt] +password = "pw" `)) if err != nil { t.Fatalf("Load: %v", err) @@ -76,6 +79,24 @@ hash_algo = "sha256" } } +// TestLoadRejectsRcloneKeysOnNativeMirrors: squirrel writes a plain sftp +// mirror itself, so the keys that only tune rclone are refused there. +func TestLoadRejectsRcloneKeysOnNativeMirrors(t *testing.T) { + for _, key := range []string{`hash_algo = "sha256"`, "checkers = 4"} { + _, err := Load(writeConfig(t, ` +[destinations.mirror] +type = "sftp" +host = "host.example" +user = "u" +root = "/data" +`+key+"\n")) + name, _, _ := strings.Cut(key, " ") + if err == nil || !strings.Contains(err.Error(), name) || !strings.Contains(err.Error(), "squirrel") { + t.Fatalf("%s on a plain sftp mirror: err = %v, want a rejection naming the key", name, err) + } + } +} + func TestLoadRejectsHashAlgoOnNonSFTP(t *testing.T) { _, err := Load(writeConfig(t, ` [destinations.bucket] @@ -111,6 +132,7 @@ type = "sftp" host = "host.example" user = "u" root = "/data" +layout = "content-addressed" checkers = 4 `)) if err != nil { @@ -135,10 +157,11 @@ func TestLoadRejectsBadCheckers(t *testing.T) { t.Run(c.name, func(t *testing.T) { _, err := Load(writeConfig(t, ` [destinations.archive] -type = "sftp" -host = "host.example" -user = "u" -root = "/data" +type = "sftp" +host = "host.example" +user = "u" +root = "/data" +layout = "content-addressed" `+c.body+"\n")) if err == nil || !strings.Contains(err.Error(), "checkers") { t.Fatalf("err = %v, want checkers rejection", err) diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md index 7070445..dcc88c1 100644 --- a/docs/src/content/docs/reference/configuration.md +++ b/docs/src/content/docs/reference/configuration.md @@ -134,8 +134,8 @@ For `layout = "content-addressed"` or `layout = "packed"` destinations. See | Key | Applies to | Default | Meaning | |---|---|---|---| -| `hash_algo` | sftp | `sha256` | Which server-side hash the [scan-back fingerprint](/squirrel/guides/verification/) uses. | -| `checkers` | rclone remotes | rclone default | Cap rclone's concurrent checkers (`--checkers`). | +| `hash_algo` | sftp, except a mirror without crypt | `sha256` | Which server-side hash the [scan-back fingerprint](/squirrel/guides/verification/) uses. A plain sftp mirror runs no command on the server, so the key is rejected there. | +| `checkers` | rclone remotes | rclone default | Cap rclone's concurrent checkers (`--checkers`). Rejected on a `local` mirror and on an `sftp` mirror without crypt: squirrel writes those itself, without rclone. | | `force_path_style` | s3 | `false` | Path-style bucket addressing for squirrel's own ETag reader (not the rclone transport). | | `pack_threshold` | packed | — | Files smaller than this are packed; at/above land as objects (e.g. `1MiB`). | | `pack_size` | packed | — | Target size of one pack before it is closed (e.g. `512MiB`). | From 1fc1f6ce823156776ce2f68be8ddbba1d808ac54 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 01:03:55 +0200 Subject: [PATCH 13/61] sync: add the sftp transport Built on x/crypto/ssh and pkg/sftp. It logs in with a key file, a password, or ssh-agent when neither is set, and accepts only a host key known_hosts pins; an unknown host is refused with its fingerprint and the line that would trust it. The handshake asks for the key types known_hosts pins, so a server offering another type first is still checked. Put writes concurrently and flushes through fsync@openssh.com where the server offers it. Put and Rename Lstat their target first: pkg/sftp's own server replaces on rename, and protocol version 3 cannot say that an exclusive create failed because the name exists. The name checks the local transport does move into transport.go and both implementations share them. The contract suite gains a large-body case and runs against an in-process pkg/sftp server and against rclone serve sftp, the testbed's server. --- design/native-mirror.md | 18 +- go.mod | 10 +- go.sum | 36 +-- sync/transport.go | 59 +++++ sync/transport_contract_test.go | 16 ++ sync/transport_local.go | 50 +---- sync/transport_sftp.go | 202 +++++++++++++++++ sync/transport_sftp_dial.go | 166 ++++++++++++++ sync/transport_sftp_hostkey.go | 120 ++++++++++ sync/transport_sftp_test.go | 373 ++++++++++++++++++++++++++++++++ 10 files changed, 982 insertions(+), 68 deletions(-) create mode 100644 sync/transport_sftp.go create mode 100644 sync/transport_sftp_dial.go create mode 100644 sync/transport_sftp_hostkey.go create mode 100644 sync/transport_sftp_test.go diff --git a/design/native-mirror.md b/design/native-mirror.md index 0339b5b..a0c49eb 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -283,15 +283,25 @@ type transport interface { ### sftp implementation - Built on `golang.org/x/crypto/ssh`, already a dependency, and - `github.com/pkg/sftp`, which is new. + `github.com/pkg/sftp`, which is new (`sync/transport_sftp.go`). - `Put` opens with `SSH_FXF_CREAT|SSH_FXF_EXCL` and uses concurrent writes, so high latency doesn't cap throughput. It syncs through `fsync@openssh.com` when the server offers it. - **mtime is whole seconds.** Protocol version 3 carries only seconds, so the records store the mtime the server reports. -- **`Rename` checks first.** The protocol's rename fails when the target - exists. Servers don't all honour that, so the transport also runs `Lstat` - first. The contract suite pins the behaviour against the testbed's server. +- **`Put` and `Rename` check first.** The protocol's rename fails when the + target exists, but servers don't all honour that: `pkg/sftp`'s own server + replaces it (`TestSFTPServerRenameReplaces`). Version 3 also has no + "already exists" status, so an exclusive create that fails can't say why. So + both calls run `Lstat` on their target first and fail with `fs.ErrExist`, + and every call checks its name's parent chain for symlinks, as the local + transport does. The contract suite passes against an in-process `pkg/sftp` + server and against `rclone serve sftp`, the testbed's server. That server + hides symlinks, so the symlink cases skip there. +- **Host keys follow known_hosts.** The handshake asks the server for the key + types known_hosts pins for it (or `host_key_algorithms` when set), so a + server that also offers another key type is still checked against the + pinned one (`sync/transport_sftp_hostkey.go`). - **One optional server-side command: a hash.** Content-addressed and packed artifacts get their fingerprint confirmed, and re-confirmed, by a hash command run on the server. That is `sha256sum` by default, chosen by diff --git a/go.mod b/go.mod index b70d2f3..3e4f075 100644 --- a/go.mod +++ b/go.mod @@ -12,12 +12,13 @@ require ( github.com/mattn/go-isatty v0.0.22 github.com/minio/minio-go/v7 v7.2.1 github.com/pelletier/go-toml/v2 v2.3.1 + github.com/pkg/sftp v1.13.11 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 github.com/wailsapp/wails/v3 v3.0.0-alpha.95 github.com/zeebo/blake3 v0.2.4 - golang.org/x/crypto v0.51.0 - golang.org/x/sys v0.44.0 + golang.org/x/crypto v0.54.0 + golang.org/x/sys v0.47.0 modernc.org/sqlite v1.50.1 ) @@ -54,6 +55,7 @@ require ( github.com/kevinburke/ssh_config v1.4.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/klauspost/crc32 v1.3.0 // indirect + github.com/kr/fs v0.1.0 // indirect github.com/leaanthony/go-ansi-parser v1.6.1 // indirect github.com/leaanthony/u v1.1.1 // indirect github.com/lmittmann/tint v1.1.2 // indirect @@ -82,8 +84,8 @@ require ( github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/zeebo/xxh3 v1.1.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/net v0.53.0 // indirect - golang.org/x/text v0.37.0 // indirect + golang.org/x/net v0.56.0 // indirect + golang.org/x/text v0.40.0 // indirect gopkg.in/ini.v1 v1.67.2 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect modernc.org/libc v1.72.3 // indirect diff --git a/go.sum b/go.sum index 5a85c44..e15354e 100644 --- a/go.sum +++ b/go.sum @@ -102,6 +102,8 @@ github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzh github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM= github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw= +github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -154,6 +156,8 @@ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmd github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/sftp v1.13.11 h1:0N92SLTB8JqASJB14ZLHHzFnBV8mG9zw4K7jghEFWuE= +github.com/pkg/sftp v1.13.11/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= @@ -210,17 +214,17 @@ github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI= -golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8= +golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= +golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= -golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM= -golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA= -golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= -golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= -golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -230,17 +234,17 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ= -golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4= -golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= -golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c= -golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= diff --git a/sync/transport.go b/sync/transport.go index 24e105e..032ff39 100644 --- a/sync/transport.go +++ b/sync/transport.go @@ -3,8 +3,11 @@ package sync import ( "context" "errors" + "fmt" "io" "io/fs" + "path" + "strings" "time" ) @@ -75,6 +78,62 @@ var errParentNotDir = errors.New("a parent along the path is not a directory") // inside the root. var errInvalidName = errors.New("invalid destination name") +// errUnexpectedKind refuses an operation on a name that is not the kind of +// entry the operation reads. +var errUnexpectedKind = errors.New("unexpected kind of entry") + +// validName reports whether name is a clean slash-separated path strictly +// below a root. +func validName(name string) bool { + return fs.ValidPath(name) && name != "." +} + +// checkParents refuses a name whose parent chain crosses a symlink or +// something that is not a directory. lstat describes one root-relative +// name without following it. A parent that does not exist ends the check: +// nothing below it exists either. +func checkParents(name string, lstat func(string) (fs.FileInfo, error)) error { + dir := path.Dir(name) + if dir == "." { + return nil + } + parts := strings.Split(dir, "/") + for i := range parts { + p := strings.Join(parts[:i+1], "/") + fi, err := lstat(p) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return err + } + switch kindOf(fi.Mode()) { + case kindDir: + case kindSymlink: + return fmt.Errorf("%s: %w", p, errSymlinkInPath) + default: + return fmt.Errorf("%s: %w", p, errParentNotDir) + } + } + return nil +} + +// requireKind refuses name unless it exists and is of kind want. +func requireKind(name string, want entryKind, lstat func(string) (fs.FileInfo, error)) error { + fi, err := lstat(name) + if err != nil { + return err + } + if kindOf(fi.Mode()) != want { + return fmt.Errorf("%s: %w", name, errUnexpectedKind) + } + return nil +} + +func entryOf(fi fs.FileInfo) entry { + return entry{name: fi.Name(), kind: kindOf(fi.Mode()), size: fi.Size(), mtime: fi.ModTime()} +} + // ctxReader stops a streaming copy once its context is done. type ctxReader struct { ctx context.Context diff --git a/sync/transport_contract_test.go b/sync/transport_contract_test.go index 7ca19ac..2bf9bfb 100644 --- a/sync/transport_contract_test.go +++ b/sync/transport_contract_test.go @@ -29,6 +29,7 @@ func runTransportContract(t *testing.T, open transportHarness) { run func(t *testing.T, tr transport, plant func(target, name string)) }{ {"PutThenStatListGet", contractPutThenStatListGet}, + {"PutLandsALargeBodyIntact", contractPutLarge}, {"PutNeverReplaces", contractPutNeverReplaces}, {"StatAbsent", contractStatAbsent}, {"RenameMovesAndCreatesParents", contractRenameMoves}, @@ -118,6 +119,21 @@ func contractPutThenStatListGet(t *testing.T, tr transport, _ func(string, strin } } +// contractPutLarge lands a body spanning many write requests, which an +// sftp transport sends concurrently and a server may apply out of order. +func contractPutLarge(t *testing.T, tr transport, _ func(string, string)) { + body := make([]byte, 5<<20+123) + for i := range body { + body[i] = byte(i * 7 % 251) + } + if err := tr.Put(context.Background(), "big", bytes.NewReader(body), contractMtime); err != nil { + t.Fatalf("Put: %v", err) + } + if got := mustRead(t, tr, "big"); got != string(body) { + t.Fatalf("read back %d bytes, want the %d written", len(got), len(body)) + } +} + func contractPutNeverReplaces(t *testing.T, tr transport, _ func(string, string)) { mustPut(t, tr, "x", "first") err := tr.Put(context.Background(), "x", strings.NewReader("second"), contractMtime) diff --git a/sync/transport_local.go b/sync/transport_local.go index 364aa7a..80e39b3 100644 --- a/sync/transport_local.go +++ b/sync/transport_local.go @@ -49,7 +49,7 @@ func (t *localTransport) List(_ context.Context, dir string) ([]entry, error) { if err := t.checkName(dir); err != nil { return nil, err } - if err := t.requireKind(dir, kindDir); err != nil { + if err := requireKind(dir, kindDir, t.lstat); err != nil { return nil, err } } @@ -77,7 +77,7 @@ func (t *localTransport) Get(_ context.Context, name string) (io.ReadCloser, err if err := t.checkName(name); err != nil { return nil, err } - if err := t.requireKind(name, kindFile); err != nil { + if err := requireKind(name, kindFile, t.lstat); err != nil { return nil, err } return t.root.Open(filepath.FromSlash(name)) @@ -150,44 +150,14 @@ func (t *localTransport) Remove(_ context.Context, name string) error { // checkName refuses a name that is not a clean path below the root, or // whose parent chain crosses a symlink or a non-directory. func (t *localTransport) checkName(name string) error { - if !fs.ValidPath(name) || name == "." || (runtime.GOOS == "windows" && strings.ContainsRune(name, '\\')) { + if !validName(name) || (runtime.GOOS == "windows" && strings.ContainsRune(name, '\\')) { return fmt.Errorf("%w: %q", errInvalidName, name) } - dir := path.Dir(name) - if dir == "." { - return nil - } - parts := strings.Split(dir, "/") - for i := range parts { - p := strings.Join(parts[:i+1], "/") - fi, err := t.root.Lstat(filepath.FromSlash(p)) - if errors.Is(err, fs.ErrNotExist) { - return nil - } - if err != nil { - return err - } - switch kindOf(fi.Mode()) { - case kindDir: - case kindSymlink: - return fmt.Errorf("%s: %w", p, errSymlinkInPath) - default: - return fmt.Errorf("%s: %w", p, errParentNotDir) - } - } - return nil + return checkParents(name, t.lstat) } -// requireKind refuses name unless it exists and is of kind want. -func (t *localTransport) requireKind(name string, want entryKind) error { - fi, err := t.root.Lstat(filepath.FromSlash(name)) - if err != nil { - return err - } - if kindOf(fi.Mode()) != want { - return fmt.Errorf("%s: %w", name, errUnexpectedKind) - } - return nil +func (t *localTransport) lstat(name string) (fs.FileInfo, error) { + return t.root.Lstat(filepath.FromSlash(name)) } func (t *localTransport) mkdirParents(name string) error { @@ -215,14 +185,6 @@ func (t *localTransport) syncDir(dir string) error { return nil } -// errUnexpectedKind refuses an operation on a name that is not the kind of -// entry the operation reads. -var errUnexpectedKind = errors.New("unexpected kind of entry") - -func entryOf(fi fs.FileInfo) entry { - return entry{name: fi.Name(), kind: kindOf(fi.Mode()), size: fi.Size(), mtime: fi.ModTime()} -} - // renameCheckThenMove is the rename for a filesystem without a no-replace // rename, exFAT for one: an Lstat, then a plain rename. A writer outside // squirrel could slip a file in between the two; squirrel cannot collide diff --git a/sync/transport_sftp.go b/sync/transport_sftp.go new file mode 100644 index 0000000..072faf9 --- /dev/null +++ b/sync/transport_sftp.go @@ -0,0 +1,202 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +// sftpTransport is the transport onto a directory of an sftp server. The +// server resolves symlinks itself, so every operation checks its name's +// parent chain with Lstat and refuses a symlink anywhere along it. The +// protocol's own create-exclusive and rename are not trusted to refuse an +// existing name on every server, so Put and Rename Lstat their target +// first. +type sftpTransport struct { + conn *ssh.Client + client *sftp.Client + root string // the destination root on the server + // fsync is whether the server offers fsync@openssh.com, which Put + // uses to flush a file to stable storage before it returns. + fsync bool +} + +func (t *sftpTransport) Close() error { + err := t.client.Close() + if cerr := t.conn.Close(); err == nil { + err = cerr + } + return err +} + +func (t *sftpTransport) Stat(_ context.Context, name string) (entry, error) { + if err := t.checkName(name); err != nil { + return entry{}, err + } + fi, err := t.lstat(name) + if err != nil { + return entry{}, err + } + return entryOf(fi), nil +} + +func (t *sftpTransport) List(_ context.Context, dir string) ([]entry, error) { + full := t.root + if dir != "." { + if err := t.checkName(dir); err != nil { + return nil, err + } + if err := requireKind(dir, kindDir, t.lstat); err != nil { + return nil, err + } + full = t.full(dir) + } + fis, err := t.client.ReadDir(full) + if err != nil { + return nil, fmt.Errorf("list %s: %w", dir, err) + } + out := make([]entry, 0, len(fis)) + for _, fi := range fis { + if fi.Name() == "." || fi.Name() == ".." { + continue + } + out = append(out, entryOf(fi)) + } + return out, nil +} + +func (t *sftpTransport) Get(_ context.Context, name string) (io.ReadCloser, error) { + if err := t.checkName(name); err != nil { + return nil, err + } + if err := requireKind(name, kindFile, t.lstat); err != nil { + return nil, err + } + return t.client.Open(t.full(name)) +} + +func (t *sftpTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if err := t.checkName(name); err != nil { + return err + } + if err := t.refuseExisting("put", name); err != nil { + return err + } + if err := t.mkdirParents(name); err != nil { + return err + } + f, err := t.client.OpenFile(t.full(name), os.O_WRONLY|os.O_CREATE|os.O_EXCL) + if err != nil { + if exists := t.refuseExisting("put", name); exists != nil { + return exists + } + return err + } + if err := t.fill(ctx, f, name, r, mtime); err != nil { + _ = f.Close() + return err + } + if err := f.Close(); err != nil { + return fmt.Errorf("close %s: %w", name, err) + } + return nil +} + +// fill streams r into the freshly created f with concurrent writes, so a +// high-latency link does not cap throughput, stamps mtime, and flushes +// the file where the server offers it. +func (t *sftpTransport) fill(ctx context.Context, f *sftp.File, name string, r io.Reader, mtime time.Time) error { + if _, err := f.ReadFromWithConcurrency(ctxReader{ctx: ctx, r: r}, 0); err != nil { + return fmt.Errorf("write %s: %w", name, err) + } + if err := t.client.Chtimes(t.full(name), mtime, mtime); err != nil { + return fmt.Errorf("set mtime of %s: %w", name, err) + } + if !t.fsync { + return nil + } + if err := f.Sync(); err != nil { + return fmt.Errorf("sync %s: %w", name, err) + } + return nil +} + +func (t *sftpTransport) Rename(_ context.Context, from, to string) error { + if err := t.checkName(from); err != nil { + return err + } + if err := t.checkName(to); err != nil { + return err + } + if _, err := t.lstat(from); err != nil { + return err + } + if err := t.mkdirParents(to); err != nil { + return err + } + if err := t.refuseExisting("rename", to); err != nil { + return err + } + if err := t.client.Rename(t.full(from), t.full(to)); err != nil { + return &os.LinkError{Op: "rename", Old: from, New: to, Err: err} + } + return nil +} + +func (t *sftpTransport) Remove(_ context.Context, name string) error { + if err := t.checkName(name); err != nil { + return err + } + fi, err := t.lstat(name) + if err != nil { + return err + } + if fi.IsDir() { + return t.client.RemoveDirectory(t.full(name)) + } + return t.client.Remove(t.full(name)) +} + +// refuseExisting fails with fs.ErrExist when name is present. +func (t *sftpTransport) refuseExisting(op, name string) error { + _, err := t.lstat(name) + if err == nil { + return &fs.PathError{Op: op, Path: name, Err: fs.ErrExist} + } + if errors.Is(err, fs.ErrNotExist) { + return nil + } + return err +} + +func (t *sftpTransport) checkName(name string) error { + if !validName(name) { + return fmt.Errorf("%w: %q", errInvalidName, name) + } + return checkParents(name, t.lstat) +} + +func (t *sftpTransport) lstat(name string) (fs.FileInfo, error) { + return t.client.Lstat(t.full(name)) +} + +func (t *sftpTransport) full(name string) string { return path.Join(t.root, name) } + +func (t *sftpTransport) mkdirParents(name string) error { + dir := path.Dir(name) + if dir == "." { + return nil + } + if err := t.client.MkdirAll(t.full(dir)); err != nil { + return fmt.Errorf("create %s: %w", dir, err) + } + return nil +} diff --git a/sync/transport_sftp_dial.go b/sync/transport_sftp_dial.go new file mode 100644 index 0000000..c7b3eb0 --- /dev/null +++ b/sync/transport_sftp_dial.go @@ -0,0 +1,166 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "strings" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" + + "github.com/mbertschler/squirrel/config" +) + +// sftpConnectTimeout bounds the TCP connect and the ssh handshake of one +// sftp session. +const sftpConnectTimeout = time.Minute + +// fsyncExtension is the OpenSSH extension that flushes an open file to +// stable storage. +const fsyncExtension = "fsync@openssh.com" + +// dialSFTP opens an sftp session to dest's server and returns the +// transport onto dest's root. The server's host key must be one +// known_hosts pins for it. +func dialSFTP(ctx context.Context, dest *config.Destination) (*sftpTransport, error) { + keys, err := loadHostKeys(dest) + if err != nil { + return nil, fmt.Errorf("destination %q: %w", dest.Name, err) + } + auth, release, err := sftpAuth(dest) + if err != nil { + return nil, fmt.Errorf("destination %q: %w", dest.Name, err) + } + cfg := &ssh.ClientConfig{User: dest.Params["user"], Auth: auth, HostKeyCallback: keys.check} + if algos := dest.Params["host_key_algorithms"]; algos != "" { + cfg.HostKeyAlgorithms = strings.Fields(algos) + } + conn, err := dialSSH(ctx, sftpAddress(dest), cfg, keys) + release() + if err != nil { + return nil, fmt.Errorf("destination %q: %w", dest.Name, err) + } + client, err := sftp.NewClient(conn, sftp.UseConcurrentWrites(true)) + if err != nil { + _ = conn.Close() + return nil, fmt.Errorf("destination %q: start sftp: %w", dest.Name, err) + } + data, ok := client.HasExtension(fsyncExtension) + return &sftpTransport{conn: conn, client: client, root: dest.Root, fsync: ok && data == "1"}, nil +} + +// sftpAddress is the host:port dest's server listens on. +func sftpAddress(dest *config.Destination) string { + port := dest.Params["port"] + if port == "" { + port = "22" + } + return net.JoinHostPort(dest.Params["host"], port) +} + +// dialSSH connects to addr and completes the ssh handshake within +// sftpConnectTimeout. Unless the config pins them, the host key +// algorithms follow the keys known_hosts pins, settled once the peer's +// address is known, since known_hosts may pin keys by address. +func dialSSH(ctx context.Context, addr string, cfg *ssh.ClientConfig, keys hostKeys) (*ssh.Client, error) { + ctx, cancel := context.WithTimeout(ctx, sftpConnectTimeout) + defer cancel() + var d net.Dialer + tcp, err := d.DialContext(ctx, "tcp", addr) + if err != nil { + return nil, fmt.Errorf("connect to %s: %w", addr, err) + } + if cfg.HostKeyAlgorithms == nil { + cfg.HostKeyAlgorithms = keys.algorithms(addr, tcp.RemoteAddr()) + } + deadline, _ := ctx.Deadline() + _ = tcp.SetDeadline(deadline) + c, chans, reqs, err := ssh.NewClientConn(tcp, addr, cfg) + if err != nil { + _ = tcp.Close() + return nil, fmt.Errorf("ssh to %s: %w", addr, err) + } + _ = tcp.SetDeadline(time.Time{}) + return ssh.NewClient(c, chans, reqs), nil +} + +// sftpAuth is how squirrel logs in: with the key file and the password +// where configured, else with the keys ssh-agent holds. +func sftpAuth(dest *config.Destination) ([]ssh.AuthMethod, func(), error) { + var auth []ssh.AuthMethod + if file := dest.Params["key_file"]; file != "" { + signer, err := readPrivateKey(file) + if err != nil { + return nil, nil, err + } + auth = append(auth, ssh.PublicKeys(signer)) + } + if pw := dest.Params["password"]; pw != "" { + auth = append(auth, ssh.Password(pw), ssh.KeyboardInteractive(answerWith(pw))) + } + if len(auth) > 0 { + return auth, func() {}, nil + } + return agentAuth() +} + +func readPrivateKey(file string) (ssh.Signer, error) { + b, err := os.ReadFile(expandHome(file)) + if err != nil { + return nil, fmt.Errorf("read key_file: %w", err) + } + signer, err := ssh.ParsePrivateKey(b) + if _, ok := errors.AsType[*ssh.PassphraseMissingError](err); ok { + return nil, fmt.Errorf("key_file %s is protected by a passphrase, which squirrel cannot enter unattended: load it into ssh-agent and leave key_file and password unset", file) + } + if err != nil { + return nil, fmt.Errorf("parse key_file %s: %w", file, err) + } + return signer, nil +} + +// answerWith answers every keyboard-interactive prompt with the password, +// for servers that ask for it that way. +func answerWith(pw string) ssh.KeyboardInteractiveChallenge { + return func(_, _ string, questions []string, _ []bool) ([]string, error) { + answers := make([]string, len(questions)) + for i := range answers { + answers[i] = pw + } + return answers, nil + } +} + +// agentAuth offers the keys of the ssh-agent at SSH_AUTH_SOCK. The agent +// signs during the handshake, so its connection stays open until release. +func agentAuth() ([]ssh.AuthMethod, func(), error) { + sock := os.Getenv("SSH_AUTH_SOCK") + if sock == "" { + return nil, nil, errors.New("no password or key_file is set, and there is no ssh-agent to log in with (SSH_AUTH_SOCK is unset)") + } + c, err := net.Dial("unix", sock) + if err != nil { + return nil, nil, fmt.Errorf("no password or key_file is set, and the ssh-agent at %s is unreachable: %w", sock, err) + } + auth := []ssh.AuthMethod{ssh.PublicKeysCallback(agent.NewClient(c).Signers)} + return auth, func() { _ = c.Close() }, nil +} + +// expandHome expands a leading ~/ to the user's home directory. +func expandHome(p string) string { + rest, ok := strings.CutPrefix(p, "~/") + if !ok { + return p + } + home, err := os.UserHomeDir() + if err != nil { + return p + } + return filepath.Join(home, rest) +} diff --git a/sync/transport_sftp_hostkey.go b/sync/transport_sftp_hostkey.go new file mode 100644 index 0000000..13031b0 --- /dev/null +++ b/sync/transport_sftp_hostkey.go @@ -0,0 +1,120 @@ +package sync + +import ( + "crypto/ed25519" + "crypto/rand" + "errors" + "fmt" + "io/fs" + "net" + "os" + "path/filepath" + + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/knownhosts" + + "github.com/mbertschler/squirrel/config" +) + +// errUnknownHostKey refuses an sftp server whose host key known_hosts does +// not pin. +var errUnknownHostKey = errors.New("the sftp server's host key is not in known_hosts") + +// errHostKeyChanged refuses an sftp server whose host key differs from +// the one known_hosts pins for it. +var errHostKeyChanged = errors.New("the sftp server's host key differs from the one known_hosts pins") + +// knownHostsFile is where dest's pinned host keys live: known_hosts_file, +// else ~/.ssh/known_hosts. +func knownHostsFile(dest *config.Destination) (string, error) { + if f := dest.Params["known_hosts_file"]; f != "" { + return expandHome(f), nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("find ~/.ssh/known_hosts (set known_hosts_file instead): %w", err) + } + return filepath.Join(home, ".ssh", "known_hosts"), nil +} + +// hostKeys is the host key check for one destination: the keys its +// known_hosts file pins. +type hostKeys struct { + file string + // known is knownhosts' own check, which reports an unknown host as a + // KeyError listing no key. + known ssh.HostKeyCallback +} + +// loadHostKeys reads dest's known_hosts. A missing file pins nothing, so +// every host is unknown. +func loadHostKeys(dest *config.Destination) (hostKeys, error) { + file, err := knownHostsFile(dest) + if err != nil { + return hostKeys{}, err + } + known, err := knownhosts.New(file) + if errors.Is(err, fs.ErrNotExist) { + known = func(string, net.Addr, ssh.PublicKey) error { return &knownhosts.KeyError{} } + } else if err != nil { + return hostKeys{}, fmt.Errorf("read known_hosts %s: %w", file, err) + } + return hostKeys{file: file, known: known}, nil +} + +// check accepts only a host key known_hosts pins for the server. An +// unknown host is refused with its fingerprint and the line that would +// trust it. +func (h hostKeys) check(host string, remote net.Addr, key ssh.PublicKey) error { + err := h.known(host, remote, key) + ke, ok := errors.AsType[*knownhosts.KeyError](err) + switch { + case !ok: + return err + case len(ke.Want) == 0: + return fmt.Errorf("%w: %s presented %s key %s, and squirrel refuses hosts it does not know — if that is the server's fingerprint, trust it by adding this line to %s:\n%s", + errUnknownHostKey, host, key.Type(), ssh.FingerprintSHA256(key), h.file, knownhosts.Line([]string{knownhosts.Normalize(host)}, key)) + default: + return fmt.Errorf("%w: %s presented %s key %s, but %s pins another key for it — the server was reinstalled, or something is intercepting the connection; confirm the new key with the server's operator before replacing the entry", + errHostKeyChanged, host, key.Type(), ssh.FingerprintSHA256(key), h.file) + } +} + +// algorithms lists the host key algorithms of the keys known_hosts pins +// for host, so the handshake asks the server for a key squirrel can check +// instead of one it has never seen. It returns nil, the client's +// defaults, when known_hosts pins nothing for host. +func (h hostKeys) algorithms(host string, remote net.Addr) []string { + probe, err := probeKey() + if err != nil { + return nil + } + ke, ok := errors.AsType[*knownhosts.KeyError](h.known(host, remote, probe)) + if !ok { + return nil + } + var algos []string + for _, k := range ke.Want { + algos = append(algos, algorithmsFor(k.Key.Type())...) + } + return algos +} + +// probeKey is a fresh key no known_hosts file holds: checking it against +// a host yields the keys known_hosts pins for that host. +func probeKey() (ssh.PublicKey, error) { + pub, _, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return nil, err + } + return ssh.NewPublicKey(pub) +} + +// algorithmsFor names the signature algorithms a host key of keyType +// signs with. +func algorithmsFor(keyType string) []string { + if keyType == ssh.KeyAlgoRSA { + return []string{ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSA} + } + return []string{keyType} +} diff --git a/sync/transport_sftp_test.go b/sync/transport_sftp_test.go new file mode 100644 index 0000000..10a6e92 --- /dev/null +++ b/sync/transport_sftp_test.go @@ -0,0 +1,373 @@ +package sync + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/rsa" + "encoding/pem" + "errors" + "net" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/agent" + "golang.org/x/crypto/ssh/knownhosts" + + "github.com/mbertschler/squirrel/config" +) + +// sftpTestServer is an in-process ssh server whose sftp subsystem serves +// the real filesystem, with password "p" for user "u" and one client key +// allowed. +type sftpTestServer struct { + addr string + hostKeys []ssh.Signer + // clientKey is the private half of the one client key the server + // accepts. + clientKey ed25519.PrivateKey +} + +func newKey(t *testing.T) (ed25519.PrivateKey, ssh.Signer) { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + s, err := ssh.NewSignerFromKey(priv) + if err != nil { + t.Fatal(err) + } + return priv, s +} + +func newSigner(t *testing.T) ssh.Signer { + t.Helper() + _, s := newKey(t) + return s +} + +// startSFTPServer serves until the test ends. With no host keys given it +// presents one fresh ed25519 key. +func startSFTPServer(t *testing.T, hostKeys ...ssh.Signer) *sftpTestServer { + t.Helper() + if len(hostKeys) == 0 { + hostKeys = []ssh.Signer{newSigner(t)} + } + clientKey, clientSigner := newKey(t) + srv := &sftpTestServer{hostKeys: hostKeys, clientKey: clientKey} + cfg := &ssh.ServerConfig{ + PasswordCallback: func(c ssh.ConnMetadata, pw []byte) (*ssh.Permissions, error) { + if c.User() == "u" && string(pw) == "p" { + return nil, nil + } + return nil, errors.New("wrong password") + }, + PublicKeyCallback: func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { + if string(key.Marshal()) == string(clientSigner.PublicKey().Marshal()) { + return nil, nil + } + return nil, errors.New("unknown key") + }, + } + for _, k := range hostKeys { + cfg.AddHostKey(k) + } + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = l.Close() }) + srv.addr = l.Addr().String() + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + go serveSSH(c, cfg) + } + }() + return srv +} + +func serveSSH(c net.Conn, cfg *ssh.ServerConfig) { + defer func() { _ = c.Close() }() + _, chans, reqs, err := ssh.NewServerConn(c, cfg) + if err != nil { + return + } + go ssh.DiscardRequests(reqs) + for nc := range chans { + if nc.ChannelType() != "session" { + _ = nc.Reject(ssh.UnknownChannelType, "session only") + continue + } + ch, chReqs, err := nc.Accept() + if err != nil { + return + } + go func() { + for r := range chReqs { + ok := r.Type == "subsystem" && len(r.Payload) > 4 && string(r.Payload[4:]) == "sftp" + _ = r.Reply(ok, nil) + if ok { + go serveSFTP(ch) + } + } + }() + } +} + +func serveSFTP(ch ssh.Channel) { + defer func() { _ = ch.Close() }() + s, err := sftp.NewServer(ch) + if err != nil { + return + } + _ = s.Serve() +} + +// knownHosts writes a known_hosts file pinning keys for the server. +func (s *sftpTestServer) knownHosts(t *testing.T, keys ...ssh.PublicKey) string { + t.Helper() + var lines []string + for _, k := range keys { + lines = append(lines, knownhosts.Line([]string{knownhosts.Normalize(s.addr)}, k)) + } + p := filepath.Join(t.TempDir(), "known_hosts") + if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +// destination is an sftp destination onto root on the server, logging in +// with password "p" and pinning the server's first host key. +func (s *sftpTestServer) destination(t *testing.T, root string) *config.Destination { + t.Helper() + host, port, _ := net.SplitHostPort(s.addr) + return &config.Destination{Name: "box", Type: "sftp", Root: root, Layout: config.LayoutMirror, Params: map[string]string{ + "host": host, "port": port, "user": "u", "password": "p", + "known_hosts_file": s.knownHosts(t, s.hostKeys[0].PublicKey()), + }} +} + +func mustDialSFTP(t *testing.T, dest *config.Destination) *sftpTransport { + t.Helper() + tr, err := dialSFTP(context.Background(), dest) + if err != nil { + t.Fatalf("dialSFTP: %v", err) + } + return tr +} + +func plantSymlink(t *testing.T, dir string) func(target, name string) { + return func(target, name string) { + p := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, p); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + } +} + +func TestSFTPTransportContract(t *testing.T) { + srv := startSFTPServer(t) + runTransportContract(t, func(t *testing.T) (transport, func(target, name string)) { + dir := t.TempDir() + return mustDialSFTP(t, srv.destination(t, dir)), plantSymlink(t, dir) + }) +} + +// TestSFTPServerRenameReplaces pins why the transport checks a rename's +// target itself: the in-process server's rename replaces an existing +// name, as some real servers do. +func TestSFTPServerRenameReplaces(t *testing.T) { + srv := startSFTPServer(t) + dir := t.TempDir() + tr := mustDialSFTP(t, srv.destination(t, dir)) + t.Cleanup(func() { _ = tr.Close() }) + mustPut(t, tr, "x", "from") + mustPut(t, tr, "y", "to") + if err := tr.client.Rename(tr.full("x"), tr.full("y")); err != nil { + t.Skipf("this server refuses the replacing rename itself: %v", err) + } + if got := mustRead(t, tr, "y"); got != "from" { + t.Fatalf("y after the raw rename = %q, want from", got) + } +} + +func TestSFTPRefusesUnknownHostKey(t *testing.T) { + srv := startSFTPServer(t) + dest := srv.destination(t, t.TempDir()) + dest.Params["known_hosts_file"] = srv.knownHosts(t) + _, err := dialSFTP(context.Background(), dest) + if !errors.Is(err, errUnknownHostKey) { + t.Fatalf("dial with an empty known_hosts = %v, want errUnknownHostKey", err) + } + want := knownhosts.Line([]string{knownhosts.Normalize(srv.addr)}, srv.hostKeys[0].PublicKey()) + for _, s := range []string{ssh.FingerprintSHA256(srv.hostKeys[0].PublicKey()), want} { + if !strings.Contains(err.Error(), s) { + t.Fatalf("refusal lacks %q:\n%v", s, err) + } + } + + dest.Params["known_hosts_file"] = filepath.Join(t.TempDir(), "absent") + if _, err := dialSFTP(context.Background(), dest); !errors.Is(err, errUnknownHostKey) { + t.Fatalf("dial with no known_hosts file = %v, want errUnknownHostKey", err) + } +} + +func TestSFTPRefusesChangedHostKey(t *testing.T) { + srv := startSFTPServer(t) + dest := srv.destination(t, t.TempDir()) + dest.Params["known_hosts_file"] = srv.knownHosts(t, newSigner(t).PublicKey()) + if _, err := dialSFTP(context.Background(), dest); !errors.Is(err, errHostKeyChanged) { + t.Fatalf("dial with another pinned key = %v, want errHostKeyChanged", err) + } +} + +// TestSFTPNegotiatesThePinnedHostKeyType: a server offering an ed25519 and +// an RSA key, pinned only by its RSA key, is still accepted — the +// handshake asks for the key type known_hosts holds. +func TestSFTPNegotiatesThePinnedHostKeyType(t *testing.T) { + rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + rsaSigner, err := ssh.NewSignerFromKey(rsaKey) + if err != nil { + t.Fatal(err) + } + srv := startSFTPServer(t, newSigner(t), rsaSigner) + dest := srv.destination(t, t.TempDir()) + dest.Params["known_hosts_file"] = srv.knownHosts(t, rsaSigner.PublicKey()) + tr := mustDialSFTP(t, dest) + _ = tr.Close() +} + +func TestSFTPAuthenticatesByKeyFile(t *testing.T) { + srv := startSFTPServer(t) + dest := srv.destination(t, t.TempDir()) + delete(dest.Params, "password") + block, err := ssh.MarshalPrivateKey(srv.clientKey, "") + if err != nil { + t.Fatal(err) + } + keyFile := filepath.Join(t.TempDir(), "id") + if err := os.WriteFile(keyFile, pem.EncodeToMemory(block), 0o600); err != nil { + t.Fatal(err) + } + dest.Params["key_file"] = keyFile + tr := mustDialSFTP(t, dest) + _ = tr.Close() +} + +func TestSFTPAuthenticatesThroughAgent(t *testing.T) { + srv := startSFTPServer(t) + dest := srv.destination(t, t.TempDir()) + delete(dest.Params, "password") + keyring := agent.NewKeyring() + if err := keyring.Add(agent.AddedKey{PrivateKey: srv.clientKey}); err != nil { + t.Fatal(err) + } + sock := filepath.Join(shortTempDir(t), "agent.sock") + l, err := net.Listen("unix", sock) + if err != nil { + t.Skipf("unix sockets unavailable: %v", err) + } + t.Cleanup(func() { _ = l.Close() }) + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + go func() { _ = agent.ServeAgent(keyring, c); _ = c.Close() }() + } + }() + t.Setenv("SSH_AUTH_SOCK", sock) + tr := mustDialSFTP(t, dest) + _ = tr.Close() + + t.Setenv("SSH_AUTH_SOCK", "") + if _, err := dialSFTP(context.Background(), dest); err == nil || !strings.Contains(err.Error(), "SSH_AUTH_SOCK") { + t.Fatalf("dial with no credentials and no agent = %v, want a refusal naming SSH_AUTH_SOCK", err) + } +} + +// shortTempDir is a temporary directory with a path short enough for a +// unix socket. +func shortTempDir(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("/tmp", "sq") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + return dir +} + +// TestSFTPTransportContractAgainstRcloneServe runs the contract against +// the testbed's server, `rclone serve sftp`. That server hides symlinks, +// so the symlink cases skip there. +func TestSFTPTransportContractAgainstRcloneServe(t *testing.T) { + rclone, err := exec.LookPath("rclone") + if err != nil { + t.Skip("rclone not on PATH") + } + hostPriv, hostKey := newKey(t) + keyFile := filepath.Join(t.TempDir(), "host_key") + block, err := ssh.MarshalPrivateKey(hostPriv, "") + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(keyFile, pem.EncodeToMemory(block), 0o600); err != nil { + t.Fatal(err) + } + runTransportContract(t, func(t *testing.T) (transport, func(target, name string)) { + dir := t.TempDir() + srv := startRcloneServe(t, rclone, dir, keyFile, hostKey) + dest := srv.destination(t, "/") + return mustDialSFTP(t, dest), func(string, string) { t.Skip("rclone serve sftp hides symlinks") } + }) +} + +// startRcloneServe serves dir with `rclone serve sftp` on a free loopback +// port until the test ends. +func startRcloneServe(t *testing.T, rclone, dir, keyFile string, hostKey ssh.Signer) *sftpTestServer { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + _ = l.Close() + cmd := exec.Command(rclone, "serve", "sftp", dir, "--addr", addr, "--user", "u", "--pass", "p", + "--key", keyFile, "--config", filepath.Join(t.TempDir(), "rclone.conf")) + if err := cmd.Start(); err != nil { + t.Fatalf("start rclone serve sftp: %v", err) + } + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }) + for i := 0; ; i++ { + c, err := net.DialTimeout("tcp", addr, time.Second) + if err == nil { + _ = c.Close() + break + } + if i == 100 { + t.Fatalf("rclone serve sftp never listened on %s: %v", addr, err) + } + time.Sleep(50 * time.Millisecond) + } + return &sftpTestServer{addr: addr, hostKeys: []ssh.Signer{hostKey}} +} From 6491a0e968b2a9bd91f374dc6f2551223686e362 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 01:14:37 +0200 Subject: [PATCH 14/61] sync: push plain sftp mirrors natively MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HandlerFor sends every native mirror — local, or sftp without crypt — to the mirror handler, which opens its root through the local or the sftp transport. The marker gate runs through that transport too: an existing marker is read and checked, and a missing one is written under --init with an exclusive Put, so the filesystem-only gate goes. A local root that does not exist yet is still created under --init. The rclone marker gate now wraps ErrRefused on its refusals, as the native one does. The crash table runs on both transports, and a push to an sftp server whose host key known_hosts does not pin is recorded as a refused run. Ride-along, restore and recover still reach the destination through rclone, so Pair.DrivesRclone stays true for native mirrors until they move. --- cmd/squirrel/sync.go | 2 +- config/destinations.go | 15 +- docs/src/content/docs/guides/syncing.md | 20 +-- docs/src/content/docs/layouts/mirror.md | 27 ++-- docs/src/content/docs/reference/cli.md | 2 +- .../content/docs/reference/configuration.md | 23 +++- .../content/docs/reference/on-disk-layout.md | 2 +- sync/handler.go | 12 +- sync/handler_test.go | 20 ++- sync/mirror.go | 14 +- sync/mirror_marker.go | 102 ++++++++++++++ sync/mirror_reconcile.go | 2 +- sync/mirror_sftp_test.go | 79 +++++++++++ sync/mirror_test.go | 129 ++++++++++++------ sync/mirror_write.go | 2 +- sync/sync.go | 71 ++-------- 16 files changed, 371 insertions(+), 151 deletions(-) create mode 100644 sync/mirror_marker.go create mode 100644 sync/mirror_sftp_test.go diff --git a/cmd/squirrel/sync.go b/cmd/squirrel/sync.go index b309f1e..7454c73 100644 --- a/cmd/squirrel/sync.go +++ b/cmd/squirrel/sync.go @@ -41,7 +41,7 @@ func newSyncCmd() *cobra.Command { }, } cmd.Flags().StringVar(&to, "to", "", "limit to this destination name (default: every destination declared on the volume)") - cmd.Flags().BoolVar(&shallow, "shallow", false, "skip the checksum comparison on a remote mirror; trust rclone's default size+mtime comparison (refused on a local mirror)") + cmd.Flags().BoolVar(&shallow, "shallow", false, "skip the checksum comparison on an rclone mirror; trust rclone's default size+mtime comparison (refused on a native mirror: local, or sftp without crypt)") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "preview what a push would transfer without transferring; no runs row is written") cmd.Flags().BoolVar(&initDst, "init", false, "authorise first-use destination bootstrap: write a .squirrel-volume marker, or create a kopia repository when connect finds none (refused without --init so a typo or outage can't mint a fresh empty target)") cmd.Flags().BoolVarP(&progress, "progress", "P", false, "show live transfer progress (auto-enabled on a terminal; use --progress=false to force off)") diff --git a/config/destinations.go b/config/destinations.go index 906f62a..063132d 100644 --- a/config/destinations.go +++ b/config/destinations.go @@ -841,7 +841,7 @@ func (d *Destination) NativeMirror() bool { } func nativeMirror(typ, layout string, crypt bool) bool { - return layout == LayoutMirror && !crypt && (typ == "local" || typ == "sftp") + return !layoutHidesArtifactNames(layout) && !crypt && (typ == "local" || typ == "sftp") } // HidesArtifactNames reports whether this destination names its content @@ -866,10 +866,11 @@ func layoutHidesArtifactNames(layout string) bool { // reason names the structural gap for the caller's message; it is empty // when capable. // -// The structurally-incapable shape is a mirror. A native local mirror hashes -// each file as it sends it but reads nothing back, so it advances with -// presence+size and nothing upgrades it. An rclone mirror, plain or crypt, -// compares source against destination by rclone's --checksum — under +// The structurally-incapable shape is a mirror. A native mirror (local, or +// sftp without crypt) hashes each file as it sends it but reads nothing +// back, so it advances with presence+size and nothing upgrades it. An +// rclone mirror compares source against destination by rclone's +// --checksum — under // a hash rclone picks, unrelated to the index's BLAKE3 — or, behind a crypt // overlay, by size+mtime alone (sync.EffectiveShallow); and the mirror // layout records no scan-back fingerprint that a later `squirrel verify` @@ -885,8 +886,8 @@ func (d *Destination) CanEverGateOffload() (bool, string) { switch { case d.Layout == LayoutContentAddressed || d.Layout == LayoutPacked: return true, "" - case d.Type == "local": - return false, "local mirror destination: a push hashes each file as it sends it but reads nothing back from the disk, so its evidence stays presence+size, which is not content-verified" + case d.NativeMirror(): + return false, fmt.Sprintf("%s mirror destination: a push hashes each file as it sends it but reads nothing back, so its evidence stays presence+size, which is not content-verified", d.Type) } return false, "mirror destination: a sync compares it with the source by rclone's checksum or by size+mtime, never against the index's BLAKE3, and the mirror layout records no scan-back fingerprint to upgrade" } diff --git a/docs/src/content/docs/guides/syncing.md b/docs/src/content/docs/guides/syncing.md index 32e60ec..be63e22 100644 --- a/docs/src/content/docs/guides/syncing.md +++ b/docs/src/content/docs/guides/syncing.md @@ -22,7 +22,7 @@ with BLAKE3 as it streams out, confirms each written path's size and mtime, and records the run with the `presence+size` method (see [Mirror](/squirrel/layouts/mirror/)). -Sync compares every file with its copy on a remote mirror destination by +Sync compares every file with its copy on an rclone mirror destination by checksum (rclone's `--checksum`), under the first hash both ends support — MD5 on S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an error, so the runs row is **not** marked success. The run is @@ -32,9 +32,10 @@ The offload gate accepts neither method, so a mirror cannot back an offload. Peer syncs are different: both ends hash every byte with BLAKE3 (see [Peer sync](/squirrel/guides/peer-sync/)). -Use `--shallow` to fall back to rclone's default size+mtime comparison on a -remote mirror if you want speed over integrity for a big initial push. A local -mirror refuses it: there is no comparison to switch off. Encrypted +Use `--shallow` to fall back to rclone's default size+mtime comparison on an +rclone mirror if you want speed over integrity for a big initial push. A +[native mirror](/squirrel/layouts/mirror/#how-a-mirror-is-written) (`local`, or +`sftp` without crypt) refuses it: there is no comparison to switch off. Encrypted ([`crypt`](/squirrel/layouts/encrypted/)) destinations always use the size+mtime comparison, and content-addressed/packed destinations use presence+size plus the [scan-back fingerprint](/squirrel/guides/verification/). @@ -46,7 +47,7 @@ Sync never deletes at a destination: files removed locally remain there. | Flag | Default | Meaning | |---|---|---| | `--to ` | all | Limit to this destination name. | -| `--shallow` | off | Skip the checksum comparison on a remote mirror; trust rclone's size+mtime comparison. Refused on a local mirror. | +| `--shallow` | off | Skip the checksum comparison on an rclone mirror; trust rclone's size+mtime comparison. Refused on a native mirror (`local`, or `sftp` without crypt). | | `--dry-run` | off | Preview what a push would transfer without transferring; no runs row is written. | | `--init` | off | Authorise first-use destination bootstrap (see below). | | `--progress`, `-P` | auto on a TTY | Show a live transfer progress line (files, bytes, rate, ETA). | @@ -63,10 +64,11 @@ squirrel sync pictures --to mirror # every time after `--init` authorises the one-time first-use setup, by destination type: -- **`local` and remote rclone** (`sftp`, `s3`, `b2`, `gcs`) — write a - `.squirrel-volume` marker under the destination's volume directory (on the - filesystem for local, over rclone through the same overlay the transfer uses - for remotes). Every later sync **requires** that marker and refuses if it is +- **`local`, `sftp`, `s3`, `b2`, `gcs`** — write a `.squirrel-volume` marker + under the destination's volume directory, through the same path the transfer + takes: squirrel's own transport on a native mirror, rclone and its overlay + everywhere else. On a `local` destination whose root does not exist yet, + `--init` also creates the root. Every later sync **requires** that marker and refuses if it is missing (a missing marker after the fact almost always means the root is wrong — an unmounted disk, a typo, or an unreachable remote). A marker that names a *different* volume is always refused, with or without `--init`. This holds diff --git a/docs/src/content/docs/layouts/mirror.md b/docs/src/content/docs/layouts/mirror.md index 0336389..dfdfc60 100644 --- a/docs/src/content/docs/layouts/mirror.md +++ b/docs/src/content/docs/layouts/mirror.md @@ -12,9 +12,9 @@ destination without a `layout` key. pictures/ 2024/cat.jpg .squirrel-history/run-7/2024/cat.jpg # prior content of cat.jpg - .squirrel-index/run-12 # receipt: what run 12 changed (local disks) + .squirrel-index/run-12 # receipt: what run 12 changed (native mirrors) .squirrel-index/index-20260604T120000.000Z-run-12.db # global index snapshot (ride-along) - .squirrel-staging/ # in-flight writes (local disks) + .squirrel-staging/ # in-flight writes (native mirrors) docs/ invoice.pdf .squirrel-history/run-9/invoice.pdf @@ -22,7 +22,9 @@ destination without a `layout` key. ## How a mirror is written -On a `local` destination squirrel writes the mirror itself. A push plans from +On a `local` destination, and on an `sftp` destination without +[crypt](/squirrel/layouts/encrypted/), squirrel writes the mirror itself: a +*native* mirror. A push plans from the index: it sends the changes recorded since the destination's last confirmed run, not what a fresh walk of the disk finds. For each changed path it: @@ -37,10 +39,13 @@ push leaves a **receipt** at `.squirrel-index/run-`: the run's changes in th [manifest segment format](/squirrel/reference/formats/), so the mirror can be checked without the index. A push that finds no receipt for the last success it recorded refuses, unless the root is empty and squirrel holds no records for it. -So a local mirror starts on a fresh or emptied root: squirrel does not adopt a -tree some other tool wrote. +So a native mirror starts on a fresh or emptied root: squirrel does not adopt a +tree some other tool wrote, rclone included. -Mirrors on remote destinations (`sftp`, `s3`, `b2`, `gcs`) are written by rclone, +On sftp, squirrel checks the server's host key against `known_hosts` and refuses +a server it does not know (see [sftp keys](/squirrel/reference/configuration/#sftp)). + +Encrypted mirrors, and mirrors on `s3`, `b2` and `gcs`, are written by rclone, which compares both trees and moves overwritten files into its `--backup-dir`. ## Append-only history @@ -48,7 +53,7 @@ which compares both trees and moves overwritten files into its `--backup-dir`. `.squirrel-history/run-/` holds the prior bytes of every file a sync run replaced. They are moved there first, never deleted. -- On a local mirror, anything found at a path squirrel is about to write moves +- On a native mirror, anything found at a path squirrel is about to write moves there, including bytes squirrel did not write. The run names each one in a warning and in its audit trail. - It is **filtered out** of all subsequent comparisons, so it does not grow @@ -61,13 +66,13 @@ Files removed locally remain at the destination. ## Verification -A local mirror push hashes every file with BLAKE3 as it streams out and +A native mirror push hashes every file with BLAKE3 as it streams out and confirms each written path's size and mtime. Nothing reads the landed bytes back yet, so the run advances the destination's durability evidence under the -`presence+size` method. `--shallow` is refused on a local mirror: there is no +`presence+size` method. `--shallow` is refused on a native mirror: there is no comparison to switch off. -A remote mirror compares every file with its copy by checksum (rclone's +An rclone mirror compares every file with its copy by checksum (rclone's `--checksum`), under the first hash both ends support — MD5 on S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an error, so the run is not marked success, and the run advances the evidence under @@ -81,7 +86,7 @@ offload gate accepts neither: a mirror cannot be named in ## Index snapshots `.squirrel-index/` holds the [index snapshots](/squirrel/configuration/index-snapshots/) -ridden along after each successful sync, and a local mirror's receipts. Like +ridden along after each successful sync, and a native mirror's receipts. Like `.squirrel-history`, it is filtered out of all sync and restore transfers and from peer-sync. diff --git a/docs/src/content/docs/reference/cli.md b/docs/src/content/docs/reference/cli.md index ac0cfd9..71f7103 100644 --- a/docs/src/content/docs/reference/cli.md +++ b/docs/src/content/docs/reference/cli.md @@ -108,7 +108,7 @@ Optional single positional. No arg = every `(volume, destination)` pair; one arg | Flag | Default | Meaning | |---|---|---| | `--to` | all | Limit to this destination name. | -| `--shallow` | `false` | Skip the checksum comparison on remote mirror destinations; trust rclone's size+mtime comparison. Refused on a local mirror, which has no comparison to skip. A peer sync hashes every byte on both ends regardless. | +| `--shallow` | `false` | Skip the checksum comparison on rclone mirror destinations; trust rclone's size+mtime comparison. Refused on a native mirror (`local`, or `sftp` without crypt), which has no comparison to skip. A peer sync hashes every byte on both ends regardless. | | `--dry-run` | `false` | Preview what a push would transfer without transferring; no runs row is written. | | `--init` | `false` | Authorise first-use destination bootstrap. | | `--progress`, `-P` | auto on a TTY | Show live transfer progress (files, bytes, rate, ETA). | diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md index dcc88c1..3cce5b2 100644 --- a/docs/src/content/docs/reference/configuration.md +++ b/docs/src/content/docs/reference/configuration.md @@ -59,14 +59,31 @@ See [Hooks](/squirrel/guides/hooks/). | Key | Meaning | |---|---| | `host` | Server hostname. | -| `port` | SSH port (optional; rclone's default when omitted). | +| `port` | SSH port (optional; `22` when omitted). | | `user` | SSH user. | | `password` | Secret (literal or `{ env }`). | -| `key_file` | Path to a private key file, as an alternative to `password` (optional). | +| `key_file` | Path to a private key file, as an alternative to `password` (optional; a leading `~/` is expanded). A passphrase-protected key goes through ssh-agent instead. | | `root` | Base path on the server. | -| `known_hosts_file` | Path to a known_hosts file; **validates the server host key** (recommended). Without it, rclone connects to whatever host answers. | +| `known_hosts_file` | Path to a known_hosts file holding the server's host key. | | `host_key_algorithms` | Space-separated list pinning accepted host-key algorithms (optional). | +With neither `password` nor `key_file` set, squirrel logs in with the keys of the +running ssh-agent (`SSH_AUTH_SOCK`). + +A mirror without [crypt](/squirrel/layouts/encrypted/) is a +[native mirror](/squirrel/layouts/mirror/#how-a-mirror-is-written): squirrel +connects to the server itself, and **always checks its host key**, against +`known_hosts_file` or `~/.ssh/known_hosts` when that is unset. A server whose key +the file does not hold is refused; the message gives the key's fingerprint and +the known_hosts line that trusts it, to add once you have confirmed it. A key +that differs from the pinned one is refused too. Unless `host_key_algorithms` is +set, squirrel asks the server for the key types the file holds for it. `checkers` +and `hash_algo` tune rclone, so a native mirror rejects them. + +Every other sftp destination — an encrypted mirror, or the content-addressed and +packed layouts — is written by rclone, which checks the host key against +`known_hosts_file` and accepts whatever key the server presents when it is unset. + ### `s3` | Key | Meaning | diff --git a/docs/src/content/docs/reference/on-disk-layout.md b/docs/src/content/docs/reference/on-disk-layout.md index 8620b2e..fa31c71 100644 --- a/docs/src/content/docs/reference/on-disk-layout.md +++ b/docs/src/content/docs/reference/on-disk-layout.md @@ -88,7 +88,7 @@ for user content: | Directory | Purpose | |---|---| | `.squirrel-history/run-/` | Prior bytes of the files a sync run replaced on a [mirror](/squirrel/layouts/mirror/). | -| `.squirrel-index/` | Ride-along [index snapshots](/squirrel/configuration/index-snapshots/), and a local mirror's receipts. | +| `.squirrel-index/` | Ride-along [index snapshots](/squirrel/configuration/index-snapshots/), and a native mirror's receipts. | | `.squirrel-restore-history/run-/` | Files displaced by an [`--in-place` restore](/squirrel/guides/restore/). | | `.squirrel-staging/run-/` | A native [mirror](/squirrel/layouts/mirror/)'s in-flight writes, renamed onto their paths once complete. | diff --git a/sync/handler.go b/sync/handler.go index 520e6ab..25b6ff5 100644 --- a/sync/handler.go +++ b/sync/handler.go @@ -134,8 +134,8 @@ func HandlerFor(s *store.Store, tools Tools, p Pair) (Handler, error) { return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) } return &contentAddressedHandler{contentPusher{store: s, rcl: tools.Rclone, vol: p.Volume, dest: p.Destination}}, nil - case p.Destination.Type == "local": - return &mirrorHandler{store: s, vol: p.Volume, dest: p.Destination, openTransport: openLocalDestination, stallTimeout: DefaultStallTimeout}, nil + case p.Destination.NativeMirror(): + return &mirrorHandler{store: s, vol: p.Volume, dest: p.Destination, openTransport: openDestinationTransport, stallTimeout: DefaultStallTimeout}, nil default: if tools.Rclone == nil { return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) @@ -144,8 +144,12 @@ func HandlerFor(s *store.Store, tools Tools, p Pair) (Handler, error) { } } -// openLocalDestination opens a local destination's root directory. -func openLocalDestination(dest *config.Destination) (transport, error) { +// openDestinationTransport opens a native mirror's destination root: a +// directory on this machine, or on an sftp server. +func openDestinationTransport(ctx context.Context, dest *config.Destination) (transport, error) { + if dest.Type == "sftp" { + return dialSFTP(ctx, dest) + } return openLocalTransport(dest.Root) } diff --git a/sync/handler_test.go b/sync/handler_test.go index 378e049..1befa02 100644 --- a/sync/handler_test.go +++ b/sync/handler_test.go @@ -9,8 +9,10 @@ import ( func TestHandlerForDispatch(t *testing.T) { vol := &config.Volume{Name: "pics", Path: "/tmp/pics"} - bucket := &config.Destination{Name: "offsite", Type: "sftp", Root: "/data"} + bucket := &config.Destination{Name: "offsite", Type: "s3", Root: "/data"} usb := &config.Destination{Name: "usb", Type: "local", Root: "/tmp/dst"} + box := &config.Destination{Name: "box", Type: "sftp", Root: "/data"} + cryptBox := &config.Destination{Name: "box", Type: "sftp", Root: "/data", Crypt: &config.Crypt{Password: "pw"}} node := &config.Node{Name: "nas"} tools := Tools{Rclone: &Rclone{Binary: "rclone"}} @@ -31,6 +33,22 @@ func TestHandlerForDispatch(t *testing.T) { t.Fatalf("local mirror pair resolved to %T (%q), want *mirrorHandler usb", h, h.TargetName()) } + // So is a plain sftp mirror; an encrypted one stays on rclone. + h, err = HandlerFor(nil, Tools{}, Pair{Volume: vol, Destination: box}) + if err != nil { + t.Fatalf("sftp mirror pair: %v", err) + } + if _, ok := h.(*mirrorHandler); !ok { + t.Fatalf("sftp mirror pair resolved to %T, want *mirrorHandler", h) + } + h, err = HandlerFor(nil, tools, Pair{Volume: vol, Destination: cryptBox}) + if err != nil { + t.Fatalf("crypt sftp mirror pair: %v", err) + } + if _, ok := h.(*rcloneHandler); !ok { + t.Fatalf("crypt sftp mirror pair resolved to %T, want *rcloneHandler", h) + } + h, err = HandlerFor(nil, tools, Pair{Volume: vol, Node: node}) if err != nil { t.Fatalf("node pair: %v", err) diff --git a/sync/mirror.go b/sync/mirror.go index 94e0700..0ee48f5 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -32,7 +32,7 @@ type mirrorHandler struct { dest *config.Destination // openTransport opens the destination root; tests wrap it to inject // faults. - openTransport func(*config.Destination) (transport, error) + openTransport func(context.Context, *config.Destination) (transport, error) // stallTimeout bounds every transport call by progress. stallTimeout time.Duration @@ -60,9 +60,9 @@ func (h *mirrorHandler) Push(ctx context.Context, opts Options) (Report, error) // root is the destination root as a layout may hold it: guarded, so only // runID's own moves pass (none when runID is 0), and bounded by progress. -func (h *mirrorHandler) root(runID int64) (transport, error) { +func (h *mirrorHandler) root(ctx context.Context, runID int64) (transport, error) { if h.raw == nil { - raw, err := h.openTransport(h.dest) + raw, err := h.openTransport(ctx, h.dest) if err != nil { return nil, err } @@ -99,7 +99,7 @@ func (h *mirrorHandler) markers(ctx context.Context, rep *Report, volumeID int64 if opts.DryRun { return nil } - merr := ensureLocalDestinationMarker(ctx, h.store, h.dest, h.vol.Name, opts.Init) + merr := h.ensureMarker(ctx, opts.Init) if merr == nil { return nil } @@ -109,7 +109,7 @@ func (h *mirrorHandler) markers(ctx context.Context, rep *Report, volumeID int64 // landed reports whether runID left its receipt at the destination. func (h *mirrorHandler) landed(ctx context.Context, runID int64) (bool, error) { - tr, err := h.root(0) + tr, err := h.root(ctx, 0) if err != nil { return false, err } @@ -126,7 +126,7 @@ func (h *mirrorHandler) landed(ctx context.Context, runID int64) (bool, error) { // rootEmpty reports whether the destination root holds no file beyond // the volume markers, walking it until the first one. func (h *mirrorHandler) rootEmpty(ctx context.Context) (bool, error) { - tr, err := h.root(0) + tr, err := h.root(ctx, 0) if err != nil { return false, err } @@ -164,7 +164,7 @@ func (h *mirrorHandler) seal(ctx context.Context, _ *Report, runID int64, p push if err != nil { return err } - tr, err := h.root(runID) + tr, err := h.root(ctx, runID) if err != nil { return err } diff --git a/sync/mirror_marker.go b/sync/mirror_marker.go new file mode 100644 index 0000000..494643e --- /dev/null +++ b/sync/mirror_marker.go @@ -0,0 +1,102 @@ +package sync + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "time" + + "github.com/mbertschler/squirrel/volmark" +) + +// maxMarkerBytes bounds how much of a destination's marker squirrel reads. +const maxMarkerBytes = 64 << 10 + +// ensureMarker is a native mirror's gate against a wrong or unmounted +// root: the destination's /.squirrel-volume must name this volume. +// A missing marker is written only under init, through an exclusive Put, +// and a marker naming another volume, or one that does not parse, is +// always refused and never overwritten. A local root that does not exist +// yet is created under init, so a first push can land on an empty disk. +func (h *mirrorHandler) ensureMarker(ctx context.Context, init bool) error { + if init && h.dest.Type == "local" { + if err := os.MkdirAll(h.dest.Root, 0o755); err != nil { + return fmt.Errorf("destination %q: create root %s: %w", h.dest.Name, h.dest.Root, err) + } + } + tr, err := h.root(ctx, 0) + if err != nil { + return err + } + name := path.Join(h.vol.Name, volmark.MarkerName) + data, err := readSmallFile(ctx, tr, name, maxMarkerBytes) + switch { + case err == nil: + return h.checkMarker(name, data) + case !errors.Is(err, fs.ErrNotExist): + return fmt.Errorf("destination %q: read %s: %w", h.dest.Name, name, err) + case !init: + return fmt.Errorf("destination %q has no %s at %s — re-run with --init to bootstrap (refusing in case the root is a typo or the disk is not mounted): %w", h.dest.Name, volmark.MarkerName, h.where(name), ErrRefused) + } + return h.writeMarker(ctx, tr, name) +} + +func (h *mirrorHandler) checkMarker(name string, data []byte) error { + m, err := volmark.Parse(data) + if err != nil { + return fmt.Errorf("destination %q: %w at %s: %w", h.dest.Name, err, h.where(name), ErrRefused) + } + if m.Volume != h.vol.Name { + return fmt.Errorf("destination %q: %s at %s names volume %q, want %q (refusing to sync over a different volume's tree): %w", + h.dest.Name, volmark.MarkerName, h.where(name), m.Volume, h.vol.Name, ErrRefused) + } + return nil +} + +func (h *mirrorHandler) writeMarker(ctx context.Context, tr transport, name string) error { + m, err := selfMarker(ctx, h.store, h.vol.Name) + if err != nil { + return fmt.Errorf("destination %q: %w", h.dest.Name, err) + } + data, err := volmark.Marshal(m) + if err != nil { + return fmt.Errorf("destination %q: %w", h.dest.Name, err) + } + if err := tr.Put(ctx, name, bytes.NewReader(data), time.Now()); err != nil { + return fmt.Errorf("destination %q: write %s: %w", h.dest.Name, h.where(name), err) + } + return nil +} + +// where names a destination-relative name for a message: the path on a +// local disk, host:path on an sftp server. +func (h *mirrorHandler) where(name string) string { + full := path.Join(h.dest.Root, name) + if h.dest.Type == "sftp" { + return h.dest.Params["host"] + ":" + full + } + return full +} + +// readSmallFile reads the whole regular file at name, refusing one larger +// than limit. +func readSmallFile(ctx context.Context, tr transport, name string, limit int64) ([]byte, error) { + rc, err := tr.Get(ctx, name) + if err != nil { + return nil, err + } + defer func() { _ = rc.Close() }() + data, err := io.ReadAll(io.LimitReader(ctxReader{ctx: ctx, r: rc}, limit+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > limit { + return nil, fmt.Errorf("%s is larger than %d bytes", name, limit) + } + return data, nil +} diff --git a/sync/mirror_reconcile.go b/sync/mirror_reconcile.go index a90d438..ec1af0c 100644 --- a/sync/mirror_reconcile.go +++ b/sync/mirror_reconcile.go @@ -16,7 +16,7 @@ import ( // recorded but may not have finished, deciding each from where the bytes // actually are, then removes the staging finished runs left behind. func (h *mirrorHandler) reconcile(ctx context.Context, rep *Report, volumeID, runID int64) error { - tr, err := h.root(runID) + tr, err := h.root(ctx, runID) if err != nil { return err } diff --git a/sync/mirror_sftp_test.go b/sync/mirror_sftp_test.go new file mode 100644 index 0000000..4643e3f --- /dev/null +++ b/sync/mirror_sftp_test.go @@ -0,0 +1,79 @@ +package sync + +import ( + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// TestMirrorPushOverSFTP: a plain sftp mirror pushes natively with no +// rclone wrapper. --init writes the marker through the transport, a +// changed path moves its prior version into history, and every run +// leaves its receipt. +func TestMirrorPushOverSFTP(t *testing.T) { + f := setupMirrorFixtureOn(t, sftpBackend) + if err := os.Remove(filepath.Join(f.dst, "pics", volmark.MarkerName)); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "v1") + f.write(t, "2024/cat.jpg", "meow") + f.index(t) + + if _, err := f.push(t, Options{}); !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "--init") { + t.Fatalf("push onto a root with no marker = %v, want a refusal naming --init", err) + } + first, err := f.push(t, Options{Init: true}) + if err != nil || first.Status != store.RunStatusSuccess { + t.Fatalf("--init push: status=%q err=%v", first.Status, err) + } + if err := volmark.Validate(filepath.Join(f.dst, "pics"), "pics"); err != nil { + t.Fatalf("marker after --init: %v", err) + } + f.write(t, "a.txt", "v2") + f.index(t) + second := f.mustPush(t) + + if f.readDest(t, "a.txt") != "v2" || f.readDest(t, "2024/cat.jpg") != "meow" { + t.Fatal("destination bytes differ from the source") + } + if got := f.readDest(t, historyName("", second.RunID, "a.txt")); got != "v1" { + t.Fatalf("history holds %q, want the displaced v1", got) + } + for _, rep := range []Report{first, second} { + if _, err := os.Stat(f.dest(IndexDirName + "/run-" + strconv.FormatInt(rep.RunID, 10))); err != nil { + t.Fatalf("receipt of run %d: %v", rep.RunID, err) + } + } + f.checkInvariants(t, nil) +} + +// TestMirrorOverSFTPRefusesAnUnknownHost: a server whose host key +// known_hosts does not pin never receives a byte, and the refusal is +// recorded as its own run. +func TestMirrorOverSFTPRefusesAnUnknownHost(t *testing.T) { + f := setupMirrorFixtureOn(t, sftpBackend) + empty := filepath.Join(t.TempDir(), "known_hosts") + if err := os.WriteFile(empty, nil, 0o600); err != nil { + t.Fatal(err) + } + f.pair.Destination.Params["known_hosts_file"] = empty + f.write(t, "a.txt", "alpha") + f.index(t) + + rep, err := f.push(t, Options{Init: true}) + if !errors.Is(err, errUnknownHostKey) || rep.Status != store.RunStatusRefused { + t.Fatalf("push to an unknown host: status=%q err=%v, want a refused run", rep.Status, err) + } + if _, err := os.Stat(f.dest("a.txt")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("a.txt reached the unknown host: %v", err) + } + if runs := mustListSyncRuns(t, f.store); len(runs) != 1 || runs[0].Status != store.RunStatusRefused { + t.Fatalf("runs = %+v, want the one refused run", runs) + } +} diff --git a/sync/mirror_test.go b/sync/mirror_test.go index 2983d55..e2c2712 100644 --- a/sync/mirror_test.go +++ b/sync/mirror_test.go @@ -4,7 +4,9 @@ import ( "context" "encoding/hex" "errors" + "fmt" "io/fs" + "net" "os" "path/filepath" "strconv" @@ -21,8 +23,9 @@ import ( "github.com/mbertschler/squirrel/volmark" ) -// mirrorFixture is one volume, "pics", mirrored to a native local -// destination, "usb", with the destination's volume marker in place. +// mirrorFixture is one volume, "pics", mirrored to a native destination, +// "usb", with the destination's volume marker in place. The destination +// is a local directory unless the fixture is set up on another backend. type mirrorFixture struct { store *store.Store pair Pair @@ -30,7 +33,34 @@ type mirrorFixture struct { dst string // the destination root } +// mirrorBackend is where a mirror fixture's destination lives: its name, +// and the settings of a destination rooted at dst on it. +type mirrorBackend struct { + name string + settings func(t *testing.T, dst string) string +} + +var ( + localBackend = mirrorBackend{"local", func(_ *testing.T, dst string) string { + return fmt.Sprintf("type = \"local\"\nroot = %q\n", dst) + }} + // sftpBackend serves the destination root from an in-process sftp + // server, so the fixture reads what landed straight off the disk. + sftpBackend = mirrorBackend{"sftp", func(t *testing.T, dst string) string { + srv := startSFTPServer(t) + host, port, _ := net.SplitHostPort(srv.addr) + return fmt.Sprintf("type = \"sftp\"\nroot = %q\nhost = %q\nport = %q\nuser = \"u\"\npassword = \"p\"\nknown_hosts_file = %q\n", + dst, host, port, srv.knownHosts(t, srv.hostKeys[0].PublicKey())) + }} + mirrorBackends = []mirrorBackend{localBackend, sftpBackend} +) + func setupMirrorFixture(t *testing.T) *mirrorFixture { + t.Helper() + return setupMirrorFixtureOn(t, localBackend) +} + +func setupMirrorFixtureOn(t *testing.T, b mirrorBackend) *mirrorFixture { t.Helper() root := t.TempDir() f := &mirrorFixture{src: filepath.Join(root, "src"), dst: filepath.Join(root, "usb")} @@ -49,7 +79,7 @@ func setupMirrorFixture(t *testing.T) *mirrorFixture { t.Cleanup(func() { s.Close() }) f.store = s cfgPath := filepath.Join(root, "config.toml") - body := "[destinations.usb]\ntype = \"local\"\nroot = \"" + f.dst + "\"\n\n" + + body := "[destinations.usb]\n" + b.settings(t, f.dst) + "\n" + "[volumes.pics]\npath = \"" + f.src + "\"\nsync_to = [\"usb\"]\n" if err := os.WriteFile(cfgPath, []byte(body), 0o600); err != nil { t.Fatal(err) @@ -100,8 +130,8 @@ func (f *mirrorFixture) mustPush(t *testing.T) Report { func (f *mirrorFixture) pushCrashing(t *testing.T, crashAt func(transportCall) bool, mode crashMode) (Report, error) { t.Helper() h := f.handler(t) - h.openTransport = func(d *config.Destination) (transport, error) { - raw, err := openLocalDestination(d) + h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) if err != nil { return nil, err } @@ -467,22 +497,26 @@ func isReceiptPut(c transportCall) bool { return c.op == "put" && strings.Contains(c.name, IndexDirName+"/run-") } +// mirrorCrashCase is one row of the crash table: where the push dies, and +// what it leaves recorded. +type mirrorCrashCase struct { + name string + crashAt func(transportCall) bool + mode crashMode + // crashed is the changed path's rows after the crash, oldest first. + crashed []string + check func(t *testing.T, f *mirrorFixture, clean Report) +} + // TestMirrorCrashTable is the design's crash table: a push that dies at -// each point of writing one changed path, then a clean push. Each row pins -// what the crash leaves recorded and how reconcile settles it; afterwards -// the three invariants hold. +// each point of writing one changed path, then a clean push, on both +// transports. Each row pins what the crash leaves recorded and how +// reconcile settles it; afterwards the three invariants hold. func TestMirrorCrashTable(t *testing.T) { staged := func(c transportCall) bool { return strings.Contains(c.name, StagingDirName+"/") } intoHistory := func(c transportCall) bool { return c.op == "rename" && strings.Contains(c.to, HistoryDirName+"/") } commitRename := func(c transportCall) bool { return c.op == "rename" && staged(c) } - cases := []struct { - name string - crashAt func(transportCall) bool - mode crashMode - // rows after the crash, oldest first - crashed []string - check func(t *testing.T, f *mirrorFixture, clean Report) - }{ + cases := []mirrorCrashCase{ {"staging write", func(c transportCall) bool { return c.op == "put" && staged(c) }, crashMidway, []string{store.RemotePathLive}, nil}, {"displacing recorded", intoHistory, crashBefore, @@ -501,36 +535,41 @@ func TestMirrorCrashTable(t *testing.T) { } }}, } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - f := setupMirrorFixture(t) - f.write(t, "keep.txt", "untouched") - f.write(t, "a.txt", "v1") - f.index(t) - f.mustPush(t) - f.write(t, "a.txt", "v2 is longer") - f.index(t) - before := f.contentHashes(t) - - if rep, err := f.pushCrashing(t, c.crashAt, c.mode); !crashedOn(rep, err) { - t.Fatalf("crashing push = %v (failures %+v), want the injected crash", err, rep.RcloneResult.FailedFiles) - } - if got := f.rowsAt(t, "a.txt"); !slicesEqual(got, c.crashed) { - t.Fatalf("rows after the crash = %v, want %v", got, c.crashed) - } - clean := f.mustPush(t) - if f.readDest(t, "a.txt") != "v2 is longer" { - t.Fatal("the clean push did not land the new version") - } - if c.check != nil { - c.check(t, f, clean) - } - f.checkInvariants(t, before) - f.checkStagingEmpty(t, clean.RunID) - }) + for _, b := range mirrorBackends { + for _, c := range cases { + t.Run(b.name+"/"+c.name, func(t *testing.T) { + runCrashCase(t, setupMirrorFixtureOn(t, b), c) + }) + } } } +func runCrashCase(t *testing.T, f *mirrorFixture, c mirrorCrashCase) { + f.write(t, "keep.txt", "untouched") + f.write(t, "a.txt", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2 is longer") + f.index(t) + before := f.contentHashes(t) + + if rep, err := f.pushCrashing(t, c.crashAt, c.mode); !crashedOn(rep, err) { + t.Fatalf("crashing push = %v (failures %+v), want the injected crash", err, rep.RcloneResult.FailedFiles) + } + if got := f.rowsAt(t, "a.txt"); !slicesEqual(got, c.crashed) { + t.Fatalf("rows after the crash = %v, want %v", got, c.crashed) + } + clean := f.mustPush(t) + if f.readDest(t, "a.txt") != "v2 is longer" { + t.Fatal("the clean push did not land the new version") + } + if c.check != nil { + c.check(t, f, clean) + } + f.checkInvariants(t, before) + f.checkStagingEmpty(t, clean.RunID) +} + // crashedOn reports whether a push failed on the injected crash, directly // or on one of its paths. func crashedOn(rep Report, err error) bool { @@ -793,8 +832,8 @@ func TestMirrorStallFailsThePush(t *testing.T) { release := make(chan struct{}) h := f.handler(t) h.stallTimeout = 50 * time.Millisecond - h.openTransport = func(d *config.Destination) (transport, error) { - raw, err := openLocalDestination(d) + h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) return blockingTransport{transport: raw, release: release}, err } if _, err := h.Push(context.Background(), Options{}); !errors.Is(err, errTransportStalled) { diff --git a/sync/mirror_write.go b/sync/mirror_write.go index cd7b805..a0cbf9d 100644 --- a/sync/mirror_write.go +++ b/sync/mirror_write.go @@ -40,7 +40,7 @@ type mirrorWriter struct { // recorded and saves work on the retry — but any failure fails the run // before its receipt is written, so the watermark holds. func (h *mirrorHandler) execute(ctx context.Context, rep *Report, runID int64, ops *mirrorOps) error { - tr, err := h.root(runID) + tr, err := h.root(ctx, runID) if err != nil { return err } diff --git a/sync/sync.go b/sync/sync.go index a205dbb..fc2ee30 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -312,14 +312,12 @@ func Sync(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volume, return rep, err } - // Marker gate. Local destinations validate the marker on the - // filesystem; remote rclone destinations (sftp/s3/b2/gcs) read and, - // with --init, write it through the same overlay the transfer uses. - // The dry-run path skips: it never writes, and refusing a dry-run on + // Marker gate, read and (with --init) written through the same + // overlay the transfer uses. The dry-run path skips: it never writes, and refusing a dry-run on // an uninitialised destination would prevent the "preview what would // happen" workflow. if !opts.DryRun { - if merr := ensureDestinationMarker(ctx, s, rcl, dest, vol.Name, opts.Init); merr != nil { + if merr := ensureRemoteDestinationMarker(ctx, s, rcl, dest, vol.Name, opts.Init); merr != nil { // A marker refusal fires before the sync run is allocated, so // record it as its own terminal 'refused' run — otherwise a // month-dead backup disk produces zero red anywhere but agent @@ -630,57 +628,12 @@ func validateLocalVolumeMarker(vol *config.Volume) error { return fmt.Errorf("volume %q marker check: %w", vol.Name, err) } -// ensureDestinationMarker validates (or, with init, writes) the -// .squirrel-volume marker at the destination's per-volume root. It is -// the single gate against pushing to a wrong or unmounted root: a -// matching marker passes, a missing marker is bootstrapped only under -// init (refused otherwise, in case the root is a typo or the remote is -// unreachable), and a marker naming a different volume is always -// refused — overwriting it would erase the trail that distinguishes the -// two volumes. -// -// Local destinations reach the marker on the filesystem; remote rclone -// destinations reach it through the same overlay their transfers use. -func ensureDestinationMarker(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination, volumeName string, init bool) error { - if dest.Type != "local" { - return ensureRemoteDestinationMarker(ctx, s, rcl, dest, volumeName, init) - } - return ensureLocalDestinationMarker(ctx, s, dest, volumeName, init) -} - -// ensureLocalDestinationMarker is the filesystem gate for local -// destinations. The directory is created on first --init so the marker -// can land even when the destination tree is empty. -func ensureLocalDestinationMarker(ctx context.Context, s *store.Store, dest *config.Destination, volumeName string, init bool) error { - root := filepath.Join(dest.Root, volumeName) - err := volmark.Validate(root, volumeName) - if err == nil { - return nil - } - if _, ok := errors.AsType[*volmark.ErrMismatch](err); ok { - return fmt.Errorf("destination %q: %w (refuse to init over a different volume's tree): %w", dest.Name, err, ErrRefused) - } - if !errors.Is(err, volmark.ErrMissing) { - return fmt.Errorf("destination %q marker check: %w", dest.Name, err) - } - if !init { - return fmt.Errorf("destination %q at %s has no %s marker — re-run with --init to bootstrap (refusing in case the root is a typo): %w", dest.Name, root, volmark.MarkerName, ErrRefused) - } - if err := os.MkdirAll(root, 0o755); err != nil { - return fmt.Errorf("destination %q: mkdir %s: %w", dest.Name, root, err) - } - m, err := selfMarker(ctx, s, volumeName) - if err != nil { - return fmt.Errorf("destination %q: %w", dest.Name, err) - } - if err := volmark.Write(root, m); err != nil { - return fmt.Errorf("destination %q: %w", dest.Name, err) - } - return nil -} - -// ensureRemoteDestinationMarker is the rclone-mediated gate for remote -// destinations (sftp/s3/b2/gcs). It probes the marker at the per-volume +// ensureRemoteDestinationMarker is the gate against pushing to a wrong or +// unreachable root for the destinations rclone writes (crypt mirrors, +// mirrors on s3/b2/gcs, and the content layouts). It validates (or, with +// init, writes) the .squirrel-volume marker at the per-volume root: a +// matching marker passes, a missing one is bootstrapped only under init, +// and one naming a different volume is always refused. It probes the marker at the per-volume // root through remoteSubpathURI — the same overlay the layout's // transfers use, so a crypt destination's marker rides the encrypted // path too — and applies the identical rules as the local gate. @@ -705,7 +658,7 @@ func ensureRemoteDestinationMarker(ctx context.Context, s *store.Store, rcl *Rcl } if !present { if !init { - return fmt.Errorf("destination %q at %s has no %s marker — re-run with --init to bootstrap (refusing in case the root is a typo)", dest.Name, markerURI, volmark.MarkerName) + return fmt.Errorf("destination %q at %s has no %s marker — re-run with --init to bootstrap (refusing in case the root is a typo): %w", dest.Name, markerURI, volmark.MarkerName, ErrRefused) } return writeRemoteMarker(ctx, s, rcl, dest, markerURI, volumeName) } @@ -728,8 +681,8 @@ func validateRemoteMarker(dest *config.Destination, markerURI, volumeName string return fmt.Errorf("destination %q: %w at %s", dest.Name, err, markerURI) } if m.Volume != volumeName { - return fmt.Errorf("destination %q: %s at %s names %q, want %q (refuse to sync over a different volume's tree)", - dest.Name, volmark.MarkerName, markerURI, m.Volume, volumeName) + return fmt.Errorf("destination %q: %s at %s names %q, want %q (refuse to sync over a different volume's tree): %w", + dest.Name, volmark.MarkerName, markerURI, m.Volume, volumeName, ErrRefused) } return nil } From 3931e06f720cd52748116aaa3852c394d593e639 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 01:21:28 +0200 Subject: [PATCH 15/61] sync: ride the index snapshot along through the transport MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Snapshotter no longer holds an rclone wrapper. Each push hands over the shelf its ride-along lands on — the destination's /.squirrel-index/ — and a new layout method opens it: through rclone for the content layouts, through the guarded transport for a native mirror, whose name guard permits removing a snapshot there and nothing else. Rotation lists and removes through the same shelf, so it never touches a mirror's receipts. Syncing a native mirror now runs no rclone at all, so Pair.DrivesRclone is false for it, and the agent schedules such syncs on a host without rclone. --- cmd/squirrel/agent_scheduler.go | 14 +-- cmd/squirrel/agent_scheduler_test.go | 20 ++++ cmd/squirrel/sync.go | 2 +- design/native-mirror.md | 3 + sync/content_addressed.go | 6 ++ sync/kopia.go | 6 +- sync/mirror.go | 10 ++ sync/mirror_sftp_test.go | 41 ++++++++ sync/naming_test.go | 2 +- sync/node.go | 4 +- sync/push.go | 5 +- sync/rclone.go | 3 +- sync/recover.go | 3 +- sync/snapshot.go | 148 +++++++++++++++++++++------ sync/snapshot_test.go | 20 ++-- sync/sync.go | 9 +- sync/transport_guard.go | 2 +- 17 files changed, 230 insertions(+), 68 deletions(-) diff --git a/cmd/squirrel/agent_scheduler.go b/cmd/squirrel/agent_scheduler.go index d7d7e3b..0e7fc25 100644 --- a/cmd/squirrel/agent_scheduler.go +++ b/cmd/squirrel/agent_scheduler.go @@ -82,9 +82,9 @@ func (t *schedulerTools) rebuild(ctx context.Context, cfg *config.Config) error // anyVolumeNeedsScheduledSync reports whether a scheduled sync will // invoke rclone. Only rclone-backed destinations count: a peer node -// streams its bytes over the sync API and a kopia destination drives its -// own binary, so a cadence naming only those runs its whole schedule on a -// host with no rclone installed. +// streams its bytes over the sync API, a kopia destination drives its own +// binary, and squirrel writes a native mirror itself, so a cadence naming +// only those runs its whole schedule on a host with no rclone installed. func anyVolumeNeedsScheduledSync(cfg *config.Config) bool { for _, v := range cfg.Volumes { if v.SyncEvery <= 0 { @@ -108,8 +108,8 @@ func targetNeedsRclone(cfg *config.Config, target string) bool { if _, isNode := cfg.Nodes[target]; isNode { return false } - if dest, ok := cfg.Destinations[target]; ok && dest.Type == "kopia" { - return false + if dest, ok := cfg.Destinations[target]; ok { + return sync.Pair{Destination: dest}.DrivesRclone() } return true } @@ -159,7 +159,7 @@ func buildSchedulerSyncRunner(live *config.Live, s *store.Store, tools *schedule return agent.SyncRunReport{Err: err} } rcl := tools.rclone() - if rcl == nil && !pair.IsNode() { + if rcl == nil && pair.DrivesRclone() { return agent.SyncRunReport{Err: errors.New("scheduled sync needs rclone, which the configuration in force did not call for")} } // Per-kick because the kopia lookup belongs to the kicks that @@ -174,7 +174,7 @@ func buildSchedulerSyncRunner(live *config.Live, s *store.Store, tools *schedule // a single pair, so a fresh Snapshotter per kick is the right unit. opts := sync.Options{} if cfg.Backups.Enabled { - opts.Snapshot = sync.NewSnapshotter(s, rcl, snapshotConfig(cfg, s.Path())) + opts.Snapshot = sync.NewSnapshotter(s, snapshotConfig(cfg, s.Path())) } rep, runErr := sync.RunPair(ctx, s, syncTools, pair, opts) return agent.SyncRunReport{ diff --git a/cmd/squirrel/agent_scheduler_test.go b/cmd/squirrel/agent_scheduler_test.go index 4dd271a..5b2e35b 100644 --- a/cmd/squirrel/agent_scheduler_test.go +++ b/cmd/squirrel/agent_scheduler_test.go @@ -109,3 +109,23 @@ func TestSchedulerToolsRebuildKeepsRclone(t *testing.T) { t.Fatalf("rclone() = %p after a reload that needs none, want the located wrapper %p", got, located) } } + +// TestScheduledSyncToANativeMirrorNeedsNoRclone: squirrel writes a local +// mirror and a plain sftp mirror itself, so a cadence naming only those +// runs on a host without rclone; an encrypted sftp mirror still needs it. +func TestScheduledSyncToANativeMirrorNeedsNoRclone(t *testing.T) { + cfg := &config.Config{ + Volumes: map[string]*config.Volume{"pics": {Name: "pics", SyncEvery: time.Hour, SyncTo: []string{"usb", "box"}}}, + Destinations: map[string]*config.Destination{ + "usb": {Name: "usb", Type: "local", Layout: config.LayoutMirror}, + "box": {Name: "box", Type: "sftp", Layout: config.LayoutMirror}, + }, + } + if anyVolumeNeedsScheduledSync(cfg) { + t.Fatal("a cadence onto native mirrors only must not need rclone") + } + cfg.Destinations["box"].Crypt = &config.Crypt{Password: "pw"} + if !anyVolumeNeedsScheduledSync(cfg) { + t.Fatal("an encrypted sftp mirror is written by rclone") + } +} diff --git a/cmd/squirrel/sync.go b/cmd/squirrel/sync.go index 7454c73..b9d9a57 100644 --- a/cmd/squirrel/sync.go +++ b/cmd/squirrel/sync.go @@ -91,7 +91,7 @@ func runSync(cmd *cobra.Command, volumeName, destinationName string, progress bo // for dry-run (no run rows to snapshot against) and when [backups] is // turned off. if !opts.DryRun && cfg.Backups.Enabled { - opts.Snapshot = sync.NewSnapshotter(s, rcl, snapshotConfig(cfg, s.Path())) + opts.Snapshot = sync.NewSnapshotter(s, snapshotConfig(cfg, s.Path())) } // Progress renders to stderr (leaving stdout for the summary lines). A diff --git a/design/native-mirror.md b/design/native-mirror.md index a0c49eb..6a1350f 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -125,6 +125,9 @@ type layout[O operations] interface { // advanceMethod names the evidence the confirmed landing earns; an // empty method holds the vector (packed, while a fingerprint is pending). advanceMethod(ctx context.Context, rep *Report, p pushPlan) (string, error) + // shelf opens /.squirrel-index/ for the ride-along: through + // rclone for the content layouts, through the transport for a mirror. + shelf(ctx context.Context, runID int64) (snapshotShelf, error) } ``` diff --git a/sync/content_addressed.go b/sync/content_addressed.go index 9bc1943..823bd58 100644 --- a/sync/content_addressed.go +++ b/sync/content_addressed.go @@ -125,6 +125,12 @@ func (h *contentPusher) ensureMarkers(ctx context.Context, init bool) error { return ensureRemoteDestinationMarker(ctx, h.store, h.rcl, h.dest, h.vol.Name, init) } +// shelf is the destination's .squirrel-index/ directory, reached through +// rclone like the rest of the push. +func (h *contentPusher) shelf(context.Context, int64) (snapshotShelf, error) { + return rcloneShelfOf(h.rcl, h.dest, h.vol.Name)() +} + // markers is the content layouts' marker gate. A dry run checks the naming // scheme read-only and writes nothing. func (h *contentPusher) markers(ctx context.Context, _ *Report, _ int64, opts Options) error { diff --git a/sync/kopia.go b/sync/kopia.go index 15d4d64..4853a4b 100644 --- a/sync/kopia.go +++ b/sync/kopia.go @@ -221,9 +221,9 @@ func (h *kopiaHandler) Push(ctx context.Context, opts Options) (Report, error) { err = h.snapshotAndVerify(ctx, &rep, opts.Init) finishHandlerRun(ctx, h.store, &rep, err) // Local index snapshot only: the repository is kopia's own format, - // so the rclone ride-along stays out of it (dest=nil, mirroring the - // peer flow). - opts.Snapshot.afterSync(ctx, &rep, h.vol, nil) + // so the ride-along stays out of it (no shelf, mirroring the peer + // flow). + opts.Snapshot.afterSync(ctx, &rep, nil) return rep, err } diff --git a/sync/mirror.go b/sync/mirror.go index 0ee48f5..5d2d275 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -188,6 +188,16 @@ func (h *mirrorHandler) advanceMethod(context.Context, *Report, pushPlan) (strin return store.VerifyMethodPresenceSize, nil } +// shelf is the mirror's /.squirrel-index/, reached through runID's +// guarded transport. +func (h *mirrorHandler) shelf(ctx context.Context, runID int64) (snapshotShelf, error) { + tr, err := h.root(ctx, runID) + if err != nil { + return nil, err + } + return transportShelf{tr: tr, dir: path.Join(h.vol.Name, IndexDirName)}, nil +} + func (h *mirrorHandler) receiptName(runID int64) string { return path.Join(h.vol.Name, IndexDirName, "run-"+strconv.FormatInt(runID, 10)) } diff --git a/sync/mirror_sftp_test.go b/sync/mirror_sftp_test.go index 4643e3f..7d7fea9 100644 --- a/sync/mirror_sftp_test.go +++ b/sync/mirror_sftp_test.go @@ -77,3 +77,44 @@ func TestMirrorOverSFTPRefusesAnUnknownHost(t *testing.T) { t.Fatalf("runs = %+v, want the one refused run", runs) } } + +// TestMirrorRideAlongThroughTheTransport: a native mirror's ride-along +// index snapshot lands in /.squirrel-index/ through the transport, +// on both backends, and rotation removes only the oldest snapshots, +// leaving every receipt in place. +func TestMirrorRideAlongThroughTheTransport(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + var runs []int64 + for i := range 3 { + f.write(t, "a.txt", strings.Repeat("v", i+1)) + f.index(t) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 2}) + rep, err := f.push(t, Options{Snapshot: sn}) + if err != nil || rep.SnapshotErr != nil { + t.Fatalf("push %d: err=%v snapshot=%v", i, err, rep.SnapshotErr) + } + runs = append(runs, rep.RunID) + } + entries, err := os.ReadDir(f.dest(IndexDirName)) + if err != nil { + t.Fatal(err) + } + var snaps, receipts []string + for _, e := range entries { + if isSnapshotName(e.Name()) { + snaps = append(snaps, e.Name()) + } else { + receipts = append(receipts, e.Name()) + } + } + if len(snaps) != 2 || !strings.HasSuffix(snaps[1], "-run-"+strconv.FormatInt(runs[2], 10)+".db") { + t.Fatalf("snapshots = %v, want the newest two", snaps) + } + if len(receipts) != 3 { + t.Fatalf("receipts = %v, want one per run", receipts) + } + }) + } +} diff --git a/sync/naming_test.go b/sync/naming_test.go index bfcaced..e68f654 100644 --- a/sync/naming_test.go +++ b/sync/naming_test.go @@ -369,7 +369,7 @@ func TestKeyedVolumeDirFoundByRecovery(t *testing.T) { f := setupContentAddressedFixture(t) f.write(t, "a.txt", "alpha") f.index(t) - sn := NewSnapshotter(f.store, f.rcl, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) rep, err := RunPair(context.Background(), f.store, Tools{Rclone: f.rcl}, f.pair, Options{Snapshot: sn}) if err != nil { t.Fatalf("sync: %v", err) diff --git a/sync/node.go b/sync/node.go index 5c25c24..18e1e83 100644 --- a/sync/node.go +++ b/sync/node.go @@ -50,9 +50,9 @@ func SyncNode(ctx context.Context, s *store.Store, vol *config.Volume, node *con // runNodeSession's deferred finishRun has committed the run's // terminal state by now, so the snapshot reflects this run's own row. // Peer-sync takes the local snapshot only — there is no ride-along to - // peer nodes (dest=nil), and the Snapshotter no-ops on non-terminal + // peer nodes (no shelf), and the Snapshotter no-ops on non-terminal // states and dry-run. - opts.Snapshot.afterSync(ctx, &rep, vol, nil) + opts.Snapshot.afterSync(ctx, &rep, nil) return rep, err } diff --git a/sync/push.go b/sync/push.go index 7eded82..22c63b7 100644 --- a/sync/push.go +++ b/sync/push.go @@ -54,6 +54,9 @@ type layout[O operations] interface { // advanceMethod names the evidence the confirmed landing earns. An // empty method holds the durability vector where it is. advanceMethod(ctx context.Context, rep *Report, p pushPlan) (string, error) + // shelf opens the destination's .squirrel-index/ directory, where + // runID's ride-along index snapshot lands. + shelf(ctx context.Context, runID int64) (snapshotShelf, error) } // pushTarget is the (volume, destination) pair one layout push serves. @@ -99,7 +102,7 @@ func pushThrough[O operations](ctx context.Context, t pushTarget, l layout[O], o } err = landPush(ctx, t, l, &rep, volID, runID) finishHandlerRun(ctx, t.store, &rep, err) - opts.Snapshot.afterSync(ctx, &rep, t.vol, t.dest) + opts.Snapshot.afterSync(ctx, &rep, func() (snapshotShelf, error) { return l.shelf(ctx, runID) }) return rep, err } diff --git a/sync/rclone.go b/sync/rclone.go index a2d0bd2..3d7c458 100644 --- a/sync/rclone.go +++ b/sync/rclone.go @@ -650,8 +650,7 @@ func (r *Rclone) listSnapshots(ctx context.Context, dirURI string) ([]string, er } var names []string for _, line := range strings.Split(string(out), "\n") { - name := strings.TrimSpace(line) - if strings.HasPrefix(name, snapshotPrefix) && strings.HasSuffix(name, ".db") { + if name := strings.TrimSpace(line); isSnapshotName(name) { names = append(names, name) } } diff --git a/sync/recover.go b/sync/recover.go index 003d2c0..4208b9f 100644 --- a/sync/recover.go +++ b/sync/recover.go @@ -85,8 +85,7 @@ func listSnapshotsStrict(ctx context.Context, rcl *Rclone, dirURI string) ([]str } var names []string for _, line := range strings.Split(string(out), "\n") { - name := strings.TrimSpace(line) - if strings.HasPrefix(name, snapshotPrefix) && strings.HasSuffix(name, ".db") { + if name := strings.TrimSpace(line); isSnapshotName(name) { names = append(names, name) } } diff --git a/sync/snapshot.go b/sync/snapshot.go index 0747f84..83a8f6a 100644 --- a/sync/snapshot.go +++ b/sync/snapshot.go @@ -2,7 +2,9 @@ package sync import ( "context" + "errors" "fmt" + "io/fs" "os" "path" "path/filepath" @@ -37,7 +39,6 @@ const snapshotPrefix = "index-" // the disabled state and every method is a safe no-op on it. type Snapshotter struct { store *store.Store - rcl *Rclone dir string // resolved local snapshot directory keep int // local rotation bound (0 = no rotation) cloud bool // ride snapshots along to destination buckets @@ -60,12 +61,11 @@ type SnapshotConfig struct { } // NewSnapshotter returns a Snapshotter ready to be shared across one -// invocation's pairs. The store backs the VACUUM INTO snapshot; the -// rclone wrapper (with its Config already written) backs the ride-along. -func NewSnapshotter(s *store.Store, rcl *Rclone, cfg SnapshotConfig) *Snapshotter { +// invocation's pairs. The store backs the VACUUM INTO snapshot; each +// push hands over the shelf its ride-along lands on. +func NewSnapshotter(s *store.Store, cfg SnapshotConfig) *Snapshotter { return &Snapshotter{ store: s, - rcl: rcl, dir: cfg.Dir, keep: cfg.Keep, cloud: cfg.Cloud, @@ -73,13 +73,24 @@ func NewSnapshotter(s *store.Store, rcl *Rclone, cfg SnapshotConfig) *Snapshotte } } -// afterSync is the post-run hook called by Sync and SyncNode once the -// run's terminal state is committed. It takes (once) the local snapshot -// and, for destination syncs with cloud enabled, rides a copy along to -// the destination. Failures are surfaced on rep.SnapshotErr and never -// mutate rep.Status — the snapshot is defense-in-depth, not part of the -// sync's success contract. A nil receiver (feature disabled) is a no-op. -func (sn *Snapshotter) afterSync(ctx context.Context, rep *Report, vol *config.Volume, dest *config.Destination) { +// snapshotShelf is a destination's per-volume .squirrel-index/ directory, +// where ride-along snapshots are kept. +type snapshotShelf interface { + // upload copies the local snapshot at localPath onto the shelf as name. + upload(ctx context.Context, localPath, name string) error + // snapshots lists the snapshot names on the shelf. + snapshots(ctx context.Context) ([]string, error) + remove(ctx context.Context, name string) error +} + +// afterSync is the post-run hook every push calls once the run's terminal +// state is committed. It takes (once) the local snapshot and, with cloud +// enabled, rides a copy along to the shelf openShelf opens; a nil +// openShelf (peer and kopia pushes) keeps the local snapshot only. +// Failures are surfaced on rep.SnapshotErr and never mutate rep.Status — +// the snapshot is defense-in-depth, not part of the sync's success +// contract. A nil receiver (feature disabled) is a no-op. +func (sn *Snapshotter) afterSync(ctx context.Context, rep *Report, openShelf func() (snapshotShelf, error)) { if sn == nil { return } @@ -101,10 +112,10 @@ func (sn *Snapshotter) afterSync(ctx context.Context, rep *Report, vol *config.V // The VACUUM itself failed; there is nothing to ride along. return } - if dest == nil || !sn.cloud { + if openShelf == nil || !sn.cloud { return } - if rideErr := sn.rideAlong(ctx, localPath, dest, vol.Name); rideErr != nil { + if rideErr := sn.rideAlong(ctx, localPath, rep, openShelf); rideErr != nil { rep.SnapshotErr = rideErr } } @@ -138,32 +149,33 @@ func (sn *Snapshotter) ensureLocalSnapshot(ctx context.Context, runID int64) (st return sn.localPath, sn.takeErr } -// rideAlong uploads localPath to //.squirrel-index/ via the -// rclone wrapper, then rotates that per-volume directory to at most +// rideAlong uploads localPath to the destination's +// /.squirrel-index/, then rotates that directory to at most // cloudKeep snapshots. The uploaded copy keeps the snapshot's filename so // the catalog is traceable to its producing run on the destination too. -func (sn *Snapshotter) rideAlong(ctx context.Context, localPath string, dest *config.Destination, volumeName string) error { - dirURI := indexDirURI(dest, volumeName) - name := filepath.Base(localPath) - if err := sn.rcl.copyTo(ctx, localPath, dirURI+"/"+name); err != nil { - return fmt.Errorf("ride-along upload to %s: %w", dest.Name, err) +func (sn *Snapshotter) rideAlong(ctx context.Context, localPath string, rep *Report, openShelf func() (snapshotShelf, error)) error { + shelf, err := openShelf() + if err != nil { + return fmt.Errorf("ride-along to %s: %w", rep.Destination, err) } - if err := sn.rotateCloud(ctx, dirURI); err != nil { - return fmt.Errorf("rotate %s/%s/%s: %w", dest.Name, volumeName, IndexDirName, err) + if err := shelf.upload(ctx, localPath, filepath.Base(localPath)); err != nil { + return fmt.Errorf("ride-along upload to %s: %w", rep.Destination, err) + } + if err := sn.rotateCloud(ctx, shelf); err != nil { + return fmt.Errorf("rotate %s/%s/%s: %w", rep.Destination, rep.Volume, IndexDirName, err) } return nil } -// rotateCloud lists the destination's .squirrel-index/ directory and -// deletes the oldest snapshots until at most cloudKeep remain. Snapshots -// are lexically sortable (decision #3), so "newest N" is the tail of the -// name-sorted list — no per-file metadata read required. cloudKeep<=0 -// means "no rotation". -func (sn *Snapshotter) rotateCloud(ctx context.Context, dirURI string) error { +// rotateCloud deletes the oldest snapshots on the shelf until at most +// cloudKeep remain. Snapshots are lexically sortable (decision #3), so +// "newest N" is the tail of the name-sorted list — no per-file metadata +// read required. cloudKeep<=0 means "no rotation". +func (sn *Snapshotter) rotateCloud(ctx context.Context, shelf snapshotShelf) error { if sn.cloudKeep <= 0 { return nil } - names, err := sn.rcl.listSnapshots(ctx, dirURI) + names, err := shelf.snapshots(ctx) if err != nil { return err } @@ -172,13 +184,87 @@ func (sn *Snapshotter) rotateCloud(ctx context.Context, dirURI string) error { } sort.Strings(names) for _, old := range names[:len(names)-sn.cloudKeep] { - if err := sn.rcl.deleteFile(ctx, dirURI+"/"+old); err != nil { + if err := shelf.remove(ctx, old); err != nil { return err } } return nil } +// isSnapshotName reports whether a file name in .squirrel-index/ is a +// ride-along snapshot, index-*.db, as opposed to a receipt. +func isSnapshotName(name string) bool { + return strings.HasPrefix(name, snapshotPrefix) && strings.HasSuffix(name, ".db") +} + +// rcloneShelf is the .squirrel-index/ directory of a destination rclone +// writes, addressed through the same overlay as its data. +type rcloneShelf struct { + rcl *Rclone + dir string // the directory's rclone URI +} + +func (s rcloneShelf) upload(ctx context.Context, localPath, name string) error { + return s.rcl.copyTo(ctx, localPath, s.dir+"/"+name) +} + +func (s rcloneShelf) snapshots(ctx context.Context) ([]string, error) { + return s.rcl.listSnapshots(ctx, s.dir) +} + +func (s rcloneShelf) remove(ctx context.Context, name string) error { + return s.rcl.deleteFile(ctx, s.dir+"/"+name) +} + +// rcloneShelfOf opens dest's shelf for volumeName through rcl. +func rcloneShelfOf(rcl *Rclone, dest *config.Destination, volumeName string) func() (snapshotShelf, error) { + return func() (snapshotShelf, error) { + return rcloneShelf{rcl: rcl, dir: indexDirURI(dest, volumeName)}, nil + } +} + +// transportShelf is a native mirror's .squirrel-index/ directory, reached +// through the push's guarded transport, whose name guard permits removing +// a snapshot there and nothing else. +type transportShelf struct { + tr transport + dir string +} + +func (s transportShelf) upload(ctx context.Context, localPath, name string) error { + f, err := os.Open(localPath) + if err != nil { + return err + } + defer f.Close() + fi, err := f.Stat() + if err != nil { + return err + } + return s.tr.Put(ctx, path.Join(s.dir, name), f, fi.ModTime()) +} + +func (s transportShelf) snapshots(ctx context.Context) ([]string, error) { + entries, err := s.tr.List(ctx, s.dir) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var names []string + for _, e := range entries { + if e.kind == kindFile && isSnapshotName(e.name) { + names = append(names, e.name) + } + } + return names, nil +} + +func (s transportShelf) remove(ctx context.Context, name string) error { + return s.tr.Remove(ctx, path.Join(s.dir, name)) +} + // indexDirURI returns the rclone URI of the per-volume .squirrel-index/ // directory under dest, addressed the same way the data transfer is // (through the crypt overlay when the destination has one). diff --git a/sync/snapshot_test.go b/sync/snapshot_test.go index 2fbb7a8..26c07ad 100644 --- a/sync/snapshot_test.go +++ b/sync/snapshot_test.go @@ -20,7 +20,7 @@ func (f *syncFixture) snapshotterFor(t *testing.T, cfg SnapshotConfig) *Snapshot if cfg.Dir == "" { cfg.Dir = t.TempDir() } - return NewSnapshotter(f.store, f.rcl, cfg) + return NewSnapshotter(f.store, cfg) } func globOne(t *testing.T, pattern string) string { @@ -174,7 +174,7 @@ func TestSnapshotErrorDoesNotFailSync(t *testing.T) { if err := os.WriteFile(blocker, []byte("x"), 0o644); err != nil { t.Fatal(err) } - sn := NewSnapshotter(f.store, f.rcl, SnapshotConfig{Dir: filepath.Join(blocker, "backups"), Keep: 7, Cloud: true, CloudKeep: 7}) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: filepath.Join(blocker, "backups"), Keep: 7, Cloud: true, CloudKeep: 7}) rep, err := Sync(context.Background(), f.store, f.rcl, f.vol, f.dest, Options{Snapshot: sn}) if err != nil { @@ -397,23 +397,17 @@ func argsHaveFilter(args []string, want string) bool { // TestSnapshotterWithoutRcloneServesPeerPairs pins the coupling that lets // a peer-only or kopia-only sync run on a host with no rclone installed: -// `runSync` now leaves the wrapper nil for such a batch, and the -// Snapshotter is still constructed and still takes its local snapshot. -// Only the destination ride-along needs rclone, and both handlers that -// never have one (peer sync, kopia) pass a nil destination, which -// afterSync returns on before reaching it. -// -// A test rather than a comment because the safety of the nil is a -// cross-package invariant: it holds only as long as every caller reaching -// rideAlong is an rclone-driven handler. +// the Snapshotter holds no rclone wrapper, and the handlers that have no +// ride-along (peer sync, kopia) pass no shelf, so it still takes its local +// snapshot. func TestSnapshotterWithoutRcloneServesPeerPairs(t *testing.T) { f := setupFixture(t) - sn := NewSnapshotter(f.store, nil, SnapshotConfig{ + sn := NewSnapshotter(f.store, SnapshotConfig{ Dir: filepath.Join(t.TempDir(), "backups"), Keep: 7, Cloud: true, CloudKeep: 7, }) rep := &Report{RunID: 1, Status: store.RunStatusSuccess} - sn.afterSync(context.Background(), rep, f.vol, nil) + sn.afterSync(context.Background(), rep, nil) if rep.SnapshotErr != nil { t.Fatalf("SnapshotErr = %v, want the local snapshot to succeed without rclone", rep.SnapshotErr) diff --git a/sync/sync.go b/sync/sync.go index fc2ee30..1e340b7 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -362,7 +362,7 @@ func Sync(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volume, // terminal state by now, so the snapshot reflects this run's own row. // Destination syncs are eligible for the cloud ride-along; the // Snapshotter no-ops on dry-run and on non-terminal-success states. - opts.Snapshot.afterSync(ctx, &rep, vol, dest) + opts.Snapshot.afterSync(ctx, &rep, rcloneShelfOf(rcl, dest, vol.Name)) return rep, err } @@ -935,10 +935,11 @@ func (p Pair) TargetName() string { func (p Pair) IsNode() bool { return p.Node != nil } // DrivesRclone reports whether syncing this pair invokes rclone. Every -// destination does except kopia, which drives its own binary; a peer node -// streams its bytes over the sync API. +// destination does except kopia, which drives its own binary, and a +// native mirror, which squirrel writes itself; a peer node streams its +// bytes over the sync API. func (p Pair) DrivesRclone() bool { - return p.Destination != nil && p.Destination.Type != "kopia" + return p.Destination != nil && p.Destination.Type != "kopia" && !p.Destination.NativeMirror() } // RestoreOptions shape one Restore invocation. ToPath overrides the local diff --git a/sync/transport_guard.go b/sync/transport_guard.go index 5e01d9c..7138332 100644 --- a/sync/transport_guard.go +++ b/sync/transport_guard.go @@ -62,7 +62,7 @@ func (g nameGuard) permit(op guardOp, name, to string) error { func (g nameGuard) removable(name string) bool { if rel, ok := strings.CutPrefix(name, g.volumeDir+"/"+IndexDirName+"/"); ok { - return !strings.Contains(rel, "/") && strings.HasPrefix(rel, snapshotPrefix) && strings.HasSuffix(rel, ".db") + return !strings.Contains(rel, "/") && isSnapshotName(rel) } runID, key, ok := g.stagingParts(name) if !ok || runID == g.runID || !g.finished(runID) { From f5cf92697ed0df58091acf471d9b6b37b6691f23 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 01:28:42 +0200 Subject: [PATCH 16/61] sync: discover and fetch a native mirror's snapshots through the transport MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit recover --from a native mirror lists its /.squirrel-index/ and fetches the chosen snapshot through a read-only transport — the name guard, held by no run, refuses every move and removal — so it needs no rclone and the CLI no longer looks for it. The marker gate and restore read through Get, so the stall bound now covers it: the open, and every Read of the file it returns. A Read runs into the reader's own buffer, so one given up on can finish later without touching the caller's. --- cmd/squirrel/main_test.go | 7 ++++ cmd/squirrel/recover.go | 16 +++------ cmd/squirrel/recover_test.go | 8 ++--- cmd/squirrel/sync.go | 17 ++++++++++ sync/handler.go | 15 +++++++++ sync/mirror.go | 8 ++++- sync/mirror_sftp_test.go | 31 ++++++++++++++++++ sync/recover.go | 57 +++++++++++++++++++++++++++----- sync/transport_stall.go | 50 ++++++++++++++++++++++++++++ sync/transport_stall_test.go | 63 ++++++++++++++++++++++++++++++++++++ 10 files changed, 248 insertions(+), 24 deletions(-) create mode 100644 sync/transport_stall_test.go diff --git a/cmd/squirrel/main_test.go b/cmd/squirrel/main_test.go index 58a40b9..db472b5 100644 --- a/cmd/squirrel/main_test.go +++ b/cmd/squirrel/main_test.go @@ -24,6 +24,13 @@ func requireRcloneCLI(t *testing.T) { } } +// withoutRclone hides rclone from the test: PATH names only an empty +// directory, so a command that reached for rclone would fail to find it. +func withoutRclone(t *testing.T) { + t.Helper() + t.Setenv("PATH", t.TempDir()) +} + // syncFixturePaths bundles the paths writeSyncFixture lays down so callers // can pass them straight to the CLI via --config / --db. type syncFixturePaths struct { diff --git a/cmd/squirrel/recover.go b/cmd/squirrel/recover.go index c740bb8..fb8b541 100644 --- a/cmd/squirrel/recover.go +++ b/cmd/squirrel/recover.go @@ -70,6 +70,7 @@ type recoverOptions struct { // before agreeing to its first step. type recoverPlan struct { dest *config.Destination + rcl *sync.Rclone // nil for a native mirror, which squirrel reads itself volumes []string snapshots []sync.IndexSnapshot chosen sync.IndexSnapshot @@ -123,14 +124,11 @@ func discoverRecovery(cmd *cobra.Command, cfg *config.Config, opts recoverOption cfg.Path, opts.From) } - rcl, err := sync.Find(cmd.Context()) - if err != nil { - return recoverPlan{}, err - } - if err := writeRcloneConfigLogged(cmd.OutOrStdout(), rcl, cfg); err != nil { + var err error + if plan.rcl, err = rcloneFor(cmd, cfg, dest); err != nil { return recoverPlan{}, err } - plan.snapshots, err = sync.DiscoverIndexSnapshots(cmd.Context(), rcl, dest, plan.volumes) + plan.snapshots, err = sync.DiscoverIndexSnapshots(cmd.Context(), plan.rcl, dest, plan.volumes) if err != nil { return recoverPlan{}, err } @@ -242,10 +240,6 @@ func recoverIndexPhase(cmd *cobra.Command, plan recoverPlan, opts recoverOptions return false, nil } - rcl, err := sync.Find(cmd.Context()) - if err != nil { - return false, err - } dir, err := os.MkdirTemp("", "squirrel-recover-") if err != nil { return false, fmt.Errorf("create staging directory: %w", err) @@ -254,7 +248,7 @@ func recoverIndexPhase(cmd *cobra.Command, plan recoverPlan, opts recoverOptions staged := filepath.Join(dir, plan.chosen.Name) fmt.Fprintf(out, "fetching %s …\n", plan.chosen.Name) - if err := sync.FetchIndexSnapshot(cmd.Context(), rcl, plan.dest, plan.chosen, staged); err != nil { + if err := sync.FetchIndexSnapshot(cmd.Context(), plan.rcl, plan.dest, plan.chosen, staged); err != nil { return false, err } // runDBRestore preflights the schema version, refuses to clobber a live diff --git a/cmd/squirrel/recover_test.go b/cmd/squirrel/recover_test.go index dcd9cb7..ef250ba 100644 --- a/cmd/squirrel/recover_test.go +++ b/cmd/squirrel/recover_test.go @@ -76,7 +76,7 @@ func TestRecoverRejectsPeerNode(t *testing.T) { // catalog is a real state, and the message has to say what is still // possible rather than only what failed. func TestRecoverWithoutSnapshotsExplains(t *testing.T) { - requireRcloneCLI(t) // discovery lists the destination through rclone + withoutRclone(t) // a local mirror is read through squirrel's own transport cfgPath, _ := recoverConfig(t) out, err := runCLIExpectErr(t, "--config", cfgPath, "recover", "--from", "scratch") joined := out + err.Error() @@ -93,7 +93,7 @@ func TestRecoverWithoutSnapshotsExplains(t *testing.T) { // runs `squirrel recover --from X` to find out what is there must not // discover they have started a recovery. func TestRecoverDryRunTouchesNothing(t *testing.T) { - requireRcloneCLI(t) // discovery lists the destination through rclone + withoutRclone(t) // a local mirror is read through squirrel's own transport cfgPath, destRoot := recoverConfig(t) newest := "index-20260807T120000.000Z-run-42.db" seedSnapshots(t, destRoot, "photos", "index-20260101T090000.000Z-run-7.db", newest) @@ -119,7 +119,7 @@ func TestRecoverDryRunTouchesNothing(t *testing.T) { // TestRecoverRejectsUnknownSnapshot: naming a snapshot that is not there // stops before any fetch, and says how to see the real list. func TestRecoverRejectsUnknownSnapshot(t *testing.T) { - requireRcloneCLI(t) // discovery lists the destination through rclone + withoutRclone(t) // a local mirror is read through squirrel's own transport cfgPath, destRoot := recoverConfig(t) seedSnapshots(t, destRoot, "photos", "index-20260807T120000.000Z-run-42.db") @@ -171,7 +171,7 @@ func TestSnapshotAgeUnknownIsSaid(t *testing.T) { // which is itself the property worth pinning: absence of an answer is not // consent. func TestRecoverDeclinedPhaseStopsTheSequence(t *testing.T) { - requireRcloneCLI(t) // discovery lists the destination through rclone + withoutRclone(t) // a local mirror is read through squirrel's own transport cfgPath, destRoot := recoverConfig(t) seedSnapshots(t, destRoot, "photos", "index-20260807T120000.000Z-run-42.db") diff --git a/cmd/squirrel/sync.go b/cmd/squirrel/sync.go index b9d9a57..62ef097 100644 --- a/cmd/squirrel/sync.go +++ b/cmd/squirrel/sync.go @@ -152,6 +152,23 @@ func rcloneConfigPathFor(cfg *config.Config) string { return filepath.Join(filepath.Dir(cfg.Path), "rclone.conf") } +// rcloneFor locates rclone and renders its config for reading dest. A +// native mirror is read through squirrel's own transport, so it gets a nil +// wrapper and no rclone preamble. +func rcloneFor(cmd *cobra.Command, cfg *config.Config, dest *config.Destination) (*sync.Rclone, error) { + if dest.NativeMirror() { + return nil, nil + } + rcl, err := sync.Find(cmd.Context()) + if err != nil { + return nil, err + } + if err := writeRcloneConfigLogged(cmd.OutOrStdout(), rcl, cfg); err != nil { + return nil, err + } + return rcl, nil +} + // writeRcloneConfigLogged renders the rclone.conf and logs a single line // when the file actually changed. An unexpected rewrite is worth // surfacing: the config is derived deterministically from squirrel's diff --git a/sync/handler.go b/sync/handler.go index 25b6ff5..f548572 100644 --- a/sync/handler.go +++ b/sync/handler.go @@ -153,6 +153,21 @@ func openDestinationTransport(ctx context.Context, dest *config.Destination) (tr return openLocalTransport(dest.Root) } +// openReadOnly opens a native mirror's root for reading alone: the name +// guard, held by no run, refuses every move and removal, and every call is +// bounded by progress. +func openReadOnly(ctx context.Context, dest *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, dest) + if err != nil { + return nil, err + } + return stallTransport{ + transport: guardedTransport{transport: raw}, + timeout: DefaultStallTimeout, + stalled: stalledCounter(dest.Name), + }, nil +} + // rcloneHandler pushes to an rclone-backed bucket destination via Sync. type rcloneHandler struct { store *store.Store diff --git a/sync/mirror.go b/sync/mirror.go index 5d2d275..b8ec2d5 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -195,7 +195,13 @@ func (h *mirrorHandler) shelf(ctx context.Context, runID int64) (snapshotShelf, if err != nil { return nil, err } - return transportShelf{tr: tr, dir: path.Join(h.vol.Name, IndexDirName)}, nil + return mirrorShelf(tr, h.vol.Name), nil +} + +// mirrorShelf is volume's .squirrel-index/ on a native mirror reached +// through tr. +func mirrorShelf(tr transport, volume string) transportShelf { + return transportShelf{tr: tr, dir: path.Join(volume, IndexDirName)} } func (h *mirrorHandler) receiptName(runID int64) string { diff --git a/sync/mirror_sftp_test.go b/sync/mirror_sftp_test.go index 7d7fea9..d0b8f5b 100644 --- a/sync/mirror_sftp_test.go +++ b/sync/mirror_sftp_test.go @@ -1,6 +1,7 @@ package sync import ( + "context" "errors" "os" "path/filepath" @@ -118,3 +119,33 @@ func TestMirrorRideAlongThroughTheTransport(t *testing.T) { }) } } + +// TestRecoverFindsAMirrorsSnapshots: recover's discovery lists a native +// mirror's ride-along snapshots and fetches one through the transport, +// with no rclone wrapper, on both backends. +func TestRecoverFindsAMirrorsSnapshots(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "alpha") + f.index(t) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) + rep, err := f.push(t, Options{Snapshot: sn}) + if err != nil || rep.SnapshotErr != nil { + t.Fatalf("push: err=%v snapshot=%v", err, rep.SnapshotErr) + } + ctx := context.Background() + snaps, err := DiscoverIndexSnapshots(ctx, nil, f.pair.Destination, []string{"pics", "never-synced"}) + if err != nil || len(snaps) != 1 || snaps[0].RunID != rep.RunID { + t.Fatalf("discovery = %+v, %v; want run %d's snapshot", snaps, err, rep.RunID) + } + local := filepath.Join(t.TempDir(), snaps[0].Name) + if err := FetchIndexSnapshot(ctx, nil, f.pair.Destination, snaps[0], local); err != nil { + t.Fatalf("fetch: %v", err) + } + if fileHash(t, local) != fileHash(t, f.dest(IndexDirName+"/"+snaps[0].Name)) { + t.Fatal("the fetched snapshot differs from the one on the destination") + } + }) + } +} diff --git a/sync/recover.go b/sync/recover.go index 4208b9f..ab08401 100644 --- a/sync/recover.go +++ b/sync/recover.go @@ -3,6 +3,9 @@ package sync import ( "context" "fmt" + "io" + "os" + "path" "sort" "strconv" "strings" @@ -43,15 +46,25 @@ func (s IndexSnapshot) Age(now time.Time) (time.Duration, bool) { // DiscoverIndexSnapshots lists the ride-along index snapshots a destination // holds for each named volume, newest first, then by volume. It is // read-only: it lists, it does not fetch, so an operator can be told what -// is recoverable before anything is touched. +// is recoverable before anything is touched. A native mirror is listed +// through squirrel's own transport, so rcl may be nil for one. // // A volume directory that does not exist yields no snapshots rather than an // error — a destination that has simply never carried a given volume is a // normal answer to "what do you have", not a failure. func DiscoverIndexSnapshots(ctx context.Context, rcl *Rclone, dest *config.Destination, volumes []string) ([]IndexSnapshot, error) { + list := func(vol string) ([]string, error) { return listSnapshotsStrict(ctx, rcl, indexDirURI(dest, vol)) } + if dest.NativeMirror() { + tr, err := openReadOnly(ctx, dest) + if err != nil { + return nil, err + } + defer func() { _ = tr.Close() }() + list = func(vol string) ([]string, error) { return mirrorShelf(tr, vol).snapshots(ctx) } + } var out []IndexSnapshot for _, vol := range volumes { - names, err := listSnapshotsStrict(ctx, rcl, indexDirURI(dest, vol)) + names, err := list(vol) if err != nil { return nil, fmt.Errorf("list index snapshots for %s/%s: %w", dest.Name, vol, err) } @@ -128,14 +141,42 @@ func parseSnapshotName(volume, name string) IndexSnapshot { return snap } -// FetchIndexSnapshot downloads one snapshot to localPath. It only moves the -// file; validating that the bytes are a usable index at this binary's -// schema version is store.PreflightCheckSnapshot's job, and the caller runs -// it before letting the file near the live database. +// FetchIndexSnapshot downloads one snapshot to localPath, which must not +// exist yet. It only moves the file; validating that the bytes are a +// usable index at this binary's schema version is +// store.PreflightCheckSnapshot's job, and the caller runs it before letting +// the file near the live database. rcl may be nil for a native mirror. func FetchIndexSnapshot(ctx context.Context, rcl *Rclone, dest *config.Destination, snap IndexSnapshot, localPath string) error { - uri := indexDirURI(dest, snap.Volume) + "/" + snap.Name - if err := rcl.copyTo(ctx, uri, localPath); err != nil { + var err error + if dest.NativeMirror() { + err = fetchThroughTransport(ctx, dest, path.Join(snap.Volume, IndexDirName, snap.Name), localPath) + } else { + err = rcl.copyTo(ctx, indexDirURI(dest, snap.Volume)+"/"+snap.Name, localPath) + } + if err != nil { return fmt.Errorf("fetch index snapshot %s from %s: %w", snap.Name, dest.Name, err) } return nil } + +func fetchThroughTransport(ctx context.Context, dest *config.Destination, name, localPath string) error { + tr, err := openReadOnly(ctx, dest) + if err != nil { + return err + } + defer func() { _ = tr.Close() }() + rc, err := tr.Get(ctx, name) + if err != nil { + return err + } + defer func() { _ = rc.Close() }() + f, err := os.OpenFile(localPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return err + } + if _, err := io.Copy(f, ctxReader{ctx: ctx, r: rc}); err != nil { + _ = f.Close() + return err + } + return f.Close() +} diff --git a/sync/transport_stall.go b/sync/transport_stall.go index 619cc22..fd22d6c 100644 --- a/sync/transport_stall.go +++ b/sync/transport_stall.go @@ -92,6 +92,18 @@ func (s stallTransport) List(ctx context.Context, dir string) ([]entry, error) { }) } +// Get bounds the open, and every Read of the file it returns, by the same +// allowance. +func (s stallTransport) Get(ctx context.Context, name string) (io.ReadCloser, error) { + rc, err := bounded(ctx, s, "get "+name, func(ctx context.Context, _ func(time.Duration)) (io.ReadCloser, error) { + return s.transport.Get(ctx, name) + }) + if err != nil { + return nil, err + } + return &stallReader{ctx: ctx, s: s, name: name, rc: rc}, nil +} + func (s stallTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { _, err := bounded(ctx, s, "put "+name, func(ctx context.Context, progress func(time.Duration)) (struct{}, error) { return struct{}{}, s.transport.Put(ctx, name, &progressingReader{r: r, timeout: s.timeout, progress: progress}, mtime) @@ -113,6 +125,44 @@ func (s stallTransport) Remove(ctx context.Context, name string) error { return err } +// stallReader bounds each Read of a file Get opened. A Read runs into the +// reader's own buffer, so one given up on can finish later without +// touching the caller's; after that the reader only reports the stall. +type stallReader struct { + ctx context.Context + s stallTransport + name string + rc io.ReadCloser + buf []byte + err error // the stall, once one happened +} + +func (r *stallReader) Read(p []byte) (int, error) { + if r.err != nil { + return 0, r.err + } + if cap(r.buf) < len(p) { + r.buf = make([]byte, len(p)) + } + buf := r.buf[:len(p)] + n, err := bounded(r.ctx, r.s, "read "+r.name, func(context.Context, func(time.Duration)) (int, error) { + return r.rc.Read(buf) + }) + if errors.Is(err, errTransportStalled) { + r.err = err + return 0, err + } + return copy(p, buf[:n]), err +} + +func (r *stallReader) Close() error { + if r.err != nil { + go func() { _ = r.rc.Close() }() + return nil + } + return r.rc.Close() +} + // progressingReader reports each chunk it reads as progress, and at the // end of the body allows the final sync time to flush what it read. type progressingReader struct { diff --git a/sync/transport_stall_test.go b/sync/transport_stall_test.go new file mode 100644 index 0000000..7ee578e --- /dev/null +++ b/sync/transport_stall_test.go @@ -0,0 +1,63 @@ +package sync + +import ( + "context" + "errors" + "io" + "strings" + "sync/atomic" + "testing" + "time" +) + +// hangingReads is a transport whose files read their first bytes, then +// hang until release is closed. +type hangingReads struct { + transport + release chan struct{} +} + +func (h hangingReads) Get(context.Context, string) (io.ReadCloser, error) { + return io.NopCloser(io.MultiReader(strings.NewReader("first"), blockUntil(h.release))), nil +} + +type blockUntil chan struct{} + +func (b blockUntil) Read([]byte) (int, error) { + <-b + return 0, io.EOF +} + +// TestStallBoundsEveryRead: a file whose reads stop making progress fails +// with errTransportStalled once the allowance runs out, keeps failing, +// and counts as a call given up on until the read finally returns. +func TestStallBoundsEveryRead(t *testing.T) { + release := make(chan struct{}) + stalled := new(atomic.Int64) + s := stallTransport{transport: hangingReads{release: release}, timeout: 50 * time.Millisecond, stalled: stalled} + rc, err := s.Get(context.Background(), "f") + if err != nil { + t.Fatalf("Get: %v", err) + } + buf := make([]byte, 16) + if n, err := rc.Read(buf); err != nil || string(buf[:n]) != "first" { + t.Fatalf("first Read = %q, %v; want the bytes that were there", buf[:n], err) + } + if _, err := rc.Read(buf); !errors.Is(err, errTransportStalled) { + t.Fatalf("hanging Read = %v, want errTransportStalled", err) + } + if _, err := rc.Read(buf); !errors.Is(err, errTransportStalled) { + t.Fatalf("Read after a stall = %v, want the stall again", err) + } + if stalled.Load() != 1 { + t.Fatalf("calls given up on = %d, want 1", stalled.Load()) + } + _ = rc.Close() + close(release) + for deadline := time.Now().Add(5 * time.Second); stalled.Load() > 0 && time.Now().Before(deadline); { + time.Sleep(10 * time.Millisecond) + } + if stalled.Load() != 0 { + t.Fatal("the read that finally returned is still counted as outstanding") + } +} From 45be05ecac3869de4e42cc36c73bbbbaef9e50cd Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 01:36:09 +0200 Subject: [PATCH 17/61] sync: restore each file through a temporary file beside its path Archive restore wrote each file with O_TRUNC in place: a crash or a broken stream left a truncated file at the path. The new restorePlacer streams the bytes into a temporary file in the target directory while it hashes them, checks them, stamps the mtime, flushes, and only then renames the file over the path, moving the old one into the run's restore history first on an in-place restore. Bytes that fail their check never reach a path, and no temporary file stays behind. The native mirror restore will place through the same code. --- sync/restore_archive.go | 168 ++++++++++--------------------------- sync/restore_place.go | 150 +++++++++++++++++++++++++++++++++ sync/restore_place_test.go | 103 +++++++++++++++++++++++ 3 files changed, 299 insertions(+), 122 deletions(-) create mode 100644 sync/restore_place.go create mode 100644 sync/restore_place_test.go diff --git a/sync/restore_archive.go b/sync/restore_archive.go index 1e6b977..ddbb1f7 100644 --- a/sync/restore_archive.go +++ b/sync/restore_archive.go @@ -6,14 +6,11 @@ import ( "cmp" "context" "encoding/hex" - "errors" "fmt" "io" "os" "path" - "path/filepath" "slices" - "strconv" "time" "github.com/klauspost/compress/zstd" @@ -33,15 +30,13 @@ import ( // offset/length pack slicing needs. Packs are fetched once per pack and // every requested member is extracted from that single stream. type archiveRestore struct { - store *store.Store - rcl *Rclone - vol *config.Volume - dest *config.Destination - volID int64 - runID int64 - target string // resolved local directory (vol.Path or --to) - preserve bool // move overwritten files to .squirrel-restore-history/ - dryRun bool + store *store.Store + rcl *Rclone + vol *config.Volume + dest *config.Destination + volID int64 + placer restorePlacer + dryRun bool } // restoreArchive orchestrates one content-addressed or packed restore: it @@ -51,28 +46,35 @@ type archiveRestore struct { // reason. Read-only against the index and destination throughout. func restoreArchive(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volume, dest *config.Destination, volID, runID int64, targetInPlace bool, opts RestoreOptions, rep *Report) error { rep.RunID = runID + ar := &archiveRestore{ + store: s, rcl: rcl, vol: vol, dest: dest, volID: volID, + placer: newRestorePlacer(vol, runID, targetInPlace, opts), dryRun: opts.DryRun, + } + runErr := ar.run(ctx, rep, opts.IncludeFromFile) + finishRestore(ctx, s, opts.DryRun, runID, rep, runErr) + return runErr +} + +// newRestorePlacer targets the volume's path, or --to. It preserves what +// it replaces only for an in-place restore that asked to (--in-place), +// mirroring the mirror layout's history contract. +func newRestorePlacer(vol *config.Volume, runID int64, targetInPlace bool, opts RestoreOptions) restorePlacer { target := vol.Path if opts.ToPath != "" { target = opts.ToPath } - ar := newArchiveRestore(s, rcl, vol, dest, volID, runID, target, targetInPlace && opts.InPlace, opts.DryRun) - runErr := ar.run(ctx, rep, opts.IncludeFromFile) + return restorePlacer{target: target, runID: runID, preserve: targetInPlace && opts.InPlace} +} + +// finishRestore writes a restore run's terminal state. A fatal error +// (nothing counted as an individual failure) is turned into a synthesised +// failed-file so the runs row carries the reason. +func finishRestore(ctx context.Context, s *store.Store, dryRun bool, runID int64, rep *Report, runErr error) { if runErr != nil && rep.RcloneResult.Errors == 0 { rep.RcloneResult.FatalError = true rep.RcloneResult.FailedFiles = append(rep.RcloneResult.FailedFiles, FailedFile{Message: runErr.Error()}) } - finishRun(ctx, s, opts.DryRun, runID, rep) - return runErr -} - -// newArchiveRestore builds the restorer. preserve is set only for an -// in-place restore that must keep any overwritten bytes, mirroring the -// mirror layout's --backup-dir contract. -func newArchiveRestore(s *store.Store, rcl *Rclone, vol *config.Volume, dest *config.Destination, volID, runID int64, target string, preserve, dryRun bool) *archiveRestore { - return &archiveRestore{ - store: s, rcl: rcl, vol: vol, dest: dest, - volID: volID, runID: runID, target: target, preserve: preserve, dryRun: dryRun, - } + finishRun(ctx, s, dryRun, runID, rep) } // restoreContent is one content to restore and the volume-relative paths it @@ -224,17 +226,17 @@ func (ar *archiveRestore) restoreObject(ctx context.Context, rep *Report, c rest } tmp, err := ar.fetch(ctx, path.Join(ObjectsDirName, namerFor(ar.dest).object(c.blake3))) if err != nil { - ar.recordFailure(rep, c.firstPath(), err) + recordRestoreFailure(rep, c.firstPath(), err) return } defer func() { _ = os.Remove(tmp) }() digest, err := hashLocalFile(tmp) if err != nil { - ar.recordFailure(rep, c.firstPath(), fmt.Errorf("re-hash object: %w", err)) + recordRestoreFailure(rep, c.firstPath(), fmt.Errorf("re-hash object: %w", err)) return } if !bytes.Equal(digest, c.blake3) { - ar.recordFailure(rep, c.firstPath(), fmt.Errorf("object hashes to %s, want %s", hex.EncodeToString(digest), hex.EncodeToString(c.blake3))) + recordRestoreFailure(rep, c.firstPath(), fmt.Errorf("object hashes to %s, want %s", hex.EncodeToString(digest), hex.EncodeToString(c.blake3))) return } ar.place(rep, tmp, c) @@ -296,7 +298,7 @@ func (ar *archiveRestore) extractMembers(rep *Report, packTmp string, members [] } if !bytes.Equal(digest, m.content.blake3) { _ = os.Remove(memberTmp) - ar.recordFailure(rep, m.content.firstPath(), fmt.Errorf("pack member hashes to %s, want %s", hex.EncodeToString(digest), hex.EncodeToString(m.content.blake3))) + recordRestoreFailure(rep, m.content.firstPath(), fmt.Errorf("pack member hashes to %s, want %s", hex.EncodeToString(digest), hex.EncodeToString(m.content.blake3))) continue } ar.place(rep, memberTmp, m.content) @@ -353,8 +355,8 @@ func (ar *archiveRestore) fetch(ctx context.Context, subpath string) (string, er // failure is recorded and does not stop the others. func (ar *archiveRestore) place(rep *Report, srcTmp string, c restoreContent) { for _, p := range c.paths { - if err := ar.writeOne(p, srcTmp); err != nil { - ar.recordFailure(rep, p.rel, err) + if err := ar.writeOne(p, srcTmp, c.blake3); err != nil { + recordRestoreFailure(rep, p.rel, err) continue } rep.RcloneResult.Transferred++ @@ -362,72 +364,16 @@ func (ar *archiveRestore) place(rep *Report, srcTmp string, c restoreContent) { } } -// writeOne copies the verified bytes to /, creating parent -// directories, refusing to write over a non-regular file (symlink, device, -// directory, …), preserving any overwritten regular file for an in-place -// restore, and stamping the index-recorded mtime. -func (ar *archiveRestore) writeOne(p restorePath, srcTmp string) error { - dst := filepath.Join(ar.target, filepath.FromSlash(p.rel)) - if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { - return fmt.Errorf("create target dir: %w", err) - } - if err := refuseNonRegularTarget(p.rel, dst); err != nil { - return err - } - if ar.preserve { - if err := ar.backupExisting(p.rel, dst); err != nil { - return err - } - } - if err := copyFileContents(srcTmp, dst); err != nil { - return err - } - t := time.Unix(0, p.mtimeNs) - if err := os.Chtimes(dst, t, t); err != nil { - return fmt.Errorf("set mtime on %s: %w", p.rel, err) - } - return nil -} - -// refuseNonRegularTarget refuses to write when the destination already -// exists as anything other than a regular file. Writing through a symlink -// with os.OpenFile would follow it and could clobber a path *outside* the -// restore target — a data-loss path squirrel must never take — so an -// existing symlink, device, fifo, socket, or directory is a hard refusal, -// not a silent skip. An absent path or a plain regular file is allowed. -func refuseNonRegularTarget(rel, dst string) error { - info, err := os.Lstat(dst) - if errors.Is(err, os.ErrNotExist) { - return nil - } +// writeOne places the bytes at srcTmp at p, re-checked against want and +// stamped with the index-recorded mtime. +func (ar *archiveRestore) writeOne(p restorePath, srcTmp string, want []byte) error { + f, err := os.Open(srcTmp) if err != nil { - return fmt.Errorf("stat target %s: %w", rel, err) - } - if !info.Mode().IsRegular() { - return fmt.Errorf("refusing to write %s: destination already exists as a non-regular file (%s) — squirrel will not follow or replace it", rel, info.Mode().Type()) - } - return nil -} - -// backupExisting moves an existing regular file at dst under the per-run -// restore-history subtree so an in-place overwrite never destroys prior -// bytes — the local-side counterpart of sync's --backup-dir. The caller -// has already refused any non-regular destination, so dst is absent or a -// regular file here. -func (ar *archiveRestore) backupExisting(rel, dst string) error { - if _, err := os.Lstat(dst); errors.Is(err, os.ErrNotExist) { - return nil - } else if err != nil { - return fmt.Errorf("stat existing %s: %w", rel, err) - } - backup := filepath.Join(ar.target, RestoreHistoryDirName, "run-"+strconv.FormatInt(ar.runID, 10), filepath.FromSlash(rel)) - if err := os.MkdirAll(filepath.Dir(backup), 0o755); err != nil { - return fmt.Errorf("create restore-history dir: %w", err) - } - if err := os.Rename(dst, backup); err != nil { - return fmt.Errorf("preserve overwritten %s: %w", rel, err) + return fmt.Errorf("open restored bytes: %w", err) } - return nil + defer func() { _ = f.Close() }() + _, err = ar.placer.place(p.rel, f, want, time.Unix(0, p.mtimeNs)) + return err } // countContent tallies the files (and bytes) a content would restore, @@ -437,8 +383,9 @@ func (ar *archiveRestore) countContent(rep *Report, c restoreContent) { rep.RcloneResult.Bytes += c.size * int64(len(c.paths)) } -// recordFailure counts one failed content and captures its message (capped). -func (ar *archiveRestore) recordFailure(rep *Report, object string, err error) { +// recordRestoreFailure counts one failed restore item and captures its +// message (capped). +func recordRestoreFailure(rep *Report, object string, err error) { rep.RcloneResult.Errors++ if int64(len(rep.RcloneResult.FailedFiles)) < maxFailedFiles { rep.RcloneResult.FailedFiles = append(rep.RcloneResult.FailedFiles, FailedFile{Object: object, Message: err.Error()}) @@ -449,7 +396,7 @@ func (ar *archiveRestore) recordFailure(rep *Report, object string, err error) { // used when a whole pack could not be fetched or its stream broke. func (ar *archiveRestore) failMembers(rep *Report, members []packMemberRestore, err error) { for _, m := range members { - ar.recordFailure(rep, m.content.firstPath(), err) + recordRestoreFailure(rep, m.content.firstPath(), err) } } @@ -475,26 +422,3 @@ func loadIncludeSet(pathname string) (map[string]bool, error) { } return set, nil } - -// copyFileContents writes src's bytes to dst, truncating an existing file. -// The bytes are already BLAKE3-verified by the caller, so a plain copy is -// safe. -func copyFileContents(src, dst string) error { - in, err := os.Open(src) - if err != nil { - return fmt.Errorf("open restored bytes: %w", err) - } - defer func() { _ = in.Close() }() - out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) - if err != nil { - return fmt.Errorf("create %s: %w", dst, err) - } - if _, err := io.Copy(out, in); err != nil { - _ = out.Close() - return fmt.Errorf("write %s: %w", dst, err) - } - if err := out.Close(); err != nil { - return fmt.Errorf("close %s: %w", dst, err) - } - return nil -} diff --git a/sync/restore_place.go b/sync/restore_place.go new file mode 100644 index 0000000..b8c95bf --- /dev/null +++ b/sync/restore_place.go @@ -0,0 +1,150 @@ +package sync + +import ( + "bytes" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "time" + + "github.com/zeebo/blake3" +) + +// restorePlacer lands restored files in a target tree. Each file streams +// into a temporary file beside its path while it is hashed, is checked, +// stamped and flushed, and is then renamed over the path: a crash never +// leaves a half-written file at a path, and bytes that fail their check +// never reach one. With preserve, a file the path already held first moves +// into .squirrel-restore-history/run-/. +type restorePlacer struct { + target string + runID int64 + preserve bool +} + +// place writes the bytes r yields to rel, stamped with mtime. want, when +// set, is the BLAKE3 they must hash to; nil places them unchecked. It +// returns how many bytes it placed. +func (pl restorePlacer) place(rel string, r io.Reader, want []byte, mtime time.Time) (int64, error) { + dst := pl.path(rel) + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + return 0, fmt.Errorf("create target dir: %w", err) + } + if err := refuseNonRegularTarget(rel, dst); err != nil { + return 0, err + } + tmp, n, err := stageRestored(dst, r, want, mtime) + if err != nil { + return 0, fmt.Errorf("restore %s: %w", rel, err) + } + if err := pl.commit(rel, dst, tmp); err != nil { + _ = os.Remove(tmp) + return 0, err + } + return n, nil +} + +func (pl restorePlacer) path(rel string) string { + return filepath.Join(pl.target, filepath.FromSlash(rel)) +} + +// stageRestored streams r into a fresh temporary file beside dst while +// hashing it, and returns the file's name once its bytes check out, carry +// mtime, and are flushed to disk. +func stageRestored(dst string, r io.Reader, want []byte, mtime time.Time) (string, int64, error) { + f, err := os.CreateTemp(filepath.Dir(dst), ".squirrel-restore-*") + if err != nil { + return "", 0, err + } + h := blake3.New() + n, err := io.Copy(io.MultiWriter(f, h), r) + if err == nil && want != nil && !bytes.Equal(h.Sum(nil), want) { + err = fmt.Errorf("the bytes hash to %s, want %s", hex.EncodeToString(h.Sum(nil)), hex.EncodeToString(want)) + } + if err == nil { + err = os.Chtimes(f.Name(), mtime, mtime) + } + if err == nil { + err = f.Sync() + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + _ = os.Remove(f.Name()) + return "", 0, err + } + return f.Name(), n, nil +} + +// commit renames the staged file over rel, first moving a file rel holds +// aside when the restore preserves what it replaces. +func (pl restorePlacer) commit(rel, dst, tmp string) error { + if pl.preserve { + if err := pl.backupExisting(rel, dst); err != nil { + return err + } + } + if err := os.Rename(tmp, dst); err != nil { + return fmt.Errorf("place %s: %w", rel, err) + } + return syncLocalDir(filepath.Dir(dst)) +} + +// backupExisting moves an existing regular file at dst under the per-run +// restore-history subtree so an in-place restore never destroys prior +// bytes — the local-side counterpart of a mirror's .squirrel-history. The +// caller has already refused any non-regular destination, so dst is absent +// or a regular file here. +func (pl restorePlacer) backupExisting(rel, dst string) error { + if _, err := os.Lstat(dst); errors.Is(err, os.ErrNotExist) { + return nil + } else if err != nil { + return fmt.Errorf("stat existing %s: %w", rel, err) + } + backup := filepath.Join(pl.target, RestoreHistoryDirName, "run-"+strconv.FormatInt(pl.runID, 10), filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(backup), 0o755); err != nil { + return fmt.Errorf("create restore-history dir: %w", err) + } + if err := os.Rename(dst, backup); err != nil { + return fmt.Errorf("preserve overwritten %s: %w", rel, err) + } + return nil +} + +// refuseNonRegularTarget refuses to write when the destination already +// exists as anything other than a regular file. A symlink, device, fifo, +// socket, or directory is a hard refusal, not a silent skip: squirrel +// never replaces what it does not understand. An absent path or a plain +// regular file is allowed. +func refuseNonRegularTarget(rel, dst string) error { + info, err := os.Lstat(dst) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("stat target %s: %w", rel, err) + } + if !info.Mode().IsRegular() { + return fmt.Errorf("refusing to write %s: destination already exists as a non-regular file (%s) — squirrel will not follow or replace it", rel, info.Mode().Type()) + } + return nil +} + +// syncLocalDir flushes a directory of this machine, so a name moved into +// it survives a power cut. +func syncLocalDir(dir string) error { + f, err := os.Open(dir) + if err != nil { + return fmt.Errorf("open %s to sync it: %w", dir, err) + } + defer func() { _ = f.Close() }() + if err := f.Sync(); err != nil && !dirSyncUnsupported(err) { + return fmt.Errorf("sync %s: %w", dir, err) + } + return nil +} diff --git a/sync/restore_place_test.go b/sync/restore_place_test.go new file mode 100644 index 0000000..00e0415 --- /dev/null +++ b/sync/restore_place_test.go @@ -0,0 +1,103 @@ +package sync + +import ( + "errors" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/zeebo/blake3" +) + +func blake3Of(s string) []byte { + sum := blake3.Sum256([]byte(s)) + return sum[:] +} + +// placeFixture is a target directory whose a.txt holds "old". +func placeFixture(t *testing.T, preserve bool) (restorePlacer, string) { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "a.txt"), []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + return restorePlacer{target: dir, runID: 7, preserve: preserve}, dir +} + +// onlyFiles asserts dir holds exactly the named entries: no temporary +// file was left behind. +func onlyFiles(t *testing.T, dir string, want ...string) { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + var got []string + for _, e := range entries { + got = append(got, e.Name()) + } + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("%s holds %v, want %v", dir, got, want) + } +} + +func readFile(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// TestPlaceNeverLeavesAPartialFile: bytes that stop mid-stream, or that +// fail their check, never reach the path, and no temporary file stays. +func TestPlaceNeverLeavesAPartialFile(t *testing.T) { + pl, dir := placeFixture(t, false) + broken := io.MultiReader(strings.NewReader("new"), iotestErrReader{}) + if _, err := pl.place("a.txt", broken, nil, time.Now()); err == nil { + t.Fatal("place of a broken stream succeeded") + } + if _, err := pl.place("a.txt", strings.NewReader("new"), blake3Of("other"), time.Now()); err == nil || !strings.Contains(err.Error(), "hash") { + t.Fatalf("place of mismatching bytes = %v, want a hash refusal", err) + } + if got := readFile(t, filepath.Join(dir, "a.txt")); got != "old" { + t.Fatalf("a.txt = %q after refused places, want old", got) + } + onlyFiles(t, dir, "a.txt") +} + +type iotestErrReader struct{} + +func (iotestErrReader) Read([]byte) (int, error) { return 0, errors.New("the stream broke") } + +// TestPlaceReplacesOrPreserves: a scratch restore renames the new bytes +// over the path; an in-place one first moves the old file into the run's +// restore history. Either way the path ends up with the new bytes and +// their mtime. +func TestPlaceReplacesOrPreserves(t *testing.T) { + mtime := time.Date(2024, 5, 6, 7, 8, 9, 0, time.UTC) + for _, preserve := range []bool{false, true} { + pl, dir := placeFixture(t, preserve) + n, err := pl.place("a.txt", strings.NewReader("new!"), blake3Of("new!"), mtime) + if err != nil || n != 4 { + t.Fatalf("preserve=%v: place = %d, %v", preserve, n, err) + } + dst := filepath.Join(dir, "a.txt") + fi, err := os.Stat(dst) + if err != nil || readFile(t, dst) != "new!" || !fi.ModTime().Equal(mtime) { + t.Fatalf("preserve=%v: a.txt = %q at %v, want new! at %v", preserve, readFile(t, dst), fi.ModTime(), mtime) + } + if !preserve { + onlyFiles(t, dir, "a.txt") + continue + } + onlyFiles(t, dir, RestoreHistoryDirName, "a.txt") + if got := readFile(t, filepath.Join(dir, RestoreHistoryDirName, "run-7", "a.txt")); got != "old" { + t.Fatalf("restore history holds %q, want the replaced old", got) + } + } +} From 1d00c10e9ad0d0a7b128fca462a2cb452efbbdcc Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 01:42:12 +0200 Subject: [PATCH 18/61] sync: restore native mirrors through the transport MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A restore from a local mirror or a plain sftp mirror no longer runs rclone. With an index that holds present files for the volume, each present path is fetched by its path and placed only once its bytes hash to the indexed BLAKE3; a path that already holds them is left alone and counted as already correct, so an in-place restore preserves only what it really replaces. Without one — a fresh machine — the restore walks the mirrored tree, leaving out squirrel's reserved entries, and checks each file against the content the newest receipt naming it recorded; a file no receipt names is restored unchecked and counted in a warning. Restore splits its target gates out into checkRestoreTarget, and the restore, sync and status CLI tests on a local mirror now run with rclone hidden from PATH. --- cmd/squirrel/restore.go | 13 +- cmd/squirrel/restore_test.go | 10 +- cmd/squirrel/status_test.go | 2 +- cmd/squirrel/sync_test.go | 10 +- design/native-mirror.md | 21 ++- docs/src/content/docs/guides/restore.md | 40 ++++- docs/src/content/docs/reference/cli.md | 10 +- sync/restore_mirror.go | 230 ++++++++++++++++++++++++ sync/restore_mirror_test.go | 141 +++++++++++++++ sync/restore_place.go | 12 ++ sync/sync.go | 129 +++++++------ 11 files changed, 516 insertions(+), 102 deletions(-) create mode 100644 sync/restore_mirror.go create mode 100644 sync/restore_mirror_test.go diff --git a/cmd/squirrel/restore.go b/cmd/squirrel/restore.go index b5b1b71..e43e653 100644 --- a/cmd/squirrel/restore.go +++ b/cmd/squirrel/restore.go @@ -32,7 +32,7 @@ func newRestoreCmd() *cobra.Command { ) cmd := &cobra.Command{ Use: "restore ", - Short: "Pull a volume back from one of its rclone destinations", + Short: "Pull a volume back from one of its destinations", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { return runRestore(cmd, args[0], from, sync.RestoreOptions{ @@ -45,8 +45,8 @@ func newRestoreCmd() *cobra.Command { } cmd.Flags().StringVar(&from, "from", "", "destination name to pull from, or peer node name to filter by content origin (overloaded; names are unique across both kinds)") cmd.Flags().StringVar(&to, "to", "", "local target path (default: the volume's declared path)") - cmd.Flags().BoolVar(&shallow, "shallow", false, "skip the checksum comparison on the way down") - cmd.Flags().BoolVar(&dryRun, "dry-run", false, "preview rclone actions without transferring") + cmd.Flags().BoolVar(&shallow, "shallow", false, "skip the checksum comparison on the way down from an rclone mirror (every other destination's bytes are always re-hashed)") + cmd.Flags().BoolVar(&dryRun, "dry-run", false, "preview what the restore would fetch without transferring") cmd.Flags().BoolVar(&inPlace, "in-place", false, "permit restore against a non-empty live vol.Path; overwritten files are moved to .squirrel-restore-history/run-/") return cmd } @@ -84,17 +84,14 @@ func runRestore(cmd *cobra.Command, volumeName, fromName string, opts sync.Resto opts.IncludeFromFile = includeFile } - rcl, err := sync.Find(cmd.Context()) + rcl, err := rcloneFor(cmd, cfg, dest) if err != nil { return err } out := cmd.OutOrStdout() - if opts.Shallow { + if opts.Shallow && rcl != nil { fmt.Fprintln(out, shallowSyncWarning) } - if err := writeRcloneConfigLogged(out, rcl, cfg); err != nil { - return err - } rep, runErr := sync.Restore(cmd.Context(), s, rcl, vol, dest, opts) // Restore pulls destination → local, so flip the arrow: the sync-shaped diff --git a/cmd/squirrel/restore_test.go b/cmd/squirrel/restore_test.go index 5d6d25a..5f53b8f 100644 --- a/cmd/squirrel/restore_test.go +++ b/cmd/squirrel/restore_test.go @@ -17,7 +17,7 @@ import ( // remove the local copy, restore from the destination, and verify the // contents match. func TestCLIRestoreRoundTrip(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") writeTestFile(t, filepath.Join(f.volumeDir, "b.txt"), "beta") @@ -63,7 +63,7 @@ func TestCLIRestoreRoundTrip(t *testing.T) { // TestCLIRestoreToPathOverridesVolumePath confirms --to writes to the // override directory rather than the volume's declared path. func TestCLIRestoreToPathOverridesVolumePath(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") @@ -92,7 +92,7 @@ func TestCLIRestoreToPathOverridesVolumePath(t *testing.T) { // TestCLIRestoreRecordsRunsRowWithKindRestore verifies that the restore // command produces a runs row distinguishable from sync runs. func TestCLIRestoreRecordsRunsRowWithKindRestore(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") runCLI(t, "--config", f.configPath, "index", f.volumeName) @@ -110,7 +110,7 @@ func TestCLIRestoreRecordsRunsRowWithKindRestore(t *testing.T) { // candidate is picked automatically. This is the common case and the // counterpart to TestCLIRestoreNeedsExplicitFromWhenAmbiguous. func TestCLIRestoreInfersDestinationWhenUnambiguous(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") @@ -137,7 +137,7 @@ func TestCLIRestoreInfersDestinationWhenUnambiguous(t *testing.T) { // introduction), and syncs the tree. Restoring with --from peer-a // should land only the from-a path in the target tree. func TestCLIRestoreFromNodeFiltersByAttribution(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "local.txt"), "local") diff --git a/cmd/squirrel/status_test.go b/cmd/squirrel/status_test.go index fbc9b1d..08301cd 100644 --- a/cmd/squirrel/status_test.go +++ b/cmd/squirrel/status_test.go @@ -77,7 +77,7 @@ func TestCLIStatusNeverSyncedIsAmber(t *testing.T) { // TestCLIStatusAfterSyncIsGreen: once a fresh sync lands, the pair is // caught up within cadence and the command exits 0. func TestCLIStatusAfterSyncIsGreen(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) cfg := writeStatusConfig(t) runCLI(t, "--config", cfg, "index", "pics") runCLI(t, "--config", cfg, "sync", "pics", "--init") diff --git a/cmd/squirrel/sync_test.go b/cmd/squirrel/sync_test.go index dcedf01..cbf4101 100644 --- a/cmd/squirrel/sync_test.go +++ b/cmd/squirrel/sync_test.go @@ -9,7 +9,7 @@ import ( ) func TestCLISyncErrorsWhenVolumeNotIndexed(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") @@ -21,7 +21,7 @@ func TestCLISyncErrorsWhenVolumeNotIndexed(t *testing.T) { } func TestCLISyncHappyPath(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") writeTestFile(t, filepath.Join(f.volumeDir, "b.txt"), "beta") @@ -46,7 +46,7 @@ func TestCLISyncHappyPath(t *testing.T) { // volume reports already_correct so an in-sync no-op is distinguishable // from an empty one (transferred=0 alone is ambiguous). func TestCLISyncAlreadyCorrect(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") writeTestFile(t, filepath.Join(f.volumeDir, "b.txt"), "beta") @@ -143,7 +143,7 @@ func TestCLISyncRequiresConfig(t *testing.T) { // sync/. We verify (a) the command succeeds and prints a report, (b) // nothing lands at the destination, and (c) no new runs row is recorded. func TestCLISyncDryRun(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") runCLI(t, "--config", f.configPath, "index", f.volumeName) @@ -175,7 +175,7 @@ func TestCLISyncMissingExplicitConfigErrors(t *testing.T) { } func TestCLISyncRunsRowVisibleViaRunsCommand(t *testing.T) { - requireRcloneCLI(t) + withoutRclone(t) f := writeSyncFixture(t) writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") diff --git a/design/native-mirror.md b/design/native-mirror.md index 6a1350f..bb5267d 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -559,18 +559,29 @@ for local mirrors. ## 6. Restore, ride-along, recover -- **Mirror restore with an index** uses the archive restore pipeline: +- **Mirror restore with an index** uses the archive restore pipeline + (`sync/restore_mirror.go`): 1. resolve the present paths; 2. `Get` each one by path; 3. BLAKE3 while streaming; 4. place it. Placing goes through a temporary file in the target directory, a sync and a - rename. Today's archive restore writes with `O_TRUNC` in place. Both get - fixed together. + rename (`sync/restore_place.go`). Archive restore wrote with `O_TRUNC` in + place; both now place the same way. Bytes that fail their hash never reach + the path. A path that already holds its indexed bytes is left alone and + counted as already correct, so an in-place restore moves into + `.squirrel-restore-history/` only what it actually replaces. - **Mirror restore without an index** (a fresh machine) walks the mirror with - `List` and skips the reserved directories. When receipts are present, each - file is checked against them, and files that can't be checked are counted. + `List` and skips the reserved directories. "Without an index" means the index + holds no present file for the volume: a fresh database, or one whose rows for + the volume are all missing after a rescan of an emptied disk. The receipts, + folded oldest run first, give each path the content its newest present entry + recorded. A file with such an entry is checked against it and refused when it + differs; a file no receipt names can't be checked, so it is restored and + counted in a warning. A receipt that doesn't parse is reported and skipped. +- **`--shallow` changes nothing** on a native mirror restore, as on an archive + restore: every byte is hashed anyway. - **The marker gate, the snapshot ride-along and its rotation, and `recover --from` discovery** become transport calls. That removes the rclone-specific helpers `statRemoteExists`, `catRemote`, `copyTo`, `listSnapshots`, diff --git a/docs/src/content/docs/guides/restore.md b/docs/src/content/docs/guides/restore.md index 277e36b..bffe353 100644 --- a/docs/src/content/docs/guides/restore.md +++ b/docs/src/content/docs/guides/restore.md @@ -1,9 +1,9 @@ --- title: Restoring -description: Pull a volume back from one of its rclone destinations, with content verification on the way down (BLAKE3 for archive layouts, a checksum comparison for mirrors). +description: Pull a volume back from one of its destinations, with content verification on the way down (BLAKE3 for native mirrors and archive layouts, a checksum comparison for rclone mirrors). --- -`squirrel restore` pulls a volume back from one of its rclone destinations. +`squirrel restore` pulls a volume back from one of its destinations. ```sh squirrel restore pictures --from nas @@ -18,16 +18,21 @@ It takes exactly one positional argument — the **volume name**. |---|---|---| | `--from ` | — | Destination name to pull from, **or** peer node name to filter by content origin (names are unique across both kinds). | | `--to ` | volume's declared path | Local target path. | -| `--shallow` | off | Skip the checksum comparison on the way down (mirror destinations). | -| `--dry-run` | off | Preview rclone actions without transferring. | +| `--shallow` | off | Skip the checksum comparison on the way down from an rclone mirror. Every other destination's bytes are re-hashed regardless. | +| `--dry-run` | off | Preview what the restore would fetch without transferring. | | `--in-place` | off | Permit restore against a non-empty live `vol.Path`; overwritten files are moved to `.squirrel-restore-history/run-/`. | ## Verification on the way down -By default, a mirror restore compares each file with its copy by checksum as it -arrives, the same comparison [`sync`](/squirrel/guides/syncing/) uses on the way -up. Pass `--shallow` to skip it. Content-addressed and packed restores re-hash -everything they extract to BLAKE3 regardless (see below). +A [native mirror](#native-mirrors) restore and a content-addressed or packed +restore hash every byte to BLAKE3 as it arrives and refuse what does not match +(see below). A restore from an rclone mirror compares each file with its copy by +checksum as it arrives, the same comparison [`sync`](/squirrel/guides/syncing/) +uses on the way up; pass `--shallow` to skip it. + +Every restored file lands through a temporary file beside its path, which is +flushed and then renamed over it, so a restore that stops halfway never leaves a +truncated file behind. :::note[Encrypted destinations are always size+mtime] [Encrypted (`crypt`)](/squirrel/layouts/encrypted/) destinations cannot expose @@ -44,6 +49,25 @@ overwrite is first moved to `.squirrel-restore-history/run-/`, mirroring the append-only [`.squirrel-history`](/squirrel/layouts/mirror/) behavior on the sync side. Nothing is destroyed. +## Native mirrors + +A [native mirror](/squirrel/layouts/mirror/#how-a-mirror-is-written) — `local`, +or `sftp` without crypt — is read through squirrel's own transport; no rclone is +involved. + +- **With an index** that holds present files for the volume, each present path + is fetched by its path and its bytes are checked against the index's BLAKE3 + as they stream; a file whose bytes differ is refused, not written. A path that + already holds its indexed bytes is left alone and counted as already correct. +- **Without one** — a fresh machine, before or instead of + [`squirrel recover`](/squirrel/guides/recovery/) — restore walks the mirrored + tree, leaving out `.squirrel-history/`, `.squirrel-index/`, + `.squirrel-staging/` and the marker. The mirror's + [receipts](/squirrel/layouts/mirror/#how-a-mirror-is-written) name the content + each path last held, so every file a receipt names is checked against it and + refused if it differs. A file no receipt names (one squirrel did not write) is + restored unchecked, and the run's warnings count them. + ## Content-addressed and packed destinations `squirrel restore` handles the diff --git a/docs/src/content/docs/reference/cli.md b/docs/src/content/docs/reference/cli.md index 71f7103..e28d49c 100644 --- a/docs/src/content/docs/reference/cli.md +++ b/docs/src/content/docs/reference/cli.md @@ -402,7 +402,7 @@ winner live. Adopting the preserved version instead is a deliberate ## squirrel restore -**Pull a volume back from one of its rclone destinations.** +**Pull a volume back from one of its destinations.** ``` squirrel restore @@ -414,10 +414,14 @@ Exactly one positional — the volume name. See [Restoring](/squirrel/guides/res |---|---|---| | `--from` | — | Destination name to pull from, or peer node name to filter by content origin. | | `--to` | volume's declared path | Local target path. | -| `--shallow` | `false` | Skip the checksum comparison on the way down (mirror destinations). | -| `--dry-run` | `false` | Preview rclone actions without transferring. | +| `--shallow` | `false` | Skip the checksum comparison on the way down from an rclone mirror. Native mirrors and the content-addressed and packed layouts are always re-hashed to BLAKE3. | +| `--dry-run` | `false` | Preview what the restore would fetch without transferring. | | `--in-place` | `false` | Permit restore against a non-empty live path; overwritten files move to `.squirrel-restore-history/run-/`. | +A [native mirror](/squirrel/guides/restore/#native-mirrors) restore needs no rclone: +with an index it checks each path against it, and without one it walks the mirror +and checks each file against the mirror's receipts. + Restore from an [encrypted (`crypt`)](/squirrel/layouts/encrypted/) destination is always a size+mtime comparison (recorded shallow) even without `--shallow`, because rclone crypt remotes don't expose content hashes. diff --git a/sync/restore_mirror.go b/sync/restore_mirror.go new file mode 100644 index 0000000..93bf002 --- /dev/null +++ b/sync/restore_mirror.go @@ -0,0 +1,230 @@ +package sync + +import ( + "bufio" + "context" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io/fs" + "path" + "slices" + "strconv" + "strings" + "time" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// mirrorRestore restores a volume from a native mirror through a read-only +// transport. With an index that holds present paths for the volume, it +// fetches each of them by path and checks its bytes against the indexed +// BLAKE3 as they stream. Without one — a fresh machine — it walks the +// mirrored tree and checks each file against the mirror's receipts. +type mirrorRestore struct { + store *store.Store + vol *config.Volume + dest *config.Destination + volID int64 + tr transport + placer restorePlacer + dryRun bool +} + +// restoreMirror runs one native mirror restore and writes the +// kind='restore' runs row's terminal state. +func restoreMirror(ctx context.Context, s *store.Store, vol *config.Volume, dest *config.Destination, volID, runID int64, targetInPlace bool, opts RestoreOptions, rep *Report) error { + rep.RunID = runID + tr, err := openReadOnly(ctx, dest) + if err != nil { + finishRestore(ctx, s, opts.DryRun, runID, rep, err) + return err + } + defer func() { _ = tr.Close() }() + mr := &mirrorRestore{ + store: s, vol: vol, dest: dest, volID: volID, tr: tr, + placer: newRestorePlacer(vol, runID, targetInPlace, opts), dryRun: opts.DryRun, + } + runErr := mr.run(ctx, rep, opts.IncludeFromFile) + finishRestore(ctx, s, opts.DryRun, runID, rep, runErr) + return runErr +} + +func (mr *mirrorRestore) run(ctx context.Context, rep *Report, includeFile string) error { + rows, err := mr.store.ListPresentContent(ctx, mr.volID) + if err != nil { + return fmt.Errorf("list present content for %q: %w", mr.vol.Name, err) + } + switch { + case includeFile != "": + include, err := loadIncludeSet(includeFile) + if err != nil { + return err + } + mr.restoreIndexed(ctx, rep, slices.DeleteFunc(rows, func(r store.PathDelta) bool { return !include[r.Path] })) + case len(rows) > 0: + mr.restoreIndexed(ctx, rep, rows) + default: + if err := mr.restoreWalked(ctx, rep); err != nil { + return err + } + } + if rep.RcloneResult.Errors > 0 { + return fmt.Errorf("restore of %q from %q: %d file(s) failed", mr.vol.Name, mr.dest.Name, rep.RcloneResult.Errors) + } + return nil +} + +// restoreIndexed restores each present path the index names, checked +// against its indexed hash and stamped with its indexed mtime. +func (mr *mirrorRestore) restoreIndexed(ctx context.Context, rep *Report, rows []store.PathDelta) { + for _, r := range rows { + mr.restoreOne(ctx, rep, r.Path, r.SizeBytes, r.Blake3, time.Unix(0, r.MtimeNs)) + } +} + +// restoreWalked restores every file of the mirrored tree. A file a receipt +// names is checked against the content the newest such receipt recorded; +// the rest are restored unchecked, and counted in a warning. +func (mr *mirrorRestore) restoreWalked(ctx context.Context, rep *Report) error { + receipts, err := mr.readReceipts(ctx, rep) + if err != nil { + return err + } + unchecked := 0 + err = mr.walk(ctx, rep, "", func(rel string, e entry) { + want, ok := receipts[rel] + if !ok { + unchecked++ + } + mr.restoreOne(ctx, rep, rel, e.size, want, e.mtime) + }) + if unchecked > 0 { + rep.Warnings = append(rep.Warnings, fmt.Sprintf("%d file(s) on %q are named in no receipt, so their bytes could not be checked; they are restored unchecked", unchecked, mr.dest.Name)) + } + return err +} + +// restoreOne fetches rel from the mirror and places it. A path that +// already holds the wanted bytes is left as it is and counted as already +// correct; a failure is recorded against rel and the restore goes on. +func (mr *mirrorRestore) restoreOne(ctx context.Context, rep *Report, rel string, size int64, want []byte, mtime time.Time) { + if want != nil && mr.placer.holds(rel, size, want) { + rep.RcloneResult.Checked++ + return + } + if mr.dryRun { + rep.RcloneResult.Transferred++ + rep.RcloneResult.Bytes += size + return + } + rc, err := mr.tr.Get(ctx, path.Join(mr.vol.Name, rel)) + if err != nil { + recordRestoreFailure(rep, rel, fmt.Errorf("fetch from %q: %w", mr.dest.Name, err)) + return + } + defer func() { _ = rc.Close() }() + n, err := mr.placer.place(rel, ctxReader{ctx: ctx, r: rc}, want, mtime) + if err != nil { + recordRestoreFailure(rep, rel, err) + return + } + rep.RcloneResult.Transferred++ + rep.RcloneResult.Bytes += n +} + +// walk visits every file of the mirrored tree under dir, leaving out +// squirrel's reserved entries at the volume root. An entry that is neither +// a file nor a directory is reported and not restored. +func (mr *mirrorRestore) walk(ctx context.Context, rep *Report, dir string, visit func(rel string, e entry)) error { + name := path.Join(mr.vol.Name, dir) + entries, err := mr.tr.List(ctx, name) + if err != nil { + return fmt.Errorf("list %s on %q: %w", name, mr.dest.Name, err) + } + for _, e := range entries { + rel := path.Join(dir, e.name) + switch { + case dir == "" && (isReservedFolderPath(e.name) || e.name == volmark.MarkerName): + case e.kind == kindDir: + if err := mr.walk(ctx, rep, rel, visit); err != nil { + return err + } + case e.kind == kindFile: + visit(rel, e) + default: + rep.Warnings = append(rep.Warnings, fmt.Sprintf("%s on %q is neither a file nor a directory; it is not restored", rel, mr.dest.Name)) + } + } + return nil +} + +// readReceipts folds the mirror's receipts, oldest run first, into the +// BLAKE3 each path last held: a present entry overrides every earlier run. +// A receipt that cannot be read is reported and left out, so the paths it +// covered are checked against older receipts. +func (mr *mirrorRestore) readReceipts(ctx context.Context, rep *Report) (map[string][]byte, error) { + dir := path.Join(mr.vol.Name, IndexDirName) + entries, err := mr.tr.List(ctx, dir) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("list %s on %q: %w", dir, mr.dest.Name, err) + } + var runs []int64 + for _, e := range entries { + if id, ok := receiptRunID(e); ok { + runs = append(runs, id) + } + } + slices.Sort(runs) + out := map[string][]byte{} + for _, id := range runs { + name := path.Join(dir, "run-"+strconv.FormatInt(id, 10)) + if err := foldReceipt(ctx, mr.tr, name, out); err != nil { + rep.Warnings = append(rep.Warnings, fmt.Sprintf("receipt %s on %q could not be read (%v); the files it names are checked against older receipts", name, mr.dest.Name, err)) + } + } + return out, nil +} + +// receiptRunID reads the run id of a receipt, a file named run-. +func receiptRunID(e entry) (int64, bool) { + idText, ok := strings.CutPrefix(e.name, "run-") + if !ok || e.kind != kindFile { + return 0, false + } + id, err := strconv.ParseInt(idText, 10, 64) + return id, err == nil && id > 0 && strconv.FormatInt(id, 10) == idText +} + +// foldReceipt records into the content of every present path the receipt +// at name lists. +func foldReceipt(ctx context.Context, tr transport, name string, into map[string][]byte) error { + rc, err := tr.Get(ctx, name) + if err != nil { + return err + } + defer func() { _ = rc.Close() }() + sc := bufio.NewScanner(ctxReader{ctx: ctx, r: rc}) + sc.Buffer(make([]byte, 0, 64<<10), 1<<20) + for sc.Scan() { + var e ManifestEntry + if err := json.Unmarshal(sc.Bytes(), &e); err != nil { + return err + } + if e.Status != store.StatusPresent { + continue + } + sum, err := hex.DecodeString(e.Blake3) + if err != nil || len(sum) != 32 { + return fmt.Errorf("%s: blake3 %q is not a 32-byte hex hash", e.Path, e.Blake3) + } + into[e.Path] = sum + } + return sc.Err() +} diff --git a/sync/restore_mirror_test.go b/sync/restore_mirror_test.go new file mode 100644 index 0000000..d5aea0b --- /dev/null +++ b/sync/restore_mirror_test.go @@ -0,0 +1,141 @@ +package sync + +import ( + "context" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/mbertschler/squirrel/store" +) + +func (f *mirrorFixture) restore(t *testing.T, s *store.Store, opts RestoreOptions) (Report, error) { + t.Helper() + return Restore(context.Background(), s, nil, f.pair.Volume, f.pair.Destination, opts) +} + +// scratchFile reads rel under a restore target, "" when it is absent. +func scratchFile(t *testing.T, dir, rel string) string { + t.Helper() + b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel))) + if os.IsNotExist(err) { + return "" + } + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// TestMirrorRestoreFromTheIndex: with an index, a native mirror restore +// fetches each present path through the transport with no rclone, checks +// it against the indexed hash, and leaves a path that already holds its +// bytes alone. A mirrored file whose bytes no longer match the index is +// refused, never placed. +func TestMirrorRestoreFromTheIndex(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "alpha") + f.write(t, "2024/cat.jpg", "meow") + f.write(t, "b.txt", "beta") + f.index(t) + f.mustPush(t) + + scratch := t.TempDir() + if err := os.WriteFile(filepath.Join(scratch, "a.txt"), []byte("alpha"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("b.txt"), []byte("BETA"), 0o644); err != nil { + t.Fatal(err) + } + rep, err := f.restore(t, f.store, RestoreOptions{ToPath: scratch}) + if err == nil || rep.RcloneResult.Errors != 1 || rep.RcloneResult.FailedFiles[0].Object != "b.txt" { + t.Fatalf("restore = %v, failures %+v; want b.txt refused", err, rep.RcloneResult.FailedFiles) + } + if rep.RcloneResult.Transferred != 1 || rep.AlreadyCorrect != 1 { + t.Fatalf("counters = %+v already_correct=%d, want cat.jpg fetched and a.txt left alone", rep.RcloneResult, rep.AlreadyCorrect) + } + if scratchFile(t, scratch, "2024/cat.jpg") != "meow" || scratchFile(t, scratch, "b.txt") != "" { + t.Fatal("restore placed the wrong bytes") + } + }) + } +} + +// TestMirrorRestoreOnAFreshMachine: with no index, a restore walks the +// mirrored tree, leaves squirrel's reserved entries out, checks every file +// a receipt names against it, and restores the rest unchecked, counting +// them in a warning. A file that contradicts its receipt is refused. +func TestMirrorRestoreOnAFreshMachine(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "v1") + f.write(t, "2024/cat.jpg", "meow") + f.write(t, "c.txt", "gamma") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2") + f.index(t) + f.mustPush(t) + if err := os.WriteFile(f.dest("foreign.txt"), []byte("not squirrel's"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("c.txt"), []byte("GAMMA"), 0o644); err != nil { + t.Fatal(err) + } + + fresh, err := store.Open(filepath.Join(t.TempDir(), "fresh.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fresh.Close() }) + scratch := t.TempDir() + rep, err := f.restore(t, fresh, RestoreOptions{ToPath: scratch}) + if err == nil || rep.RcloneResult.Errors != 1 || rep.RcloneResult.FailedFiles[0].Object != "c.txt" { + t.Fatalf("restore = %v, failures %+v; want c.txt refused", err, rep.RcloneResult.FailedFiles) + } + for rel, want := range map[string]string{"a.txt": "v2", "2024/cat.jpg": "meow", "foreign.txt": "not squirrel's", "c.txt": ""} { + if got := scratchFile(t, scratch, rel); got != want { + t.Fatalf("%s = %q, want %q", rel, got, want) + } + } + entries, _ := os.ReadDir(scratch) + for _, e := range entries { + if strings.HasPrefix(e.Name(), ".squirrel") { + t.Fatalf("restore brought back squirrel's own %s", e.Name()) + } + } + if !warned(rep, "1 file(s)") || !warned(rep, "restored unchecked") { + t.Fatalf("warnings = %v, want the one unchecked file counted", rep.Warnings) + } + }) + } +} + +// TestMirrorRestoreInPlacePreservesWhatItReplaces: an in-place restore +// moves every file it replaces into the run's restore history, and +// leaves a file that already holds its indexed bytes where it is. +func TestMirrorRestoreInPlacePreservesWhatItReplaces(t *testing.T) { + f := setupMirrorFixtureOn(t, localBackend) + f.write(t, "a.txt", "alpha") + f.write(t, "b.txt", "beta") + f.index(t) + f.mustPush(t) + f.write(t, "b.txt", "local edit") + + rep, err := f.restore(t, f.store, RestoreOptions{InPlace: true}) + if err != nil || rep.RcloneResult.Transferred != 1 || rep.AlreadyCorrect != 1 { + t.Fatalf("restore = %v, counters %+v already_correct=%d; want b.txt replaced and a.txt left alone", err, rep.RcloneResult, rep.AlreadyCorrect) + } + if scratchFile(t, f.src, "b.txt") != "beta" { + t.Fatal("b.txt was not restored") + } + history := filepath.Join(RestoreHistoryDirName, "run-"+strconv.FormatInt(rep.RunID, 10), "b.txt") + if got := scratchFile(t, f.src, history); got != "local edit" { + t.Fatalf("restore history holds %q, want the replaced local edit", got) + } +} diff --git a/sync/restore_place.go b/sync/restore_place.go index b8c95bf..b520552 100644 --- a/sync/restore_place.go +++ b/sync/restore_place.go @@ -48,6 +48,18 @@ func (pl restorePlacer) place(rel string, r io.Reader, want []byte, mtime time.T return n, nil } +// holds reports whether rel already holds size bytes hashing to want, so +// a restore can leave it as it is. +func (pl restorePlacer) holds(rel string, size int64, want []byte) bool { + dst := pl.path(rel) + fi, err := os.Lstat(dst) + if err != nil || !fi.Mode().IsRegular() || fi.Size() != size { + return false + } + digest, err := hashLocalFile(dst) + return err == nil && bytes.Equal(digest, want) +} + func (pl restorePlacer) path(rel string) string { return filepath.Join(pl.target, filepath.FromSlash(rel)) } diff --git a/sync/sync.go b/sync/sync.go index 1e340b7..798efdf 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -973,90 +973,50 @@ type RestoreOptions struct { } // Restore reverses Sync back to the local filesystem, recording a -// kind='restore' runs row. The mirror layout copies the destination's -// per-volume tree down with rclone; the content-addressed and packed -// layouts (which have no mirrored tree) resolve each present path to its -// content hash in the local index, fetch the per-hash object or pack -// member, and re-hash it before writing. Restore is read-only against both -// the index and the destination — it never uploads, never mutates content -// rows — but the rclone mirror path will overwrite whatever exists at the -// target on a hash mismatch, so callers point ToPath at an empty / scratch -// directory unless they explicitly intend to restore in place. +// kind='restore' runs row. A native mirror (local, or sftp without crypt) +// is read through squirrel's own transport and every file is placed +// through a temporary file beside its path, checked against the index — +// or, on a fresh machine, against the mirror's receipts; rcl may be nil +// for one. An rclone mirror is copied down with rclone. The +// content-addressed and packed layouts (which have no mirrored tree) +// resolve each present path to its content hash in the local index, fetch +// the per-hash object or pack member, and re-hash it before writing. +// Restore is read-only against both the index and the destination — it +// never uploads, never mutates content rows. An in-place restore without +// InPlace is refused on a non-empty volume, and with it every file it +// replaces moves into .squirrel-restore-history/run-/. func Restore(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volume, dest *config.Destination, opts RestoreOptions) (rep Report, err error) { rep = Report{Volume: vol.Name, Destination: dest.Name} if dest.Type == "kopia" { return rep, fmt.Errorf("destination %q is a kopia repository — restore from it with the kopia CLI (`kopia snapshot restore`)", dest.Name) } - archive := dest.Layout == config.LayoutContentAddressed || dest.Layout == config.LayoutPacked - - // "In-place" is the dangerous direction: writing into the live - // volume path. Unsetting ToPath is the canonical request, but a - // caller who explicitly passes ToPath == vol.Path is asking for - // the same thing and must go through the same gates — otherwise - // `--to ` would silently bypass the marker check, the - // non-empty refusal, AND the overwrite backup, reintroducing exactly - // the data-loss path this guard is trying to close. - targetInPlace, err := isInPlaceRestore(vol, opts.ToPath) + targetInPlace, err := checkRestoreTarget(vol, opts) if err != nil { return rep, err } - - // Local target marker check: when restoring into the live volume - // path, insist on a marker that names this volume. A missing or - // mismatched marker is the strongest signal we have that vol.Path - // is a typo or unrelated tree, and overwriting it would be - // irreversible. A genuine scratch --to bypasses the check because - // the operator is explicitly redirecting to an unrelated directory. - if !opts.DryRun && targetInPlace { - if err := validateLocalVolumeMarker(vol); err != nil { - return rep, err - } - } - - // In-place overwrite gate: a non-empty live vol.Path is the - // most likely realistic data-loss path in squirrel today (user - // runs `restore` to recover what they think is missing, and the - // destination's view replaces local edits). When InPlace is unset - // and the directory carries anything beyond the marker/history - // subtree, refuse with the --in-place hint. - if !opts.DryRun && targetInPlace && !opts.InPlace { - hasContent, err := localVolumeHasContent(vol.Path) - if err != nil { - return rep, err - } - if hasContent { - return rep, fmt.Errorf("volume %q at %s is not empty — pass --in-place to overwrite (a per-run history of replaced files lands under %s/run-/) or --to to restore into a different directory", vol.Name, vol.Path, RestoreHistoryDirName) - } - } - - // We deliberately don't require an existing index for the mirror - // pull: the destination is the source of truth there, and a fresh - // laptop may have no DB rows yet. We still create a volumes row so - // the runs row's FK resolves. (The archive pull does need the index - // — that is where path→hash lives — but a fresh volume simply - // resolves to zero present rows and restores nothing.) + // We deliberately don't require an existing index: a fresh machine + // may have no DB rows yet, and a mirror restores from its own tree + // then. We still create a volumes row so the runs row's FK resolves. v, err := getOrCreateVolumeForRestore(ctx, s, vol) if err != nil { return rep, err } - - // The archive layouts re-hash every extracted content locally, so the - // pull is content-verified regardless of --shallow or a crypt overlay; - // the mirror pull records rclone's effective comparison instead. - shallow := EffectiveShallow(dest, opts.Shallow) - if archive { - shallow = false - } + // Squirrel re-hashes every file it restores from a native mirror or an + // archive layout, so those pulls are content-verified regardless of + // --shallow or a crypt overlay; an rclone mirror pull records rclone's + // effective comparison instead. + archive := dest.Layout == config.LayoutContentAddressed || dest.Layout == config.LayoutPacked + shallow := EffectiveShallow(dest, opts.Shallow) && !archive && !dest.NativeMirror() runID, err := beginRestoreRun(ctx, s, opts.DryRun, v.ID, dest.Name, shallow) if err != nil { return rep, err } - - if archive { - err = restoreArchive(ctx, s, rcl, vol, dest, v.ID, runID, targetInPlace, opts, &rep) - return rep, err + switch { + case archive: + return rep, restoreArchive(ctx, s, rcl, vol, dest, v.ID, runID, targetInPlace, opts, &rep) + case dest.NativeMirror(): + return rep, restoreMirror(ctx, s, vol, dest, v.ID, runID, targetInPlace, opts, &rep) } - if w := cryptVerificationWarning(dest, opts.Shallow); w != "" { rep.Warnings = append(rep.Warnings, w) } @@ -1067,6 +1027,41 @@ func Restore(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volum return rep, err } +// checkRestoreTarget applies the in-place gates and reports whether the +// restore writes into the live volume path. "In-place" is the dangerous +// direction: an unset ToPath is the canonical request, but a caller who +// explicitly passes ToPath == vol.Path is asking for the same thing and +// must go through the same gates — otherwise `--to ` would +// silently bypass the marker check, the non-empty refusal, AND the +// overwrite backup. +// +// Into the live path, a marker naming this volume is required: a missing +// or mismatched one is the strongest signal that vol.Path is a typo or an +// unrelated tree. And a non-empty live path — the most realistic data-loss +// path, where the destination's view replaces local edits — is refused +// unless InPlace. A genuine scratch --to bypasses both, because the +// operator explicitly redirected to an unrelated directory. +func checkRestoreTarget(vol *config.Volume, opts RestoreOptions) (bool, error) { + targetInPlace, err := isInPlaceRestore(vol, opts.ToPath) + if err != nil || opts.DryRun || !targetInPlace { + return targetInPlace, err + } + if err := validateLocalVolumeMarker(vol); err != nil { + return true, err + } + if opts.InPlace { + return true, nil + } + hasContent, err := localVolumeHasContent(vol.Path) + if err != nil { + return true, err + } + if hasContent { + return true, fmt.Errorf("volume %q at %s is not empty — pass --in-place to overwrite (a per-run history of replaced files lands under %s/run-/) or --to to restore into a different directory", vol.Name, vol.Path, RestoreHistoryDirName) + } + return true, nil +} + // isInPlaceRestore reports whether the restore target equals // vol.Path. The CLI's --to flag is for "restore into a scratch // directory" — when the operator points it at the live volume itself From 4d34f9f6864fde4b6eb3a8e332e71d334d288be6 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 01:45:36 +0200 Subject: [PATCH 19/61] sync: pin that both test servers' rename replaces its target rclone serve sftp, the testbed's server, replaces an existing name on a raw protocol rename just as pkg/sftp's own server does; the test now runs against both. testbed.md describes how the contract suite uses that server, what it lacks next to OpenSSH, and how to walk a native sftp mirror beside the encrypted cloudbox. The design notes that sftp concurrency is per file for now, with paths written one at a time. --- design/native-mirror.md | 10 ++++--- design/testbed.md | 31 ++++++++++++++++++++ sync/transport_sftp_test.go | 56 +++++++++++++++++++++++-------------- 3 files changed, 72 insertions(+), 25 deletions(-) diff --git a/design/native-mirror.md b/design/native-mirror.md index bb5267d..072ba94 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -293,8 +293,8 @@ type transport interface { - **mtime is whole seconds.** Protocol version 3 carries only seconds, so the records store the mtime the server reports. - **`Put` and `Rename` check first.** The protocol's rename fails when the - target exists, but servers don't all honour that: `pkg/sftp`'s own server - replaces it (`TestSFTPServerRenameReplaces`). Version 3 also has no + target exists, but servers don't all honour that: `pkg/sftp`'s own server and + `rclone serve sftp` both replace it (`TestSFTPServersRenameOverAnExistingName`). Version 3 also has no "already exists" status, so an exclusive create that fails can't say why. So both calls run `Lstat` on their target first and fail with `fs.ErrExist`, and every call checks its name's parent chain for symlinks, as the local @@ -604,8 +604,10 @@ for local mirrors. everywhere, and `hash_algo` on sftp mirrors. On content-addressed and packed sftp destinations, `hash_algo` still chooses the hash, which now names the command the transport runs on the server. No key is added. - Concurrency is fixed: a few parallel writes on sftp, and one or two on a - local disk. + Concurrency is fixed. On sftp each file goes out as concurrent write + requests (`pkg/sftp`'s default of 64 in flight); paths are written one at a + time on both transports. The testbed benchmark against rclone (section 8) + decides whether several paths in flight are worth their bookkeeping. ## 8. What we give up diff --git a/design/testbed.md b/design/testbed.md index 65acc8e..23bb284 100644 --- a/design/testbed.md +++ b/design/testbed.md @@ -17,6 +17,37 @@ machines are five processes on loopback ports. | kopia-mirror | `kopia` binary + a repo directory | Same as production: squirrel drives the CLI | | usb disk | a plain directory; "unplugging" = renaming it | `local` destination + marker semantics don't care about hardware | +### The sftp server and native mirrors + +`rclone serve sftp` is also the server the sftp transport's contract suite runs +against: `go test ./sync` starts one per case whenever rclone is on PATH +(`TestSFTPTransportContractAgainstRcloneServe`). It differs from an OpenSSH +server in three ways the suite accounts for: + +- its rename replaces an existing target (`TestSFTPServersRenameOverAnExistingName`), + which is why the transport checks every target first; +- it hides symlinks, so the symlink cases skip there; +- it offers no `fsync@openssh.com`, so a push to it skips the flush. + +cloudbox is an encrypted mirror, so rclone still writes it. To walk a native +sftp mirror, declare a second, plain sftp destination against the same server: + +```toml +[destinations.cloudbox-plain] +type = "sftp" +host = "127.0.0.1" +port = "2222" +user = "u123456" +password = { env = "CLOUDBOX_PASS" } +root = "/plain" +known_hosts_file = ".testbed/cloudbox/known_hosts" +``` + +squirrel refuses the server until its host key is pinned; the first push's +refusal prints the known_hosts line to add. Serve with `--key ` to keep +the key stable across restarts (without it, rclone reuses keys it generated in +its cache directory). + Deliberately not simulated: Synology/QNAP packaging (below squirrel), b2/gcs (same shape as s3), real network partitions — a dead machine or dark destination is simulated by stopping its process, which is also diff --git a/sync/transport_sftp_test.go b/sync/transport_sftp_test.go index 10a6e92..6a4f1fc 100644 --- a/sync/transport_sftp_test.go +++ b/sync/transport_sftp_test.go @@ -188,21 +188,30 @@ func TestSFTPTransportContract(t *testing.T) { }) } -// TestSFTPServerRenameReplaces pins why the transport checks a rename's -// target itself: the in-process server's rename replaces an existing -// name, as some real servers do. -func TestSFTPServerRenameReplaces(t *testing.T) { - srv := startSFTPServer(t) - dir := t.TempDir() - tr := mustDialSFTP(t, srv.destination(t, dir)) - t.Cleanup(func() { _ = tr.Close() }) - mustPut(t, tr, "x", "from") - mustPut(t, tr, "y", "to") - if err := tr.client.Rename(tr.full("x"), tr.full("y")); err != nil { - t.Skipf("this server refuses the replacing rename itself: %v", err) - } - if got := mustRead(t, tr, "y"); got != "from" { - t.Fatalf("y after the raw rename = %q, want from", got) +// TestSFTPServersRenameOverAnExistingName pins why the transport checks a +// rename's target itself: the raw protocol rename of both test servers — +// pkg/sftp's own, and rclone serve sftp, the testbed's — replaces an +// existing name. +func TestSFTPServersRenameOverAnExistingName(t *testing.T) { + servers := map[string]func(t *testing.T) *sftpTransport{ + "pkg-sftp": func(t *testing.T) *sftpTransport { + return mustDialSFTP(t, startSFTPServer(t).destination(t, t.TempDir())) + }, + "rclone-serve": rcloneServeTransport, + } + for name, open := range servers { + t.Run(name, func(t *testing.T) { + tr := open(t) + t.Cleanup(func() { _ = tr.Close() }) + mustPut(t, tr, "x", "from") + mustPut(t, tr, "y", "to") + if err := tr.client.Rename(tr.full("x"), tr.full("y")); err != nil { + t.Skipf("this server refuses the replacing rename itself: %v", err) + } + if got := mustRead(t, tr, "y"); got != "from" { + t.Fatalf("y after the raw rename = %q, want from", got) + } + }) } } @@ -321,6 +330,15 @@ func shortTempDir(t *testing.T) string { // the testbed's server, `rclone serve sftp`. That server hides symlinks, // so the symlink cases skip there. func TestSFTPTransportContractAgainstRcloneServe(t *testing.T) { + runTransportContract(t, func(t *testing.T) (transport, func(target, name string)) { + return rcloneServeTransport(t), func(string, string) { t.Skip("rclone serve sftp hides symlinks") } + }) +} + +// rcloneServeTransport serves a fresh directory with `rclone serve sftp` +// and dials it; the test skips without rclone on PATH. +func rcloneServeTransport(t *testing.T) *sftpTransport { + t.Helper() rclone, err := exec.LookPath("rclone") if err != nil { t.Skip("rclone not on PATH") @@ -334,12 +352,8 @@ func TestSFTPTransportContractAgainstRcloneServe(t *testing.T) { if err := os.WriteFile(keyFile, pem.EncodeToMemory(block), 0o600); err != nil { t.Fatal(err) } - runTransportContract(t, func(t *testing.T) (transport, func(target, name string)) { - dir := t.TempDir() - srv := startRcloneServe(t, rclone, dir, keyFile, hostKey) - dest := srv.destination(t, "/") - return mustDialSFTP(t, dest), func(string, string) { t.Skip("rclone serve sftp hides symlinks") } - }) + srv := startRcloneServe(t, rclone, t.TempDir(), keyFile, hostKey) + return mustDialSFTP(t, srv.destination(t, "/")) } // startRcloneServe serves dir with `rclone serve sftp` on a free loopback From 33c3afe819c7b3cd62b99398101646d0db4c6102 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 01:53:01 +0200 Subject: [PATCH 20/61] sync: clear a partial ride-along snapshot, and tidy the shelves A snapshot upload to a native mirror that fails halfway left a truncated index-*.db behind, which recover would offer as the newest snapshot. The shelf now removes it again (the name guard permits exactly that). The shelf opens its transport lazily, so a layout hands afterSync a shelf instead of a function returning one, and recover shares the snapshot listing with it. The snapshot tests that run on both backends move to their own file, and nativeMirror spells out the layouts it excludes. --- config/destinations.go | 3 +- design/native-mirror.md | 7 +- .../content/docs/reference/configuration.md | 2 +- sync/content_addressed.go | 4 +- sync/mirror.go | 15 +- sync/mirror_sftp_test.go | 72 ---------- sync/mirror_snapshot_test.go | 131 ++++++++++++++++++ sync/push.go | 6 +- sync/recover.go | 2 +- sync/snapshot.go | 62 +++++---- sync/sync.go | 2 +- 11 files changed, 187 insertions(+), 119 deletions(-) create mode 100644 sync/mirror_snapshot_test.go diff --git a/config/destinations.go b/config/destinations.go index 063132d..96310c4 100644 --- a/config/destinations.go +++ b/config/destinations.go @@ -841,7 +841,8 @@ func (d *Destination) NativeMirror() bool { } func nativeMirror(typ, layout string, crypt bool) bool { - return !layoutHidesArtifactNames(layout) && !crypt && (typ == "local" || typ == "sftp") + mirror := layout != LayoutContentAddressed && layout != LayoutPacked + return mirror && !crypt && (typ == "local" || typ == "sftp") } // HidesArtifactNames reports whether this destination names its content diff --git a/design/native-mirror.md b/design/native-mirror.md index 072ba94..d365672 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -125,9 +125,10 @@ type layout[O operations] interface { // advanceMethod names the evidence the confirmed landing earns; an // empty method holds the vector (packed, while a fingerprint is pending). advanceMethod(ctx context.Context, rep *Report, p pushPlan) (string, error) - // shelf opens /.squirrel-index/ for the ride-along: through - // rclone for the content layouts, through the transport for a mirror. - shelf(ctx context.Context, runID int64) (snapshotShelf, error) + // shelf is /.squirrel-index/ for the ride-along: reached + // through rclone for the content layouts, through the transport for a + // mirror. + shelf(runID int64) snapshotShelf } ``` diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md index 3cce5b2..c98f5a1 100644 --- a/docs/src/content/docs/reference/configuration.md +++ b/docs/src/content/docs/reference/configuration.md @@ -64,7 +64,7 @@ See [Hooks](/squirrel/guides/hooks/). | `password` | Secret (literal or `{ env }`). | | `key_file` | Path to a private key file, as an alternative to `password` (optional; a leading `~/` is expanded). A passphrase-protected key goes through ssh-agent instead. | | `root` | Base path on the server. | -| `known_hosts_file` | Path to a known_hosts file holding the server's host key. | +| `known_hosts_file` | Path to a known_hosts file holding the server's host key (a leading `~/` is expanded). | | `host_key_algorithms` | Space-separated list pinning accepted host-key algorithms (optional). | With neither `password` nor `key_file` set, squirrel logs in with the keys of the diff --git a/sync/content_addressed.go b/sync/content_addressed.go index 823bd58..f71f6e8 100644 --- a/sync/content_addressed.go +++ b/sync/content_addressed.go @@ -127,8 +127,8 @@ func (h *contentPusher) ensureMarkers(ctx context.Context, init bool) error { // shelf is the destination's .squirrel-index/ directory, reached through // rclone like the rest of the push. -func (h *contentPusher) shelf(context.Context, int64) (snapshotShelf, error) { - return rcloneShelfOf(h.rcl, h.dest, h.vol.Name)() +func (h *contentPusher) shelf(int64) snapshotShelf { + return rcloneShelf{rcl: h.rcl, dir: indexDirURI(h.dest, h.vol.Name)} } // markers is the content layouts' marker gate. A dry run checks the naming diff --git a/sync/mirror.go b/sync/mirror.go index b8ec2d5..a1fefe4 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -190,18 +190,11 @@ func (h *mirrorHandler) advanceMethod(context.Context, *Report, pushPlan) (strin // shelf is the mirror's /.squirrel-index/, reached through runID's // guarded transport. -func (h *mirrorHandler) shelf(ctx context.Context, runID int64) (snapshotShelf, error) { - tr, err := h.root(ctx, runID) - if err != nil { - return nil, err +func (h *mirrorHandler) shelf(runID int64) snapshotShelf { + return transportShelf{ + open: func(ctx context.Context) (transport, error) { return h.root(ctx, runID) }, + dir: path.Join(h.vol.Name, IndexDirName), } - return mirrorShelf(tr, h.vol.Name), nil -} - -// mirrorShelf is volume's .squirrel-index/ on a native mirror reached -// through tr. -func mirrorShelf(tr transport, volume string) transportShelf { - return transportShelf{tr: tr, dir: path.Join(volume, IndexDirName)} } func (h *mirrorHandler) receiptName(runID int64) string { diff --git a/sync/mirror_sftp_test.go b/sync/mirror_sftp_test.go index d0b8f5b..4643e3f 100644 --- a/sync/mirror_sftp_test.go +++ b/sync/mirror_sftp_test.go @@ -1,7 +1,6 @@ package sync import ( - "context" "errors" "os" "path/filepath" @@ -78,74 +77,3 @@ func TestMirrorOverSFTPRefusesAnUnknownHost(t *testing.T) { t.Fatalf("runs = %+v, want the one refused run", runs) } } - -// TestMirrorRideAlongThroughTheTransport: a native mirror's ride-along -// index snapshot lands in /.squirrel-index/ through the transport, -// on both backends, and rotation removes only the oldest snapshots, -// leaving every receipt in place. -func TestMirrorRideAlongThroughTheTransport(t *testing.T) { - for _, b := range mirrorBackends { - t.Run(b.name, func(t *testing.T) { - f := setupMirrorFixtureOn(t, b) - var runs []int64 - for i := range 3 { - f.write(t, "a.txt", strings.Repeat("v", i+1)) - f.index(t) - sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 2}) - rep, err := f.push(t, Options{Snapshot: sn}) - if err != nil || rep.SnapshotErr != nil { - t.Fatalf("push %d: err=%v snapshot=%v", i, err, rep.SnapshotErr) - } - runs = append(runs, rep.RunID) - } - entries, err := os.ReadDir(f.dest(IndexDirName)) - if err != nil { - t.Fatal(err) - } - var snaps, receipts []string - for _, e := range entries { - if isSnapshotName(e.Name()) { - snaps = append(snaps, e.Name()) - } else { - receipts = append(receipts, e.Name()) - } - } - if len(snaps) != 2 || !strings.HasSuffix(snaps[1], "-run-"+strconv.FormatInt(runs[2], 10)+".db") { - t.Fatalf("snapshots = %v, want the newest two", snaps) - } - if len(receipts) != 3 { - t.Fatalf("receipts = %v, want one per run", receipts) - } - }) - } -} - -// TestRecoverFindsAMirrorsSnapshots: recover's discovery lists a native -// mirror's ride-along snapshots and fetches one through the transport, -// with no rclone wrapper, on both backends. -func TestRecoverFindsAMirrorsSnapshots(t *testing.T) { - for _, b := range mirrorBackends { - t.Run(b.name, func(t *testing.T) { - f := setupMirrorFixtureOn(t, b) - f.write(t, "a.txt", "alpha") - f.index(t) - sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) - rep, err := f.push(t, Options{Snapshot: sn}) - if err != nil || rep.SnapshotErr != nil { - t.Fatalf("push: err=%v snapshot=%v", err, rep.SnapshotErr) - } - ctx := context.Background() - snaps, err := DiscoverIndexSnapshots(ctx, nil, f.pair.Destination, []string{"pics", "never-synced"}) - if err != nil || len(snaps) != 1 || snaps[0].RunID != rep.RunID { - t.Fatalf("discovery = %+v, %v; want run %d's snapshot", snaps, err, rep.RunID) - } - local := filepath.Join(t.TempDir(), snaps[0].Name) - if err := FetchIndexSnapshot(ctx, nil, f.pair.Destination, snaps[0], local); err != nil { - t.Fatalf("fetch: %v", err) - } - if fileHash(t, local) != fileHash(t, f.dest(IndexDirName+"/"+snaps[0].Name)) { - t.Fatal("the fetched snapshot differs from the one on the destination") - } - }) - } -} diff --git a/sync/mirror_snapshot_test.go b/sync/mirror_snapshot_test.go new file mode 100644 index 0000000..7f2f029 --- /dev/null +++ b/sync/mirror_snapshot_test.go @@ -0,0 +1,131 @@ +package sync + +import ( + "context" + "errors" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/mbertschler/squirrel/config" +) + +// TestMirrorRideAlongThroughTheTransport: a native mirror's ride-along +// index snapshot lands in /.squirrel-index/ through the transport, +// on both backends, and rotation removes only the oldest snapshots, +// leaving every receipt in place. +func TestMirrorRideAlongThroughTheTransport(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + var runs []int64 + for i := range 3 { + f.write(t, "a.txt", strings.Repeat("v", i+1)) + f.index(t) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 2}) + rep, err := f.push(t, Options{Snapshot: sn}) + if err != nil || rep.SnapshotErr != nil { + t.Fatalf("push %d: err=%v snapshot=%v", i, err, rep.SnapshotErr) + } + runs = append(runs, rep.RunID) + } + entries, err := os.ReadDir(f.dest(IndexDirName)) + if err != nil { + t.Fatal(err) + } + var snaps, receipts []string + for _, e := range entries { + if isSnapshotName(e.Name()) { + snaps = append(snaps, e.Name()) + } else { + receipts = append(receipts, e.Name()) + } + } + if len(snaps) != 2 || !strings.HasSuffix(snaps[1], "-run-"+strconv.FormatInt(runs[2], 10)+".db") { + t.Fatalf("snapshots = %v, want the newest two", snaps) + } + if len(receipts) != 3 { + t.Fatalf("receipts = %v, want one per run", receipts) + } + }) + } +} + +// TestRecoverFindsAMirrorsSnapshots: recover's discovery lists a native +// mirror's ride-along snapshots and fetches one through the transport, +// with no rclone wrapper, on both backends. +func TestRecoverFindsAMirrorsSnapshots(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "alpha") + f.index(t) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) + rep, err := f.push(t, Options{Snapshot: sn}) + if err != nil || rep.SnapshotErr != nil { + t.Fatalf("push: err=%v snapshot=%v", err, rep.SnapshotErr) + } + ctx := context.Background() + snaps, err := DiscoverIndexSnapshots(ctx, nil, f.pair.Destination, []string{"pics", "never-synced"}) + if err != nil || len(snaps) != 1 || snaps[0].RunID != rep.RunID { + t.Fatalf("discovery = %+v, %v; want run %d's snapshot", snaps, err, rep.RunID) + } + local := filepath.Join(t.TempDir(), snaps[0].Name) + if err := FetchIndexSnapshot(ctx, nil, f.pair.Destination, snaps[0], local); err != nil { + t.Fatalf("fetch: %v", err) + } + if fileHash(t, local) != fileHash(t, f.dest(IndexDirName+"/"+snaps[0].Name)) { + t.Fatal("the fetched snapshot differs from the one on the destination") + } + }) + } +} + +// partialPuts lands one byte of every Put whose name matches, then fails +// it, while every other call works on. +type partialPuts struct { + transport + match func(name string) bool +} + +func (p partialPuts) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if !p.match(name) { + return p.transport.Put(ctx, name, r, mtime) + } + if err := p.transport.Put(ctx, name, io.LimitReader(r, 1), mtime); err != nil { + return err + } + return errors.New("the link dropped") +} + +// TestMirrorRideAlongLeavesNoPartialSnapshot: a snapshot upload that fails +// halfway is removed again, so recovery never offers a truncated snapshot +// as the newest; the push itself still succeeds. +func TestMirrorRideAlongLeavesNoPartialSnapshot(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + h := f.handler(t) + h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + return partialPuts{transport: raw, match: func(name string) bool { return isSnapshotName(filepath.Base(name)) }}, err + } + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) + rep, err := h.Push(context.Background(), Options{Snapshot: sn}) + if err != nil || rep.SnapshotErr == nil { + t.Fatalf("push: err=%v snapshot=%v, want a successful push reporting the failed ride-along", err, rep.SnapshotErr) + } + entries, err := os.ReadDir(f.dest(IndexDirName)) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if isSnapshotName(e.Name()) { + t.Fatalf("the partial snapshot %s stayed on the mirror", e.Name()) + } + } +} diff --git a/sync/push.go b/sync/push.go index 22c63b7..068df36 100644 --- a/sync/push.go +++ b/sync/push.go @@ -54,9 +54,9 @@ type layout[O operations] interface { // advanceMethod names the evidence the confirmed landing earns. An // empty method holds the durability vector where it is. advanceMethod(ctx context.Context, rep *Report, p pushPlan) (string, error) - // shelf opens the destination's .squirrel-index/ directory, where + // shelf is the destination's .squirrel-index/ directory, where // runID's ride-along index snapshot lands. - shelf(ctx context.Context, runID int64) (snapshotShelf, error) + shelf(runID int64) snapshotShelf } // pushTarget is the (volume, destination) pair one layout push serves. @@ -102,7 +102,7 @@ func pushThrough[O operations](ctx context.Context, t pushTarget, l layout[O], o } err = landPush(ctx, t, l, &rep, volID, runID) finishHandlerRun(ctx, t.store, &rep, err) - opts.Snapshot.afterSync(ctx, &rep, func() (snapshotShelf, error) { return l.shelf(ctx, runID) }) + opts.Snapshot.afterSync(ctx, &rep, l.shelf(runID)) return rep, err } diff --git a/sync/recover.go b/sync/recover.go index ab08401..d3d7269 100644 --- a/sync/recover.go +++ b/sync/recover.go @@ -60,7 +60,7 @@ func DiscoverIndexSnapshots(ctx context.Context, rcl *Rclone, dest *config.Desti return nil, err } defer func() { _ = tr.Close() }() - list = func(vol string) ([]string, error) { return mirrorShelf(tr, vol).snapshots(ctx) } + list = func(vol string) ([]string, error) { return listSnapshotNames(ctx, tr, path.Join(vol, IndexDirName)) } } var out []IndexSnapshot for _, vol := range volumes { diff --git a/sync/snapshot.go b/sync/snapshot.go index 83a8f6a..8fd0a35 100644 --- a/sync/snapshot.go +++ b/sync/snapshot.go @@ -85,12 +85,12 @@ type snapshotShelf interface { // afterSync is the post-run hook every push calls once the run's terminal // state is committed. It takes (once) the local snapshot and, with cloud -// enabled, rides a copy along to the shelf openShelf opens; a nil -// openShelf (peer and kopia pushes) keeps the local snapshot only. +// enabled, rides a copy along to shelf; a nil shelf (peer and kopia +// pushes) keeps the local snapshot only. // Failures are surfaced on rep.SnapshotErr and never mutate rep.Status — // the snapshot is defense-in-depth, not part of the sync's success // contract. A nil receiver (feature disabled) is a no-op. -func (sn *Snapshotter) afterSync(ctx context.Context, rep *Report, openShelf func() (snapshotShelf, error)) { +func (sn *Snapshotter) afterSync(ctx context.Context, rep *Report, shelf snapshotShelf) { if sn == nil { return } @@ -112,10 +112,10 @@ func (sn *Snapshotter) afterSync(ctx context.Context, rep *Report, openShelf fun // The VACUUM itself failed; there is nothing to ride along. return } - if openShelf == nil || !sn.cloud { + if shelf == nil || !sn.cloud { return } - if rideErr := sn.rideAlong(ctx, localPath, rep, openShelf); rideErr != nil { + if rideErr := sn.rideAlong(ctx, localPath, rep, shelf); rideErr != nil { rep.SnapshotErr = rideErr } } @@ -153,11 +153,7 @@ func (sn *Snapshotter) ensureLocalSnapshot(ctx context.Context, runID int64) (st // /.squirrel-index/, then rotates that directory to at most // cloudKeep snapshots. The uploaded copy keeps the snapshot's filename so // the catalog is traceable to its producing run on the destination too. -func (sn *Snapshotter) rideAlong(ctx context.Context, localPath string, rep *Report, openShelf func() (snapshotShelf, error)) error { - shelf, err := openShelf() - if err != nil { - return fmt.Errorf("ride-along to %s: %w", rep.Destination, err) - } +func (sn *Snapshotter) rideAlong(ctx context.Context, localPath string, rep *Report, shelf snapshotShelf) error { if err := shelf.upload(ctx, localPath, filepath.Base(localPath)); err != nil { return fmt.Errorf("ride-along upload to %s: %w", rep.Destination, err) } @@ -216,22 +212,21 @@ func (s rcloneShelf) remove(ctx context.Context, name string) error { return s.rcl.deleteFile(ctx, s.dir+"/"+name) } -// rcloneShelfOf opens dest's shelf for volumeName through rcl. -func rcloneShelfOf(rcl *Rclone, dest *config.Destination, volumeName string) func() (snapshotShelf, error) { - return func() (snapshotShelf, error) { - return rcloneShelf{rcl: rcl, dir: indexDirURI(dest, volumeName)}, nil - } -} - // transportShelf is a native mirror's .squirrel-index/ directory, reached -// through the push's guarded transport, whose name guard permits removing -// a snapshot there and nothing else. +// through the transport open returns: for a push, its guarded transport, +// whose name guard permits removing a snapshot there and nothing else. type transportShelf struct { - tr transport - dir string + open func(context.Context) (transport, error) + dir string } +// upload removes what a failed Put left behind, so recovery never offers +// a truncated snapshot as the newest. func (s transportShelf) upload(ctx context.Context, localPath, name string) error { + tr, err := s.open(ctx) + if err != nil { + return err + } f, err := os.Open(localPath) if err != nil { return err @@ -241,11 +236,26 @@ func (s transportShelf) upload(ctx context.Context, localPath, name string) erro if err != nil { return err } - return s.tr.Put(ctx, path.Join(s.dir, name), f, fi.ModTime()) + dst := path.Join(s.dir, name) + err = tr.Put(ctx, dst, f, fi.ModTime()) + if err != nil && !errors.Is(err, fs.ErrExist) { + _ = tr.Remove(ctx, dst) + } + return err } func (s transportShelf) snapshots(ctx context.Context) ([]string, error) { - entries, err := s.tr.List(ctx, s.dir) + tr, err := s.open(ctx) + if err != nil { + return nil, err + } + return listSnapshotNames(ctx, tr, s.dir) +} + +// listSnapshotNames lists the snapshots in dir through tr; a dir that +// does not exist holds none. +func listSnapshotNames(ctx context.Context, tr transport, dir string) ([]string, error) { + entries, err := tr.List(ctx, dir) if errors.Is(err, fs.ErrNotExist) { return nil, nil } @@ -262,7 +272,11 @@ func (s transportShelf) snapshots(ctx context.Context) ([]string, error) { } func (s transportShelf) remove(ctx context.Context, name string) error { - return s.tr.Remove(ctx, path.Join(s.dir, name)) + tr, err := s.open(ctx) + if err != nil { + return err + } + return tr.Remove(ctx, path.Join(s.dir, name)) } // indexDirURI returns the rclone URI of the per-volume .squirrel-index/ diff --git a/sync/sync.go b/sync/sync.go index 798efdf..82a8904 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -362,7 +362,7 @@ func Sync(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volume, // terminal state by now, so the snapshot reflects this run's own row. // Destination syncs are eligible for the cloud ride-along; the // Snapshotter no-ops on dry-run and on non-terminal-success states. - opts.Snapshot.afterSync(ctx, &rep, rcloneShelfOf(rcl, dest, vol.Name)) + opts.Snapshot.afterSync(ctx, &rep, rcloneShelf{rcl: rcl, dir: indexDirURI(dest, vol.Name)}) return rep, err } From 0068c2ba3607d6d85cb2e2686709794e2024cc3b Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 02:05:12 +0200 Subject: [PATCH 21/61] sync: let a hung sftp server release the transport pkg/sftp's Close waits for the server to end the session, which a hung server never does, so the push that gave up on a stalled call blocked for good in its deferred close. The transport now drops the ssh connection first. The connect deadline also stays in force until the sftp session has started, so a server whose subsystem never answers fails the dial instead of hanging it. List refuses a name the server returns that is not a single path element, so a hostile server cannot steer a restore out of its target. --- sync/transport_sftp.go | 18 ++++++++----- sync/transport_sftp_dial.go | 31 +++++++++++---------- sync/transport_sftp_test.go | 54 ++++++++++++++++++++++++++++++++----- 3 files changed, 76 insertions(+), 27 deletions(-) diff --git a/sync/transport_sftp.go b/sync/transport_sftp.go index 072faf9..b9ee96a 100644 --- a/sync/transport_sftp.go +++ b/sync/transport_sftp.go @@ -8,6 +8,7 @@ import ( "io/fs" "os" "path" + "strings" "time" "github.com/pkg/sftp" @@ -29,11 +30,11 @@ type sftpTransport struct { fsync bool } +// Close drops the ssh connection first: the sftp client's own Close +// waits for the server to end the session, which a hung server never does. func (t *sftpTransport) Close() error { - err := t.client.Close() - if cerr := t.conn.Close(); err == nil { - err = cerr - } + err := t.conn.Close() + _ = t.client.Close() return err } @@ -65,10 +66,13 @@ func (t *sftpTransport) List(_ context.Context, dir string) ([]entry, error) { } out := make([]entry, 0, len(fis)) for _, fi := range fis { - if fi.Name() == "." || fi.Name() == ".." { - continue + switch name := fi.Name(); { + case name == "." || name == "..": + case !validName(name) || strings.Contains(name, "/"): + return nil, fmt.Errorf("list %s: the server listed %q: %w", dir, name, errInvalidName) + default: + out = append(out, entryOf(fi)) } - out = append(out, entryOf(fi)) } return out, nil } diff --git a/sync/transport_sftp_dial.go b/sync/transport_sftp_dial.go index c7b3eb0..92da8cb 100644 --- a/sync/transport_sftp_dial.go +++ b/sync/transport_sftp_dial.go @@ -41,18 +41,13 @@ func dialSFTP(ctx context.Context, dest *config.Destination) (*sftpTransport, er if algos := dest.Params["host_key_algorithms"]; algos != "" { cfg.HostKeyAlgorithms = strings.Fields(algos) } - conn, err := dialSSH(ctx, sftpAddress(dest), cfg, keys) + tr, err := dialSession(ctx, sftpAddress(dest), cfg, keys) release() if err != nil { return nil, fmt.Errorf("destination %q: %w", dest.Name, err) } - client, err := sftp.NewClient(conn, sftp.UseConcurrentWrites(true)) - if err != nil { - _ = conn.Close() - return nil, fmt.Errorf("destination %q: start sftp: %w", dest.Name, err) - } - data, ok := client.HasExtension(fsyncExtension) - return &sftpTransport{conn: conn, client: client, root: dest.Root, fsync: ok && data == "1"}, nil + tr.root = dest.Root + return tr, nil } // sftpAddress is the host:port dest's server listens on. @@ -64,11 +59,12 @@ func sftpAddress(dest *config.Destination) string { return net.JoinHostPort(dest.Params["host"], port) } -// dialSSH connects to addr and completes the ssh handshake within -// sftpConnectTimeout. Unless the config pins them, the host key -// algorithms follow the keys known_hosts pins, settled once the peer's -// address is known, since known_hosts may pin keys by address. -func dialSSH(ctx context.Context, addr string, cfg *ssh.ClientConfig, keys hostKeys) (*ssh.Client, error) { +// dialSession connects to addr, completes the ssh handshake and starts +// the sftp session, all within sftpConnectTimeout. Unless the config pins +// them, the host key algorithms follow the keys known_hosts pins, settled +// once the peer's address is known, since known_hosts may pin keys by +// address. +func dialSession(ctx context.Context, addr string, cfg *ssh.ClientConfig, keys hostKeys) (*sftpTransport, error) { ctx, cancel := context.WithTimeout(ctx, sftpConnectTimeout) defer cancel() var d net.Dialer @@ -86,8 +82,15 @@ func dialSSH(ctx context.Context, addr string, cfg *ssh.ClientConfig, keys hostK _ = tcp.Close() return nil, fmt.Errorf("ssh to %s: %w", addr, err) } + conn := ssh.NewClient(c, chans, reqs) + client, err := sftp.NewClient(conn, sftp.UseConcurrentWrites(true)) + if err != nil { + _ = conn.Close() + return nil, fmt.Errorf("start sftp on %s: %w", addr, err) + } _ = tcp.SetDeadline(time.Time{}) - return ssh.NewClient(c, chans, reqs), nil + data, ok := client.HasExtension(fsyncExtension) + return &sftpTransport{conn: conn, client: client, fsync: ok && data == "1"}, nil } // sftpAuth is how squirrel logs in: with the key file and the password diff --git a/sync/transport_sftp_test.go b/sync/transport_sftp_test.go index 6a4f1fc..a785bf9 100644 --- a/sync/transport_sftp_test.go +++ b/sync/transport_sftp_test.go @@ -32,6 +32,9 @@ type sftpTestServer struct { // clientKey is the private half of the one client key the server // accepts. clientKey ed25519.PrivateKey + // hung, once closed, makes the sftp subsystem stop reading requests, + // as a server whose disk hangs does. + hung chan struct{} } func newKey(t *testing.T) (ed25519.PrivateKey, ssh.Signer) { @@ -61,7 +64,7 @@ func startSFTPServer(t *testing.T, hostKeys ...ssh.Signer) *sftpTestServer { hostKeys = []ssh.Signer{newSigner(t)} } clientKey, clientSigner := newKey(t) - srv := &sftpTestServer{hostKeys: hostKeys, clientKey: clientKey} + srv := &sftpTestServer{hostKeys: hostKeys, clientKey: clientKey, hung: make(chan struct{})} cfg := &ssh.ServerConfig{ PasswordCallback: func(c ssh.ConnMetadata, pw []byte) (*ssh.Permissions, error) { if c.User() == "u" && string(pw) == "p" { @@ -91,13 +94,13 @@ func startSFTPServer(t *testing.T, hostKeys ...ssh.Signer) *sftpTestServer { if err != nil { return } - go serveSSH(c, cfg) + go serveSSH(c, cfg, srv.hung) } }() return srv } -func serveSSH(c net.Conn, cfg *ssh.ServerConfig) { +func serveSSH(c net.Conn, cfg *ssh.ServerConfig, hung chan struct{}) { defer func() { _ = c.Close() }() _, chans, reqs, err := ssh.NewServerConn(c, cfg) if err != nil { @@ -118,22 +121,39 @@ func serveSSH(c net.Conn, cfg *ssh.ServerConfig) { ok := r.Type == "subsystem" && len(r.Payload) > 4 && string(r.Payload[4:]) == "sftp" _ = r.Reply(ok, nil) if ok { - go serveSFTP(ch) + go serveSFTP(ch, hung) } } }() } } -func serveSFTP(ch ssh.Channel) { +func serveSFTP(ch ssh.Channel, hung chan struct{}) { defer func() { _ = ch.Close() }() - s, err := sftp.NewServer(ch) + s, err := sftp.NewServer(hangingChannel{Channel: ch, hung: hung}) if err != nil { return } _ = s.Serve() } +// hangingChannel stops delivering requests, even the end of the session, +// once hung is closed. +type hangingChannel struct { + ssh.Channel + hung chan struct{} +} + +func (h hangingChannel) Read(p []byte) (int, error) { + n, err := h.Channel.Read(p) + select { + case <-h.hung: + select {} + default: + return n, err + } +} + // knownHosts writes a known_hosts file pinning keys for the server. func (s *sftpTestServer) knownHosts(t *testing.T, keys ...ssh.PublicKey) string { t.Helper() @@ -215,6 +235,28 @@ func TestSFTPServersRenameOverAnExistingName(t *testing.T) { } } +// TestSFTPHungServerReleasesTheTransport: a server that stops answering +// neither wedges Close nor a dial past its deadline, so a push that gave +// up on a stalled call can always end. +func TestSFTPHungServerReleasesTheTransport(t *testing.T) { + srv := startSFTPServer(t) + tr := mustDialSFTP(t, srv.destination(t, t.TempDir())) + close(srv.hung) + closed := make(chan error, 1) + go func() { closed <- tr.Close() }() + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Fatal("Close blocked on a hung server") + } + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + if _, err := dialSFTP(ctx, srv.destination(t, t.TempDir())); err == nil { + t.Fatal("dial of a server whose sftp subsystem never answers succeeded") + } +} + func TestSFTPRefusesUnknownHostKey(t *testing.T) { srv := startSFTPServer(t) dest := srv.destination(t, t.TempDir()) From 2cc55a9bced275aee0b0e95be93324bbd3101f3c Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 02:05:12 +0200 Subject: [PATCH 22/61] sync: land the marker and the ride-along snapshot whole or not at all MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both were written straight to their final name, so a write that failed halfway left a marker that does not parse — refused on every later push, --init included — or a truncated snapshot that recover offered as the newest. Cleaning up after the failure cannot work when the link is what failed. Both are now staged and renamed onto their name, as every mirrored path is. The name guard gains the two rules that takes: from this run's staging onto a snapshot name, and, under --init only, the marker's own staging name onto .squirrel-volume. A partial copy stays in staging, where reconcile clears a finished run's and the next --init the marker's. --- design/native-mirror.md | 12 ++++++-- sync/mirror.go | 11 +++++-- sync/mirror_marker.go | 22 ++++++++++---- sync/mirror_reconcile.go | 3 ++ sync/mirror_snapshot_test.go | 56 ++++++++++++++++++++++++++++++------ sync/snapshot.go | 31 +++++++++++--------- sync/transport_guard.go | 43 +++++++++++++++++++++++---- sync/transport_guard_test.go | 35 ++++++++++++++++++++++ 8 files changed, 174 insertions(+), 39 deletions(-) diff --git a/design/native-mirror.md b/design/native-mirror.md index d365672..2fd62ad 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -250,8 +250,16 @@ type transport interface { finished (`.squirrel-staging/run-/`), and on ride-along snapshots (`.squirrel-index/index-*.db`, which rotation already deletes today). Anything else found in staging is reported and left alone; - - `Rename` only from staging to a live name (commit), or from a live name - to `.squirrel-history/run-/` (displacement). + - `Rename` only from this run's staging to a live name (commit) or to a + snapshot name (the ride-along), or from a live name to + `.squirrel-history/run-/` (displacement); + - under `--init`, before the push holds a run, the marker's own staging: + it is written to `.squirrel-staging/volume-marker` and renamed onto + `.squirrel-volume`, and a stale staged copy may be removed. + + So the marker and the ride-along snapshot land whole or not at all, like + every path: a write that fails halfway leaves its partial copy in staging, + never at a name recovery or the marker gate reads. That function is the whole audit surface for destroying or moving bytes on a destination. diff --git a/sync/mirror.go b/sync/mirror.go index a1fefe4..c7f95f4 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -61,6 +61,11 @@ func (h *mirrorHandler) Push(ctx context.Context, opts Options) (Report, error) // root is the destination root as a layout may hold it: guarded, so only // runID's own moves pass (none when runID is 0), and bounded by progress. func (h *mirrorHandler) root(ctx context.Context, runID int64) (transport, error) { + return h.guarded(ctx, nameGuard{volumeDir: h.vol.Name, runID: runID, finished: h.runFinished}) +} + +// guarded is the destination root behind guard, bounded by progress. +func (h *mirrorHandler) guarded(ctx context.Context, guard nameGuard) (transport, error) { if h.raw == nil { raw, err := h.openTransport(ctx, h.dest) if err != nil { @@ -68,7 +73,6 @@ func (h *mirrorHandler) root(ctx context.Context, runID int64) (transport, error } h.raw = raw } - guard := nameGuard{volumeDir: h.vol.Name, runID: runID, finished: h.runFinished} return stallTransport{ transport: guardedTransport{transport: h.raw, guard: guard}, timeout: h.stallTimeout, @@ -192,8 +196,9 @@ func (h *mirrorHandler) advanceMethod(context.Context, *Report, pushPlan) (strin // guarded transport. func (h *mirrorHandler) shelf(runID int64) snapshotShelf { return transportShelf{ - open: func(ctx context.Context) (transport, error) { return h.root(ctx, runID) }, - dir: path.Join(h.vol.Name, IndexDirName), + open: func(ctx context.Context) (transport, error) { return h.root(ctx, runID) }, + volume: h.vol.Name, + runID: runID, } } diff --git a/sync/mirror_marker.go b/sync/mirror_marker.go index 494643e..4ed6613 100644 --- a/sync/mirror_marker.go +++ b/sync/mirror_marker.go @@ -19,17 +19,17 @@ const maxMarkerBytes = 64 << 10 // ensureMarker is a native mirror's gate against a wrong or unmounted // root: the destination's /.squirrel-volume must name this volume. -// A missing marker is written only under init, through an exclusive Put, -// and a marker naming another volume, or one that does not parse, is -// always refused and never overwritten. A local root that does not exist -// yet is created under init, so a first push can land on an empty disk. +// A missing marker is written only under init, and a marker naming another +// volume, or one that does not parse, is always refused and never +// overwritten. A local root that does not exist yet is created under init, +// so a first push can land on an empty disk. func (h *mirrorHandler) ensureMarker(ctx context.Context, init bool) error { if init && h.dest.Type == "local" { if err := os.MkdirAll(h.dest.Root, 0o755); err != nil { return fmt.Errorf("destination %q: create root %s: %w", h.dest.Name, h.dest.Root, err) } } - tr, err := h.root(ctx, 0) + tr, err := h.guarded(ctx, nameGuard{volumeDir: h.vol.Name, bootstrap: init}) if err != nil { return err } @@ -58,6 +58,9 @@ func (h *mirrorHandler) checkMarker(name string, data []byte) error { return nil } +// writeMarker stages the marker, then renames it onto name, so a write +// that fails halfway never leaves a marker that does not parse. A copy an +// earlier --init left staged is cleared first. func (h *mirrorHandler) writeMarker(ctx context.Context, tr transport, name string) error { m, err := selfMarker(ctx, h.store, h.vol.Name) if err != nil { @@ -67,7 +70,14 @@ func (h *mirrorHandler) writeMarker(ctx context.Context, tr transport, name stri if err != nil { return fmt.Errorf("destination %q: %w", h.dest.Name, err) } - if err := tr.Put(ctx, name, bytes.NewReader(data), time.Now()); err != nil { + staged := markerStagingName(h.vol.Name) + if err := tr.Remove(ctx, staged); err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("destination %q: clear the staged marker %s: %w", h.dest.Name, h.where(staged), err) + } + if err := tr.Put(ctx, staged, bytes.NewReader(data), time.Now()); err != nil { + return fmt.Errorf("destination %q: write %s: %w", h.dest.Name, h.where(staged), err) + } + if err := tr.Rename(ctx, staged, name); err != nil { return fmt.Errorf("destination %q: write %s: %w", h.dest.Name, h.where(name), err) } return nil diff --git a/sync/mirror_reconcile.go b/sync/mirror_reconcile.go index ec1af0c..410af46 100644 --- a/sync/mirror_reconcile.go +++ b/sync/mirror_reconcile.go @@ -139,6 +139,9 @@ func (h *mirrorHandler) clearFinishedStaging(ctx context.Context, rep *Report, t return fmt.Errorf("list %s: %w", dir, err) } for _, e := range runs { + if e.name == markerStagingBase { + continue + } runID, ok := stagingRunID(e) if !ok { h.warnForeignStaging(rep, path.Join(dir, e.name)) diff --git a/sync/mirror_snapshot_test.go b/sync/mirror_snapshot_test.go index 7f2f029..63b34b1 100644 --- a/sync/mirror_snapshot_test.go +++ b/sync/mirror_snapshot_test.go @@ -12,6 +12,8 @@ import ( "time" "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" ) // TestMirrorRideAlongThroughTheTransport: a native mirror's ride-along @@ -102,18 +104,29 @@ func (p partialPuts) Put(ctx context.Context, name string, r io.Reader, mtime ti return errors.New("the link dropped") } +// withPartialPuts makes the fixture's handler land only one byte of every +// Put whose name match selects. +func (f *mirrorFixture) withPartialPuts(t *testing.T, match func(name string) bool) *mirrorHandler { + t.Helper() + h := f.handler(t) + h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + return partialPuts{transport: raw, match: match}, err + } + return h +} + // TestMirrorRideAlongLeavesNoPartialSnapshot: a snapshot upload that fails -// halfway is removed again, so recovery never offers a truncated snapshot -// as the newest; the push itself still succeeds. +// halfway leaves nothing in .squirrel-index/, so recovery never offers a +// truncated snapshot as the newest — even when the link is gone and +// nothing could be cleaned up. The push itself still succeeds, and the +// partial copy goes with its run's staging at the next push. func TestMirrorRideAlongLeavesNoPartialSnapshot(t *testing.T) { f := setupMirrorFixture(t) f.write(t, "a.txt", "alpha") f.index(t) - h := f.handler(t) - h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { - raw, err := openDestinationTransport(ctx, d) - return partialPuts{transport: raw, match: func(name string) bool { return isSnapshotName(filepath.Base(name)) }}, err - } + f.mustPush(t) + h := f.withPartialPuts(t, func(name string) bool { return strings.Contains(name, StagingDirName+"/") }) sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) rep, err := h.Push(context.Background(), Options{Snapshot: sn}) if err != nil || rep.SnapshotErr == nil { @@ -125,7 +138,34 @@ func TestMirrorRideAlongLeavesNoPartialSnapshot(t *testing.T) { } for _, e := range entries { if isSnapshotName(e.Name()) { - t.Fatalf("the partial snapshot %s stayed on the mirror", e.Name()) + t.Fatalf("the partial snapshot %s reached .squirrel-index", e.Name()) } } + clean := f.mustPush(t) + f.checkStagingEmpty(t, clean.RunID) +} + +// TestMirrorMarkerWriteIsAllOrNothing: an --init whose marker write fails +// halfway leaves no marker that does not parse, so the next --init +// succeeds. +func TestMirrorMarkerWriteIsAllOrNothing(t *testing.T) { + f := setupMirrorFixture(t) + if err := os.Remove(f.dest(volmark.MarkerName)); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "alpha") + f.index(t) + h := f.withPartialPuts(t, func(name string) bool { return name == markerStagingName("pics") }) + if _, err := h.Push(context.Background(), Options{Init: true}); err == nil { + t.Fatal("an --init whose marker write failed succeeded") + } + if _, err := os.Stat(f.dest(volmark.MarkerName)); !os.IsNotExist(err) { + t.Fatalf("a failed marker write left a marker behind: %v", err) + } + if rep, err := f.push(t, Options{Init: true}); err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("the next --init: status=%q err=%v", rep.Status, err) + } + if err := volmark.Validate(f.dest(""), "pics"); err != nil { + t.Fatalf("marker after the retried --init: %v", err) + } } diff --git a/sync/snapshot.go b/sync/snapshot.go index 8fd0a35..c38750c 100644 --- a/sync/snapshot.go +++ b/sync/snapshot.go @@ -212,16 +212,20 @@ func (s rcloneShelf) remove(ctx context.Context, name string) error { return s.rcl.deleteFile(ctx, s.dir+"/"+name) } -// transportShelf is a native mirror's .squirrel-index/ directory, reached -// through the transport open returns: for a push, its guarded transport, -// whose name guard permits removing a snapshot there and nothing else. +// transportShelf is a native mirror's /.squirrel-index/, reached +// through runID's guarded transport, which open returns. type transportShelf struct { - open func(context.Context) (transport, error) - dir string + open func(context.Context) (transport, error) + volume string + runID int64 } -// upload removes what a failed Put left behind, so recovery never offers -// a truncated snapshot as the newest. +func (s transportShelf) dir() string { return path.Join(s.volume, IndexDirName) } + +// upload stages the snapshot in runID's staging, then renames it onto +// name, so an upload that fails halfway never leaves a truncated snapshot +// for recovery to offer as the newest. A partial staged copy goes with the +// run's staging at the next push. func (s transportShelf) upload(ctx context.Context, localPath, name string) error { tr, err := s.open(ctx) if err != nil { @@ -236,12 +240,11 @@ func (s transportShelf) upload(ctx context.Context, localPath, name string) erro if err != nil { return err } - dst := path.Join(s.dir, name) - err = tr.Put(ctx, dst, f, fi.ModTime()) - if err != nil && !errors.Is(err, fs.ErrExist) { - _ = tr.Remove(ctx, dst) + staged := stagingName(s.volume, s.runID, stagingKey(path.Join(IndexDirName, name))) + if err := tr.Put(ctx, staged, f, fi.ModTime()); err != nil { + return err } - return err + return tr.Rename(ctx, staged, path.Join(s.dir(), name)) } func (s transportShelf) snapshots(ctx context.Context) ([]string, error) { @@ -249,7 +252,7 @@ func (s transportShelf) snapshots(ctx context.Context) ([]string, error) { if err != nil { return nil, err } - return listSnapshotNames(ctx, tr, s.dir) + return listSnapshotNames(ctx, tr, s.dir()) } // listSnapshotNames lists the snapshots in dir through tr; a dir that @@ -276,7 +279,7 @@ func (s transportShelf) remove(ctx context.Context, name string) error { if err != nil { return err } - return tr.Remove(ctx, path.Join(s.dir, name)) + return tr.Remove(ctx, path.Join(s.dir(), name)) } // indexDirURI returns the rclone URI of the per-volume .squirrel-index/ diff --git a/sync/transport_guard.go b/sync/transport_guard.go index 7138332..e5e5bd2 100644 --- a/sync/transport_guard.go +++ b/sync/transport_guard.go @@ -21,6 +21,9 @@ var errGuardRefused = errors.New("the name guard refuses this operation") type nameGuard struct { volumeDir string // the volume's directory under the destination root runID int64 // the push holding the guard + // bootstrap lets a push under --init write the volume marker, before + // it holds a run. + bootstrap bool // finished reports whether a run has ended, so its staging may go. finished func(runID int64) bool } @@ -33,17 +36,28 @@ const ( ) // permit is the whole audit surface for destroying or moving bytes on a -// destination. A guard held by no run (runID 0, a dry run's reads) refuses -// everything; otherwise it allows: +// destination. A bootstrap guard allows, run or not: +// +// - Remove of the staged marker, /.squirrel-staging/volume-marker, +// and its Rename onto /.squirrel-volume. +// +// Beyond that, a guard held by no run (runID 0, a dry run's reads) +// refuses everything; otherwise it allows: // // - Remove of a staging entry, or an emptied staging run directory, // of a run that has finished: /.squirrel-staging/run-[/]; // - Remove of a ride-along snapshot: /.squirrel-index/index-*.db; -// - Rename from this run's staging onto a live name (a commit); +// - Rename from this run's staging onto a live name (a commit), or onto +// a snapshot name (the ride-along); // - Rename of a live name to the same path under this run's history // (a displacement): /.squirrel-history/run-/. +// +// Every Rename lands on a name that does not exist yet: the transport +// fails one onto an existing name. func (g nameGuard) permit(op guardOp, name, to string) error { switch { + case g.bootstrap && name == markerStagingName(g.volumeDir) && (op == opRemove || to == path.Join(g.volumeDir, volmark.MarkerName)): + return nil case g.runID == 0: case op == opRemove: if g.removable(name) { @@ -53,16 +67,23 @@ func (g nameGuard) permit(op guardOp, name, to string) error { if rel, ok := g.liveRel(name); ok && to == historyName(g.volumeDir, g.runID, rel) { return nil } - if _, ok := g.liveRel(to); ok && g.stagedByThisRun(name) { + if _, ok := g.liveRel(to); (ok || g.snapshot(to)) && g.stagedByThisRun(name) { return nil } } return fmt.Errorf("%w: %s %q → %q", errGuardRefused, [...]string{"remove", "rename"}[op], name, to) } +// snapshot reports whether name is a ride-along snapshot of the volume: +// /.squirrel-index/index-*.db. +func (g nameGuard) snapshot(name string) bool { + rel, ok := strings.CutPrefix(name, g.volumeDir+"/"+IndexDirName+"/") + return ok && !strings.Contains(rel, "/") && isSnapshotName(rel) +} + func (g nameGuard) removable(name string) bool { - if rel, ok := strings.CutPrefix(name, g.volumeDir+"/"+IndexDirName+"/"); ok { - return !strings.Contains(rel, "/") && isSnapshotName(rel) + if g.snapshot(name) { + return true } runID, key, ok := g.stagingParts(name) if !ok || runID == g.runID || !g.finished(runID) { @@ -111,6 +132,16 @@ func historyName(volumeDir string, runID int64, rel string) string { return path.Join(volumeDir, HistoryDirName, "run-"+strconv.FormatInt(runID, 10), rel) } +// markerStagingBase is the staging name the volume marker is written to +// before it is renamed onto .squirrel-volume. +const markerStagingBase = "volume-marker" + +// markerStagingName is where a --init push stages the volume marker: +// /.squirrel-staging/volume-marker. +func markerStagingName(volumeDir string) string { + return path.Join(volumeDir, StagingDirName, markerStagingBase) +} + // stagingName is where runID stages the path whose key is key: // /.squirrel-staging/run-/. func stagingName(volumeDir string, runID int64, key string) string { diff --git a/sync/transport_guard_test.go b/sync/transport_guard_test.go index 1846f56..8236173 100644 --- a/sync/transport_guard_test.go +++ b/sync/transport_guard_test.go @@ -42,6 +42,12 @@ func TestNameGuardPermits(t *testing.T) { {"remove a live file", opRemove, "pics/2024/cat.jpg", "", false}, {"remove history", opRemove, "pics/.squirrel-history/run-6/cat.jpg", "", false}, {"remove another volume's staging", opRemove, "docs/.squirrel-staging/run-6/" + key, "", false}, + {"ride a snapshot along from this run's staging", opRename, "pics/.squirrel-staging/run-7/" + key, "pics/.squirrel-index/index-20260101T000000.000Z-run-7.db", true}, + {"stage onto a receipt", opRename, "pics/.squirrel-staging/run-7/" + key, "pics/.squirrel-index/run-7", false}, + {"ride a snapshot along from another run's staging", opRename, "pics/.squirrel-staging/run-6/" + key, "pics/.squirrel-index/index-20260101T000000.000Z-run-7.db", false}, + {"move a live file onto a snapshot name", opRename, "pics/a.db", "pics/.squirrel-index/index-20260101T000000.000Z-run-7.db", false}, + {"marker bootstrap without --init", opRename, "pics/.squirrel-staging/volume-marker", "pics/.squirrel-volume", false}, + {"remove the staged marker without --init", opRemove, "pics/.squirrel-staging/volume-marker", "", false}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -58,3 +64,32 @@ func TestNameGuardPermits(t *testing.T) { }) } } + +// TestNameGuardBootstrap: under --init the guard also lets the marker be +// staged, renamed onto .squirrel-volume, and a stale staged copy removed — +// run or not — and nothing more. +func TestNameGuardBootstrap(t *testing.T) { + cases := []struct { + name string + op guardOp + from, to string + want bool + }{ + {"rename the staged marker onto the marker", opRename, "pics/.squirrel-staging/volume-marker", "pics/.squirrel-volume", true}, + {"remove a stale staged marker", opRemove, "pics/.squirrel-staging/volume-marker", "", true}, + {"rename the staged marker elsewhere", opRename, "pics/.squirrel-staging/volume-marker", "pics/a.txt", false}, + {"rename something else onto the marker", opRename, "pics/a.txt", "pics/.squirrel-volume", false}, + {"remove the marker", opRemove, "pics/.squirrel-volume", "", false}, + {"another volume's staged marker", opRename, "docs/.squirrel-staging/volume-marker", "docs/.squirrel-volume", false}, + {"remove a live file", opRemove, "pics/a.txt", "", false}, + } + g := nameGuard{volumeDir: "pics", bootstrap: true} + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + err := g.permit(c.op, c.from, c.to) + if got := err == nil; got != c.want { + t.Fatalf("permit = %v, want allowed=%t", err, c.want) + } + }) + } +} From 2dbce81422adba1f3d55b80061af3f1e0c5b4978 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 02:05:13 +0200 Subject: [PATCH 23/61] sync: skip a broken receipt whole, and read restores in large blocks A receipt that failed to parse still contributed the lines before the error; it now contributes nothing, as its warning says. The restore walk refuses a listed name that is not a single path element. Copies out of a transport read in 1 MiB blocks: io.Copy's 32 KiB reads through the stall reader cost one sftp round trip each, while pkg/sftp splits a large read into concurrent requests. A few comments lose overlong lines and a reference to the removed local gate. --- config/destinations.go | 4 +- sync/recover.go | 2 +- sync/restore_mirror.go | 25 ++++++++----- sync/restore_mirror_test.go | 68 ++++++++++++++++++++++++++++++++++ sync/restore_place.go | 9 ++--- sync/sync.go | 14 +++---- sync/transport.go | 6 +++ sync/transport_sftp_hostkey.go | 6 +-- 8 files changed, 107 insertions(+), 27 deletions(-) diff --git a/config/destinations.go b/config/destinations.go index 96310c4..44f51d9 100644 --- a/config/destinations.go +++ b/config/destinations.go @@ -834,8 +834,8 @@ func sortedSubset(in []string) []string { } // NativeMirror reports whether squirrel writes this destination itself, -// through its own transport, instead of driving rclone: a mirror on a -// local disk, or on an sftp server without crypt. +// through its own transport: a mirror on a local disk, or on an sftp +// server without crypt. func (d *Destination) NativeMirror() bool { return nativeMirror(d.Type, d.Layout, d.Crypt != nil) } diff --git a/sync/recover.go b/sync/recover.go index d3d7269..9e2dd59 100644 --- a/sync/recover.go +++ b/sync/recover.go @@ -174,7 +174,7 @@ func fetchThroughTransport(ctx context.Context, dest *config.Destination, name, if err != nil { return err } - if _, err := io.Copy(f, ctxReader{ctx: ctx, r: rc}); err != nil { + if _, err := io.CopyBuffer(f, ctxReader{ctx: ctx, r: rc}, make([]byte, copyBufferSize)); err != nil { _ = f.Close() return err } diff --git a/sync/restore_mirror.go b/sync/restore_mirror.go index 93bf002..a5cbf28 100644 --- a/sync/restore_mirror.go +++ b/sync/restore_mirror.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "io/fs" + "maps" "path" "slices" "strconv" @@ -148,6 +149,8 @@ func (mr *mirrorRestore) walk(ctx context.Context, rep *Report, dir string, visi for _, e := range entries { rel := path.Join(dir, e.name) switch { + case !validName(rel) || path.Base(rel) != e.name: + return fmt.Errorf("list %s on %q: %w: %q", name, mr.dest.Name, errInvalidName, e.name) case dir == "" && (isReservedFolderPath(e.name) || e.name == volmark.MarkerName): case e.kind == kindDir: if err := mr.walk(ctx, rep, rel, visit); err != nil { @@ -185,9 +188,12 @@ func (mr *mirrorRestore) readReceipts(ctx context.Context, rep *Report) (map[str out := map[string][]byte{} for _, id := range runs { name := path.Join(dir, "run-"+strconv.FormatInt(id, 10)) - if err := foldReceipt(ctx, mr.tr, name, out); err != nil { + entries, err := readReceipt(ctx, mr.tr, name) + if err != nil { rep.Warnings = append(rep.Warnings, fmt.Sprintf("receipt %s on %q could not be read (%v); the files it names are checked against older receipts", name, mr.dest.Name, err)) + continue } + maps.Copy(out, entries) } return out, nil } @@ -202,29 +208,30 @@ func receiptRunID(e entry) (int64, bool) { return id, err == nil && id > 0 && strconv.FormatInt(id, 10) == idText } -// foldReceipt records into the content of every present path the receipt -// at name lists. -func foldReceipt(ctx context.Context, tr transport, name string, into map[string][]byte) error { +// readReceipt maps every present path the receipt at name lists to its +// BLAKE3. +func readReceipt(ctx context.Context, tr transport, name string) (map[string][]byte, error) { rc, err := tr.Get(ctx, name) if err != nil { - return err + return nil, err } defer func() { _ = rc.Close() }() + out := map[string][]byte{} sc := bufio.NewScanner(ctxReader{ctx: ctx, r: rc}) sc.Buffer(make([]byte, 0, 64<<10), 1<<20) for sc.Scan() { var e ManifestEntry if err := json.Unmarshal(sc.Bytes(), &e); err != nil { - return err + return nil, err } if e.Status != store.StatusPresent { continue } sum, err := hex.DecodeString(e.Blake3) if err != nil || len(sum) != 32 { - return fmt.Errorf("%s: blake3 %q is not a 32-byte hex hash", e.Path, e.Blake3) + return nil, fmt.Errorf("%s: blake3 %q is not a 32-byte hex hash", e.Path, e.Blake3) } - into[e.Path] = sum + out[e.Path] = sum } - return sc.Err() + return out, sc.Err() } diff --git a/sync/restore_mirror_test.go b/sync/restore_mirror_test.go index d5aea0b..a999ebb 100644 --- a/sync/restore_mirror_test.go +++ b/sync/restore_mirror_test.go @@ -2,6 +2,7 @@ package sync import ( "context" + "errors" "os" "path/filepath" "strconv" @@ -139,3 +140,70 @@ func TestMirrorRestoreInPlacePreservesWhatItReplaces(t *testing.T) { t.Fatalf("restore history holds %q, want the replaced local edit", got) } } + +// escapingListing lists one extra file whose name climbs out of its +// directory, as a hostile or broken server might. +type escapingListing struct{ transport } + +func (e escapingListing) List(ctx context.Context, dir string) ([]entry, error) { + entries, err := e.transport.List(ctx, dir) + return append(entries, entry{name: "../escaped", kind: kindFile, size: 1}), err +} + +// TestMirrorRestoreRefusesAnEscapingName: a walked name that is not a +// single path element stops the restore before anything lands outside +// the target. +func TestMirrorRestoreRefusesAnEscapingName(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + raw, err := openLocalTransport(f.dst) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = raw.Close() }) + parent := t.TempDir() + target := filepath.Join(parent, "target") + mr := &mirrorRestore{store: f.store, vol: f.pair.Volume, dest: f.pair.Destination, + tr: escapingListing{raw}, placer: restorePlacer{target: target}} + var rep Report + if err := mr.restoreWalked(context.Background(), &rep); !errors.Is(err, errInvalidName) { + t.Fatalf("walk over an escaping name = %v, want errInvalidName", err) + } + if _, err := os.Stat(filepath.Join(parent, "escaped")); !os.IsNotExist(err) { + t.Fatalf("a file landed outside the target: %v", err) + } +} + +// TestMirrorRestoreSkipsABrokenReceiptWhole: a receipt that does not +// parse contributes nothing, not even its readable lines, so the files it +// names are checked against the receipts before it. +func TestMirrorRestoreSkipsABrokenReceiptWhole(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2") + f.index(t) + second := f.mustPush(t) + receipt := f.dest(IndexDirName + "/run-" + strconv.FormatInt(second.RunID, 10)) + file, err := os.OpenFile(receipt, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + if _, err := file.WriteString("{not json\n"); err != nil { + t.Fatal(err) + } + _ = file.Close() + + fresh, err := store.Open(filepath.Join(t.TempDir(), "fresh.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fresh.Close() }) + rep, err := f.restore(t, fresh, RestoreOptions{ToPath: t.TempDir()}) + if err == nil || rep.RcloneResult.Errors != 1 || !warned(rep, "could not be read") { + t.Fatalf("restore = %v, errors=%d warnings=%v; want the broken receipt reported and a.txt checked against the older one", err, rep.RcloneResult.Errors, rep.Warnings) + } +} diff --git a/sync/restore_place.go b/sync/restore_place.go index b520552..8e79da6 100644 --- a/sync/restore_place.go +++ b/sync/restore_place.go @@ -73,7 +73,7 @@ func stageRestored(dst string, r io.Reader, want []byte, mtime time.Time) (strin return "", 0, err } h := blake3.New() - n, err := io.Copy(io.MultiWriter(f, h), r) + n, err := io.CopyBuffer(io.MultiWriter(f, h), r, make([]byte, copyBufferSize)) if err == nil && want != nil && !bytes.Equal(h.Sum(nil), want) { err = fmt.Errorf("the bytes hash to %s, want %s", hex.EncodeToString(h.Sum(nil)), hex.EncodeToString(want)) } @@ -129,10 +129,9 @@ func (pl restorePlacer) backupExisting(rel, dst string) error { } // refuseNonRegularTarget refuses to write when the destination already -// exists as anything other than a regular file. A symlink, device, fifo, -// socket, or directory is a hard refusal, not a silent skip: squirrel -// never replaces what it does not understand. An absent path or a plain -// regular file is allowed. +// exists as anything other than a regular file — a symlink, device, fifo, +// socket, or directory — and reports it: squirrel replaces only a plain +// file it can preserve. An absent path or a regular file is allowed. func refuseNonRegularTarget(rel, dst string) error { info, err := os.Lstat(dst) if errors.Is(err, os.ErrNotExist) { diff --git a/sync/sync.go b/sync/sync.go index 82a8904..30f27ca 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -313,9 +313,9 @@ func Sync(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volume, } // Marker gate, read and (with --init) written through the same - // overlay the transfer uses. The dry-run path skips: it never writes, and refusing a dry-run on - // an uninitialised destination would prevent the "preview what would - // happen" workflow. + // overlay the transfer uses. The dry-run path skips: it never writes, + // and refusing a dry-run on an uninitialised destination would + // prevent the "preview what would happen" workflow. if !opts.DryRun { if merr := ensureRemoteDestinationMarker(ctx, s, rcl, dest, vol.Name, opts.Init); merr != nil { // A marker refusal fires before the sync run is allocated, so @@ -633,10 +633,10 @@ func validateLocalVolumeMarker(vol *config.Volume) error { // mirrors on s3/b2/gcs, and the content layouts). It validates (or, with // init, writes) the .squirrel-volume marker at the per-volume root: a // matching marker passes, a missing one is bootstrapped only under init, -// and one naming a different volume is always refused. It probes the marker at the per-volume -// root through remoteSubpathURI — the same overlay the layout's -// transfers use, so a crypt destination's marker rides the encrypted -// path too — and applies the identical rules as the local gate. +// and one naming a different volume is always refused. It probes the +// marker through remoteSubpathURI — the same overlay the layout's +// transfers use, so a crypt destination's marker rides the encrypted path +// too — and applies the same rules as a native mirror's gate. // Presence is decided by a stat (statRemoteExists), not by the read: // only a definite absence is eligible for an --init bootstrap, a present // marker is read and validated (a mismatch is always refused and never diff --git a/sync/transport.go b/sync/transport.go index 032ff39..3987671 100644 --- a/sync/transport.go +++ b/sync/transport.go @@ -134,6 +134,12 @@ func entryOf(fi fs.FileInfo) entry { return entry{name: fi.Name(), kind: kindOf(fi.Mode()), size: fi.Size(), mtime: fi.ModTime()} } +// copyBufferSize is the buffer a copy out of a transport reads with. A +// read this large lets the sftp client split it into concurrent requests, +// so a high-latency link does not cap a download at one round trip per +// 32 KiB. +const copyBufferSize = 1 << 20 + // ctxReader stops a streaming copy once its context is done. type ctxReader struct { ctx context.Context diff --git a/sync/transport_sftp_hostkey.go b/sync/transport_sftp_hostkey.go index 13031b0..ac0e487 100644 --- a/sync/transport_sftp_hostkey.go +++ b/sync/transport_sftp_hostkey.go @@ -81,9 +81,9 @@ func (h hostKeys) check(host string, remote net.Addr, key ssh.PublicKey) error { } // algorithms lists the host key algorithms of the keys known_hosts pins -// for host, so the handshake asks the server for a key squirrel can check -// instead of one it has never seen. It returns nil, the client's -// defaults, when known_hosts pins nothing for host. +// for host, so the handshake asks the server for a key squirrel can check. +// It returns nil, the client's defaults, when known_hosts pins nothing for +// host. func (h hostKeys) algorithms(host string, remote net.Addr) []string { probe, err := probeKey() if err != nil { From 73293473bb22249c3cd1db661cf63b8e9f7f0050 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 02:33:10 +0200 Subject: [PATCH 24/61] store: record a mirror copy's read-back fingerprint, and let the gate count it remote_paths rows carry the BLAKE3 a read of the stored bytes confirmed. The pending-fingerprint tally and the per-content gate check count a live or displaced copy that records one. New reads serve the mirror verify pass (every stored row, least recently verified first) and the planner's repairs (present paths whose current content the destination lost). Migration v33 indexes remote_paths by content and its lost rows. --- store/content_presence.go | 45 ++++++---- store/migrate_v27_test.go | 2 +- store/migrations.go | 29 ++++++- store/remote_paths.go | 56 +++++++++---- store/remote_paths_evidence.go | 85 +++++++++++++++++++ store/remote_paths_test.go | 146 +++++++++++++++++++++++++++++++++ store/schema.sql | 6 +- 7 files changed, 333 insertions(+), 36 deletions(-) create mode 100644 store/remote_paths_evidence.go diff --git a/store/content_presence.go b/store/content_presence.go index 8718e98..fec3f6b 100644 --- a/store/content_presence.go +++ b/store/content_presence.go @@ -37,11 +37,11 @@ func (s *Store) ContentPresentOnDestination(ctx context.Context, contentID int64 // contents of the volume that do NOT yet carry a verified provider // fingerprint on the destination — the whole-state "pending artifact" // tally the fingerprint-verified upgrade gates on. A content counts as -// pending unless it has either a remote_objects row or a member pack's -// remote_packs row on this destination with a non-NULL checksum and -// verified_at_ns, so content not yet uploaded, uploaded but not yet -// fingerprinted, or fingerprinted but not yet re-confirmed all keep the -// tally above zero. Zero means every present content is fingerprint- +// pending unless a remote_objects row, a member pack's remote_packs row, or +// a live or displaced mirror copy's remote_paths row on this destination +// carries a non-NULL checksum and verified_at_ns, so content not yet +// uploaded, uploaded but not yet fingerprinted, or fingerprinted but not +// yet re-confirmed all keep the tally above zero. Zero means every present content is fingerprint- // verified on the destination, so the vector may advance to // VerifyMethodFingerprint over the whole present set. The reserved sync // subtrees are excluded, matching PresentOriginMaxima — they never travel @@ -67,24 +67,32 @@ func (s *Store) CountVolumeContentsPendingFingerprint(ctx context.Context, volum WHERE pm.content_id = f.content_id AND rp.destination = ? AND rp.checksum IS NOT NULL AND rp.verified_at_ns IS NOT NULL ) + OR EXISTS ( + SELECT 1 FROM remote_paths rpa + WHERE rpa.content_id = f.content_id AND rpa.destination = ? + AND rpa.state IN ('live', 'displaced') + AND rpa.checksum IS NOT NULL AND rpa.verified_at_ns IS NOT NULL + ) ) ) - `, volumeID, destination, destination).Scan(&pending) + `, volumeID, destination, destination, destination).Scan(&pending) if err != nil { return 0, fmt.Errorf("count pending fingerprints for volume %d on %q: %w", volumeID, destination, err) } return pending, nil } -// ContentFingerprintVerified reports whether a verified provider -// fingerprint backs the content on the destination via either layout: a -// remote_objects row carrying a checksum and a verified_at_ns, or a -// remote_packs row (for a pack this content belongs to) likewise -// re-confirmed. The offload gate uses it to certify a presence+size -// component — a coarse vector that only claims bytes-present — so packed -// content gates exactly when its pack has a re-confirmed fingerprint, the -// packed analogue of the per-object scan-back the content-addressed layout -// requires. One verified pack vouches for every member. +// ContentFingerprintVerified reports whether a verified fingerprint backs +// the content on the destination in any layout: a remote_objects row +// carrying a checksum and a verified_at_ns, a remote_packs row (for a pack +// this content belongs to) likewise re-confirmed, or a live or displaced +// mirror copy whose remote_paths row records the BLAKE3 a read of the +// stored bytes confirmed. The offload gate uses it to certify a +// presence+size component — a coarse vector that only claims bytes-present +// — so packed content gates exactly when its pack has a re-confirmed +// fingerprint, the packed analogue of the per-object scan-back the +// content-addressed layout requires. One verified pack vouches for every +// member. func (s *Store) ContentFingerprintVerified(ctx context.Context, contentID int64, destination string) (bool, error) { var verified int err := s.db.QueryRowContext(ctx, ` @@ -100,7 +108,12 @@ func (s *Store) ContentFingerprintVerified(ctx context.Context, contentID int64, WHERE pm.content_id = ? AND rp.destination = ? AND rp.checksum IS NOT NULL AND rp.verified_at_ns IS NOT NULL ) - `, contentID, destination, contentID, destination).Scan(&verified) + OR EXISTS ( + SELECT 1 FROM remote_paths + WHERE content_id = ? AND destination = ? AND state IN ('live', 'displaced') + AND checksum IS NOT NULL AND verified_at_ns IS NOT NULL + ) + `, contentID, destination, contentID, destination, contentID, destination).Scan(&verified) if err != nil { return false, fmt.Errorf("lookup content fingerprint on %q: %w", destination, err) } diff --git a/store/migrate_v27_test.go b/store/migrate_v27_test.go index 4c7cdb5..f5ce2a5 100644 --- a/store/migrate_v27_test.go +++ b/store/migrate_v27_test.go @@ -150,7 +150,7 @@ func TestMigrateV26ToV27PreservesEveryRow(t *testing.T) { t.Errorf("table %s missing after migration to v%d", table, SchemaVersion) } } - indexesAddedAfterV27 := []string{"idx_remote_paths_unsettled", "uniq_remote_paths_live"} // v32 + indexesAddedAfterV27 := []string{"idx_remote_paths_unsettled", "uniq_remote_paths_live", "idx_remote_paths_content", "idx_remote_paths_lost"} // v32, v33 wantObjects := append(append([]string{}, objectsBefore...), indexesAddedAfterV27...) sort.Strings(wantObjects) if after := schemaObjectNames(t, s.db); !equalStrings(after, wantObjects) { diff --git a/store/migrations.go b/store/migrations.go index 68cc3fe..3e467ca 100644 --- a/store/migrations.go +++ b/store/migrations.go @@ -10,7 +10,7 @@ import ( ) // SchemaVersion is the schema version this binary writes and reads. -const SchemaVersion = 32 +const SchemaVersion = 33 // freshSchemaBaseline is the version applied to a brand-new database. The // chain in `migrations` continues from here. v1 is no longer reachable from @@ -75,6 +75,7 @@ func buildMigrations(mctx migrationCtx) []migration { {version: 30, up: migrateV29ToV30}, {version: 31, up: migrateV30ToV31}, {version: 32, up: migrateV31ToV32}, + {version: 33, up: migrateV32ToV33}, } } @@ -2506,3 +2507,29 @@ func migrateV31ToV32(ctx context.Context, db *sql.DB) error { } return tx.Commit() } + +// --- v32 → v33 --- + +// migrateV32ToV33 indexes remote_paths for the reads the mirror's evidence +// adds: by content, for the offload gate's per-content fingerprint check +// and the pending-fingerprint tally, and the lost rows of a destination, +// which a push plans again as repairs. Additive. +func migrateV32ToV33(ctx context.Context, db *sql.DB) error { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + + stmts := []string{ + `CREATE INDEX idx_remote_paths_content ON remote_paths (content_id)`, + `CREATE INDEX idx_remote_paths_lost ON remote_paths (destination) WHERE state = 'lost'`, + `INSERT INTO schema_version (version) VALUES (33)`, + } + for _, stmt := range stmts { + if _, err := tx.ExecContext(ctx, stmt); err != nil { + return fmt.Errorf("migrate to schema v33: %w", err) + } + } + return tx.Commit() +} diff --git a/store/remote_paths.go b/store/remote_paths.go index 654fe7b..e849d98 100644 --- a/store/remote_paths.go +++ b/store/remote_paths.go @@ -26,9 +26,11 @@ const ( ) // RemotePath is one version squirrel wrote at a mirror path on a -// destination, keyed on the files row it came from. Path and SizeBytes are -// read through that row's folder and content. MtimeNs is the mtime the -// destination reported for the written version. +// destination, keyed on the files row it came from. Path, SizeBytes and +// Blake3 are read through that row's folder and content. MtimeNs is the +// mtime the destination reported for the written version. Checksum is +// the BLAKE3 a read of the stored bytes confirmed, NULL while none did, +// and VerifiedAtNs when a read last confirmed it. type RemotePath struct { ID int64 ContentID int64 @@ -36,21 +38,32 @@ type RemotePath struct { State string DisplacedRunID sql.NullInt64 MtimeNs int64 + Checksum sql.NullString + VerifiedAtNs sql.NullInt64 Path string SizeBytes int64 + Blake3 []byte } // RemotePathWrite is the intent to commit one version at a mirror path. +// Checksum is the lowercase hex BLAKE3 a read-back of the staged version +// confirmed at VerifiedAtNs, or empty when the destination offered none. type RemotePathWrite struct { - Destination string - FolderID int64 - Name string - ContentID int64 - RunID int64 - MtimeNs int64 + Destination string + FolderID int64 + Name string + ContentID int64 + RunID int64 + MtimeNs int64 + Checksum string + VerifiedAtNs int64 } +// ChecksumAlgoBlake3 is the checksum_algo of a fingerprint squirrel +// computed itself, by reading the stored bytes back through BLAKE3. +const ChecksumAlgoBlake3 = "blake3" + // BeginRemotePathCommit records the intent to rename a staged version onto // its path, as a committing row. The path's previous live row must already // be displacing, displaced or lost: at most one committing-or-live row per @@ -60,10 +73,18 @@ func (s *Store) BeginRemotePathCommit(ctx context.Context, w RemotePathWrite) (i if w.Destination == "" { return 0, fmt.Errorf("BeginRemotePathCommit: destination must be non-empty") } + var algo, checksum sql.NullString + var verified sql.NullInt64 + if w.Checksum != "" { + algo = sql.NullString{String: ChecksumAlgoBlake3, Valid: true} + checksum = sql.NullString{String: w.Checksum, Valid: true} + verified = sql.NullInt64{Int64: w.VerifiedAtNs, Valid: true} + } res, err := s.db.ExecContext(ctx, ` - INSERT INTO remote_paths (destination, folder_id, name, content_id, written_run_id, state, mtime_ns) - VALUES (?, ?, ?, ?, ?, 'committing', ?) - `, w.Destination, w.FolderID, w.Name, w.ContentID, w.RunID, w.MtimeNs) + INSERT INTO remote_paths (destination, folder_id, name, content_id, written_run_id, state, mtime_ns, + checksum_algo, checksum, verified_at_ns) + VALUES (?, ?, ?, ?, ?, 'committing', ?, ?, ?, ?) + `, w.Destination, w.FolderID, w.Name, w.ContentID, w.RunID, w.MtimeNs, algo, checksum, verified) if err != nil { return 0, fmt.Errorf("record commit of %q on %q: %w", w.Name, w.Destination, err) } @@ -139,12 +160,12 @@ func (s *Store) transitionRemotePaths(ctx context.Context, ids []int64, to, upda } // remotePathSelect reads remote_paths rows with their volume-relative path -// and content size (table aliases rp, fo, c). +// and content size and hash (table aliases rp, fo, c). const remotePathSelect = ` SELECT rp.id, rp.content_id, rp.written_run_id, - rp.state, rp.displaced_run_id, rp.mtime_ns, + rp.state, rp.displaced_run_id, rp.mtime_ns, rp.checksum, rp.verified_at_ns, CASE fo.path WHEN '' THEN rp.name ELSE fo.path || '/' || rp.name END, - c.size_bytes + c.size_bytes, c.blake3 FROM remote_paths rp JOIN folders fo ON fo.id = rp.folder_id JOIN contents c ON c.id = rp.content_id` @@ -152,7 +173,8 @@ const remotePathSelect = ` func scanRemotePath(s rowScanner) (RemotePath, error) { var r RemotePath err := s.Scan(&r.ID, &r.ContentID, &r.WrittenRunID, - &r.State, &r.DisplacedRunID, &r.MtimeNs, &r.Path, &r.SizeBytes) + &r.State, &r.DisplacedRunID, &r.MtimeNs, &r.Checksum, &r.VerifiedAtNs, + &r.Path, &r.SizeBytes, &r.Blake3) return r, err } @@ -162,7 +184,7 @@ func scanRemotePath(s rowScanner) (RemotePath, error) { func (s *Store) ListLiveRemotePaths(ctx context.Context, destination string, volumeID int64) ([]RemotePath, error) { return queryRows(ctx, s.db, remotePathSelect+` WHERE rp.destination = ? AND fo.volume_id = ? AND rp.state = 'live' - ORDER BY 7 + ORDER BY 9 `, scanRemotePath, destination, volumeID) } diff --git a/store/remote_paths_evidence.go b/store/remote_paths_evidence.go new file mode 100644 index 0000000..1ef8168 --- /dev/null +++ b/store/remote_paths_evidence.go @@ -0,0 +1,85 @@ +package store + +import ( + "context" + "fmt" +) + +// StoredRemotePath is a live or displaced remote_paths row with the name of +// the volume it belongs to: a version a mirror holds by squirrel's records, +// at / or in that volume's history. +type StoredRemotePath struct { + RemotePath + Volume string +} + +// ListStoredRemotePaths returns every live and displaced row on the +// destination, in every volume: what a verify pass checks. They come least +// recently verified first, never-verified ones before all others, so a pass +// that re-reads only a slice of them rotates through the whole set. +func (s *Store) ListStoredRemotePaths(ctx context.Context, destination string) ([]StoredRemotePath, error) { + return queryRows(ctx, s.db, ` + SELECT rp.id, rp.content_id, rp.written_run_id, + rp.state, rp.displaced_run_id, rp.mtime_ns, rp.checksum, rp.verified_at_ns, + CASE fo.path WHEN '' THEN rp.name ELSE fo.path || '/' || rp.name END, + c.size_bytes, c.blake3, v.name + FROM remote_paths rp + JOIN folders fo ON fo.id = rp.folder_id + JOIN volumes v ON v.id = fo.volume_id + JOIN contents c ON c.id = rp.content_id + WHERE rp.destination = ? AND rp.state IN ('live', 'displaced') + ORDER BY rp.verified_at_ns IS NOT NULL, rp.verified_at_ns, rp.id + `, func(sc rowScanner) (StoredRemotePath, error) { + var r StoredRemotePath + err := sc.Scan(&r.ID, &r.ContentID, &r.WrittenRunID, + &r.State, &r.DisplacedRunID, &r.MtimeNs, &r.Checksum, &r.VerifiedAtNs, + &r.Path, &r.SizeBytes, &r.Blake3, &r.Volume) + return r, err + }, destination) +} + +// RecordRemotePathVerified records that a read of a live or displaced +// row's stored bytes just hashed to checksum, its content's BLAKE3 in +// lowercase hex, at atNs. A row that already records a checksum must record +// this one: a read never replaces the fingerprint it re-confirms. +func (s *Store) RecordRemotePathVerified(ctx context.Context, id int64, checksum string, atNs int64) error { + res, err := s.db.ExecContext(ctx, ` + UPDATE remote_paths SET checksum_algo = ?, checksum = ?, verified_at_ns = ? + WHERE id = ? AND state IN ('live', 'displaced') AND (checksum IS NULL OR checksum = ?) + `, ChecksumAlgoBlake3, checksum, atNs, id, checksum) + if err != nil { + return fmt.Errorf("record verification of remote path %d: %w", id, err) + } + n, err := res.RowsAffected() + if err != nil { + return fmt.Errorf("record verification of remote path %d: %w", id, err) + } + if n != 1 { + return fmt.Errorf("record verification of remote path %d: the row is not stored, or records another checksum", id) + } + return nil +} + +// ListRemotePathRepairs returns the volume's present paths the destination +// lost: a lost row holds the path's current content, and no committing or +// live row does. A push writes them again although the index did not change +// — the planner's repairs. Ordered by path, like the delta. +func (s *Store) ListRemotePathRepairs(ctx context.Context, destination string, volumeID int64) ([]PathDelta, error) { + return queryRows(ctx, s.db, ` + SELECT DISTINCT `+pathFromFolderAndName+`, f.folder_id, f.content_id, c.blake3, c.size_bytes, f.mtime_ns, f.status + FROM remote_paths rp + JOIN files f ON f.folder_id = rp.folder_id AND f.name = rp.name AND f.content_id = rp.content_id + JOIN folders fo ON fo.id = f.folder_id + JOIN contents c ON c.id = f.content_id + WHERE rp.destination = ? AND rp.state = 'lost' + AND fo.volume_id = ? AND f.status = 'present' + AND `+reservedSubtreeFilter+` + AND NOT EXISTS ( + SELECT 1 FROM remote_paths held + WHERE held.destination = rp.destination AND held.folder_id = rp.folder_id + AND held.name = rp.name AND held.content_id = rp.content_id + AND held.state IN ('committing', 'live') + ) + ORDER BY 1 + `, scanPathDelta, destination, volumeID) +} diff --git a/store/remote_paths_test.go b/store/remote_paths_test.go index a47dc01..3ed579e 100644 --- a/store/remote_paths_test.go +++ b/store/remote_paths_test.go @@ -202,3 +202,149 @@ func TestResetDestinationClearsRemotePaths(t *testing.T) { t.Fatalf("DestinationHasUploadRecords after reset = %t, %v; want false", has, err) } } + +// liveRemotePath commits d at runID on "usb" with checksum (empty for +// none) and confirms it live. +func liveRemotePath(t *testing.T, s *Store, d PathDelta, runID int64, checksum string) int64 { + t.Helper() + ctx := context.Background() + w := commitWrite(d, runID) + w.Checksum, w.VerifiedAtNs = checksum, 7 + id, err := s.BeginRemotePathCommit(ctx, w) + if err != nil { + t.Fatalf("BeginRemotePathCommit: %v", err) + } + if err := s.ConfirmRemotePathsLive(ctx, id); err != nil { + t.Fatalf("ConfirmRemotePathsLive: %v", err) + } + return id +} + +// TestMirrorFingerprintsGateOnlyWhileStored: a live or displaced mirror copy +// whose read-back recorded its BLAKE3 counts as fingerprint-verified; one +// without a checksum, or a lost one, does not. +func TestMirrorFingerprintsGateOnlyWhileStored(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + verified := func() bool { + t.Helper() + ok, err := s.ContentFingerprintVerified(ctx, d.ContentID, "usb") + if err != nil { + t.Fatal(err) + } + pending, err := s.CountVolumeContentsPendingFingerprint(ctx, vID, "usb") + if err != nil { + t.Fatal(err) + } + if ok != (pending == 0) { + t.Fatalf("ContentFingerprintVerified = %t but %d content(s) pending", ok, pending) + } + return ok + } + + unhashed := liveRemotePath(t, s, d, runID, "") + if verified() { + t.Fatal("a mirror copy without a checksum counts as verified") + } + if err := s.MarkRemotePathsLost(ctx, unhashed); err != nil { + t.Fatal(err) + } + id := liveRemotePath(t, s, d, runID, "abc") + if !verified() { + t.Fatal("a live mirror copy with a read-back checksum does not count as verified") + } + if err := s.BeginRemotePathsDisplace(ctx, runID, id); err != nil { + t.Fatal(err) + } + if verified() { + t.Fatal("a copy on its way into history counts as verified") + } + if err := s.ConfirmRemotePathsDisplaced(ctx, id); err != nil { + t.Fatal(err) + } + if !verified() { + t.Fatal("a displaced copy with a read-back checksum does not count as verified") + } + if err := s.MarkRemotePathsLost(ctx, id); err != nil { + t.Fatal(err) + } + if verified() { + t.Fatal("a lost copy counts as verified") + } +} + +// TestListStoredRemotePathsRotatesByVerification: the verify listing holds +// every live and displaced row, never-verified first, then oldest verified, +// and a re-read moves a row to the back. +func TestListStoredRemotePathsRotatesByVerification(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, _, runID := remotePathFixture(t, s) + first := liveRemotePath(t, s, d, runID, "abc") + if err := s.BeginRemotePathsDisplace(ctx, runID, first); err != nil { + t.Fatal(err) + } + if err := s.ConfirmRemotePathsDisplaced(ctx, first); err != nil { + t.Fatal(err) + } + second := liveRemotePath(t, s, d, runID, "") + ids := func() []int64 { + t.Helper() + rows, err := s.ListStoredRemotePaths(ctx, "usb") + if err != nil { + t.Fatal(err) + } + var out []int64 + for _, r := range rows { + if r.Volume != "v" || r.Path != "2024/cat.jpg" { + t.Fatalf("row = %+v, want volume v at 2024/cat.jpg", r) + } + out = append(out, r.ID) + } + return out + } + if got := ids(); len(got) != 2 || got[0] != second || got[1] != first { + t.Fatalf("order = %v, want the never-verified %d before %d", got, second, first) + } + if err := s.RecordRemotePathVerified(ctx, second, "abc", 9); err != nil { + t.Fatalf("RecordRemotePathVerified: %v", err) + } + if got := ids(); got[0] != first || got[1] != second { + t.Fatalf("order after re-reading %d = %v", second, got) + } + if err := s.RecordRemotePathVerified(ctx, second, "def", 10); err == nil { + t.Fatal("a read replaced the checksum it should re-confirm") + } +} + +// TestListRemotePathRepairs: a present path whose current content the +// destination lost is a repair until a new live row holds it again. +func TestListRemotePathRepairs(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + repairs := func() []PathDelta { + t.Helper() + out, err := s.ListRemotePathRepairs(ctx, "usb", vID) + if err != nil { + t.Fatal(err) + } + return out + } + id := liveRemotePath(t, s, d, runID, "") + if got := repairs(); len(got) != 0 { + t.Fatalf("repairs with a live copy = %+v", got) + } + if err := s.MarkRemotePathsLost(ctx, id); err != nil { + t.Fatal(err) + } + got := repairs() + if len(got) != 1 || got[0].Path != d.Path || got[0].ContentID != d.ContentID || got[0].Status != StatusPresent { + t.Fatalf("repairs after the copy was lost = %+v, want %s", got, d.Path) + } + liveRemotePath(t, s, d, runID, "") + if got := repairs(); len(got) != 0 { + t.Fatalf("repairs once a new copy is live = %+v", got) + } +} diff --git a/store/schema.sql b/store/schema.sql index 3c27b50..612e82f 100644 --- a/store/schema.sql +++ b/store/schema.sql @@ -1,6 +1,6 @@ -- Generated by `go test ./store -update-schema` — DO NOT EDIT. -- --- Flattened snapshot of the squirrel index schema at version 32, for humans +-- Flattened snapshot of the squirrel index schema at version 33, for humans -- and agents who want the current shape without replaying the migration -- chain in migrations.go. It is NOT used to create or migrate databases — -- a fresh DB is built by applyV5 plus the migration registry. The golden @@ -231,6 +231,10 @@ CREATE TABLE remote_paths ( CHECK ((checksum_algo IS NULL) = (checksum IS NULL)) ) STRICT; +CREATE INDEX idx_remote_paths_content ON remote_paths (content_id); + +CREATE INDEX idx_remote_paths_lost ON remote_paths (destination) WHERE state = 'lost'; + CREATE INDEX idx_remote_paths_unsettled ON remote_paths (destination) WHERE state IN ('committing', 'displacing'); From 1a2bb18a49ab57931e2b12a6ea6b3f6bc701596c Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 02:38:22 +0200 Subject: [PATCH 25/61] sync: read a local mirror's staged copy back before committing it A local mirror's staged version is re-read past the page cache and hashed with BLAKE3 before it is committed; a match records the fingerprint on its remote_paths row, a mismatch fails the path. The local transport keeps Put's and Get's pages out of the cache for that (F_NOCACHE on macOS, dropping the synced pages on Linux). A mirror push then advances as fingerprint-verified once no present content is pending; an sftp mirror reads nothing back and stays presence+size. --- design/native-mirror.md | 17 ++++--- sync/mirror.go | 19 ++++++-- sync/mirror_sftp_test.go | 11 ++++- sync/mirror_test.go | 78 +++++++++++++++++++++++++++++--- sync/mirror_write.go | 81 ++++++++++++++++++++++++---------- sync/readback.go | 38 ++++++++++++++++ sync/transport_local.go | 13 +++++- sync/transport_local_darwin.go | 7 +++ sync/transport_local_linux.go | 6 +++ sync/transport_local_other.go | 4 ++ 10 files changed, 234 insertions(+), 40 deletions(-) create mode 100644 sync/readback.go diff --git a/design/native-mirror.md b/design/native-mirror.md index 2fd62ad..416c7d8 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -531,14 +531,21 @@ for local mirrors. - **Read-back at write time, on local disks.** After staging and syncing, squirrel re-reads the staged file and hashes it with BLAKE3 before - committing. The read bypasses the cache (`POSIX_FADV_DONTNEED` on Linux, - `F_NOCACHE` on macOS). It is best effort: a USB bridge's own cache is out of - reach. + committing (`sync/readback.go`). The read bypasses the cache: on Linux the + synced pages are dropped (`POSIX_FADV_DONTNEED`) before the read, and on + macOS both the write and the read run with `F_NOCACHE`, because a read + there is still served from pages the write left cached. It is best + effort: a USB bridge's own cache is out of reach. A mismatch fails the + path before its commit, and the staged copy goes with the run's staging. A match records `checksum_algo = blake3` and `verified_at_ns` on the row. `CountVolumeContentsPendingFingerprint` and `ContentFingerprintVerified` - consult `remote_paths`. So a push can advance as `fingerprint-verified` - through the existing gate path, which requires a verify cadence. + consult `remote_paths` rows in the `live` and `displaced` states. So a push + advances as `fingerprint-verified` once no present content is pending, as + the content layouts do; the gate accepts that component through the + existing path, which requires a verify cadence or a per-content + fingerprint. Migration v33 indexes `remote_paths` by content for those + per-content reads. - **sftp mirrors stay non-gating.** An sftp push skips read-back, and mirror paths never go on a server command line, so their fingerprints stay pending. diff --git a/sync/mirror.go b/sync/mirror.go index c7f95f4..ed966f0 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -186,9 +186,22 @@ func (h *mirrorHandler) seal(ctx context.Context, _ *Report, runID int64, p push return nil } -// advanceMethod is presence+size: the push hashed every path's bytes as -// they streamed out and confirmed each landed at its size. -func (h *mirrorHandler) advanceMethod(context.Context, *Report, pushPlan) (string, error) { +// advanceMethod is fingerprint-verified once every present content of the +// volume has a copy on the destination whose read-back confirmed its +// BLAKE3 (a local disk), and presence+size otherwise: the push hashed +// every path's bytes as they streamed out and confirmed each landed at its +// size, and an sftp mirror stays there. +func (h *mirrorHandler) advanceMethod(ctx context.Context, _ *Report, p pushPlan) (string, error) { + if len(p.advance) == 0 { + return store.VerifyMethodPresenceSize, nil + } + pending, err := h.store.CountVolumeContentsPendingFingerprint(ctx, p.volumeID, h.dest.Name) + if err != nil { + return "", err + } + if pending == 0 { + return store.VerifyMethodFingerprint, nil + } return store.VerifyMethodPresenceSize, nil } diff --git a/sync/mirror_sftp_test.go b/sync/mirror_sftp_test.go index 4643e3f..2f33a77 100644 --- a/sync/mirror_sftp_test.go +++ b/sync/mirror_sftp_test.go @@ -15,7 +15,8 @@ import ( // TestMirrorPushOverSFTP: a plain sftp mirror pushes natively with no // rclone wrapper. --init writes the marker through the transport, a // changed path moves its prior version into history, and every run -// leaves its receipt. +// leaves its receipt. Nothing is read back, so no row records a +// fingerprint and the vector stays presence+size. func TestMirrorPushOverSFTP(t *testing.T) { f := setupMirrorFixtureOn(t, sftpBackend) if err := os.Remove(filepath.Join(f.dst, "pics", volmark.MarkerName)); err != nil { @@ -51,6 +52,14 @@ func TestMirrorPushOverSFTP(t *testing.T) { } } f.checkInvariants(t, nil) + for _, r := range f.rows(t) { + if r.Checksum.Valid || r.VerifiedAtNs.Valid { + t.Fatalf("%s row = %+v, want no fingerprint over sftp", r.Path, r) + } + } + if comps := volumeComponents(t, f.store, "pics", "usb"); len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodPresenceSize { + t.Fatalf("vector = %+v, want one presence+size component", comps) + } } // TestMirrorOverSFTPRefusesAnUnknownHost: a server whose host key diff --git a/sync/mirror_test.go b/sync/mirror_test.go index e2c2712..10bf04e 100644 --- a/sync/mirror_test.go +++ b/sync/mirror_test.go @@ -1,10 +1,12 @@ package sync import ( + "bytes" "context" "encoding/hex" "errors" "fmt" + "io" "io/fs" "net" "os" @@ -284,9 +286,10 @@ func (f *mirrorFixture) contentHashOf(t *testing.T, volID int64, r store.RemoteP // TestMirrorPushWithoutRclone: a local mirror pushes through the native // handler with no rclone wrapper, lands every present path with its bytes -// and mtime, records each one live, writes the run's receipt, and advances -// the vector as presence+size. An unchanged second push writes nothing and -// still leaves a receipt. +// and mtime, records each one live with the BLAKE3 its read-back +// confirmed, writes the run's receipt, and advances the vector as +// fingerprint-verified. An unchanged second push writes nothing and still +// leaves a receipt. func TestMirrorPushWithoutRclone(t *testing.T) { f := setupMirrorFixture(t) f.write(t, "a.txt", "alpha") @@ -310,6 +313,14 @@ func TestMirrorPushWithoutRclone(t *testing.T) { t.Fatalf("%s rows = %v, want one live", rel, got) } } + for _, r := range f.rows(t) { + if r.Checksum.String != hex.EncodeToString(r.Blake3) || !r.VerifiedAtNs.Valid { + t.Fatalf("%s row = %+v, want the read-back BLAKE3 recorded", r.Path, r) + } + } + if rep.Fingerprints != 2 { + t.Fatalf("fingerprints = %d, want one read-back per path", rep.Fingerprints) + } delta, err := f.store.ListPathDeltaSince(context.Background(), f.volumeID(t), 0) if err != nil { t.Fatal(err) @@ -319,8 +330,8 @@ func TestMirrorPushWithoutRclone(t *testing.T) { t.Fatalf("receipt = %q, want the delta's manifest segment %q", got, want) } comps := volumeComponents(t, f.store, "pics", "usb") - if len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodPresenceSize { - t.Fatalf("vector = %+v, want one presence+size component", comps) + if len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodFingerprint { + t.Fatalf("vector = %+v, want one fingerprint-verified component", comps) } run, err := f.store.GetRun(context.Background(), rep.RunID) if err != nil || !run.Shallow.Valid || !run.Shallow.Bool { @@ -853,3 +864,60 @@ func TestMirrorStallFailsThePush(t *testing.T) { } f.checkInvariants(t, nil) } + +// corruptingTransport returns every staged file it reads with its first +// byte flipped, as a disk that kept other bytes than it was given. +type corruptingTransport struct{ transport } + +func (c corruptingTransport) Get(ctx context.Context, name string) (io.ReadCloser, error) { + rc, err := c.transport.Get(ctx, name) + if err != nil || !strings.Contains(name, "/"+StagingDirName+"/") { + return rc, err + } + defer func() { _ = rc.Close() }() + b, err := io.ReadAll(rc) + if err != nil { + return nil, err + } + if len(b) > 0 { + b[0] ^= 0xff + } + return io.NopCloser(bytes.NewReader(b)), nil +} + +// TestMirrorReadBackRefusesBytesTheDiskChanged: a staged copy that reads +// back as other bytes than were sent is never committed. The path fails, +// the run fails before its receipt, and the staged copy stays for the next +// push's reconcile. +func TestMirrorReadBackRefusesBytesTheDiskChanged(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + h := f.handler(t) + h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + return corruptingTransport{raw}, err + } + rep, err := h.Push(context.Background(), Options{}) + if err == nil || rep.Status != store.RunStatusFailed { + t.Fatalf("push: status=%q err=%v, want a failed run", rep.Status, err) + } + if len(rep.RcloneResult.FailedFiles) != 1 || !strings.Contains(rep.RcloneResult.FailedFiles[0].Message, errReadBackMismatch.Error()) { + t.Fatalf("failed files = %+v, want a read-back mismatch", rep.RcloneResult.FailedFiles) + } + if _, err := os.Stat(f.dest("a.txt")); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("a.txt was committed: %v", err) + } + if rows := f.rows(t); len(rows) != 0 { + t.Fatalf("rows = %+v, want none", rows) + } + staged := filepath.Join(f.dst, filepath.FromSlash(stagingName("pics", rep.RunID, stagingKey("a.txt")))) + if _, err := os.Stat(staged); err != nil { + t.Fatalf("staged copy: %v", err) + } + f.mustPush(t) + if _, err := os.Stat(staged); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the next push left the failed run's staging: %v", err) + } + f.checkInvariants(t, nil) +} diff --git a/sync/mirror_write.go b/sync/mirror_write.go index a0cbf9d..33ac061 100644 --- a/sync/mirror_write.go +++ b/sync/mirror_write.go @@ -92,10 +92,20 @@ func (w *mirrorWriter) confirm(ctx context.Context, d store.PathDelta) (bool, er return false, nil } +// stagedVersion is one path's version in this run's staging, as the +// destination confirmed it: its mtime, and on a disk squirrel reads back, +// the hex BLAKE3 the read-back confirmed and when. +type stagedVersion struct { + name string + mtime time.Time + checksum string + verifiedAtNs int64 +} + // write lands one path: stage the content while hashing it, clear the way // (displacing whatever the path and its parents hold), then commit. func (w *mirrorWriter) write(ctx context.Context, d store.PathDelta) error { - staged, mtime, err := w.stage(ctx, d) + staged, err := w.stage(ctx, d) if err != nil { return err } @@ -105,38 +115,59 @@ func (w *mirrorWriter) write(ctx context.Context, d store.PathDelta) error { if err := w.displace(ctx, d.Path); err != nil { return err } - return w.commit(ctx, d, staged, mtime) + return w.commit(ctx, d, staged) } // stage streams the source into this run's staging and hashes the same -// bytes. A source that drifted from its indexed hash fails the path with -// errContentDrift; its staged file stays until the next push's reconcile -// removes it with this run's staging. -func (w *mirrorWriter) stage(ctx context.Context, d store.PathDelta) (string, time.Time, error) { +// bytes, then confirms what landed: its size, and on a local disk its +// bytes, read back. A source that drifted from its indexed hash fails the +// path with errContentDrift; its staged file stays until the next push's +// reconcile removes it with this run's staging. +func (w *mirrorWriter) stage(ctx context.Context, d store.PathDelta) (stagedVersion, error) { src := filepath.Join(w.h.vol.Path, filepath.FromSlash(d.Path)) f, err := os.Open(src) if err != nil { - return "", time.Time{}, fmt.Errorf("open source %s: %w", src, err) + return stagedVersion{}, fmt.Errorf("open source %s: %w", src, err) } defer f.Close() - staged := stagingName(w.h.vol.Name, w.runID, stagingKey(d.Path)) + staged := stagedVersion{name: stagingName(w.h.vol.Name, w.runID, stagingKey(d.Path))} hasher := blake3.New() counted := &countWriter{w: hasher} - if err := w.tr.Put(ctx, staged, io.TeeReader(f, counted), time.Unix(0, d.MtimeNs)); err != nil { - return "", time.Time{}, fmt.Errorf("stage %s: %w", d.Path, err) + if err := w.tr.Put(ctx, staged.name, io.TeeReader(f, counted), time.Unix(0, d.MtimeNs)); err != nil { + return stagedVersion{}, fmt.Errorf("stage %s: %w", d.Path, err) } if counted.n != d.SizeBytes || !bytes.Equal(hasher.Sum(nil), d.Blake3) { - return "", time.Time{}, fmt.Errorf("%w: %s sent %d bytes hashing to %s, indexed as %d bytes %s — run `squirrel index %s` and sync again", + return stagedVersion{}, fmt.Errorf("%w: %s sent %d bytes hashing to %s, indexed as %d bytes %s — run `squirrel index %s` and sync again", errContentDrift, d.Path, counted.n, hex.EncodeToString(hasher.Sum(nil)), d.SizeBytes, hex.EncodeToString(d.Blake3), w.h.vol.Name) } - e, err := w.tr.Stat(ctx, staged) + e, err := w.tr.Stat(ctx, staged.name) if err != nil { - return "", time.Time{}, fmt.Errorf("confirm staged %s: %w", d.Path, err) + return stagedVersion{}, fmt.Errorf("confirm staged %s: %w", d.Path, err) } if e.size != d.SizeBytes { - return "", time.Time{}, fmt.Errorf("staged %s landed with size %d, want %d", d.Path, e.size, d.SizeBytes) + return stagedVersion{}, fmt.Errorf("staged %s landed with size %d, want %d", d.Path, e.size, d.SizeBytes) + } + staged.mtime = e.mtime + if readsBack(w.h.dest) { + return staged, w.readBackStaged(ctx, d, &staged) } - return staged, e.mtime, nil + return staged, nil +} + +// readBackStaged confirms the staged bytes are the content squirrel sent, +// and records the fingerprint that earns. +func (w *mirrorWriter) readBackStaged(ctx context.Context, d store.PathDelta, staged *stagedVersion) error { + sum, err := readBack(ctx, w.tr, staged.name) + if err != nil { + return fmt.Errorf("read back staged %s: %w", d.Path, err) + } + if !bytes.Equal(sum, d.Blake3) { + return fmt.Errorf("%w: staged %s hashes to %s, sent %s", errReadBackMismatch, d.Path, hex.EncodeToString(sum), hex.EncodeToString(d.Blake3)) + } + staged.checksum = hex.EncodeToString(sum) + staged.verifiedAtNs = store.NowNs() + w.rep.Fingerprints++ + return nil } // clearParents displaces the first parent of rel that is not a directory @@ -264,26 +295,28 @@ func (w *mirrorWriter) noteUnrecordedMove(ctx context.Context, note string) erro // commit records the intent, renames the staged version onto rel, and // confirms. If the rename fails the row stays committing, and the next // push's reconcile withdraws it. -func (w *mirrorWriter) commit(ctx context.Context, d store.PathDelta, staged string, mtime time.Time) error { +func (w *mirrorWriter) commit(ctx context.Context, d store.PathDelta, staged stagedVersion) error { id, err := w.h.store.BeginRemotePathCommit(ctx, store.RemotePathWrite{ - Destination: w.h.dest.Name, - FolderID: d.FolderID, - Name: path.Base(d.Path), - ContentID: d.ContentID, - RunID: w.runID, - MtimeNs: mtime.UnixNano(), + Destination: w.h.dest.Name, + FolderID: d.FolderID, + Name: path.Base(d.Path), + ContentID: d.ContentID, + RunID: w.runID, + MtimeNs: staged.mtime.UnixNano(), + Checksum: staged.checksum, + VerifiedAtNs: staged.verifiedAtNs, }) if err != nil { return err } - if err := w.tr.Rename(ctx, staged, w.h.liveName(d.Path)); err != nil { + if err := w.tr.Rename(ctx, staged.name, w.h.liveName(d.Path)); err != nil { return fmt.Errorf("commit %s: %w", d.Path, err) } if err := w.h.store.ConfirmRemotePathsLive(ctx, id); err != nil { return err } w.live[d.Path] = store.RemotePath{ID: id, ContentID: d.ContentID, WrittenRunID: w.runID, State: store.RemotePathLive, - MtimeNs: mtime.UnixNano(), Path: d.Path, SizeBytes: d.SizeBytes} + MtimeNs: staged.mtime.UnixNano(), Path: d.Path, SizeBytes: d.SizeBytes} w.rep.RcloneResult.Transferred++ w.rep.RcloneResult.Bytes += d.SizeBytes return nil diff --git a/sync/readback.go b/sync/readback.go new file mode 100644 index 0000000..5634105 --- /dev/null +++ b/sync/readback.go @@ -0,0 +1,38 @@ +package sync + +import ( + "context" + "errors" + "io" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/config" +) + +// errReadBackMismatch marks a stored file whose bytes, read back, are not +// the bytes squirrel sent: the disk kept something else. +var errReadBackMismatch = errors.New("the stored bytes read back differently from the bytes sent") + +// readsBack reports whether dest is a disk squirrel reads back, BLAKE3 over +// what it just stored, before trusting it: a local destination. An sftp +// server's bytes are read back only through its hash command. +func readsBack(dest *config.Destination) bool { + return dest.Type == "local" +} + +// readBack hashes the file at name as the destination returns it. The +// local transport reads past the page cache where the platform allows, so +// the hash covers what reached the disk. +func readBack(ctx context.Context, tr transport, name string) ([]byte, error) { + rc, err := tr.Get(ctx, name) + if err != nil { + return nil, err + } + defer func() { _ = rc.Close() }() + h := blake3.New() + if _, err := io.CopyBuffer(h, ctxReader{ctx: ctx, r: rc}, make([]byte, copyBufferSize)); err != nil { + return nil, err + } + return h.Sum(nil), nil +} diff --git a/sync/transport_local.go b/sync/transport_local.go index 80e39b3..8c3a7d1 100644 --- a/sync/transport_local.go +++ b/sync/transport_local.go @@ -18,7 +18,9 @@ import ( // filesystem. os.Root confines every name to the root; on top of that each // operation checks its name's parent chain with Lstat and refuses a // symlink anywhere along it, because os.Root follows symlinks that stay -// inside the root. +// inside the root. Put and Get keep their pages out of the cache where +// the platform allows (bypassCache), so reading back a file just written +// reads what reached the disk. type localTransport struct { root *os.Root } @@ -80,7 +82,12 @@ func (t *localTransport) Get(_ context.Context, name string) (io.ReadCloser, err if err := requireKind(name, kindFile, t.lstat); err != nil { return nil, err } - return t.root.Open(filepath.FromSlash(name)) + f, err := t.root.Open(filepath.FromSlash(name)) + if err != nil { + return nil, err + } + bypassCache(f) + return f, nil } func (t *localTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { @@ -94,6 +101,7 @@ func (t *localTransport) Put(ctx context.Context, name string, r io.Reader, mtim if err != nil { return err } + bypassCache(f) if err := t.fill(ctx, f, name, r, mtime); err != nil { _ = f.Close() return err @@ -115,6 +123,7 @@ func (t *localTransport) fill(ctx context.Context, f *os.File, name string, r io if err := f.Sync(); err != nil { return fmt.Errorf("sync %s: %w", name, err) } + bypassCache(f) return nil } diff --git a/sync/transport_local_darwin.go b/sync/transport_local_darwin.go index a65f861..4299116 100644 --- a/sync/transport_local_darwin.go +++ b/sync/transport_local_darwin.go @@ -23,6 +23,13 @@ func renameNoReplace(root *os.Root, from, to string) error { return nil } +// bypassCache sets F_NOCACHE on f, so its reads and writes go to the +// device and leave no pages in the cache behind: a read of a file written +// that way returns what the disk holds. +func bypassCache(f *os.File) { + _, _ = unix.FcntlInt(f.Fd(), unix.F_NOCACHE, 1) +} + // dirSyncUnsupported reports a filesystem that cannot flush a directory. func dirSyncUnsupported(err error) bool { return errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOTSUP) diff --git a/sync/transport_local_linux.go b/sync/transport_local_linux.go index 83df1ea..ff59b63 100644 --- a/sync/transport_local_linux.go +++ b/sync/transport_local_linux.go @@ -23,6 +23,12 @@ func renameNoReplace(root *os.Root, from, to string) error { return nil } +// bypassCache drops f's clean pages from the cache, so the next read of +// what was synced comes from the device. +func bypassCache(f *os.File) { + _ = unix.Fadvise(int(f.Fd()), 0, 0, unix.FADV_DONTNEED) +} + // dirSyncUnsupported reports a filesystem that cannot flush a directory. func dirSyncUnsupported(err error) bool { return errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOTSUP) diff --git a/sync/transport_local_other.go b/sync/transport_local_other.go index 9c26a77..d81c20f 100644 --- a/sync/transport_local_other.go +++ b/sync/transport_local_other.go @@ -10,6 +10,10 @@ func renameNoReplace(root *os.Root, from, to string) error { return renameCheckThenMove(root, from, to) } +// bypassCache: this platform gives squirrel no handle on the cache, so a +// read may be served from it. +func bypassCache(*os.File) {} + // dirSyncUnsupported: a directory cannot be flushed through a handle on // this platform, so the sync is best effort. func dirSyncUnsupported(error) bool { return true } From 7df2e2fbec50e5c7af2651470ad50c3ef621f8d5 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 02:48:14 +0200 Subject: [PATCH 26/61] sync: verify native mirrors, and write again what they lost squirrel verify and the agent's verify cadence now cover native mirrors, through the transport and without rclone. A pass checks every live and displaced copy's size and mtime; on a local disk it also re-reads the least recently verified tenth of the stored bytes through BLAKE3. A copy found gone or changed is marked lost and latches the destination's alarm, and the next push writes the path again when the index still holds that content there. verify_every is valid on native mirrors, a native local mirror may gate offload, and an sftp mirror's refusal says why it cannot. --- agent/scheduler.go | 6 +- cmd/squirrel/agent_scheduler.go | 25 +++-- cmd/squirrel/agent_scheduler_test.go | 12 +- cmd/squirrel/verify.go | 65 ++++++++--- cmd/squirrel/verify_test.go | 31 ++++-- config/config_test.go | 62 ++++++++--- config/destinations.go | 82 +++++++------- config/offload_capability_test.go | 13 ++- design/native-mirror.md | 34 ++++-- store/remote_paths_evidence.go | 18 +++ store/remote_paths_test.go | 22 ++++ sync/mirror_test.go | 18 ++- sync/mirror_translate.go | 37 ++++++- sync/mirror_write.go | 4 + sync/verify_mirror.go | 159 +++++++++++++++++++++++++++ sync/verify_mirror_test.go | 145 ++++++++++++++++++++++++ sync/verify_remote.go | 55 ++++++--- sync/verify_remote_test.go | 10 +- 18 files changed, 657 insertions(+), 141 deletions(-) create mode 100644 sync/verify_mirror.go create mode 100644 sync/verify_mirror_test.go diff --git a/agent/scheduler.go b/agent/scheduler.go index 1a0420f..dc20b03 100644 --- a/agent/scheduler.go +++ b/agent/scheduler.go @@ -113,15 +113,15 @@ func (s *scheduler) refresh() { s.pullEvery = resolvePullCadences(cur.Nodes) } -// resolveVerifyCadences maps each verifiable (content-addressed or packed) -// destination to its effective verify cadence: the destination's own +// resolveVerifyCadences maps each verifiable destination (content-addressed, +// packed, or a native mirror) to its effective verify cadence: the destination's own // verify_every when set, otherwise the [agent] verify_every default. Only // destinations with a positive resulting cadence are included, so a config // with neither knob set yields an empty map and no verify activity. func resolveVerifyCadences(dests map[string]*config.Destination, def time.Duration) map[string]time.Duration { out := make(map[string]time.Duration) for name, d := range dests { - if d.Layout != config.LayoutContentAddressed && d.Layout != config.LayoutPacked { + if !d.Verifiable() { continue } eff := d.VerifyEvery diff --git a/cmd/squirrel/agent_scheduler.go b/cmd/squirrel/agent_scheduler.go index 0e7fc25..ae840e8 100644 --- a/cmd/squirrel/agent_scheduler.go +++ b/cmd/squirrel/agent_scheduler.go @@ -61,7 +61,7 @@ func (t *schedulerTools) rclone() *sync.Rclone { return t.rcl.Load() } // destinations the kick was planned against. func (t *schedulerTools) rebuild(ctx context.Context, cfg *config.Config) error { needsSync := anyVolumeNeedsScheduledSync(cfg) - needsVerify := anyDestinationNeedsScheduledVerify(cfg) + needsVerify := anyScheduledVerifyNeedsRclone(cfg) if !needsSync && !needsVerify { return nil } @@ -114,15 +114,16 @@ func targetNeedsRclone(cfg *config.Config, target string) bool { return true } -// anyDestinationNeedsScheduledVerify reports whether any verifiable -// destination has an effective verify cadence — its own verify_every, or the -// [agent] verify_every default. Mirrors the scheduler's own resolution so -// the rclone/runner wiring lines up with what the scheduler will actually -// fire. -func anyDestinationNeedsScheduledVerify(cfg *config.Config) bool { +// anyScheduledVerifyNeedsRclone reports whether any verifiable destination +// squirrel reaches through rclone has an effective verify cadence — its own +// verify_every, or the [agent] verify_every default. Mirrors the scheduler's +// own resolution so the rclone wiring lines up with what the scheduler will +// actually fire; a native mirror is verified through squirrel's own +// transport. +func anyScheduledVerifyNeedsRclone(cfg *config.Config) bool { agentDefault := cfg.AgentVerifyEvery() > 0 for _, d := range cfg.Destinations { - if d.Layout != config.LayoutContentAddressed && d.Layout != config.LayoutPacked { + if !d.Verifiable() || !(sync.Pair{Destination: d}).DrivesRclone() { continue } if d.VerifyEvery > 0 || agentDefault { @@ -205,14 +206,14 @@ func schedulerPairFor(cfg *config.Config, vol *config.Volume, destName string) ( // never reaches it. func buildSchedulerVerifyRunner(live *config.Live, s *store.Store, tools *schedulerTools) agent.VerifyRunner { return func(ctx context.Context, destName string) agent.VerifyRunReport { - rcl := tools.rclone() - if rcl == nil { - return agent.VerifyRunReport{Status: store.RunStatusFailed, Err: errors.New("scheduled verify needs rclone, which the configuration in force did not call for")} - } dest, ok := live.Get().Destinations[destName] if !ok { return agent.VerifyRunReport{Status: store.RunStatusFailed, Err: fmt.Errorf("destination %q is not declared in config", destName)} } + rcl := tools.rclone() + if rcl == nil && (sync.Pair{Destination: dest}).DrivesRclone() { + return agent.VerifyRunReport{Status: store.RunStatusFailed, Err: errors.New("scheduled verify needs rclone, which the configuration in force did not call for")} + } rep, err := sync.VerifyRemote(ctx, s, rcl, dest) return agent.VerifyRunReport{RunID: rep.RunID, Status: verifyRunStatus(rep, err), Err: err} } diff --git a/cmd/squirrel/agent_scheduler_test.go b/cmd/squirrel/agent_scheduler_test.go index 5b2e35b..eacc868 100644 --- a/cmd/squirrel/agent_scheduler_test.go +++ b/cmd/squirrel/agent_scheduler_test.go @@ -61,20 +61,26 @@ func TestAnyDestinationNeedsScheduledVerify(t *testing.T) { cfg := base() cfg.Destinations["m"] = &config.Destination{Layout: config.LayoutMirror, VerifyEvery: time.Hour} - if anyDestinationNeedsScheduledVerify(cfg) { + if anyScheduledVerifyNeedsRclone(cfg) { t.Fatalf("mirror layout must never need scheduled verify") } + cfg = base() + cfg.Destinations["usb"] = &config.Destination{Type: "local", Layout: config.LayoutMirror, VerifyEvery: time.Hour} + if anyScheduledVerifyNeedsRclone(cfg) { + t.Fatalf("a native mirror's scheduled verify must not need rclone") + } + cfg = base() cfg.Destinations["p"] = &config.Destination{Layout: config.LayoutPacked, VerifyEvery: time.Hour} - if !anyDestinationNeedsScheduledVerify(cfg) { + if !anyScheduledVerifyNeedsRclone(cfg) { t.Fatalf("packed destination with own cadence should need verify") } cfg = base() cfg.Agent.VerifyEvery = time.Hour cfg.Destinations["c"] = &config.Destination{Layout: config.LayoutContentAddressed} - if !anyDestinationNeedsScheduledVerify(cfg) { + if !anyScheduledVerifyNeedsRclone(cfg) { t.Fatalf("agent default should cover a verifiable destination with no own cadence") } } diff --git a/cmd/squirrel/verify.go b/cmd/squirrel/verify.go index e160a72..9a8da2b 100644 --- a/cmd/squirrel/verify.go +++ b/cmd/squirrel/verify.go @@ -3,6 +3,7 @@ package main import ( "fmt" "io" + "slices" "sort" "github.com/spf13/cobra" @@ -53,12 +54,9 @@ func runVerify(cmd *cobra.Command, destName string) error { } defer s.Close() - rcl, err := sync.Find(cmd.Context()) - if err != nil { - return err - } out := cmd.OutOrStdout() - if err := writeRcloneConfigLogged(out, rcl, cfg); err != nil { + rcl, err := verifyRclone(cmd, cfg, names) + if err != nil { return err } @@ -76,51 +74,70 @@ func runVerify(cmd *cobra.Command, destName string) error { return nil } +// verifyRclone locates rclone and renders its config when a target is +// reached through it; a native mirror is verified without it. +func verifyRclone(cmd *cobra.Command, cfg *config.Config, names []string) (*sync.Rclone, error) { + if !slices.ContainsFunc(names, func(name string) bool { + return sync.Pair{Destination: cfg.Destinations[name]}.DrivesRclone() + }) { + return nil, nil + } + rcl, err := sync.Find(cmd.Context()) + if err != nil { + return nil, err + } + if err := writeRcloneConfigLogged(cmd.OutOrStdout(), rcl, cfg); err != nil { + return nil, err + } + return rcl, nil +} + // verifyTargetNames resolves the verification subjects in deterministic -// order: an explicit destination (validated to exist and be -// content-addressed or packed), or every such destination in config. +// order: an explicit destination (validated to exist and be verifiable), +// or every verifiable destination in config. func verifyTargetNames(cfg *config.Config, destName string) ([]string, error) { if destName != "" { d, ok := cfg.Destinations[destName] if !ok { return nil, fmt.Errorf("unknown destination %q (declare it in %s)", destName, cfg.Path) } - if !verifiableLayout(d.Layout) { - return nil, fmt.Errorf("destination %q has layout %q — verify covers the recorded objects and packs of content-addressed and packed destinations", destName, d.Layout) + if !d.Verifiable() { + return nil, fmt.Errorf("destination %q is an rclone mirror — verify covers the recorded objects and packs of content-addressed and packed destinations, and the recorded copies of a mirror squirrel writes itself (local, or sftp without crypt)", destName) } return []string{destName}, nil } var names []string for name, d := range cfg.Destinations { - if verifiableLayout(d.Layout) { + if d.Verifiable() { names = append(names, name) } } if len(names) == 0 { - return nil, fmt.Errorf("no content-addressed or packed destinations declared in %s", cfg.Path) + return nil, fmt.Errorf("no verifiable destinations declared in %s: verify covers content-addressed and packed destinations and native mirrors", cfg.Path) } sort.Strings(names) return names, nil } -// verifiableLayout reports whether a destination's layout keeps per-object -// or per-pack fingerprints that `squirrel verify` re-checks. -func verifiableLayout(layout string) bool { - return layout == config.LayoutContentAddressed || layout == config.LayoutPacked -} - // printVerifyReport renders one destination's pass: a loud stderr line // per missing or mismatched object or pack, then the summary counters, // then the standing-alarm transition this pass caused (#157, F30). func printVerifyReport(out, errOut io.Writer, rep sync.RemoteVerifyReport, runErr error) { printVerifyFailures(errOut, "object", rep.Destination, rep.Missing, rep.Mismatched) printVerifyFailures(errOut, "pack", rep.Destination, rep.PacksMissing, rep.PackMismatched) + printMirrorFailures(errOut, rep) if runErr != nil { fmt.Fprintf(errOut, "verify %s: %v\n", rep.Destination, runErr) return } + if rep.Paths > 0 { + fmt.Fprintf(out, "verify %s: run=%d copies=%d reread=%d changed=%d missing=%d\n", + rep.Destination, rep.RunID, rep.Paths, rep.PathsReread, len(rep.PathsChanged), len(rep.PathsMissing)) + printVerifyAlarmTransition(out, errOut, rep) + return + } if rep.Objects == 0 && rep.Packs == 0 { - fmt.Fprintf(out, "verify %s: no recorded objects or packs\n", rep.Destination) + fmt.Fprintf(out, "verify %s: nothing recorded to verify\n", rep.Destination) return } fmt.Fprintf(out, "verify %s: run=%d objects=%d verified=%d fingerprinted=%d pending=%d mismatched=%d missing=%d unrecorded=%d packs=%d packs_verified=%d packs_fingerprinted=%d packs_pending=%d packs_mismatched=%d packs_missing=%d\n", @@ -144,6 +161,18 @@ func printVerifyAlarmTransition(out, errOut io.Writer, rep sync.RemoteVerifyRepo } } +// printMirrorFailures writes one stderr line per mirror copy the pass found +// gone or changed; the next push writes each one again that the index still +// holds. +func printMirrorFailures(errOut io.Writer, rep sync.RemoteVerifyReport) { + for _, name := range rep.PathsMissing { + fmt.Fprintf(errOut, "error: copy %s on %q: recorded as stored but absent\n", name, rep.Destination) + } + for _, name := range rep.PathsChanged { + fmt.Fprintf(errOut, "error: copy %s on %q: its size, mtime or BLAKE3 no longer matches what squirrel stored — possible corruption or tampering\n", name, rep.Destination) + } +} + // printVerifyFailures writes one stderr line per missing or mismatched // artifact (an object or a pack), naming the kind so a mixed destination's // failures stay distinguishable. diff --git a/cmd/squirrel/verify_test.go b/cmd/squirrel/verify_test.go index cdf702d..f45aca2 100644 --- a/cmd/squirrel/verify_test.go +++ b/cmd/squirrel/verify_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/mbertschler/squirrel/config" "github.com/mbertschler/squirrel/sync" ) @@ -16,18 +17,28 @@ func TestVerifyUnknownDestination(t *testing.T) { } } -func TestVerifyRefusesMirrorDestination(t *testing.T) { +// TestVerifyNativeMirrorNeedsNoRclone: a local mirror is verifiable, and a +// pass over one with nothing recorded yet runs without rclone. +func TestVerifyNativeMirrorNeedsNoRclone(t *testing.T) { fx := writeSyncFixture(t) - _, err := runCLIExpectErr(t, "verify", "scratch", "--config", fx.configPath) - if !strings.Contains(err.Error(), "content-addressed") { - t.Fatalf("err = %v, want content-addressed refusal", err) + t.Setenv("PATH", t.TempDir()) + out := runCLI(t, "verify", "scratch", "--config", fx.configPath) + if !strings.Contains(out, "verify scratch: nothing recorded to verify") { + t.Fatalf("output = %q, want the empty summary", out) } } -func TestVerifyNoContentAddressedDestinations(t *testing.T) { - fx := writeSyncFixture(t) - _, err := runCLIExpectErr(t, "verify", "--config", fx.configPath) - if !strings.Contains(err.Error(), "no content-addressed or packed destinations") { +// TestVerifyTargetNamesRefusesRcloneMirrors: an rclone mirror records +// nothing to re-check, so naming one is refused, and a config holding only +// such mirrors has no verify targets. +func TestVerifyTargetNamesRefusesRcloneMirrors(t *testing.T) { + cfg := &config.Config{Path: "squirrel.toml", Destinations: map[string]*config.Destination{ + "cloudbox": {Name: "cloudbox", Type: "sftp", Layout: config.LayoutMirror, Crypt: &config.Crypt{Password: "x"}}, + }} + if _, err := verifyTargetNames(cfg, "cloudbox"); err == nil || !strings.Contains(err.Error(), "rclone mirror") { + t.Fatalf("err = %v, want an rclone-mirror refusal", err) + } + if _, err := verifyTargetNames(cfg, ""); err == nil || !strings.Contains(err.Error(), "no verifiable destinations") { t.Fatalf("err = %v, want no-destinations refusal", err) } } @@ -38,7 +49,7 @@ func TestVerifyNoContentAddressedDestinations(t *testing.T) { func TestPrintVerifyReportErrorSuppressesSummary(t *testing.T) { var out, errOut strings.Builder printVerifyReport(&out, &errOut, sync.RemoteVerifyReport{Destination: "offsite"}, errors.New("rclone exploded")) - if strings.Contains(out.String(), "no recorded objects") || out.Len() != 0 { + if out.Len() != 0 { t.Fatalf("stdout = %q, want empty on an error run", out.String()) } if !strings.Contains(errOut.String(), "rclone exploded") { @@ -51,7 +62,7 @@ func TestPrintVerifyReportErrorSuppressesSummary(t *testing.T) { func TestPrintVerifyReportCleanEmptyShowsSummary(t *testing.T) { var out, errOut strings.Builder printVerifyReport(&out, &errOut, sync.RemoteVerifyReport{Destination: "offsite"}, nil) - if !strings.Contains(out.String(), "no recorded objects") { + if !strings.Contains(out.String(), "nothing recorded to verify") { t.Fatalf("stdout = %q, want the no-objects summary on a clean run", out.String()) } } diff --git a/config/config_test.go b/config/config_test.go index 8e5ae61..7dd6938 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -323,24 +323,50 @@ offload_requires = ["cloudbox"] } } -// TestLoadRejectsPlainMirrorOffloadRequires: a plain mirror's sync is -// compared by rclone's checksum under a hash rclone picks, never the -// index's BLAKE3, so it can no more gate offload than a crypt mirror can -// (#211). Naming one fails at load. -func TestLoadRejectsPlainMirrorOffloadRequires(t *testing.T) { +// TestLoadRejectsSFTPMirrorOffloadRequires: a native sftp mirror reads +// nothing back and never hashes a mirror path on the server, so it can no +// more gate offload than a crypt mirror can. Naming one fails at load, and +// the reason says why. +func TestLoadRejectsSFTPMirrorOffloadRequires(t *testing.T) { + p := writeConfig(t, ` +[destinations.box] +type = "sftp" +host = "host.example" +user = "u" +root = "/data" + +[volumes.docs] +path = "/tmp/docs" +sync_to = ["box"] +offload_requires = ["box"] +`) + _, err := Load(p) + if err == nil || !strings.Contains(err.Error(), "can never satisfy the durability gate") || !strings.Contains(err.Error(), "reads nothing back") { + t.Fatalf("expected sftp-mirror offload_requires rejection naming the reason, got %v", err) + } +} + +// TestLoadAcceptsLocalMirrorOffloadRequires: a native local mirror reads +// every copy back through BLAKE3, so it may gate offload, with a verify +// cadence re-reading its copies. +func TestLoadAcceptsLocalMirrorOffloadRequires(t *testing.T) { p := writeConfig(t, ` [destinations.usb] -type = "local" -root = "/media/usb" +type = "local" +root = "/media/usb" +verify_every = "168h" [volumes.docs] path = "/tmp/docs" sync_to = ["usb"] offload_requires = ["usb"] `) - _, err := Load(p) - if err == nil || !strings.Contains(err.Error(), "can never satisfy the durability gate") { - t.Fatalf("expected plain-mirror offload_requires rejection, got %v", err) + cfg, err := Load(p) + if err != nil { + t.Fatalf("Load: %v", err) + } + if !cfg.VerifyCadencedTargets([]string{"usb"})["usb"] { + t.Fatal("the local mirror's verify cadence does not count for the gate") } } @@ -1596,14 +1622,20 @@ secret_access_key = { env = "K" } } } -// TestLoadRejectsVerifyEveryOnMirror rejects verify_every on a layout that -// keeps no per-object fingerprints — verify has nothing to re-check there. +// TestLoadRejectsVerifyEveryOnMirror rejects verify_every on an rclone +// mirror, which keeps no records of what it stored — verify has nothing to +// re-check there. func TestLoadRejectsVerifyEveryOnMirror(t *testing.T) { p := writeConfig(t, ` -[destinations.usb] -type = "local" -root = "/media/usb" +[destinations.cloudbox] +type = "sftp" +host = "host.example" +user = "u" +root = "/data" verify_every = "168h" + +[destinations.cloudbox.crypt] +password = "obscured-pw" `) _, err := Load(p) if err == nil || !strings.Contains(err.Error(), "verify_every requires") { diff --git a/config/destinations.go b/config/destinations.go index 44f51d9..f522897 100644 --- a/config/destinations.go +++ b/config/destinations.go @@ -163,7 +163,7 @@ func resolveDestination(name string, raw map[string]any) (*Destination, error) { if err != nil { return nil, err } - verifyEvery, err := resolveVerifyEvery(raw, layout) + verifyEvery, err := resolveVerifyEvery(raw, verifiable(layout, native)) if err != nil { return nil, err } @@ -233,13 +233,13 @@ func resolveCryptAndLayout(raw map[string]any, typ string) (*Crypt, string, erro // resolveVerifyEvery validates the optional per-destination `verify_every` // cadence that drives the agent's scheduled re-check of this destination's -// recorded objects and packs (the same pass as `squirrel verify`). It is -// meaningful only on the content-addressed and packed layouts that keep -// per-artifact fingerprints, so a present key on any other layout is -// rejected rather than silently ignored — a mirror destination has nothing -// for verify to re-check. Empty stays zero: no per-destination cadence, an -// [agent] verify_every default may still apply. -func resolveVerifyEvery(raw map[string]any, layout string) (time.Duration, error) { +// records (the same pass as `squirrel verify`). It is meaningful only where +// squirrel records what it stored — the content-addressed and packed +// layouts' objects and packs, a native mirror's copies — so a present key +// on an rclone mirror is rejected rather than silently ignored. Empty stays +// zero: no per-destination cadence, an [agent] verify_every default may +// still apply. +func resolveVerifyEvery(raw map[string]any, verifiable bool) (time.Duration, error) { v, err := optionalString(raw, "verify_every") if err != nil { return 0, err @@ -247,8 +247,8 @@ func resolveVerifyEvery(raw map[string]any, layout string) (time.Duration, error if v == "" { return 0, nil } - if layout != LayoutContentAddressed && layout != LayoutPacked { - return 0, fmt.Errorf("verify_every requires the %q or %q layout; layout %q keeps no per-object fingerprints to re-check", LayoutContentAddressed, LayoutPacked, layout) + if !verifiable { + return 0, fmt.Errorf("verify_every requires the %q or %q layout, or a mirror squirrel writes itself (local, or sftp without crypt): an rclone mirror keeps no records of what it stored to re-check", LayoutContentAddressed, LayoutPacked) } return parseVolumeCadence("verify_every", v) } @@ -845,6 +845,17 @@ func nativeMirror(typ, layout string, crypt bool) bool { return mirror && !crypt && (typ == "local" || typ == "sftp") } +// Verifiable reports whether `squirrel verify` re-checks this destination: +// squirrel records what it stored there, as the content-addressed and +// packed layouts' objects and packs, or as a native mirror's copies. +func (d *Destination) Verifiable() bool { + return verifiable(d.Layout, d.NativeMirror()) +} + +func verifiable(layout string, nativeMirror bool) bool { + return layout == LayoutContentAddressed || layout == LayoutPacked || nativeMirror +} + // HidesArtifactNames reports whether this destination names its content // objects, packs, and per-volume directories by a keyed BLAKE3 hash derived // from its crypt passwords, so the remote discloses neither a path nor a @@ -862,40 +873,38 @@ func layoutHidesArtifactNames(layout string) bool { // CanEverGateOffload reports whether a durability push to this destination // can ever advance its vector with a component the offload gate will accept -// — one that is content-verified, either natively or after a scan-back -// fingerprint upgrades a presence+size component. When it returns false, -// reason names the structural gap for the caller's message; it is empty -// when capable. +// — one that is content-verified, either natively or after a fingerprint +// upgrades a presence+size component. When it returns false, reason names +// the structural gap for the caller's message; it is empty when capable. // -// The structurally-incapable shape is a mirror. A native mirror (local, or -// sftp without crypt) hashes each file as it sends it but reads nothing -// back, so it advances with presence+size and nothing upgrades it. An -// rclone mirror compares source against destination by rclone's -// --checksum — under -// a hash rclone picks, unrelated to the index's BLAKE3 — or, behind a crypt -// overlay, by size+mtime alone (sync.EffectiveShallow); and the mirror -// layout records no scan-back fingerprint that a later `squirrel verify` -// could upgrade (#211). The content-addressed and packed layouts, by -// contrast, advance with presence+size but stay upgradable — their -// fingerprint is read back over the stored ciphertext, so a crypt overlay -// does not block it — and kopia's own repository verification is capable -// outright. +// The content-addressed and packed layouts advance with presence+size but +// stay upgradable — their fingerprint is read back over the stored +// ciphertext, so a crypt overlay does not block it — and kopia's own +// repository verification is capable outright. So is a native local mirror: +// every copy it writes is read back through BLAKE3 before it is committed, +// and `squirrel verify` re-reads them. The incapable shapes are the other +// mirrors. A native sftp mirror reads nothing back, and its paths — the +// volume's own file names — never go on a server command line, so its +// evidence stays presence+size. An rclone mirror compares source against +// destination by rclone's --checksum — under a hash rclone picks, unrelated +// to the index's BLAKE3 — or, behind a crypt overlay, by size+mtime alone +// (sync.EffectiveShallow), and records nothing a later `squirrel verify` +// could upgrade (#211). func (d *Destination) CanEverGateOffload() (bool, string) { - if d.Type == "kopia" { - return true, "" - } switch { - case d.Layout == LayoutContentAddressed || d.Layout == LayoutPacked: + case d.Type == "kopia", d.Layout == LayoutContentAddressed || d.Layout == LayoutPacked: + return true, "" + case d.NativeMirror() && d.Type == "local": return true, "" case d.NativeMirror(): - return false, fmt.Sprintf("%s mirror destination: a push hashes each file as it sends it but reads nothing back, so its evidence stays presence+size, which is not content-verified", d.Type) + return false, "sftp mirror destination: a push reads nothing back, and its paths are the volume's own file names, which squirrel never puts on a server command line, so no copy is fingerprinted and its evidence stays presence+size, which is not content-verified; a local mirror, or a content-addressed or packed sftp destination, can gate" } - return false, "mirror destination: a sync compares it with the source by rclone's checksum or by size+mtime, never against the index's BLAKE3, and the mirror layout records no scan-back fingerprint to upgrade" + return false, "mirror destination: a sync compares it with the source by rclone's checksum or by size+mtime, never against the index's BLAKE3, and records nothing a later verify could upgrade" } // VerifyCadencedTargets marks the required targets that carry an effective // local verify cadence — a per-destination verify_every, or the [agent] -// verify_every default applied to a content-addressed/packed destination. +// verify_every default applied to a verifiable destination. // The offload gate accepts a locally-advanced fingerprint-verified // component as content-verified only for a target in this set, so the // provider-fingerprint evidence keeps being re-confirmed for as long as @@ -915,10 +924,7 @@ func (c *Config) VerifyCadencedTargets(require []string) map[string]bool { out := make(map[string]bool, len(require)) for _, name := range require { d, ok := c.Destinations[name] - if !ok { - continue - } - if d.Layout != LayoutContentAddressed && d.Layout != LayoutPacked { + if !ok || !d.Verifiable() { continue } eff := d.VerifyEvery diff --git a/config/offload_capability_test.go b/config/offload_capability_test.go index 18cb823..ef4eba7 100644 --- a/config/offload_capability_test.go +++ b/config/offload_capability_test.go @@ -6,9 +6,10 @@ import ( ) // TestCanEverGateOffload pins the structural capability predicate the -// offload fail-fast reads: the incapable shape is an rclone mirror, plain or -// crypt (checksum or size+mtime, no fingerprint to upgrade it); every other -// shape can eventually contribute a content-verified component. +// offload fail-fast reads: the incapable shapes are an rclone mirror (a +// crypt one: checksum or size+mtime, no fingerprint to upgrade it) and a +// native sftp mirror (nothing read back); every other shape, a native local +// mirror included, can eventually contribute a content-verified component. func TestCanEverGateOffload(t *testing.T) { crypt := &Crypt{Password: "obscured"} cases := []struct { @@ -16,13 +17,15 @@ func TestCanEverGateOffload(t *testing.T) { dest Destination wantCapable bool }{ - {"mirror plain", Destination{Type: "sftp", Layout: LayoutMirror}, false}, + {"sftp mirror", Destination{Type: "sftp", Layout: LayoutMirror}, false}, {"mirror crypt", Destination{Type: "sftp", Layout: LayoutMirror, Crypt: crypt}, false}, + {"local mirror crypt", Destination{Type: "local", Layout: LayoutMirror, Crypt: crypt}, false}, + {"b2 mirror", Destination{Type: "b2", Layout: LayoutMirror}, false}, {"content-addressed plain", Destination{Type: "sftp", Layout: LayoutContentAddressed}, true}, {"content-addressed crypt", Destination{Type: "s3", Layout: LayoutContentAddressed, Crypt: crypt}, true}, {"packed plain", Destination{Type: "s3", Layout: LayoutPacked}, true}, {"packed crypt", Destination{Type: "s3", Layout: LayoutPacked, Crypt: crypt}, true}, - {"local mirror", Destination{Type: "local", Layout: LayoutMirror}, false}, + {"local mirror", Destination{Type: "local", Layout: LayoutMirror}, true}, {"kopia mirror", Destination{Type: "kopia", Layout: LayoutMirror}, true}, } for _, c := range cases { diff --git a/design/native-mirror.md b/design/native-mirror.md index 416c7d8..96b738d 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -192,17 +192,23 @@ was absent; only a later verify pass would have noticed. The planner now fails closed here (`DestinationHasUploadRecords`), because the mirror's records would repeat the same mistake. -### Repairs: the planner's second input +### Repairs: the mirror's second input This input arrives with the evidence step. A verify pass that finds a -recorded artifact missing or changed marks that record `lost`. The next -push then plans the record's content again, even though the index didn't -change: +recorded copy missing or changed marks that record `lost`. The next push +then plans the record's content again, even though the index didn't change: work = delta since watermark ∪ records marked lost -Today the content layouts only raise an alarm in this case. With repairs, the -same push that raised the alarm also heals it. +The mirror's translate reads them (`ListRemotePathRepairs`): present paths +where a `lost` row holds the current content and no live row does. A +withdrawn commit is one too, but its path is still in the delta. A push +that writes repairs counts them as changed, so the runs fold shows it. + +The content layouts keep only raising the alarm. Their records have no +`lost` state, and a changed object can't be healed in place: nothing +replaces an existing name, so repairing one needs a displacement the +content layouts don't have. ## 2. Layouts translate changes into operations @@ -557,13 +563,19 @@ for local mirrors. - It checks the size and mtime of every `live` and `displaced` row with `Lstat`. Both states count as stored content, so both are checked. This is cheap and catches deletion, truncation and replacement. - - On local mirrors, it re-hashes a slice of rows, oldest `verified_at_ns` first, within a - budget per pass. So every byte is re-read within a known period. Kopia's - `verify_files_percent` is the precedent for sampled read-back. + - On local mirrors, it re-hashes a slice of rows, oldest `verified_at_ns` + first (never-verified first of all), until the slice covers a tenth of the + bytes the destination holds (`mirrorRereadShare`, `sync/verify_mirror.go`), + and always at least one row. So every byte is re-read within about ten + passes. Kopia's `verify_files_percent` is the precedent for sampled + read-back. Findings latch the existing destination alarm and mark the affected rows - `lost`. `lost` live rows whose content is still the index's current content - become the planner's repairs. + `lost` — only while the row is still in the state the pass read it in, since + a push may be moving it. `lost` rows whose content is still the index's + current content become the mirror's repairs. A clean pass re-attempts the + `fingerprint-verified` upgrade, as it does for the content layouts. + `squirrel verify` reaches the mirror through its transport, without rclone. - **Documents amended in the same PR:** - `CanEverGateOffload` becomes true for native local mirrors, and `offload_requires` accepts them. sftp mirrors keep refusing, and the diff --git a/store/remote_paths_evidence.go b/store/remote_paths_evidence.go index 1ef8168..2d04024 100644 --- a/store/remote_paths_evidence.go +++ b/store/remote_paths_evidence.go @@ -60,6 +60,24 @@ func (s *Store) RecordRemotePathVerified(ctx context.Context, id int64, checksum return nil } +// LoseStoredRemotePath marks a row lost that a verify pass found missing or +// changed, provided it is still in state, the state the pass read it in. +// It reports whether the row moved: a push may have moved it since, and +// then the pass's finding describes a version that is no longer there. +func (s *Store) LoseStoredRemotePath(ctx context.Context, id int64, state string) (bool, error) { + res, err := s.db.ExecContext(ctx, ` + UPDATE remote_paths SET state = 'lost' WHERE id = ? AND state = ? AND state IN ('live', 'displaced') + `, id, state) + if err != nil { + return false, fmt.Errorf("mark remote path %d lost: %w", id, err) + } + n, err := res.RowsAffected() + if err != nil { + return false, fmt.Errorf("mark remote path %d lost: %w", id, err) + } + return n == 1, nil +} + // ListRemotePathRepairs returns the volume's present paths the destination // lost: a lost row holds the path's current content, and no committing or // live row does. A push writes them again although the index did not change diff --git a/store/remote_paths_test.go b/store/remote_paths_test.go index 3ed579e..37d8a37 100644 --- a/store/remote_paths_test.go +++ b/store/remote_paths_test.go @@ -348,3 +348,25 @@ func TestListRemotePathRepairs(t *testing.T) { t.Fatalf("repairs once a new copy is live = %+v", got) } } + +// TestLoseStoredRemotePathOnlyFromTheStateRead: a verify finding marks a +// row lost only while it is still in the state the pass read, so a push +// that moved the row in between keeps its record. +func TestLoseStoredRemotePathOnlyFromTheStateRead(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, _, runID := remotePathFixture(t, s) + id := liveRemotePath(t, s, d, runID, "") + if err := s.BeginRemotePathsDisplace(ctx, runID, id); err != nil { + t.Fatal(err) + } + if moved, err := s.LoseStoredRemotePath(ctx, id, RemotePathLive); err != nil || moved { + t.Fatalf("lose a row read live that is now displacing = %t, %v; want untouched", moved, err) + } + if err := s.ConfirmRemotePathsDisplaced(ctx, id); err != nil { + t.Fatal(err) + } + if moved, err := s.LoseStoredRemotePath(ctx, id, RemotePathDisplaced); err != nil || !moved { + t.Fatalf("lose a displaced row = %t, %v; want moved", moved, err) + } +} diff --git a/sync/mirror_test.go b/sync/mirror_test.go index 10bf04e..10d9d4e 100644 --- a/sync/mirror_test.go +++ b/sync/mirror_test.go @@ -358,11 +358,18 @@ func TestMirrorPushWithoutRclone(t *testing.T) { // record already holds its content is only confirmed. func TestMirrorTranslationRules(t *testing.T) { f := setupMirrorFixture(t) - for _, rel := range []string{"same.txt", "changed.txt", "gone.txt", "offloaded.txt"} { + for _, rel := range []string{"same.txt", "changed.txt", "gone.txt", "offloaded.txt", "lost.txt"} { f.write(t, rel, "v1 "+rel) } f.index(t) f.mustPush(t) + for _, r := range f.rows(t) { + if r.Path == "lost.txt" { + if err := f.store.MarkRemotePathsLost(context.Background(), r.ID); err != nil { + t.Fatal(err) + } + } + } f.write(t, "changed.txt", "v2 changed") f.write(t, "new.txt", "new") if err := os.Remove(filepath.Join(f.src, "gone.txt")); err != nil { @@ -378,10 +385,16 @@ func TestMirrorTranslationRules(t *testing.T) { if err := f.store.MarkOffloaded(ctx, volID, "offloaded.txt", off.ContentID, off.LastSeenRunID); err != nil { t.Fatalf("MarkOffloaded: %v", err) } - delta, err := f.store.ListPathDeltaSince(ctx, volID, 0) + full, err := f.store.ListPathDeltaSince(ctx, volID, 0) if err != nil { t.Fatal(err) } + var delta []store.PathDelta + for _, d := range full { + if d.Path != "lost.txt" { + delta = append(delta, d) + } + } ops, err := f.handler(t).translate(ctx, pushPlan{volumeID: volID, delta: delta}) if err != nil { @@ -395,6 +408,7 @@ func TestMirrorTranslationRules(t *testing.T) { "same.txt": "confirm", // present, live record holds C "changed.txt": "write", // present, live record holds other content "new.txt": "write", // present, no live record + "lost.txt": "write", // repair: outside the delta, its record lost // gone.txt (missing), offloaded.txt (offloaded) and changed.txt's // superseded row produce nothing. } diff --git a/sync/mirror_translate.go b/sync/mirror_translate.go index 67b62e9..b4e3031 100644 --- a/sync/mirror_translate.go +++ b/sync/mirror_translate.go @@ -8,14 +8,17 @@ import ( ) // mirrorOps is the mirror translation of a plan: one operation per present -// delta path, and the live records the operations were decided against. -// execute keeps live current as it moves versions. +// delta path and per repair, and the live records the operations were +// decided against. execute keeps live current as it moves versions. type mirrorOps struct { paths []mirrorPath live map[string]store.RemotePath // volume-relative path → live row // inSync counts the live rows that hold their path's present content, // in the delta or not: what the report calls already correct. inSync int64 + // repairs counts the paths planned because the destination lost their + // current content, beyond the delta. + repairs int64 } // mirrorPath is one planned path. When the live record already holds the @@ -27,13 +30,17 @@ type mirrorPath struct { current bool } -// translate applies the mirror's translation rules to the delta. Rows -// that are missing, offloaded or superseded produce nothing: a -// destination keeps content the source no longer has. +// translate applies the mirror's translation rules to the delta, then adds +// the repairs: present paths whose current content the destination lost +// (a push or a verify pass found other bytes there, or none), written +// again although the index did not change. Rows that are missing, +// offloaded or superseded produce nothing: a destination keeps content the +// source no longer has. // // present, live record holds C → confirm (already correct) // present, live record holds other → write C, displacing the recorded version // present, no live record → write C, displacing any unrecorded entry +// repair: a lost record holds C → write C, displacing whatever is there func (h *mirrorHandler) translate(ctx context.Context, p pushPlan) (*mirrorOps, error) { rows, err := h.store.ListLiveRemotePaths(ctx, h.dest.Name, p.volumeID) if err != nil { @@ -47,14 +54,32 @@ func (h *mirrorHandler) translate(ctx context.Context, p pushPlan) (*mirrorOps, for _, r := range rows { ops.live[r.Path] = r } + planned := make(map[string]bool, len(p.delta)) for _, d := range p.delta { if d.Status != store.StatusPresent { continue } + planned[d.Path] = true live, ok := ops.live[d.Path] ops.paths = append(ops.paths, mirrorPath{delta: d, current: ok && live.ContentID == d.ContentID}) } - return ops, nil + return ops, h.addRepairs(ctx, p.volumeID, ops, planned) +} + +// addRepairs plans every repair the delta does not already cover. +func (h *mirrorHandler) addRepairs(ctx context.Context, volumeID int64, ops *mirrorOps, planned map[string]bool) error { + repairs, err := h.store.ListRemotePathRepairs(ctx, h.dest.Name, volumeID) + if err != nil { + return fmt.Errorf("list lost mirror paths on %q: %w", h.dest.Name, err) + } + for _, d := range repairs { + if planned[d.Path] { + continue + } + ops.paths = append(ops.paths, mirrorPath{delta: d}) + ops.repairs++ + } + return nil } // preview counts what execute would do: written paths as Transferred and diff --git a/sync/mirror_write.go b/sync/mirror_write.go index 33ac061..1805002 100644 --- a/sync/mirror_write.go +++ b/sync/mirror_write.go @@ -46,6 +46,10 @@ func (h *mirrorHandler) execute(ctx context.Context, rep *Report, runID int64, o } w := &mirrorWriter{h: h, rep: rep, runID: runID, tr: tr, live: ops.live, progress: h.progress, total: len(ops.paths)} rep.AlreadyCorrect = ops.inSync + if ops.repairs > 0 { + rep.Changed = knownChanged(rep.Changed.Int64 + ops.repairs) + rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination %q lost %d path(s) the index still holds there (found gone or changed); they are written again", h.dest.Name, ops.repairs)) + } for _, p := range ops.paths { if err := ctx.Err(); err != nil { return err diff --git a/sync/verify_mirror.go b/sync/verify_mirror.go new file mode 100644 index 0000000..a03797b --- /dev/null +++ b/sync/verify_mirror.go @@ -0,0 +1,159 @@ +package sync + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "io/fs" + "path" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" +) + +// mirrorRereadShare is the share of a local mirror's stored bytes one +// verify pass re-reads, least recently verified first: a tenth, so every +// byte is read again within about ten passes. +const mirrorRereadShare = 10 + +// verifyMirror checks every copy a native mirror holds by squirrel's +// records, the live and the displaced ones: each gets one Lstat against its +// recorded size and mtime, and on a local disk a slice of them is re-read +// through BLAKE3. A copy that is gone or changed is marked lost, which +// latches the destination's alarm and makes the next push write the path +// again if the index still holds that content there. +func verifyMirror(ctx context.Context, s *store.Store, dest *config.Destination, rep *RemoteVerifyReport) error { + rows, err := s.ListStoredRemotePaths(ctx, dest.Name) + if err != nil { + return fmt.Errorf("list recorded mirror copies for %q: %w", dest.Name, err) + } + rep.Paths = len(rows) + if len(rows) == 0 { + return nil + } + runID, err := s.BeginRemoteVerifyRun(ctx) + if err != nil { + return fmt.Errorf("record verify run: %w", err) + } + rep.RunID = runID + verifyErr := checkMirrorCopies(ctx, s, dest, rows, rep) + if err := recordVerifyOutcome(ctx, s, rep, verifyErr); err != nil { + return err + } + if verifyErr == nil && rep.Clean() { + return upgradeFingerprintVectors(ctx, s, dest.Name) + } + return verifyErr +} + +// mirrorCopy is one recorded copy as a verify pass addresses it. +type mirrorCopy struct { + store.StoredRemotePath + name string // where the copy is, relative to the destination root +} + +func checkMirrorCopies(ctx context.Context, s *store.Store, dest *config.Destination, rows []store.StoredRemotePath, rep *RemoteVerifyReport) error { + tr, err := openReadOnly(ctx, dest) + if err != nil { + return err + } + defer func() { _ = tr.Close() }() + var intact []mirrorCopy + for _, r := range rows { + c := mirrorCopy{StoredRemotePath: r, name: storedCopyName(r)} + ok, err := statCopy(ctx, s, tr, c, rep) + if err != nil { + return err + } + if ok { + intact = append(intact, c) + } + } + if !readsBack(dest) { + return nil + } + return rereadCopies(ctx, s, tr, rereadSlice(intact), rep) +} + +// storedCopyName is where a live copy sits, /, or a displaced +// one, /.squirrel-history/run-/. +func storedCopyName(r store.StoredRemotePath) string { + if r.State == store.RemotePathDisplaced { + return historyName(r.Volume, r.DisplacedRunID.Int64, r.Path) + } + return path.Join(r.Volume, r.Path) +} + +// statCopy checks one copy's size and mtime and reports whether it is +// intact. A copy that is gone or changed is recorded as a finding. +func statCopy(ctx context.Context, s *store.Store, tr transport, c mirrorCopy, rep *RemoteVerifyReport) (bool, error) { + e, err := tr.Stat(ctx, c.name) + switch { + case errors.Is(err, fs.ErrNotExist) || errors.Is(err, errParentNotDir): + return false, loseCopy(ctx, s, c, &rep.PathsMissing) + case err != nil: + return false, fmt.Errorf("stat %s: %w", c.name, err) + case !matchesRecord(e, c.RemotePath): + return false, loseCopy(ctx, s, c, &rep.PathsChanged) + } + return true, nil +} + +// rereadSlice picks the copies one pass re-reads: least recently verified +// first, until they cover mirrorRereadShare of the bytes the destination +// holds, and always at least one. +func rereadSlice(copies []mirrorCopy) []mirrorCopy { + var total int64 + for _, c := range copies { + total += c.SizeBytes + } + var read int64 + for i, c := range copies { + if i > 0 && read*mirrorRereadShare >= total { + return copies[:i] + } + read += c.SizeBytes + } + return copies +} + +// rereadCopies hashes each copy as the disk returns it: a match re-stamps +// its fingerprint, other bytes are a finding. +func rereadCopies(ctx context.Context, s *store.Store, tr transport, copies []mirrorCopy, rep *RemoteVerifyReport) error { + for _, c := range copies { + sum, err := readBack(ctx, tr, c.name) + if errors.Is(err, fs.ErrNotExist) { + if err := loseCopy(ctx, s, c, &rep.PathsMissing); err != nil { + return err + } + continue + } + if err != nil { + return fmt.Errorf("re-read %s: %w", c.name, err) + } + if !bytes.Equal(sum, c.Blake3) { + if err := loseCopy(ctx, s, c, &rep.PathsChanged); err != nil { + return err + } + continue + } + if err := s.RecordRemotePathVerified(ctx, c.ID, hex.EncodeToString(sum), store.NowNs()); err != nil { + return err + } + rep.PathsReread++ + } + return nil +} + +// loseCopy marks a copy lost and lists its name under the finding, unless a +// push moved its row since the pass read it. +func loseCopy(ctx context.Context, s *store.Store, c mirrorCopy, finding *[]string) error { + moved, err := s.LoseStoredRemotePath(ctx, c.ID, c.State) + if err != nil || !moved { + return err + } + *finding = append(*finding, c.name) + return nil +} diff --git a/sync/verify_mirror_test.go b/sync/verify_mirror_test.go new file mode 100644 index 0000000..9c5c3c1 --- /dev/null +++ b/sync/verify_mirror_test.go @@ -0,0 +1,145 @@ +package sync + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/mbertschler/squirrel/store" +) + +func (f *mirrorFixture) verify(t *testing.T) RemoteVerifyReport { + t.Helper() + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err != nil { + t.Fatalf("VerifyRemote: %v", err) + } + return rep +} + +// TestVerifyMirrorChecksEveryStoredCopy: a pass checks the live and the +// displaced copies without rclone, re-reads a slice of them on a local +// disk, and stays clean while they hold what squirrel stored. +func TestVerifyMirrorChecksEveryStoredCopy(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "v1") + f.write(t, "b.txt", "beta") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2") + f.index(t) + f.mustPush(t) + + rep := f.verify(t) + if !rep.Clean() || rep.Paths != 3 || rep.PathsReread == 0 || rep.RunID == 0 { + t.Fatalf("rep = %+v, want a clean pass over 3 copies that re-read some", rep) + } + run, err := f.store.GetRun(context.Background(), rep.RunID) + if err != nil || run.Status != store.RunStatusSuccess || run.FileCount != 3 { + t.Fatalf("run = %+v, %v; want a successful audit over 3 copies", run, err) + } +} + +// TestVerifyMirrorRereadRotates: successive passes re-read the least +// recently verified copies first, so every copy is re-read in turn. +func TestVerifyMirrorRereadRotates(t *testing.T) { + f := setupMirrorFixture(t) + for _, name := range []string{"a", "b", "c", "d"} { + f.write(t, name, "same size") + } + f.index(t) + f.mustPush(t) + before := map[int64]int64{} + for _, r := range f.rows(t) { + before[r.ID] = r.VerifiedAtNs.Int64 + } + for range 4 { + if rep := f.verify(t); rep.PathsReread != 1 { + t.Fatalf("pass re-read %d copies, want the one a tenth of the bytes needs", rep.PathsReread) + } + } + for _, r := range f.rows(t) { + if r.VerifiedAtNs.Int64 == before[r.ID] { + t.Fatalf("%s was never re-read in four passes", r.Path) + } + } +} + +// TestVerifyMirrorFindingsMarkCopiesLost: a copy deleted, changed in size +// and mtime, or changed behind an unchanged size and mtime is a finding: +// its row becomes lost, the destination's alarm latches, and the next push +// writes each path again although the index did not change. +func TestVerifyMirrorFindingsMarkCopiesLost(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "gone.txt", "gone") + f.write(t, "grown.txt", "grown") + f.write(t, "flipped.txt", "flipped") + f.index(t) + f.mustPush(t) + + if err := os.Remove(f.dest("gone.txt")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("grown.txt"), []byte("grown, and longer"), 0o644); err != nil { + t.Fatal(err) + } + flipped := f.dest("flipped.txt") + fi, _ := os.Stat(flipped) + if err := os.WriteFile(flipped, []byte("FLIPPED"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(flipped, fi.ModTime(), fi.ModTime()); err != nil { + t.Fatal(err) + } + found := f.verify(t) + if found.Clean() || len(found.PathsMissing) != 1 || len(found.PathsChanged) != 2 || !found.AlarmRaised { + t.Fatalf("rep = %+v, want one copy missing, two changed, and the alarm raised", found) + } + if got := f.lostPaths(t); len(got) != 3 { + t.Fatalf("lost = %v, want all three copies", got) + } + + rep := f.mustPush(t) + if rep.RcloneResult.Transferred != 3 { + t.Fatalf("repair push transferred %d, want the three lost paths", rep.RcloneResult.Transferred) + } + if f.readDest(t, "gone.txt") != "gone" || f.readDest(t, "grown.txt") != "grown" || f.readDest(t, "flipped.txt") != "flipped" { + t.Fatal("the repair push did not restore the lost copies") + } + f.checkInvariants(t, nil) + if rep := f.verify(t); !rep.Clean() { + t.Fatalf("pass after the repair = %+v, want clean", rep) + } +} + +func (f *mirrorFixture) lostPaths(t *testing.T) []string { + t.Helper() + var out []string + for _, r := range f.rows(t) { + if r.State == store.RemotePathLost { + out = append(out, r.Path) + } + } + return out +} + +// TestVerifyMirrorOverSFTPChecksWithoutReading: over sftp a pass checks +// size and mtime alone, and finds a copy that went missing. +func TestVerifyMirrorOverSFTPChecksWithoutReading(t *testing.T) { + f := setupMirrorFixtureOn(t, sftpBackend) + f.write(t, "a.txt", "alpha") + f.write(t, "b.txt", "beta") + f.index(t) + f.mustPush(t) + if rep := f.verify(t); !rep.Clean() || rep.Paths != 2 || rep.PathsReread != 0 { + t.Fatalf("rep = %+v, want a clean size-and-mtime pass", rep) + } + if err := os.Remove(filepath.Join(f.dst, "pics", "a.txt")); err != nil { + t.Fatal(err) + } + rep := f.verify(t) + if len(rep.PathsMissing) != 1 || rep.PathsMissing[0] != "pics/a.txt" { + t.Fatalf("missing = %v, want pics/a.txt", rep.PathsMissing) + } +} diff --git a/sync/verify_remote.go b/sync/verify_remote.go index 6d47a93..8e0860d 100644 --- a/sync/verify_remote.go +++ b/sync/verify_remote.go @@ -12,9 +12,9 @@ import ( ) // RemoteVerifyReport summarises one verification pass over a -// destination's recorded content-addressed objects. Every recorded -// object lands in exactly one of Verified, Populated, Pending, Missing, -// or Mismatched. +// destination's recorded content-addressed objects and packs, or a native +// mirror's recorded copies. Every recorded object lands in exactly one of +// Verified, Populated, Pending, Missing, or Mismatched. type RemoteVerifyReport struct { Destination string RunID int64 @@ -57,6 +57,19 @@ type RemoteVerifyReport struct { // the recorded one (Hash holds the pack key hex). PackMismatched []RemoteObjectMismatch + // Paths counts a native mirror's recorded copies, the live and the + // displaced ones; each is checked by size and mtime. Zero on the + // content layouts. + Paths int + // PathsReread counts the copies a re-read through BLAKE3 confirmed: + // on a local disk, the least recently verified share of them. + PathsReread int + // PathsMissing and PathsChanged name, relative to the destination root, + // the copies found gone and the ones found with another size, mtime or + // BLAKE3. Their records are marked lost. + PathsMissing []string + PathsChanged []string + // AlarmRaised is true when this pass latched a new standing alarm on // the destination because it was not clean (#157, F30). A pass on an // already-alarmed destination leaves it false (the latch was already @@ -80,11 +93,19 @@ type RemoteObjectMismatch struct { Actual string } -// Clean reports whether every recorded object and pack was accounted for -// without a mismatch. +// Clean reports whether every recorded object, pack and mirror copy was +// accounted for without a mismatch. func (r RemoteVerifyReport) Clean() bool { return len(r.Missing) == 0 && len(r.Mismatched) == 0 && - len(r.PacksMissing) == 0 && len(r.PackMismatched) == 0 + len(r.PacksMissing) == 0 && len(r.PackMismatched) == 0 && + len(r.PathsMissing) == 0 && len(r.PathsChanged) == 0 +} + +// failures counts the recorded artifacts this pass found missing or +// changed. +func (r RemoteVerifyReport) failures() int { + return len(r.Missing) + len(r.Mismatched) + len(r.PacksMissing) + len(r.PackMismatched) + + len(r.PathsMissing) + len(r.PathsChanged) } // VerifyRemote re-reads the provider checksums of every object recorded @@ -95,14 +116,20 @@ func (r RemoteVerifyReport) Clean() bool { // mismatches and missing objects land loudly on the report. The pass // reads destination metadata and updates local verification state only. // +// A native mirror is checked through squirrel's own transport instead +// (verifyMirror), so rcl may be nil for one. +// // The pass is recorded as a kind='audit' run: success when every object // checked out, partial when objects mismatched or went missing, failed // when the pass itself aborted. A 'verify-destination' runs_audit entry // carries the destination name and counters. func VerifyRemote(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination) (RemoteVerifyReport, error) { rep := RemoteVerifyReport{Destination: dest.Name} + if dest.NativeMirror() { + return rep, verifyMirror(ctx, s, dest, &rep) + } if dest.Layout != config.LayoutContentAddressed && dest.Layout != config.LayoutPacked { - return rep, fmt.Errorf("destination %q has layout %q — verify covers the recorded objects and packs of content-addressed and packed destinations", dest.Name, dest.Layout) + return rep, fmt.Errorf("destination %q is an rclone mirror — verify covers the recorded objects and packs of content-addressed and packed destinations, and the recorded copies of a mirror squirrel writes itself", dest.Name) } rows, err := s.ListRemoteObjects(ctx, dest.Name) if err != nil { @@ -436,12 +463,12 @@ func recordVerifyOutcome(ctx context.Context, s *store.Store, rep *RemoteVerifyR errMsg = verifyErr.Error() case !rep.Clean(): status = store.RunStatusPartial - failed := len(rep.Missing) + len(rep.Mismatched) + len(rep.PacksMissing) + len(rep.PackMismatched) - errMsg = fmt.Sprintf("%d object(s)/pack(s) failed verification on %q", failed, rep.Destination) + errMsg = fmt.Sprintf("%d object(s)/pack(s)/mirror copies failed verification on %q", rep.failures(), rep.Destination) } - note := fmt.Sprintf("destination=%s objects=%d verified=%d fingerprinted=%d pending=%d mismatched=%d missing=%d unrecorded=%d packs=%d packs_verified=%d packs_fingerprinted=%d packs_pending=%d packs_mismatched=%d packs_missing=%d", + note := fmt.Sprintf("destination=%s objects=%d verified=%d fingerprinted=%d pending=%d mismatched=%d missing=%d unrecorded=%d packs=%d packs_verified=%d packs_fingerprinted=%d packs_pending=%d packs_mismatched=%d packs_missing=%d paths=%d paths_reread=%d paths_changed=%d paths_missing=%d", rep.Destination, rep.Objects, rep.Verified, rep.Populated, rep.Pending, len(rep.Mismatched), len(rep.Missing), rep.Unrecorded, - rep.Packs, rep.PacksVerified, rep.PacksPopulated, rep.PacksPending, len(rep.PackMismatched), len(rep.PacksMissing)) + rep.Packs, rep.PacksVerified, rep.PacksPopulated, rep.PacksPending, len(rep.PackMismatched), len(rep.PacksMissing), + rep.Paths, rep.PathsReread, len(rep.PathsChanged), len(rep.PathsMissing)) if err := s.AppendRunAudit(ctx, store.RunAuditEntry{ RunID: rep.RunID, Transition: store.TransitionVerifyDestination, Note: note, }); err != nil { @@ -454,7 +481,7 @@ func recordVerifyOutcome(ctx context.Context, s *store.Store, rep *RemoteVerifyR // noise (#182). A pass that found a mismatch or a missing object is // 'partial' or 'failed' and stays visible on status alone. changed := int64(rep.Populated + rep.PacksPopulated) - if err := s.FinishRunChanged(ctx, rep.RunID, status, errMsg, int64(rep.Objects+rep.Packs), changed); err != nil { + if err := s.FinishRunChanged(ctx, rep.RunID, status, errMsg, int64(rep.Objects+rep.Packs+rep.Paths), changed); err != nil { return fmt.Errorf("finish verify run %d: %w", rep.RunID, err) } return applyVerifyAlarm(ctx, s, rep, verifyErr) @@ -472,8 +499,8 @@ func applyVerifyAlarm(ctx context.Context, s *store.Store, rep *RemoteVerifyRepo return nil } if !rep.Clean() { - detail := fmt.Sprintf("objects mismatched=%d missing=%d, packs mismatched=%d missing=%d", - len(rep.Mismatched), len(rep.Missing), len(rep.PackMismatched), len(rep.PacksMissing)) + detail := fmt.Sprintf("objects mismatched=%d missing=%d, packs mismatched=%d missing=%d, mirror copies changed=%d missing=%d", + len(rep.Mismatched), len(rep.Missing), len(rep.PackMismatched), len(rep.PacksMissing), len(rep.PathsChanged), len(rep.PathsMissing)) // AlarmRaised reflects only a *newly* created latch, taken from the // atomic insert itself — so the CLI shouts on first detection but a // concurrent second raise (which found the latch already there) diff --git a/sync/verify_remote_test.go b/sync/verify_remote_test.go index 2373268..94b1883 100644 --- a/sync/verify_remote_test.go +++ b/sync/verify_remote_test.go @@ -288,11 +288,13 @@ func TestVerifyRemoteNoRecordedObjects(t *testing.T) { } } -func TestVerifyRemoteRefusesMirrorDestination(t *testing.T) { +// TestVerifyRemoteRefusesRcloneMirror: an rclone mirror records nothing a +// pass could re-check. +func TestVerifyRemoteRefusesRcloneMirror(t *testing.T) { f := setupContentAddressedFixture(t) - dest := &config.Destination{Name: "mirror", Type: "sftp", Root: "/data", Layout: config.LayoutMirror} + dest := &config.Destination{Name: "mirror", Type: "sftp", Root: "/data", Layout: config.LayoutMirror, Crypt: &config.Crypt{Password: "x"}} _, err := VerifyRemote(context.Background(), f.store, f.rcl, dest) - if err == nil || !strings.Contains(err.Error(), "content-addressed") { - t.Fatalf("err = %v, want content-addressed refusal", err) + if err == nil || !strings.Contains(err.Error(), "rclone mirror") { + t.Fatalf("err = %v, want an rclone-mirror refusal", err) } } From 81ca000f278aab10e7f773f29d232af0bf35cca8 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 02:51:18 +0200 Subject: [PATCH 27/61] offload: pin that a native local mirror gates, and an sftp mirror never does --- offload/native_mirror_test.go | 85 +++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 offload/native_mirror_test.go diff --git a/offload/native_mirror_test.go b/offload/native_mirror_test.go new file mode 100644 index 0000000..101cdb7 --- /dev/null +++ b/offload/native_mirror_test.go @@ -0,0 +1,85 @@ +package offload + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/sync" + "github.com/mbertschler/squirrel/volmark" +) + +// pushNativeMirror pushes the indexed volume at root to a native mirror +// on a local disk at dst, as `squirrel sync` does, and returns the +// destination. +func pushNativeMirror(t *testing.T, s *store.Store, root, dst string) *config.Destination { + t.Helper() + if err := os.MkdirAll(filepath.Join(dst, volName), 0o755); err != nil { + t.Fatal(err) + } + if err := volmark.Write(filepath.Join(dst, volName), volmark.Marker{Volume: volName}); err != nil { + t.Fatalf("seed destination marker: %v", err) + } + dest := &config.Destination{Name: "usb", Type: "local", Root: dst, Layout: config.LayoutMirror} + pair := sync.Pair{Volume: &config.Volume{Name: volName, Path: root}, Destination: dest} + rep, err := sync.RunPair(context.Background(), s, sync.Tools{}, pair, sync.Options{}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("push: status=%q err=%v warnings=%v", rep.Status, err, rep.Warnings) + } + return dest +} + +// TestOffloadGatesOnNativeLocalMirror: a native local mirror reads every +// copy back through BLAKE3, so its push alone lets offload delete the local +// bytes. Once a verify pass finds a copy gone, that copy stops vouching and +// its file stays. +func TestOffloadGatesOnNativeLocalMirror(t *testing.T) { + root, dst := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(root, "a.txt"), "alpha") + writeFile(t, filepath.Join(root, "b.txt"), "bravo") + s := setupStore(t) + ctx := context.Background() + indexVolume(t, s, root) + dest := pushNativeMirror(t, s, root, dst) + + if err := os.Remove(filepath.Join(dst, volName, "b.txt")); err != nil { + t.Fatal(err) + } + if rep, err := sync.VerifyRemote(ctx, s, nil, dest); err != nil || len(rep.PathsMissing) != 1 { + t.Fatalf("verify = %+v, %v; want b.txt found missing", rep, err) + } + + rep, err := Offload(ctx, s, root, Options{ + Name: volName, Paths: []string{"."}, Require: []string{"usb"}, + RequireDests: map[string]*config.Destination{"usb": dest}, + }) + if err != nil { + t.Fatalf("Offload: %v", err) + } + oneResult(t, rep, "a.txt", OutcomeOffloaded) + mustBeGone(t, filepath.Join(root, "a.txt")) + oneFailure(t, oneResult(t, rep, "b.txt", OutcomeNotDurable), "usb", FailureNotVerified) + mustExist(t, filepath.Join(root, "b.txt")) +} + +// TestOffloadRefusesNativeSFTPMirrorUpFront: a native sftp mirror reads +// nothing back, so naming one aborts the offload before any file is +// walked, and the reason says so. +func TestOffloadRefusesNativeSFTPMirrorUpFront(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "a.txt"), "alpha") + s := setupStore(t) + indexVolume(t, s, root) + dests := map[string]*config.Destination{"box": {Name: "box", Type: "sftp", Layout: config.LayoutMirror}} + _, err := Offload(context.Background(), s, root, Options{ + Name: volName, Paths: []string{"."}, Require: []string{"box"}, RequireDests: dests, + }) + if err == nil || !strings.Contains(err.Error(), "reads nothing back") { + t.Fatalf("err = %v, want an up-front refusal naming the reason", err) + } + mustExist(t, filepath.Join(root, "a.txt")) +} From 9a9025c195342ac26173122318c281ecf328aa2e Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 02:54:11 +0200 Subject: [PATCH 28/61] docs, design, audit: a native local mirror can gate offload again The mirror layout, offloading, verification, syncing and agent guides, the CLI and configuration references and the README describe the read-back fingerprint, the mirror verify pass and repairs, and which mirrors may be named in offload_requires. reference-setup.md's offload-gate paragraph, friction-log F21 and SAFETY-AUDIT.md M1 record the partial reversal of #211/#216. --- README.md | 2 +- SAFETY-AUDIT.md | 7 ++- design/friction-log.md | 8 ++++ design/reference-setup.md | 31 ++++++------- docs/src/content/docs/guides/agent.md | 9 ++-- docs/src/content/docs/guides/offloading.md | 30 +++++++++---- docs/src/content/docs/guides/syncing.md | 11 ++--- docs/src/content/docs/guides/verification.md | 33 +++++++++++--- docs/src/content/docs/layouts/mirror.md | 44 ++++++++++++++----- docs/src/content/docs/reference/cli.md | 10 +++-- .../content/docs/reference/configuration.md | 6 +-- 11 files changed, 133 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 352ecc1..6f1fa46 100644 --- a/README.md +++ b/README.md @@ -384,7 +384,7 @@ squirrel sync pictures --to nas # just one squirrel sync # every (volume, destination) pair in config ``` -A mirror on a `local` disk is written by squirrel itself: it hashes every file with BLAKE3 as it streams out, confirms each written path's size and mtime, and records the `presence+size` method; `--shallow` is refused there, since there is no comparison to skip. Sync compares every file with its copy on a remote mirror destination by checksum (rclone's `--checksum`), under the first hash both ends support — MD5 on S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an error, so the runs row is not marked success, and the run records the `checksum` method. The offload gate accepts neither: a mirror can never be named in `offload_requires`. Use `--shallow` to fall back to rclone's default size+mtime comparison on a remote mirror if you want speed over integrity for a big initial push. Encrypted (`crypt`) destinations always use the size+mtime comparison (see [Encrypted destinations](#encrypted-destinations)). +A mirror on a `local` disk is written by squirrel itself: it hashes every file with BLAKE3 as it streams out, reads each copy back through BLAKE3 before committing it, and records the run as `fingerprint-verified` once every file has such a copy, so it can be named in `offload_requires`; `--shallow` is refused there, since there is no comparison to skip. A native sftp mirror (no crypt) is written the same way, without the read-back. Sync compares every file with its copy on a mirror rclone writes (encrypted, or on s3, b2 or gcs) by checksum (rclone's `--checksum`), under the first hash both ends support — MD5 on S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an error, so the runs row is not marked success, and the run records the `checksum` method, which the offload gate refuses: such a mirror can never be named in `offload_requires`, and neither can a native sftp mirror, which reads nothing back. Use `--shallow` to fall back to rclone's default size+mtime comparison on an rclone mirror if you want speed over integrity for a big initial push. Encrypted (`crypt`) destinations always use the size+mtime comparison (see [Encrypted destinations](#encrypted-destinations)). ### First use and the `.squirrel-volume` marker diff --git a/SAFETY-AUDIT.md b/SAFETY-AUDIT.md index 15340f0..2618537 100644 --- a/SAFETY-AUDIT.md +++ b/SAFETY-AUDIT.md @@ -1019,7 +1019,12 @@ local and s3 — and runs were recorded as `blake3` all the same. records such a run as `checksum`, relabels the components already stored, and stops the offload gate from accepting it, so a mirror can no longer be named in `offload_requires`. The shallow warning now says "skipping the -checksum comparison". +checksum comparison". The native mirror +([#217](https://github.com/mbertschler/squirrel/pull/217)) earns the evidence +back on a `local` disk: it refuses `--shallow`, hashes every file as it +streams, reads each copy back through BLAKE3 before committing it, and +`squirrel verify` re-checks its copies, so a local mirror may gate offload +again. rclone mirrors and native sftp mirrors still may not. **Issue:** `sync: surface --shallow trade-off in logs and persist it on the runs row` → tracked in [#79](https://github.com/mbertschler/squirrel/issues/79), diff --git a/design/friction-log.md b/design/friction-log.md index 39c5e7b..df7f2c1 100644 --- a/design/friction-log.md +++ b/design/friction-log.md @@ -296,6 +296,14 @@ advance the vector, now as `checksum`, but the gate refuses that method and config load rejects every mirror in `offload_requires`, plain or crypt. The fail-fast half stands and now covers both. +*Revised again in the native mirror PR (#217).* A mirror squirrel writes on a +`local` disk reads every copy back through BLAKE3 before committing it, records +that as the copy's fingerprint, and advances the vector as +`fingerprint-verified`; `squirrel verify` re-checks its copies. Such a mirror +may be named in `offload_requires` again. Every other mirror is still rejected +at load: an rclone mirror (crypt, or on s3, b2, gcs) compares by checksum or +size+mtime, and a native sftp mirror reads nothing back. + ## Checkpoints 4–5 — trip return + offload day **F22 · S2 — ~~gate refusals are per-file walls of jargon that can't diff --git a/design/reference-setup.md b/design/reference-setup.md index 0bf5e7c..e24ccf2 100644 --- a/design/reference-setup.md +++ b/design/reference-setup.md @@ -70,21 +70,22 @@ so nothing ever tries. | **media** | nas (master), htpc | nas → htpc; nas → cloudbox + s3archive | htpc offloads watched items once s3archive holds them | Offload gates may name only targets that *produce durability evidence*. -Three shapes do: content-addressed and packed destinations (presence+size, -upgraded to content-verified by the scan-back fingerprint), peer nodes the -offloading machine itself pushes to (`peer-blake3`), and kopia repositories -(`kopia-verify`). A **mirror** — cloudbox, usb — never yields evidence the -gate accepts. A plain mirror's sync is rclone's `--checksum` compare, which -runs under the first hash both backends support (MD5 on local and s3), never -against the index's BLAKE3; it advances the vector with the `checksum` method -so `status` can show how current the copy is, but the gate refuses it (#211; -#156 had accepted it believing the compare was BLAKE3). A crypt mirror is -weaker still: the overlay hides the content hash, so rclone falls back to -size+mtime (friction log F21). Neither layout keeps a fingerprint a verify -pass could upgrade. Naming a locally-configured mirror in `offload_requires` -is therefore rejected at config load as an unsatisfiable policy — -fail-early, not the wait-forever gate the walk hit with the laptop gating on -the crypt-mirror cloudbox. +Four shapes do: content-addressed and packed destinations (presence+size, +upgraded to content-verified by the scan-back fingerprint), a mirror squirrel +writes itself on a local disk — usb — which reads every copy back through +BLAKE3 before committing it and advances as `fingerprint-verified`, peer nodes +the offloading machine itself pushes to (`peer-blake3`), and kopia +repositories (`kopia-verify`). Every other **mirror** never yields evidence +the gate accepts. The crypt mirror cloudbox is written by rclone: the overlay +hides the content hash, so rclone compares by size+mtime (friction log F21), +and a plain rclone mirror's `--checksum` compare runs under the first hash +both backends support, never against the index's BLAKE3 (#211). A native sftp +mirror reads nothing back, and squirrel never puts its paths — the volume's +own file names — on a server command line. None of those keeps a fingerprint a +verify pass could upgrade. Naming one in `offload_requires` is therefore +rejected at config load as an unsatisfiable policy — fail-early, not the +wait-forever gate the walk hit with the laptop gating on the crypt-mirror +cloudbox. A receive-only node (htpc) cannot credit its *upstream* peer, so its gate rests on the offsites the hub pushes to, reached via the durability pull. diff --git a/docs/src/content/docs/guides/agent.md b/docs/src/content/docs/guides/agent.md index af4e7c9..55d58cf 100644 --- a/docs/src/content/docs/guides/agent.md +++ b/docs/src/content/docs/guides/agent.md @@ -21,10 +21,11 @@ The agent requires an `[agent]` block in config. - **Scheduled audits** — runs [`audit`](/squirrel/guides/auditing/) passes on a schedule. - **Scheduled verify** — re-checks each content-addressed/packed destination's - recorded objects and packs against their upload fingerprints on its - `verify_every` cadence (per-destination, or an `[agent]` default) — the same - pass as [`squirrel verify`](/squirrel/guides/verification/), recorded as an - `audit` run. Offsite bitrot detection stops depending on anyone typing it. + recorded objects and packs against their upload fingerprints, and each native + mirror's recorded copies, on its `verify_every` cadence (per-destination, or + an `[agent]` default) — the same pass as + [`squirrel verify`](/squirrel/guides/verification/), recorded as an `audit` + run. Offsite bitrot detection stops depending on anyone typing it. - **Scheduled durability pull** — refreshes a peer's relayed durability evidence on its `pull_durability_every` cadence, independent of any sync. A receive-only node keeps its [offload](/squirrel/guides/offloading/) gate diff --git a/docs/src/content/docs/guides/offloading.md b/docs/src/content/docs/guides/offloading.md index 39c912c..a81d55b 100644 --- a/docs/src/content/docs/guides/offloading.md +++ b/docs/src/content/docs/guides/offloading.md @@ -36,13 +36,21 @@ destination/node namespace that `sync_to` uses; they may also name targets only has not arrived yet simply keeps the gate closed. :::caution[An unsatisfiable requirement is a config error, not a closed gate] -A target whose layout can *never* produce evidence the gate accepts — any -[mirror](/squirrel/layouts/mirror/) destination, plain or encrypted — is rejected -when the config loads, rather than leaving a gate that silently never opens. A -mirror sync compares each copy by checksum or by size+mtime, never against the -BLAKE3 in the index, and keeps no fingerprint a verify pass could upgrade. The check covers targets only a peer pushes to as well, -using the capabilities that peer reports. This distinction is the whole point: -a refusal you see always means **not yet**, never **never**. +A target that can *never* produce evidence the gate accepts is rejected when the +config loads, rather than leaving a gate that silently never opens. That is every +[mirror](/squirrel/layouts/mirror/) except one squirrel writes itself on a +`local` disk: + +- a mirror rclone writes (an encrypted one, or one on `s3`, `b2` or `gcs`) + compares each copy by checksum or by size+mtime, never against the BLAKE3 in + the index, and records nothing a verify pass could upgrade; +- a mirror on `sftp` reads nothing back, and never hashes your file names on + the server, so its copies are never fingerprinted. + +A mirror on a `local` disk reads every copy back through BLAKE3 and can gate. +The check covers targets only a peer pushes to as well, using the capabilities +that peer reports. This distinction is the whole point: a refusal you see always +means **not yet**, never **never**. ::: ## The durability gate @@ -74,6 +82,12 @@ object and pack fingerprint-verified: the component is re-stamped as content-verified and relays to peers that way, so a hub's certified archive can open an edge machine's gate. +A mirror on a `local` disk earns the same upgrade at push time: every copy is +read back through BLAKE3 before it is committed, so once every file of the +volume has such a copy, the push itself advances the component as +`fingerprint-verified`. A copy a verify pass later finds gone or changed stops +counting for its file until the next push writes it again. + The practical consequence: on a cold-archive target, offload becomes possible after verification has run, not merely after the sync succeeded. Give `verify` [its own agent cadence](/squirrel/guides/agent/) and this happens @@ -137,7 +151,7 @@ The causes, in the order the gate applies them: | **evidence is behind** | The target's coverage of that origin stops at an earlier run than this file's. | | **evidence is too old** | Coverage is sound but was last re-verified outside [`offload_max_evidence_age`](#evidence-staleness-opt-in). | | **not pushed since this file appeared** | No completed whole-volume sync covers the run in which the path became present (re-acquisition). | -| **stored but not content-verified** | The component rests on presence or on a mirror's checksum comparison, not on proof of the bytes; a verify pass upgrades a `presence+size` component. | +| **stored but not content-verified** | The component rests on presence or on an rclone mirror's checksum comparison, not on proof of the bytes; a verify pass upgrades a `presence+size` component, and a local mirror's next push rewrites a copy verify found gone or changed. | ## Evidence staleness (opt-in) diff --git a/docs/src/content/docs/guides/syncing.md b/docs/src/content/docs/guides/syncing.md index be63e22..1e60d16 100644 --- a/docs/src/content/docs/guides/syncing.md +++ b/docs/src/content/docs/guides/syncing.md @@ -18,17 +18,18 @@ squirrel sync # every (volume, destination) pair in config ## Verification A mirror on a `local` disk is written by squirrel itself: it hashes every file -with BLAKE3 as it streams out, confirms each written path's size and mtime, and -records the run with the `presence+size` method (see -[Mirror](/squirrel/layouts/mirror/)). +with BLAKE3 as it streams out, reads each copy back through BLAKE3 before +committing it, and records the run as `fingerprint-verified` once every file +has such a copy (see [Mirror](/squirrel/layouts/mirror/#verification)). That +mirror can back an offload. A native mirror on `sftp` reads nothing back, so +its runs stay `presence+size` and cannot. Sync compares every file with its copy on an rclone mirror destination by checksum (rclone's `--checksum`), under the first hash both ends support — MD5 on S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an error, so the runs row is **not** marked success. The run is -recorded with the `checksum` method. +recorded with the `checksum` method, which the offload gate refuses. -The offload gate accepts neither method, so a mirror cannot back an offload. Peer syncs are different: both ends hash every byte with BLAKE3 (see [Peer sync](/squirrel/guides/peer-sync/)). diff --git a/docs/src/content/docs/guides/verification.md b/docs/src/content/docs/guides/verification.md index 2e3e7e1..cab1bbc 100644 --- a/docs/src/content/docs/guides/verification.md +++ b/docs/src/content/docs/guides/verification.md @@ -1,6 +1,6 @@ --- title: Offsite verification -description: Content-addressed and packed destinations get a metadata-only integrity check — the scan-back fingerprint — that re-checks stored objects without downloading a byte. +description: squirrel verify re-checks what squirrel stored — content-addressed and packed objects by their scan-back fingerprint, a native mirror's copies by size, mtime and BLAKE3. --- Cold archive storage is exactly the copy you can't cheaply re-download and @@ -45,8 +45,7 @@ The read is done via a direct S3 `ListObjectsV2` for `s3`, or `rclone lsjson ## Running verify -Re-verify a destination (or all content-addressed and packed destinations) at any -time: +Re-verify a destination (or every destination verify covers) at any time: ```sh squirrel verify archive @@ -54,8 +53,9 @@ squirrel verify ``` With no argument, `verify` covers every content-addressed or packed destination -in config. An explicit destination must have one of those layouts, else it -errors. +and every [native mirror](#native-mirrors) in config. An explicit destination +must be one of those, else it errors: a mirror rclone writes records nothing to +re-check. The pass lists the destination's `objects/` directory once (batched, metadata-only), then per recorded object: @@ -116,6 +116,29 @@ locally from the crypt passwords. Verification is otherwise identical, so keying the names costs no depth of checking and no offload eligibility. ::: +## Native mirrors + +A [mirror](/squirrel/layouts/mirror/) squirrel writes itself — on a `local` +disk, or on `sftp` without crypt — records every copy it stored, so verify +re-checks those instead of objects. It reaches the mirror through squirrel's own +transport, without rclone. Each pass: + +- checks every copy squirrel stored, the live ones and those in + `.squirrel-history`, by size and mtime — one `lstat` each; +- on a `local` disk, also re-reads the least recently checked copies through + BLAKE3, until it has read a tenth of the stored bytes, so every byte is read + again within about ten passes. + +A copy found gone or changed prints one loud line, latches the +[alarm](#a-mismatch-latches-an-alarm), and stops counting as evidence for its +file. The next push writes it again as long as the index still holds that file +there, with a warning; the copy that was found keeps its place in history if the +push has to move it aside. + +A local mirror earns its fingerprints at push time: every copy is read back +through BLAKE3 before it is committed. An sftp mirror is checked by size and +mtime alone, and never gates offload. + ## Related knobs ```toml diff --git a/docs/src/content/docs/layouts/mirror.md b/docs/src/content/docs/layouts/mirror.md index dfdfc60..ef2cbd9 100644 --- a/docs/src/content/docs/layouts/mirror.md +++ b/docs/src/content/docs/layouts/mirror.md @@ -30,8 +30,11 @@ run, not what a fresh walk of the disk finds. For each changed path it: 1. streams the file into `.squirrel-staging/run-/`, hashing the bytes as they go, and refuses the path if they no longer match the index; -2. moves whatever the path holds into `.squirrel-history/run-/`; -3. renames the staged copy onto the path. The rename never replaces a file. +2. on a `local` disk, reads the staged copy back through BLAKE3, past the page + cache where the system allows, and refuses the path if the disk returns + other bytes; +3. moves whatever the path holds into `.squirrel-history/run-/`; +4. renames the staged copy onto the path. The rename never replaces a file. squirrel records each move before making it, so the next push finishes or withdraws whatever a crashed or unplugged push left half done. Every successful @@ -67,21 +70,38 @@ Files removed locally remain at the destination. ## Verification A native mirror push hashes every file with BLAKE3 as it streams out and -confirms each written path's size and mtime. Nothing reads the landed bytes back -yet, so the run advances the destination's durability evidence under the -`presence+size` method. `--shallow` is refused on a native mirror: there is no -comparison to switch off. +confirms each written path's size and mtime. What else backs it depends on +where the mirror lives: + +- **On a `local` disk**, every copy is read back through BLAKE3 before it is + committed, and the match is recorded as the copy's fingerprint. Once every + file of the volume has such a copy, the run advances the destination's + durability evidence as `fingerprint-verified`. A local mirror can therefore be + named in [`offload_requires`](/squirrel/guides/offloading/). +- **On sftp**, nothing is read back: a mirror's paths are your own file names, + and squirrel never puts them on a server command line to hash them there. The + run advances as `presence+size`, and an sftp mirror cannot gate offload. Use a + [content-addressed](/squirrel/layouts/content-addressed/) or + [packed](/squirrel/layouts/packed/) sftp destination for that. + +[`squirrel verify`](/squirrel/guides/verification/) re-checks a native mirror, +on demand or on the agent's `verify_every` cadence. Each pass checks every copy +squirrel stored — the live ones and those in `.squirrel-history` — by size and +mtime. On a local disk it also re-reads the least recently checked copies, a +tenth of the stored bytes per pass, so every byte is read again within about ten +passes. A copy found gone or changed stops counting as evidence, raises the +destination's alarm, and is written again by the next push while the index still +holds that file. + +`--shallow` is refused on a native mirror: there is no comparison to switch off. An rclone mirror compares every file with its copy by checksum (rclone's `--checksum`), under the first hash both ends support — MD5 on S3, independent of the BLAKE3 in the index. A copy that fails the check after transfer is an error, so the run is not marked success, and the run advances the evidence under -the `checksum` method. - -[`squirrel status`](/squirrel/reference/cli/) shows either method, but the -offload gate accepts neither: a mirror cannot be named in -[`offload_requires`](/squirrel/guides/offloading/). See -[Syncing & first use](/squirrel/guides/syncing/). +the `checksum` method. [`squirrel status`](/squirrel/reference/cli/) shows it, +but the offload gate refuses it, and an rclone mirror cannot be named in +`offload_requires`. See [Syncing & first use](/squirrel/guides/syncing/). ## Index snapshots diff --git a/docs/src/content/docs/reference/cli.md b/docs/src/content/docs/reference/cli.md index e28d49c..d197222 100644 --- a/docs/src/content/docs/reference/cli.md +++ b/docs/src/content/docs/reference/cli.md @@ -214,22 +214,24 @@ renders the same facts from the same query layer — see ## squirrel verify -**Re-check recorded offsite objects and packs against their upload fingerprints.** +**Re-check what squirrel recorded storing on a destination: objects and packs against their upload fingerprints, a native mirror's copies by size, mtime and BLAKE3.** ``` squirrel verify [] ``` Optional single positional. If omitted, verifies every content-addressed or -packed destination in config (sorted). An explicit destination must have layout -`content-addressed` or `packed`, else it errors. No flags. See +packed destination and every native mirror in config (sorted). An explicit +destination must be one of those, else it errors: a mirror rclone writes records +nothing to re-check. No flags. See [Offsite verification](/squirrel/guides/verification/). A clean pass does two things beyond reporting: it fills any pending fingerprints and then **upgrades the destination's durability vector to a content-verified method**, which is what lets [`offload`](#squirrel-offload) accept it. A mismatch **latches a standing alarm** on the destination that survives the run and shows -on every surface until acknowledged. +on every surface until acknowledged. On a native mirror, a copy found gone or +changed is also marked lost, and the next push writes it again. ### squirrel verify ack diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md index c98f5a1..94c5c20 100644 --- a/docs/src/content/docs/reference/configuration.md +++ b/docs/src/content/docs/reference/configuration.md @@ -25,7 +25,7 @@ table resolved at load time. | `sync_to` | no | List of destination names to push to. | | `sync_every` | no | Duration; the [agent](/squirrel/guides/agent/) syncs this volume to every target in `sync_to` on this cadence. Absent = no scheduled sync. | | `index_every` | no | Duration; cadence for *standalone* index passes between syncs (a sync indexes first anyway). Absent = no extra indexing. | -| `offload_requires` | no | List of targets whose durability must cover a file before its local bytes may be [offloaded](/squirrel/guides/offloading/). A volume without this key refuses to offload. Naming a mirror destination is a config error: a mirror can never produce evidence the gate accepts. | +| `offload_requires` | no | List of targets whose durability must cover a file before its local bytes may be [offloaded](/squirrel/guides/offloading/). A volume without this key refuses to offload. Naming a mirror destination is a config error, except a native mirror on a `local` disk: every other mirror can never produce evidence the gate accepts. | | `offload_max_evidence_age` | no | Duration; a target whose durability evidence was last re-verified longer ago than this refuses the offload. Default disabled. | ### `[volumes..hook]` @@ -157,7 +157,7 @@ For `layout = "content-addressed"` or `layout = "packed"` destinations. See | `pack_threshold` | packed | — | Files smaller than this are packed; at/above land as objects (e.g. `1MiB`). | | `pack_size` | packed | — | Target size of one pack before it is closed (e.g. `512MiB`). | | `zstd_level` | packed | — | zstd compression level, `1` fastest … `4` best. | -| `verify_every` | content-addressed / packed | off | Cadence for the agent to re-check this destination's recorded objects and packs against their upload fingerprints — the same pass as [`squirrel verify`](/squirrel/guides/verification/), recorded as an `audit` run. Falls back to `[agent] verify_every`. Read-only; the agent never writes to the destination. | +| `verify_every` | content-addressed / packed, native mirror | off | Cadence for the agent to re-check what squirrel recorded storing on this destination — objects and packs against their upload fingerprints, a native mirror's copies by size, mtime and (on a local disk) BLAKE3 — the same pass as [`squirrel verify`](/squirrel/guides/verification/), recorded as an `audit` run. Falls back to `[agent] verify_every`. Read-only; the agent never writes to the destination. Rejected on a mirror rclone writes. | ## `[backups]` @@ -195,7 +195,7 @@ optional. See [The agent](/squirrel/guides/agent/#listener-less-cadence-only-mac | `auth.peers..bearer` | no | Per-peer bearer token this agent accepts from node ``. Must equal that node's `[nodes.].auth.bearer`; [`squirrel node pair`](/squirrel/guides/peer-sync/) emits both halves so they match by construction. | | `scan_interval` | no | Drift-scan cadence over every hosted volume. Off when absent. | | `scan_strategy` | no | `shallow` (default) or `deep` (re-hash everything — bit-rot detection). | -| `verify_every` | no | Fleet-wide default verify cadence applied to every content-addressed/packed destination that declares no `verify_every` of its own. Off when absent. | +| `verify_every` | no | Fleet-wide default verify cadence applied to every content-addressed, packed or native mirror destination that declares no `verify_every` of its own. Off when absent. | ## `[nodes.]` From 4db8561a653c78142445ba0d4cf5df5c4f11948b Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 02:56:50 +0200 Subject: [PATCH 29/61] sync: let the name guard commit a content layout's artifacts A guard held by a content-addressed or packed push commits this run's staging onto objects/, packs/, this run's placement map and this run's manifest segment, and never displaces anything; a mirror's guard still commits onto the mirrored tree alone. --- design/native-mirror.md | 8 ++++--- sync/transport_guard.go | 45 +++++++++++++++++++++++++++++++----- sync/transport_guard_test.go | 43 ++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 9 deletions(-) diff --git a/design/native-mirror.md b/design/native-mirror.md index 96b738d..b7a3fa2 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -256,9 +256,11 @@ type transport interface { finished (`.squirrel-staging/run-/`), and on ride-along snapshots (`.squirrel-index/index-*.db`, which rotation already deletes today). Anything else found in staging is reported and left alone; - - `Rename` only from this run's staging to a live name (commit) or to a - snapshot name (the ride-along), or from a live name to - `.squirrel-history/run-/` (displacement); + - `Rename` only from this run's staging to a snapshot name (the + ride-along) or to what the layout commits — a live name for a mirror; for + a content layout `objects/`, `packs/`, `packs/map-` + or `/index/run-` — or, for a mirror only, from a live + name to `.squirrel-history/run-/` (displacement); - under `--init`, before the push holds a run, the marker's own staging: it is written to `.squirrel-staging/volume-marker` and renamed onto `.squirrel-volume`, and a stale staged copy may be removed. diff --git a/sync/transport_guard.go b/sync/transport_guard.go index e5e5bd2..6190f1c 100644 --- a/sync/transport_guard.go +++ b/sync/transport_guard.go @@ -21,6 +21,10 @@ var errGuardRefused = errors.New("the name guard refuses this operation") type nameGuard struct { volumeDir string // the volume's directory under the destination root runID int64 // the push holding the guard + // content marks a content-addressed or packed push: its commits land + // on artifact names instead of the mirrored tree, and it displaces + // nothing. + content bool // bootstrap lets a push under --init write the volume marker, before // it holds a run. bootstrap bool @@ -47,10 +51,12 @@ const ( // - Remove of a staging entry, or an emptied staging run directory, // of a run that has finished: /.squirrel-staging/run-[/]; // - Remove of a ride-along snapshot: /.squirrel-index/index-*.db; -// - Rename from this run's staging onto a live name (a commit), or onto -// a snapshot name (the ride-along); -// - Rename of a live name to the same path under this run's history -// (a displacement): /.squirrel-history/run-/. +// - Rename from this run's staging onto a snapshot name (the ride-along), +// or onto what the layout commits: a live name for a mirror, an +// artifact name for a content layout (see artifact); +// - for a mirror, Rename of a live name to the same path under this +// run's history (a displacement): +// /.squirrel-history/run-/. // // Every Rename lands on a name that does not exist yet: the transport // fails one onto an existing name. @@ -64,16 +70,43 @@ func (g nameGuard) permit(op guardOp, name, to string) error { return nil } case op == opRename: - if rel, ok := g.liveRel(name); ok && to == historyName(g.volumeDir, g.runID, rel) { + if rel, ok := g.liveRel(name); ok && !g.content && to == historyName(g.volumeDir, g.runID, rel) { return nil } - if _, ok := g.liveRel(to); (ok || g.snapshot(to)) && g.stagedByThisRun(name) { + if g.stagedByThisRun(name) && (g.snapshot(to) || g.commitTarget(to)) { return nil } } return fmt.Errorf("%w: %s %q → %q", errGuardRefused, [...]string{"remove", "rename"}[op], name, to) } +// commitTarget reports whether a staged file may be committed onto name. +func (g nameGuard) commitTarget(name string) bool { + if g.content { + return g.artifact(name) + } + _, ok := g.liveRel(name) + return ok +} + +// artifact reports whether name is one a content layout's run commits: a +// content object, objects/; a pack, packs/; this run's placement +// map, packs/map-; or this run's manifest segment, +// /index/run-. +func (g nameGuard) artifact(name string) bool { + dir, base := path.Split(name) + run := strconv.FormatInt(g.runID, 10) + switch dir { + case ObjectsDirName + "/": + return isStagingKey(base) + case PacksDirName + "/": + return isStagingKey(base) || base == packMapPrefix+run + case g.volumeDir + "/" + ManifestDirName + "/": + return base == "run-"+run + } + return false +} + // snapshot reports whether name is a ride-along snapshot of the volume: // /.squirrel-index/index-*.db. func (g nameGuard) snapshot(name string) bool { diff --git a/sync/transport_guard_test.go b/sync/transport_guard_test.go index 8236173..ade242c 100644 --- a/sync/transport_guard_test.go +++ b/sync/transport_guard_test.go @@ -65,6 +65,49 @@ func TestNameGuardPermits(t *testing.T) { } } +// TestNameGuardContentLayout: a content layout's guard commits this run's +// staging onto artifact names alone, and displaces nothing. +func TestNameGuardContentLayout(t *testing.T) { + key := strings.Repeat("ab", 32) + staged := "pics/.squirrel-staging/run-7/" + key + g := nameGuard{volumeDir: "pics", runID: 7, content: true, finished: func(id int64) bool { return id != 7 }} + cases := []struct { + name string + op guardOp + from, to string + want bool + }{ + {"commit an object", opRename, staged, "objects/" + key, true}, + {"commit a pack", opRename, staged, "packs/" + key, true}, + {"commit this run's placement map", opRename, staged, "packs/map-7", true}, + {"commit another run's placement map", opRename, staged, "packs/map-6", false}, + {"commit this run's segment", opRename, staged, "pics/index/run-7", true}, + {"commit another run's segment", opRename, staged, "pics/index/run-6", false}, + {"commit another volume's segment", opRename, staged, "docs/index/run-7", false}, + {"commit an object from another run's staging", opRename, "pics/.squirrel-staging/run-6/" + key, "objects/" + key, false}, + {"commit an object under a name that is no hash", opRename, staged, "objects/cat.jpg", false}, + {"commit an object below objects", opRename, staged, "objects/ab/" + key, false}, + {"commit onto the mirrored tree", opRename, staged, "pics/2024/cat.jpg", false}, + {"ride a snapshot along", opRename, staged, "pics/.squirrel-index/index-20260101T000000.000Z-run-7.db", true}, + {"displace a segment", opRename, "pics/index/run-6", "pics/.squirrel-history/run-7/index/run-6", false}, + {"move an object", opRename, "objects/" + key, "packs/" + key, false}, + {"remove an object", opRemove, "objects/" + key, "", false}, + {"remove a finished run's staging", opRemove, "pics/.squirrel-staging/run-6/" + key, "", true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + err := g.permit(c.op, c.from, c.to) + if got := err == nil; got != c.want { + t.Fatalf("permit = %v, want allowed=%t", err, c.want) + } + }) + } + mirror := nameGuard{volumeDir: "pics", runID: 7} + if err := mirror.permit(opRename, staged, "objects/"+key); err == nil { + t.Fatal("a mirror's guard committed onto an object name") + } +} + // TestNameGuardBootstrap: under --init the guard also lets the marker be // staged, renamed onto .squirrel-volume, and a stale staged copy removed — // run or not — and nothing more. From 4409d7c5ff7cde246feb9551f2cb2ac48bcfad56 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:00:58 +0200 Subject: [PATCH 30/61] sync: run the sftp server's hash command through the transport ServerHash runs the hash_algo's sum command on the server over an artifact, built from the root and a hex artifact name alone and only when both hold safe characters. The command is probed once per session by hashing a known input; a server that runs no programs, or computes something else, offers no server hash. The local transport offers none: its bytes are read back. The test sftp server runs sum commands on request. --- design/native-mirror.md | 22 ++-- sync/transport.go | 4 + sync/transport_local.go | 6 ++ sync/transport_sftp.go | 7 ++ sync/transport_sftp_dial.go | 1 + sync/transport_sftp_hash.go | 178 +++++++++++++++++++++++++++++++ sync/transport_sftp_hash_test.go | 103 ++++++++++++++++++ sync/transport_sftp_test.go | 72 +++++++++++-- sync/transport_stall.go | 13 +++ 9 files changed, 393 insertions(+), 13 deletions(-) create mode 100644 sync/transport_sftp_hash.go create mode 100644 sync/transport_sftp_hash_test.go diff --git a/design/native-mirror.md b/design/native-mirror.md index b7a3fa2..da27c2c 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -324,13 +324,21 @@ type transport interface { pinned one (`sync/transport_sftp_hostkey.go`). - **One optional server-side command: a hash.** Content-addressed and packed artifacts get their fingerprint confirmed, and re-confirmed, by a hash - command run on the server. That is `sha256sum` by default, chosen by - `hash_algo`, as rclone runs today. - - The command line is built only from the configured root and hex artifact - names. A root holding anything beyond letters, digits, `.`, `_`, `-` and - `/` is never hashed on the server. - - The transport probes for the command once per push. On a server that runs - no programs, like the cloudbox shape, fingerprints stay pending, as today. + command run on the server (`ServerHash`, `sync/transport_sftp_hash.go`). + That is `sha256sum` by default, chosen by `hash_algo`: `md5sum`, + `sha1sum`, `sha256sum` or `b3sum`, the hashes squirrel can also compute + itself to compare against. + - The command line is built only from the configured root and a name + whose last element is a lowercase hex artifact name: an object or pack, + or its staged copy `/.squirrel-staging/run-/` (volume + names hold only letters, digits, `_` and `-`). A root holding anything + beyond letters, digits, `.`, `_`, `-` and `/` is never hashed on the + server, and a relative one is passed as `./` so it never reads as + an option. + - The transport probes for the command once per session, and a push opens + one session: it hashes a known input on the server and compares. On a + server that runs no programs, like the cloudbox shape, or whose command + computes something else, fingerprints stay pending, as today. - Mirror paths are user filenames, so they never go on a command line. ## 4. The mirror layout diff --git a/sync/transport.go b/sync/transport.go index 3987671..9777cc3 100644 --- a/sync/transport.go +++ b/sync/transport.go @@ -32,6 +32,10 @@ type transport interface { Rename(ctx context.Context, from, to string) error // Remove deletes the file or empty directory at name. Remove(ctx context.Context, name string) error + // ServerHash is the destination's own hash of the file at name, run + // where the bytes are: an sftp server's hash command. errNoServerHash + // where there is none. + ServerHash(ctx context.Context, name string) (remoteChecksum, error) Close() error } diff --git a/sync/transport_local.go b/sync/transport_local.go index 8c3a7d1..264ae31 100644 --- a/sync/transport_local.go +++ b/sync/transport_local.go @@ -156,6 +156,12 @@ func (t *localTransport) Remove(_ context.Context, name string) error { return t.root.Remove(filepath.FromSlash(name)) } +// ServerHash: a local disk runs no hash of its own; squirrel reads its +// bytes back instead. +func (t *localTransport) ServerHash(context.Context, string) (remoteChecksum, error) { + return remoteChecksum{}, errNoServerHash +} + // checkName refuses a name that is not a clean path below the root, or // whose parent chain crosses a symlink or a non-directory. func (t *localTransport) checkName(name string) error { diff --git a/sync/transport_sftp.go b/sync/transport_sftp.go index b9ee96a..6d37352 100644 --- a/sync/transport_sftp.go +++ b/sync/transport_sftp.go @@ -9,6 +9,7 @@ import ( "os" "path" "strings" + "sync" "time" "github.com/pkg/sftp" @@ -28,6 +29,12 @@ type sftpTransport struct { // fsync is whether the server offers fsync@openssh.com, which Put // uses to flush a file to stable storage before it returns. fsync bool + // hashAlgo is the destination's hash_algo: the hash command + // ServerHash runs, probed once (probed, probeErr). + hashAlgo string + probeMu sync.Mutex + probed bool + probeErr error } // Close drops the ssh connection first: the sftp client's own Close diff --git a/sync/transport_sftp_dial.go b/sync/transport_sftp_dial.go index 92da8cb..8dfe4a4 100644 --- a/sync/transport_sftp_dial.go +++ b/sync/transport_sftp_dial.go @@ -47,6 +47,7 @@ func dialSFTP(ctx context.Context, dest *config.Destination) (*sftpTransport, er return nil, fmt.Errorf("destination %q: %w", dest.Name, err) } tr.root = dest.Root + tr.hashAlgo = dest.HashAlgo return tr, nil } diff --git a/sync/transport_sftp_hash.go b/sync/transport_sftp_hash.go new file mode 100644 index 0000000..1a71287 --- /dev/null +++ b/sync/transport_sftp_hash.go @@ -0,0 +1,178 @@ +package sync + +import ( + "bytes" + "context" + "crypto/md5" + "crypto/sha1" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "hash" + "io" + "path" + "regexp" + "strings" + + "github.com/zeebo/blake3" +) + +// errNoServerHash marks a destination that offers squirrel no hash of its +// own for a file: a local disk, whose bytes squirrel reads back instead, an +// sftp server that runs no hash command, or a name the command line may +// not carry. +var errNoServerHash = errors.New("the destination offers no hash of its own") + +// serverHashCommands are the commands an sftp server runs for each +// hash_algo squirrel's own transport supports. +var serverHashCommands = map[string]string{ + "md5": "md5sum", + "sha1": "sha1sum", + "sha256": "sha256sum", + "blake3": "b3sum", +} + +// newArtifactHash is the hash algo names, computed on this machine: what +// the server's command must agree with. +func newArtifactHash(algo string) hash.Hash { + switch algo { + case "md5": + return md5.New() + case "sha1": + return sha1.New() + case "sha256": + return sha256.New() + case "blake3": + return blake3.New() + } + return nil +} + +// commandSafe matches what a server command line may carry unquoted. +var commandSafe = regexp.MustCompile(`^[A-Za-z0-9._/-]+$`) + +// serverHashProbe is the input the probe hashes on the server. +const serverHashProbe = "squirrel server hash probe\n" + +// maxHashOutput bounds what squirrel reads from one hash command. +const maxHashOutput = 4 << 10 + +// ServerHash runs the configured hash command on the server over the file +// at name. The command line is built from the destination root and name +// alone, and only when both hold nothing but letters, digits, '.', '_', '-' +// and '/' and name ends in a lowercase hex artifact name — never from a +// mirror path, which is a user's file name. The command is probed once per +// session, by hashing a known input; a server without it gets +// errNoServerHash. +func (t *sftpTransport) ServerHash(_ context.Context, name string) (remoteChecksum, error) { + if err := t.checkName(name); err != nil { + return remoteChecksum{}, err + } + target, err := t.hashTarget(name) + if err != nil { + return remoteChecksum{}, err + } + if err := t.probeServerHash(); err != nil { + return remoteChecksum{}, err + } + out, err := t.runCommand(serverHashCommands[t.hashAlgo]+" "+target, nil) + if err != nil { + return remoteChecksum{}, err + } + sum, err := parseHashOutput(out, newArtifactHash(t.hashAlgo).Size()) + if err != nil { + return remoteChecksum{}, fmt.Errorf("hash %s on the server: %w", name, err) + } + return remoteChecksum{Algo: t.hashAlgo, Value: sum}, nil +} + +// hashTarget is the command-line argument naming name on the server, or +// errNoServerHash when the command line may not carry it. +func (t *sftpTransport) hashTarget(name string) (string, error) { + if _, ok := serverHashCommands[t.hashAlgo]; !ok { + return "", fmt.Errorf("%w: no hash_algo names a command squirrel runs", errNoServerHash) + } + full := path.Join(t.root, name) + if !commandSafe.MatchString(full) || !isStagingKey(path.Base(name)) { + return "", fmt.Errorf("%w: %s holds characters squirrel never puts on a server command line", errNoServerHash, full) + } + if !strings.HasPrefix(full, "/") { + full = "./" + full + } + return full, nil +} + +// probeServerHash asks the server, once, to hash a known input, and +// remembers whether its command agreed with this machine. +func (t *sftpTransport) probeServerHash() error { + t.probeMu.Lock() + defer t.probeMu.Unlock() + if !t.probed { + t.probeErr = t.runProbe() + t.probed = true + } + return t.probeErr +} + +func (t *sftpTransport) runProbe() error { + h := newArtifactHash(t.hashAlgo) + h.Write([]byte(serverHashProbe)) + command := serverHashCommands[t.hashAlgo] + out, err := t.runCommand(command, strings.NewReader(serverHashProbe)) + if err != nil { + return fmt.Errorf("%w: %v", errNoServerHash, err) + } + sum, err := parseHashOutput(out, h.Size()) + if err != nil || sum != hex.EncodeToString(h.Sum(nil)) { + return fmt.Errorf("%w: %s on the server does not compute %s", errNoServerHash, command, t.hashAlgo) + } + return nil +} + +// runCommand runs cmd in a session of its own and returns what it printed. +func (t *sftpTransport) runCommand(cmd string, stdin io.Reader) (string, error) { + s, err := t.conn.NewSession() + if err != nil { + return "", fmt.Errorf("open a session for %s: %w", cmd, err) + } + defer func() { _ = s.Close() }() + var out bytes.Buffer + s.Stdin = stdin + s.Stdout = &limitedWriter{w: &out, n: maxHashOutput} + if err := s.Run(cmd); err != nil { + return "", fmt.Errorf("run %s on the server: %w", cmd, err) + } + return out.String(), nil +} + +// parseHashOutput reads the digest a sum command printed first: size bytes +// of lowercase hex. +func parseHashOutput(out string, size int) (string, error) { + fields := strings.Fields(out) + if len(fields) == 0 { + return "", errors.New("the command printed nothing") + } + sum := strings.ToLower(fields[0]) + if b, err := hex.DecodeString(sum); err != nil || len(b) != size { + return "", fmt.Errorf("the command printed %q, not a digest", fields[0]) + } + return sum, nil +} + +// limitedWriter keeps the first n bytes written to it and drops the rest. +type limitedWriter struct { + w io.Writer + n int +} + +func (l *limitedWriter) Write(p []byte) (int, error) { + keep := min(len(p), l.n) + if keep > 0 { + if _, err := l.w.Write(p[:keep]); err != nil { + return 0, err + } + l.n -= keep + } + return len(p), nil +} diff --git a/sync/transport_sftp_hash_test.go b/sync/transport_sftp_hash_test.go new file mode 100644 index 0000000..8850d2b --- /dev/null +++ b/sync/transport_sftp_hash_test.go @@ -0,0 +1,103 @@ +package sync + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// hashFixture serves root from a test server that runs commands, and +// plants one artifact, objects/, holding body. +func hashFixture(t *testing.T, commands map[string]string, body string) (*sftpTransport, string) { + t.Helper() + srv := startSFTPServer(t) + srv.runsHashCommands(commands) + root := t.TempDir() + key := strings.Repeat("ab", 32) + if err := os.MkdirAll(filepath.Join(root, ObjectsDirName), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, ObjectsDirName, key), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + dest := srv.destination(t, root) + dest.HashAlgo = "sha256" + tr := mustDialSFTP(t, dest) + t.Cleanup(func() { _ = tr.Close() }) + return tr, ObjectsDirName + "/" + key +} + +// TestServerHashRunsTheCommand: a server with the command hashes an +// artifact where it lies, and the value is what this machine computes. +func TestServerHashRunsTheCommand(t *testing.T) { + tr, name := hashFixture(t, map[string]string{"sha256sum": "sha256"}, "alpha") + got, err := tr.ServerHash(context.Background(), name) + if err != nil { + t.Fatalf("ServerHash: %v", err) + } + want := sha256.Sum256([]byte("alpha")) + if got.Algo != "sha256" || got.Value != hex.EncodeToString(want[:]) { + t.Fatalf("ServerHash = %+v, want sha256 %x", got, want) + } +} + +// TestServerHashRefusesWhatItCannotTrust: a server that runs no programs, +// or whose command computes another hash, offers no server hash; neither +// does a name that is no hex artifact name, a root the command line may not +// carry, or a local disk. +func TestServerHashRefusesWhatItCannotTrust(t *testing.T) { + ctx := context.Background() + for _, c := range []struct { + name string + commands map[string]string + }{ + {"no programs", nil}, + {"a command computing another hash", map[string]string{"sha256sum": "blake3"}}, + } { + t.Run(c.name, func(t *testing.T) { + tr, name := hashFixture(t, c.commands, "alpha") + if _, err := tr.ServerHash(ctx, name); !errors.Is(err, errNoServerHash) { + t.Fatalf("ServerHash = %v, want errNoServerHash", err) + } + }) + } + tr, _ := hashFixture(t, map[string]string{"sha256sum": "sha256"}, "alpha") + if err := os.WriteFile(filepath.Join(tr.root, "cat; rm -rf x.jpg"), []byte("meow"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := tr.ServerHash(ctx, "cat; rm -rf x.jpg"); !errors.Is(err, errNoServerHash) { + t.Fatalf("ServerHash of a user's file name = %v, want errNoServerHash", err) + } + tr.root += "/with space" + if _, err := tr.ServerHash(ctx, ObjectsDirName+"/"+strings.Repeat("ab", 32)); !errors.Is(err, errNoServerHash) { + t.Fatalf("ServerHash under an unsafe root = %v, want errNoServerHash", err) + } + local, err := openLocalTransport(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer local.Close() + if _, err := local.ServerHash(ctx, "objects/x"); !errors.Is(err, errNoServerHash) { + t.Fatalf("local ServerHash = %v, want errNoServerHash", err) + } +} + +// TestServerHashProbesOnce: the probe runs once per session, so a server +// that stops running the command afterwards fails the hash itself. +func TestServerHashProbesOnce(t *testing.T) { + srvCommands := map[string]string{"sha256sum": "sha256"} + tr, name := hashFixture(t, srvCommands, "alpha") + ctx := context.Background() + if _, err := tr.ServerHash(ctx, name); err != nil { + t.Fatalf("first ServerHash: %v", err) + } + tr.hashAlgo = "sha1" + if _, err := tr.ServerHash(ctx, name); err == nil || errors.Is(err, errNoServerHash) { + t.Fatalf("ServerHash after the probe = %v, want the command's own failure", err) + } +} diff --git a/sync/transport_sftp_test.go b/sync/transport_sftp_test.go index a785bf9..191b127 100644 --- a/sync/transport_sftp_test.go +++ b/sync/transport_sftp_test.go @@ -7,11 +7,14 @@ import ( "crypto/rsa" "encoding/pem" "errors" + "fmt" + "io" "net" "os" "os/exec" "path/filepath" "strings" + "sync" "testing" "time" @@ -35,6 +38,26 @@ type sftpTestServer struct { // hung, once closed, makes the sftp subsystem stop reading requests, // as a server whose disk hangs does. hung chan struct{} + + mu sync.Mutex + // commands maps each hash command the server runs to the hash it + // actually computes; a server with none runs no programs. + commands map[string]string +} + +// runsHashCommands lets the server run the given sum commands, each +// computing the hash its value names. +func (s *sftpTestServer) runsHashCommands(commands map[string]string) { + s.mu.Lock() + defer s.mu.Unlock() + s.commands = commands +} + +func (s *sftpTestServer) hashCommand(name string) (string, bool) { + s.mu.Lock() + defer s.mu.Unlock() + algo, ok := s.commands[name] + return algo, ok } func newKey(t *testing.T) (ed25519.PrivateKey, ssh.Signer) { @@ -94,13 +117,13 @@ func startSFTPServer(t *testing.T, hostKeys ...ssh.Signer) *sftpTestServer { if err != nil { return } - go serveSSH(c, cfg, srv.hung) + go serveSSH(c, cfg, srv) } }() return srv } -func serveSSH(c net.Conn, cfg *ssh.ServerConfig, hung chan struct{}) { +func serveSSH(c net.Conn, cfg *ssh.ServerConfig, srv *sftpTestServer) { defer func() { _ = c.Close() }() _, chans, reqs, err := ssh.NewServerConn(c, cfg) if err != nil { @@ -118,16 +141,53 @@ func serveSSH(c net.Conn, cfg *ssh.ServerConfig, hung chan struct{}) { } go func() { for r := range chReqs { - ok := r.Type == "subsystem" && len(r.Payload) > 4 && string(r.Payload[4:]) == "sftp" - _ = r.Reply(ok, nil) - if ok { - go serveSFTP(ch, hung) + switch { + case r.Type == "subsystem" && len(r.Payload) > 4 && string(r.Payload[4:]) == "sftp": + _ = r.Reply(true, nil) + go serveSFTP(ch, srv.hung) + case r.Type == "exec" && len(r.Payload) > 4: + _ = r.Reply(true, nil) + go srv.serveExec(ch, string(r.Payload[4:])) + default: + _ = r.Reply(false, nil) } } }() } } +// serveExec runs a sum command the way coreutils does — over the named +// file, or over stdin when none is named — and exits 127 for a command the +// server does not have. +func (s *sftpTestServer) serveExec(ch ssh.Channel, cmd string) { + defer func() { _ = ch.Close() }() + status := uint32(0) + defer func() { _, _ = ch.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{status})) }() + fields := strings.Fields(cmd) + algo, ok := s.hashCommand(fields[0]) + if !ok || len(fields) > 2 { + status = 127 + return + } + var in io.Reader = ch + name := "-" + if len(fields) == 2 { + f, err := os.Open(fields[1]) + if err != nil { + status = 1 + return + } + defer f.Close() + in, name = f, fields[1] + } + h := newArtifactHash(algo) + if _, err := io.Copy(h, in); err != nil { + status = 1 + return + } + _, _ = fmt.Fprintf(ch, "%x %s\n", h.Sum(nil), name) +} + func serveSFTP(ch ssh.Channel, hung chan struct{}) { defer func() { _ = ch.Close() }() s, err := sftp.NewServer(hangingChannel{Channel: ch, hung: hung}) diff --git a/sync/transport_stall.go b/sync/transport_stall.go index fd22d6c..c664a31 100644 --- a/sync/transport_stall.go +++ b/sync/transport_stall.go @@ -125,6 +125,19 @@ func (s stallTransport) Remove(ctx context.Context, name string) error { return err } +// ServerHash allows the server the time its bytes take to read at the +// slowest rate squirrel expects, beyond the usual allowance. +func (s stallTransport) ServerHash(ctx context.Context, name string) (remoteChecksum, error) { + e, err := s.Stat(ctx, name) + if err != nil { + return remoteChecksum{}, err + } + return bounded(ctx, s, "hash "+name, func(ctx context.Context, progress func(time.Duration)) (remoteChecksum, error) { + progress(s.timeout + time.Duration(e.size/stallBytesPerSecond)*time.Second) + return s.transport.ServerHash(ctx, name) + }) +} + // stallReader bounds each Read of a file Get opened. A Read runs into the // reader's own buffer, so one given up on can finish later without // touching the caller's; after that the reader only reports the stall. From 0084ca895e0e7e4dea7d1b5bcd76ff69bc38cb9d Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:03:26 +0200 Subject: [PATCH 31/61] sync: pull the native root's plumbing out of the mirror handler destinationRoot opens a native destination once per push, hands it out behind a name guard and bounded by progress, gates on the volume marker, and clears the staging finished runs left. The mirror handler embeds it; the content layouts will too. --- ...mirror_marker.go => destination_marker.go} | 22 +-- sync/destination_root.go | 139 ++++++++++++++++++ sync/handler.go | 2 +- sync/mirror.go | 44 +----- sync/mirror_reconcile.go | 77 ---------- 5 files changed, 154 insertions(+), 130 deletions(-) rename sync/{mirror_marker.go => destination_marker.go} (83%) create mode 100644 sync/destination_root.go diff --git a/sync/mirror_marker.go b/sync/destination_marker.go similarity index 83% rename from sync/mirror_marker.go rename to sync/destination_marker.go index 4ed6613..b599087 100644 --- a/sync/mirror_marker.go +++ b/sync/destination_marker.go @@ -17,23 +17,23 @@ import ( // maxMarkerBytes bounds how much of a destination's marker squirrel reads. const maxMarkerBytes = 64 << 10 -// ensureMarker is a native mirror's gate against a wrong or unmounted +// ensureMarker is a native destination's gate against a wrong or unmounted // root: the destination's /.squirrel-volume must name this volume. // A missing marker is written only under init, and a marker naming another // volume, or one that does not parse, is always refused and never // overwritten. A local root that does not exist yet is created under init, // so a first push can land on an empty disk. -func (h *mirrorHandler) ensureMarker(ctx context.Context, init bool) error { +func (h *destinationRoot) ensureMarker(ctx context.Context, init bool) error { if init && h.dest.Type == "local" { if err := os.MkdirAll(h.dest.Root, 0o755); err != nil { return fmt.Errorf("destination %q: create root %s: %w", h.dest.Name, h.dest.Root, err) } } - tr, err := h.guarded(ctx, nameGuard{volumeDir: h.vol.Name, bootstrap: init}) + tr, err := h.guarded(ctx, nameGuard{volumeDir: h.volumeDir, bootstrap: init}) if err != nil { return err } - name := path.Join(h.vol.Name, volmark.MarkerName) + name := path.Join(h.volumeDir, volmark.MarkerName) data, err := readSmallFile(ctx, tr, name, maxMarkerBytes) switch { case err == nil: @@ -46,14 +46,14 @@ func (h *mirrorHandler) ensureMarker(ctx context.Context, init bool) error { return h.writeMarker(ctx, tr, name) } -func (h *mirrorHandler) checkMarker(name string, data []byte) error { +func (h *destinationRoot) checkMarker(name string, data []byte) error { m, err := volmark.Parse(data) if err != nil { return fmt.Errorf("destination %q: %w at %s: %w", h.dest.Name, err, h.where(name), ErrRefused) } - if m.Volume != h.vol.Name { + if m.Volume != h.volumeDir { return fmt.Errorf("destination %q: %s at %s names volume %q, want %q (refusing to sync over a different volume's tree): %w", - h.dest.Name, volmark.MarkerName, h.where(name), m.Volume, h.vol.Name, ErrRefused) + h.dest.Name, volmark.MarkerName, h.where(name), m.Volume, h.volumeDir, ErrRefused) } return nil } @@ -61,8 +61,8 @@ func (h *mirrorHandler) checkMarker(name string, data []byte) error { // writeMarker stages the marker, then renames it onto name, so a write // that fails halfway never leaves a marker that does not parse. A copy an // earlier --init left staged is cleared first. -func (h *mirrorHandler) writeMarker(ctx context.Context, tr transport, name string) error { - m, err := selfMarker(ctx, h.store, h.vol.Name) +func (h *destinationRoot) writeMarker(ctx context.Context, tr transport, name string) error { + m, err := selfMarker(ctx, h.store, h.volumeDir) if err != nil { return fmt.Errorf("destination %q: %w", h.dest.Name, err) } @@ -70,7 +70,7 @@ func (h *mirrorHandler) writeMarker(ctx context.Context, tr transport, name stri if err != nil { return fmt.Errorf("destination %q: %w", h.dest.Name, err) } - staged := markerStagingName(h.vol.Name) + staged := markerStagingName(h.volumeDir) if err := tr.Remove(ctx, staged); err != nil && !errors.Is(err, fs.ErrNotExist) { return fmt.Errorf("destination %q: clear the staged marker %s: %w", h.dest.Name, h.where(staged), err) } @@ -85,7 +85,7 @@ func (h *mirrorHandler) writeMarker(ctx context.Context, tr transport, name stri // where names a destination-relative name for a message: the path on a // local disk, host:path on an sftp server. -func (h *mirrorHandler) where(name string) string { +func (h *destinationRoot) where(name string) string { full := path.Join(h.dest.Root, name) if h.dest.Type == "sftp" { return h.dest.Params["host"] + ":" + full diff --git a/sync/destination_root.go b/sync/destination_root.go new file mode 100644 index 0000000..778f50c --- /dev/null +++ b/sync/destination_root.go @@ -0,0 +1,139 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io/fs" + "path" + "strconv" + "strings" + "time" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" +) + +// destinationRoot is a native destination's root for one push: opened on +// first use, closed when the push returns, and handed to a layout only +// behind a name guard and bounded by progress. +type destinationRoot struct { + store *store.Store + dest *config.Destination + volumeDir string // the volume's directory under the root + // openTransport opens the destination root; tests wrap it to inject + // faults. + openTransport func(context.Context, *config.Destination) (transport, error) + // stallTimeout bounds every transport call by progress. + stallTimeout time.Duration + + raw transport // opened on first use, closed by close +} + +func newDestinationRoot(s *store.Store, dest *config.Destination, volumeDir string) *destinationRoot { + return &destinationRoot{store: s, dest: dest, volumeDir: volumeDir, openTransport: openDestinationTransport, stallTimeout: DefaultStallTimeout} +} + +// guarded is the destination root behind guard, bounded by progress. +func (h *destinationRoot) guarded(ctx context.Context, guard nameGuard) (transport, error) { + if h.raw == nil { + raw, err := h.openTransport(ctx, h.dest) + if err != nil { + return nil, err + } + h.raw = raw + } + return stallTransport{ + transport: guardedTransport{transport: h.raw, guard: guard}, + timeout: h.stallTimeout, + stalled: stalledCounter(h.dest.Name), + }, nil +} + +func (h *destinationRoot) close() { + if h.raw != nil { + _ = h.raw.Close() + h.raw = nil + } +} + +// runFinished reports whether runID has ended, so its staging may be +// removed. A run squirrel cannot look up is left alone. +func (h *destinationRoot) runFinished(runID int64) bool { + r, err := h.store.GetRun(context.Background(), runID) + return err == nil && r.Status != store.RunStatusRunning +} + +// clearFinishedStaging removes what finished runs left in staging: +// partial files from a crash, and a drifted source's staged copy. +// Anything in staging squirrel did not name is reported and left alone. +func (h *destinationRoot) clearFinishedStaging(ctx context.Context, rep *Report, tr transport) error { + dir := path.Join(h.volumeDir, StagingDirName) + runs, err := tr.List(ctx, dir) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("list %s: %w", dir, err) + } + for _, e := range runs { + if e.name == markerStagingBase { + continue + } + runID, ok := stagingRunID(e) + if !ok { + h.warnForeignStaging(rep, path.Join(dir, e.name)) + continue + } + if !h.runFinished(runID) { + continue + } + if err := h.clearStagingRun(ctx, rep, tr, path.Join(dir, e.name)); err != nil { + return err + } + } + return nil +} + +func (h *destinationRoot) clearStagingRun(ctx context.Context, rep *Report, tr transport, runDir string) error { + entries, err := tr.List(ctx, runDir) + if err != nil { + return fmt.Errorf("list %s: %w", runDir, err) + } + foreign := false + for _, e := range entries { + name := path.Join(runDir, e.name) + if e.kind != kindFile || !isStagingKey(e.name) { + foreign = true + h.warnForeignStaging(rep, name) + continue + } + if err := tr.Remove(ctx, name); err != nil { + return fmt.Errorf("remove finished staging %s: %w", name, err) + } + } + if foreign { + return nil + } + if err := tr.Remove(ctx, runDir); err != nil { + return fmt.Errorf("remove finished staging %s: %w", runDir, err) + } + return nil +} + +// stagingRunID reads the run id of a staging run directory, run-. +func stagingRunID(e entry) (int64, bool) { + idText, ok := strings.CutPrefix(e.name, "run-") + if !ok || e.kind != kindDir { + return 0, false + } + id, err := strconv.ParseInt(idText, 10, 64) + if err != nil || id <= 0 || strconv.FormatInt(id, 10) != idText { + return 0, false + } + return id, true +} + +func (h *destinationRoot) warnForeignStaging(rep *Report, name string) { + rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination %q: %s is in squirrel's staging but squirrel did not write it; it is left alone", h.dest.Name, name)) +} diff --git a/sync/handler.go b/sync/handler.go index f548572..eb8125d 100644 --- a/sync/handler.go +++ b/sync/handler.go @@ -135,7 +135,7 @@ func HandlerFor(s *store.Store, tools Tools, p Pair) (Handler, error) { } return &contentAddressedHandler{contentPusher{store: s, rcl: tools.Rclone, vol: p.Volume, dest: p.Destination}}, nil case p.Destination.NativeMirror(): - return &mirrorHandler{store: s, vol: p.Volume, dest: p.Destination, openTransport: openDestinationTransport, stallTimeout: DefaultStallTimeout}, nil + return &mirrorHandler{destinationRoot: newDestinationRoot(s, p.Destination, p.Volume.Name), vol: p.Volume}, nil default: if tools.Rclone == nil { return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) diff --git a/sync/mirror.go b/sync/mirror.go index ed966f0..aee6f9b 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -27,16 +27,8 @@ import ( // in remote_paths. Each run leaves a receipt, the same manifest segment the // content layouts write, at /.squirrel-index/run-. type mirrorHandler struct { - store *store.Store - vol *config.Volume - dest *config.Destination - // openTransport opens the destination root; tests wrap it to inject - // faults. - openTransport func(context.Context, *config.Destination) (transport, error) - // stallTimeout bounds every transport call by progress. - stallTimeout time.Duration - - raw transport // opened by root on first use, closed when Push returns + *destinationRoot + vol *config.Volume progress func(runevents.Progress) // this push's Options.Progress } @@ -54,7 +46,7 @@ func (h *mirrorHandler) Push(ctx context.Context, opts Options) (Report, error) return rep, fmt.Errorf("destination %q: %d transport call(s) an earlier push gave up on have not returned — the disk or server may be hung; wait, or restart squirrel once it is reachable again", h.dest.Name, n) } h.progress = opts.Progress - defer h.closeRoot() + defer h.close() return pushThrough(ctx, pushTarget{store: h.store, vol: h.vol, dest: h.dest}, h, opts) } @@ -64,36 +56,6 @@ func (h *mirrorHandler) root(ctx context.Context, runID int64) (transport, error return h.guarded(ctx, nameGuard{volumeDir: h.vol.Name, runID: runID, finished: h.runFinished}) } -// guarded is the destination root behind guard, bounded by progress. -func (h *mirrorHandler) guarded(ctx context.Context, guard nameGuard) (transport, error) { - if h.raw == nil { - raw, err := h.openTransport(ctx, h.dest) - if err != nil { - return nil, err - } - h.raw = raw - } - return stallTransport{ - transport: guardedTransport{transport: h.raw, guard: guard}, - timeout: h.stallTimeout, - stalled: stalledCounter(h.dest.Name), - }, nil -} - -func (h *mirrorHandler) closeRoot() { - if h.raw != nil { - _ = h.raw.Close() - h.raw = nil - } -} - -// runFinished reports whether runID has ended, so its staging may be -// removed. A run squirrel cannot look up is left alone. -func (h *mirrorHandler) runFinished(runID int64) bool { - r, err := h.store.GetRun(context.Background(), runID) - return err == nil && r.Status != store.RunStatusRunning -} - // markers gates the push on the per-volume .squirrel-volume marker, the // guard against pushing to an unmounted disk or a mistyped root. A refusal // is recorded as its own refused run, so a disk that stays unplugged shows diff --git a/sync/mirror_reconcile.go b/sync/mirror_reconcile.go index 410af46..f979754 100644 --- a/sync/mirror_reconcile.go +++ b/sync/mirror_reconcile.go @@ -5,9 +5,6 @@ import ( "errors" "fmt" "io/fs" - "path" - "strconv" - "strings" "github.com/mbertschler/squirrel/store" ) @@ -125,77 +122,3 @@ func present(ctx context.Context, tr transport, name string) (bool, error) { } return err == nil, err } - -// clearFinishedStaging removes what finished runs left in staging: -// partial files from a crash, and a drifted source's staged copy. -// Anything in staging squirrel did not name is reported and left alone. -func (h *mirrorHandler) clearFinishedStaging(ctx context.Context, rep *Report, tr transport) error { - dir := path.Join(h.vol.Name, StagingDirName) - runs, err := tr.List(ctx, dir) - if errors.Is(err, fs.ErrNotExist) { - return nil - } - if err != nil { - return fmt.Errorf("list %s: %w", dir, err) - } - for _, e := range runs { - if e.name == markerStagingBase { - continue - } - runID, ok := stagingRunID(e) - if !ok { - h.warnForeignStaging(rep, path.Join(dir, e.name)) - continue - } - if !h.runFinished(runID) { - continue - } - if err := h.clearStagingRun(ctx, rep, tr, path.Join(dir, e.name)); err != nil { - return err - } - } - return nil -} - -func (h *mirrorHandler) clearStagingRun(ctx context.Context, rep *Report, tr transport, runDir string) error { - entries, err := tr.List(ctx, runDir) - if err != nil { - return fmt.Errorf("list %s: %w", runDir, err) - } - foreign := false - for _, e := range entries { - name := path.Join(runDir, e.name) - if e.kind != kindFile || !isStagingKey(e.name) { - foreign = true - h.warnForeignStaging(rep, name) - continue - } - if err := tr.Remove(ctx, name); err != nil { - return fmt.Errorf("remove finished staging %s: %w", name, err) - } - } - if foreign { - return nil - } - if err := tr.Remove(ctx, runDir); err != nil { - return fmt.Errorf("remove finished staging %s: %w", runDir, err) - } - return nil -} - -// stagingRunID reads the run id of a staging run directory, run-. -func stagingRunID(e entry) (int64, bool) { - idText, ok := strings.CutPrefix(e.name, "run-") - if !ok || e.kind != kindDir { - return 0, false - } - id, err := strconv.ParseInt(idText, 10, 64) - if err != nil || id <= 0 || strconv.FormatInt(id, 10) != idText { - return 0, false - } - return id, true -} - -func (h *mirrorHandler) warnForeignStaging(rep *Report, name string) { - rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination %q: %s is in squirrel's staging but squirrel did not write it; it is left alone", h.dest.Name, name)) -} From f4528299b4d66c56a83775ae0b51076e28bcf3a4 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:08:08 +0200 Subject: [PATCH 32/61] sync: land the content layouts' artifacts through an artifact store contentPusher no longer holds rclone: it lands objects, packs, maps and segments through artifactStore, whose one implementation so far is rclone (re-hash, copyto, stat, scan-back capture, and the marker and naming gates). put returns the fingerprint a landing already confirmed, so the native store to come can record it on the spot; rclone's stays pending for capture as before. No behaviour change. --- sync/artifacts.go | 64 ++++++++++++ sync/artifacts_rclone.go | 110 ++++++++++++++++++++ sync/content_addressed.go | 177 ++++++++++++--------------------- sync/content_addressed_test.go | 2 +- sync/handler.go | 10 +- sync/naming.go | 12 +-- sync/packed.go | 149 +++++++++++++-------------- sync/scanback.go | 8 +- 8 files changed, 327 insertions(+), 205 deletions(-) create mode 100644 sync/artifacts.go create mode 100644 sync/artifacts_rclone.go diff --git a/sync/artifacts.go b/sync/artifacts.go new file mode 100644 index 0000000..d9f1740 --- /dev/null +++ b/sync/artifacts.go @@ -0,0 +1,64 @@ +package sync + +import ( + "context" + "fmt" + "os" + + "github.com/zeebo/blake3" +) + +// artifactStore is where a content-addressed or packed push lands its +// artifacts: an rclone remote, or a native destination root reached +// through squirrel's own transport. Names are slash-separated and relative +// to the destination root, as namer and the layout constants build them. +type artifactStore interface { + // markers gates the push on the destination's markers, writing missing + // ones under opts.Init; a dry run only checks. + markers(ctx context.Context, opts Options) error + // exists reports whether the artifact at name is present. + exists(ctx context.Context, name string) (bool, error) + // rootEmpty reports whether the root holds nothing beyond squirrel's + // markers. + rootEmpty(ctx context.Context) (bool, error) + // reconcile clears what finished pushes left in flight, once at push + // start. + reconcile(ctx context.Context, rep *Report, runID int64) error + // put lands the local file src at name whole, and confirms it landed: + // its size, and bytes whose BLAKE3 is sum — errContentDrift when src + // no longer hashes to sum. It returns the fingerprint the landing + // already confirmed, or nil when capture must read one later. + put(ctx context.Context, runID int64, name, src string, size int64, sum []byte) (*remoteChecksum, error) + // capture fills the fingerprints put left pending for this run's + // artifacts under dir (ObjectsDirName or PacksDirName). + capture(ctx context.Context, rep *Report, dir string, targets []captureTarget) + // shelf is the volume's .squirrel-index/ directory, where runID's + // ride-along index snapshot lands. + shelf(runID int64) snapshotShelf + // where names an artifact for a message. + where(name string) string + // close releases the destination once the push returns. + close() +} + +// putBytes lands body at name through art, staged in a temporary file. +// what names the artifact in error messages. +func putBytes(ctx context.Context, art artifactStore, runID int64, name string, body []byte, what string) error { + tmp, err := os.CreateTemp("", "squirrel-meta-*") + if err != nil { + return fmt.Errorf("stage %s: %w", what, err) + } + defer func() { _ = os.Remove(tmp.Name()) }() + if _, err := tmp.Write(body); err != nil { + _ = tmp.Close() + return fmt.Errorf("write %s: %w", what, err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("close %s: %w", what, err) + } + sum := blake3.Sum256(body) + if _, err := art.put(ctx, runID, name, tmp.Name(), int64(len(body)), sum[:]); err != nil { + return fmt.Errorf("upload %s to %s: %w", what, art.where(name), err) + } + return nil +} diff --git a/sync/artifacts_rclone.go b/sync/artifacts_rclone.go new file mode 100644 index 0000000..627556e --- /dev/null +++ b/sync/artifacts_rclone.go @@ -0,0 +1,110 @@ +package sync + +import ( + "bytes" + "context" + "encoding/hex" + "fmt" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" +) + +// rcloneArtifacts is an artifact store rclone reaches, through the crypt +// overlay when the destination has one. +type rcloneArtifacts struct { + store *store.Store + rcl *Rclone + vol *config.Volume + dest *config.Destination +} + +// names is how the destination names its artifacts. +func (a *rcloneArtifacts) names() namer { return namerFor(a.dest) } + +// markers gates a remote push on the root's naming scheme, then on the +// destination's per-volume .squirrel-volume marker, exactly as the mirror +// layout does (the marker sits at the volume root regardless of layout). A +// dry run checks the naming scheme read-only and writes nothing. Local +// content-addressed and packed destinations are left ungated here: they +// carry no such gate today, so extending it to them is a separate parity +// concern — this closes only the remote gap (#150). +func (a *rcloneArtifacts) markers(ctx context.Context, opts Options) error { + if opts.DryRun { + _, err := a.checkNamingScheme(ctx) + return err + } + if a.dest.Type == "local" { + return nil + } + if err := a.ensureNamingScheme(ctx, opts.Init); err != nil { + return err + } + return ensureRemoteDestinationMarker(ctx, a.store, a.rcl, a.dest, a.vol.Name, opts.Init) +} + +func (a *rcloneArtifacts) exists(ctx context.Context, name string) (bool, error) { + return a.rcl.statRemoteExists(ctx, a.where(name), checkersArgs(a.dest)...) +} + +// rootEmpty reports whether the destination root holds no files beyond +// squirrel's markers — a wiped or repointed destination, or one whose +// recorded state was cleared by `squirrel destination reset`. +func (a *rcloneArtifacts) rootEmpty(ctx context.Context) (bool, error) { + return a.rcl.remoteRootEmpty(ctx, remoteSubpathURI(a.dest, ""), rootMarkerNames(a.dest), checkersArgs(a.dest)...) +} + +// reconcile has nothing to settle: rclone lands every artifact under its +// own name, and squirrel records it only after it landed. +func (a *rcloneArtifacts) reconcile(context.Context, *Report, int64) error { return nil } + +// put re-hashes src immediately before the transfer and refuses +// (errContentDrift) when the digest no longer matches sum, catching a +// size+mtime-preserving in-place edit that a metadata stat would pass. The +// post-transfer stat confirms presence and size; the fingerprint is read +// back afterwards (capture). +// +// Residual: rclone reads the file in a separate child process after the +// re-hash, so a writer that edits the file in the window between the hash +// and rclone's read could still upload drifted bytes. The window is the +// fork/exec of one rclone invocation rather than the whole walk-to-push +// span, and the scan-back fingerprint pass (#109) re-reads the landed +// object to upgrade the durability vector, catching any byte that slipped +// through before the object is treated as content-verified. +func (a *rcloneArtifacts) put(ctx context.Context, _ int64, name, src string, size int64, sum []byte) (*remoteChecksum, error) { + digest, err := hashLocalFile(src) + if err != nil { + return nil, fmt.Errorf("re-hash %s before upload: %w", src, err) + } + if !bytes.Equal(digest, sum) { + return nil, fmt.Errorf("%w: %s now hashes to %s, indexed as %s", errContentDrift, src, hex.EncodeToString(digest), hex.EncodeToString(sum)) + } + uri := a.where(name) + if err := a.rcl.copyTo(ctx, src, uri, checkersArgs(a.dest)...); err != nil { + return nil, err + } + landed, err := a.rcl.statRemote(ctx, uri, checkersArgs(a.dest)...) + if err != nil { + return nil, fmt.Errorf("confirm %s after upload: %w", uri, err) + } + if landed != size { + return nil, fmt.Errorf("%s landed with size %d, want %d", uri, landed, size) + } + return nil, nil +} + +func (a *rcloneArtifacts) capture(ctx context.Context, rep *Report, dir string, targets []captureTarget) { + a.captureScanBackFingerprints(ctx, rep, dir, targets) +} + +// shelf is the destination's .squirrel-index/ directory, reached through +// rclone like the rest of the push. +func (a *rcloneArtifacts) shelf(int64) snapshotShelf { + return rcloneShelf{rcl: a.rcl, dir: indexDirURI(a.dest, a.vol.Name)} +} + +// where is the artifact's rclone URI, through the crypt overlay when the +// destination has one. +func (a *rcloneArtifacts) where(name string) string { return remoteSubpathURI(a.dest, name) } + +func (a *rcloneArtifacts) close() {} diff --git a/sync/content_addressed.go b/sync/content_addressed.go index f71f6e8..f58cc03 100644 --- a/sync/content_addressed.go +++ b/sync/content_addressed.go @@ -1,8 +1,8 @@ package sync import ( - "bytes" "context" + "database/sql" "encoding/hex" "encoding/json" "errors" @@ -97,60 +97,28 @@ func encodeManifestSegment(delta []store.PathDelta) ([]byte, error) { // per-run manifest segment under /index/run-, and fingerprint // freshly landed objects the same way. The content-addressed layout uses // this base directly; the packed layout embeds it and adds pack assembly -// for content below its threshold. +// for content below its threshold. art is where the artifacts land. type contentPusher struct { store *store.Store - rcl *Rclone vol *config.Volume dest *config.Destination + art artifactStore } // names is how this push names the artifacts it writes. func (h *contentPusher) names() namer { return namerFor(h.dest) } -// ensureMarkers gates a remote content-layout push on the root's naming -// scheme, then on the destination's per-volume .squirrel-volume marker, -// exactly as the mirror layout does (the marker sits at the volume root -// regardless of layout). Local content-addressed and packed destinations -// are intentionally left ungated here: they carry no such gate today, so -// extending it to them is a separate parity concern — this closes only the -// remote gap (#150). -func (h *contentPusher) ensureMarkers(ctx context.Context, init bool) error { - if h.dest.Type == "local" { - return nil - } - if err := h.ensureNamingScheme(ctx, init); err != nil { - return err - } - return ensureRemoteDestinationMarker(ctx, h.store, h.rcl, h.dest, h.vol.Name, init) -} - -// shelf is the destination's .squirrel-index/ directory, reached through -// rclone like the rest of the push. -func (h *contentPusher) shelf(int64) snapshotShelf { - return rcloneShelf{rcl: h.rcl, dir: indexDirURI(h.dest, h.vol.Name)} -} +func (h *contentPusher) shelf(runID int64) snapshotShelf { return h.art.shelf(runID) } -// markers is the content layouts' marker gate. A dry run checks the naming -// scheme read-only and writes nothing. func (h *contentPusher) markers(ctx context.Context, _ *Report, _ int64, opts Options) error { - if opts.DryRun { - _, err := h.checkNamingScheme(ctx) - return err - } - return h.ensureMarkers(ctx, opts.Init) + return h.art.markers(ctx, opts) } -// rootEmpty reports whether the destination root holds no files beyond -// squirrel's markers — a wiped or repointed destination, or one whose -// recorded state was cleared by `squirrel destination reset`. -func (h *contentPusher) rootEmpty(ctx context.Context) (bool, error) { - return h.rcl.remoteRootEmpty(ctx, remoteSubpathURI(h.dest, ""), rootMarkerNames(h.dest), checkersArgs(h.dest)...) -} +func (h *contentPusher) rootEmpty(ctx context.Context) (bool, error) { return h.art.rootEmpty(ctx) } -// reconcile has nothing to settle: every content-layout artifact is -// written once under its own name and recorded only after it landed. -func (h *contentPusher) reconcile(context.Context, *Report, int64, int64) error { return nil } +func (h *contentPusher) reconcile(ctx context.Context, rep *Report, _, runID int64) error { + return h.art.reconcile(ctx, rep, runID) +} func (h *contentPusher) target() pushTarget { return pushTarget{store: h.store, vol: h.vol, dest: h.dest} @@ -172,6 +140,7 @@ type contentAddressedHandler struct { func (h *contentAddressedHandler) TargetName() string { return h.dest.Name } func (h *contentAddressedHandler) Push(ctx context.Context, opts Options) (Report, error) { + defer h.art.close() if h.vol.Name == ObjectsDirName { rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} rep.Verification.Method = VerifyMethodPresenceSize @@ -223,11 +192,11 @@ func (h *contentAddressedHandler) advanceMethod(ctx context.Context, _ *Report, // Every successful content-addressed run uploads one, so its absence means // the recorded history belongs to a different layout or a wiped root. func (h *contentAddressedHandler) landed(ctx context.Context, runID int64) (bool, error) { - return h.rcl.statRemoteExists(ctx, h.segmentURI(runID), checkersArgs(h.dest)...) + return h.art.exists(ctx, h.segmentName(runID)) } func (h *contentAddressedHandler) foreignHistory(runID int64) error { - return fmt.Errorf("destination %q: the last successful sync (run %d) left no manifest segment at %s — its history does not look content-addressed; point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w", h.dest.Name, runID, h.segmentURI(runID), h.dest.Name, ErrRefused) + return fmt.Errorf("destination %q: the last successful sync (run %d) left no manifest segment at %s — its history does not look content-addressed; point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w", h.dest.Name, runID, h.art.where(h.segmentName(runID)), h.dest.Name, ErrRefused) } // objectUploads is the object side of a content push: the planned content @@ -287,10 +256,11 @@ func (h *contentPusher) splitRecorded(ctx context.Context, planned []store.PathD // the drifted bytes ever being recorded under the hash. func (h *contentPusher) uploadObjects(ctx context.Context, rep *Report, runID int64, ops objectUploads) error { rep.RcloneResult.Checked += ops.recorded - var confirmed []store.PathDelta + var pending []store.PathDelta var drifted int for _, d := range ops.needed { - if err := h.uploadOneObject(ctx, runID, d); err != nil { + fingerprinted, err := h.uploadOneObject(ctx, runID, d) + if err != nil { if errors.Is(err, errContentDrift) { drifted++ rep.Warnings = append(rep.Warnings, err.Error()) @@ -303,11 +273,15 @@ func (h *contentPusher) uploadObjects(ctx context.Context, rep *Report, runID in } continue } - confirmed = append(confirmed, d) + if fingerprinted { + rep.Fingerprints++ + } else { + pending = append(pending, d) + } rep.RcloneResult.Transferred++ rep.RcloneResult.Bytes += d.SizeBytes } - h.captureFingerprints(ctx, rep, confirmed) + h.captureFingerprints(ctx, rep, pending) if rep.RcloneResult.Errors > 0 { return fmt.Errorf("%d object(s) failed to land on %q; the manifest segment for run %d was not written and the durability vector did not advance", rep.RcloneResult.Errors, h.dest.Name, runID) } @@ -318,15 +292,17 @@ func (h *contentPusher) uploadObjects(ctx context.Context, rep *Report, runID in } // captureFingerprints fills the pending checksum pair of every object -// confirmed during this run with the provider checksum read back from the -// underlying remote's objects/ directory, over the shared scan-back capture -// surface. That read-back is the first verification, so each object records -// and stamps verified_at_ns in one write (SetRemoteObjectFingerprint) — -// matching the packed layout; the later `squirrel verify` re-read re-stamps -// it on each re-confirmation. -func (h *contentPusher) captureFingerprints(ctx context.Context, rep *Report, confirmed []store.PathDelta) { - targets := make([]captureTarget, 0, len(confirmed)) - for _, d := range confirmed { +// confirmed during this run without one, read back from the destination's +// objects/ directory (the scan-back capture over rclone). That read-back is +// the first verification, so each object records and stamps verified_at_ns +// in one write (SetRemoteObjectFingerprint) — matching the packed layout; +// the later `squirrel verify` re-read re-stamps it on each re-confirmation. +func (h *contentPusher) captureFingerprints(ctx context.Context, rep *Report, pending []store.PathDelta) { + if len(pending) == 0 { + return + } + targets := make([]captureTarget, 0, len(pending)) + for _, d := range pending { d := d targets = append(targets, captureTarget{ name: h.names().object(d.Blake3), @@ -336,7 +312,7 @@ func (h *contentPusher) captureFingerprints(ctx context.Context, rep *Report, co }, }) } - h.captureScanBackFingerprints(ctx, rep, ObjectsDirName, targets) + h.art.capture(ctx, rep, ObjectsDirName, targets) } // plannedUploads selects the delta rows that need a content object — @@ -362,54 +338,34 @@ func plannedUploads(delta []store.PathDelta) []store.PathDelta { // the run so the watermark holds and the object is re-offered next run. var errContentDrift = errors.New("source content drifted from its indexed hash") -// uploadOneObject lands one content object and records the upload. It -// guards the content-addressed invariant — the bytes stored under a hash -// must be the bytes that produced it — by re-hashing the source file -// immediately before the transfer and refusing (errContentDrift) when the -// digest no longer matches the indexed hash, catching a -// size+mtime-preserving in-place edit that a metadata stat would pass. -// The post-transfer stat confirms presence and size on the remote, and the -// upload record is written only after that confirmation, so a recorded -// hash is always a confirmed one; a crash in between re-uploads the same -// bytes idempotently on the next run. -// -// Residual: rclone reads the file in a separate child process after the -// re-hash, so a writer that edits the file in the window between the hash -// and rclone's read could still upload drifted bytes. The window is the -// fork/exec of one rclone invocation rather than the whole walk-to-push -// span, and the scan-back fingerprint pass (#109) re-reads the landed -// object to upgrade the durability vector, catching any byte that slipped -// through before the object is treated as content-verified. -func (h *contentPusher) uploadOneObject(ctx context.Context, runID int64, d store.PathDelta) error { +// uploadOneObject lands one content object and records the upload, with +// its fingerprint when the landing already confirmed one. It guards the +// content-addressed invariant — the bytes stored under a hash must be the +// bytes that produced it: the artifact store refuses a source that no +// longer hashes to the indexed hash (errContentDrift), catching a +// size+mtime-preserving in-place edit that a metadata stat would pass. The +// upload record is written only after the landing was confirmed, so a +// recorded hash is always a confirmed one; a crash in between lands the +// same bytes again on the next run. +func (h *contentPusher) uploadOneObject(ctx context.Context, runID int64, d store.PathDelta) (bool, error) { src := filepath.Join(h.vol.Path, filepath.FromSlash(d.Path)) - digest, err := hashLocalFile(src) - if err != nil { - return fmt.Errorf("re-hash %s before upload: %w", src, err) + cs, err := h.art.put(ctx, runID, h.objectName(d.Blake3), src, d.SizeBytes, d.Blake3) + if errors.Is(err, errContentDrift) { + return false, fmt.Errorf("%s: %w — run `squirrel index %s` and sync again", d.Path, err, h.vol.Name) } - if !bytes.Equal(digest, d.Blake3) { - return fmt.Errorf("%w: %s now hashes to %s, indexed as %s — run `squirrel index %s` and sync again", - errContentDrift, d.Path, hex.EncodeToString(digest), hex.EncodeToString(d.Blake3), h.vol.Name) - } - hash := hex.EncodeToString(d.Blake3) - uri := h.objectURI(d.Blake3) - if err := h.rcl.copyTo(ctx, src, uri, checkersArgs(h.dest)...); err != nil { - return err - } - size, err := h.rcl.statRemote(ctx, uri, checkersArgs(h.dest)...) if err != nil { - return fmt.Errorf("confirm object %s after upload: %w", hash, err) + return false, err } - if size != d.SizeBytes { - return fmt.Errorf("object %s landed with size %d, want %d", hash, size, d.SizeBytes) + obj := store.RemoteObject{ContentID: d.ContentID, Destination: h.dest.Name, UploadedRunID: runID} + if cs != nil { + obj.ChecksumAlgo = sql.NullString{String: cs.Algo, Valid: true} + obj.Checksum = sql.NullString{String: cs.Value, Valid: true} + obj.VerifiedAtNs = sql.NullInt64{Int64: store.NowNs(), Valid: true} } - if err := h.store.InsertRemoteObject(ctx, store.RemoteObject{ - ContentID: d.ContentID, - Destination: h.dest.Name, - UploadedRunID: runID, - }); err != nil { - return fmt.Errorf("record upload of %s: %w", hash, err) + if err := h.store.InsertRemoteObject(ctx, obj); err != nil { + return false, fmt.Errorf("record upload of %s: %w", hex.EncodeToString(d.Blake3), err) } - return nil + return cs != nil, nil } // hashLocalFile streams the file at path through BLAKE3 and returns the @@ -436,20 +392,19 @@ func (h *contentPusher) uploadSegment(ctx context.Context, delta []store.PathDel if err != nil { return err } - return h.uploadBytes(ctx, body, h.segmentURI(runID), "manifest segment") + return putBytes(ctx, h.art, runID, h.segmentName(runID), body, "manifest segment") } -// objectURI addresses one content object under the destination-root -// objects/ directory, through the crypt overlay when the destination -// has one. The basename is namer.object's. -func (h *contentPusher) objectURI(contentHash []byte) string { - return remoteSubpathURI(h.dest, path.Join(ObjectsDirName, h.names().object(contentHash))) +// objectName is one content object under the destination-root objects/ +// directory. The basename is namer.object's. +func (h *contentPusher) objectName(contentHash []byte) string { + return path.Join(ObjectsDirName, h.names().object(contentHash)) } -// segmentURI addresses one run's manifest segment under the -// destination's per-volume index/ directory. The run id stays in clear: -// replaying the segments in run order is what recovers a volume without -// squirrel, and that ordering has to survive without the naming key. -func (h *contentPusher) segmentURI(runID int64) string { - return remoteSubpathURI(h.dest, path.Join(h.names().volumeDir(h.vol.Name), ManifestDirName, "run-"+strconv.FormatInt(runID, 10))) +// segmentName is one run's manifest segment under the destination's +// per-volume index/ directory. The run id stays in clear: replaying the +// segments in run order is what recovers a volume without squirrel, and +// that ordering has to survive without the naming key. +func (h *contentPusher) segmentName(runID int64) string { + return path.Join(h.names().volumeDir(h.vol.Name), ManifestDirName, "run-"+strconv.FormatInt(runID, 10)) } diff --git a/sync/content_addressed_test.go b/sync/content_addressed_test.go index e8a107f..f3822f9 100644 --- a/sync/content_addressed_test.go +++ b/sync/content_addressed_test.go @@ -340,7 +340,7 @@ func (f *caFixture) seedMarker(t *testing.T, volumes ...string) { // push established. func (f *caFixture) seedNamingMarker(t *testing.T) { t.Helper() - h := &contentPusher{store: f.store, rcl: f.rcl, dest: f.cfg.Destinations["offsite"]} + h := &rcloneArtifacts{store: f.store, rcl: f.rcl, dest: f.cfg.Destinations["offsite"]} if err := h.writeNamingMarker(context.Background()); err != nil { t.Fatalf("seed %s: %v", namingMarkerName, err) } diff --git a/sync/handler.go b/sync/handler.go index eb8125d..0c5f065 100644 --- a/sync/handler.go +++ b/sync/handler.go @@ -128,12 +128,12 @@ func HandlerFor(s *store.Store, tools Tools, p Pair) (Handler, error) { if tools.Rclone == nil { return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) } - return &packedHandler{contentPusher{store: s, rcl: tools.Rclone, vol: p.Volume, dest: p.Destination}}, nil + return &packedHandler{rcloneContentPusher(s, tools.Rclone, p)}, nil case p.Destination.Layout == config.LayoutContentAddressed: if tools.Rclone == nil { return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) } - return &contentAddressedHandler{contentPusher{store: s, rcl: tools.Rclone, vol: p.Volume, dest: p.Destination}}, nil + return &contentAddressedHandler{rcloneContentPusher(s, tools.Rclone, p)}, nil case p.Destination.NativeMirror(): return &mirrorHandler{destinationRoot: newDestinationRoot(s, p.Destination, p.Volume.Name), vol: p.Volume}, nil default: @@ -144,6 +144,12 @@ func HandlerFor(s *store.Store, tools Tools, p Pair) (Handler, error) { } } +// rcloneContentPusher is a content layout's push through rclone. +func rcloneContentPusher(s *store.Store, rcl *Rclone, p Pair) contentPusher { + art := &rcloneArtifacts{store: s, rcl: rcl, vol: p.Volume, dest: p.Destination} + return contentPusher{store: s, vol: p.Volume, dest: p.Destination, art: art} +} + // openDestinationTransport opens a native mirror's destination root: a // directory on this machine, or on an sftp server. func openDestinationTransport(ctx context.Context, dest *config.Destination) (transport, error) { diff --git a/sync/naming.go b/sync/naming.go index 5a57988..5dbb544 100644 --- a/sync/naming.go +++ b/sync/naming.go @@ -123,7 +123,7 @@ const ( // always on a root proven to be keyed under this destination's key. A // fresh root without init is left untouched for the volume-marker gate to // refuse. -func (h *contentPusher) ensureNamingScheme(ctx context.Context, init bool) error { +func (h *rcloneArtifacts) ensureNamingScheme(ctx context.Context, init bool) error { stamp, err := h.checkNamingScheme(ctx) if err != nil { return err @@ -137,7 +137,7 @@ func (h *contentPusher) ensureNamingScheme(ctx context.Context, init bool) error // checkNamingScheme refuses a push to a root whose artifacts are named under // any other scheme, and reports what the root still needs stamped. // Read-only, so a dry run asks it too. -func (h *contentPusher) checkNamingScheme(ctx context.Context) (namingStamp, error) { +func (h *rcloneArtifacts) checkNamingScheme(ctx context.Context) (namingStamp, error) { if !h.dest.HidesArtifactNames() { return stampNone, nil } @@ -158,7 +158,7 @@ func (h *contentPusher) checkNamingScheme(ctx context.Context) (namingStamp, err // keyed directory was named some other way — or under other crypt // passwords — and adding keyed names beside it would leave it disclosing // what it always did. -func (h *contentPusher) classifyUnmarkedRoot(ctx context.Context) (namingStamp, error) { +func (h *rcloneArtifacts) classifyUnmarkedRoot(ctx context.Context) (namingStamp, error) { rootURI := underlyingDirURI(h.dest, "") empty, err := h.rcl.remoteRootEmpty(ctx, rootURI, nil, checkersArgs(h.dest)...) if err != nil { @@ -178,7 +178,7 @@ func (h *contentPusher) classifyUnmarkedRoot(ctx context.Context) (namingStamp, h.dest.Name, rootURI, namingMarkerName, h.vol.Name, h.dest.Name, ErrRefused) } -func (h *contentPusher) holdsKeyedVolumeMarker(ctx context.Context) (bool, error) { +func (h *rcloneArtifacts) holdsKeyedVolumeMarker(ctx context.Context) (bool, error) { uri := remoteSubpathURI(h.dest, path.Join(h.names().volumeDir(h.vol.Name), volmark.MarkerName)) present, err := h.rcl.statRemoteExists(ctx, uri, checkersArgs(h.dest)...) if err != nil { @@ -206,7 +206,7 @@ func validateNamingScheme(ctx context.Context, rcl *Rclone, dest *config.Destina } // writeNamingMarker stamps the scheme on a fresh destination root. -func (h *contentPusher) writeNamingMarker(ctx context.Context) error { +func (h *rcloneArtifacts) writeNamingMarker(ctx context.Context) error { body, err := json.Marshal(namingMarker{ Naming: namingSchemeKeyed, CreatedAt: time.Now().UTC().Format(time.RFC3339), @@ -214,5 +214,5 @@ func (h *contentPusher) writeNamingMarker(ctx context.Context) error { if err != nil { return fmt.Errorf("encode %s: %w", namingMarkerName, err) } - return h.uploadBytes(ctx, body, remoteSubpathURI(h.dest, namingMarkerName), namingMarkerName) + return putBytes(ctx, h, 0, namingMarkerName, body, namingMarkerName) } diff --git a/sync/packed.go b/sync/packed.go index 8f56d58..845f323 100644 --- a/sync/packed.go +++ b/sync/packed.go @@ -122,6 +122,7 @@ func (h *packedHandler) TargetName() string { return h.dest.Name } func (h *packedHandler) sealed() {} func (h *packedHandler) Push(ctx context.Context, opts Options) (Report, error) { + defer h.art.close() if h.vol.Name == ObjectsDirName || h.vol.Name == PacksDirName { rep := Report{Volume: h.vol.Name, Destination: h.dest.Name} rep.Verification.Method = VerifyMethodPresenceSize @@ -133,7 +134,7 @@ func (h *packedHandler) Push(ctx context.Context, opts Options) (Report, error) // packedOps is the packed translation of a plan: the large content routed // to per-hash objects, the small content still to be packed (hash-sorted, // so assembly is deterministic), and how much small content an earlier -// pack already holds. execute fills in the packs it assembled, which seal +// pack already holds. execute fills in the packs it landed, which seal // records. type packedOps struct { objects objectUploads @@ -141,10 +142,17 @@ type packedOps struct { alreadyInPack int64 packSize int64 - writes []store.PackWrite + packs []landedPack placements []PlacementEntry } +// landedPack is one pack execute landed: the rows to record, and the +// fingerprint the landing confirmed, nil while capture must read one. +type landedPack struct { + write store.PackWrite + fingerprint *remoteChecksum +} + // preview reports the object side on rep.RcloneResult, exactly as the // content-addressed preview does, and the pack side on rep.PackPreview. func (o *packedOps) preview(rep *Report) { @@ -198,11 +206,11 @@ func (h *packedHandler) execute(ctx context.Context, rep *Report, runID int64, o if err := h.uploadObjects(ctx, rep, runID, ops.objects); err != nil { return err } - writes, placements, err := h.assembleAndUploadPacks(ctx, rep, runID, ops.members) + packs, placements, err := h.assembleAndUploadPacks(ctx, rep, runID, ops.members) if err != nil { return err } - ops.writes, ops.placements = writes, placements + ops.packs, ops.placements = packs, placements return nil } @@ -217,10 +225,14 @@ func (h *packedHandler) seal(ctx context.Context, rep *Report, runID int64, p pu if err := h.uploadSegment(ctx, p.delta, runID); err != nil { return err } - if err := h.store.InsertPacks(ctx, ops.writes); err != nil { + writes := make([]store.PackWrite, len(ops.packs)) + for i, lp := range ops.packs { + writes[i] = lp.write + } + if err := h.store.InsertPacks(ctx, writes); err != nil { return fmt.Errorf("record packs for run %d: %w", runID, err) } - h.capturePackFingerprints(ctx, rep, runID, ops.writes) + h.capturePackFingerprints(ctx, rep, runID, ops.packs) return nil } @@ -258,17 +270,19 @@ func (h *packedHandler) advanceMethod(ctx context.Context, rep *Report, p pushPl } // capturePackFingerprints records a per-destination upload row for each -// landed pack and fills its scan-back fingerprint, reusing the shared -// capture surface over the packs/ directory. Every pack exceeds the -// multipart threshold, so on s3 the composite ETag is read from the S3 API -// (never rclone's md5 slot, which is blank for a multipart object); other -// backends read `rclone lsjson --hash`. A pack whose fingerprint could not -// be read stays pending (checksum NULL) with a warning — never a fabricated -// value. The whole-pair pending tally (CountVolumeContentsPendingFingerprint) -// is what advanceMethod gates the vector advance on, so this returns nothing. -func (h *packedHandler) capturePackFingerprints(ctx context.Context, rep *Report, runID int64, writes []store.PackWrite) { - targets := make([]captureTarget, 0, len(writes)) - for _, w := range writes { +// landed pack, with the fingerprint its landing confirmed or, failing +// that, one read back over the shared capture surface on the packs/ +// directory. Every pack exceeds the multipart threshold, so on s3 the +// composite ETag is read from the S3 API (never rclone's md5 slot, which +// is blank for a multipart object); other rclone backends read `rclone +// lsjson --hash`. A pack whose fingerprint could not be read stays pending +// (checksum NULL) with a warning — never a fabricated value. The whole-pair +// pending tally (CountVolumeContentsPendingFingerprint) is what +// advanceMethod gates the vector advance on, so this returns nothing. +func (h *packedHandler) capturePackFingerprints(ctx context.Context, rep *Report, runID int64, packs []landedPack) { + targets := make([]captureTarget, 0, len(packs)) + for _, lp := range packs { + w := lp.write pack, err := h.store.GetPackByKey(ctx, w.Pack.PackKey) if err != nil { rep.Warnings = append(rep.Warnings, fmt.Sprintf("look up recorded pack %s: %v", hex.EncodeToString(w.Pack.PackKey), err)) @@ -281,6 +295,14 @@ func (h *packedHandler) capturePackFingerprints(ctx context.Context, rep *Report continue } packID := pack.ID + if cs := lp.fingerprint; cs != nil { + if err := h.store.SetRemotePackFingerprint(ctx, packID, h.dest.Name, cs.Algo, cs.Value, store.NowNs()); err != nil { + rep.Warnings = append(rep.Warnings, fmt.Sprintf("record fingerprint for pack %s: %v", hex.EncodeToString(w.Pack.PackKey), err)) + continue + } + rep.Fingerprints++ + continue + } targets = append(targets, captureTarget{ name: h.names().pack(w.Pack.PackKey), label: "pack", @@ -289,7 +311,9 @@ func (h *packedHandler) capturePackFingerprints(ctx context.Context, rep *Report }, }) } - h.captureScanBackFingerprints(ctx, rep, PacksDirName, targets) + if len(targets) > 0 { + h.art.capture(ctx, rep, PacksDirName, targets) + } } // landed reports whether runID's placement map is at the destination. @@ -298,11 +322,11 @@ func (h *packedHandler) capturePackFingerprints(ctx context.Context, rep *Report // layout — a mirror leaves no map, a content-addressed root leaves objects // and segments but no packs/ map — or a wiped root. func (h *packedHandler) landed(ctx context.Context, runID int64) (bool, error) { - return h.rcl.statRemoteExists(ctx, h.mapURI(runID), checkersArgs(h.dest)...) + return h.art.exists(ctx, mapName(runID)) } func (h *packedHandler) foreignHistory(runID int64) error { - return fmt.Errorf("destination %q: the last successful sync (run %d) left no pack placement map at %s — its history is not packed (a mirror or content-addressed root); point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w", h.dest.Name, runID, h.mapURI(runID), h.dest.Name, ErrRefused) + return fmt.Errorf("destination %q: the last successful sync (run %d) left no pack placement map at %s — its history is not packed (a mirror or content-addressed root); point the layout at a fresh destination or root, or (after wiping the remote root) run `squirrel destination reset %s`, instead of switching an existing one: %w", h.dest.Name, runID, h.art.where(mapName(runID)), h.dest.Name, ErrRefused) } // routeBySize splits the planned uploads by dest.PackThreshold: content at @@ -335,12 +359,12 @@ func (h *packedHandler) routeBySize(ctx context.Context, planned []store.PathDel // assembleAndUploadPacks bundles the sorted small content into tar.zst // packs, staging and uploading one pack at a time so memory and disk stay -// bounded regardless of corpus size. It returns the pack rows to record +// bounded regardless of corpus size. It returns the packs to record // locally and the placement entries for the run's map; nothing is recorded // in the store here (push does that only after the map and segment land). -func (h *packedHandler) assembleAndUploadPacks(ctx context.Context, rep *Report, runID int64, small []store.PathDelta) ([]store.PackWrite, []PlacementEntry, error) { +func (h *packedHandler) assembleAndUploadPacks(ctx context.Context, rep *Report, runID int64, small []store.PathDelta) ([]landedPack, []PlacementEntry, error) { level := zstdEncoderLevel(h.dest.ZstdLevel) - var writes []store.PackWrite + var packs []landedPack var placements []PlacementEntry for i := 0; i < len(small); { pack, next, err := h.buildOnePack(small, i, level) @@ -348,15 +372,16 @@ func (h *packedHandler) assembleAndUploadPacks(ctx context.Context, rep *Report, return nil, nil, err } i = next - if err := h.uploadPack(ctx, pack); err != nil { + fingerprint, err := h.uploadPack(ctx, runID, pack) + if err != nil { return nil, nil, err } rep.RcloneResult.Transferred++ rep.RcloneResult.Bytes += pack.compressedSize - writes = append(writes, pack.toWrite(runID)) + packs = append(packs, landedPack{write: pack.toWrite(runID), fingerprint: fingerprint}) placements = append(placements, pack.placements()...) } - return writes, placements, nil + return packs, placements, nil } // buildOnePack assembles content from srcs starting at index start into a @@ -406,25 +431,17 @@ func (h *packedHandler) buildOnePack(srcs []store.PathDelta, start int, level zs return assembledPack{tmpPath: tmp.Name(), key: key, compressedSize: size, members: members}, i, nil } -// uploadPack copies one staged pack to packs/ through the -// crypt overlay and confirms it landed at the compressed size, then removes -// the temp file. Through a crypt overlay the reported size is the decrypted -// length, which is the compressed pack, so it compares directly. -func (h *packedHandler) uploadPack(ctx context.Context, pack assembledPack) error { +// uploadPack lands one staged pack at packs/, confirmed at +// its compressed size and its key — the BLAKE3 of those bytes — then +// removes the temp file. Through a crypt overlay the reported size is the +// decrypted length, which is the compressed pack, so it compares directly. +func (h *packedHandler) uploadPack(ctx context.Context, runID int64, pack assembledPack) (*remoteChecksum, error) { defer func() { _ = os.Remove(pack.tmpPath) }() - hexKey := hex.EncodeToString(pack.key) - uri := h.packURI(pack.key) - if err := h.rcl.copyTo(ctx, pack.tmpPath, uri, checkersArgs(h.dest)...); err != nil { - return fmt.Errorf("upload pack %s: %w", hexKey, err) - } - size, err := h.rcl.statRemote(ctx, uri, checkersArgs(h.dest)...) + fingerprint, err := h.art.put(ctx, runID, h.packName(pack.key), pack.tmpPath, pack.compressedSize, pack.key) if err != nil { - return fmt.Errorf("confirm pack %s after upload: %w", hexKey, err) + return nil, fmt.Errorf("upload pack %s: %w", hex.EncodeToString(pack.key), err) } - if size != pack.compressedSize { - return fmt.Errorf("pack %s landed with size %d, want %d", hexKey, size, pack.compressedSize) - } - return nil + return fingerprint, nil } // uploadPlacementMap writes the run's placement map and confirms it landed @@ -436,49 +453,19 @@ func (h *packedHandler) uploadPlacementMap(ctx context.Context, placements []Pla if err != nil { return err } - return h.uploadBytes(ctx, body, h.mapURI(runID), "placement map") -} - -// uploadBytes stages body in a temp file, copies it to uri through the -// crypt overlay, and confirms it landed at len(body). what names the -// artifact in error messages. -func (h *contentPusher) uploadBytes(ctx context.Context, body []byte, uri, what string) error { - tmp, err := os.CreateTemp("", "squirrel-meta-*") - if err != nil { - return fmt.Errorf("stage %s: %w", what, err) - } - defer func() { _ = os.Remove(tmp.Name()) }() - if _, err := tmp.Write(body); err != nil { - _ = tmp.Close() - return fmt.Errorf("write %s: %w", what, err) - } - if err := tmp.Close(); err != nil { - return fmt.Errorf("close %s: %w", what, err) - } - if err := h.rcl.copyTo(ctx, tmp.Name(), uri, checkersArgs(h.dest)...); err != nil { - return fmt.Errorf("upload %s to %s: %w", what, uri, err) - } - size, err := h.rcl.statRemote(ctx, uri, checkersArgs(h.dest)...) - if err != nil { - return fmt.Errorf("confirm %s at %s: %w", what, uri, err) - } - if size != int64(len(body)) { - return fmt.Errorf("%s at %s landed with size %d, want %d", what, uri, size, len(body)) - } - return nil + return putBytes(ctx, h.art, runID, mapName(runID), body, "placement map") } -// packURI addresses one pack under the destination-root packs/ directory, -// through the crypt overlay when the destination has one. The basename is -// namer.pack's. -func (h *packedHandler) packURI(packKey []byte) string { - return remoteSubpathURI(h.dest, path.Join(PacksDirName, h.names().pack(packKey))) +// packName is one pack under the destination-root packs/ directory. The +// basename is namer.pack's. +func (h *packedHandler) packName(packKey []byte) string { + return path.Join(PacksDirName, h.names().pack(packKey)) } -// mapURI addresses one run's placement map under the destination-root -// packs/ directory. -func (h *packedHandler) mapURI(runID int64) string { - return remoteSubpathURI(h.dest, path.Join(PacksDirName, packMapPrefix+strconv.FormatInt(runID, 10))) +// mapName is one run's placement map under the destination-root packs/ +// directory. +func mapName(runID int64) string { + return path.Join(PacksDirName, packMapPrefix+strconv.FormatInt(runID, 10)) } // zstdEncoderLevel maps the config's 1..4 zstd level onto klauspost's diff --git a/sync/scanback.go b/sync/scanback.go index 04d8cb1..363584f 100644 --- a/sync/scanback.go +++ b/sync/scanback.go @@ -32,7 +32,7 @@ type captureTarget struct { // fingerprint left pending. The content-addressed object path and the // packed pack path share this surface, differing only in the dirName they // scan and the record closure each target carries. -func (h *contentPusher) captureScanBackFingerprints(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { +func (h *rcloneArtifacts) captureScanBackFingerprints(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { // A run that uploaded nothing new has nothing to fingerprint; return // before the s3 path would otherwise list the whole prefix (and possibly // warn on a transient failure) for an empty batch. @@ -49,7 +49,7 @@ func (h *contentPusher) captureScanBackFingerprints(ctx context.Context, rep *Re // captureScanBackRclone reads provider checksums via `rclone lsjson // --hash`, batched into one invocation per chunk and scoped by --include // filters so the backend hashes only this run's uploads. -func (h *contentPusher) captureScanBackRclone(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { +func (h *rcloneArtifacts) captureScanBackRclone(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { dirURI := underlyingDirURI(h.dest, dirName) types := captureHashTypes(h.dest) for batch := range slices.Chunk(targets, fingerprintBatchSize) { @@ -79,7 +79,7 @@ func (h *contentPusher) captureScanBackRclone(ctx context.Context, rep *Report, // every fingerprint pending with a warning — capture is not on the // durability critical path (the bytes are already confirmed), so `squirrel // verify` is the backstop. -func (h *contentPusher) captureScanBackS3(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { +func (h *rcloneArtifacts) captureScanBackS3(ctx context.Context, rep *Report, dirName string, targets []captureTarget) { reader, err := newS3ETagReader(h.dest, dirName) if err == nil { var etags map[string]string @@ -103,7 +103,7 @@ func (h *contentPusher) captureScanBackS3(ctx context.Context, rep *Report, dirN // listing (byName, present). A target absent from the listing or exposing // no usable checksum stays pending with a warning; the fingerprint is never // fabricated. Each recorded checksum counts toward rep.Fingerprints. -func (h *contentPusher) recordScanBack(ctx context.Context, rep *Report, targets []captureTarget, byName map[string]map[string]string, present map[string]bool) { +func (h *rcloneArtifacts) recordScanBack(ctx context.Context, rep *Report, targets []captureTarget, byName map[string]map[string]string, present map[string]bool) { for _, t := range targets { if !present[t.name] { rep.Warnings = append(rep.Warnings, fmt.Sprintf("%s %s on %q: not yet returned by the remote listing; fingerprint stays pending", t.label, t.name, h.dest.Name)) From 3b43b1b0b7bc53364a25ec106de0cadfbb652530 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:08:37 +0200 Subject: [PATCH 33/61] sync: tidy the server hash tests and wrap the probe's failure --- sync/transport_sftp_hash.go | 2 +- sync/transport_sftp_hash_test.go | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/sync/transport_sftp_hash.go b/sync/transport_sftp_hash.go index 1a71287..549dfb8 100644 --- a/sync/transport_sftp_hash.go +++ b/sync/transport_sftp_hash.go @@ -121,7 +121,7 @@ func (t *sftpTransport) runProbe() error { command := serverHashCommands[t.hashAlgo] out, err := t.runCommand(command, strings.NewReader(serverHashProbe)) if err != nil { - return fmt.Errorf("%w: %v", errNoServerHash, err) + return fmt.Errorf("%w: %w", errNoServerHash, err) } sum, err := parseHashOutput(out, h.Size()) if err != nil || sum != hex.EncodeToString(h.Sum(nil)) { diff --git a/sync/transport_sftp_hash_test.go b/sync/transport_sftp_hash_test.go index 8850d2b..6a49496 100644 --- a/sync/transport_sftp_hash_test.go +++ b/sync/transport_sftp_hash_test.go @@ -12,8 +12,8 @@ import ( ) // hashFixture serves root from a test server that runs commands, and -// plants one artifact, objects/, holding body. -func hashFixture(t *testing.T, commands map[string]string, body string) (*sftpTransport, string) { +// plants one artifact, objects/, holding "alpha". +func hashFixture(t *testing.T, commands map[string]string) (*sftpTransport, string) { t.Helper() srv := startSFTPServer(t) srv.runsHashCommands(commands) @@ -22,7 +22,7 @@ func hashFixture(t *testing.T, commands map[string]string, body string) (*sftpTr if err := os.MkdirAll(filepath.Join(root, ObjectsDirName), 0o755); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(root, ObjectsDirName, key), []byte(body), 0o644); err != nil { + if err := os.WriteFile(filepath.Join(root, ObjectsDirName, key), []byte("alpha"), 0o644); err != nil { t.Fatal(err) } dest := srv.destination(t, root) @@ -35,7 +35,7 @@ func hashFixture(t *testing.T, commands map[string]string, body string) (*sftpTr // TestServerHashRunsTheCommand: a server with the command hashes an // artifact where it lies, and the value is what this machine computes. func TestServerHashRunsTheCommand(t *testing.T) { - tr, name := hashFixture(t, map[string]string{"sha256sum": "sha256"}, "alpha") + tr, name := hashFixture(t, map[string]string{"sha256sum": "sha256"}) got, err := tr.ServerHash(context.Background(), name) if err != nil { t.Fatalf("ServerHash: %v", err) @@ -60,13 +60,13 @@ func TestServerHashRefusesWhatItCannotTrust(t *testing.T) { {"a command computing another hash", map[string]string{"sha256sum": "blake3"}}, } { t.Run(c.name, func(t *testing.T) { - tr, name := hashFixture(t, c.commands, "alpha") + tr, name := hashFixture(t, c.commands) if _, err := tr.ServerHash(ctx, name); !errors.Is(err, errNoServerHash) { t.Fatalf("ServerHash = %v, want errNoServerHash", err) } }) } - tr, _ := hashFixture(t, map[string]string{"sha256sum": "sha256"}, "alpha") + tr, _ := hashFixture(t, map[string]string{"sha256sum": "sha256"}) if err := os.WriteFile(filepath.Join(tr.root, "cat; rm -rf x.jpg"), []byte("meow"), 0o644); err != nil { t.Fatal(err) } @@ -81,7 +81,7 @@ func TestServerHashRefusesWhatItCannotTrust(t *testing.T) { if err != nil { t.Fatal(err) } - defer local.Close() + defer func() { _ = local.Close() }() if _, err := local.ServerHash(ctx, "objects/x"); !errors.Is(err, errNoServerHash) { t.Fatalf("local ServerHash = %v, want errNoServerHash", err) } @@ -91,7 +91,7 @@ func TestServerHashRefusesWhatItCannotTrust(t *testing.T) { // that stops running the command afterwards fails the hash itself. func TestServerHashProbesOnce(t *testing.T) { srvCommands := map[string]string{"sha256sum": "sha256"} - tr, name := hashFixture(t, srvCommands, "alpha") + tr, name := hashFixture(t, srvCommands) ctx := context.Background() if _, err := tr.ServerHash(ctx, name); err != nil { t.Fatalf("first ServerHash: %v", err) From 5a7fa92c1c29479edd57663bf78946b9a222a44c Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:21:10 +0200 Subject: [PATCH 34/61] sync: push content-addressed and packed destinations through the transport On local, and on sftp without crypt, the content layouts land every artifact through squirrel's own transport: staged while BLAKE3 hashes the bytes sent, confirmed by a read-back on a local disk or by the server's hash command on sftp, recorded with that fingerprint at once, and renamed onto its name. An artifact already at its name is confirmed and adopted, never replaced. They are gated on the volume marker like a native mirror, and a missing local root is refused until --init creates it. config: Destination.Native covers every layout on local and plain sftp. The content layouts are valid on local now, native sftp content destinations take md5, sha1, sha256 (the default, now for packed too) or blake3 as hash_algo, and checkers is refused on every native destination. --- config/destinations.go | 91 ++++---- config/fingerprint_knobs_test.go | 32 +++ config/layout_test.go | 16 +- config/pack_test.go | 13 +- design/native-mirror.md | 42 +++- sync/artifacts_rclone.go | 10 +- sync/artifacts_transport.go | 190 ++++++++++++++++ sync/content_addressed.go | 9 +- sync/content_addressed_test.go | 13 -- sync/content_native_test.go | 374 +++++++++++++++++++++++++++++++ sync/destination_marker.go | 26 ++- sync/handler.go | 31 ++- sync/mirror_test.go | 16 +- sync/naming_test.go | 10 +- sync/packed.go | 2 +- 15 files changed, 765 insertions(+), 110 deletions(-) create mode 100644 sync/artifacts_transport.go create mode 100644 sync/content_native_test.go diff --git a/config/destinations.go b/config/destinations.go index f522897..a295140 100644 --- a/config/destinations.go +++ b/config/destinations.go @@ -146,7 +146,7 @@ func resolveDestination(name string, raw map[string]any) (*Destination, error) { if err != nil { return nil, err } - native := nativeMirror(typ, layout, crypt != nil) + native := isNative(typ, crypt != nil) hashAlgo, err := resolveHashAlgo(raw, typ, layout, native) if err != nil { return nil, err @@ -163,7 +163,7 @@ func resolveDestination(name string, raw map[string]any) (*Destination, error) { if err != nil { return nil, err } - verifyEvery, err := resolveVerifyEvery(raw, verifiable(layout, native)) + verifyEvery, err := resolveVerifyEvery(raw, verifiable(layout, native && isMirrorLayout(layout))) if err != nil { return nil, err } @@ -254,45 +254,54 @@ func resolveVerifyEvery(raw map[string]any, verifiable bool) (time.Duration, err } // sftpHashAlgos are the checksum types rclone's sftp backend can read -// via a server-side sum command, the valid values for `hash_algo`. +// via a server-side sum command, the valid values for `hash_algo` on an +// sftp destination rclone writes. var sftpHashAlgos = map[string]bool{ "md5": true, "sha1": true, "sha256": true, "crc32": true, "blake3": true, "xxh3": true, "xxh128": true, } -// resolveHashAlgo validates the optional `hash_algo` key. sftp is the -// one backend where rclone must be told which server-side hash command -// to run; every other type exposes a fixed checksum, so the key is -// rejected there, and so is it on a native sftp mirror, which runs no -// command on the server. Content-addressed sftp destinations default to -// "sha256" so scan-back fingerprints get a strong checksum without -// relying on rclone's md5/sha1 preference. +// nativeHashAlgos are the valid values for `hash_algo` on a content- +// addressed or packed sftp destination squirrel writes itself: the hashes +// whose server command (md5sum, sha1sum, sha256sum, b3sum) squirrel runs, +// and which it computes itself to check the server's answer. +var nativeHashAlgos = map[string]bool{"md5": true, "sha1": true, "sha256": true, "blake3": true} + +// resolveHashAlgo validates the optional `hash_algo` key: which hash +// command the sftp server runs to fingerprint what squirrel stored. Every +// other type exposes a fixed checksum, so the key is rejected there, and +// so is it on a native sftp mirror, which runs no command on the server. +// Content-addressed sftp destinations, and packed ones squirrel writes +// itself, default to "sha256" so fingerprints get a strong checksum. func resolveHashAlgo(raw map[string]any, typ, layout string, native bool) (string, error) { v, err := optionalString(raw, "hash_algo") if err != nil { return "", err } if v == "" { - if typ == "sftp" && layout == LayoutContentAddressed { + if typ == "sftp" && (layout == LayoutContentAddressed || (native && layout == LayoutPacked)) { return "sha256", nil } return "", nil } - if typ != "sftp" { + allowed := sftpHashAlgos + switch { + case typ != "sftp": return "", fmt.Errorf(`hash_algo is only supported on type "sftp" destinations; type %q exposes a fixed checksum`, typ) - } - if native { + case native && isMirrorLayout(layout): return "", errors.New("hash_algo names the hash command run on the sftp server, and a mirror without crypt runs none: squirrel writes it itself and hashes every file as it sends it") + case native: + allowed = nativeHashAlgos } - if !sftpHashAlgos[v] { - return "", fmt.Errorf("unknown hash_algo %q (supported: %v)", v, sortedKeys(sftpHashAlgos)) + if !allowed[v] { + return "", fmt.Errorf("unknown hash_algo %q (supported: %v)", v, sortedKeys(allowed)) } return v, nil } // resolveCheckers validates the optional `checkers` key: a positive // integer cap on rclone's concurrent checkers for this destination. A -// native mirror runs no rclone, so the key is rejected there. +// native destination runs no rclone, so the key is rejected there. func resolveCheckers(raw map[string]any, typ string, native bool) (int, error) { v, ok := raw["checkers"] if !ok { @@ -300,7 +309,7 @@ func resolveCheckers(raw map[string]any, typ string, native bool) (int, error) { } switch { case native: - return 0, fmt.Errorf("checkers caps rclone's checkers, and a type %q mirror without crypt is written by squirrel itself, without rclone", typ) + return 0, fmt.Errorf("checkers caps rclone's checkers, and a type %q destination without crypt is written by squirrel itself, without rclone", typ) case typ == "kopia": return 0, fmt.Errorf("checkers requires an rclone-remote destination type, not %q", typ) } @@ -341,9 +350,8 @@ func sortedKeys(m map[string]bool) []string { // resolveLayout validates the optional `layout` key of a destination. An // absent key resolves to LayoutMirror. LayoutContentAddressed and -// LayoutPacked drive squirrel's own rclone transfers, so both require an -// rclone-remote type: type "local" is addressed by filesystem path, and -// "kopia" repositories already use kopia's own content-addressed format. +// LayoutPacked are squirrel's own formats, on any type but "kopia", whose +// repositories already use kopia's own content-addressed format. func resolveLayout(raw map[string]any, typ string) (string, error) { v, err := optionalString(raw, "layout") if err != nil { @@ -353,8 +361,8 @@ func resolveLayout(raw map[string]any, typ string) (string, error) { case "", LayoutMirror: return LayoutMirror, nil case LayoutContentAddressed, LayoutPacked: - if err := requireRcloneRemote(v, typ); err != nil { - return "", err + if typ == "kopia" { + return "", fmt.Errorf(`layout %q does not apply to type "kopia": kopia repositories are content-addressed by kopia itself`, v) } return v, nil default: @@ -362,21 +370,6 @@ func resolveLayout(raw map[string]any, typ string) (string, error) { } } -// requireRcloneRemote rejects the two rclone-remote-only layouts on the -// destination types that can't drive per-object squirrel transfers: type -// "local" is a filesystem path, and "kopia" runs its own content-addressed -// binary. Shared by the LayoutContentAddressed and LayoutPacked branches so -// both give the same guardrail message. -func requireRcloneRemote(layout, typ string) error { - switch typ { - case "local": - return fmt.Errorf(`layout %q requires an rclone-remote destination; type "local" is addressed by filesystem path`, layout) - case "kopia": - return fmt.Errorf(`layout %q requires an rclone-remote destination; type "kopia" repositories are content-addressed by kopia itself`, layout) - } - return nil -} - // Pack-layout knob defaults, applied when a LayoutPacked destination omits // the corresponding key. Sizes are in bytes. const ( @@ -833,16 +826,24 @@ func sortedSubset(in []string) []string { return out } -// NativeMirror reports whether squirrel writes this destination itself, -// through its own transport: a mirror on a local disk, or on an sftp -// server without crypt. +// Native reports whether squirrel writes this destination itself, through +// its own transport, in any layout: a local disk, or an sftp server without +// crypt. rclone writes every other destination but kopia. +func (d *Destination) Native() bool { + return isNative(d.Type, d.Crypt != nil) +} + +func isNative(typ string, crypt bool) bool { + return !crypt && (typ == "local" || typ == "sftp") +} + +// NativeMirror reports whether this is a mirror squirrel writes itself. func (d *Destination) NativeMirror() bool { - return nativeMirror(d.Type, d.Layout, d.Crypt != nil) + return d.Native() && isMirrorLayout(d.Layout) } -func nativeMirror(typ, layout string, crypt bool) bool { - mirror := layout != LayoutContentAddressed && layout != LayoutPacked - return mirror && !crypt && (typ == "local" || typ == "sftp") +func isMirrorLayout(layout string) bool { + return layout != LayoutContentAddressed && layout != LayoutPacked } // Verifiable reports whether `squirrel verify` re-checks this destination: diff --git a/config/fingerprint_knobs_test.go b/config/fingerprint_knobs_test.go index 778b5cd..a1a9166 100644 --- a/config/fingerprint_knobs_test.go +++ b/config/fingerprint_knobs_test.go @@ -79,6 +79,35 @@ password = "pw" } } +// TestNativeContentLayoutsTakeTheirOwnHashes: a content-addressed or packed +// sftp destination squirrel writes itself defaults to sha256, accepts the +// hashes whose command squirrel runs and checks, refuses the ones only +// rclone reads, and refuses checkers; one behind crypt keeps rclone's. +func TestNativeContentLayoutsTakeTheirOwnHashes(t *testing.T) { + dest := func(extra string) string { + return "[destinations.archive]\ntype = \"sftp\"\nhost = \"h\"\nuser = \"u\"\nroot = \"/data\"\nlayout = \"packed\"\n" + extra + } + cfg, err := Load(writeConfig(t, dest(""))) + if err != nil { + t.Fatalf("Load: %v", err) + } + if got := cfg.Destinations["archive"].HashAlgo; got != "sha256" { + t.Fatalf("HashAlgo = %q, want the sha256 default on a native packed destination", got) + } + if _, err := Load(writeConfig(t, dest(`hash_algo = "blake3"`+"\n"))); err != nil { + t.Fatalf("blake3 on a native packed destination: %v", err) + } + for _, key := range []string{`hash_algo = "xxh3"`, "checkers = 4"} { + name, _, _ := strings.Cut(key, " ") + if _, err := Load(writeConfig(t, dest(key+"\n"))); err == nil || !strings.Contains(err.Error(), name) { + t.Fatalf("%s on a native packed destination: err = %v, want a rejection naming it", key, err) + } + } + if _, err := Load(writeConfig(t, dest(`hash_algo = "xxh3"`+"\n\n[destinations.archive.crypt]\npassword = \"pw\"\n"))); err != nil { + t.Fatalf("xxh3 behind crypt, which rclone writes: %v", err) + } +} + // TestLoadRejectsRcloneKeysOnNativeMirrors: squirrel writes a plain sftp // mirror itself, so the keys that only tune rclone are refused there. func TestLoadRejectsRcloneKeysOnNativeMirrors(t *testing.T) { @@ -134,6 +163,9 @@ user = "u" root = "/data" layout = "content-addressed" checkers = 4 + +[destinations.archive.crypt] +password = "pw" `)) if err != nil { t.Fatalf("Load: %v", err) diff --git a/config/layout_test.go b/config/layout_test.go index 8f43aa2..0f37190 100644 --- a/config/layout_test.go +++ b/config/layout_test.go @@ -63,16 +63,20 @@ layout = "mirror" } } -func TestLoadRejectsContentAddressedOnLocal(t *testing.T) { - p := writeConfig(t, ` +// TestLoadContentAddressedOnLocal: squirrel writes a content-addressed +// destination on a local disk itself, so the layout is valid there. +func TestLoadContentAddressedOnLocal(t *testing.T) { + cfg, err := Load(writeConfig(t, ` [destinations.scratch] type = "local" root = "/tmp/dst" layout = "content-addressed" -`) - _, err := Load(p) - if err == nil || !strings.Contains(err.Error(), "rclone-remote") { - t.Fatalf("expected rclone-remote requirement error, got %v", err) +`)) + if err != nil { + t.Fatalf("Load: %v", err) + } + if d := cfg.Destinations["scratch"]; d.Layout != LayoutContentAddressed || !d.Native() { + t.Fatalf("destination = %+v, want a native content-addressed one", d) } } diff --git a/config/pack_test.go b/config/pack_test.go index 11d646b..ac6ab27 100644 --- a/config/pack_test.go +++ b/config/pack_test.go @@ -83,15 +83,20 @@ root = "p" } } -func TestLoadRejectsPackedOnLocal(t *testing.T) { - _, err := Load(writeConfig(t, ` +// TestLoadPackedOnLocal: squirrel writes a packed destination on a local +// disk itself, so the layout is valid there. +func TestLoadPackedOnLocal(t *testing.T) { + cfg, err := Load(writeConfig(t, ` [destinations.scratch] type = "local" root = "/tmp/dst" layout = "packed" `)) - if err == nil || !strings.Contains(err.Error(), "rclone-remote") { - t.Fatalf("expected rclone-remote requirement error, got %v", err) + if err != nil { + t.Fatalf("Load: %v", err) + } + if d := cfg.Destinations["scratch"]; d.Layout != LayoutPacked || !d.Native() { + t.Fatalf("destination = %+v, want a native packed one", d) } } diff --git a/design/native-mirror.md b/design/native-mirror.md index da27c2c..4a5dc77 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -595,6 +595,36 @@ for local mirrors. - the F21 entry in friction-log.md; - SAFETY-AUDIT.md. +### The content layouts on the transport + +Content-addressed and packed destinations on `local`, and on `sftp` without +`crypt`, are written through the transport too (`sync/artifacts_transport.go`). +The layouts land every object, pack, placement map and manifest segment +through one small interface, `artifactStore` (`sync/artifacts.go`), whose +other implementation is rclone's, for crypt destinations and for s3, b2 and +gcs. Each artifact: + +1. is streamed into `/.squirrel-staging/run-/` while BLAKE3 + hashes the bytes sent — the drift check, over exactly those bytes — and, on + sftp, the hash the server's command computes; +2. is confirmed before it gets its name: read back through BLAKE3 on a local + disk, hashed by the server's command on sftp. A match is the artifact's + fingerprint, recorded with its upload row at once; a mismatch fails the + artifact. A server without the command confirms nothing, and the + fingerprint stays pending, as it does under rclone for such a server; +3. is renamed onto its name. If the name already holds a file — a crash + between landing and recording, or a failed run's orphan — that file is + confirmed instead (downloaded and hashed when the server runs no command) + and recorded, or the artifact fails. Squirrel never replaces it. + +The staged copy of a failed artifact goes with the run's staging at the next +push's reconcile. The content layouts' guard commits only onto artifact names +and displaces nothing (section 3). Both native content layouts are gated on +the volume marker like a native mirror, `--init` creating a missing local +root; a missing root is otherwise refused like a missing marker. Before this, +config refused the content layouts on `local` outright, because rclone +addressed local destinations by path; that restriction is gone. + ## 6. Restore, ride-along, recover - **Mirror restore with an index** uses the archive restore pipeline @@ -627,8 +657,11 @@ for local mirrors. ## 7. Configuration and dispatch -- **Dispatch.** `HandlerFor` sends mirrors on `local`, and on `sftp` without - `crypt`, to the native handler. Every other pair is unchanged. +- **Dispatch.** `HandlerFor` sends every destination on `local`, and on + `sftp` without `crypt`, through squirrel's own transport + (`Destination.Native`): mirrors to the native mirror handler, the content + layouts to their handlers with the transport's artifact store. Crypt + destinations and s3, b2 and gcs keep rclone. - **sftp settings.** `host`, `port`, `user`, `password`, `key_file`, `known_hosts_file` and `host_key_algorithms` map onto `ssh.ClientConfig`. When there is neither password nor key file, squirrel uses ssh-agent, as @@ -641,7 +674,10 @@ for local mirrors. - **Rclone-only keys are rejected** on native destinations: `checkers` everywhere, and `hash_algo` on sftp mirrors. On content-addressed and packed sftp destinations, `hash_algo` still chooses the hash, which now names the - command the transport runs on the server. No key is added. + command the transport runs on the server: `md5`, `sha1`, `sha256` (the + default, now for packed as well) or `blake3`, the hashes squirrel also + computes to check the server's answer. rclone's other hashes (`crc32`, + `xxh3`, `xxh128`) stay valid behind crypt only. No key is added. Concurrency is fixed. On sftp each file goes out as concurrent write requests (`pkg/sftp`'s default of 64 in flight); paths are written one at a time on both transports. The testbed benchmark against rclone (section 8) diff --git a/sync/artifacts_rclone.go b/sync/artifacts_rclone.go index 627556e..306f025 100644 --- a/sync/artifacts_rclone.go +++ b/sync/artifacts_rclone.go @@ -22,21 +22,15 @@ type rcloneArtifacts struct { // names is how the destination names its artifacts. func (a *rcloneArtifacts) names() namer { return namerFor(a.dest) } -// markers gates a remote push on the root's naming scheme, then on the +// markers gates the push on the root's naming scheme, then on the // destination's per-volume .squirrel-volume marker, exactly as the mirror // layout does (the marker sits at the volume root regardless of layout). A -// dry run checks the naming scheme read-only and writes nothing. Local -// content-addressed and packed destinations are left ungated here: they -// carry no such gate today, so extending it to them is a separate parity -// concern — this closes only the remote gap (#150). +// dry run checks the naming scheme read-only and writes nothing. func (a *rcloneArtifacts) markers(ctx context.Context, opts Options) error { if opts.DryRun { _, err := a.checkNamingScheme(ctx) return err } - if a.dest.Type == "local" { - return nil - } if err := a.ensureNamingScheme(ctx, opts.Init); err != nil { return err } diff --git a/sync/artifacts_transport.go b/sync/artifacts_transport.go new file mode 100644 index 0000000..6a10b0e --- /dev/null +++ b/sync/artifacts_transport.go @@ -0,0 +1,190 @@ +package sync + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "hash" + "io" + "io/fs" + "os" + "time" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/store" +) + +// transportArtifacts is an artifact store squirrel writes itself: a +// content-addressed or packed destination on a local disk, or on an sftp +// server without crypt. Each artifact is staged in the volume's +// .squirrel-staging/run-/ while BLAKE3 hashes the bytes sent, read +// back — through BLAKE3 on a local disk, through the server's hash command +// on sftp — and renamed onto its name, so it lands whole or not at all. +type transportArtifacts struct { + *destinationRoot + // noServerHash is why the sftp server fingerprinted nothing this push, + // once a landing found out. + noServerHash error +} + +// root is the destination root as the push may hold it: guarded, so only +// runID's own commits pass (none when runID is 0), and bounded by progress. +func (a *transportArtifacts) root(ctx context.Context, runID int64) (transport, error) { + return a.guarded(ctx, nameGuard{volumeDir: a.volumeDir, runID: runID, content: true, finished: a.runFinished}) +} + +// markers gates the push on the volume marker, as a native mirror does: +// written under --init, which also creates a missing local root, and +// refused otherwise. A dry run checks nothing. +func (a *transportArtifacts) markers(ctx context.Context, opts Options) error { + if opts.DryRun { + return nil + } + return a.ensureMarker(ctx, opts.Init) +} + +func (a *transportArtifacts) exists(ctx context.Context, name string) (bool, error) { + tr, err := a.root(ctx, 0) + if err != nil { + return false, err + } + return present(ctx, tr, name) +} + +func (a *transportArtifacts) rootEmpty(ctx context.Context) (bool, error) { + tr, err := a.root(ctx, 0) + if err != nil { + return false, err + } + return treeEmpty(ctx, tr, ".") +} + +// reconcile removes what finished runs left staged: a partial artifact +// from a crash, a drifted source's copy, or one whose name another run's +// landing already held. +func (a *transportArtifacts) reconcile(ctx context.Context, rep *Report, runID int64) error { + tr, err := a.root(ctx, runID) + if err != nil { + return err + } + return a.clearFinishedStaging(ctx, rep, tr) +} + +func (a *transportArtifacts) put(ctx context.Context, runID int64, name, src string, size int64, sum []byte) (*remoteChecksum, error) { + tr, err := a.root(ctx, runID) + if err != nil { + return nil, err + } + staged := stagingName(a.volumeDir, runID, stagingKey(name)) + sent, err := a.stage(ctx, tr, staged, src, size, sum) + if err != nil { + return nil, err + } + fingerprint, err := a.confirm(ctx, tr, staged, sum, sent, true) + if err != nil { + return nil, err + } + err = tr.Rename(ctx, staged, name) + if errors.Is(err, fs.ErrExist) { + return a.confirm(ctx, tr, name, sum, sent, false) + } + return fingerprint, err +} + +// stage streams src into staged, hashing the bytes sent with BLAKE3 and, +// on sftp, with the hash the server's command computes. It returns that +// server-side hash's value for what was sent, or "" when there is none. +func (a *transportArtifacts) stage(ctx context.Context, tr transport, staged, src string, size int64, sum []byte) (string, error) { + f, err := os.Open(src) + if err != nil { + return "", fmt.Errorf("open %s: %w", src, err) + } + defer f.Close() + b3 := blake3.New() + counted := &countWriter{w: b3} + sink := io.Writer(counted) + server := newArtifactHash(a.dest.HashAlgo) + if server != nil { + sink = io.MultiWriter(counted, server) + } + if err := tr.Put(ctx, staged, io.TeeReader(f, sink), time.Now()); err != nil { + return "", fmt.Errorf("stage %s: %w", staged, err) + } + if counted.n != size || !bytes.Equal(b3.Sum(nil), sum) { + return "", fmt.Errorf("%w: %s sent %d bytes hashing to %s, want %d bytes %s", errContentDrift, src, counted.n, hex.EncodeToString(b3.Sum(nil)), size, hex.EncodeToString(sum)) + } + e, err := tr.Stat(ctx, staged) + if err != nil { + return "", fmt.Errorf("confirm %s: %w", staged, err) + } + if e.size != size { + return "", fmt.Errorf("%s landed with size %d, want %d", staged, e.size, size) + } + return hexSum(server), nil +} + +// confirm checks that name holds the bytes sent — read back through +// BLAKE3 against sum on a local disk, hashed by the server's command +// against sent on sftp — and returns the fingerprint that earns. An sftp +// server without the command confirms nothing and fingerprints nothing: +// a staged artifact is committed with its fingerprint pending; one already +// at its name — a crash between its landing and its record, or an earlier +// failed run's orphan — is downloaded and hashed instead, because squirrel +// never replaces it. +func (a *transportArtifacts) confirm(ctx context.Context, tr transport, name string, sum []byte, sent string, staged bool) (*remoteChecksum, error) { + if !readsBack(a.dest) { + cs, err := tr.ServerHash(ctx, name) + switch { + case err == nil && cs.Value == sent: + return &cs, nil + case err == nil: + return nil, fmt.Errorf("%w: %s hashes to %s %s on the server, sent %s", errReadBackMismatch, name, cs.Algo, cs.Value, sent) + case !errors.Is(err, errNoServerHash): + return nil, fmt.Errorf("hash %s on the server: %w", name, err) + } + a.noServerHash = err + if staged { + return nil, nil + } + } + got, err := readBack(ctx, tr, name) + if err != nil { + return nil, fmt.Errorf("read back %s: %w", name, err) + } + if !bytes.Equal(got, sum) { + return nil, fmt.Errorf("%w: %s hashes to %s, sent %s — squirrel never replaces it; inspect it", errReadBackMismatch, name, hex.EncodeToString(got), hex.EncodeToString(sum)) + } + if !readsBack(a.dest) { + return nil, nil + } + return &remoteChecksum{Algo: store.ChecksumAlgoBlake3, Value: hex.EncodeToString(got)}, nil +} + +// capture warns about the artifacts that landed without a fingerprint: an +// sftp server that runs no hash command squirrel trusts. +func (a *transportArtifacts) capture(_ context.Context, rep *Report, dir string, targets []captureTarget) { + if len(targets) == 0 { + return + } + rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination %q: %d artifact(s) under %s/ landed without a fingerprint (%v); they stay pending, so the destination cannot gate offload for them", a.dest.Name, len(targets), dir, a.noServerHash)) +} + +// shelf is the volume's .squirrel-index/, reached through runID's guarded +// transport. +func (a *transportArtifacts) shelf(runID int64) snapshotShelf { + return transportShelf{ + open: func(ctx context.Context) (transport, error) { return a.root(ctx, runID) }, + volume: a.volumeDir, + runID: runID, + } +} + +func hexSum(h hash.Hash) string { + if h == nil { + return "" + } + return hex.EncodeToString(h.Sum(nil)) +} diff --git a/sync/content_addressed.go b/sync/content_addressed.go index f58cc03..8f7535b 100644 --- a/sync/content_addressed.go +++ b/sync/content_addressed.go @@ -124,15 +124,14 @@ func (h *contentPusher) target() pushTarget { return pushTarget{store: h.store, vol: h.vol, dest: h.dest} } -// contentAddressedHandler pushes a volume to a content-addressed rclone -// destination: per-hash `rclone copyto` for each content object the -// destination lacks, then the run's manifest segment. The landing is +// contentAddressedHandler pushes a volume to a content-addressed +// destination: one object for each content the destination lacks, then the +// run's manifest segment, through the artifact store. The landing is // transactional from the durability gate's point of view — the runs row // reaches success and the destination vector advances only once both // the objects and the segment are confirmed present at the expected // size; any earlier failure leaves orphaned objects that are recorded -// (or re-uploaded idempotently) and harmless without a segment mapping -// them. +// (or landed again) and harmless without a segment mapping them. type contentAddressedHandler struct { contentPusher } diff --git a/sync/content_addressed_test.go b/sync/content_addressed_test.go index f3822f9..9a9f327 100644 --- a/sync/content_addressed_test.go +++ b/sync/content_addressed_test.go @@ -228,19 +228,6 @@ password = "obscured-pw" return f } -// setupPlainContentAddressedFixture is setupContentAddressedFixture -// without the crypt block. -func setupPlainContentAddressedFixture(t *testing.T) *caFixture { - t.Helper() - return setupCAFixture(t, `[destinations.offsite] -type = "sftp" -host = "remote.invalid" -user = "u" -root = "/data" -layout = "content-addressed" -`, "/data") -} - // setupCAFixture is the destination-configurable body of // setupContentAddressedFixture. destBlock declares the `offsite` // destination; strip is the destination root the shim removes from diff --git a/sync/content_native_test.go b/sync/content_native_test.go new file mode 100644 index 0000000..deef493 --- /dev/null +++ b/sync/content_native_test.go @@ -0,0 +1,374 @@ +package sync + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/index" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// nativeContentFixture is one volume, "pics", pushed to a content-addressed +// or packed destination squirrel writes itself, "vault": a directory on +// this machine, or one an in-process sftp server serves. dst is where the +// destination's bytes land on this machine either way. +type nativeContentFixture struct { + store *store.Store + pair Pair + src string + dst string +} + +// contentBackend is where a native content fixture's destination lives. +type contentBackend struct { + name string + settings func(t *testing.T, dst string) string +} + +var ( + localContent = contentBackend{"local", func(_ *testing.T, dst string) string { + return fmt.Sprintf("type = \"local\"\nroot = %q\n", dst) + }} + // sftpContent runs sha256sum, as an OpenSSH host does. + sftpContent = contentBackend{"sftp", func(t *testing.T, dst string) string { + return sftpSettings(t, dst, map[string]string{"sha256sum": "sha256"}) + }} + // sftpContentNoPrograms runs no programs, the cloudbox shape. + sftpContentNoPrograms = contentBackend{"sftp without programs", func(t *testing.T, dst string) string { + return sftpSettings(t, dst, nil) + }} + contentBackends = []contentBackend{localContent, sftpContent} + contentLayouts = []string{config.LayoutContentAddressed, config.LayoutPacked} +) + +// setupNativeContentFixture declares vault on b with layout; a packed one +// packs content under 8 bytes. The destination root exists, and on sftp it +// carries the volume marker. +func setupNativeContentFixture(t *testing.T, b contentBackend, layout string) *nativeContentFixture { + t.Helper() + root := t.TempDir() + f := &nativeContentFixture{src: filepath.Join(root, "src"), dst: filepath.Join(root, "vault")} + for _, d := range []string{f.src, filepath.Join(f.dst, "pics")} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + if err := volmark.Write(filepath.Join(f.dst, "pics"), volmark.Marker{Volume: "pics"}); err != nil { + t.Fatalf("seed marker: %v", err) + } + s, err := store.Open(filepath.Join(root, "test.db")) + if err != nil { + t.Fatalf("store.Open: %v", err) + } + t.Cleanup(func() { s.Close() }) + f.store = s + body := "[destinations.vault]\n" + b.settings(t, f.dst) + fmt.Sprintf("layout = %q\n", layout) + if layout == config.LayoutPacked { + body += "pack_threshold = \"8B\"\n" + } + body += "\n[volumes.pics]\npath = \"" + f.src + "\"\nsync_to = [\"vault\"]\n" + cfgPath := filepath.Join(root, "config.toml") + if err := os.WriteFile(cfgPath, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := config.Load(cfgPath) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + f.pair = Pair{Volume: cfg.Volumes["pics"], Destination: cfg.Destinations["vault"]} + return f +} + +func (f *nativeContentFixture) write(t *testing.T, rel, body string) { + t.Helper() + p := filepath.Join(f.src, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +func (f *nativeContentFixture) index(t *testing.T) { + t.Helper() + if _, err := index.Index(context.Background(), f.store, f.src, index.Options{Name: "pics"}); err != nil { + t.Fatalf("index: %v", err) + } +} + +// push runs one push with no rclone wrapper at all. +func (f *nativeContentFixture) push(t *testing.T, opts Options) (Report, error) { + t.Helper() + return RunPair(context.Background(), f.store, Tools{}, f.pair, opts) +} + +func (f *nativeContentFixture) mustPush(t *testing.T) Report { + t.Helper() + rep, err := f.push(t, Options{}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("push: status=%q err=%v warnings=%v", rep.Status, err, rep.Warnings) + } + return rep +} + +// pushCrashing runs one push whose transport crashes at the first call +// crashAt selects. +func (f *nativeContentFixture) pushCrashing(t *testing.T, crashAt func(transportCall) bool) (Report, error) { + t.Helper() + h, err := HandlerFor(f.store, Tools{}, f.pair) + if err != nil { + t.Fatalf("HandlerFor: %v", err) + } + var art artifactStore + switch h := h.(type) { + case *contentAddressedHandler: + art = h.art + case *packedHandler: + art = h.art + } + root := art.(*transportArtifacts).destinationRoot + root.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + if err != nil { + return nil, err + } + return &faultTransport{transport: raw, crashAt: crashAt, mode: crashAfter}, nil + } + return h.Push(context.Background(), Options{}) +} + +func (f *nativeContentFixture) objectPath(body string) string { + return filepath.Join(f.dst, ObjectsDirName, blake3Hex(body)) +} + +func (f *nativeContentFixture) remoteObject(t *testing.T, body string) (store.RemoteObject, bool) { + t.Helper() + ctx := context.Background() + v, err := f.store.GetVolumeByName(ctx, "pics") + if err != nil { + t.Fatal(err) + } + present, err := f.store.ListPresentContent(ctx, v.ID) + if err != nil { + t.Fatal(err) + } + for _, d := range present { + if hex.EncodeToString(d.Blake3) == blake3Hex(body) { + obj, err := f.store.GetRemoteObject(ctx, d.ContentID, "vault") + return obj, err == nil + } + } + t.Fatalf("no present content holds %q", body) + return store.RemoteObject{}, false +} + +// wantFingerprint is what a native push records for body's bytes on b: the +// BLAKE3 a local read-back confirmed, or the server's sha256. +func wantFingerprint(b contentBackend, body string) (string, string) { + if b.name == localContent.name { + return store.ChecksumAlgoBlake3, blake3Hex(body) + } + sum := sha256.Sum256([]byte(body)) + return "sha256", hex.EncodeToString(sum[:]) +} + +// TestNativeContentPushWithoutRclone: both content layouts push to a local +// disk and to an sftp server with no rclone wrapper. Every artifact lands +// at its name with its bytes, records the fingerprint its landing confirmed +// — a read-back BLAKE3 locally, the server's sha256 over sftp — and the +// vector advances as fingerprint-verified. The next push clears the first +// run's staging. +func TestNativeContentPushWithoutRclone(t *testing.T) { + for _, b := range contentBackends { + for _, layout := range contentLayouts { + t.Run(b.name+"/"+layout, func(t *testing.T) { + f := setupNativeContentFixture(t, b, layout) + f.write(t, "a.txt", "alpha") + f.write(t, "big.txt", "a larger file") + f.index(t) + first := f.mustPush(t) + + if got, err := os.ReadFile(f.objectPath("a larger file")); err != nil || string(got) != "a larger file" { + t.Fatalf("object = %q, %v", got, err) + } + obj, ok := f.remoteObject(t, "a larger file") + algo, value := wantFingerprint(b, "a larger file") + if !ok || obj.ChecksumAlgo.String != algo || obj.Checksum.String != value || !obj.VerifiedAtNs.Valid { + t.Fatalf("remote object = %+v, want %s %s recorded at landing", obj, algo, value) + } + segment := filepath.Join(f.dst, "pics", ManifestDirName, fmt.Sprintf("run-%d", first.RunID)) + if _, err := os.Stat(segment); err != nil { + t.Fatalf("manifest segment: %v", err) + } + if layout == config.LayoutPacked { + if _, err := os.Stat(filepath.Join(f.dst, PacksDirName, fmt.Sprintf("map-%d", first.RunID))); err != nil { + t.Fatalf("placement map: %v", err) + } + if _, err := os.Stat(f.objectPath("alpha")); err == nil { + t.Fatal("content under the threshold landed as an object") + } + } + if comps := volumeComponents(t, f.store, "pics", "vault"); len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodFingerprint { + t.Fatalf("vector = %+v, want one fingerprint-verified component", comps) + } + + f.mustPush(t) + if _, err := os.Stat(filepath.Join(f.dst, stagingName("pics", first.RunID, ""))); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("the next push left the first run's staging: %v", err) + } + }) + } + } +} + +// TestNativeContentWithoutServerHash: an sftp server that runs no programs +// still takes every artifact, whole, but fingerprints nothing: the objects +// stay pending with a warning and the vector stays presence+size. +func TestNativeContentWithoutServerHash(t *testing.T) { + f := setupNativeContentFixture(t, sftpContentNoPrograms, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + rep := f.mustPush(t) + if obj, ok := f.remoteObject(t, "alpha"); !ok || obj.Checksum.Valid { + t.Fatalf("remote object = %+v, want recorded with a pending fingerprint", obj) + } + if !strings.Contains(strings.Join(rep.Warnings, "\n"), "without a fingerprint") { + t.Fatalf("warnings = %v, want the pending fingerprints named", rep.Warnings) + } + if comps := volumeComponents(t, f.store, "pics", "vault"); len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodPresenceSize { + t.Fatalf("vector = %+v, want one presence+size component", comps) + } +} + +// TestNativeContentAdoptsAnArtifactItAlreadyLanded: a push that crashed +// between landing an object and recording it leaves the object at its +// name. The next push finds it there, confirms its bytes, and records it +// instead of replacing it. +func TestNativeContentAdoptsAnArtifactItAlreadyLanded(t *testing.T) { + for _, b := range contentBackends { + t.Run(b.name, func(t *testing.T) { + f := setupNativeContentFixture(t, b, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + if _, err := f.pushCrashing(t, func(c transportCall) bool { + return c.op == "rename" && strings.HasPrefix(c.to, ObjectsDirName+"/") + }); err == nil { + t.Fatal("the crashing push succeeded") + } + if _, err := os.Stat(f.objectPath("alpha")); err != nil { + t.Fatalf("the crash left no object: %v", err) + } + if _, ok := f.remoteObject(t, "alpha"); ok { + t.Fatal("the crashed push recorded the object") + } + + f.mustPush(t) + obj, ok := f.remoteObject(t, "alpha") + algo, value := wantFingerprint(b, "alpha") + if !ok || obj.ChecksumAlgo.String != algo || obj.Checksum.String != value { + t.Fatalf("remote object = %+v, want the landed object adopted with %s %s", obj, algo, value) + } + }) + } +} + +// TestNativeContentRefusesOtherBytesAtAnArtifactName: bytes squirrel did +// not record sitting at an object's name are never replaced: the object +// fails, the push fails before its segment, and the bytes stay. +func TestNativeContentRefusesOtherBytesAtAnArtifactName(t *testing.T) { + f := setupNativeContentFixture(t, localContent, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + if err := os.MkdirAll(filepath.Join(f.dst, ObjectsDirName), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.objectPath("alpha"), []byte("other"), 0o644); err != nil { + t.Fatal(err) + } + rep, err := f.push(t, Options{}) + if err == nil || len(rep.RcloneResult.FailedFiles) != 1 || !strings.Contains(rep.RcloneResult.FailedFiles[0].Message, errReadBackMismatch.Error()) { + t.Fatalf("push: err=%v failed=%+v, want the object refused as other bytes", err, rep.RcloneResult.FailedFiles) + } + if got, _ := os.ReadFile(f.objectPath("alpha")); string(got) != "other" { + t.Fatalf("object = %q, want the bytes that were there left alone", got) + } + if _, ok := f.remoteObject(t, "alpha"); ok { + t.Fatal("the refused object was recorded") + } +} + +// TestNativeContentMarkerGate: a native content destination is gated on +// its volume marker, as a native mirror is, and --init writes it through +// the transport. On a local disk --init also creates a missing root. +func TestNativeContentMarkerGate(t *testing.T) { + for _, b := range contentBackends { + t.Run(b.name, func(t *testing.T) { + f := setupNativeContentFixture(t, b, config.LayoutPacked) + bare := filepath.Join(f.dst, "pics") + if b.name == localContent.name { + bare = f.dst + } + if err := os.RemoveAll(bare); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "alpha") + f.index(t) + if _, err := f.push(t, Options{}); !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "--init") { + t.Fatalf("push without a marker = %v, want a refusal naming --init", err) + } + if rep, err := f.push(t, Options{Init: true}); err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("--init push: status=%q err=%v", rep.Status, err) + } + if err := volmark.Validate(filepath.Join(f.dst, "pics"), "pics"); err != nil { + t.Fatalf("marker after --init: %v", err) + } + }) + } +} + +// TestNativeContentDriftLeavesNothingAtTheName: a source whose bytes +// drifted from their indexed hash is refused after staging; nothing lands +// at the object's name, and the next push clears the staged copy and lands +// the honest bytes. +func TestNativeContentDriftLeavesNothingAtTheName(t *testing.T) { + f := setupNativeContentFixture(t, localContent, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + src := filepath.Join(f.src, "a.txt") + fi, err := os.Stat(src) + if err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "ALPHA") + if err := os.Chtimes(src, fi.ModTime(), fi.ModTime()); err != nil { + t.Fatal(err) + } + rep, err := f.push(t, Options{}) + if err == nil || !strings.Contains(err.Error(), "drifting") { + t.Fatalf("push = %v, want a drift refusal", err) + } + if _, err := os.Stat(f.objectPath("alpha")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("drifted bytes reached the object name: %v", err) + } + f.write(t, "a.txt", "alpha") + if err := os.Chtimes(src, fi.ModTime(), fi.ModTime()); err != nil { + t.Fatal(err) + } + f.mustPush(t) + if got, _ := os.ReadFile(f.objectPath("alpha")); string(got) != "alpha" { + t.Fatalf("object = %q, want the honest bytes", got) + } + if _, err := os.Stat(filepath.Join(f.dst, stagingName("pics", rep.RunID, ""))); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("the drifted run's staging is still there: %v", err) + } +} diff --git a/sync/destination_marker.go b/sync/destination_marker.go index b599087..158b818 100644 --- a/sync/destination_marker.go +++ b/sync/destination_marker.go @@ -22,12 +22,11 @@ const maxMarkerBytes = 64 << 10 // A missing marker is written only under init, and a marker naming another // volume, or one that does not parse, is always refused and never // overwritten. A local root that does not exist yet is created under init, -// so a first push can land on an empty disk. +// so a first push can land on an empty disk, and refused like a missing +// marker otherwise. func (h *destinationRoot) ensureMarker(ctx context.Context, init bool) error { - if init && h.dest.Type == "local" { - if err := os.MkdirAll(h.dest.Root, 0o755); err != nil { - return fmt.Errorf("destination %q: create root %s: %w", h.dest.Name, h.dest.Root, err) - } + if err := h.ensureLocalRoot(init); err != nil { + return err } tr, err := h.guarded(ctx, nameGuard{volumeDir: h.volumeDir, bootstrap: init}) if err != nil { @@ -46,6 +45,23 @@ func (h *destinationRoot) ensureMarker(ctx context.Context, init bool) error { return h.writeMarker(ctx, tr, name) } +func (h *destinationRoot) ensureLocalRoot(init bool) error { + if h.dest.Type != "local" { + return nil + } + _, err := os.Stat(h.dest.Root) + switch { + case !errors.Is(err, fs.ErrNotExist): + return nil + case init: + if err := os.MkdirAll(h.dest.Root, 0o755); err != nil { + return fmt.Errorf("destination %q: create root %s: %w", h.dest.Name, h.dest.Root, err) + } + return nil + } + return fmt.Errorf("destination %q has no root at %s — re-run with --init to create it (refusing in case the disk is not mounted): %w", h.dest.Name, h.dest.Root, ErrRefused) +} + func (h *destinationRoot) checkMarker(name string, data []byte) error { m, err := volmark.Parse(data) if err != nil { diff --git a/sync/handler.go b/sync/handler.go index 0c5f065..d585fb4 100644 --- a/sync/handler.go +++ b/sync/handler.go @@ -125,15 +125,17 @@ func HandlerFor(s *store.Store, tools Tools, p Pair) (Handler, error) { } return &kopiaHandler{store: s, kopia: tools.Kopia, vol: p.Volume, dest: p.Destination}, nil case p.Destination.Layout == config.LayoutPacked: - if tools.Rclone == nil { - return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) + pusher, err := contentPusherFor(s, tools, p) + if err != nil { + return nil, err } - return &packedHandler{rcloneContentPusher(s, tools.Rclone, p)}, nil + return &packedHandler{pusher}, nil case p.Destination.Layout == config.LayoutContentAddressed: - if tools.Rclone == nil { - return nil, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) + pusher, err := contentPusherFor(s, tools, p) + if err != nil { + return nil, err } - return &contentAddressedHandler{rcloneContentPusher(s, tools.Rclone, p)}, nil + return &contentAddressedHandler{pusher}, nil case p.Destination.NativeMirror(): return &mirrorHandler{destinationRoot: newDestinationRoot(s, p.Destination, p.Volume.Name), vol: p.Volume}, nil default: @@ -144,10 +146,19 @@ func HandlerFor(s *store.Store, tools Tools, p Pair) (Handler, error) { } } -// rcloneContentPusher is a content layout's push through rclone. -func rcloneContentPusher(s *store.Store, rcl *Rclone, p Pair) contentPusher { - art := &rcloneArtifacts{store: s, rcl: rcl, vol: p.Volume, dest: p.Destination} - return contentPusher{store: s, vol: p.Volume, dest: p.Destination, art: art} +// contentPusherFor is a content layout's push: through squirrel's own +// transport onto a native destination, through rclone onto any other. +func contentPusherFor(s *store.Store, tools Tools, p Pair) (contentPusher, error) { + pusher := contentPusher{store: s, vol: p.Volume, dest: p.Destination} + switch { + case p.Destination.Native(): + pusher.art = &transportArtifacts{destinationRoot: newDestinationRoot(s, p.Destination, p.Volume.Name)} + case tools.Rclone == nil: + return contentPusher{}, fmt.Errorf("destination %q: rclone wrapper is required", p.Destination.Name) + default: + pusher.art = &rcloneArtifacts{store: s, rcl: tools.Rclone, vol: p.Volume, dest: p.Destination} + } + return pusher, nil } // openDestinationTransport opens a native mirror's destination root: a diff --git a/sync/mirror_test.go b/sync/mirror_test.go index 10d9d4e..f4e277b 100644 --- a/sync/mirror_test.go +++ b/sync/mirror_test.go @@ -49,14 +49,22 @@ var ( // sftpBackend serves the destination root from an in-process sftp // server, so the fixture reads what landed straight off the disk. sftpBackend = mirrorBackend{"sftp", func(t *testing.T, dst string) string { - srv := startSFTPServer(t) - host, port, _ := net.SplitHostPort(srv.addr) - return fmt.Sprintf("type = \"sftp\"\nroot = %q\nhost = %q\nport = %q\nuser = \"u\"\npassword = \"p\"\nknown_hosts_file = %q\n", - dst, host, port, srv.knownHosts(t, srv.hostKeys[0].PublicKey())) + return sftpSettings(t, dst, nil) }} mirrorBackends = []mirrorBackend{localBackend, sftpBackend} ) +// sftpSettings are the settings of a destination rooted at dst on a fresh +// in-process sftp server that runs the given hash commands. +func sftpSettings(t *testing.T, dst string, commands map[string]string) string { + t.Helper() + srv := startSFTPServer(t) + srv.runsHashCommands(commands) + host, port, _ := net.SplitHostPort(srv.addr) + return fmt.Sprintf("type = \"sftp\"\nroot = %q\nhost = %q\nport = %q\nuser = \"u\"\npassword = \"p\"\nknown_hosts_file = %q\n", + dst, host, port, srv.knownHosts(t, srv.hostKeys[0].PublicKey())) +} + func setupMirrorFixture(t *testing.T) *mirrorFixture { t.Helper() return setupMirrorFixtureOn(t, localBackend) diff --git a/sync/naming_test.go b/sync/naming_test.go index e68f654..acacfa6 100644 --- a/sync/naming_test.go +++ b/sync/naming_test.go @@ -51,16 +51,14 @@ func TestKeyedNamesDiscloseNothing(t *testing.T) { // no key to derive from, so the append-only layouts name artifacts by // content hash and write no naming marker. func TestPlainDestinationKeepsContentHashNames(t *testing.T) { - f := setupPlainContentAddressedFixture(t) + f := setupNativeContentFixture(t, localContent, config.LayoutContentAddressed) f.write(t, "a.txt", "alpha") f.index(t) - if _, err := f.sync(t); err != nil { - t.Fatalf("sync: %v", err) - } - if _, err := os.Stat(f.remotePath(ObjectsDirName, blake3Hex("alpha"))); err != nil { + f.mustPush(t) + if _, err := os.Stat(f.objectPath("alpha")); err != nil { t.Fatalf("object not at its content-hash name: %v", err) } - if _, err := os.Stat(f.remotePath(namingMarkerName)); err == nil { + if _, err := os.Stat(filepath.Join(f.dst, namingMarkerName)); err == nil { t.Fatalf("an unencrypted destination wrote a %s marker", namingMarkerName) } } diff --git a/sync/packed.go b/sync/packed.go index 845f323..66d31c2 100644 --- a/sync/packed.go +++ b/sync/packed.go @@ -97,7 +97,7 @@ type PackPreview struct { SizeBand int64 // destination pack_size (target compressed pack size) } -// packedHandler pushes a volume to a packed rclone destination. Content at +// packedHandler pushes a volume to a packed destination. Content at // or above dest.PackThreshold lands as a per-hash object exactly as the // content-addressed layout does (reusing contentPusher's object path); // content below the threshold is bundled into immutable tar.zst packs. Each From 603141913f6d450f925713e643408d023b34c7c3 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:23:12 +0200 Subject: [PATCH 35/61] sync: restore and recover native content destinations through the transport An archive restore from a native content-addressed or packed destination fetches every object and pack through one read-only transport, and a dry run opens none. recover's snapshot discovery and fetch cover every native destination, not only mirrors. --- sync/content_native_test.go | 54 +++++++++++++++++++++++++++ sync/recover.go | 28 ++++++++------ sync/restore_archive.go | 73 ++++++++++++++++++++++++++++--------- sync/sync.go | 2 +- 4 files changed, 128 insertions(+), 29 deletions(-) diff --git a/sync/content_native_test.go b/sync/content_native_test.go index deef493..a671669 100644 --- a/sync/content_native_test.go +++ b/sync/content_native_test.go @@ -372,3 +372,57 @@ func TestNativeContentDriftLeavesNothingAtTheName(t *testing.T) { t.Fatalf("the drifted run's staging is still there: %v", err) } } + +// TestNativeContentRestoreWithoutRclone: both content layouts restore from +// a local disk and from an sftp server with no rclone wrapper, every byte +// re-hashed on the way down. +func TestNativeContentRestoreWithoutRclone(t *testing.T) { + for _, b := range contentBackends { + for _, layout := range contentLayouts { + t.Run(b.name+"/"+layout, func(t *testing.T) { + f := setupNativeContentFixture(t, b, layout) + f.write(t, "a.txt", "alpha") + f.write(t, "2024/big.txt", "a larger file") + f.index(t) + f.mustPush(t) + to := t.TempDir() + rep, err := Restore(context.Background(), f.store, nil, f.pair.Volume, f.pair.Destination, RestoreOptions{ToPath: to}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("restore: status=%q err=%v", rep.Status, err) + } + for rel, want := range map[string]string{"a.txt": "alpha", "2024/big.txt": "a larger file"} { + if got, err := os.ReadFile(filepath.Join(to, filepath.FromSlash(rel))); err != nil || string(got) != want { + t.Fatalf("%s = %q, %v; want %q", rel, got, err, want) + } + } + }) + } + } +} + +// TestNativeContentRideAlongAndRecover: a native content push rides the +// index snapshot along through the transport, and recover's discovery lists +// and fetches it without rclone. +func TestNativeContentRideAlongAndRecover(t *testing.T) { + for _, b := range contentBackends { + t.Run(b.name, func(t *testing.T) { + f := setupNativeContentFixture(t, b, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + sn := NewSnapshotter(f.store, SnapshotConfig{Dir: t.TempDir(), Keep: 7, Cloud: true, CloudKeep: 7}) + rep, err := f.push(t, Options{Snapshot: sn}) + if err != nil || rep.SnapshotErr != nil { + t.Fatalf("push: err=%v snapshot=%v", err, rep.SnapshotErr) + } + ctx := context.Background() + snaps, err := DiscoverIndexSnapshots(ctx, nil, f.pair.Destination, []string{"pics"}) + if err != nil || len(snaps) != 1 || snaps[0].RunID != rep.RunID { + t.Fatalf("snapshots = %+v, %v; want run %d's", snaps, err, rep.RunID) + } + local := filepath.Join(t.TempDir(), "index.db") + if err := FetchIndexSnapshot(ctx, nil, f.pair.Destination, snaps[0], local); err != nil { + t.Fatalf("FetchIndexSnapshot: %v", err) + } + }) + } +} diff --git a/sync/recover.go b/sync/recover.go index 9e2dd59..30015d0 100644 --- a/sync/recover.go +++ b/sync/recover.go @@ -46,15 +46,15 @@ func (s IndexSnapshot) Age(now time.Time) (time.Duration, bool) { // DiscoverIndexSnapshots lists the ride-along index snapshots a destination // holds for each named volume, newest first, then by volume. It is // read-only: it lists, it does not fetch, so an operator can be told what -// is recoverable before anything is touched. A native mirror is listed -// through squirrel's own transport, so rcl may be nil for one. +// is recoverable before anything is touched. A native destination is +// listed through squirrel's own transport, so rcl may be nil for one. // // A volume directory that does not exist yields no snapshots rather than an // error — a destination that has simply never carried a given volume is a // normal answer to "what do you have", not a failure. func DiscoverIndexSnapshots(ctx context.Context, rcl *Rclone, dest *config.Destination, volumes []string) ([]IndexSnapshot, error) { list := func(vol string) ([]string, error) { return listSnapshotsStrict(ctx, rcl, indexDirURI(dest, vol)) } - if dest.NativeMirror() { + if dest.Native() { tr, err := openReadOnly(ctx, dest) if err != nil { return nil, err @@ -145,10 +145,10 @@ func parseSnapshotName(volume, name string) IndexSnapshot { // exist yet. It only moves the file; validating that the bytes are a // usable index at this binary's schema version is // store.PreflightCheckSnapshot's job, and the caller runs it before letting -// the file near the live database. rcl may be nil for a native mirror. +// the file near the live database. rcl may be nil for a native destination. func FetchIndexSnapshot(ctx context.Context, rcl *Rclone, dest *config.Destination, snap IndexSnapshot, localPath string) error { var err error - if dest.NativeMirror() { + if dest.Native() { err = fetchThroughTransport(ctx, dest, path.Join(snap.Volume, IndexDirName, snap.Name), localPath) } else { err = rcl.copyTo(ctx, indexDirURI(dest, snap.Volume)+"/"+snap.Name, localPath) @@ -165,18 +165,24 @@ func fetchThroughTransport(ctx context.Context, dest *config.Destination, name, return err } defer func() { _ = tr.Close() }() - rc, err := tr.Get(ctx, name) - if err != nil { - return err - } - defer func() { _ = rc.Close() }() f, err := os.OpenFile(localPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { return err } - if _, err := io.CopyBuffer(f, ctxReader{ctx: ctx, r: rc}, make([]byte, copyBufferSize)); err != nil { + if err := copyOut(ctx, tr, name, f); err != nil { _ = f.Close() return err } return f.Close() } + +// copyOut streams the file at name on tr into w. +func copyOut(ctx context.Context, tr transport, name string, w io.Writer) error { + rc, err := tr.Get(ctx, name) + if err != nil { + return err + } + defer func() { _ = rc.Close() }() + _, err = io.CopyBuffer(w, ctxReader{ctx: ctx, r: rc}, make([]byte, copyBufferSize)) + return err +} diff --git a/sync/restore_archive.go b/sync/restore_archive.go index ddbb1f7..2ba50ff 100644 --- a/sync/restore_archive.go +++ b/sync/restore_archive.go @@ -25,18 +25,22 @@ import ( // destination. It resolves each requested path to a content hash from the // local index, locates the bytes (a per-hash object under objects/, or a // member inside a tar.zst pack under packs/), fetches through the same -// rclone (crypt) read path sync uses, and re-hashes every extracted -// content to BLAKE3 before writing — the misplacement/corruption check the -// offset/length pack slicing needs. Packs are fetched once per pack and -// every requested member is extracted from that single stream. +// read path sync writes through — squirrel's own transport on a native +// destination, rclone (and its crypt overlay) otherwise — and re-hashes +// every extracted content to BLAKE3 before writing: the +// misplacement/corruption check the offset/length pack slicing needs. +// Packs are fetched once per pack and every requested member is extracted +// from that single stream. type archiveRestore struct { - store *store.Store - rcl *Rclone - vol *config.Volume - dest *config.Destination - volID int64 - placer restorePlacer - dryRun bool + store *store.Store + // fetchTo copies one destination-root artifact over the local file at + // localPath. + fetchTo func(ctx context.Context, name, localPath string) error + vol *config.Volume + dest *config.Destination + volID int64 + placer restorePlacer + dryRun bool } // restoreArchive orchestrates one content-addressed or packed restore: it @@ -46,8 +50,14 @@ type archiveRestore struct { // reason. Read-only against the index and destination throughout. func restoreArchive(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volume, dest *config.Destination, volID, runID int64, targetInPlace bool, opts RestoreOptions, rep *Report) error { rep.RunID = runID + fetchTo, release, err := archiveFetcher(ctx, rcl, dest, opts.DryRun) + if err != nil { + finishRestore(ctx, s, opts.DryRun, runID, rep, err) + return err + } + defer release() ar := &archiveRestore{ - store: s, rcl: rcl, vol: vol, dest: dest, volID: volID, + store: s, fetchTo: fetchTo, vol: vol, dest: dest, volID: volID, placer: newRestorePlacer(vol, runID, targetInPlace, opts), dryRun: opts.DryRun, } runErr := ar.run(ctx, rep, opts.IncludeFromFile) @@ -55,6 +65,37 @@ func restoreArchive(ctx context.Context, s *store.Store, rcl *Rclone, vol *confi return runErr } +// archiveFetcher is how a restore reads dest's artifacts: through one +// read-only transport for the whole restore on a native destination, +// through rclone otherwise. A dry run fetches nothing, so it opens nothing. +// release closes what it opened. +func archiveFetcher(ctx context.Context, rcl *Rclone, dest *config.Destination, dryRun bool) (func(context.Context, string, string) error, func(), error) { + if !dest.Native() { + return func(ctx context.Context, name, localPath string) error { + return rcl.copyTo(ctx, remoteSubpathURI(dest, name), localPath, checkersArgs(dest)...) + }, func() {}, nil + } + if dryRun { + return nil, func() {}, nil + } + tr, err := openReadOnly(ctx, dest) + if err != nil { + return nil, nil, err + } + fetch := func(ctx context.Context, name, localPath string) error { + f, err := os.OpenFile(localPath, os.O_WRONLY|os.O_TRUNC, 0) + if err != nil { + return err + } + if err := copyOut(ctx, tr, name, f); err != nil { + _ = f.Close() + return err + } + return f.Close() + } + return fetch, func() { _ = tr.Close() }, nil +} + // newRestorePlacer targets the volume's path, or --to. It preserves what // it replaces only for an in-place restore that asked to (--in-place), // mirroring the mirror layout's history contract. @@ -330,9 +371,8 @@ func (ar *archiveRestore) readMember(r io.Reader, length int64) (string, []byte, } // fetch pulls one destination-root subpath (objects/ or -// packs/) to a local temp file through the same rclone read path — -// crypt overlay included — the push uses, and returns the temp path. The -// caller removes it. +// packs/) to a local temp file through the same read path the push +// writes through, and returns the temp path. The caller removes it. func (ar *archiveRestore) fetch(ctx context.Context, subpath string) (string, error) { tmp, err := os.CreateTemp("", "squirrel-restore-*") if err != nil { @@ -342,8 +382,7 @@ func (ar *archiveRestore) fetch(ctx context.Context, subpath string) (string, er _ = os.Remove(tmp.Name()) return "", fmt.Errorf("stage download: %w", err) } - uri := remoteSubpathURI(ar.dest, subpath) - if err := ar.rcl.copyTo(ctx, uri, tmp.Name(), checkersArgs(ar.dest)...); err != nil { + if err := ar.fetchTo(ctx, subpath, tmp.Name()); err != nil { _ = os.Remove(tmp.Name()) return "", fmt.Errorf("fetch %s: %w", subpath, err) } diff --git a/sync/sync.go b/sync/sync.go index 30f27ca..5e021d2 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -1006,7 +1006,7 @@ func Restore(ctx context.Context, s *store.Store, rcl *Rclone, vol *config.Volum // --shallow or a crypt overlay; an rclone mirror pull records rclone's // effective comparison instead. archive := dest.Layout == config.LayoutContentAddressed || dest.Layout == config.LayoutPacked - shallow := EffectiveShallow(dest, opts.Shallow) && !archive && !dest.NativeMirror() + shallow := EffectiveShallow(dest, opts.Shallow) && !archive && !dest.Native() runID, err := beginRestoreRun(ctx, s, opts.DryRun, v.ID, dest.Name, shallow) if err != nil { return rep, err From 80126f895ca101206c71b4dc07c944f2dbe36fb4 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:27:24 +0200 Subject: [PATCH 36/61] sync: verify native content destinations through the transport A verify pass over a native content-addressed or packed destination lists objects/ and packs/ through the transport and re-reads each recorded artifact: BLAKE3 (and any other hash its row recorded) on a local disk, the server's hash command on sftp. On a plain destination a BLAKE3 that contradicts the artifact's name is a mismatch on every backend. --- design/native-mirror.md | 7 +++ sync/content_native_test.go | 73 ++++++++++++++++++++++++ sync/verify_native.go | 108 ++++++++++++++++++++++++++++++++++++ sync/verify_remote.go | 83 +++++++++++++++++++++++---- 4 files changed, 260 insertions(+), 11 deletions(-) create mode 100644 sync/verify_native.go diff --git a/design/native-mirror.md b/design/native-mirror.md index 4a5dc77..ab16ee3 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -617,6 +617,13 @@ gcs. Each artifact: confirmed instead (downloaded and hashed when the server runs no command) and recorded, or the artifact fails. Squirrel never replaces it. +`squirrel verify` reads these destinations through the transport too +(`sync/verify_native.go`): it lists `objects/` and `packs/` and re-reads +every recorded artifact — through BLAKE3, and through any other hash its row +recorded, on a local disk; through the server's hash command on sftp. On a +plain destination a BLAKE3 that differs from what the name says (an object's +content hash, a pack's key) is a mismatch, whichever backend reported it. + The staged copy of a failed artifact goes with the run's staging at the next push's reconcile. The content layouts' guard commits only onto artifact names and displaces nothing (section 3). Both native content layouts are gated on diff --git a/sync/content_native_test.go b/sync/content_native_test.go index a671669..e2818a5 100644 --- a/sync/content_native_test.go +++ b/sync/content_native_test.go @@ -426,3 +426,76 @@ func TestNativeContentRideAlongAndRecover(t *testing.T) { }) } } + +func (f *nativeContentFixture) verify(t *testing.T) RemoteVerifyReport { + t.Helper() + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err != nil { + t.Fatalf("VerifyRemote: %v", err) + } + return rep +} + +// TestNativeContentVerifyWithoutRclone: verify re-reads a native content +// destination through the transport — BLAKE3 against the content hash or +// pack key on a local disk, the server's hash command over sftp — and +// finds an artifact changed in place or gone. +func TestNativeContentVerifyWithoutRclone(t *testing.T) { + for _, b := range contentBackends { + for _, layout := range contentLayouts { + t.Run(b.name+"/"+layout, func(t *testing.T) { + f := setupNativeContentFixture(t, b, layout) + f.write(t, "a.txt", "alpha") + f.write(t, "big.txt", "a larger file") + f.write(t, "gone.txt", "gone, soon") + f.index(t) + f.mustPush(t) + rep := f.verify(t) + objects, packs := 3, 0 + if layout == config.LayoutPacked { + objects, packs = 2, 1 + } + if !rep.Clean() || rep.Verified != objects || rep.PacksVerified != packs { + t.Fatalf("rep = %+v, want a clean pass re-confirming every artifact", rep) + } + + if err := os.WriteFile(f.objectPath("a larger file"), []byte("A LARGER FILE"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Remove(f.objectPath("gone, soon")); err != nil { + t.Fatal(err) + } + if layout == config.LayoutPacked { + f.flipPack(t) + } + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err != nil || len(rep.Mismatched) != 1 || len(rep.Missing) != 1 || len(rep.PackMismatched) != packs || !rep.AlarmRaised { + t.Fatalf("rep = %+v, %v; want one object changed, one gone, every pack changed, and the alarm raised", rep, err) + } + }) + } + } +} + +// flipPack changes the first byte of every pack in place. +func (f *nativeContentFixture) flipPack(t *testing.T) { + t.Helper() + entries, err := os.ReadDir(filepath.Join(f.dst, PacksDirName)) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if strings.HasPrefix(e.Name(), packMapPrefix) { + continue + } + p := filepath.Join(f.dst, PacksDirName, e.Name()) + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + b[0] ^= 0xff + if err := os.WriteFile(p, b, 0o644); err != nil { + t.Fatal(err) + } + } +} diff --git a/sync/verify_native.go b/sync/verify_native.go new file mode 100644 index 0000000..9c59d20 --- /dev/null +++ b/sync/verify_native.go @@ -0,0 +1,108 @@ +package sync + +import ( + "context" + "encoding/hex" + "errors" + "fmt" + "hash" + "io" + "io/fs" + "path" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" +) + +// transportChecksums reads a native destination's checksums through +// squirrel's own transport: a local disk's artifacts are read back through +// BLAKE3, and through any other hash their upload rows recorded; an sftp +// server's are hashed by its hash command, and fingerprint nothing on a +// server without one. +type transportChecksums struct { + tr transport + dest *config.Destination +} + +func (c transportChecksums) objects(ctx context.Context, rows []store.RemoteObjectRecord) (map[string]map[string]string, error) { + names := namerFor(c.dest) + want := make(map[string]string, len(rows)) + for _, r := range rows { + want[names.object(r.Blake3)] = r.ChecksumAlgo.String + } + return c.read(ctx, ObjectsDirName, want) +} + +func (c transportChecksums) packs(ctx context.Context, packs []store.RemotePackRecord) (map[string]map[string]string, error) { + names := namerFor(c.dest) + want := make(map[string]string, len(packs)) + for _, p := range packs { + want[names.pack(p.PackKey)] = p.ChecksumAlgo.String + } + return c.read(ctx, PacksDirName, want) +} + +// read lists dir and hashes each file a row recorded; want maps a +// basename to the algo its row recorded, "" while pending. A dir that does +// not exist holds nothing. +func (c transportChecksums) read(ctx context.Context, dir string, want map[string]string) (map[string]map[string]string, error) { + entries, err := c.tr.List(ctx, dir) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + out := make(map[string]map[string]string, len(entries)) + for _, e := range entries { + if e.kind != kindFile { + continue + } + recorded, ok := want[e.name] + if !ok { + out[e.name] = nil + continue + } + hashes, err := c.hash(ctx, path.Join(dir, e.name), recorded) + if err != nil { + return nil, fmt.Errorf("hash %s: %w", e.name, err) + } + out[e.name] = hashes + } + return out, nil +} + +// hash is the checksums of the file at name: its BLAKE3, and the hash its +// row recorded when this machine computes that one too, read back from a +// local disk; the server's hash command's answer on sftp, none when the +// server runs no command squirrel trusts. +func (c transportChecksums) hash(ctx context.Context, name, recorded string) (map[string]string, error) { + if !readsBack(c.dest) { + cs, err := c.tr.ServerHash(ctx, name) + if errors.Is(err, errNoServerHash) { + return map[string]string{}, nil + } + if err != nil { + return nil, err + } + return map[string]string{cs.Algo: cs.Value}, nil + } + hashers := map[string]hash.Hash{store.ChecksumAlgoBlake3: blake3.New()} + if h := newArtifactHash(recorded); h != nil { + hashers[recorded] = h + } + writers := make([]io.Writer, 0, len(hashers)) + for _, h := range hashers { + writers = append(writers, h) + } + if err := copyOut(ctx, c.tr, name, io.MultiWriter(writers...)); err != nil { + return nil, err + } + out := make(map[string]string, len(hashers)) + for algo, h := range hashers { + out[algo] = hex.EncodeToString(h.Sum(nil)) + } + return out, nil +} diff --git a/sync/verify_remote.go b/sync/verify_remote.go index 8e0860d..e2a7ef9 100644 --- a/sync/verify_remote.go +++ b/sync/verify_remote.go @@ -114,10 +114,12 @@ func (r RemoteVerifyReport) failures() int { // against the fingerprints recorded at upload time. Matches stamp // verified_at_ns; objects with a pending fingerprint get one recorded; // mismatches and missing objects land loudly on the report. The pass -// reads destination metadata and updates local verification state only. +// reads the destination and updates local verification state only. // -// A native mirror is checked through squirrel's own transport instead -// (verifyMirror), so rcl may be nil for one. +// A native destination is read through squirrel's own transport instead, +// so rcl may be nil for one: a local disk's artifacts are read back through +// BLAKE3, an sftp server's hashed by its hash command, and a native +// mirror's copies are checked by verifyMirror. // // The pass is recorded as a kind='audit' run: success when every object // checked out, partial when objects mismatched or went missing, failed @@ -155,7 +157,7 @@ func VerifyRemote(ctx context.Context, s *store.Store, rcl *Rclone, dest *config } rep.RunID = runID - verifyErr := verifyRecorded(ctx, s, rcl, dest, rows, packs, &rep) + verifyErr := verifyThrough(ctx, s, rcl, dest, rows, packs, &rep) if err := recordVerifyOutcome(ctx, s, &rep, verifyErr); err != nil { return rep, err } @@ -197,28 +199,64 @@ func upgradeFingerprintVectors(ctx context.Context, s *store.Store, destination return nil } +// checksumSource reads the checksums a verify pass compares for a +// destination's recorded objects and packs, keyed by basename then hash +// name; a stored artifact nobody recorded maps to no hashes. +type checksumSource interface { + objects(ctx context.Context, rows []store.RemoteObjectRecord) (map[string]map[string]string, error) + packs(ctx context.Context, packs []store.RemotePackRecord) (map[string]map[string]string, error) +} + +// verifyThrough runs the sweeps against dest through squirrel's own +// transport on a native destination, through rclone (and the S3 API) +// otherwise. +func verifyThrough(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination, rows []store.RemoteObjectRecord, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { + if !dest.Native() { + return verifyRecorded(ctx, s, rcloneChecksums{rcl: rcl, dest: dest}, dest, rows, packs, rep) + } + tr, err := openReadOnly(ctx, dest) + if err != nil { + return err + } + defer func() { _ = tr.Close() }() + return verifyRecorded(ctx, s, transportChecksums{tr: tr, dest: dest}, dest, rows, packs, rep) +} + // verifyRecorded sweeps a destination's recorded content objects (the // large-file per-object sweep, shared with content-addressed) and, for a // packed destination, its recorded packs — one fingerprint check per pack // vouching for all its members. Either sweep can be empty. -func verifyRecorded(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination, rows []store.RemoteObjectRecord, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { +func verifyRecorded(ctx context.Context, s *store.Store, src checksumSource, dest *config.Destination, rows []store.RemoteObjectRecord, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { if len(rows) > 0 { - if err := verifyRecordedObjects(ctx, s, rcl, dest, rows, rep); err != nil { + if err := verifyRecordedObjects(ctx, s, src, dest, rows, rep); err != nil { return err } } if len(packs) > 0 { - if err := verifyRecordedPacks(ctx, s, rcl, dest, packs, rep); err != nil { + if err := verifyRecordedPacks(ctx, s, src, dest, packs, rep); err != nil { return err } } return nil } +// contentMismatch is the finding when a plain destination reports the +// BLAKE3 of an artifact whose name says what its BLAKE3 must be (an +// object's content hash, a pack's key) and the two differ. It holds for +// any backend that exposes BLAKE3; behind crypt the stored bytes are +// ciphertext, so it never applies there. +func contentMismatch(dest *config.Destination, hashes map[string]string, want []byte) (RemoteObjectMismatch, bool) { + got := hashes[store.ChecksumAlgoBlake3] + if dest.Crypt != nil || got == "" || got == hex.EncodeToString(want) { + return RemoteObjectMismatch{}, false + } + return RemoteObjectMismatch{Hash: hex.EncodeToString(want), Algo: store.ChecksumAlgoBlake3, Recorded: hex.EncodeToString(want), Actual: got}, true +} + // verifyRecordedObjects compares the remote listing against the recorded // rows and applies the per-object outcome to the store and the report. -func verifyRecordedObjects(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination, rows []store.RemoteObjectRecord, rep *RemoteVerifyReport) error { - byName, err := readObjectChecksums(ctx, rcl, dest, rows) +func verifyRecordedObjects(ctx context.Context, s *store.Store, src checksumSource, dest *config.Destination, rows []store.RemoteObjectRecord, rep *RemoteVerifyReport) error { + byName, err := src.objects(ctx, rows) if err != nil { return fmt.Errorf("read object checksums from %q: %w", dest.Name, err) } @@ -232,6 +270,10 @@ func verifyRecordedObjects(ctx context.Context, s *store.Store, rcl *Rclone, des continue } matched++ + if m, bad := contentMismatch(dest, hashes, row.Blake3); bad { + rep.Mismatched = append(rep.Mismatched, m) + continue + } if !row.ChecksumAlgo.Valid { if err := populateFingerprint(ctx, s, dest, row, hashes, rep); err != nil { return err @@ -257,6 +299,21 @@ func verifyRecordedObjects(ctx context.Context, s *store.Store, rcl *Rclone, des return nil } +// rcloneChecksums reads a destination's checksums through rclone, and +// through the S3 API on s3. +type rcloneChecksums struct { + rcl *Rclone + dest *config.Destination +} + +func (c rcloneChecksums) objects(ctx context.Context, rows []store.RemoteObjectRecord) (map[string]map[string]string, error) { + return readObjectChecksums(ctx, c.rcl, c.dest, rows) +} + +func (c rcloneChecksums) packs(ctx context.Context, packs []store.RemotePackRecord) (map[string]map[string]string, error) { + return readPackChecksums(ctx, c.rcl, c.dest, packs) +} + // readObjectChecksums reads the provider checksums verification compares, // keyed by object basename (namer.object) then rclone hash name. s3 reads raw // ETags straight from the S3 API — the only surface exposing a multipart @@ -327,8 +384,8 @@ func verifyObjectHashTypes(dest *config.Destination, rows []store.RemoteObjectRe // recorded pack rows and applies the per-pack outcome. One fingerprint // check per pack vouches for every content it holds, so a packed // destination is swept per pack rather than per member. -func verifyRecordedPacks(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { - byName, err := readPackChecksums(ctx, rcl, dest, packs) +func verifyRecordedPacks(ctx context.Context, s *store.Store, src checksumSource, dest *config.Destination, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { + byName, err := src.packs(ctx, packs) if err != nil { return fmt.Errorf("read pack checksums from %q: %w", dest.Name, err) } @@ -340,6 +397,10 @@ func verifyRecordedPacks(ctx context.Context, s *store.Store, rcl *Rclone, dest rep.PacksMissing = append(rep.PacksMissing, key) continue } + if m, bad := contentMismatch(dest, hashes, row.PackKey); bad { + rep.PackMismatched = append(rep.PackMismatched, m) + continue + } if !row.ChecksumAlgo.Valid { if err := populatePackFingerprint(ctx, s, dest, row, hashes, rep); err != nil { return err From 9164ccae5ff1401f5a4299e23b496ce416c9b179 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:28:49 +0200 Subject: [PATCH 37/61] sync, cmd: reach every native destination without rclone Pair.DrivesRclone and the CLI's rclone lookup key on Destination.Native, so a content-addressed or packed destination on a local disk or a plain sftp server syncs, verifies, restores and recovers with no rclone installed. rclone is left to crypt destinations and s3, b2 and gcs. --- cmd/squirrel/agent_scheduler.go | 4 +-- cmd/squirrel/content_native_test.go | 43 +++++++++++++++++++++++++++++ cmd/squirrel/recover.go | 2 +- cmd/squirrel/sync.go | 6 ++-- cmd/squirrel/verify.go | 2 +- sync/sync.go | 8 +++--- 6 files changed, 54 insertions(+), 11 deletions(-) create mode 100644 cmd/squirrel/content_native_test.go diff --git a/cmd/squirrel/agent_scheduler.go b/cmd/squirrel/agent_scheduler.go index ae840e8..883737b 100644 --- a/cmd/squirrel/agent_scheduler.go +++ b/cmd/squirrel/agent_scheduler.go @@ -83,7 +83,7 @@ func (t *schedulerTools) rebuild(ctx context.Context, cfg *config.Config) error // anyVolumeNeedsScheduledSync reports whether a scheduled sync will // invoke rclone. Only rclone-backed destinations count: a peer node // streams its bytes over the sync API, a kopia destination drives its own -// binary, and squirrel writes a native mirror itself, so a cadence naming +// binary, and squirrel writes a native destination itself, so a cadence naming // only those runs its whole schedule on a host with no rclone installed. func anyVolumeNeedsScheduledSync(cfg *config.Config) bool { for _, v := range cfg.Volumes { @@ -118,7 +118,7 @@ func targetNeedsRclone(cfg *config.Config, target string) bool { // squirrel reaches through rclone has an effective verify cadence — its own // verify_every, or the [agent] verify_every default. Mirrors the scheduler's // own resolution so the rclone wiring lines up with what the scheduler will -// actually fire; a native mirror is verified through squirrel's own +// actually fire; a native destination is verified through squirrel's own // transport. func anyScheduledVerifyNeedsRclone(cfg *config.Config) bool { agentDefault := cfg.AgentVerifyEvery() > 0 diff --git a/cmd/squirrel/content_native_test.go b/cmd/squirrel/content_native_test.go new file mode 100644 index 0000000..77b6134 --- /dev/null +++ b/cmd/squirrel/content_native_test.go @@ -0,0 +1,43 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// TestCLIContentLayoutsOnLocalWithoutRclone: a content-addressed and a +// packed destination on a local disk sync, verify and restore with no +// rclone on PATH, and the sync fingerprints what it landed. +func TestCLIContentLayoutsOnLocalWithoutRclone(t *testing.T) { + for _, layout := range []string{"content-addressed", "packed"} { + t.Run(layout, func(t *testing.T) { + withoutRclone(t) + f := writeSyncFixture(t) + cfg, err := os.ReadFile(f.configPath) + if err != nil { + t.Fatal(err) + } + cfg = []byte(strings.Replace(string(cfg), "type = \"local\"\n", "type = \"local\"\nlayout = \""+layout+"\"\n", 1)) + if err := os.WriteFile(f.configPath, cfg, 0o600); err != nil { + t.Fatal(err) + } + writeTestFile(t, filepath.Join(f.volumeDir, "a.txt"), "alpha") + runCLI(t, "--config", f.configPath, "index", f.volumeName) + + out := runCLI(t, "--config", f.configPath, "sync", "pics") + if !strings.Contains(out, "status=success") || !strings.Contains(out, "fingerprints=1") || strings.Contains(out, "rclone") { + t.Fatalf("sync output = %q, want a fingerprinted success with no rclone preamble", out) + } + if out := runCLI(t, "--config", f.configPath, "verify", "scratch"); !strings.Contains(out, "mismatched=0 missing=0") { + t.Fatalf("verify output = %q, want a clean pass", out) + } + to := t.TempDir() + runCLI(t, "--config", f.configPath, "restore", "pics", "--from", "scratch", "--to", to) + if got, err := os.ReadFile(filepath.Join(to, "a.txt")); err != nil || string(got) != "alpha" { + t.Fatalf("restored a.txt = %q, %v", got, err) + } + }) + } +} diff --git a/cmd/squirrel/recover.go b/cmd/squirrel/recover.go index fb8b541..15c532e 100644 --- a/cmd/squirrel/recover.go +++ b/cmd/squirrel/recover.go @@ -70,7 +70,7 @@ type recoverOptions struct { // before agreeing to its first step. type recoverPlan struct { dest *config.Destination - rcl *sync.Rclone // nil for a native mirror, which squirrel reads itself + rcl *sync.Rclone // nil for a native destination, which squirrel reads itself volumes []string snapshots []sync.IndexSnapshot chosen sync.IndexSnapshot diff --git a/cmd/squirrel/sync.go b/cmd/squirrel/sync.go index 62ef097..e2bc842 100644 --- a/cmd/squirrel/sync.go +++ b/cmd/squirrel/sync.go @@ -153,10 +153,10 @@ func rcloneConfigPathFor(cfg *config.Config) string { } // rcloneFor locates rclone and renders its config for reading dest. A -// native mirror is read through squirrel's own transport, so it gets a nil -// wrapper and no rclone preamble. +// native destination is read through squirrel's own transport, so it gets +// a nil wrapper and no rclone preamble. func rcloneFor(cmd *cobra.Command, cfg *config.Config, dest *config.Destination) (*sync.Rclone, error) { - if dest.NativeMirror() { + if dest.Native() { return nil, nil } rcl, err := sync.Find(cmd.Context()) diff --git a/cmd/squirrel/verify.go b/cmd/squirrel/verify.go index 9a8da2b..5b35036 100644 --- a/cmd/squirrel/verify.go +++ b/cmd/squirrel/verify.go @@ -75,7 +75,7 @@ func runVerify(cmd *cobra.Command, destName string) error { } // verifyRclone locates rclone and renders its config when a target is -// reached through it; a native mirror is verified without it. +// reached through it; a native destination is verified without it. func verifyRclone(cmd *cobra.Command, cfg *config.Config, names []string) (*sync.Rclone, error) { if !slices.ContainsFunc(names, func(name string) bool { return sync.Pair{Destination: cfg.Destinations[name]}.DrivesRclone() diff --git a/sync/sync.go b/sync/sync.go index 5e021d2..a21cff0 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -935,11 +935,11 @@ func (p Pair) TargetName() string { func (p Pair) IsNode() bool { return p.Node != nil } // DrivesRclone reports whether syncing this pair invokes rclone. Every -// destination does except kopia, which drives its own binary, and a -// native mirror, which squirrel writes itself; a peer node streams its -// bytes over the sync API. +// destination does except kopia, which drives its own binary, and a native +// one (local, or sftp without crypt, in any layout), which squirrel writes +// itself; a peer node streams its bytes over the sync API. func (p Pair) DrivesRclone() bool { - return p.Destination != nil && p.Destination.Type != "kopia" && !p.Destination.NativeMirror() + return p.Destination != nil && p.Destination.Type != "kopia" && !p.Destination.Native() } // RestoreOptions shape one Restore invocation. ToPath overrides the local From 4119adafb18e3229140719dc747266afab88ec6f Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:31:03 +0200 Subject: [PATCH 38/61] docs: describe the content layouts squirrel writes itself The content-addressed and packed pages, the verification and restore guides, the configuration pages and the README say how a local or plain sftp content destination is written without rclone, how its fingerprint is confirmed at landing, which hash_algo values it takes, and that the layouts are valid on local disks. --- README.md | 7 +-- .../docs/configuration/destinations.md | 9 ++-- docs/src/content/docs/guides/restore.md | 8 +-- docs/src/content/docs/guides/verification.md | 22 ++++++-- .../content/docs/layouts/content-addressed.md | 51 ++++++++++++++----- docs/src/content/docs/layouts/packed.md | 17 +++++-- .../content/docs/reference/configuration.md | 6 +-- 7 files changed, 84 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 6f1fa46..ac93fdf 100644 --- a/README.md +++ b/README.md @@ -158,7 +158,7 @@ Properties that differ from rclone destinations: ### Content-addressed destinations -By default a destination mirrors the volume's tree (see [Destination layout](#destination-layout)). Any rclone-remote destination — with or without a `crypt` block — can instead opt into an **append-only, content-addressed** layout, built for cold archive storage where objects should never be rewritten or moved: +By default a destination mirrors the volume's tree (see [Destination layout](#destination-layout)). Any destination but kopia — with or without a `crypt` block — can instead opt into an **append-only, content-addressed** layout, built for cold archive storage where objects should never be rewritten or moved. squirrel writes it itself on a `local` disk and on `sftp` without `crypt`: each object is staged, confirmed (read back through BLAKE3 locally, hashed by the server's `hash_algo` command on sftp) and only then renamed onto its name, never over a file already there. rclone writes the others: ```toml [destinations.archive] @@ -182,7 +182,7 @@ Properties that differ from mirrored destinations: - **Verification is presence+size**, recorded as such: each object is re-hashed with BLAKE3 before upload and confirmed present at the expected size after it, but its stored bytes are not compared at transfer time (and `crypt` remotes expose no hashes at all), so the runs row is recorded shallow and the push never claims content verification. On top of that, each upload's provider-side ciphertext fingerprint is recorded in the index and re-checked by [`squirrel verify`](#offsite-verification-squirrel-verify). - **Pick the layout when the destination is first used.** Switching an existing mirrored destination to `content-addressed` (or back) is not supported — point the new layout at a fresh destination or root. The push detects a mirrored history (a recorded successful sync without its manifest segment) and refuses. -- **`squirrel restore` restores the layout**: it resolves each present path to its content hash from the local index, fetches the per-hash object through the same rclone (`crypt`) read path the push uses, and re-hashes every fetched object before writing. When the *local index itself* is lost, the format is deliberately simple enough to recover without squirrel — see below. +- **`squirrel restore` restores the layout**: it resolves each present path to its content hash from the local index, fetches the per-hash object through the same read path the push uses (squirrel's own on a `local` disk and plain `sftp`, rclone and its `crypt` overlay otherwise), and re-hashes every fetched object before writing. When the *local index itself* is lost, the format is deliberately simple enough to recover without squirrel — see below. - `--dry-run` is not supported yet on the push (it previews restore). #### Offsite verification (`squirrel verify`) @@ -192,7 +192,8 @@ Cold archive storage is exactly the copy you can't cheaply re-download and re-ha What gets recorded depends on the backend type: - **`s3`** — the object **ETag**, recorded as `etag-md5` for a single-part upload's whole-object MD5, or `etag-md5-composite` for a multipart object's `-` value, stored verbatim either way. The ETag is read straight from the S3 API with a paginated `ListObjectsV2` over the `objects/` prefix, *not* through rclone: rclone funnels every hash read through `Object.Hash(MD5)`, which returns an empty string for a composite ETag, so a multipart (or client-encrypted, always-streamed) object would otherwise never expose a fingerprint at all. Listing is archive-tier-safe (no per-object `HEAD`, no restore), and the composite ETag is fixed at upload time and unaffected by later storage-class transitions or server-side encryption, so the recorded value stays stable for the life of the object. This read is the counterpart to the (deferred) write-side use of S3 additional checksums; capturing the ETag needs no upload-side change. For S3-compatible providers whose endpoint the client addresses wrongly, set `force_path_style = true` (see below). -- **`sftp`** — the checksum computed server-side by the remote's hash command. Content-addressed sftp destinations default to **SHA-256** (`hash_algo = "sha256"`, rendered as rclone's sftp `hashes` option so the selection is explicit rather than rclone's md5/sha1 preference); set `hash_algo` if your server only offers another type. +- **`local`** — the BLAKE3 of the stored bytes, read back by squirrel itself as each object lands and again on every verify pass; it must equal the object's name. +- **`sftp`** — the checksum computed server-side by the remote's hash command. Content-addressed sftp destinations default to **SHA-256** (`hash_algo = "sha256"`); set `hash_algo` if your server only offers another type. Without `crypt` squirrel runs the command itself (`md5sum`, `sha1sum`, `sha256sum` or `b3sum`) and checks its answer against the bytes it sent; behind `crypt` rclone runs it, through its sftp `hashes` option. - **other backends** — whatever hash `rclone lsjson --hash` exposes, recorded under its rclone hash name (e.g. `sha1` on b2). A backend exposing no checksum leaves the fingerprint pending, with a warning in the sync output. Re-verify a destination (or all content-addressed destinations) at any time: diff --git a/docs/src/content/docs/configuration/destinations.md b/docs/src/content/docs/configuration/destinations.md index d624c02..99addae 100644 --- a/docs/src/content/docs/configuration/destinations.md +++ b/docs/src/content/docs/configuration/destinations.md @@ -94,10 +94,11 @@ storage_class = "" # archive tiers cost less to store, ## Choosing a layout -By default a destination **mirrors** the volume's tree. Any rclone-remote -destination can instead opt into an append-only, content-addressed or packed -layout, and any non-`local` destination can encrypt contents with a `crypt` -block. See: +By default a destination **mirrors** the volume's tree. Any destination but +kopia can instead opt into an append-only, content-addressed or packed layout, +and any non-`local` destination can encrypt contents with a `crypt` block. +squirrel writes a `local` destination, and an `sftp` one without `crypt`, itself +in every layout; rclone writes the others. See: - [Mirror (default)](/squirrel/layouts/mirror/) - [Encrypted (crypt)](/squirrel/layouts/encrypted/) diff --git a/docs/src/content/docs/guides/restore.md b/docs/src/content/docs/guides/restore.md index bffe353..8c8571b 100644 --- a/docs/src/content/docs/guides/restore.md +++ b/docs/src/content/docs/guides/restore.md @@ -79,9 +79,11 @@ copy, so restore works from the **local index** instead: 2. The bytes are located per content: a per-hash object under `objects/`, or a member of a `tar.zst` pack under `packs/` (`pack_members` carries its offset and length). -3. Objects and packs are fetched through the same rclone (`crypt`) read path the - push uses. **Packs are fetched once** — one download serves every requested - member of that pack, never one fetch per file. +3. Objects and packs are fetched through the same read path the push uses: + squirrel's own transport on a `local` disk and on `sftp` without crypt, with + no rclone involved, and rclone (and its `crypt` overlay) elsewhere. **Packs + are fetched once** — one download serves every requested member of that + pack, never one fetch per file. 4. Every fetched object and extracted pack member is **re-hashed to BLAKE3 and compared** before it is written, so a misplaced or corrupted byte is refused rather than restored. (Because of this, `--shallow` does not weaken an diff --git a/docs/src/content/docs/guides/verification.md b/docs/src/content/docs/guides/verification.md index cab1bbc..9481ac6 100644 --- a/docs/src/content/docs/guides/verification.md +++ b/docs/src/content/docs/guides/verification.md @@ -19,8 +19,9 @@ value then vs provider value now** — squirrel never recomputes a provider checksum, so provider-specific composite forms are handled as opaque strings, and **no object body is ever transferred**. -The read is done via a direct S3 `ListObjectsV2` for `s3`, or `rclone lsjson ---hash` for every other backend. +The read is done via a direct S3 `ListObjectsV2` for `s3`, `rclone lsjson +--hash` for every other backend rclone writes, and squirrel's own transport for +a destination it writes itself (below). ## What gets recorded, by backend @@ -36,9 +37,19 @@ The read is done via a direct S3 `ListObjectsV2` for `s3`, or `rclone lsjson storage-class transitions or server-side encryption. For S3-compatible providers whose endpoint the client addresses wrongly, set `force_path_style = true`. +- **`local`** — the BLAKE3 of the stored bytes, which squirrel reads back itself, + past the page cache where the system allows: as each object or pack lands, + before it gets its name, and on every verify pass. Here the fingerprint is a + content check too: an object's BLAKE3 must equal its name, a pack's its key. - **`sftp`** — the checksum computed server-side by the remote's hash command. - Content-addressed sftp destinations default to **SHA-256** (`hash_algo = - "sha256"`); set `hash_algo` if your server only offers another type. + Content-addressed and packed sftp destinations default to **SHA-256** + (`hash_algo = "sha256"`); set `hash_algo` if your server only offers another + type. Without `crypt` squirrel runs the command itself — `md5sum`, `sha1sum`, + `sha256sum` or `b3sum`, probed once per session — on the staged copy before it + gets its name, and checks the answer against the bytes it sent. A server that + runs no programs leaves every fingerprint pending, with a warning. The command + line carries only the destination root and the artifact's hex name, and only + when both hold nothing but letters, digits, `.`, `_`, `-` and `/`. - **other backends** — whatever hash `rclone lsjson --hash` exposes, recorded under its rclone hash name (e.g. `sha1` on b2). A backend exposing no checksum leaves the fingerprint pending, with a warning in the sync output. @@ -58,7 +69,8 @@ must be one of those, else it errors: a mirror rclone writes records nothing to re-check. The pass lists the destination's `objects/` directory once (batched, -metadata-only), then per recorded object: +metadata-only; on a `local` destination squirrel re-reads every recorded +artifact), then per recorded object: - a **match** stamps the object verified in the index; - an object **without a fingerprint yet** (uploaded before this feature, or whose diff --git a/docs/src/content/docs/layouts/content-addressed.md b/docs/src/content/docs/layouts/content-addressed.md index 04df7fe..198fb12 100644 --- a/docs/src/content/docs/layouts/content-addressed.md +++ b/docs/src/content/docs/layouts/content-addressed.md @@ -4,9 +4,10 @@ description: An append-only, content-addressed layout for cold archive storage w --- By default a destination [mirrors](/squirrel/layouts/mirror/) the volume's tree. -Any rclone-remote destination — with or without a [`crypt`](/squirrel/layouts/encrypted/) -block — can instead opt into an **append-only, content-addressed** layout, built -for cold archive storage where objects should never be rewritten or moved. +Any destination but kopia — a `local` disk, an `sftp` server, `s3`, `b2` or +`gcs`, with or without a [`crypt`](/squirrel/layouts/encrypted/) block — can +instead opt into an **append-only, content-addressed** layout, built for cold +archive storage where objects should never be rewritten or moved. ```toml [destinations.archive] @@ -40,6 +41,29 @@ Deduplication is unaffected — identical content still derives one name and uploads once. ::: +## How it is written + +On a `local` disk, and on an `sftp` server without `crypt`, squirrel writes the +destination itself, without rclone. Each object, and each manifest segment: + +1. streams into `/.squirrel-staging/run-/` while BLAKE3 hashes the + bytes sent, and is refused if they no longer match the index; +2. is confirmed before it gets its name: read back through BLAKE3 on a local + disk, hashed by the server's `hash_algo` command (`sha256sum` by default) on + sftp. A match is recorded as the object's fingerprint right away; +3. is renamed onto its name. A file already at that name is never replaced: + squirrel checks that it holds the right bytes and records it, or fails the + object. + +A server that runs no programs takes every object all the same, but +fingerprints nothing: those objects stay pending, with a warning, and the +destination cannot gate offload for them. Both kinds of destination carry the +`.squirrel-volume` marker, written under `--init`, which also creates a missing +local root. + +Encrypted destinations, and those on `s3`, `b2` and `gcs`, are written by +rclone. + ## Transactional durability Durability is **transactional per run**: the run only counts as successful — and @@ -53,21 +77,22 @@ what's missing. ## Properties that differ from mirrored destinations -- **Verification is presence+size**, recorded as such: each object is - re-hashed with BLAKE3 before upload and confirmed present at the expected size - after it, but its stored bytes are not compared at transfer time (and `crypt` - remotes expose no hashes at all), so the runs row is recorded shallow and the push never claims content - verification. On top of that, each upload's provider-side ciphertext - fingerprint is recorded and re-checked by - [`squirrel verify`](/squirrel/guides/verification/). +- **Verification is presence+size**, recorded as such: each object is hashed + with BLAKE3 on its way out and confirmed present at the expected size after + it, and the runs row is recorded shallow. On top of that, each object's + fingerprint is recorded — confirmed at landing where squirrel writes the + destination itself, read back from the provider after the upload elsewhere + (the ciphertext's, behind `crypt`) — and re-checked by + [`squirrel verify`](/squirrel/guides/verification/). A push whose volume is + fingerprinted throughout advances as `fingerprint-verified`. - **Pick the layout when the destination is first used.** Switching an existing mirrored destination to `content-addressed` (or back) is not supported — point the new layout at a fresh destination or root. The push detects a mirrored history and refuses. - **[`squirrel restore`](/squirrel/guides/restore/) restores the layout**: it resolves each present path to its content hash from the local index, fetches - the per-hash object through the same rclone (`crypt`) read path the push uses, - and re-hashes it before writing. When the local index itself is lost, the + the per-hash object through the same read path the push uses — squirrel's + own, or rclone and its `crypt` overlay — and re-hashes it before writing. When the local index itself is lost, the format is deliberately simple enough to [recover without squirrel](/squirrel/reference/formats/#disaster-recovery-without-squirrel). - **`--dry-run` is not supported yet on the push** (it previews restore). @@ -86,7 +111,7 @@ backend and how to run `squirrel verify`. [destinations.archive] # ... hash_algo = "sha256" # sftp only: which server-side hash the fingerprint uses -checkers = 4 # cap rclone's concurrent checkers (providers that limit connections) +checkers = 4 # rclone destinations only: cap rclone's concurrent checkers force_path_style = true # s3 only: path-style bucket addressing for the ETag reader ``` diff --git a/docs/src/content/docs/layouts/packed.md b/docs/src/content/docs/layouts/packed.md index c9539fd..9d685a4 100644 --- a/docs/src/content/docs/layouts/packed.md +++ b/docs/src/content/docs/layouts/packed.md @@ -60,11 +60,15 @@ destination's durability evidence only once *all three* of its artifacts — eve pack, the run's `packs/map-`, and its `index/run-` segment — are confirmed on the remote **and** every pack has a verified scan-back fingerprint. -A pack's fingerprint is read straight back from the provider after upload (one -check per ~512 MB pack vouches for every file it holds — the packed analogue of -the per-object scan-back). If that read is unavailable, the pack is left -**pending** with a warning and the vector is *not* advanced, so unverified packed -content is never counted durable. +A pack's fingerprint is confirmed as it lands where squirrel writes the +destination itself — read back through BLAKE3 on a `local` disk, hashed by the +server's command on `sftp` (see +[how it is written](/squirrel/layouts/content-addressed/#how-it-is-written)) — +and read straight back from the provider after upload elsewhere. One check per +~512 MB pack vouches for every file it holds, the packed analogue of the +per-object fingerprint. If none is available, the pack is left **pending** with +a warning and the vector is *not* advanced, so unverified packed content is +never counted durable. [`squirrel verify`](/squirrel/guides/verification/) fills any pending pack fingerprint and re-confirms the rest, per pack. @@ -72,6 +76,9 @@ fingerprint and re-confirms the rest, per pack. Properties match the content-addressed layout: +- It is written by squirrel itself on a `local` disk and on `sftp` without + `crypt`, and by rclone elsewhere, in the + [same way](/squirrel/layouts/content-addressed/#how-it-is-written). - Verification is presence+size (recorded shallow). - The layout is chosen at first use and refuses to run against a differently-shaped history. diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md index 94c5c20..758a1ab 100644 --- a/docs/src/content/docs/reference/configuration.md +++ b/docs/src/content/docs/reference/configuration.md @@ -46,7 +46,7 @@ See [Hooks](/squirrel/guides/hooks/). |---|---|---| | `type` | all | `local`, `sftp`, `s3`, `b2`, `gcs`, or `kopia`. | | `root` | all | Base path (or bucket sub-path) at the destination. | -| `layout` | rclone remotes | `mirror` (default), `content-addressed`, or `packed`. | +| `layout` | every type but kopia | `mirror` (default), `content-addressed`, or `packed`. | ### `local` @@ -151,8 +151,8 @@ For `layout = "content-addressed"` or `layout = "packed"` destinations. See | Key | Applies to | Default | Meaning | |---|---|---|---| -| `hash_algo` | sftp, except a mirror without crypt | `sha256` | Which server-side hash the [scan-back fingerprint](/squirrel/guides/verification/) uses. A plain sftp mirror runs no command on the server, so the key is rejected there. | -| `checkers` | rclone remotes | rclone default | Cap rclone's concurrent checkers (`--checkers`). Rejected on a `local` mirror and on an `sftp` mirror without crypt: squirrel writes those itself, without rclone. | +| `hash_algo` | sftp, except a mirror without crypt | `sha256` | Which server-side hash the [fingerprint](/squirrel/guides/verification/) uses. On a content-addressed or packed destination without crypt it names the command squirrel runs on the server — `md5` (`md5sum`), `sha1` (`sha1sum`), `sha256` (`sha256sum`) or `blake3` (`b3sum`) — and squirrel checks its answer against the bytes it sent. Behind crypt rclone runs it, and `crc32`, `xxh3` and `xxh128` are valid too; there the default applies to content-addressed only. A plain sftp mirror runs no command on the server, so the key is rejected there. | +| `checkers` | rclone remotes | rclone default | Cap rclone's concurrent checkers (`--checkers`). Rejected on every `local` destination and every `sftp` one without crypt: squirrel writes those itself, without rclone. | | `force_path_style` | s3 | `false` | Path-style bucket addressing for squirrel's own ETag reader (not the rclone transport). | | `pack_threshold` | packed | — | Files smaller than this are packed; at/above land as objects (e.g. `1MiB`). | | `pack_size` | packed | — | Target size of one pack before it is closed (e.g. `512MiB`). | From 8a5d41fdc72de662f5e1fb127bca674f34a08b72 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:51:05 +0200 Subject: [PATCH 39/61] sync, store: stop a lost mirror copy from vouching, and never verify an unmounted root A mirror verify finding now demotes the volume's locally advanced fingerprint-verified vector to presence+size, so the offload gate checks each content's own fingerprint even with a verify cadence, and peers pull the demoted method; the next push that leaves nothing pending upgrades it again. Before, a cadenced gate still offloaded a file whose only mirror copy verify had found gone. A pass reads every volume's marker first and fails, marking nothing, when one is missing or names another volume. An aborted pass that already recorded findings raises the alarm, and a re-stamp that races a push leaves the row to the next pass. remote_paths reads drop verified_at_ns, which only ordered the rotation. --- design/native-mirror.md | 16 ++++- offload/native_mirror_test.go | 55 ++++++++------- store/destination_run_ids.go | 25 +++++++ store/remote_paths.go | 8 +-- store/remote_paths_evidence.go | 33 +++++---- store/remote_paths_test.go | 37 ++++++++-- sync/mirror_sftp_test.go | 2 +- sync/mirror_test.go | 2 +- sync/verify_mirror.go | 119 +++++++++++++++++++++++++++------ sync/verify_mirror_test.go | 43 +++++++++--- sync/verify_remote.go | 14 ++-- 11 files changed, 262 insertions(+), 92 deletions(-) diff --git a/design/native-mirror.md b/design/native-mirror.md index ab16ee3..57b1be0 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -580,9 +580,19 @@ for local mirrors. passes. Kopia's `verify_files_percent` is the precedent for sampled read-back. - Findings latch the existing destination alarm and mark the affected rows - `lost` — only while the row is still in the state the pass read it in, since - a push may be moving it. `lost` rows whose content is still the index's + A pass first reads every volume's `.squirrel-volume` through the transport + and fails, marking nothing, when one is missing or names another volume: an + unmounted disk or an emptied share must not read as every copy gone. + + Findings latch the existing destination alarm, also when the pass aborts + after recording them, and mark the affected rows `lost` — only while the row + is still in the state the pass read it in, since a push may be moving it. A + finding also demotes the volume's locally advanced `fingerprint-verified` + components to `presence+size` (`DemoteFingerprintVerifiedVector`), at the + runs they cover. Without that, a gate with a verify cadence would still take + the component's word for a lost copy, and a peer pulling the vector would + too; demoted, the gate checks each content's own fingerprint, and the next + push that leaves nothing pending upgrades the component again. `lost` rows whose content is still the index's current content become the mirror's repairs. A clean pass re-attempts the `fingerprint-verified` upgrade, as it does for the content layouts. `squirrel verify` reaches the mirror through its transport, without rclone. diff --git a/offload/native_mirror_test.go b/offload/native_mirror_test.go index 101cdb7..b388a0e 100644 --- a/offload/native_mirror_test.go +++ b/offload/native_mirror_test.go @@ -35,35 +35,40 @@ func pushNativeMirror(t *testing.T, s *store.Store, root, dst string) *config.De // TestOffloadGatesOnNativeLocalMirror: a native local mirror reads every // copy back through BLAKE3, so its push alone lets offload delete the local -// bytes. Once a verify pass finds a copy gone, that copy stops vouching and -// its file stays. +// bytes, with or without a verify cadence. Once a verify pass finds a copy +// gone, that copy stops vouching and its file stays. func TestOffloadGatesOnNativeLocalMirror(t *testing.T) { - root, dst := t.TempDir(), t.TempDir() - writeFile(t, filepath.Join(root, "a.txt"), "alpha") - writeFile(t, filepath.Join(root, "b.txt"), "bravo") - s := setupStore(t) - ctx := context.Background() - indexVolume(t, s, root) - dest := pushNativeMirror(t, s, root, dst) + for _, cadenced := range []bool{false, true} { + t.Run(map[bool]string{false: "no cadence", true: "verify cadence"}[cadenced], func(t *testing.T) { + root, dst := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(root, "a.txt"), "alpha") + writeFile(t, filepath.Join(root, "b.txt"), "bravo") + s := setupStore(t) + ctx := context.Background() + indexVolume(t, s, root) + dest := pushNativeMirror(t, s, root, dst) - if err := os.Remove(filepath.Join(dst, volName, "b.txt")); err != nil { - t.Fatal(err) - } - if rep, err := sync.VerifyRemote(ctx, s, nil, dest); err != nil || len(rep.PathsMissing) != 1 { - t.Fatalf("verify = %+v, %v; want b.txt found missing", rep, err) - } + if err := os.Remove(filepath.Join(dst, volName, "b.txt")); err != nil { + t.Fatal(err) + } + if rep, err := sync.VerifyRemote(ctx, s, nil, dest); err != nil || len(rep.PathsMissing) != 1 { + t.Fatalf("verify = %+v, %v; want b.txt found missing", rep, err) + } - rep, err := Offload(ctx, s, root, Options{ - Name: volName, Paths: []string{"."}, Require: []string{"usb"}, - RequireDests: map[string]*config.Destination{"usb": dest}, - }) - if err != nil { - t.Fatalf("Offload: %v", err) + rep, err := Offload(ctx, s, root, Options{ + Name: volName, Paths: []string{"."}, Require: []string{"usb"}, + RequireDests: map[string]*config.Destination{"usb": dest}, + VerifyCadenced: map[string]bool{"usb": cadenced}, + }) + if err != nil { + t.Fatalf("Offload: %v", err) + } + oneResult(t, rep, "a.txt", OutcomeOffloaded) + mustBeGone(t, filepath.Join(root, "a.txt")) + oneFailure(t, oneResult(t, rep, "b.txt", OutcomeNotDurable), "usb", FailureNotVerified) + mustExist(t, filepath.Join(root, "b.txt")) + }) } - oneResult(t, rep, "a.txt", OutcomeOffloaded) - mustBeGone(t, filepath.Join(root, "a.txt")) - oneFailure(t, oneResult(t, rep, "b.txt", OutcomeNotDurable), "usb", FailureNotVerified) - mustExist(t, filepath.Join(root, "b.txt")) } // TestOffloadRefusesNativeSFTPMirrorUpFront: a native sftp mirror reads diff --git a/store/destination_run_ids.go b/store/destination_run_ids.go index fe35c8a..5df57a9 100644 --- a/store/destination_run_ids.go +++ b/store/destination_run_ids.go @@ -294,6 +294,31 @@ func (s *Store) UpgradeDestinationVectorToFingerprintVerified(ctx context.Contex return true, nil } +// DemoteFingerprintVerifiedVector re-stamps every locally advanced +// fingerprint-verified component of the (volume, destination) vector as +// presence+size, at the run and verification instant it already records: +// a verify pass found content the destination held gone or changed, so its +// vector no longer vouches for the volume as a whole. The offload gate then +// checks each content's own fingerprint, and a peer pulling the vector sees +// presence+size. The next push that leaves nothing pending upgrades it +// again. Each demotion is logged in destination_run_ids_history. +func (s *Store) DemoteFingerprintVerifiedVector(ctx context.Context, volumeID int64, destination string) error { + components, err := s.ListDestinationRunIDs(ctx, volumeID, destination) + if err != nil { + return err + } + for _, c := range components { + if c.VerifyMethod != VerifyMethodFingerprint || c.SourceNodeID.Valid { + continue + } + verifiedAt := c.VerifiedAtNs + if err := s.upsertDestinationRunID(ctx, volumeID, destination, c.OriginNodeID, c.OriginRunID, VerifyMethodPresenceSize, sql.NullInt64{}, &verifiedAt, false); err != nil { + return fmt.Errorf("demote vector of %q: %w", destination, err) + } + } + return nil +} + // recordPushFreshness overwrites the destination's push-freshness maxima // to exactly the supplied snapshot — the per-origin-node maxima of the // present set this push enumerated. Distinct from the monotonic vector diff --git a/store/remote_paths.go b/store/remote_paths.go index e849d98..147dbed 100644 --- a/store/remote_paths.go +++ b/store/remote_paths.go @@ -29,8 +29,7 @@ const ( // destination, keyed on the files row it came from. Path, SizeBytes and // Blake3 are read through that row's folder and content. MtimeNs is the // mtime the destination reported for the written version. Checksum is -// the BLAKE3 a read of the stored bytes confirmed, NULL while none did, -// and VerifiedAtNs when a read last confirmed it. +// the BLAKE3 a read of the stored bytes confirmed, NULL while none did. type RemotePath struct { ID int64 ContentID int64 @@ -39,7 +38,6 @@ type RemotePath struct { DisplacedRunID sql.NullInt64 MtimeNs int64 Checksum sql.NullString - VerifiedAtNs sql.NullInt64 Path string SizeBytes int64 @@ -163,7 +161,7 @@ func (s *Store) transitionRemotePaths(ctx context.Context, ids []int64, to, upda // and content size and hash (table aliases rp, fo, c). const remotePathSelect = ` SELECT rp.id, rp.content_id, rp.written_run_id, - rp.state, rp.displaced_run_id, rp.mtime_ns, rp.checksum, rp.verified_at_ns, + rp.state, rp.displaced_run_id, rp.mtime_ns, rp.checksum, CASE fo.path WHEN '' THEN rp.name ELSE fo.path || '/' || rp.name END, c.size_bytes, c.blake3 FROM remote_paths rp @@ -173,7 +171,7 @@ const remotePathSelect = ` func scanRemotePath(s rowScanner) (RemotePath, error) { var r RemotePath err := s.Scan(&r.ID, &r.ContentID, &r.WrittenRunID, - &r.State, &r.DisplacedRunID, &r.MtimeNs, &r.Checksum, &r.VerifiedAtNs, + &r.State, &r.DisplacedRunID, &r.MtimeNs, &r.Checksum, &r.Path, &r.SizeBytes, &r.Blake3) return r, err } diff --git a/store/remote_paths_evidence.go b/store/remote_paths_evidence.go index 2d04024..6af051d 100644 --- a/store/remote_paths_evidence.go +++ b/store/remote_paths_evidence.go @@ -5,12 +5,13 @@ import ( "fmt" ) -// StoredRemotePath is a live or displaced remote_paths row with the name of -// the volume it belongs to: a version a mirror holds by squirrel's records, -// at / or in that volume's history. +// StoredRemotePath is a live or displaced remote_paths row with the volume +// it belongs to: a version a mirror holds by squirrel's records, at +// / or in that volume's history. type StoredRemotePath struct { RemotePath - Volume string + VolumeID int64 + Volume string } // ListStoredRemotePaths returns every live and displaced row on the @@ -20,9 +21,9 @@ type StoredRemotePath struct { func (s *Store) ListStoredRemotePaths(ctx context.Context, destination string) ([]StoredRemotePath, error) { return queryRows(ctx, s.db, ` SELECT rp.id, rp.content_id, rp.written_run_id, - rp.state, rp.displaced_run_id, rp.mtime_ns, rp.checksum, rp.verified_at_ns, + rp.state, rp.displaced_run_id, rp.mtime_ns, rp.checksum, CASE fo.path WHEN '' THEN rp.name ELSE fo.path || '/' || rp.name END, - c.size_bytes, c.blake3, v.name + c.size_bytes, c.blake3, v.id, v.name FROM remote_paths rp JOIN folders fo ON fo.id = rp.folder_id JOIN volumes v ON v.id = fo.volume_id @@ -32,32 +33,30 @@ func (s *Store) ListStoredRemotePaths(ctx context.Context, destination string) ( `, func(sc rowScanner) (StoredRemotePath, error) { var r StoredRemotePath err := sc.Scan(&r.ID, &r.ContentID, &r.WrittenRunID, - &r.State, &r.DisplacedRunID, &r.MtimeNs, &r.Checksum, &r.VerifiedAtNs, - &r.Path, &r.SizeBytes, &r.Blake3, &r.Volume) + &r.State, &r.DisplacedRunID, &r.MtimeNs, &r.Checksum, + &r.Path, &r.SizeBytes, &r.Blake3, &r.VolumeID, &r.Volume) return r, err }, destination) } // RecordRemotePathVerified records that a read of a live or displaced // row's stored bytes just hashed to checksum, its content's BLAKE3 in -// lowercase hex, at atNs. A row that already records a checksum must record -// this one: a read never replaces the fingerprint it re-confirms. -func (s *Store) RecordRemotePathVerified(ctx context.Context, id int64, checksum string, atNs int64) error { +// lowercase hex, at atNs, and reports whether it did. A row that already +// records a checksum must record this one — a read never replaces the +// fingerprint it re-confirms — and a row a push moved since is left alone. +func (s *Store) RecordRemotePathVerified(ctx context.Context, id int64, checksum string, atNs int64) (bool, error) { res, err := s.db.ExecContext(ctx, ` UPDATE remote_paths SET checksum_algo = ?, checksum = ?, verified_at_ns = ? WHERE id = ? AND state IN ('live', 'displaced') AND (checksum IS NULL OR checksum = ?) `, ChecksumAlgoBlake3, checksum, atNs, id, checksum) if err != nil { - return fmt.Errorf("record verification of remote path %d: %w", id, err) + return false, fmt.Errorf("record verification of remote path %d: %w", id, err) } n, err := res.RowsAffected() if err != nil { - return fmt.Errorf("record verification of remote path %d: %w", id, err) + return false, fmt.Errorf("record verification of remote path %d: %w", id, err) } - if n != 1 { - return fmt.Errorf("record verification of remote path %d: the row is not stored, or records another checksum", id) - } - return nil + return n == 1, nil } // LoseStoredRemotePath marks a row lost that a verify pass found missing or diff --git a/store/remote_paths_test.go b/store/remote_paths_test.go index 37d8a37..d8d3942 100644 --- a/store/remote_paths_test.go +++ b/store/remote_paths_test.go @@ -307,14 +307,14 @@ func TestListStoredRemotePathsRotatesByVerification(t *testing.T) { if got := ids(); len(got) != 2 || got[0] != second || got[1] != first { t.Fatalf("order = %v, want the never-verified %d before %d", got, second, first) } - if err := s.RecordRemotePathVerified(ctx, second, "abc", 9); err != nil { - t.Fatalf("RecordRemotePathVerified: %v", err) + if stamped, err := s.RecordRemotePathVerified(ctx, second, "abc", 9); err != nil || !stamped { + t.Fatalf("RecordRemotePathVerified = %t, %v", stamped, err) } if got := ids(); got[0] != first || got[1] != second { t.Fatalf("order after re-reading %d = %v", second, got) } - if err := s.RecordRemotePathVerified(ctx, second, "def", 10); err == nil { - t.Fatal("a read replaced the checksum it should re-confirm") + if stamped, err := s.RecordRemotePathVerified(ctx, second, "def", 10); err != nil || stamped { + t.Fatalf("a read replaced the checksum it should re-confirm: %t, %v", stamped, err) } } @@ -370,3 +370,32 @@ func TestLoseStoredRemotePathOnlyFromTheStateRead(t *testing.T) { t.Fatalf("lose a displaced row = %t, %v; want moved", moved, err) } } + +// TestDemoteFingerprintVerifiedVector: a demotion re-stamps only the +// locally advanced fingerprint-verified components, keeping their runs, and +// a later advance upgrades them again. +func TestDemoteFingerprintVerifiedVector(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + _, vID, runID := remotePathFixture(t, s) + self, err := s.GetSelfNode(ctx) + if err != nil { + t.Fatal(err) + } + if err := s.UpsertDestinationRunIDVerified(ctx, vID, "usb", self.ID, runID, VerifyMethodFingerprint, false); err != nil { + t.Fatal(err) + } + if err := s.DemoteFingerprintVerifiedVector(ctx, vID, "usb"); err != nil { + t.Fatalf("DemoteFingerprintVerifiedVector: %v", err) + } + comps, err := s.ListDestinationRunIDs(ctx, vID, "usb") + if err != nil || len(comps) != 1 || comps[0].VerifyMethod != VerifyMethodPresenceSize || comps[0].OriginRunID != runID { + t.Fatalf("vector = %+v, %v; want one presence+size component at run %d", comps, err, runID) + } + if err := s.UpsertDestinationRunIDVerified(ctx, vID, "usb", self.ID, runID, VerifyMethodFingerprint, false); err != nil { + t.Fatal(err) + } + if comps, _ := s.ListDestinationRunIDs(ctx, vID, "usb"); comps[0].VerifyMethod != VerifyMethodFingerprint { + t.Fatalf("vector after a later advance = %+v, want fingerprint-verified again", comps) + } +} diff --git a/sync/mirror_sftp_test.go b/sync/mirror_sftp_test.go index 2f33a77..723c515 100644 --- a/sync/mirror_sftp_test.go +++ b/sync/mirror_sftp_test.go @@ -53,7 +53,7 @@ func TestMirrorPushOverSFTP(t *testing.T) { } f.checkInvariants(t, nil) for _, r := range f.rows(t) { - if r.Checksum.Valid || r.VerifiedAtNs.Valid { + if r.Checksum.Valid { t.Fatalf("%s row = %+v, want no fingerprint over sftp", r.Path, r) } } diff --git a/sync/mirror_test.go b/sync/mirror_test.go index f4e277b..57d6e35 100644 --- a/sync/mirror_test.go +++ b/sync/mirror_test.go @@ -322,7 +322,7 @@ func TestMirrorPushWithoutRclone(t *testing.T) { } } for _, r := range f.rows(t) { - if r.Checksum.String != hex.EncodeToString(r.Blake3) || !r.VerifiedAtNs.Valid { + if r.Checksum.String != hex.EncodeToString(r.Blake3) { t.Fatalf("%s row = %+v, want the read-back BLAKE3 recorded", r.Path, r) } } diff --git a/sync/verify_mirror.go b/sync/verify_mirror.go index a03797b..052d917 100644 --- a/sync/verify_mirror.go +++ b/sync/verify_mirror.go @@ -1,7 +1,6 @@ package sync import ( - "bytes" "context" "encoding/hex" "errors" @@ -11,6 +10,7 @@ import ( "github.com/mbertschler/squirrel/config" "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" ) // mirrorRereadShare is the share of a local mirror's stored bytes one @@ -22,8 +22,9 @@ const mirrorRereadShare = 10 // records, the live and the displaced ones: each gets one Lstat against its // recorded size and mtime, and on a local disk a slice of them is re-read // through BLAKE3. A copy that is gone or changed is marked lost, which -// latches the destination's alarm and makes the next push write the path -// again if the index still holds that content there. +// latches the destination's alarm, demotes its volume's evidence to +// presence+size, and makes the next push write the path again if the index +// still holds that content there. func verifyMirror(ctx context.Context, s *store.Store, dest *config.Destination, rep *RemoteVerifyReport) error { rows, err := s.ListStoredRemotePaths(ctx, dest.Name) if err != nil { @@ -38,7 +39,11 @@ func verifyMirror(ctx context.Context, s *store.Store, dest *config.Destination, return fmt.Errorf("record verify run: %w", err) } rep.RunID = runID - verifyErr := checkMirrorCopies(ctx, s, dest, rows, rep) + pass := &mirrorPass{s: s, dest: dest, rep: rep, lostIn: map[int64]bool{}} + verifyErr := pass.run(ctx, rows) + if err := pass.demoteLostVolumes(ctx); err != nil && verifyErr == nil { + verifyErr = err + } if err := recordVerifyOutcome(ctx, s, rep, verifyErr); err != nil { return err } @@ -48,22 +53,37 @@ func verifyMirror(ctx context.Context, s *store.Store, dest *config.Destination, return verifyErr } +// mirrorPass is one verify pass over a native mirror: where it reports, and +// the volumes it found a copy lost in. +type mirrorPass struct { + s *store.Store + dest *config.Destination + rep *RemoteVerifyReport + lostIn map[int64]bool +} + // mirrorCopy is one recorded copy as a verify pass addresses it. type mirrorCopy struct { store.StoredRemotePath name string // where the copy is, relative to the destination root } -func checkMirrorCopies(ctx context.Context, s *store.Store, dest *config.Destination, rows []store.StoredRemotePath, rep *RemoteVerifyReport) error { - tr, err := openReadOnly(ctx, dest) +// run checks every volume's marker before any of its copies, so a disk +// that is not mounted, or a share emptied from under its root, fails the +// pass instead of reading as every copy gone. +func (p *mirrorPass) run(ctx context.Context, rows []store.StoredRemotePath) error { + tr, err := openReadOnly(ctx, p.dest) if err != nil { return err } defer func() { _ = tr.Close() }() + if err := requireVolumeMarkers(ctx, tr, p.dest, storedVolumes(rows)); err != nil { + return err + } var intact []mirrorCopy for _, r := range rows { c := mirrorCopy{StoredRemotePath: r, name: storedCopyName(r)} - ok, err := statCopy(ctx, s, tr, c, rep) + ok, err := p.statCopy(ctx, tr, c) if err != nil { return err } @@ -71,10 +91,42 @@ func checkMirrorCopies(ctx context.Context, s *store.Store, dest *config.Destina intact = append(intact, c) } } - if !readsBack(dest) { + if !readsBack(p.dest) { return nil } - return rereadCopies(ctx, s, tr, rereadSlice(intact), rep) + return p.rereadCopies(ctx, tr, rereadSlice(intact)) +} + +func storedVolumes(rows []store.StoredRemotePath) []string { + var out []string + seen := map[string]bool{} + for _, r := range rows { + if !seen[r.Volume] { + seen[r.Volume] = true + out = append(out, r.Volume) + } + } + return out +} + +// requireVolumeMarkers fails unless each volume's directory on the root +// holds the .squirrel-volume marker naming it. +func requireVolumeMarkers(ctx context.Context, tr transport, dest *config.Destination, volumes []string) error { + for _, v := range volumes { + name := path.Join(v, volmark.MarkerName) + data, err := readSmallFile(ctx, tr, name, maxMarkerBytes) + if err != nil { + return fmt.Errorf("destination %q: read %s: %w — the disk may not be mounted, or the root is wrong; nothing was checked", dest.Name, name, err) + } + m, err := volmark.Parse(data) + if err == nil && m.Volume != v { + err = fmt.Errorf("it names volume %q", m.Volume) + } + if err != nil { + return fmt.Errorf("destination %q: %s: %w — nothing was checked", dest.Name, name, err) + } + } + return nil } // storedCopyName is where a live copy sits, /, or a displaced @@ -88,15 +140,15 @@ func storedCopyName(r store.StoredRemotePath) string { // statCopy checks one copy's size and mtime and reports whether it is // intact. A copy that is gone or changed is recorded as a finding. -func statCopy(ctx context.Context, s *store.Store, tr transport, c mirrorCopy, rep *RemoteVerifyReport) (bool, error) { +func (p *mirrorPass) statCopy(ctx context.Context, tr transport, c mirrorCopy) (bool, error) { e, err := tr.Stat(ctx, c.name) switch { case errors.Is(err, fs.ErrNotExist) || errors.Is(err, errParentNotDir): - return false, loseCopy(ctx, s, c, &rep.PathsMissing) + return false, p.loseCopy(ctx, c, &p.rep.PathsMissing) case err != nil: return false, fmt.Errorf("stat %s: %w", c.name, err) case !matchesRecord(e, c.RemotePath): - return false, loseCopy(ctx, s, c, &rep.PathsChanged) + return false, p.loseCopy(ctx, c, &p.rep.PathsChanged) } return true, nil } @@ -119,13 +171,16 @@ func rereadSlice(copies []mirrorCopy) []mirrorCopy { return copies } -// rereadCopies hashes each copy as the disk returns it: a match re-stamps -// its fingerprint, other bytes are a finding. -func rereadCopies(ctx context.Context, s *store.Store, tr transport, copies []mirrorCopy, rep *RemoteVerifyReport) error { +// rereadCopies hashes each copy as the disk returns it and compares it with +// the fingerprint its row records, or with its content's BLAKE3 while it +// records none: a match re-stamps the fingerprint, other bytes are a +// finding. A copy a push moved since the pass read its row is left to the +// next pass. +func (p *mirrorPass) rereadCopies(ctx context.Context, tr transport, copies []mirrorCopy) error { for _, c := range copies { sum, err := readBack(ctx, tr, c.name) if errors.Is(err, fs.ErrNotExist) { - if err := loseCopy(ctx, s, c, &rep.PathsMissing); err != nil { + if err := p.loseCopy(ctx, c, &p.rep.PathsMissing); err != nil { return err } continue @@ -133,27 +188,47 @@ func rereadCopies(ctx context.Context, s *store.Store, tr transport, copies []mi if err != nil { return fmt.Errorf("re-read %s: %w", c.name, err) } - if !bytes.Equal(sum, c.Blake3) { - if err := loseCopy(ctx, s, c, &rep.PathsChanged); err != nil { + want := hex.EncodeToString(c.Blake3) + if c.Checksum.Valid { + want = c.Checksum.String + } + if got := hex.EncodeToString(sum); got != want { + if err := p.loseCopy(ctx, c, &p.rep.PathsChanged); err != nil { return err } continue } - if err := s.RecordRemotePathVerified(ctx, c.ID, hex.EncodeToString(sum), store.NowNs()); err != nil { + stamped, err := p.s.RecordRemotePathVerified(ctx, c.ID, want, store.NowNs()) + if err != nil { return err } - rep.PathsReread++ + if stamped { + p.rep.PathsReread++ + } } return nil } // loseCopy marks a copy lost and lists its name under the finding, unless a // push moved its row since the pass read it. -func loseCopy(ctx context.Context, s *store.Store, c mirrorCopy, finding *[]string) error { - moved, err := s.LoseStoredRemotePath(ctx, c.ID, c.State) +func (p *mirrorPass) loseCopy(ctx context.Context, c mirrorCopy, finding *[]string) error { + moved, err := p.s.LoseStoredRemotePath(ctx, c.ID, c.State) if err != nil || !moved { return err } *finding = append(*finding, c.name) + p.lostIn[c.VolumeID] = true + return nil +} + +// demoteLostVolumes demotes the evidence of every volume the pass found a +// copy lost in, so the offload gate stops taking the destination's word +// for that volume as a whole until a push writes the copies again. +func (p *mirrorPass) demoteLostVolumes(ctx context.Context) error { + for volumeID := range p.lostIn { + if err := p.s.DemoteFingerprintVerifiedVector(ctx, volumeID, p.dest.Name); err != nil { + return err + } + } return nil } diff --git a/sync/verify_mirror_test.go b/sync/verify_mirror_test.go index 9c5c3c1..76665ac 100644 --- a/sync/verify_mirror_test.go +++ b/sync/verify_mirror_test.go @@ -4,6 +4,7 @@ import ( "context" "os" "path/filepath" + "strings" "testing" "github.com/mbertschler/squirrel/store" @@ -50,19 +51,19 @@ func TestVerifyMirrorRereadRotates(t *testing.T) { } f.index(t) f.mustPush(t) - before := map[int64]int64{} - for _, r := range f.rows(t) { - before[r.ID] = r.VerifiedAtNs.Int64 - } + reread := map[int64]bool{} for range 4 { + next, err := f.store.ListStoredRemotePaths(context.Background(), "usb") + if err != nil { + t.Fatal(err) + } if rep := f.verify(t); rep.PathsReread != 1 { t.Fatalf("pass re-read %d copies, want the one a tenth of the bytes needs", rep.PathsReread) } + reread[next[0].ID] = true } - for _, r := range f.rows(t) { - if r.VerifiedAtNs.Int64 == before[r.ID] { - t.Fatalf("%s was never re-read in four passes", r.Path) - } + if len(reread) != 4 { + t.Fatalf("four passes re-read %d distinct copies, want all four in turn", len(reread)) } } @@ -99,6 +100,9 @@ func TestVerifyMirrorFindingsMarkCopiesLost(t *testing.T) { if got := f.lostPaths(t); len(got) != 3 { t.Fatalf("lost = %v, want all three copies", got) } + if comps := volumeComponents(t, f.store, "pics", "usb"); len(comps) != 1 || comps[0].VerifyMethod != store.VerifyMethodPresenceSize { + t.Fatalf("vector after the findings = %+v, want it demoted to presence+size", comps) + } rep := f.mustPush(t) if rep.RcloneResult.Transferred != 3 { @@ -108,6 +112,9 @@ func TestVerifyMirrorFindingsMarkCopiesLost(t *testing.T) { t.Fatal("the repair push did not restore the lost copies") } f.checkInvariants(t, nil) + if comps := volumeComponents(t, f.store, "pics", "usb"); comps[0].VerifyMethod != store.VerifyMethodFingerprint { + t.Fatalf("vector after the repair = %+v, want fingerprint-verified again", comps) + } if rep := f.verify(t); !rep.Clean() { t.Fatalf("pass after the repair = %+v, want clean", rep) } @@ -143,3 +150,23 @@ func TestVerifyMirrorOverSFTPChecksWithoutReading(t *testing.T) { t.Fatalf("missing = %v, want pics/a.txt", rep.PathsMissing) } } + +// TestVerifyMirrorRefusesAnUnmountedRoot: a root emptied from under the +// mirror — a disk that is not mounted — fails the pass on the missing +// marker, and marks no copy lost. +func TestVerifyMirrorRefusesAnUnmountedRoot(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + if err := os.RemoveAll(filepath.Join(f.dst, "pics")); err != nil { + t.Fatal(err) + } + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err == nil || !strings.Contains(err.Error(), "nothing was checked") { + t.Fatalf("VerifyRemote = %+v, %v; want the pass refused", rep, err) + } + if lost := f.lostPaths(t); len(lost) != 0 || rep.AlarmRaised { + t.Fatalf("lost = %v, alarm raised = %t; want no record touched", lost, rep.AlarmRaised) + } +} diff --git a/sync/verify_remote.go b/sync/verify_remote.go index e2a7ef9..9458564 100644 --- a/sync/verify_remote.go +++ b/sync/verify_remote.go @@ -550,13 +550,15 @@ func recordVerifyOutcome(ctx context.Context, s *store.Store, rep *RemoteVerifyR // applyVerifyAlarm latches or clears the destination's standing alarm from // this pass's outcome (#157, F30). A pass that detected a mismatch or a -// missing object/pack raises the alarm (idempotent — a re-detection keeps -// the original "in alarm since"); a clean pass auto-clears any standing -// alarm, recording the clear against this verify run. A pass that aborted -// (verifyErr != nil) proves nothing about the destination's integrity, so -// it neither raises nor clears — its failed run row is the record. +// missing object/pack/copy raises the alarm (idempotent — a re-detection +// keeps the original "in alarm since"), even when it aborted afterwards: a +// mirror's findings are already recorded by then. A clean pass auto-clears +// any standing alarm, recording the clear against this verify run. A pass +// that aborted with no finding proves nothing about the destination's +// integrity, so it neither raises nor clears — its failed run row is the +// record. func applyVerifyAlarm(ctx context.Context, s *store.Store, rep *RemoteVerifyReport, verifyErr error) error { - if verifyErr != nil { + if verifyErr != nil && rep.Clean() { return nil } if !rep.Clean() { From e1d6770f20b692a55c00d2ae60dd045c8977cea0 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:55:26 +0200 Subject: [PATCH 40/61] sync: never mistake an unhashed artifact for a changed one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A native content verify checks every synced volume's marker first, so an unmounted root fails the pass instead of reporting every object missing. Over sftp, an artifact the server cannot hash this pass — no trusted command, or a row recorded under another hash_algo — counts as unchecked rather than mismatched, and squirrel verify prints the count. The server hash refuses a leaf that is no regular file, and only a probe the server answered is remembered for the session. --- cmd/squirrel/verify.go | 4 +- design/native-mirror.md | 15 +++-- sync/content_native_test.go | 38 +++++++++++++ sync/transport_sftp_hash.go | 22 +++++--- sync/transport_sftp_hash_test.go | 7 +++ sync/verify_native.go | 29 ++++++---- sync/verify_remote.go | 95 ++++++++++++++++++++++++++------ 7 files changed, 167 insertions(+), 43 deletions(-) diff --git a/cmd/squirrel/verify.go b/cmd/squirrel/verify.go index 5b35036..1d6aa4c 100644 --- a/cmd/squirrel/verify.go +++ b/cmd/squirrel/verify.go @@ -140,11 +140,11 @@ func printVerifyReport(out, errOut io.Writer, rep sync.RemoteVerifyReport, runEr fmt.Fprintf(out, "verify %s: nothing recorded to verify\n", rep.Destination) return } - fmt.Fprintf(out, "verify %s: run=%d objects=%d verified=%d fingerprinted=%d pending=%d mismatched=%d missing=%d unrecorded=%d packs=%d packs_verified=%d packs_fingerprinted=%d packs_pending=%d packs_mismatched=%d packs_missing=%d\n", + fmt.Fprintf(out, "verify %s: run=%d objects=%d verified=%d fingerprinted=%d pending=%d mismatched=%d missing=%d unrecorded=%d packs=%d packs_verified=%d packs_fingerprinted=%d packs_pending=%d packs_mismatched=%d packs_missing=%d unchecked=%d\n", rep.Destination, rep.RunID, rep.Objects, rep.Verified, rep.Populated, rep.Pending, len(rep.Mismatched), len(rep.Missing), rep.Unrecorded, rep.Packs, rep.PacksVerified, rep.PacksPopulated, rep.PacksPending, - len(rep.PackMismatched), len(rep.PacksMissing)) + len(rep.PackMismatched), len(rep.PacksMissing), rep.Unchecked) printVerifyAlarmTransition(out, errOut, rep) } diff --git a/design/native-mirror.md b/design/native-mirror.md index 57b1be0..341a1fd 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -336,7 +336,8 @@ type transport interface { server, and a relative one is passed as `./` so it never reads as an option. - The transport probes for the command once per session, and a push opens - one session: it hashes a known input on the server and compares. On a + one session: it hashes a known input on the server and compares. The leaf + must be a regular file, so the command never follows a symlink. On a server that runs no programs, like the cloudbox shape, or whose command computes something else, fingerprints stay pending, as today. - Mirror paths are user filenames, so they never go on a command line. @@ -628,12 +629,18 @@ gcs. Each artifact: and recorded, or the artifact fails. Squirrel never replaces it. `squirrel verify` reads these destinations through the transport too -(`sync/verify_native.go`): it lists `objects/` and `packs/` and re-reads -every recorded artifact — through BLAKE3, and through any other hash its row -recorded, on a local disk; through the server's hash command on sftp. On a +(`sync/verify_native.go`): once the marker of every volume that synced there +is in place, it lists `objects/` and `packs/` and re-reads every recorded +artifact — through BLAKE3, and through any other hash its row recorded, on a +local disk; through the server's hash command on sftp. An artifact the +server cannot hash this pass (no command, or a row recorded under another +`hash_algo`) is counted unchecked: neither re-confirmed nor a finding. On a plain destination a BLAKE3 that differs from what the name says (an object's content hash, a pack's key) is a mismatch, whichever backend reported it. +The probe runs once per session once the server has answered it; a session +that could not start the command asks again next time. + The staged copy of a failed artifact goes with the run's staging at the next push's reconcile. The content layouts' guard commits only onto artifact names and displaces nothing (section 3). Both native content layouts are gated on diff --git a/sync/content_native_test.go b/sync/content_native_test.go index e2818a5..f58b465 100644 --- a/sync/content_native_test.go +++ b/sync/content_native_test.go @@ -499,3 +499,41 @@ func (f *nativeContentFixture) flipPack(t *testing.T) { } } } + +// TestNativeContentVerifyWithoutAServerHash: over sftp, an artifact the +// server cannot hash this pass — it lost its command, or the row records +// another hash_algo — is neither re-confirmed nor a finding. +func TestNativeContentVerifyWithoutAServerHash(t *testing.T) { + f := setupNativeContentFixture(t, sftpContent, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + f.pair.Destination.HashAlgo = "sha1" + rep := f.verify(t) + if !rep.Clean() || rep.Unchecked != 1 || rep.Verified != 0 || rep.AlarmRaised { + t.Fatalf("rep = %+v, want the object left unchecked and no alarm", rep) + } +} + +// TestNativeContentVerifyRefusesAnUnmountedRoot: a native content root +// without its volume markers fails the pass instead of reporting every +// object missing. +func TestNativeContentVerifyRefusesAnUnmountedRoot(t *testing.T) { + f := setupNativeContentFixture(t, localContent, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + entries, err := os.ReadDir(f.dst) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if err := os.RemoveAll(filepath.Join(f.dst, e.Name())); err != nil { + t.Fatal(err) + } + } + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err == nil || !strings.Contains(err.Error(), "nothing was checked") || rep.AlarmRaised { + t.Fatalf("VerifyRemote = %+v, %v; want the pass refused without an alarm", rep, err) + } +} diff --git a/sync/transport_sftp_hash.go b/sync/transport_sftp_hash.go index 549dfb8..06c12c5 100644 --- a/sync/transport_sftp_hash.go +++ b/sync/transport_sftp_hash.go @@ -16,6 +16,7 @@ import ( "strings" "github.com/zeebo/blake3" + "golang.org/x/crypto/ssh" ) // errNoServerHash marks a destination that offers squirrel no hash of its @@ -69,6 +70,9 @@ func (t *sftpTransport) ServerHash(_ context.Context, name string) (remoteChecks if err := t.checkName(name); err != nil { return remoteChecksum{}, err } + if err := requireKind(name, kindFile, t.lstat); err != nil { + return remoteChecksum{}, err + } target, err := t.hashTarget(name) if err != nil { return remoteChecksum{}, err @@ -103,31 +107,33 @@ func (t *sftpTransport) hashTarget(name string) (string, error) { return full, nil } -// probeServerHash asks the server, once, to hash a known input, and -// remembers whether its command agreed with this machine. +// probeServerHash asks the server to hash a known input, and remembers +// whether its command agreed with this machine once the server has +// answered: a session that could not even start the command is asked +// again next time. func (t *sftpTransport) probeServerHash() error { t.probeMu.Lock() defer t.probeMu.Unlock() if !t.probed { - t.probeErr = t.runProbe() - t.probed = true + t.probed, t.probeErr = t.runProbe() } return t.probeErr } -func (t *sftpTransport) runProbe() error { +func (t *sftpTransport) runProbe() (bool, error) { h := newArtifactHash(t.hashAlgo) h.Write([]byte(serverHashProbe)) command := serverHashCommands[t.hashAlgo] out, err := t.runCommand(command, strings.NewReader(serverHashProbe)) if err != nil { - return fmt.Errorf("%w: %w", errNoServerHash, err) + _, answered := errors.AsType[*ssh.ExitError](err) + return answered, fmt.Errorf("%w: %w", errNoServerHash, err) } sum, err := parseHashOutput(out, h.Size()) if err != nil || sum != hex.EncodeToString(h.Sum(nil)) { - return fmt.Errorf("%w: %s on the server does not compute %s", errNoServerHash, command, t.hashAlgo) + return true, fmt.Errorf("%w: %s on the server does not compute %s", errNoServerHash, command, t.hashAlgo) } - return nil + return true, nil } // runCommand runs cmd in a session of its own and returns what it printed. diff --git a/sync/transport_sftp_hash_test.go b/sync/transport_sftp_hash_test.go index 6a49496..d1cf332 100644 --- a/sync/transport_sftp_hash_test.go +++ b/sync/transport_sftp_hash_test.go @@ -74,6 +74,13 @@ func TestServerHashRefusesWhatItCannotTrust(t *testing.T) { t.Fatalf("ServerHash of a user's file name = %v, want errNoServerHash", err) } tr.root += "/with space" + unsafe := filepath.Join(tr.root, ObjectsDirName) + if err := os.MkdirAll(unsafe, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(unsafe, strings.Repeat("ab", 32)), []byte("alpha"), 0o644); err != nil { + t.Fatal(err) + } if _, err := tr.ServerHash(ctx, ObjectsDirName+"/"+strings.Repeat("ab", 32)); !errors.Is(err, errNoServerHash) { t.Fatalf("ServerHash under an unsafe root = %v, want errNoServerHash", err) } diff --git a/sync/verify_native.go b/sync/verify_native.go index 9c59d20..7878bfa 100644 --- a/sync/verify_native.go +++ b/sync/verify_native.go @@ -26,7 +26,7 @@ type transportChecksums struct { dest *config.Destination } -func (c transportChecksums) objects(ctx context.Context, rows []store.RemoteObjectRecord) (map[string]map[string]string, error) { +func (c transportChecksums) objects(ctx context.Context, rows []store.RemoteObjectRecord) (artifactChecksums, error) { names := namerFor(c.dest) want := make(map[string]string, len(rows)) for _, r := range rows { @@ -35,7 +35,7 @@ func (c transportChecksums) objects(ctx context.Context, rows []store.RemoteObje return c.read(ctx, ObjectsDirName, want) } -func (c transportChecksums) packs(ctx context.Context, packs []store.RemotePackRecord) (map[string]map[string]string, error) { +func (c transportChecksums) packs(ctx context.Context, packs []store.RemotePackRecord) (artifactChecksums, error) { names := namerFor(c.dest) want := make(map[string]string, len(packs)) for _, p := range packs { @@ -47,42 +47,47 @@ func (c transportChecksums) packs(ctx context.Context, packs []store.RemotePackR // read lists dir and hashes each file a row recorded; want maps a // basename to the algo its row recorded, "" while pending. A dir that does // not exist holds nothing. -func (c transportChecksums) read(ctx context.Context, dir string, want map[string]string) (map[string]map[string]string, error) { +func (c transportChecksums) read(ctx context.Context, dir string, want map[string]string) (artifactChecksums, error) { + out := artifactChecksums{byName: map[string]map[string]string{}, unchecked: map[string]bool{}} entries, err := c.tr.List(ctx, dir) if errors.Is(err, fs.ErrNotExist) { - return nil, nil + return out, nil } if err != nil { - return nil, err + return artifactChecksums{}, err } - out := make(map[string]map[string]string, len(entries)) for _, e := range entries { if e.kind != kindFile { continue } recorded, ok := want[e.name] if !ok { - out[e.name] = nil + out.byName[e.name] = nil continue } hashes, err := c.hash(ctx, path.Join(dir, e.name), recorded) if err != nil { - return nil, fmt.Errorf("hash %s: %w", e.name, err) + return artifactChecksums{}, fmt.Errorf("hash %s: %w", e.name, err) } - out[e.name] = hashes + out.byName[e.name] = hashes + out.unchecked[e.name] = hashes == nil } return out, nil } // hash is the checksums of the file at name: its BLAKE3, and the hash its // row recorded when this machine computes that one too, read back from a -// local disk; the server's hash command's answer on sftp, none when the -// server runs no command squirrel trusts. +// local disk; the server's hash command's answer on sftp. It is nil when +// the sftp server cannot answer for the row: no command squirrel trusts, or +// a row recorded under another hash_algo. func (c transportChecksums) hash(ctx context.Context, name, recorded string) (map[string]string, error) { if !readsBack(c.dest) { + if recorded != "" && recorded != c.dest.HashAlgo { + return nil, nil + } cs, err := c.tr.ServerHash(ctx, name) if errors.Is(err, errNoServerHash) { - return map[string]string{}, nil + return nil, nil } if err != nil { return nil, err diff --git a/sync/verify_remote.go b/sync/verify_remote.go index 9458564..cc9a6ff 100644 --- a/sync/verify_remote.go +++ b/sync/verify_remote.go @@ -38,6 +38,11 @@ type RemoteVerifyReport struct { // remote listing. Missing []string Mismatched []RemoteObjectMismatch + // Unchecked counts recorded objects and packs that are present but + // that the destination could not hash this pass (an sftp server + // without the hash command, or one recorded under another hash_algo): + // neither re-confirmed nor a finding. + Unchecked int // Pack counters mirror the object ones for a packed destination's // per-pack sweep — one fingerprint check per pack vouches for every @@ -200,28 +205,63 @@ func upgradeFingerprintVectors(ctx context.Context, s *store.Store, destination } // checksumSource reads the checksums a verify pass compares for a -// destination's recorded objects and packs, keyed by basename then hash -// name; a stored artifact nobody recorded maps to no hashes. +// destination's recorded objects and packs. type checksumSource interface { - objects(ctx context.Context, rows []store.RemoteObjectRecord) (map[string]map[string]string, error) - packs(ctx context.Context, packs []store.RemotePackRecord) (map[string]map[string]string, error) + objects(ctx context.Context, rows []store.RemoteObjectRecord) (artifactChecksums, error) + packs(ctx context.Context, packs []store.RemotePackRecord) (artifactChecksums, error) +} + +// artifactChecksums is what a pass read of a destination's artifacts: the +// checksums of each stored one, keyed by basename then hash name (none for +// one nobody recorded), and the recorded ones present but not hashed this +// pass, which count neither as verified nor as a finding. +type artifactChecksums struct { + byName map[string]map[string]string + unchecked map[string]bool } // verifyThrough runs the sweeps against dest through squirrel's own -// transport on a native destination, through rclone (and the S3 API) -// otherwise. +// transport on a native destination, once its volume markers show the +// root is the right one, and through rclone (and the S3 API) otherwise. func verifyThrough(ctx context.Context, s *store.Store, rcl *Rclone, dest *config.Destination, rows []store.RemoteObjectRecord, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { if !dest.Native() { return verifyRecorded(ctx, s, rcloneChecksums{rcl: rcl, dest: dest}, dest, rows, packs, rep) } + volumes, err := syncedVolumes(ctx, s, dest.Name) + if err != nil { + return err + } tr, err := openReadOnly(ctx, dest) if err != nil { return err } defer func() { _ = tr.Close() }() + if err := requireVolumeMarkers(ctx, tr, dest, volumes); err != nil { + return err + } return verifyRecorded(ctx, s, transportChecksums{tr: tr, dest: dest}, dest, rows, packs, rep) } +// syncedVolumes names the volumes that have a successful sync to the +// destination: those whose marker its root must hold. +func syncedVolumes(ctx context.Context, s *store.Store, destination string) ([]string, error) { + all, err := s.ListVolumes(ctx) + if err != nil { + return nil, fmt.Errorf("list volumes: %w", err) + } + var out []string + for _, v := range all { + _, err := s.LatestSuccessfulSyncRun(ctx, v.ID, destination) + switch { + case err == nil: + out = append(out, v.Name) + case !store.IsNotFound(err): + return nil, fmt.Errorf("lookup last successful sync of %q to %q: %w", v.Name, destination, err) + } + } + return out, nil +} + // verifyRecorded sweeps a destination's recorded content objects (the // large-file per-object sweep, shared with content-addressed) and, for a // packed destination, its recorded packs — one fingerprint check per pack @@ -240,6 +280,17 @@ func verifyRecorded(ctx context.Context, s *store.Store, src checksumSource, des return nil } +// countUnchecked counts an artifact the destination could not hash this +// pass: as unchecked when its row records a fingerprint, as still pending +// when it records none. +func countUnchecked(rep *RemoteVerifyReport, fingerprinted bool, pending *int) { + if fingerprinted { + rep.Unchecked++ + return + } + *pending++ +} + // contentMismatch is the finding when a plain destination reports the // BLAKE3 of an artifact whose name says what its BLAKE3 must be (an // object's content hash, a pack's key) and the two differ. It holds for @@ -256,7 +307,7 @@ func contentMismatch(dest *config.Destination, hashes map[string]string, want [] // verifyRecordedObjects compares the remote listing against the recorded // rows and applies the per-object outcome to the store and the report. func verifyRecordedObjects(ctx context.Context, s *store.Store, src checksumSource, dest *config.Destination, rows []store.RemoteObjectRecord, rep *RemoteVerifyReport) error { - byName, err := src.objects(ctx, rows) + got, err := src.objects(ctx, rows) if err != nil { return fmt.Errorf("read object checksums from %q: %w", dest.Name, err) } @@ -264,12 +315,16 @@ func verifyRecordedObjects(ctx context.Context, s *store.Store, src checksumSour matched := 0 for _, row := range rows { hash := hex.EncodeToString(row.Blake3) - hashes, ok := byName[names.object(row.Blake3)] + hashes, ok := got.byName[names.object(row.Blake3)] if !ok { rep.Missing = append(rep.Missing, hash) continue } matched++ + if got.unchecked[names.object(row.Blake3)] { + countUnchecked(rep, row.ChecksumAlgo.Valid, &rep.Pending) + continue + } if m, bad := contentMismatch(dest, hashes, row.Blake3); bad { rep.Mismatched = append(rep.Mismatched, m) continue @@ -295,7 +350,7 @@ func verifyRecordedObjects(ctx context.Context, s *store.Store, src checksumSour Actual: actual, }) } - rep.Unrecorded = len(byName) - matched + rep.Unrecorded = len(got.byName) - matched return nil } @@ -306,12 +361,14 @@ type rcloneChecksums struct { dest *config.Destination } -func (c rcloneChecksums) objects(ctx context.Context, rows []store.RemoteObjectRecord) (map[string]map[string]string, error) { - return readObjectChecksums(ctx, c.rcl, c.dest, rows) +func (c rcloneChecksums) objects(ctx context.Context, rows []store.RemoteObjectRecord) (artifactChecksums, error) { + byName, err := readObjectChecksums(ctx, c.rcl, c.dest, rows) + return artifactChecksums{byName: byName}, err } -func (c rcloneChecksums) packs(ctx context.Context, packs []store.RemotePackRecord) (map[string]map[string]string, error) { - return readPackChecksums(ctx, c.rcl, c.dest, packs) +func (c rcloneChecksums) packs(ctx context.Context, packs []store.RemotePackRecord) (artifactChecksums, error) { + byName, err := readPackChecksums(ctx, c.rcl, c.dest, packs) + return artifactChecksums{byName: byName}, err } // readObjectChecksums reads the provider checksums verification compares, @@ -385,18 +442,22 @@ func verifyObjectHashTypes(dest *config.Destination, rows []store.RemoteObjectRe // check per pack vouches for every content it holds, so a packed // destination is swept per pack rather than per member. func verifyRecordedPacks(ctx context.Context, s *store.Store, src checksumSource, dest *config.Destination, packs []store.RemotePackRecord, rep *RemoteVerifyReport) error { - byName, err := src.packs(ctx, packs) + got, err := src.packs(ctx, packs) if err != nil { return fmt.Errorf("read pack checksums from %q: %w", dest.Name, err) } names := namerFor(dest) for _, row := range packs { key := hex.EncodeToString(row.PackKey) - hashes, ok := byName[names.pack(row.PackKey)] + hashes, ok := got.byName[names.pack(row.PackKey)] if !ok { rep.PacksMissing = append(rep.PacksMissing, key) continue } + if got.unchecked[names.pack(row.PackKey)] { + countUnchecked(rep, row.ChecksumAlgo.Valid, &rep.PacksPending) + continue + } if m, bad := contentMismatch(dest, hashes, row.PackKey); bad { rep.PackMismatched = append(rep.PackMismatched, m) continue @@ -526,10 +587,10 @@ func recordVerifyOutcome(ctx context.Context, s *store.Store, rep *RemoteVerifyR status = store.RunStatusPartial errMsg = fmt.Sprintf("%d object(s)/pack(s)/mirror copies failed verification on %q", rep.failures(), rep.Destination) } - note := fmt.Sprintf("destination=%s objects=%d verified=%d fingerprinted=%d pending=%d mismatched=%d missing=%d unrecorded=%d packs=%d packs_verified=%d packs_fingerprinted=%d packs_pending=%d packs_mismatched=%d packs_missing=%d paths=%d paths_reread=%d paths_changed=%d paths_missing=%d", + note := fmt.Sprintf("destination=%s objects=%d verified=%d fingerprinted=%d pending=%d mismatched=%d missing=%d unrecorded=%d packs=%d packs_verified=%d packs_fingerprinted=%d packs_pending=%d packs_mismatched=%d packs_missing=%d unchecked=%d paths=%d paths_reread=%d paths_changed=%d paths_missing=%d", rep.Destination, rep.Objects, rep.Verified, rep.Populated, rep.Pending, len(rep.Mismatched), len(rep.Missing), rep.Unrecorded, rep.Packs, rep.PacksVerified, rep.PacksPopulated, rep.PacksPending, len(rep.PackMismatched), len(rep.PacksMissing), - rep.Paths, rep.PathsReread, len(rep.PathsChanged), len(rep.PathsMissing)) + rep.Unchecked, rep.Paths, rep.PathsReread, len(rep.PathsChanged), len(rep.PathsMissing)) if err := s.AppendRunAudit(ctx, store.RunAuditEntry{ RunID: rep.RunID, Transition: store.TransitionVerifyDestination, Note: note, }); err != nil { From 5185997ba7f98a2bbd5fd7cdd98ce17bc48dba6f Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 03:58:18 +0200 Subject: [PATCH 41/61] sync, agent, docs: say what native destinations do now, and say it positively Comments that described the native root, the staging directory, restore and the scheduler's verify phase as a mirror's alone now cover the content layouts too, and the ones phrased as what code does not do say what it does. The verification guide names the unchecked count, the marker check and the demotion a finding causes. --- agent/scheduler.go | 10 +++++--- docs/src/content/docs/guides/verification.md | 10 ++++++-- sync/artifacts_rclone.go | 4 +-- sync/artifacts_transport.go | 6 ++--- sync/handler.go | 6 ++--- sync/readback.go | 5 ++-- sync/restore_archive.go | 2 +- sync/snapshot.go | 2 +- sync/sync.go | 27 ++++++++++---------- sync/transport_guard.go | 5 ++-- sync/transport_local.go | 4 +-- 11 files changed, 45 insertions(+), 36 deletions(-) diff --git a/agent/scheduler.go b/agent/scheduler.go index dc20b03..62fbcb1 100644 --- a/agent/scheduler.go +++ b/agent/scheduler.go @@ -252,10 +252,12 @@ func (s *scheduler) tick(ctx context.Context) { } // The verify and durability-pull cadences key on destinations and peer // nodes rather than volumes, so they run after the per-volume loop as - // their own phases. Both are read-only / metadata-only and take no - // volume lock: verify touches only the remote-object bookkeeping, and a - // durability pull only merges peer-supplied vectors — neither races the - // per-volume index/sync/audit work the loop above coordinates. + // their own phases. Both only read the destination and take no volume + // lock: verify updates only squirrel's records of what the destination + // holds, a mirror copy's only while its row is still where the pass + // read it, and a durability pull only merges peer-supplied vectors — so + // neither is confused by the per-volume index/sync/audit work the loop + // above coordinates. s.evaluateVerify(ctx) s.evaluateDurabilityPulls(ctx) } diff --git a/docs/src/content/docs/guides/verification.md b/docs/src/content/docs/guides/verification.md index 9481ac6..15f6572 100644 --- a/docs/src/content/docs/guides/verification.md +++ b/docs/src/content/docs/guides/verification.md @@ -75,6 +75,9 @@ artifact), then per recorded object: - a **match** stamps the object verified in the index; - an object **without a fingerprint yet** (uploaded before this feature, or whose capture failed) gets one recorded and is counted separately; +- an object an sftp server **cannot hash this pass** — its hash command is + gone, or the object was fingerprinted under another `hash_algo` — is counted + as `unchecked`: neither re-confirmed nor a finding; - a **mismatch or missing object** prints one loud line per object and exits non-zero — that is potential offsite corruption or tampering, and squirrel deliberately leaves both the destination and the recorded fingerprint untouched @@ -141,9 +144,12 @@ transport, without rclone. Each pass: BLAKE3, until it has read a tenth of the stored bytes, so every byte is read again within about ten passes. -A copy found gone or changed prints one loud line, latches the +A pass first reads every volume's `.squirrel-volume` marker and stops, checking +nothing, when one is missing: an unmounted disk must not read as every copy +gone. A copy found gone or changed prints one loud line, latches the [alarm](#a-mismatch-latches-an-alarm), and stops counting as evidence for its -file. The next push writes it again as long as the index still holds that file +file: the volume's evidence drops to `presence+size`, so offload checks each +file's own copy until the next push writes the lost one again. The next push writes it again as long as the index still holds that file there, with a warning; the copy that was found keeps its place in history if the push has to move it aside. diff --git a/sync/artifacts_rclone.go b/sync/artifacts_rclone.go index 306f025..ecf0f53 100644 --- a/sync/artifacts_rclone.go +++ b/sync/artifacts_rclone.go @@ -48,8 +48,8 @@ func (a *rcloneArtifacts) rootEmpty(ctx context.Context) (bool, error) { return a.rcl.remoteRootEmpty(ctx, remoteSubpathURI(a.dest, ""), rootMarkerNames(a.dest), checkersArgs(a.dest)...) } -// reconcile has nothing to settle: rclone lands every artifact under its -// own name, and squirrel records it only after it landed. +// reconcile returns at once: rclone lands every artifact under its own +// name, and squirrel records it only after it landed. func (a *rcloneArtifacts) reconcile(context.Context, *Report, int64) error { return nil } // put re-hashes src immediately before the transfer and refuses diff --git a/sync/artifacts_transport.go b/sync/artifacts_transport.go index 6a10b0e..356c7d9 100644 --- a/sync/artifacts_transport.go +++ b/sync/artifacts_transport.go @@ -36,9 +36,9 @@ func (a *transportArtifacts) root(ctx context.Context, runID int64) (transport, return a.guarded(ctx, nameGuard{volumeDir: a.volumeDir, runID: runID, content: true, finished: a.runFinished}) } -// markers gates the push on the volume marker, as a native mirror does: -// written under --init, which also creates a missing local root, and -// refused otherwise. A dry run checks nothing. +// markers gates a push that writes on the volume marker, as a native +// mirror does: written under --init, which also creates a missing local +// root, and refused otherwise. func (a *transportArtifacts) markers(ctx context.Context, opts Options) error { if opts.DryRun { return nil diff --git a/sync/handler.go b/sync/handler.go index d585fb4..13b89c0 100644 --- a/sync/handler.go +++ b/sync/handler.go @@ -161,8 +161,8 @@ func contentPusherFor(s *store.Store, tools Tools, p Pair) (contentPusher, error return pusher, nil } -// openDestinationTransport opens a native mirror's destination root: a -// directory on this machine, or on an sftp server. +// openDestinationTransport opens a native destination's root: a directory +// on this machine, or on an sftp server. func openDestinationTransport(ctx context.Context, dest *config.Destination) (transport, error) { if dest.Type == "sftp" { return dialSFTP(ctx, dest) @@ -170,7 +170,7 @@ func openDestinationTransport(ctx context.Context, dest *config.Destination) (tr return openLocalTransport(dest.Root) } -// openReadOnly opens a native mirror's root for reading alone: the name +// openReadOnly opens a native destination's root for reading alone: the name // guard, held by no run, refuses every move and removal, and every call is // bounded by progress. func openReadOnly(ctx context.Context, dest *config.Destination) (transport, error) { diff --git a/sync/readback.go b/sync/readback.go index 5634105..f83176d 100644 --- a/sync/readback.go +++ b/sync/readback.go @@ -15,8 +15,9 @@ import ( var errReadBackMismatch = errors.New("the stored bytes read back differently from the bytes sent") // readsBack reports whether dest is a disk squirrel reads back, BLAKE3 over -// what it just stored, before trusting it: a local destination. An sftp -// server's bytes are read back only through its hash command. +// what it just stored, before trusting it: a local destination. On sftp +// squirrel asks the server's hash command instead, and downloads a file +// only to confirm one it finds already at an artifact's name. func readsBack(dest *config.Destination) bool { return dest.Type == "local" } diff --git a/sync/restore_archive.go b/sync/restore_archive.go index 2ba50ff..c8d23a1 100644 --- a/sync/restore_archive.go +++ b/sync/restore_archive.go @@ -67,7 +67,7 @@ func restoreArchive(ctx context.Context, s *store.Store, rcl *Rclone, vol *confi // archiveFetcher is how a restore reads dest's artifacts: through one // read-only transport for the whole restore on a native destination, -// through rclone otherwise. A dry run fetches nothing, so it opens nothing. +// through rclone otherwise. A dry run only counts, so it gets a nil fetcher. // release closes what it opened. func archiveFetcher(ctx context.Context, rcl *Rclone, dest *config.Destination, dryRun bool) (func(context.Context, string, string) error, func(), error) { if !dest.Native() { diff --git a/sync/snapshot.go b/sync/snapshot.go index c38750c..cc4bff7 100644 --- a/sync/snapshot.go +++ b/sync/snapshot.go @@ -212,7 +212,7 @@ func (s rcloneShelf) remove(ctx context.Context, name string) error { return s.rcl.deleteFile(ctx, s.dir+"/"+name) } -// transportShelf is a native mirror's /.squirrel-index/, reached +// transportShelf is a native destination's /.squirrel-index/, reached // through runID's guarded transport, which open returns. type transportShelf struct { open func(context.Context) (transport, error) diff --git a/sync/sync.go b/sync/sync.go index a21cff0..167abb9 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -50,11 +50,12 @@ const RestoreHistoryDirName = ".squirrel-restore-history" // and from peer-sync so a snapshot is never mistaken for user content. const IndexDirName = ".squirrel-index" -// StagingDirName is the per-volume directory at a native mirror destination -// that holds in-flight writes: //.squirrel-staging/ -// run-/. A version is staged there, hashed while it streams, -// and renamed onto its path only once its predecessor is in history. Like -// the other reserved directories it never travels as user content. +// StagingDirName is the per-volume directory at a native destination that +// holds in-flight writes: //.squirrel-staging/ +// run-/. A mirror version or a content artifact is staged there, +// hashed while it streams, and renamed onto its name once confirmed — a +// mirror version once its predecessor is in history. Like the other +// reserved directories it never travels as user content. const StagingDirName = ".squirrel-staging" // ErrRefused marks a preflight safety refusal: a gate that declined to @@ -973,14 +974,14 @@ type RestoreOptions struct { } // Restore reverses Sync back to the local filesystem, recording a -// kind='restore' runs row. A native mirror (local, or sftp without crypt) -// is read through squirrel's own transport and every file is placed -// through a temporary file beside its path, checked against the index — -// or, on a fresh machine, against the mirror's receipts; rcl may be nil -// for one. An rclone mirror is copied down with rclone. The -// content-addressed and packed layouts (which have no mirrored tree) -// resolve each present path to its content hash in the local index, fetch -// the per-hash object or pack member, and re-hash it before writing. +// kind='restore' runs row. A native destination (local, or sftp without +// crypt) is read through squirrel's own transport, so rcl may be nil for +// one. A native mirror's every file is placed through a temporary file +// beside its path, checked against the index — or, on a fresh machine, +// against the mirror's receipts. An rclone mirror is copied down with +// rclone. The content-addressed and packed layouts (which have no mirrored +// tree) resolve each present path to its content hash in the local index, +// fetch the per-hash object or pack member, and re-hash it before writing. // Restore is read-only against both the index and the destination — it // never uploads, never mutates content rows. An in-place restore without // InPlace is refused on a non-empty volume, and with it every file it diff --git a/sync/transport_guard.go b/sync/transport_guard.go index 6190f1c..f79490f 100644 --- a/sync/transport_guard.go +++ b/sync/transport_guard.go @@ -21,9 +21,8 @@ var errGuardRefused = errors.New("the name guard refuses this operation") type nameGuard struct { volumeDir string // the volume's directory under the destination root runID int64 // the push holding the guard - // content marks a content-addressed or packed push: its commits land - // on artifact names instead of the mirrored tree, and it displaces - // nothing. + // content marks a content-addressed or packed push, whose commits land + // on artifact names (see artifact); displacement is a mirror's alone. content bool // bootstrap lets a push under --init write the volume marker, before // it holds a run. diff --git a/sync/transport_local.go b/sync/transport_local.go index 264ae31..72982a1 100644 --- a/sync/transport_local.go +++ b/sync/transport_local.go @@ -156,8 +156,8 @@ func (t *localTransport) Remove(_ context.Context, name string) error { return t.root.Remove(filepath.FromSlash(name)) } -// ServerHash: a local disk runs no hash of its own; squirrel reads its -// bytes back instead. +// ServerHash is errNoServerHash on a local disk: squirrel reads its bytes +// back itself (readBack). func (t *localTransport) ServerHash(context.Context, string) (remoteChecksum, error) { return remoteChecksum{}, errNoServerHash } From 72a1b4e1b46c7253ea12c9935d9be201ae6f4e62 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 04:41:05 +0200 Subject: [PATCH 42/61] sync: refuse names a folding mirror cannot tell apart, and follow case-only renames A mirror push now probes, inside staging, whether the destination folds case or Unicode normalization before its first write. On one that does, a present path whose name, or a parent's, folds onto another present path's where one is a file is refused: nothing is staged or displaced for it, and the run fails before its receipt, as drift does. A version recorded under another spelling whose path left the source moves aside as its record first, so a case-only rename no longer leaves the old row live over the new spelling's bytes. Directory displacement takes every live row under any spelling of the directory along. The guard lets a mirror push remove its own name probe. The invariant check now also fails when two live rows name one folded entry. --- design/native-mirror.md | 51 +++- docs/src/content/docs/layouts/mirror.md | 18 ++ go.mod | 2 +- sync/destination_root.go | 2 +- sync/mirror_fold.go | 365 ++++++++++++++++++++++++ sync/mirror_fold_test.go | 362 +++++++++++++++++++++++ sync/mirror_test.go | 63 +++- sync/mirror_translate.go | 7 +- sync/mirror_write.go | 72 ++++- sync/transport_guard.go | 4 +- sync/transport_guard_test.go | 5 + 11 files changed, 914 insertions(+), 37 deletions(-) create mode 100644 sync/mirror_fold.go create mode 100644 sync/mirror_fold_test.go diff --git a/design/native-mirror.md b/design/native-mirror.md index 341a1fd..1d06c95 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -263,7 +263,9 @@ type transport interface { name to `.squirrel-history/run-/` (displacement); - under `--init`, before the push holds a run, the marker's own staging: it is written to `.squirrel-staging/volume-marker` and renamed onto - `.squirrel-volume`, and a stale staged copy may be removed. + `.squirrel-volume`, and a stale staged copy may be removed; + - for a mirror push holding a run, `Remove` of the name probe, + `.squirrel-staging/fold-probe-é` (see "Names the destination folds"). So the marker and the ride-along snapshot land whole or not at all, like every path: a write that fails halfway leaves its partial copy in staging, @@ -356,6 +358,7 @@ The tree keeps the shape it has today and gains two reserved entries: .squirrel-index/run-7 # receipt: run 7's manifest segment .squirrel-index/index-…-run-7.db # ride-along index snapshot .squirrel-staging/ # in-flight writes, squirrel-owned + .squirrel-staging/fold-probe-é # name probe, removed within the push ``` `.squirrel-staging` joins the reserved names in `reservedSubtreeFilter`, @@ -472,6 +475,48 @@ new version is committed, and the new version stays in staging until then. Between steps 3 and 4 the live path is briefly empty. That costs availability until the next push, never content. +### Names the destination folds + +APFS and HFS+ resolve names that differ only by case, or only by Unicode +normalization (composed `é` against `e` plus a combining accent), to the same +entry; exFAT and NTFS fold case. A source on a Linux disk can hold both +spellings as two files, and a case-only rename at any source shows up in the +index as one path gone and another new. Squirrel's records key on the exact +spelling, so on such a destination the records alone would let a write of +`A.jpg` move `a.jpg`'s bytes to history as unrecorded while `a.jpg`'s row +stayed `live` over the other spelling's bytes, breaking invariant 1. + +- **Probe.** Before its first write, each push writes + `.squirrel-staging/fold-probe-é`, looks it up by an upper-case and by a + decomposed spelling, and removes it again (`sync/mirror_fold.go`). A lookup + that finds the file means the destination folds that way. The probe runs on + every push that writes, so a disk reformatted between pushes is probed + again; one a crashed push left behind is removed by the next probe. +- **Collisions** (decision 6). On a destination that folds, execute groups + every planned path and every `live` row by the folded form of each name + along the path. Two present paths clash when one's name folds onto the + other's under another spelling where at least one is a file: two files, or + a file where the other's parent directory is. The spelling the destination + already holds (a `live` row of a present path) wins, then the first by byte + order; every other planned path claiming that name is refused. A refused + path is never staged and displaces nothing. It fails the run before its + seal, as drift does, with a warning naming both spellings, so the watermark + holds until one of them is renamed at the source. Two directory spellings + never clash: the destination merges them. +- **Case-only renames.** A `live` row under another spelling whose path is no + longer present at the source is displaced as its record before the planned + path lands: `a.jpg` moves to `.squirrel-history/run-/a.jpg` and becomes + `displaced`, then `A.jpg` is committed. A file in the way of a planned + path's directory moves the same way, and a directory displaced because a + file replaced it takes every live row under any spelling of it along + (`nameFolding.under`). +- **What stays behind.** A directory keeps the spelling it was created with: + after `Photos/` is renamed to `photos/` at the source, the files land under + the existing `Photos/` directory. Every lookup by the recorded name finds + them, but a restore without an index, which walks the tree, restores them + under `Photos/`, as files no receipt names. +- A dry run doesn't probe, so its preview doesn't show collisions. + ### Crash points | Crash after | Destination | Reconcile at the next push | @@ -517,8 +562,8 @@ usual: refused for that path, and nothing is displaced. - Destinations that ignore Unicode normalization get the same treatment, for names that differ only in composed versus decomposed form. - - The first push probes the destination's case and normalization behaviour - inside staging. + - Each push that writes probes the destination's case and normalization + behaviour inside staging. - **Failures:** - the disk fills up or the quota runs out mid-write; - the history directory can't be written; diff --git a/docs/src/content/docs/layouts/mirror.md b/docs/src/content/docs/layouts/mirror.md index ef2cbd9..e47419a 100644 --- a/docs/src/content/docs/layouts/mirror.md +++ b/docs/src/content/docs/layouts/mirror.md @@ -45,6 +45,24 @@ recorded refuses, unless the root is empty and squirrel holds no records for it. So a native mirror starts on a fresh or emptied root: squirrel does not adopt a tree some other tool wrote, rclone included. +### Names a disk can't tell apart + +Disks formatted APFS or HFS+ (macOS), exFAT or NTFS treat `a.jpg` and `A.jpg` +as one name, and APFS and HFS+ also treat a composed `é` and an `e` followed by +a combining accent as one. Before its first write, each push checks how the +destination compares names with one small file in `.squirrel-staging/`. + +- When two of your files have names the destination can't tell apart, or one + file's name matches the other's directory, only one of them is written: the + one already on the destination, otherwise the first by name. The other is + left out and nothing moves for it, every other file still lands, and the run + fails with a warning naming both spellings. Rename one of them, index, and + sync again. +- A file you renamed only in case moves from its old spelling into + `.squirrel-history/` and lands under the new one. +- A directory keeps the spelling it was created with: after you rename + `Photos/` to `photos/`, the files land inside the existing `Photos/`. + On sftp, squirrel checks the server's host key against `known_hosts` and refuses a server it does not know (see [sftp keys](/squirrel/reference/configuration/#sftp)). diff --git a/go.mod b/go.mod index 3e4f075..53c9f87 100644 --- a/go.mod +++ b/go.mod @@ -19,6 +19,7 @@ require ( github.com/zeebo/blake3 v0.2.4 golang.org/x/crypto v0.54.0 golang.org/x/sys v0.47.0 + golang.org/x/text v0.40.0 modernc.org/sqlite v1.50.1 ) @@ -85,7 +86,6 @@ require ( github.com/zeebo/xxh3 v1.1.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/net v0.56.0 // indirect - golang.org/x/text v0.40.0 // indirect gopkg.in/ini.v1 v1.67.2 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect modernc.org/libc v1.72.3 // indirect diff --git a/sync/destination_root.go b/sync/destination_root.go index 778f50c..51a7c1d 100644 --- a/sync/destination_root.go +++ b/sync/destination_root.go @@ -77,7 +77,7 @@ func (h *destinationRoot) clearFinishedStaging(ctx context.Context, rep *Report, return fmt.Errorf("list %s: %w", dir, err) } for _, e := range runs { - if e.name == markerStagingBase { + if e.name == markerStagingBase || isFoldProbe(e.name) { continue } runID, ok := stagingRunID(e) diff --git a/sync/mirror_fold.go b/sync/mirror_fold.go new file mode 100644 index 0000000..76fe941 --- /dev/null +++ b/sync/mirror_fold.go @@ -0,0 +1,365 @@ +package sync + +import ( + "context" + "database/sql" + "errors" + "fmt" + "path" + "sort" + "strings" + "time" + "unicode" + + "golang.org/x/text/unicode/norm" + + "github.com/mbertschler/squirrel/store" +) + +// foldProbeBase is the file a mirror push writes into staging to learn how +// the destination compares names. foldProbeCase is the same name with its +// ASCII letters in upper case, foldProbeNorm the same name decomposed. +const ( + foldProbeBase = "fold-probe-\u00e9" + foldProbeCase = "FOLD-PROBE-\u00e9" + foldProbeNorm = "fold-probe-e\u0301" +) + +// foldProbeName is where a push probes the destination's names: +// /.squirrel-staging/fold-probe-é. +func foldProbeName(volumeDir string) string { + return path.Join(volumeDir, StagingDirName, foldProbeBase) +} + +// isFoldProbe reports whether a staging entry is the name probe, as a +// destination that stores names decomposed lists it. +func isFoldProbe(name string) bool { + return norm.NFC.String(name) == foldProbeBase +} + +// nameFolding is how a destination compares names: whether it resolves +// names that differ only by case, or only by Unicode normalization, to the +// same entry (APFS does both, exFAT folds case). +type nameFolding struct { + caseless, normless bool +} + +func (f nameFolding) folds() bool { return f.caseless || f.normless } + +// key is the one spelling of s the destination resolves every equivalent +// spelling to. +func (f nameFolding) key(s string) string { + if f.normless { + s = norm.NFC.String(s) + } + if f.caseless { + s = strings.Map(foldRune, s) + } + return s +} + +// under reports whether rel lies below dir, as the destination resolves +// both. +func (f nameFolding) under(rel, dir string) bool { + return strings.HasPrefix(f.key(rel), f.key(dir)+"/") +} + +// foldRune maps r to the smallest rune of its simple case folding orbit, +// so every case variant of a rune maps to the same one. +func foldRune(r rune) rune { + least := r + for f := unicode.SimpleFold(r); f != r; f = unicode.SimpleFold(f) { + least = min(least, f) + } + return least +} + +// probeFolding writes the name probe and looks it up by its upper-case and +// its decomposed spelling: whichever the destination finds, it folds. The +// probe is removed again; one a crashed push left behind is removed first. +func (w *mirrorWriter) probeFolding(ctx context.Context) (nameFolding, error) { + dir := path.Join(w.h.vol.Name, StagingDirName) + name := foldProbeName(w.h.vol.Name) + if err := w.removeProbe(ctx, name); err != nil { + return nameFolding{}, err + } + if err := w.tr.Put(ctx, name, strings.NewReader(""), time.Now()); err != nil { + return nameFolding{}, fmt.Errorf("write the name probe %s: %w", name, err) + } + var f nameFolding + var err error + if f.caseless, err = present(ctx, w.tr, path.Join(dir, foldProbeCase)); err != nil { + return nameFolding{}, fmt.Errorf("probe case folding: %w", err) + } + if f.normless, err = present(ctx, w.tr, path.Join(dir, foldProbeNorm)); err != nil { + return nameFolding{}, fmt.Errorf("probe normalization folding: %w", err) + } + return f, w.removeProbe(ctx, name) +} + +func (w *mirrorWriter) removeProbe(ctx context.Context, name string) error { + left, err := present(ctx, w.tr, name) + if err != nil || !left { + return err + } + if err := w.tr.Remove(ctx, name); err != nil { + return fmt.Errorf("remove the name probe %s: %w", name, err) + } + return nil +} + +// foldPlan is how a push writes to a destination that folds names: the +// planned paths it refuses, each with the spelling it collides with, and +// for each path it writes, the versions recorded under another spelling of +// its name or a parent's, which move aside before it lands. +type foldPlan struct { + refused map[string]string + displace map[string][]string +} + +// foldMember is one path's claim on a folded name: a file at it, or a +// directory the path lies under. +type foldMember struct { + path string + spelling string // how the path spells the name + dir bool + planned bool // the push plans the path: it is present at the source + live bool // a live record holds the path +} + +// foldEntity is one thing the destination can hold at a folded name: a +// file under one spelling, or a directory under any. +type foldEntity struct { + name string + members []foldMember + present bool // a present path claims it + onDest bool // a live record of a present path claims it +} + +// planFolding decides how every planned path lands on a folding +// destination. Two present paths whose names, or whose parents' names, +// fold together where one is a file cannot both land: the one the +// destination already holds wins, then the first by spelling, and every +// other is refused, displacing nothing. A version recorded under another +// spelling whose path is no longer present — a rename that changed only +// case — moves aside as its record before the planned path lands. +func (w *mirrorWriter) planFolding(ctx context.Context, ops *mirrorOps) (foldPlan, error) { + plan := foldPlan{refused: map[string]string{}, displace: map[string][]string{}} + groups := w.foldGroups(ops) + isPresent := w.presentAtSource(ctx) + var candidates []string + for key, members := range groups { + if collides(members) { + candidates = append(candidates, key) + } + } + sort.Strings(candidates) + for _, key := range candidates { + entities, err := foldEntities(groups[key], isPresent) + if err != nil { + return foldPlan{}, err + } + plan.refuse(entities) + } + for _, key := range candidates { + plan.displaceOthers(groups[key], isPresent) + } + return plan, nil +} + +// foldGroups gathers, for every folded name along a planned path, the +// claims of every planned path and live record on it. +func (w *mirrorWriter) foldGroups(ops *mirrorOps) map[string][]foldMember { + interest := map[string]bool{} + claims := map[string]*foldMember{} + for _, p := range ops.paths { + rel := p.delta.Path + claims[rel] = &foldMember{path: rel, planned: true} + key := w.fold.key(rel) + for i := range key { + if key[i] == '/' { + interest[key[:i]] = true + } + } + interest[key] = true + } + for rel := range w.live { + if c, ok := claims[rel]; ok { + c.live = true + continue + } + claims[rel] = &foldMember{path: rel, live: true} + } + groups := map[string][]foldMember{} + for rel, c := range claims { + key := w.fold.key(rel) + for i := range len(key) + 1 { + if i < len(key) && key[i] != '/' { + continue + } + if !interest[key[:i]] { + continue + } + m := *c + m.spelling, m.dir = spellingAt(rel, strings.Count(key[:i], "/")), i < len(key) + groups[key[:i]] = append(groups[key[:i]], m) + } + } + return groups +} + +// spellingAt is rel cut after its first depth+1 elements. +func spellingAt(rel string, depth int) string { + parts := strings.SplitN(rel, "/", depth+2) + return strings.Join(parts[:depth+1], "/") +} + +// collides reports whether the claims on one folded name can clash: two +// files under different spellings, or a file where a directory is. +func collides(members []foldMember) bool { + files := map[string]bool{} + dirs := false + for _, m := range members { + if m.dir { + dirs = true + } else { + files[m.spelling] = true + } + } + return len(files) > 1 || (len(files) == 1 && dirs) +} + +// foldEntities groups one folded name's claims into what the destination +// can hold there: a file per spelling, and one directory for every +// directory spelling, which the destination merges. +func foldEntities(members []foldMember, isPresent func(string) (bool, error)) ([]foldEntity, error) { + byName := map[string]*foldEntity{} + var dir *foldEntity + for _, m := range members { + e := byName[m.spelling] + if m.dir { + if dir == nil { + dir = &foldEntity{name: m.spelling} + } + dir.name = min(dir.name, m.spelling) + e = dir + } else if e == nil { + e = &foldEntity{name: m.spelling} + byName[m.spelling] = e + } + e.members = append(e.members, m) + } + var out []foldEntity + if dir != nil { + out = append(out, *dir) + } + for _, e := range byName { + out = append(out, *e) + } + for i := range out { + if err := out[i].weigh(isPresent); err != nil { + return nil, err + } + } + return out, nil +} + +func (e *foldEntity) weigh(isPresent func(string) (bool, error)) error { + for _, m := range e.members { + if e.onDest { + return nil + } + p := m.planned + if !p { + var err error + if p, err = isPresent(m.path); err != nil { + return err + } + } + e.present = e.present || p + e.onDest = e.onDest || (p && m.live) + } + return nil +} + +// refuse picks the winner among the present entities at one folded name, +// the one the destination holds first, then the first by spelling, and +// refuses every planned path that claims another. +func (p foldPlan) refuse(entities []foldEntity) { + var present []foldEntity + for _, e := range entities { + if e.present { + present = append(present, e) + } + } + if len(present) < 2 { + return + } + sort.Slice(present, func(i, j int) bool { + if present[i].onDest != present[j].onDest { + return present[i].onDest + } + return present[i].name < present[j].name + }) + for _, e := range present[1:] { + for _, m := range e.members { + if m.planned { + if _, done := p.refused[m.path]; !done { + p.refused[m.path] = present[0].name + } + } + } + } +} + +// displaceOthers plans, for every planned path that still lands at or +// under one folded name, the move of each version recorded as a file there +// under another spelling whose path is no longer present. +func (p foldPlan) displaceOthers(members []foldMember, isPresent func(string) (bool, error)) { + for _, stale := range members { + if stale.dir || stale.planned || !stale.live { + continue + } + if present, err := isPresent(stale.path); err != nil || present { + continue + } + for _, m := range members { + if _, refused := p.refused[m.path]; m.planned && !refused && m.path != stale.path { + p.displace[m.path] = append(p.displace[m.path], stale.path) + } + } + } +} + +// presentAtSource reports whether a path is present in the volume's +// index, remembering each answer. +func (w *mirrorWriter) presentAtSource(ctx context.Context) func(string) (bool, error) { + seen := map[string]bool{} + return func(rel string) (bool, error) { + if p, ok := seen[rel]; ok { + return p, nil + } + r, err := w.h.store.GetByPath(ctx, w.volumeID, rel) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return false, fmt.Errorf("look up %s: %w", rel, err) + } + seen[rel] = err == nil && r.Status == store.StatusPresent + return seen[rel], nil + } +} + +// displaceSpelling moves aside the version recorded at rel, another +// spelling of a planned path's name, unless an earlier path of this push +// already did. +func (w *mirrorWriter) displaceSpelling(ctx context.Context, rel string) error { + if _, ok := w.live[rel]; !ok { + return nil + } + return w.displace(ctx, rel) +} + +func (w *mirrorWriter) refuseCollision(rel, other string) { + w.collided++ + w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: %s is not written: the destination cannot tell its name apart from %s (it ignores case or Unicode normalization); rename one of them at the source", + w.h.dest.Name, rel, other)) +} diff --git a/sync/mirror_fold_test.go b/sync/mirror_fold_test.go new file mode 100644 index 0000000..0b16c18 --- /dev/null +++ b/sync/mirror_fold_test.go @@ -0,0 +1,362 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/store" +) + +// foldingTransport stands in for a destination that folds names, as APFS +// and exFAT do: each name resolves, element by element, to the entry +// already on disk whose name folds to the same key. disk is where the +// destination root is on this machine. +type foldingTransport struct { + transport + disk string + fold nameFolding +} + +func (f foldingTransport) resolve(name string) string { + parts := strings.Split(name, "/") + dir := f.disk + for i, p := range parts { + entries, err := os.ReadDir(dir) + if err != nil { + break + } + for _, e := range entries { + if f.fold.key(e.Name()) == f.fold.key(p) { + parts[i] = e.Name() + break + } + } + dir = filepath.Join(dir, parts[i]) + } + return strings.Join(parts, "/") +} + +func (f foldingTransport) Stat(ctx context.Context, name string) (entry, error) { + return f.transport.Stat(ctx, f.resolve(name)) +} + +func (f foldingTransport) List(ctx context.Context, dir string) ([]entry, error) { + return f.transport.List(ctx, f.resolve(dir)) +} + +func (f foldingTransport) Get(ctx context.Context, name string) (io.ReadCloser, error) { + return f.transport.Get(ctx, f.resolve(name)) +} + +func (f foldingTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + return f.transport.Put(ctx, f.resolve(name), r, mtime) +} + +func (f foldingTransport) Rename(ctx context.Context, from, to string) error { + return f.transport.Rename(ctx, f.resolve(from), f.resolve(to)) +} + +func (f foldingTransport) Remove(ctx context.Context, name string) error { + return f.transport.Remove(ctx, f.resolve(name)) +} + +func (f foldingTransport) ServerHash(ctx context.Context, name string) (remoteChecksum, error) { + return f.transport.ServerHash(ctx, f.resolve(name)) +} + +var ( + caseAndNormFolding = nameFolding{caseless: true, normless: true} + composed = "caf\u00e9.txt" + decomposed = "cafe\u0301.txt" +) + +func TestNameFoldingKey(t *testing.T) { + cases := []struct { + fold nameFolding + a, b string + same bool + }{ + {nameFolding{}, "a.jpg", "A.jpg", false}, + {nameFolding{caseless: true}, "a.jpg", "A.jpg", true}, + {nameFolding{caseless: true}, "Straße/Ä", "STRASSE/ä", false}, + {nameFolding{caseless: true}, "ärger/Σ", "Ärger/ς", true}, + {nameFolding{caseless: true}, composed, decomposed, false}, + {nameFolding{normless: true}, composed, decomposed, true}, + {nameFolding{normless: true}, "a.jpg", "A.jpg", false}, + {caseAndNormFolding, "Caf\u00e9/X", "cafe\u0301/x", true}, + } + for _, c := range cases { + if got := c.fold.key(c.a) == c.fold.key(c.b); got != c.same { + t.Errorf("%+v: %q and %q fold together = %v, want %v", c.fold, c.a, c.b, got, c.same) + } + } +} + +// TestMirrorProbesHowTheDestinationComparesNames: a push learns from one +// file in staging whether the destination folds case, normalization, +// both or neither, and leaves no probe behind. +func TestMirrorProbesHowTheDestinationComparesNames(t *testing.T) { + for _, b := range mirrorBackends { + for _, fold := range []nameFolding{{}, {caseless: true}, {normless: true}, caseAndNormFolding} { + t.Run(fmt.Sprintf("%s/%+v", b.name, fold), func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.fold = fold + f.write(t, "a.txt", "alpha") + f.index(t) + var got nameFolding + _, err := f.pushVia(t, Options{}, func(tr transport) transport { + return probeRecorder{transport: tr, got: &got} + }) + if err != nil { + t.Fatal(err) + } + disk := diskFolding(t, f.dst) + want := nameFolding{caseless: fold.caseless || disk.caseless, normless: fold.normless || disk.normless} + if got != want { + t.Fatalf("probe = %+v, want %+v", got, want) + } + if _, err := os.Stat(f.dest(StagingDirName + "/" + foldProbeBase)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the probe stayed in staging: %v", err) + } + }) + } + } +} + +// probeRecorder records what the name probe's two lookups found. +type probeRecorder struct { + transport + got *nameFolding +} + +func (p probeRecorder) Stat(ctx context.Context, name string) (entry, error) { + e, err := p.transport.Stat(ctx, name) + switch { + case strings.HasSuffix(name, "/"+foldProbeCase): + p.got.caseless = err == nil + case strings.HasSuffix(name, "/"+foldProbeNorm): + p.got.normless = err == nil + } + return e, err +} + +// setupFoldingMirror is a mirror fixture on b whose destination folds case +// and normalization. +func setupFoldingMirror(t *testing.T, b mirrorBackend) *mirrorFixture { + t.Helper() + f := setupMirrorFixtureOn(t, b) + f.fold = caseAndNormFolding + return f +} + +// observe records body as present at rel in a run of its own, as an index +// run over a source that holds rel would; it writes no source file, so a +// push that tried to send rel would fail to read it. +func (f *mirrorFixture) observe(t *testing.T, rel, body string) { + t.Helper() + ctx := context.Background() + volID := f.volumeID(t) + runID, err := f.store.BeginIndexRun(ctx, store.RunKindIndex, volID, false) + if err != nil { + t.Fatal(err) + } + sum := blake3.Sum256([]byte(body)) + now := time.Now().UnixNano() + row := store.FileRow{VolumeID: volID, Path: rel, Blake3: sum[:], SizeBytes: int64(len(body)), MtimeNs: now, + Status: store.StatusPresent, FirstSeenRunID: runID, LastSeenRunID: runID, IndexedAtNs: now} + if err := f.store.Upsert(ctx, row, nil); err != nil { + t.Fatalf("Upsert %s: %v", rel, err) + } + if err := f.store.FinishRun(ctx, runID, store.RunStatusSuccess, "", 1); err != nil { + t.Fatal(err) + } +} + +// TestMirrorRefusesNamesTheDestinationCannotTellApart: on a destination +// that folds case and normalization, a present path whose name — or a +// parent's — folds onto another present path's is refused, and only that +// path: nothing is displaced, the path already there keeps its bytes and +// its record, every other path lands, and the run fails before its +// receipt, so the watermark holds until one of them is renamed. +func TestMirrorRefusesNamesTheDestinationCannotTellApart(t *testing.T) { + cases := []struct { + name string + first, colliding string + }{ + {"case", "a.jpg", "A.jpg"}, + {"normalization", composed, decomposed}, + {"a file where a directory is", "d/x.txt", "D"}, + {"a directory where a file is", "f", "F/y.txt"}, + } + for _, b := range mirrorBackends { + for _, c := range cases { + t.Run(b.name+"/"+c.name, func(t *testing.T) { + f := setupFoldingMirror(t, b) + f.write(t, c.first, "first") + f.index(t) + f.mustPush(t) + f.write(t, "other.txt", "other") + f.index(t) + f.observe(t, c.colliding, "colliding") + before := f.contentHashes(t) + + rep, err := f.push(t, Options{}) + if err == nil || rep.Status != store.RunStatusFailed || !strings.Contains(err.Error(), "cannot tell their names apart") { + t.Fatalf("push: status=%q err=%v, want a failed run naming the collision", rep.Status, err) + } + if !warned(rep, c.colliding+" is not written") { + t.Fatalf("warnings = %v, want %s refused", rep.Warnings, c.colliding) + } + if f.readDest(t, c.first) != "first" || f.readDest(t, "other.txt") != "other" { + t.Fatal("the path already there changed, or the other path did not land") + } + if got := f.rowsAt(t, c.first); !slicesEqual(got, []string{store.RemotePathLive}) { + t.Fatalf("%s rows = %v, want its one live row untouched", c.first, got) + } + if got := f.rowsAt(t, c.colliding); len(got) != 0 { + t.Fatalf("%s rows = %v, want none", c.colliding, got) + } + if _, err := os.Stat(f.dest(HistoryDirName)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("a refused path displaced something: %v", err) + } + if after := f.contentHashes(t); len(after) != len(before)+1 { + t.Fatalf("destination holds %d files, want the %d before plus other.txt", len(after), len(before)) + } + if _, err := os.Stat(f.dest(".squirrel-index/run-" + strconv.FormatInt(rep.RunID, 10))); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the failed run left a receipt: %v", err) + } + }) + } + } +} + +// TestMirrorRefusesTheSecondOfTwoNewNames: two new present paths that fold +// together land as one: the first by spelling, the second refused. +func TestMirrorRefusesTheSecondOfTwoNewNames(t *testing.T) { + f := setupFoldingMirror(t, localBackend) + f.write(t, "keep.txt", "keep") + f.index(t) + f.observe(t, "X.jpg", "upper") + f.observe(t, "x.jpg", "lower") + f.write(t, "X.jpg", "upper") + rep, err := f.push(t, Options{}) + if err == nil || !warned(rep, "x.jpg is not written") { + t.Fatalf("push: err=%v warnings=%v, want x.jpg refused", err, rep.Warnings) + } + if f.readDest(t, "X.jpg") != "upper" { + t.Fatal("the first spelling did not land") + } +} + +// TestMirrorFollowsARenameThatChangesOnlyCase: a file or a directory +// renamed at the source in case alone moves the recorded versions under the +// old spelling into history as their records, then lands under the new +// one, on a destination that cannot hold both. Every record keeps +// vouching for the bytes it names, on the folding the fixture emulates and +// on this machine's own disk when that folds. +func TestMirrorFollowsARenameThatChangesOnlyCase(t *testing.T) { + for _, b := range mirrorBackends { + for _, emulate := range []bool{true, false} { + t.Run(b.name+"/emulated="+strconv.FormatBool(emulate), func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + if emulate { + f.fold = caseAndNormFolding + } else if !diskFolding(t, f.dst).caseless { + t.Skip("this machine's disk tells names apart by case") + } + f.write(t, "a.jpg", "file") + f.write(t, "Photos/x.jpg", "in a directory") + f.index(t) + f.mustPush(t) + f.rename(t, "a.jpg", "A.jpg") + f.rename(t, "Photos", "photos") + f.index(t) + before := f.contentHashes(t) + + rep := f.mustPush(t) + run := strconv.FormatInt(rep.RunID, 10) + if f.readDest(t, "A.jpg") != "file" || f.readDest(t, "photos/x.jpg") != "in a directory" { + t.Fatal("the renamed paths did not land") + } + for _, rel := range []string{"a.jpg", "Photos/x.jpg"} { + if got := f.rowsAt(t, rel); !slicesEqual(got, []string{store.RemotePathDisplaced}) { + t.Fatalf("%s rows = %v, want displaced", rel, got) + } + } + if f.readDest(t, HistoryDirName+"/run-"+run+"/a.jpg") != "file" { + t.Fatal("the old spelling's version is not in history") + } + f.checkInvariants(t, before) + }) + } + } +} + +func (f *mirrorFixture) rename(t *testing.T, from, to string) { + t.Helper() + if err := os.Rename(filepath.Join(f.src, from), filepath.Join(f.src, to)); err != nil { + t.Fatal(err) + } +} + +// diskFolding is how the disk under dir compares names. +func diskFolding(t *testing.T, dir string) nameFolding { + t.Helper() + found := func(name, lookup string) bool { + p := filepath.Join(dir, name) + if err := os.WriteFile(p, nil, 0o644); err != nil { + t.Fatal(err) + } + defer func() { _ = os.Remove(p) }() + _, err := os.Stat(filepath.Join(dir, lookup)) + return err == nil + } + return nameFolding{caseless: found("case-probe", "CASE-PROBE"), normless: found(composed, decomposed)} +} + +// TestMirrorFoldingMovesAFileOutOfADirectorysWay: a recorded file whose +// path is gone at the source moves aside as its record when a new path's +// directory folds onto its name, and a recorded directory moves with every +// version in it when a new file's name folds onto it. +func TestMirrorFoldingMovesAFileOutOfADirectorysWay(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupFoldingMirror(t, b) + f.write(t, "a", "file a") + f.write(t, "D/x", "inside D") + f.index(t) + f.mustPush(t) + for _, rel := range []string{"a", "D"} { + if err := os.RemoveAll(filepath.Join(f.src, rel)); err != nil { + t.Fatal(err) + } + } + f.write(t, "A/b", "under A") + f.write(t, "d", "file d") + f.index(t) + before := f.contentHashes(t) + + f.mustPush(t) + if f.readDest(t, "A/b") != "under A" || f.readDest(t, "d") != "file d" { + t.Fatal("the new paths did not land") + } + for _, rel := range []string{"a", "D/x"} { + if got := f.rowsAt(t, rel); !slicesEqual(got, []string{store.RemotePathDisplaced}) { + t.Fatalf("%s rows = %v, want displaced as its record", rel, got) + } + } + f.checkInvariants(t, before) + }) + } +} diff --git a/sync/mirror_test.go b/sync/mirror_test.go index 57d6e35..3da7b8a 100644 --- a/sync/mirror_test.go +++ b/sync/mirror_test.go @@ -10,6 +10,7 @@ import ( "io/fs" "net" "os" + "path" "path/filepath" "strconv" "strings" @@ -33,6 +34,9 @@ type mirrorFixture struct { pair Pair src string // the volume's source directory dst string // the destination root + // fold, when it folds, makes the destination resolve names as a disk + // that folds them does, whatever this machine's disk does. + fold nameFolding } // mirrorBackend is where a mirror fixture's destination lives: its name, @@ -123,7 +127,28 @@ func (f *mirrorFixture) index(t *testing.T) { // push runs one push with no rclone wrapper at all. func (f *mirrorFixture) push(t *testing.T, opts Options) (Report, error) { t.Helper() - return RunPair(context.Background(), f.store, Tools{}, f.pair, opts) + if !f.fold.folds() { + return RunPair(context.Background(), f.store, Tools{}, f.pair, opts) + } + return f.pushVia(t, opts, func(tr transport) transport { return tr }) +} + +// pushVia runs one push through wrap's transport, on top of the folding +// the fixture sets. +func (f *mirrorFixture) pushVia(t *testing.T, opts Options, wrap func(transport) transport) (Report, error) { + t.Helper() + h := f.handler(t) + h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + if err != nil { + return nil, err + } + if f.fold.folds() { + raw = foldingTransport{transport: raw, disk: f.dst, fold: f.fold} + } + return wrap(raw), nil + } + return h.Push(context.Background(), opts) } func (f *mirrorFixture) mustPush(t *testing.T) Report { @@ -139,15 +164,9 @@ func (f *mirrorFixture) mustPush(t *testing.T) Report { // crashAt selects. func (f *mirrorFixture) pushCrashing(t *testing.T, crashAt func(transportCall) bool, mode crashMode) (Report, error) { t.Helper() - h := f.handler(t) - h.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { - raw, err := openDestinationTransport(ctx, d) - if err != nil { - return nil, err - } - return &faultTransport{transport: raw, crashAt: crashAt, mode: mode}, nil - } - return h.Push(context.Background(), Options{}) + return f.pushVia(t, Options{}, func(tr transport) transport { + return &faultTransport{transport: tr, crashAt: crashAt, mode: mode} + }) } func (f *mirrorFixture) handler(t *testing.T) *mirrorHandler { @@ -168,9 +187,18 @@ func (f *mirrorFixture) volumeID(t *testing.T) int64 { return v.ID } -// dest is the path of rel under the destination's volume directory. +// dest is the path of rel under the destination's volume directory, as +// the destination resolves it. func (f *mirrorFixture) dest(rel string) string { - return filepath.Join(f.dst, "pics", filepath.FromSlash(rel)) + return f.onDisk(path.Join("pics", rel)) +} + +// onDisk is where the destination keeps name, relative to its root. +func (f *mirrorFixture) onDisk(name string) string { + if f.fold.folds() { + name = foldingTransport{disk: f.dst, fold: f.fold}.resolve(name) + } + return filepath.Join(f.dst, filepath.FromSlash(name)) } func (f *mirrorFixture) readDest(t *testing.T, rel string) string { @@ -243,16 +271,23 @@ func (f *mirrorFixture) checkInvariants(t *testing.T, before map[string]bool) { ctx := context.Background() volID := f.volumeID(t) liveContent := map[string]int64{} + disk := diskFolding(t, f.dst) + fold := nameFolding{caseless: f.fold.caseless || disk.caseless, normless: f.fold.normless || disk.normless} + liveAt := map[string]string{} for _, r := range f.rows(t) { want := f.contentHashOf(t, volID, r) switch r.State { case store.RemotePathLive: liveContent[r.Path] = r.ContentID + if other, ok := liveAt[fold.key(r.Path)]; ok { + t.Errorf("live %s and %s name the one entry the destination holds there", r.Path, other) + } + liveAt[fold.key(r.Path)] = r.Path if got := fileHash(t, f.dest(r.Path)); got != want { t.Errorf("live %s holds %s, want %s", r.Path, got, want) } case store.RemotePathDisplaced: - p := filepath.Join(f.dst, filepath.FromSlash(historyName("pics", r.DisplacedRunID.Int64, r.Path))) + p := f.onDisk(historyName("pics", r.DisplacedRunID.Int64, r.Path)) if got := fileHash(t, p); got != want { t.Errorf("displaced %s holds %s at %s, want %s", r.Path, got, p, want) } @@ -546,7 +581,7 @@ type mirrorCrashCase struct { // transports. Each row pins what the crash leaves recorded and how // reconcile settles it; afterwards the three invariants hold. func TestMirrorCrashTable(t *testing.T) { - staged := func(c transportCall) bool { return strings.Contains(c.name, StagingDirName+"/") } + staged := func(c transportCall) bool { return strings.Contains(c.name, StagingDirName+"/run-") } intoHistory := func(c transportCall) bool { return c.op == "rename" && strings.Contains(c.to, HistoryDirName+"/") } commitRename := func(c transportCall) bool { return c.op == "rename" && staged(c) } cases := []mirrorCrashCase{ diff --git a/sync/mirror_translate.go b/sync/mirror_translate.go index b4e3031..4255780 100644 --- a/sync/mirror_translate.go +++ b/sync/mirror_translate.go @@ -11,8 +11,9 @@ import ( // delta path and per repair, and the live records the operations were // decided against. execute keeps live current as it moves versions. type mirrorOps struct { - paths []mirrorPath - live map[string]store.RemotePath // volume-relative path → live row + volumeID int64 + paths []mirrorPath + live map[string]store.RemotePath // volume-relative path → live row // inSync counts the live rows that hold their path's present content, // in the delta or not: what the report calls already correct. inSync int64 @@ -50,7 +51,7 @@ func (h *mirrorHandler) translate(ctx context.Context, p pushPlan) (*mirrorOps, if err != nil { return nil, err } - ops := &mirrorOps{live: make(map[string]store.RemotePath, len(rows)), inSync: inSync} + ops := &mirrorOps{volumeID: p.volumeID, live: make(map[string]store.RemotePath, len(rows)), inSync: inSync} for _, r := range rows { ops.live[r.Path] = r } diff --git a/sync/mirror_write.go b/sync/mirror_write.go index 1805002..46aa48c 100644 --- a/sync/mirror_write.go +++ b/sync/mirror_write.go @@ -23,16 +23,22 @@ import ( // mirrorWriter carries one run's execution: the guarded transport, the // live records it keeps current, and the tally for the report. type mirrorWriter struct { - h *mirrorHandler - rep *Report - runID int64 - tr transport - live map[string]store.RemotePath + h *mirrorHandler + rep *Report + runID int64 + volumeID int64 + tr transport + live map[string]store.RemotePath + // fold is how the destination compares names, and names the plan + // around the collisions that causes. + fold nameFolding + names foldPlan progress func(runevents.Progress) total int done int drifted int + collided int } // execute confirms or writes every planned path. A failure on one path @@ -44,21 +50,21 @@ func (h *mirrorHandler) execute(ctx context.Context, rep *Report, runID int64, o if err != nil { return err } - w := &mirrorWriter{h: h, rep: rep, runID: runID, tr: tr, live: ops.live, progress: h.progress, total: len(ops.paths)} + w := &mirrorWriter{h: h, rep: rep, runID: runID, volumeID: ops.volumeID, tr: tr, live: ops.live, progress: h.progress, total: len(ops.paths)} rep.AlreadyCorrect = ops.inSync if ops.repairs > 0 { rep.Changed = knownChanged(rep.Changed.Int64 + ops.repairs) rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination %q lost %d path(s) the index still holds there (found gone or changed); they are written again", h.dest.Name, ops.repairs)) } + if err := w.learnNames(ctx, ops); err != nil { + return err + } for _, p := range ops.paths { if err := ctx.Err(); err != nil { return err } - if err := w.apply(ctx, p); err != nil { - w.fail(p.delta.Path, err) - if errors.Is(err, errTransportStalled) { - break - } + if stalled := w.land(ctx, p); stalled { + break } w.done++ w.emitProgress() @@ -66,6 +72,35 @@ func (h *mirrorHandler) execute(ctx context.Context, rep *Report, runID int64, o return w.result() } +// learnNames probes how the destination compares names before the first +// path lands, and on a destination that folds them plans around the +// collisions that causes. +func (w *mirrorWriter) learnNames(ctx context.Context, ops *mirrorOps) error { + if len(ops.paths) == 0 { + return nil + } + var err error + if w.fold, err = w.probeFolding(ctx); err != nil || !w.fold.folds() { + return err + } + w.names, err = w.planFolding(ctx, ops) + return err +} + +// land confirms or writes one planned path, or refuses it when its name +// collides with another's; it reports whether the transport stalled. +func (w *mirrorWriter) land(ctx context.Context, p mirrorPath) bool { + if other, ok := w.names.refused[p.delta.Path]; ok { + w.refuseCollision(p.delta.Path, other) + return false + } + if err := w.apply(ctx, p); err != nil { + w.fail(p.delta.Path, err) + return errors.Is(err, errTransportStalled) + } + return false +} + func (w *mirrorWriter) apply(ctx context.Context, p mirrorPath) error { if p.current { ok, err := w.confirm(ctx, p.delta) @@ -107,12 +142,18 @@ type stagedVersion struct { } // write lands one path: stage the content while hashing it, clear the way -// (displacing whatever the path and its parents hold), then commit. +// (displacing whatever the path and its parents hold, under any spelling +// the destination resolves to them), then commit. func (w *mirrorWriter) write(ctx context.Context, d store.PathDelta) error { staged, err := w.stage(ctx, d) if err != nil { return err } + for _, other := range w.names.displace[d.Path] { + if err := w.displaceSpelling(ctx, other); err != nil { + return err + } + } if err := w.clearParents(ctx, d.Path); err != nil { return err } @@ -226,7 +267,7 @@ func (w *mirrorWriter) displace(ctx context.Context, rel string) error { func (w *mirrorWriter) displaceDir(ctx context.Context, dir string) error { var ids []int64 for rel, live := range w.live { - if !strings.HasPrefix(rel, dir+"/") { + if !w.fold.under(rel, dir) { continue } e, err := w.tr.Stat(ctx, w.h.liveName(rel)) @@ -266,7 +307,7 @@ func (w *mirrorWriter) moveRecorded(ctx context.Context, rel string, ids []int64 return err } for r := range w.live { - if r == rel || strings.HasPrefix(r, rel+"/") { + if r == rel || w.fold.under(r, rel) { delete(w.live, r) } } @@ -366,6 +407,9 @@ func (w *mirrorWriter) result() error { if w.drifted > 0 { return fmt.Errorf("%d path(s) on %q were refused for drifting from their indexed hash; re-index the volume and sync again — the receipt for run %d was not written and the durability vector did not advance", w.drifted, w.h.dest.Name, w.runID) } + if w.collided > 0 { + return fmt.Errorf("%d path(s) on %q were refused because the destination cannot tell their names apart from another path's; rename one of each pair at the source, index, and sync again — the receipt for run %d was not written and the durability vector did not advance", w.collided, w.h.dest.Name, w.runID) + } return nil } diff --git a/sync/transport_guard.go b/sync/transport_guard.go index f79490f..39f53ff 100644 --- a/sync/transport_guard.go +++ b/sync/transport_guard.go @@ -50,6 +50,8 @@ const ( // - Remove of a staging entry, or an emptied staging run directory, // of a run that has finished: /.squirrel-staging/run-[/]; // - Remove of a ride-along snapshot: /.squirrel-index/index-*.db; +// - for a mirror, Remove of the name probe, +// /.squirrel-staging/fold-probe-é; // - Rename from this run's staging onto a snapshot name (the ride-along), // or onto what the layout commits: a live name for a mirror, an // artifact name for a content layout (see artifact); @@ -114,7 +116,7 @@ func (g nameGuard) snapshot(name string) bool { } func (g nameGuard) removable(name string) bool { - if g.snapshot(name) { + if g.snapshot(name) || (!g.content && name == foldProbeName(g.volumeDir)) { return true } runID, key, ok := g.stagingParts(name) diff --git a/sync/transport_guard_test.go b/sync/transport_guard_test.go index ade242c..a650f7c 100644 --- a/sync/transport_guard_test.go +++ b/sync/transport_guard_test.go @@ -48,6 +48,10 @@ func TestNameGuardPermits(t *testing.T) { {"move a live file onto a snapshot name", opRename, "pics/a.db", "pics/.squirrel-index/index-20260101T000000.000Z-run-7.db", false}, {"marker bootstrap without --init", opRename, "pics/.squirrel-staging/volume-marker", "pics/.squirrel-volume", false}, {"remove the staged marker without --init", opRemove, "pics/.squirrel-staging/volume-marker", "", false}, + {"remove the name probe", opRemove, foldProbeName("pics"), "", true}, + {"remove the name probe decomposed", opRemove, "pics/.squirrel-staging/" + foldProbeNorm, "", false}, + {"remove another volume's name probe", opRemove, foldProbeName("docs"), "", false}, + {"commit the name probe", opRename, foldProbeName("pics"), "pics/a.txt", false}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -93,6 +97,7 @@ func TestNameGuardContentLayout(t *testing.T) { {"move an object", opRename, "objects/" + key, "packs/" + key, false}, {"remove an object", opRemove, "objects/" + key, "", false}, {"remove a finished run's staging", opRemove, "pics/.squirrel-staging/run-6/" + key, "", true}, + {"remove a mirror's name probe", opRemove, foldProbeName("pics"), "", false}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { From d42dfaff7063f838848db7c279e494295b55e523 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 04:48:07 +0200 Subject: [PATCH 43/61] sync: crash a native push at every transport call, on both transports A mirror push that exercises every kind of step, and a content-addressed and a packed push, each die at every call they make, in every way that call can die. Right after the crash every record still vouches for its bytes and no byte left the destination; after the next clean push the three invariants hold, staging is empty, and the content layouts verify clean and restore the volume. The mirror runs it on a destination that tells names apart and on one that folds them. The invariant check splits into its three parts so the first can run after a crash, and the content fixture's crashing push takes a mode. --- sync/content_native_test.go | 10 +- sync/crash_every_call_test.go | 241 ++++++++++++++++++++++++++++++++++ sync/mirror_test.go | 93 ++++++++++--- 3 files changed, 318 insertions(+), 26 deletions(-) create mode 100644 sync/crash_every_call_test.go diff --git a/sync/content_native_test.go b/sync/content_native_test.go index f58b465..b9500bc 100644 --- a/sync/content_native_test.go +++ b/sync/content_native_test.go @@ -121,9 +121,9 @@ func (f *nativeContentFixture) mustPush(t *testing.T) Report { return rep } -// pushCrashing runs one push whose transport crashes at the first call -// crashAt selects. -func (f *nativeContentFixture) pushCrashing(t *testing.T, crashAt func(transportCall) bool) (Report, error) { +// pushCrashing runs one push whose transport crashes, as mode says, at the +// first call crashAt selects. +func (f *nativeContentFixture) pushCrashing(t *testing.T, crashAt func(transportCall) bool, mode crashMode) (Report, error) { t.Helper() h, err := HandlerFor(f.store, Tools{}, f.pair) if err != nil { @@ -142,7 +142,7 @@ func (f *nativeContentFixture) pushCrashing(t *testing.T, crashAt func(transport if err != nil { return nil, err } - return &faultTransport{transport: raw, crashAt: crashAt, mode: crashAfter}, nil + return &faultTransport{transport: raw, crashAt: crashAt, mode: mode}, nil } return h.Push(context.Background(), Options{}) } @@ -262,7 +262,7 @@ func TestNativeContentAdoptsAnArtifactItAlreadyLanded(t *testing.T) { f.index(t) if _, err := f.pushCrashing(t, func(c transportCall) bool { return c.op == "rename" && strings.HasPrefix(c.to, ObjectsDirName+"/") - }); err == nil { + }, crashAfter); err == nil { t.Fatal("the crashing push succeeded") } if _, err := os.Stat(f.objectPath("alpha")); err != nil { diff --git a/sync/crash_every_call_test.go b/sync/crash_every_call_test.go new file mode 100644 index 0000000..77074fd --- /dev/null +++ b/sync/crash_every_call_test.go @@ -0,0 +1,241 @@ +package sync + +import ( + "context" + "fmt" + "os" + "path" + "path/filepath" + "testing" + + "github.com/mbertschler/squirrel/store" +) + +// crashModesFor is every way a call can die that leaves a different +// destination behind: a read fails the same way before or after it runs, +// a write can also land, and a Put can land part of its body. +func crashModesFor(c transportCall) []crashMode { + switch c.op { + case "stat", "list": + return []crashMode{crashBefore} + case "put": + return []crashMode{crashBefore, crashMidway, crashAfter} + default: + return []crashMode{crashBefore, crashAfter} + } +} + +var crashModeNames = map[crashMode]string{crashBefore: "before", crashAfter: "after", crashMidway: "midway"} + +// crashAtCall selects the i-th call a push makes. +func crashAtCall(i int) func(transportCall) bool { + n := -1 + return func(transportCall) bool { + n++ + return n == i + } +} + +// mirrorCrashScenario lands a first tree with one clean push, then changes +// the source and the destination so the next push takes every kind of +// step: a confirm, a write displacing its recorded version, a write +// displacing bytes squirrel never wrote, a record changed behind +// squirrel's back, a file becoming a directory and a directory becoming a +// file, a rename that changes only case, and a path deleted at the source. +func mirrorCrashScenario(t *testing.T, f *mirrorFixture) { + t.Helper() + for rel, body := range map[string]string{ + "keep.txt": "keep", "change.txt": "v1", "tampered.txt": "t1", + "swap": "file swap", "dir/x": "in dir", "gone.txt": "gone", "Case.txt": "case", + } { + f.write(t, rel, body) + } + f.index(t) + f.mustPush(t) + for _, rel := range []string{"swap", "dir", "gone.txt"} { + if err := os.RemoveAll(filepath.Join(f.src, rel)); err != nil { + t.Fatal(err) + } + } + f.write(t, "change.txt", "v2 is longer") + f.write(t, "tampered.txt", "t2 at the source") + f.write(t, "swap/inner", "swap is a directory now") + f.write(t, "dir", "dir is a file now") + f.write(t, "new.txt", "new") + f.rename(t, "Case.txt", "case.txt") + f.index(t) + for rel, body := range map[string]string{"tampered.txt": "tampered on the destination", "new.txt": "foreign"} { + if err := os.WriteFile(f.dest(rel), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } +} + +// recordMirrorCalls runs the scenario's push once without a crash and returns +// every transport call it made. +func recordMirrorCalls(t *testing.T, b mirrorBackend, fold nameFolding) []transportCall { + t.Helper() + f := setupMirrorFixtureOn(t, b) + f.fold = fold + mirrorCrashScenario(t, f) + var rec *faultTransport + rep, err := f.pushVia(t, Options{}, func(tr transport) transport { + rec = &faultTransport{transport: tr} + return rec + }) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("recording push: status=%q err=%v warnings=%v", rep.Status, err, rep.Warnings) + } + return rec.calls +} + +// TestMirrorCrashAtEveryTransportCall: a push that dies at any one of its +// transport calls, in any way that call can die, leaves every record +// vouching for its bytes and every byte where it was; the next clean push +// then settles what the crash left and satisfies all three invariants. +// Both transports run it, on a destination that tells names apart and on +// one that folds them. +func TestMirrorCrashAtEveryTransportCall(t *testing.T) { + for _, b := range mirrorBackends { + for _, fold := range []nameFolding{{}, caseAndNormFolding} { + t.Run(fmt.Sprintf("%s/folds=%v", b.name, fold.folds()), func(t *testing.T) { + calls := recordMirrorCalls(t, b, fold) + for i, c := range calls { + for _, mode := range crashModesFor(c) { + t.Run(fmt.Sprintf("%03d-%s-%s-%s", i, c.op, path.Base(c.name), crashModeNames[mode]), func(t *testing.T) { + t.Parallel() + runMirrorCrashAt(t, b, fold, i, mode) + }) + } + } + }) + } + } +} + +func runMirrorCrashAt(t *testing.T, b mirrorBackend, fold nameFolding, i int, mode crashMode) { + f := setupMirrorFixtureOn(t, b) + f.fold = fold + mirrorCrashScenario(t, f) + before := f.contentHashes(t) + if rep, err := f.pushCrashing(t, crashAtCall(i), mode); !crashedOn(rep, err) { + t.Fatalf("crashing push: status=%q err=%v failures=%+v, want the injected crash", rep.Status, err, rep.RcloneResult.FailedFiles) + } + f.checkRecordsVouch(t, "tampered.txt") + f.checkOnlyGrew(t, before) + + clean := f.mustPush(t) + f.checkInvariants(t, before) + f.checkStagingEmpty(t, clean.RunID) + for rel, want := range map[string]string{ + "keep.txt": "keep", "change.txt": "v2 is longer", "tampered.txt": "t2 at the source", + "swap/inner": "swap is a directory now", "dir": "dir is a file now", "new.txt": "new", + "case.txt": "case", "gone.txt": "gone", + } { + if got := f.readDest(t, rel); got != want { + t.Errorf("%s = %q, want %q", rel, got, want) + } + } +} + +// contentCrashScenario lands a first tree on a content destination with +// one clean push, then adds, changes and deletes files so the next push +// uploads objects and, on a packed destination, a pack and its map. +func contentCrashScenario(t *testing.T, f *nativeContentFixture) { + t.Helper() + f.write(t, "a.txt", "alpha") + f.write(t, "big.txt", "a larger file") + f.write(t, "gone.txt", "gone, soon") + f.index(t) + f.mustPush(t) + if err := os.Remove(filepath.Join(f.src, "gone.txt")); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "ALPHA") + f.write(t, "b.txt", "beta") + f.write(t, "2024/big.txt", "another larger file") + f.index(t) +} + +func recordContentCalls(t *testing.T, b contentBackend, layout string) []transportCall { + t.Helper() + f := setupNativeContentFixture(t, b, layout) + contentCrashScenario(t, f) + var calls []transportCall + rep, err := f.pushCrashing(t, func(c transportCall) bool { + calls = append(calls, c) + return false + }, crashBefore) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("recording push: status=%q err=%v", rep.Status, err) + } + return calls +} + +// TestNativeContentCrashAtEveryTransportCall: a content-addressed or +// packed push that dies at any one of its transport calls leaves every +// recorded artifact at its name with its bytes and every byte where it +// was. The next clean push lands the rest, a verify pass re-confirms every +// artifact, and a restore returns the volume. +func TestNativeContentCrashAtEveryTransportCall(t *testing.T) { + for _, b := range contentBackends { + for _, layout := range contentLayouts { + t.Run(b.name+"/"+layout, func(t *testing.T) { + for i, c := range recordContentCalls(t, b, layout) { + for _, mode := range crashModesFor(c) { + t.Run(fmt.Sprintf("%03d-%s-%s-%s", i, c.op, path.Base(c.name), crashModeNames[mode]), func(t *testing.T) { + t.Parallel() + runContentCrashAt(t, b, layout, i, mode) + }) + } + } + }) + } + } +} + +func runContentCrashAt(t *testing.T, b contentBackend, layout string, i int, mode crashMode) { + f := setupNativeContentFixture(t, b, layout) + contentCrashScenario(t, f) + before := hashesOutsideStaging(t, f.dst) + if rep, err := f.pushCrashing(t, crashAtCall(i), mode); !crashedOn(rep, err) { + t.Fatalf("crashing push: status=%q err=%v failures=%+v, want the injected crash", rep.Status, err, rep.RcloneResult.FailedFiles) + } + f.checkArtifactsVouch(t) + checkStillHeld(t, before, hashesOutsideStaging(t, f.dst)) + + f.mustPush(t) + f.checkArtifactsVouch(t) + checkStillHeld(t, before, hashesOutsideStaging(t, f.dst)) + to := t.TempDir() + rep, err := Restore(context.Background(), f.store, nil, f.pair.Volume, f.pair.Destination, RestoreOptions{ToPath: to}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("restore: status=%q err=%v", rep.Status, err) + } + for rel, want := range map[string]string{"a.txt": "ALPHA", "b.txt": "beta", "big.txt": "a larger file", "2024/big.txt": "another larger file"} { + if got, err := os.ReadFile(filepath.Join(to, filepath.FromSlash(rel))); err != nil || string(got) != want { + t.Errorf("restored %s = %q, %v; want %q", rel, got, err, want) + } + } +} + +// checkArtifactsVouch asserts that every artifact squirrel recorded on the +// destination is at its name with the bytes recorded: a verify pass +// re-confirms each one and finds nothing gone or changed. +func (f *nativeContentFixture) checkArtifactsVouch(t *testing.T) { + t.Helper() + rep, err := VerifyRemote(context.Background(), f.store, nil, f.pair.Destination) + if err != nil || !rep.Clean() || rep.Unchecked != 0 { + t.Fatalf("verify = %+v, %v; want every recorded artifact re-confirmed", rep, err) + } +} + +// checkStillHeld asserts that every content in before is still in after. +func checkStillHeld(t *testing.T, before, after map[string]bool) { + t.Helper() + for h := range before { + if !after[h] { + t.Errorf("content %s left the destination", h) + } + } +} diff --git a/sync/mirror_test.go b/sync/mirror_test.go index 3da7b8a..95ca994 100644 --- a/sync/mirror_test.go +++ b/sync/mirror_test.go @@ -12,6 +12,7 @@ import ( "os" "path" "path/filepath" + "slices" "strconv" "strings" "testing" @@ -234,9 +235,16 @@ func (f *mirrorFixture) rowsAt(t *testing.T, rel string) []string { // contentHashes collects the BLAKE3 of every file under the destination // root outside staging: what invariant 2 says only grows. func (f *mirrorFixture) contentHashes(t *testing.T) map[string]bool { + t.Helper() + return hashesOutsideStaging(t, f.dst) +} + +// hashesOutsideStaging collects the BLAKE3 of every file under root that +// is not in a .squirrel-staging directory. +func hashesOutsideStaging(t *testing.T, root string) map[string]bool { t.Helper() out := map[string]bool{} - err := filepath.WalkDir(f.dst, func(p string, d fs.DirEntry, err error) error { + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { if err != nil { return err } @@ -268,48 +276,91 @@ func fileHash(t *testing.T, p string) string { // push, given the content the destination held before it. func (f *mirrorFixture) checkInvariants(t *testing.T, before map[string]bool) { t.Helper() - ctx := context.Background() - volID := f.volumeID(t) liveContent := map[string]int64{} + for _, r := range f.checkRecordsVouch(t) { + switch r.State { + case store.RemotePathLive: + liveContent[r.Path] = r.ContentID + case store.RemotePathCommitting, store.RemotePathDisplacing: + t.Errorf("%s row %d is still %s after a clean push", r.Path, r.ID, r.State) + } + } + f.checkOnlyGrew(t, before) + present, err := f.store.ListPresentContent(context.Background(), f.volumeID(t)) + if err != nil { + t.Fatalf("ListPresentContent: %v", err) + } + for _, d := range present { + if liveContent[d.Path] != d.ContentID { + t.Errorf("present %s has no live row holding content %d", d.Path, d.ContentID) + } + } +} + +// checkRecordsVouch asserts invariant 1, which holds at every point of a +// push, a crashed one too: every live row's bytes are at its path, every +// displaced row's at its history path, and no two live rows name the one +// entry a folding destination holds. It returns the rows it checked. +// Rows at a path in changed, which the test itself changed behind +// squirrel's back, are left unchecked. +func (f *mirrorFixture) checkRecordsVouch(t *testing.T, changed ...string) []store.RemotePath { + t.Helper() + volID := f.volumeID(t) disk := diskFolding(t, f.dst) fold := nameFolding{caseless: f.fold.caseless || disk.caseless, normless: f.fold.normless || disk.normless} liveAt := map[string]string{} - for _, r := range f.rows(t) { - want := f.contentHashOf(t, volID, r) + rows := f.rows(t) + for _, r := range rows { + if slices.Contains(changed, r.Path) { + continue + } + var at string switch r.State { case store.RemotePathLive: - liveContent[r.Path] = r.ContentID if other, ok := liveAt[fold.key(r.Path)]; ok { t.Errorf("live %s and %s name the one entry the destination holds there", r.Path, other) } liveAt[fold.key(r.Path)] = r.Path - if got := fileHash(t, f.dest(r.Path)); got != want { - t.Errorf("live %s holds %s, want %s", r.Path, got, want) - } + at = f.dest(r.Path) case store.RemotePathDisplaced: - p := f.onDisk(historyName("pics", r.DisplacedRunID.Int64, r.Path)) - if got := fileHash(t, p); got != want { - t.Errorf("displaced %s holds %s at %s, want %s", r.Path, got, p, want) - } - case store.RemotePathCommitting, store.RemotePathDisplacing: - t.Errorf("%s row %d is still %s after a clean push", r.Path, r.ID, r.State) + at = f.onDisk(historyName("pics", r.DisplacedRunID.Int64, r.Path)) + default: + continue + } + if got, want := hashOnDisk(at), f.contentHashOf(t, volID, r); got != want { + t.Errorf("%s row for %s: %s holds %q, want %s", r.State, r.Path, at, got, want) } } + return rows +} + +// checkOnlyGrew asserts invariant 2: every content the destination held +// outside staging before is still there. +func (f *mirrorFixture) checkOnlyGrew(t *testing.T, before map[string]bool) { + t.Helper() after := f.contentHashes(t) for h := range before { if !after[h] { t.Errorf("content %s left the destination", h) } } - present, err := f.store.ListPresentContent(ctx, volID) +} + +// hashOnDisk is the hex BLAKE3 of the file at p, or why it has none. +func hashOnDisk(p string) string { + fi, err := os.Lstat(p) if err != nil { - t.Fatalf("ListPresentContent: %v", err) + return err.Error() } - for _, d := range present { - if liveContent[d.Path] != d.ContentID { - t.Errorf("present %s has no live row holding content %d", d.Path, d.ContentID) - } + if !fi.Mode().IsRegular() { + return "not a file: " + fi.Mode().String() + } + b, err := os.ReadFile(p) + if err != nil { + return err.Error() } + sum := blake3.Sum256(b) + return hex.EncodeToString(sum[:]) } func (f *mirrorFixture) contentHashOf(t *testing.T, volID int64, r store.RemotePath) string { From 58a64ed2ee79140e2af19680c297b32fcccd4bf8 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 04:51:48 +0200 Subject: [PATCH 44/61] sync: check a native mirror against a reference model over random histories MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Random histories of adds, changes, deletes, re-adds, nested file↔directory swaps, case-only renames of files and directories, and on a folding destination a second spelling of a file it holds, run through a native mirror on both transports. A third of the pushes are preceded by one that crashes at a random transport call. After every clean push the live records and the destination's tree match the model, which keeps what the source deleted until a present path needs its name, and the three invariants hold. --- sync/mirror_model_test.go | 374 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 374 insertions(+) create mode 100644 sync/mirror_model_test.go diff --git a/sync/mirror_model_test.go b/sync/mirror_model_test.go new file mode 100644 index 0000000..4a49b4a --- /dev/null +++ b/sync/mirror_model_test.go @@ -0,0 +1,374 @@ +package sync + +import ( + "encoding/hex" + "fmt" + "io/fs" + "math/rand/v2" + "os" + "path" + "path/filepath" + "slices" + "strings" + "testing" + "time" + "unicode" + + "github.com/zeebo/blake3" + + "github.com/mbertschler/squirrel/store" +) + +// mirrorModel is the reference a native mirror is checked against: the +// source's present files, and the live tree a clean push leaves on the +// destination. A destination keeps what the source deleted, until a +// present path needs its name. +type mirrorModel struct { + fold nameFolding + present map[string]string // source path → body + dest map[string]string // destination path → body +} + +// push applies one push to the model: every present path, except the +// refused ones, lands, and every other entry whose name it needs — the same +// name under another spelling, a file where its directory goes, or a +// directory where it goes — moves into history. +func (m *mirrorModel) push(refused map[string]bool) { + for _, p := range sortedKeys(m.present) { + if refused[p] { + continue + } + for q := range m.dest { + if q != p && m.conflicts(p, q) { + delete(m.dest, q) + } + } + m.dest[p] = m.present[p] + } +} + +func (m *mirrorModel) conflicts(p, q string) bool { + kp, kq := m.fold.key(p), m.fold.key(q) + return kp == kq || strings.HasPrefix(kp, kq+"/") || strings.HasPrefix(kq, kp+"/") +} + +func sortedKeys(m map[string]string) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + slices.Sort(keys) + return keys +} + +// modelRun drives one random history against a mirror fixture and its +// model. +type modelRun struct { + t *testing.T + f *mirrorFixture + m *mirrorModel + rng *rand.Rand + step int + clock time.Time +} + +// sourceFolding is how the generator keeps the source free of spellings +// any destination would fold together, whatever this machine's disk does. +var sourceFolding = caseAndNormFolding + +// TestMirrorModel runs random histories — adds, changes, deletes, re-adds, +// file↔directory swaps, nested, renames that change only case, and on a +// folding destination names that collide — through a native mirror, each +// push preceded now and then by one that crashes at a random transport +// call. After every clean push the destination's live records and its tree +// match the reference model, and the three invariants hold. +func TestMirrorModel(t *testing.T) { + for _, b := range mirrorBackends { + for _, fold := range []nameFolding{{}, caseAndNormFolding} { + for seed := uint64(1); seed <= 3; seed++ { + t.Run(fmt.Sprintf("%s/folds=%v/seed=%d", b.name, fold.folds(), seed), func(t *testing.T) { + t.Parallel() + f := setupMirrorFixtureOn(t, b) + f.fold = fold + disk := diskFolding(t, f.dst) + r := &modelRun{t: t, f: f, rng: rand.New(rand.NewPCG(seed, seed)), clock: time.Unix(1_700_000_000, 0), + m: &mirrorModel{ + fold: nameFolding{caseless: fold.caseless || disk.caseless, normless: fold.normless || disk.normless}, + present: map[string]string{}, dest: map[string]string{}, + }} + for r.step = 0; r.step < 25; r.step++ { + r.changeSource() + r.push() + } + }) + } + } + } +} + +// changeSource applies one to three random changes to the source. +func (r *modelRun) changeSource() { + for range 1 + r.rng.IntN(3) { + switch r.rng.IntN(10) { + case 0, 1, 2, 3: + r.write(r.randomPath()) + case 4, 5: + if p, ok := r.pickPresent(); ok { + r.write(p) + } + case 6, 7: + if p, ok := r.pickPresent(); ok { + r.remove(p) + } + case 8: + if p, ok := r.pickGone(); ok { + r.write(p) + } + case 9: + r.renameCase() + } + } +} + +func (r *modelRun) randomPath() string { + elems := make([]string, 1+r.rng.IntN(3)) + for i := range elems { + elems[i] = string(rune('a' + r.rng.IntN(3))) + } + return strings.Join(elems, "/") +} + +func (r *modelRun) pickPresent() (string, bool) { + keys := sortedKeys(r.m.present) + if len(keys) == 0 { + return "", false + } + return keys[r.rng.IntN(len(keys))], true +} + +// pickGone picks a path the destination still holds that the source no +// longer has. +func (r *modelRun) pickGone() (string, bool) { + var gone []string + for _, p := range sortedKeys(r.m.dest) { + if _, ok := r.m.present[p]; !ok { + gone = append(gone, p) + } + } + if len(gone) == 0 { + return "", false + } + return gone[r.rng.IntN(len(gone))], true +} + +// write puts a new body at p, spelled as the source already spells its +// existing parts, first removing a file where p's directory goes and a +// directory where p goes: the file↔directory swaps. +func (r *modelRun) write(p string) { + p = foldingTransport{disk: r.f.src, fold: sourceFolding}.resolve(p) + for q := range r.m.present { + if strings.HasPrefix(p, q+"/") || strings.HasPrefix(q, p+"/") { + delete(r.m.present, q) + } + } + parts := strings.Split(p, "/") + for i := 1; i <= len(parts); i++ { + at := filepath.Join(r.f.src, filepath.FromSlash(strings.Join(parts[:i], "/"))) + if fi, err := os.Lstat(at); err == nil && (i < len(parts)) != fi.IsDir() { + if err := os.RemoveAll(at); err != nil { + r.t.Fatal(err) + } + } + } + body := fmt.Sprintf("%s at step %d %s", p, r.step, strings.Repeat("x", r.rng.IntN(40))) + r.f.write(r.t, p, body) + r.touch(p) + r.m.present[p] = body +} + +// touch gives p an mtime of its own, so the index sees every change. +func (r *modelRun) touch(p string) { + r.clock = r.clock.Add(time.Second) + if err := os.Chtimes(filepath.Join(r.f.src, filepath.FromSlash(p)), r.clock, r.clock); err != nil { + r.t.Fatal(err) + } +} + +func (r *modelRun) remove(p string) { + if err := os.Remove(filepath.Join(r.f.src, filepath.FromSlash(p))); err != nil { + r.t.Fatal(err) + } + delete(r.m.present, p) +} + +// renameCase renames one element of a present path — the file, or a +// directory above it — to its other case, when no other present path +// would fold onto the new spelling. +func (r *modelRun) renameCase() { + p, ok := r.pickPresent() + if !ok { + return + } + parts := strings.Split(p, "/") + i := r.rng.IntN(len(parts)) + from := strings.Join(parts[:i+1], "/") + parts[i] = otherCase(parts[i]) + to := strings.Join(parts[:i+1], "/") + moved := map[string]string{} + for q, body := range r.m.present { + switch { + case q == from || strings.HasPrefix(q, from+"/"): + moved[to+strings.TrimPrefix(q, from)] = body + case sourceFolding.key(q) == sourceFolding.key(to) || sourceFolding.under(q, to): + return + } + } + if err := os.Rename(filepath.Join(r.f.src, filepath.FromSlash(from)), filepath.Join(r.f.src, filepath.FromSlash(to))); err != nil { + r.t.Fatal(err) + } + for q := range r.m.present { + if q == from || strings.HasPrefix(q, from+"/") { + delete(r.m.present, q) + } + } + for q, body := range moved { + r.m.present[q] = body + } +} + +func otherCase(s string) string { + rs := []rune(s) + if unicode.IsUpper(rs[0]) { + rs[0] = unicode.ToLower(rs[0]) + } else { + rs[0] = unicode.ToUpper(rs[0]) + } + return string(rs) +} + +// push indexes the source, sometimes pushes once with a crash at a random +// transport call, then pushes cleanly and checks the destination against +// the model. On a folding destination it sometimes records, after the +// index, a second spelling of a file the destination holds: that push +// refuses the second spelling and fails, and the next index drops it, +// since no source file holds it. +func (r *modelRun) push() { + t, f := r.t, r.f + f.index(t) + before := f.contentHashes(t) + if r.m.fold.folds() && r.rng.IntN(6) == 0 { + if r.collide() { + return + } + } + if r.rng.IntN(3) == 0 { + mode := []crashMode{crashBefore, crashAfter, crashMidway}[r.rng.IntN(3)] + _, _ = f.pushCrashing(t, crashAtCall(r.rng.IntN(60)), mode) + f.checkRecordsVouch(t) + f.checkOnlyGrew(t, before) + } + rep, err := f.push(t, Options{}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("step %d: push: status=%q err=%v warnings=%v", r.step, rep.Status, err, rep.Warnings) + } + r.m.push(nil) + f.checkInvariants(t, before) + r.checkAgainstModel() +} + +// collide records another spelling of a file the destination holds as +// present and pushes: the push refuses that spelling alone and fails. +func (r *modelRun) collide() bool { + var held []string + for _, p := range sortedKeys(r.m.present) { + if r.m.dest[p] == r.m.present[p] { + held = append(held, p) + } + } + if len(held) == 0 { + return false + } + p := held[r.rng.IntN(len(held))] + variant := path.Join(path.Dir(p), otherCase(path.Base(p))) + r.f.observe(r.t, variant, "a spelling the destination cannot hold") + before := r.f.contentHashes(r.t) + rep, err := r.f.push(r.t, Options{}) + if err == nil || !warned(rep, variant+" is not written") { + r.t.Fatalf("step %d: push with %s beside %s: err=%v warnings=%v, want %s refused", r.step, variant, p, err, rep.Warnings, variant) + } + r.m.push(map[string]bool{variant: true}) + r.f.checkRecordsVouch(r.t) + r.f.checkOnlyGrew(r.t, before) + return true +} + +// checkAgainstModel compares the live records and the destination's tree +// with the model, name by name as the destination resolves names. +func (r *modelRun) checkAgainstModel() { + t, f := r.t, r.f + want := map[string]string{} + for p, body := range r.m.dest { + want[r.m.fold.key(p)] = p + " " + bodyHash(body) + } + live := map[string]string{} + volID := f.volumeID(t) + for _, row := range f.rows(t) { + if row.State == store.RemotePathLive { + live[r.m.fold.key(row.Path)] = row.Path + " " + f.contentHashOf(t, volID, row) + } + } + if !mapsEqual(live, want) { + t.Fatalf("step %d: live records = %v, want %v", r.step, live, want) + } + tree := r.destTree() + for k, v := range want { + if got := tree[k]; got != strings.SplitN(v, " ", 2)[1] { + t.Errorf("step %d: destination holds %q at %s, want %s", r.step, got, v, bodyHash(r.m.dest[strings.SplitN(v, " ", 2)[0]])) + } + } + if len(tree) != len(want) { + t.Fatalf("step %d: destination tree = %v, want %v", r.step, tree, want) + } +} + +// destTree is the hash of every file in the volume's mirrored tree, keyed +// by folded name, outside the reserved directories and the marker. +func (r *modelRun) destTree() map[string]string { + root := filepath.Join(r.f.dst, "pics") + out := map[string]string{} + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, _ := filepath.Rel(root, p) + rel = filepath.ToSlash(rel) + if d.IsDir() && isReservedFolderPath(rel) { + return filepath.SkipDir + } + if d.Type().IsRegular() && rel != ".squirrel-volume" { + out[r.m.fold.key(rel)] = hashOnDisk(p) + } + return nil + }) + if err != nil { + r.t.Fatal(err) + } + return out +} + +func bodyHash(body string) string { + sum := blake3.Sum256([]byte(body)) + return hex.EncodeToString(sum[:]) +} + +func mapsEqual(a, b map[string]string) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if b[k] != v { + return false + } + } + return true +} From 444a215fed737f92eb82a74f835bce11cd9b0a9a Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 05:00:05 +0200 Subject: [PATCH 45/61] sync: lose records a non-directory took away, and report staging of unknown runs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A recorded directory that the destination replaced with a file or a symlink, or lost, left the rows under it live although their bytes could no longer be at their paths. The push that finds it now marks them lost, so the next push repairs them while the index holds their content. A staging directory named for a run the index does not know was skipped silently; it is reported as foreign now, and still never removed. Tests pin both, and cover the rest of the hostile cases the design lists on both transports: symlinks at a target, along its parent chain and in place of the volume, history, staging and index directories; nested file↔directory swaps with changed and foreign entries inside; foreign files, directories and symlinks in staging; a disk that fills up or a quota that runs out mid-write; a history directory that can't be written; and a source that drifts while it streams, for the content layouts too, with symlinks at an artifact's name. --- design/native-mirror.md | 8 +- sync/content_native_test.go | 10 +- sync/destination_root.go | 14 +- sync/mirror_hostile_test.go | 538 ++++++++++++++++++++++++++++++++++++ sync/mirror_write.go | 26 +- 5 files changed, 590 insertions(+), 6 deletions(-) create mode 100644 sync/mirror_hostile_test.go diff --git a/design/native-mirror.md b/design/native-mirror.md index 1d06c95..5056e76 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -255,7 +255,8 @@ type transport interface { - `Remove` only on squirrel's own staging names from runs that have finished (`.squirrel-staging/run-/`), and on ride-along snapshots (`.squirrel-index/index-*.db`, which rotation already deletes today). - Anything else found in staging is reported and left alone; + Anything else found in staging, a run directory of a run the index + doesn't know included, is reported and left alone; - `Rename` only from this run's staging to a snapshot name (the ride-along) or to what the layout commits — a live name for a mirror; for a content layout `objects/`, `packs/`, `packs/map-` @@ -463,6 +464,11 @@ is treated as changed behind squirrel's back: its row becomes `lost` and the pat - **It is a directory** a file replaced: every live row under it becomes `displacing`, the directory moves, and they become `displaced`; a row whose bytes changed becomes `lost` first. + - **It is not a directory, or nothing**, while live rows sit under the + path (a recorded directory replaced by a file or a symlink on the + destination, or removed): those rows become `lost`, since their bytes + can't be at their paths, and turn into repairs while the index holds + their content. 4. **Commit:** 1. insert the new row as `committing`; 2. rename the staged file to the path; diff --git a/sync/content_native_test.go b/sync/content_native_test.go index b9500bc..853b852 100644 --- a/sync/content_native_test.go +++ b/sync/content_native_test.go @@ -124,6 +124,14 @@ func (f *nativeContentFixture) mustPush(t *testing.T) Report { // pushCrashing runs one push whose transport crashes, as mode says, at the // first call crashAt selects. func (f *nativeContentFixture) pushCrashing(t *testing.T, crashAt func(transportCall) bool, mode crashMode) (Report, error) { + t.Helper() + return f.pushVia(t, func(tr transport) transport { + return &faultTransport{transport: tr, crashAt: crashAt, mode: mode} + }) +} + +// pushVia runs one push through wrap's transport. +func (f *nativeContentFixture) pushVia(t *testing.T, wrap func(transport) transport) (Report, error) { t.Helper() h, err := HandlerFor(f.store, Tools{}, f.pair) if err != nil { @@ -142,7 +150,7 @@ func (f *nativeContentFixture) pushCrashing(t *testing.T, crashAt func(transport if err != nil { return nil, err } - return &faultTransport{transport: raw, crashAt: crashAt, mode: mode}, nil + return wrap(raw), nil } return h.Push(context.Background(), Options{}) } diff --git a/sync/destination_root.go b/sync/destination_root.go index 51a7c1d..896913f 100644 --- a/sync/destination_root.go +++ b/sync/destination_root.go @@ -2,6 +2,7 @@ package sync import ( "context" + "database/sql" "errors" "fmt" "io/fs" @@ -66,7 +67,8 @@ func (h *destinationRoot) runFinished(runID int64) bool { // clearFinishedStaging removes what finished runs left in staging: // partial files from a crash, and a drifted source's staged copy. -// Anything in staging squirrel did not name is reported and left alone. +// Anything in staging squirrel did not name, a run directory of a run the +// index does not know included, is reported and left alone. func (h *destinationRoot) clearFinishedStaging(ctx context.Context, rep *Report, tr transport) error { dir := path.Join(h.volumeDir, StagingDirName) runs, err := tr.List(ctx, dir) @@ -85,7 +87,15 @@ func (h *destinationRoot) clearFinishedStaging(ctx context.Context, rep *Report, h.warnForeignStaging(rep, path.Join(dir, e.name)) continue } - if !h.runFinished(runID) { + r, err := h.store.GetRun(ctx, runID) + if errors.Is(err, sql.ErrNoRows) { + h.warnForeignStaging(rep, path.Join(dir, e.name)) + continue + } + if err != nil { + return fmt.Errorf("look up the run of %s: %w", path.Join(dir, e.name), err) + } + if r.Status == store.RunStatusRunning { continue } if err := h.clearStagingRun(ctx, rep, tr, path.Join(dir, e.name)); err != nil { diff --git a/sync/mirror_hostile_test.go b/sync/mirror_hostile_test.go new file mode 100644 index 0000000..e66dd22 --- /dev/null +++ b/sync/mirror_hostile_test.go @@ -0,0 +1,538 @@ +package sync + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "github.com/mbertschler/squirrel/config" + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// plantSymlink replaces what the destination holds at rel with a symlink +// to target. +func (f *mirrorFixture) plantSymlink(t *testing.T, rel, target string) { + t.Helper() + if err := os.RemoveAll(f.dest(rel)); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(f.dest(rel)), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, f.dest(rel)); err != nil { + t.Fatal(err) + } +} + +// outsideDir is a directory beside the destination that a symlink can +// point squirrel at; checkUntouched asserts nothing was written there. +func outsideDir(t *testing.T) string { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "precious.txt"), []byte("outside"), 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +func checkUntouched(t *testing.T, dir string) { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != "precious.txt" { + t.Fatalf("outside directory holds %v, want only precious.txt", entries) + } + if b, _ := os.ReadFile(filepath.Join(dir, "precious.txt")); string(b) != "outside" { + t.Fatalf("precious.txt = %q, want it unchanged", b) + } +} + +// TestMirrorNeverFollowsASymlinkAtATarget: a symlink the destination holds +// where a path, or a directory along it, should be is never followed. It +// moves into history as bytes squirrel did not write, a record it replaced +// becomes lost, and the path lands in a real directory; nothing is written +// where the symlink points. +func TestMirrorNeverFollowsASymlinkAtATarget(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "dir/old.txt", "old") + f.write(t, "a.txt", "a1") + f.index(t) + f.mustPush(t) + outside := outsideDir(t) + f.plantSymlink(t, "dir", outside) + f.plantSymlink(t, "a.txt", filepath.Join(outside, "precious.txt")) + f.write(t, "dir/new.txt", "new") + f.write(t, "a.txt", "a2") + f.index(t) + + rep := f.mustPush(t) + checkUntouched(t, outside) + if f.readDest(t, "dir/new.txt") != "new" || f.readDest(t, "a.txt") != "a2" { + t.Fatal("the paths did not land in real entries") + } + run := strconv.FormatInt(rep.RunID, 10) + for _, rel := range []string{"dir", "a.txt"} { + if fi, err := os.Lstat(f.dest(HistoryDirName + "/run-" + run + "/" + rel)); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Fatalf("history/%s = %v, %v; want the symlink itself preserved", rel, fi, err) + } + } + for _, rel := range []string{"dir/old.txt", "a.txt"} { + if got := f.rowsAt(t, rel); len(got) == 0 || got[0] != store.RemotePathLost { + t.Fatalf("%s rows = %v, want its first row lost", rel, got) + } + } + f.checkRecordsVouch(t) + + f.mustPush(t) + if f.readDest(t, "dir/old.txt") != "old" { + t.Fatal("the next push did not repair the path the symlink took away") + } + f.checkInvariants(t, nil) + }) + } +} + +// TestMirrorNeverFollowsASymlinkedReservedDirectory: a symlink in place of +// the volume directory, or of its history, staging or index directory, +// fails the push instead of being followed, and nothing is written where +// it points. Once the symlink is gone, a clean push settles everything. +func TestMirrorNeverFollowsASymlinkedReservedDirectory(t *testing.T) { + for _, b := range mirrorBackends { + for _, rel := range []string{HistoryDirName, StagingDirName, IndexDirName, "."} { + t.Run(b.name+"/"+rel, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2, longer") + f.index(t) + outside := outsideDir(t) + real := f.dest(rel) + ".real" + if err := os.Rename(f.dest(rel), real); err != nil && !errors.Is(err, fs.ErrNotExist) { + t.Fatal(err) + } + if err := os.Symlink(outside, f.dest(rel)); err != nil { + t.Fatal(err) + } + if rel == "." { + if err := volmark.Write(outside, volmark.Marker{Volume: "pics"}); err != nil { + t.Fatal(err) + } + } + + if rep, err := f.push(t, Options{}); err == nil || rep.Status == store.RunStatusSuccess { + t.Fatalf("push through a symlinked %s: status=%q err=%v, want it failed", rel, rep.Status, err) + } + if rel == "." { + _ = os.Remove(filepath.Join(outside, volmark.MarkerName)) + } + checkUntouched(t, outside) + if err := os.Remove(f.dest(rel)); err != nil { + t.Fatal(err) + } + if err := os.Rename(real, f.dest(rel)); err != nil && !errors.Is(err, fs.ErrNotExist) { + t.Fatal(err) + } + f.checkRecordsVouch(t) + f.mustPush(t) + if f.readDest(t, "a.txt") != "v2, longer" { + t.Fatal("the push after the symlink went did not land the change") + } + f.checkInvariants(t, nil) + }) + } + } +} + +// TestMirrorNestedFileDirectorySwaps: a file deep in the tree that became a +// directory holding a deeper file, and a directory tree that became a +// file, each move aside as their records — a replaced directory with every +// version recorded under it, a version changed behind squirrel's back +// losing its record, and bytes squirrel never wrote kept beside them. +func TestMirrorNestedFileDirectorySwaps(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a/b/c", "file c") + f.write(t, "x/y/z", "file z") + f.write(t, "x/y/w", "file w") + f.write(t, "x/v", "file v") + f.index(t) + f.mustPush(t) + for _, rel := range []string{"a/b/c", "x"} { + if err := os.RemoveAll(filepath.Join(f.src, rel)); err != nil { + t.Fatal(err) + } + } + f.write(t, "a/b/c/d/e", "deep under c") + f.write(t, "x", "x is a file") + f.index(t) + if err := os.WriteFile(f.dest("x/y/w"), []byte("changed on the destination"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest("x/y/foreign"), []byte("not squirrel's"), 0o644); err != nil { + t.Fatal(err) + } + before := f.contentHashes(t) + + rep := f.mustPush(t) + run := HistoryDirName + "/run-" + strconv.FormatInt(rep.RunID, 10) + "/" + if f.readDest(t, "a/b/c/d/e") != "deep under c" || f.readDest(t, "x") != "x is a file" { + t.Fatal("the swapped paths did not land") + } + for rel, want := range map[string]string{"a/b/c": "file c", "x/y/z": "file z", "x/v": "file v", "x/y/foreign": "not squirrel's", "x/y/w": "changed on the destination"} { + if got := f.readDest(t, run+rel); got != want { + t.Errorf("history %s = %q, want %q", rel, got, want) + } + } + for rel, want := range map[string]string{"a/b/c": store.RemotePathDisplaced, "x/y/z": store.RemotePathDisplaced, "x/v": store.RemotePathDisplaced, "x/y/w": store.RemotePathLost} { + if got := f.rowsAt(t, rel); !slicesEqual(got, []string{want}) { + t.Errorf("%s rows = %v, want %s", rel, got, want) + } + } + f.checkInvariants(t, before) + }) + } +} + +// TestMirrorLeavesForeignStagingAlone: whatever squirrel did not name in +// staging — a file or directory at its top, a run directory of a run the +// index does not know, a symlink or directory in a finished run's staging +// — is reported and never removed, while the finished run's own staging +// beside it goes. +func TestMirrorLeavesForeignStagingAlone(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "alpha") + f.index(t) + first := f.mustPush(t) + finished := StagingDirName + "/run-" + strconv.FormatInt(first.RunID, 10) + "/" + key := stagingKey("a.txt") + foreign := []string{StagingDirName + "/notes.txt", StagingDirName + "/mine/x", StagingDirName + "/run-999999/" + key, finished + key + "0/x"} + for _, rel := range foreign { + if err := os.MkdirAll(filepath.Dir(f.dest(rel)), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest(rel), []byte("foreign"), 0o644); err != nil { + t.Fatal(err) + } + } + if err := os.Symlink(outsideDir(t), f.dest(finished+"link")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest(finished+key), []byte("a crashed run's partial copy"), 0o644); err != nil { + t.Fatal(err) + } + + f.write(t, "a.txt", "alpha, changed") + f.index(t) + rep := f.mustPush(t) + for _, name := range []string{"notes.txt", "mine", "run-999999", key + "0", "link"} { + if !warned(rep, name+" is in squirrel's staging") { + t.Errorf("warnings = %v, want %s reported", rep.Warnings, name) + } + } + for _, rel := range append(foreign, finished+"link") { + if _, err := os.Lstat(f.dest(rel)); err != nil { + t.Errorf("%s was removed: %v", rel, err) + } + } + if _, err := os.Stat(f.dest(finished + key)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the finished run's own staged copy is still there: %v", err) + } + }) + } +} + +// fullTransport fails a Put that full selects once it has taken limit +// bytes, as a disk that fills up, or a quota that runs out, mid-write. +type fullTransport struct { + transport + full func(name string) bool + limit int64 + errno syscall.Errno +} + +func (f fullTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if !f.full(name) { + return f.transport.Put(ctx, name, r, mtime) + } + return f.transport.Put(ctx, name, &fillingReader{r: r, left: f.limit, errno: f.errno}, mtime) +} + +type fillingReader struct { + r io.Reader + left int64 + errno syscall.Errno +} + +func (f *fillingReader) Read(p []byte) (int, error) { + if f.left <= 0 { + return 0, &fs.PathError{Op: "write", Path: "staged", Err: f.errno} + } + if int64(len(p)) > f.left { + p = p[:f.left] + } + n, err := f.r.Read(p) + f.left -= int64(n) + return n, err +} + +// TestMirrorDiskFullMidWrite: a destination that fills up, or runs out of +// quota, part way through a path's staged copy, the name probe or the +// receipt fails the push with the disk's error. Nothing reaches a path, +// every version already there stays, and once there is room again a clean +// push lands everything and clears the partial copy. +func TestMirrorDiskFullMidWrite(t *testing.T) { + staged := func(n string) bool { return strings.Contains(n, StagingDirName+"/run-") } + cases := []struct { + name string + full func(string) bool + limit int64 + errno syscall.Errno + }{ + {"staged copy, disk full", staged, 100, syscall.ENOSPC}, + {"staged copy, quota", staged, 100, syscall.EDQUOT}, + {"name probe", func(n string) bool { return strings.HasSuffix(n, foldProbeBase) }, 0, syscall.ENOSPC}, + {"receipt", func(n string) bool { return strings.Contains(n, IndexDirName+"/run-") }, 100, syscall.ENOSPC}, + } + for _, b := range mirrorBackends { + for _, c := range cases { + t.Run(b.name+"/"+c.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", strings.Repeat("v2 ", 1000)) + f.write(t, "b.txt", strings.Repeat("new ", 1000)) + f.index(t) + before := f.contentHashes(t) + rep, err := f.pushVia(t, Options{}, func(tr transport) transport { + return fullTransport{transport: tr, full: c.full, limit: c.limit, errno: c.errno} + }) + if err == nil || rep.Status == store.RunStatusSuccess { + t.Fatalf("push onto a full disk: status=%q err=%v, want it failed", rep.Status, err) + } + if msg := err.Error() + fmt.Sprint(rep.RcloneResult.FailedFiles); !strings.Contains(msg, c.errno.Error()) { + t.Fatalf("failure %q, want the disk's error %q named", msg, c.errno.Error()) + } + if c.name != "receipt" && f.readDest(t, "a.txt") != "v1" { + t.Fatal("a path changed although its new version never fully landed") + } + f.checkRecordsVouch(t) + f.checkOnlyGrew(t, before) + + clean := f.mustPush(t) + if f.readDest(t, "a.txt") != strings.Repeat("v2 ", 1000) || f.readDest(t, "b.txt") != strings.Repeat("new ", 1000) { + t.Fatal("the push with room again did not land everything") + } + f.checkInvariants(t, before) + f.checkStagingEmpty(t, clean.RunID) + }) + } + } +} + +// TestMirrorHistoryUnwritable: when the history directory can't be +// written, a path whose recorded version must move there fails and keeps +// that version in place; nothing else is displaced for it. Once history is +// writable again, the next push settles the interrupted move and lands the +// change. +func TestMirrorHistoryUnwritable(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("permissions do not bind root") + } + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "a.txt", "v2") + f.index(t) + f.mustPush(t) + history := f.dest(HistoryDirName) + if err := os.Chmod(history, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(history, 0o755) }) + f.write(t, "a.txt", "v3, longer") + f.index(t) + before := f.contentHashes(t) + + rep, err := f.push(t, Options{}) + if err == nil || len(rep.RcloneResult.FailedFiles) != 1 { + t.Fatalf("push: err=%v failures=%+v, want a.txt failed", err, rep.RcloneResult.FailedFiles) + } + if f.readDest(t, "a.txt") != "v2" { + t.Fatal("the recorded version left its path although history could not take it") + } + f.checkRecordsVouch(t) + f.checkOnlyGrew(t, before) + + if err := os.Chmod(history, 0o755); err != nil { + t.Fatal(err) + } + f.mustPush(t) + if f.readDest(t, "a.txt") != "v3, longer" { + t.Fatal("the push with history writable did not land the change") + } + f.checkInvariants(t, before) + }) + } +} + +// driftingTransport changes the source file of the path staged at a +// staging key once its Put has taken the first chunk: the source drifts +// while it streams. +type driftingTransport struct { + transport + src string // the source file that drifts +} + +func (d driftingTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if !strings.Contains(name, StagingDirName+"/run-") { + return d.transport.Put(ctx, name, r, mtime) + } + return d.transport.Put(ctx, name, &driftingReader{r: r, src: d.src}, mtime) +} + +type driftingReader struct { + r io.Reader + src string + drifted bool +} + +func (d *driftingReader) Read(p []byte) (int, error) { + n, err := d.r.Read(p) + if !d.drifted && n > 0 { + d.drifted = true + b, rerr := os.ReadFile(d.src) + if rerr != nil { + return n, rerr + } + for i := range b { + b[i] ^= 0xff + } + if werr := os.WriteFile(d.src, b, 0o644); werr != nil { + return n, werr + } + } + return n, err +} + +// TestMirrorSourceDriftWhileStreaming: a source file that changes while +// its bytes stream to the destination is refused — the hash covers exactly +// the bytes sent — and its path keeps the version it had. The run fails +// before its receipt; after an index run the next push lands the new +// bytes and clears the refused copy. +func TestMirrorSourceDriftWhileStreaming(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "big.bin", "v1") + f.index(t) + f.mustPush(t) + f.write(t, "big.bin", strings.Repeat("0123456789abcdef", 256<<10)) + f.index(t) + before := f.contentHashes(t) + rep, err := f.pushVia(t, Options{}, func(tr transport) transport { + return driftingTransport{transport: tr, src: filepath.Join(f.src, "big.bin")} + }) + if err == nil || !strings.Contains(err.Error(), "drifting") || !warned(rep, "big.bin sent") { + t.Fatalf("push: err=%v warnings=%v, want big.bin refused for drifting", err, rep.Warnings) + } + if f.readDest(t, "big.bin") != "v1" { + t.Fatal("the path changed although its source drifted") + } + f.checkRecordsVouch(t) + f.checkOnlyGrew(t, before) + + f.index(t) + clean := f.mustPush(t) + want, _ := os.ReadFile(filepath.Join(f.src, "big.bin")) + if f.readDest(t, "big.bin") != string(want) { + t.Fatal("the push after the index did not land the drifted bytes") + } + f.checkInvariants(t, before) + f.checkStagingEmpty(t, clean.RunID) + }) + } +} + +// TestNativeContentNeverFollowsASymlinkAtAnArtifactName: a symlink where +// an object, or the objects directory, should be is never followed or +// replaced: the artifact fails, nothing is recorded for it, and nothing is +// written where the symlink points. +func TestNativeContentNeverFollowsASymlinkAtAnArtifactName(t *testing.T) { + for _, b := range contentBackends { + for _, at := range []string{"object", "objects directory"} { + t.Run(b.name+"/"+at, func(t *testing.T) { + f := setupNativeContentFixture(t, b, config.LayoutContentAddressed) + f.write(t, "a.txt", "alpha") + f.index(t) + outside := outsideDir(t) + link, target := f.objectPath("alpha"), filepath.Join(outside, "precious.txt") + if at == "objects directory" { + link, target = filepath.Dir(link), outside + } else if err := os.MkdirAll(filepath.Dir(link), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + if rep, err := f.push(t, Options{}); err == nil || rep.Status == store.RunStatusSuccess { + t.Fatalf("push: status=%q err=%v, want the object refused", rep.Status, err) + } + checkUntouched(t, outside) + if fi, err := os.Lstat(link); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Fatalf("the symlink was replaced: %v, %v", fi, err) + } + if _, ok := f.remoteObject(t, "alpha"); ok { + t.Fatal("the refused object was recorded") + } + }) + } + } +} + +// TestNativeContentSourceDriftWhileStreaming: a content layout refuses an +// object whose source changed while it streamed; nothing lands at the +// object's name. +func TestNativeContentSourceDriftWhileStreaming(t *testing.T) { + for _, b := range contentBackends { + t.Run(b.name, func(t *testing.T) { + f := setupNativeContentFixture(t, b, config.LayoutContentAddressed) + body := strings.Repeat("0123456789abcdef", 256<<10) + f.write(t, "big.bin", body) + f.index(t) + rep, err := f.pushVia(t, func(tr transport) transport { + return driftingTransport{transport: tr, src: filepath.Join(f.src, "big.bin")} + }) + if err == nil || rep.Status == store.RunStatusSuccess { + t.Fatalf("push: status=%q err=%v, want the drifted object refused", rep.Status, err) + } + if _, err := os.Stat(f.objectPath(body)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("drifted bytes reached the object's name: %v", err) + } + if _, ok := f.remoteObject(t, body); ok { + t.Fatal("the drifted object was recorded") + } + }) + } +} diff --git a/sync/mirror_write.go b/sync/mirror_write.go index 46aa48c..a2a87cd 100644 --- a/sync/mirror_write.go +++ b/sync/mirror_write.go @@ -239,15 +239,24 @@ func (w *mirrorWriter) clearParents(ctx context.Context, rel string) error { // whose size and mtime match its live record moves as that record; a // directory moves with every live record under it; anything else moves as // unrecorded bytes, and a record they contradict becomes lost, so a -// record in history always vouches for the bytes there. +// record in history always vouches for the bytes there. Where rel holds +// no directory, every record under it is lost too. func (w *mirrorWriter) displace(ctx context.Context, rel string) error { e, err := w.tr.Stat(ctx, w.h.liveName(rel)) if errors.Is(err, fs.ErrNotExist) { + if err := w.loseRecordsUnder(ctx, rel); err != nil { + return err + } return w.loseRecordAt(ctx, rel, "is gone from the destination") } if err != nil { return err } + if e.kind != kindDir { + if err := w.loseRecordsUnder(ctx, rel); err != nil { + return err + } + } if live, ok := w.live[rel]; ok { if matchesRecord(e, live) { return w.moveRecorded(ctx, rel, []int64{live.ID}) @@ -367,6 +376,19 @@ func (w *mirrorWriter) commit(ctx context.Context, d store.PathDelta, staged sta return nil } +// loseRecordsUnder marks lost every live record below rel, whose +// directory the destination no longer holds. +func (w *mirrorWriter) loseRecordsUnder(ctx context.Context, rel string) error { + for r, live := range w.live { + if w.fold.under(r, rel) { + if err := w.loseRecord(ctx, live, "is gone: "+rel+" is not a directory on the destination"); err != nil { + return err + } + } + } + return nil +} + // loseRecordAt marks the live record at rel lost, if there is one. func (w *mirrorWriter) loseRecordAt(ctx context.Context, rel, why string) error { if live, ok := w.live[rel]; ok { @@ -380,7 +402,7 @@ func (w *mirrorWriter) loseRecord(ctx context.Context, live store.RemotePath, wh return err } delete(w.live, live.Path) - w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: %s %s — it was changed behind squirrel's back, so it is written again", w.h.dest.Name, live.Path, why)) + w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: %s %s — it was changed behind squirrel's back, so its record no longer counts as a copy, and a push writes it again while the index holds it", w.h.dest.Name, live.Path, why)) return nil } From 8009e4565767db43bb621014671be8bfb2f82c95 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 05:33:37 +0200 Subject: [PATCH 46/61] sync: refuse a first push onto a tree squirrel did not record, and leave AppleDouble files to macOS The testbed walk found two gaps on a real exFAT disk. A fresh index pushing to a native mirror took the watermark rule's first branch and started from 0 over whatever the volume's directory held: it moved a whole tree rclone wrote into history and wrote it again, doubling what the disk holds, where decision 4 refuses existing trees. The first push of a volume now refuses a volume directory that holds files outside staging while squirrel has no row of the volume there, and points at recover for a native mirror whose index is gone. A crashed first push left rows, so its retry passes; a second volume beside the first starts fresh. The content layouts keep adopting artifacts at their names. macOS keeps every file's attributes in a ._ companion on exFAT, so each push reported the previous run's ._run- as foreign staging, and an index-less restore brought back hundreds of ._ files, those of the reserved directories included, as unchecked. A ._X beside X is now X's: skipped by the staging report and the emptiness checks, and left out of an index-less restore, counted once, unless a receipt names it. --- design/native-mirror.md | 33 ++++- docs/src/content/docs/guides/restore.md | 4 +- docs/src/content/docs/layouts/mirror.md | 9 +- store/remote_paths.go | 15 +++ store/remote_paths_test.go | 24 ++++ sync/appledouble.go | 21 ++++ sync/content_addressed.go | 5 + sync/destination_root.go | 30 ++++- sync/mirror.go | 37 +++++- sync/mirror_first_push_test.go | 155 ++++++++++++++++++++++++ sync/push.go | 9 +- sync/restore_mirror.go | 23 ++-- 12 files changed, 340 insertions(+), 25 deletions(-) create mode 100644 sync/appledouble.go create mode 100644 sync/mirror_first_push_test.go diff --git a/design/native-mirror.md b/design/native-mirror.md index 5056e76..a780094 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -149,7 +149,17 @@ closed as success; it now closes as failed, like content-addressed. This rule is shared by all three layouts: 1. If there is no successful sync of this (volume, destination), the - watermark is 0. + watermark is 0, once the layout's first-push gate passes. The content + layouts pass it always: an artifact already at its name is confirmed and + adopted. A mirror refuses when squirrel holds no `remote_paths` row of the + volume there and the volume's directory holds files outside + `.squirrel-staging/` beyond its marker (`mirrorHandler.firstPush`): a + tree rclone wrote, or a native mirror whose index is gone, which + `squirrel recover --from` restores. Without the gate, a fresh index moved + the whole existing tree into history and wrote it again, doubling what + the disk holds. A first push that crashed left rows, so its retry passes, + and the check covers the volume's directory only, so a second volume + starts fresh beside the first. 2. If the last success left its landing evidence at the destination, the watermark is that run's id. 3. The watermark is also 0 (a fresh start) when all three of these hold: @@ -523,6 +533,20 @@ stayed `live` over the other spelling's bytes, breaking invariant 1. under `Photos/`, as files no receipt names. - A dry run doesn't probe, so its preview doesn't show collisions. +### AppleDouble companions + +On a filesystem without extended attributes (exFAT, FAT, some SMB shares), +macOS keeps a file's attributes in a companion `._` beside it, and +moves and removes the companion with the file. Every file squirrel writes +from a Mac gets one, since the system tags new files with an attribute. The +testbed walk found them reported as foreign staging on every push, restored +as unchecked files by an index-less restore, and counted as content by the +emptiness checks. A `._X` whose `X` is in the same listing is now X's +(`sync/appledouble.go`): skipped by the staging report and the emptiness +checks, and left out of an index-less restore, counted in one warning, +unless a receipt names it. A companion the system left behind is reported +like any other foreign entry. + ### Crash points | Crash after | Destination | Reconcile at the next push | @@ -815,9 +839,10 @@ Decided on 2026-09-23: Configs that relied on rclone accepting any key must pin it first. 3. **Read-back** runs on local disks only (section 5). 4. **Existing mirror trees aren't adopted.** The watermark rule refuses an - rclone-era mirror: the tree isn't empty, and its runs left no receipts. A - native mirror needs a fresh or emptied root. Adoption gets built only if the - testbed shows that hurts. + rclone-era mirror: the tree isn't empty, and its runs left no receipts. + An index that never synced there is refused too, by the first-push gate + (rule 1). A native mirror needs a fresh or emptied root. Adoption gets + built only if the testbed shows that hurts. 5. **Receipts** for mirrors live in `.squirrel-index/`. The content layouts keep their segments where they are. 6. **Case-folding and normalization collisions** refuse only the colliding diff --git a/docs/src/content/docs/guides/restore.md b/docs/src/content/docs/guides/restore.md index 8c8571b..245ed06 100644 --- a/docs/src/content/docs/guides/restore.md +++ b/docs/src/content/docs/guides/restore.md @@ -66,7 +66,9 @@ involved. [receipts](/squirrel/layouts/mirror/#how-a-mirror-is-written) name the content each path last held, so every file a receipt names is checked against it and refused if it differs. A file no receipt names (one squirrel did not write) is - restored unchecked, and the run's warnings count them. + restored unchecked, and the run's warnings count them. The `._` files macOS + keeps beside each file on an exFAT or FAT disk hold that file's extended + attributes; restore leaves them out and counts them in one warning. ## Content-addressed and packed destinations diff --git a/docs/src/content/docs/layouts/mirror.md b/docs/src/content/docs/layouts/mirror.md index e47419a..13f0a2b 100644 --- a/docs/src/content/docs/layouts/mirror.md +++ b/docs/src/content/docs/layouts/mirror.md @@ -42,8 +42,13 @@ push leaves a **receipt** at `.squirrel-index/run-`: the run's changes in th [manifest segment format](/squirrel/reference/formats/), so the mirror can be checked without the index. A push that finds no receipt for the last success it recorded refuses, unless the root is empty and squirrel holds no records for it. -So a native mirror starts on a fresh or emptied root: squirrel does not adopt a -tree some other tool wrote, rclone included. +A volume's first push refuses too when its directory already holds files +squirrel has no record of writing. So a native mirror starts on a fresh or +emptied root: squirrel does not adopt a tree some other tool wrote, rclone +included. If the tree is a native mirror whose index you lost, recover the +index from it with [`squirrel recover --from`](/squirrel/guides/recovery/) +instead: the index snapshots and receipts on the mirror let the next push carry +on where the last one stopped. ### Names a disk can't tell apart diff --git a/store/remote_paths.go b/store/remote_paths.go index 147dbed..eb6e360 100644 --- a/store/remote_paths.go +++ b/store/remote_paths.go @@ -204,6 +204,21 @@ func (s *Store) ListRemotePaths(ctx context.Context, destination string, volumeI `, scanRemotePath, destination, volumeID) } +// VolumeHasRemotePaths reports whether squirrel holds any row of the +// volume on the destination, in any state. +func (s *Store) VolumeHasRemotePaths(ctx context.Context, destination string, volumeID int64) (bool, error) { + var has int + err := s.db.QueryRowContext(ctx, ` + SELECT EXISTS ( + SELECT 1 FROM remote_paths rp JOIN folders fo ON fo.id = rp.folder_id + WHERE rp.destination = ? AND fo.volume_id = ?) + `, destination, volumeID).Scan(&has) + if err != nil { + return false, fmt.Errorf("lookup mirror records of volume %d on %q: %w", volumeID, destination, err) + } + return has != 0, nil +} + // CountInSyncRemotePaths counts the volume's live rows on the destination // whose files row is still present: paths the destination holds with // their current content by squirrel's records, the mirror's "already diff --git a/store/remote_paths_test.go b/store/remote_paths_test.go index d8d3942..eae6187 100644 --- a/store/remote_paths_test.go +++ b/store/remote_paths_test.go @@ -75,6 +75,30 @@ func TestRemotePathLifecycle(t *testing.T) { } } +// TestVolumeHasRemotePaths: a volume has mirror records on a destination +// once any row of it is there, in any state, and only on that destination. +func TestVolumeHasRemotePaths(t *testing.T) { + s := openTestStore(t) + ctx := context.Background() + d, vID, runID := remotePathFixture(t, s) + if has, err := s.VolumeHasRemotePaths(ctx, "usb", vID); err != nil || has { + t.Fatalf("before any write = %v, %v; want none", has, err) + } + id, err := s.BeginRemotePathCommit(ctx, commitWrite(d, runID)) + if err != nil { + t.Fatal(err) + } + if err := s.MarkRemotePathsLost(ctx, id); err != nil { + t.Fatal(err) + } + if has, err := s.VolumeHasRemotePaths(ctx, "usb", vID); err != nil || !has { + t.Fatalf("with a lost row = %v, %v; want records", has, err) + } + if has, err := s.VolumeHasRemotePaths(ctx, "other", vID); err != nil || has { + t.Fatalf("on another destination = %v, %v; want none", has, err) + } +} + // TestRemotePathTransitionsNeedTheirSourceState: a move applies only to a // row in the state it starts from, and a batch with one wrong row changes // nothing, so a record never claims a move it did not witness. diff --git a/sync/appledouble.go b/sync/appledouble.go new file mode 100644 index 0000000..b752195 --- /dev/null +++ b/sync/appledouble.go @@ -0,0 +1,21 @@ +package sync + +import "strings" + +// appleDouble reports whether name is the AppleDouble companion of an +// entry beside it: "._X" next to "X", where macOS keeps X's extended +// attributes on a filesystem that has none (exFAT, FAT, some SMB shares). +// The system moves and removes the companion together with X. +func appleDouble(name string, siblings map[string]bool) bool { + x, ok := strings.CutPrefix(name, "._") + return ok && x != "" && siblings[x] +} + +// entryNames is the set of the entries' names. +func entryNames(entries []entry) map[string]bool { + names := make(map[string]bool, len(entries)) + for _, e := range entries { + names[e.name] = true + } + return names +} diff --git a/sync/content_addressed.go b/sync/content_addressed.go index 8f7535b..87674d2 100644 --- a/sync/content_addressed.go +++ b/sync/content_addressed.go @@ -116,6 +116,11 @@ func (h *contentPusher) markers(ctx context.Context, _ *Report, _ int64, opts Op func (h *contentPusher) rootEmpty(ctx context.Context) (bool, error) { return h.art.rootEmpty(ctx) } +// firstPush lets a content layout start over whatever the destination +// holds: an artifact already at its name is confirmed and adopted, never +// replaced. +func (h *contentPusher) firstPush(context.Context, int64) error { return nil } + func (h *contentPusher) reconcile(ctx context.Context, rep *Report, _, runID int64) error { return h.art.reconcile(ctx, rep, runID) } diff --git a/sync/destination_root.go b/sync/destination_root.go index 896913f..fb47a99 100644 --- a/sync/destination_root.go +++ b/sync/destination_root.go @@ -78,8 +78,9 @@ func (h *destinationRoot) clearFinishedStaging(ctx context.Context, rep *Report, if err != nil { return fmt.Errorf("list %s: %w", dir, err) } + names := entryNames(runs) for _, e := range runs { - if e.name == markerStagingBase || isFoldProbe(e.name) { + if e.name == markerStagingBase || isFoldProbe(e.name) || appleDouble(e.name, names) { continue } runID, ok := stagingRunID(e) @@ -105,26 +106,43 @@ func (h *destinationRoot) clearFinishedStaging(ctx context.Context, rep *Report, return nil } +// clearStagingRun removes a finished run's staged copies, then the run's +// staging directory once nothing else is left in it. An AppleDouble +// companion goes with its staged copy; one the system left behind is +// reported like anything else squirrel did not write. func (h *destinationRoot) clearStagingRun(ctx context.Context, rep *Report, tr transport, runDir string) error { entries, err := tr.List(ctx, runDir) if err != nil { return fmt.Errorf("list %s: %w", runDir, err) } foreign := false + names := entryNames(entries) for _, e := range entries { name := path.Join(runDir, e.name) - if e.kind != kindFile || !isStagingKey(e.name) { + switch { + case appleDouble(e.name, names): + case e.kind != kindFile || !isStagingKey(e.name): foreign = true h.warnForeignStaging(rep, name) - continue - } - if err := tr.Remove(ctx, name); err != nil { - return fmt.Errorf("remove finished staging %s: %w", name, err) + default: + if err := tr.Remove(ctx, name); err != nil { + return fmt.Errorf("remove finished staging %s: %w", name, err) + } } } if foreign { return nil } + left, err := tr.List(ctx, runDir) + if err != nil { + return fmt.Errorf("list %s: %w", runDir, err) + } + for _, e := range left { + h.warnForeignStaging(rep, path.Join(runDir, e.name)) + } + if len(left) > 0 { + return nil + } if err := tr.Remove(ctx, runDir); err != nil { return fmt.Errorf("remove finished staging %s: %w", runDir, err) } diff --git a/sync/mirror.go b/sync/mirror.go index aee6f9b..807a1f9 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -8,6 +8,7 @@ import ( "fmt" "io/fs" "path" + "slices" "strconv" "time" @@ -90,7 +91,7 @@ func (h *mirrorHandler) landed(ctx context.Context, runID int64) (bool, error) { } // rootEmpty reports whether the destination root holds no file beyond -// the volume markers, walking it until the first one. +// the volume markers. func (h *mirrorHandler) rootEmpty(ctx context.Context) (bool, error) { tr, err := h.root(ctx, 0) if err != nil { @@ -99,15 +100,20 @@ func (h *mirrorHandler) rootEmpty(ctx context.Context) (bool, error) { return treeEmpty(ctx, tr, ".") } -func treeEmpty(ctx context.Context, tr transport, dir string) (bool, error) { +// treeEmpty reports whether dir holds no file beyond volume markers, +// walking it until the first one. A directory skip names is not walked. +func treeEmpty(ctx context.Context, tr transport, dir string, skip ...string) (bool, error) { entries, err := tr.List(ctx, dir) if err != nil { return false, err } + names := entryNames(entries) for _, e := range entries { switch { + case appleDouble(e.name, names): + case e.kind == kindDir && slices.Contains(skip, path.Join(dir, e.name)): case e.kind == kindDir: - empty, err := treeEmpty(ctx, tr, path.Join(dir, e.name)) + empty, err := treeEmpty(ctx, tr, path.Join(dir, e.name), skip...) if err != nil || !empty { return false, err } @@ -119,6 +125,31 @@ func treeEmpty(ctx context.Context, tr transport, dir string) (bool, error) { return true, nil } +// firstPush refuses to start a volume's mirror over a volume directory +// that already holds files squirrel has no record of writing — a tree +// rclone wrote, another layout's, or a native mirror whose index is gone: +// a native mirror adopts no tree. A first push that crashed left records, +// so its retry passes. +func (h *mirrorHandler) firstPush(ctx context.Context, volumeID int64) error { + recorded, err := h.store.VolumeHasRemotePaths(ctx, h.dest.Name, volumeID) + if err != nil || recorded { + return err + } + tr, err := h.root(ctx, 0) + if err != nil { + return err + } + empty, err := treeEmpty(ctx, tr, h.vol.Name, path.Join(h.vol.Name, StagingDirName)) + if errors.Is(err, fs.ErrNotExist) || empty { + return nil + } + if err != nil { + return fmt.Errorf("destination %q: check whether %s/ is empty: %w", h.dest.Name, h.vol.Name, err) + } + return fmt.Errorf("destination %q: %s/ already holds files, but squirrel has no record of syncing volume %q there; a native mirror does not adopt a tree it did not record writing: if squirrel wrote it, recover this index from it with `squirrel recover --from %s`; otherwise point the destination at a fresh root, or empty %s/ apart from its %s: %w", + h.dest.Name, h.vol.Name, h.vol.Name, h.dest.Name, h.vol.Name, volmark.MarkerName, ErrRefused) +} + func (h *mirrorHandler) foreignHistory(runID int64) error { return fmt.Errorf("destination %q: the last successful sync (run %d) left no receipt at %s, so the root holds a tree this mirror did not write (by rclone, or another layout) or was emptied while squirrel still records uploads to it; a native mirror does not adopt an existing tree: point the destination at a fresh or emptied root, and after emptying it run `squirrel destination reset %s`: %w", h.dest.Name, runID, h.receiptName(runID), h.dest.Name, ErrRefused) } diff --git a/sync/mirror_first_push_test.go b/sync/mirror_first_push_test.go new file mode 100644 index 0000000..8e9e8e4 --- /dev/null +++ b/sync/mirror_first_push_test.go @@ -0,0 +1,155 @@ +package sync + +import ( + "errors" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/mbertschler/squirrel/store" + "github.com/mbertschler/squirrel/volmark" +) + +// TestMirrorRefusesATreeItHasNoRecordOf: a volume's first push to a native +// mirror refuses a volume directory that already holds files squirrel has +// no record of writing — a tree rclone wrote, or a native mirror whose +// index is gone — and a dry run refuses the same. Nothing moves. Another +// volume on the same root still starts fresh, and so does one whose +// directory holds only its marker and staging. +func TestMirrorRefusesATreeItHasNoRecordOf(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "alpha") + f.index(t) + if err := os.WriteFile(f.dest("a.txt"), []byte("written by another tool"), 0o644); err != nil { + t.Fatal(err) + } + for _, dryRun := range []bool{true, false} { + _, err := f.push(t, Options{DryRun: dryRun}) + if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "squirrel recover --from usb") { + t.Fatalf("push (dry run %v) = %v, want a refusal pointing at recover", dryRun, err) + } + } + if f.readDest(t, "a.txt") != "written by another tool" { + t.Fatal("the refused push moved the tree it found") + } + if _, err := os.Stat(f.dest(HistoryDirName)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the refused push displaced something: %v", err) + } + + if err := os.Remove(f.dest("a.txt")); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(f.dest(StagingDirName+"/run-99"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.dest(StagingDirName+"/run-99/"+stagingKey("a.txt")), []byte("partial"), 0o644); err != nil { + t.Fatal(err) + } + f.mustPush(t) + f.checkInvariants(t, nil) + }) + } +} + +// TestMirrorSecondVolumeStartsFreshBesideAnother: a volume's first push to +// a root that already holds another volume's mirror is no adoption: it +// starts fresh in its own directory. +func TestMirrorSecondVolumeStartsFreshBesideAnother(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + if err := os.MkdirAll(filepath.Join(f.dst, "docs", "2024"), 0o755); err != nil { + t.Fatal(err) + } + if err := volmark.Write(filepath.Join(f.dst, "docs"), volmark.Marker{Volume: "docs"}); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(f.dst, "docs", "2024", "invoice.pdf"), []byte("another volume's"), 0o644); err != nil { + t.Fatal(err) + } + f.mustPush(t) + f.checkInvariants(t, nil) +} + +// TestMirrorRetriesAFirstPushThatCrashed: a first push that died after +// committing some paths left records, so its retry is no adoption: it +// settles what the crash left and lands the rest. +func TestMirrorRetriesAFirstPushThatCrashed(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + f.write(t, "a.txt", "alpha") + f.write(t, "b.txt", "beta") + f.index(t) + commits := 0 + if rep, err := f.pushCrashing(t, func(c transportCall) bool { + if c.op == "rename" && strings.Contains(c.name, StagingDirName+"/run-") { + commits++ + } + return commits == 2 + }, crashAfter); !crashedOn(rep, err) { + t.Fatalf("crashing first push = %v, want the injected crash", err) + } + f.mustPush(t) + f.checkInvariants(t, nil) + }) + } +} + +// TestMirrorLeavesAppleDoubleCompanionsToTheSystem: the "._X" files macOS +// keeps beside X on a disk without extended attributes are X's, not +// foreign: one beside the marker leaves a root empty, one beside a +// finished run's staging is not reported, and an index-less restore leaves +// them out, counted once, while an orphan with no X beside it is restored +// like any file no receipt names. +func TestMirrorLeavesAppleDoubleCompanionsToTheSystem(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + f := setupMirrorFixtureOn(t, b) + if err := os.WriteFile(f.dest("._"+volmark.MarkerName), []byte("attributes"), 0o644); err != nil { + t.Fatal(err) + } + f.write(t, "a.txt", "alpha") + f.index(t) + first := f.mustPush(t) + run := "run-" + strconv.FormatInt(first.RunID, 10) + for _, rel := range []string{StagingDirName + "/._" + run, "._a.txt", "._" + HistoryDirName, "._orphan.txt"} { + if err := os.WriteFile(f.dest(rel), []byte("attributes"), 0o644); err != nil { + t.Fatal(err) + } + } + if err := os.MkdirAll(f.dest(HistoryDirName), 0o755); err != nil { + t.Fatal(err) + } + f.write(t, "b.txt", "beta") + f.index(t) + if rep := f.mustPush(t); warned(rep, "._"+run) { + t.Fatalf("warnings = %v, want the companion of finished staging left alone", rep.Warnings) + } + + to := t.TempDir() + fresh, err := store.Open(filepath.Join(t.TempDir(), "fresh.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { fresh.Close() }) + rep, err := Restore(t.Context(), fresh, nil, f.pair.Volume, f.pair.Destination, RestoreOptions{ToPath: to}) + if err != nil || rep.Status != store.RunStatusSuccess { + t.Fatalf("restore: status=%q err=%v", rep.Status, err) + } + if !warned(rep, "3 AppleDouble file(s)") || !warned(rep, "1 file(s) on \"usb\" are named in no receipt") { + t.Fatalf("warnings = %v, want three companions left out and the orphan restored unchecked", rep.Warnings) + } + for rel, want := range map[string]bool{"a.txt": true, "b.txt": true, "._orphan.txt": true, "._a.txt": false, "._" + HistoryDirName: false, "._" + volmark.MarkerName: false} { + if _, err := os.Stat(filepath.Join(to, rel)); (err == nil) != want { + t.Errorf("%s restored = %v, want %v", rel, err == nil, want) + } + } + }) + } +} diff --git a/sync/push.go b/sync/push.go index 068df36..70df788 100644 --- a/sync/push.go +++ b/sync/push.go @@ -40,6 +40,10 @@ type layout[O operations] interface { // foreignHistory is the refusal for a last success at runID that left // no landing evidence on a destination that is no fresh start. foreignHistory(runID int64) error + // firstPush gates a push of a volume that never synced to the + // destination, from watermark 0, on what the destination already + // holds: nil, or the refusal. + firstPush(ctx context.Context, volumeID int64) error // reconcile settles, once at push start, whatever an earlier push left // in flight on the destination, so translate reads settled records. reconcile(ctx context.Context, rep *Report, volumeID, runID int64) error @@ -188,7 +192,8 @@ func planPush[O operations](ctx context.Context, t pushTarget, l layout[O], volI // pushWatermark applies the watermark rule every layout shares: // -// 1. no successful sync of this (volume, destination): 0; +// 1. no successful sync of this (volume, destination): 0, once the +// layout's firstPush gate passes; // 2. the last success left its landing evidence: that run's id; // 3. the evidence is absent but the destination is a fresh start // (freshStart): 0; @@ -197,7 +202,7 @@ func planPush[O operations](ctx context.Context, t pushTarget, l layout[O], volI func pushWatermark[O operations](ctx context.Context, t pushTarget, l layout[O], volID int64) (int64, error) { last, err := t.store.LatestSuccessfulSyncRun(ctx, volID, t.dest.Name) if store.IsNotFound(err) { - return 0, nil + return 0, l.firstPush(ctx, volID) } if err != nil { return 0, fmt.Errorf("lookup last successful sync of %s: %w", t.dest.Name, err) diff --git a/sync/restore_mirror.go b/sync/restore_mirror.go index a5cbf28..ef17eb8 100644 --- a/sync/restore_mirror.go +++ b/sync/restore_mirror.go @@ -95,10 +95,14 @@ func (mr *mirrorRestore) restoreWalked(ctx context.Context, rep *Report) error { if err != nil { return err } - unchecked := 0 - err = mr.walk(ctx, rep, "", func(rel string, e entry) { + unchecked, companions := 0, 0 + err = mr.walk(ctx, rep, "", func(rel string, e entry, companion bool) { want, ok := receipts[rel] - if !ok { + switch { + case !ok && companion: + companions++ + return + case !ok: unchecked++ } mr.restoreOne(ctx, rep, rel, e.size, want, e.mtime) @@ -106,6 +110,9 @@ func (mr *mirrorRestore) restoreWalked(ctx context.Context, rep *Report) error { if unchecked > 0 { rep.Warnings = append(rep.Warnings, fmt.Sprintf("%d file(s) on %q are named in no receipt, so their bytes could not be checked; they are restored unchecked", unchecked, mr.dest.Name)) } + if companions > 0 { + rep.Warnings = append(rep.Warnings, fmt.Sprintf("%d AppleDouble file(s) (._*) on %q, where macOS kept the extended attributes of the file beside each, are named in no receipt and not restored", companions, mr.dest.Name)) + } return err } @@ -138,14 +145,16 @@ func (mr *mirrorRestore) restoreOne(ctx context.Context, rep *Report, rel string } // walk visits every file of the mirrored tree under dir, leaving out -// squirrel's reserved entries at the volume root. An entry that is neither -// a file nor a directory is reported and not restored. -func (mr *mirrorRestore) walk(ctx context.Context, rep *Report, dir string, visit func(rel string, e entry)) error { +// squirrel's reserved entries at the volume root, and tells visit whether +// the file is the AppleDouble companion of an entry beside it. An entry +// that is neither a file nor a directory is reported and not restored. +func (mr *mirrorRestore) walk(ctx context.Context, rep *Report, dir string, visit func(rel string, e entry, companion bool)) error { name := path.Join(mr.vol.Name, dir) entries, err := mr.tr.List(ctx, name) if err != nil { return fmt.Errorf("list %s on %q: %w", name, mr.dest.Name, err) } + names := entryNames(entries) for _, e := range entries { rel := path.Join(dir, e.name) switch { @@ -157,7 +166,7 @@ func (mr *mirrorRestore) walk(ctx context.Context, rep *Report, dir string, visi return err } case e.kind == kindFile: - visit(rel, e) + visit(rel, e, appleDouble(e.name, names)) default: rep.Warnings = append(rep.Warnings, fmt.Sprintf("%s on %q is neither a file nor a directory; it is not restored", rel, mr.dest.Name)) } From 3b7f270f15738966600f5f29345a4199f7195c33 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 05:39:14 +0200 Subject: [PATCH 47/61] sync, config: tell an unplugged disk from a new one, and name the local mirror as a gate A native destination that lost its root or its marker told the operator to re-run with --init, even when the volume had synced there before; on an unplugged disk --init would bootstrap an empty destination on the mountpoint instead. A volume that synced there before is now refused as a disk that is most likely not mounted or a root that moved, and --init is named only for a new, empty destination. Verify, restore and recover over a missing local root say the same instead of a raw open error. The refusal of an offload_requires target that can never gate listed every gating shape but the local mirror; it names it now. --- config/config.go | 2 +- sync/destination_marker.go | 28 ++++++++++++++++++++++++---- sync/handler.go | 4 ++++ sync/mirror_first_push_test.go | 23 +++++++++++++++++++++++ 4 files changed, 52 insertions(+), 5 deletions(-) diff --git a/config/config.go b/config/config.go index 2aedbb7..1677acf 100644 --- a/config/config.go +++ b/config/config.go @@ -531,7 +531,7 @@ func rejectUnsatisfiableOffloadRequires(names []string, dests map[string]*Destin continue } if capable, reason := d.CanEverGateOffload(); !capable { - return fmt.Errorf("offload_requires names %q, which can never satisfy the durability gate (%s); require a content-addressed or packed destination, a kopia repository, or a peer node instead", n, reason) + return fmt.Errorf("offload_requires names %q, which can never satisfy the durability gate (%s); require a local mirror, a content-addressed or packed destination, a kopia repository, or a peer node instead", n, reason) } } return nil diff --git a/sync/destination_marker.go b/sync/destination_marker.go index 158b818..ad99617 100644 --- a/sync/destination_marker.go +++ b/sync/destination_marker.go @@ -25,7 +25,7 @@ const maxMarkerBytes = 64 << 10 // so a first push can land on an empty disk, and refused like a missing // marker otherwise. func (h *destinationRoot) ensureMarker(ctx context.Context, init bool) error { - if err := h.ensureLocalRoot(init); err != nil { + if err := h.ensureLocalRoot(ctx, init); err != nil { return err } tr, err := h.guarded(ctx, nameGuard{volumeDir: h.volumeDir, bootstrap: init}) @@ -40,12 +40,12 @@ func (h *destinationRoot) ensureMarker(ctx context.Context, init bool) error { case !errors.Is(err, fs.ErrNotExist): return fmt.Errorf("destination %q: read %s: %w", h.dest.Name, name, err) case !init: - return fmt.Errorf("destination %q has no %s at %s — re-run with --init to bootstrap (refusing in case the root is a typo or the disk is not mounted): %w", h.dest.Name, volmark.MarkerName, h.where(name), ErrRefused) + return fmt.Errorf("destination %q has no %s at %s — %s: %w", h.dest.Name, volmark.MarkerName, h.where(name), h.bootstrapHint(ctx), ErrRefused) } return h.writeMarker(ctx, tr, name) } -func (h *destinationRoot) ensureLocalRoot(init bool) error { +func (h *destinationRoot) ensureLocalRoot(ctx context.Context, init bool) error { if h.dest.Type != "local" { return nil } @@ -59,7 +59,27 @@ func (h *destinationRoot) ensureLocalRoot(init bool) error { } return nil } - return fmt.Errorf("destination %q has no root at %s — re-run with --init to create it (refusing in case the disk is not mounted): %w", h.dest.Name, h.dest.Root, ErrRefused) + return fmt.Errorf("destination %q has no root at %s — %s: %w", h.dest.Name, h.dest.Root, h.bootstrapHint(ctx), ErrRefused) +} + +// bootstrapHint is what a refusal over a missing root or marker asks for. +// A volume that synced to the destination before points at an unmounted +// disk or a moved root, not at --init, which would bootstrap a new, empty +// destination in its place. +func (h *destinationRoot) bootstrapHint(ctx context.Context) string { + if h.volumeSyncedBefore(ctx) { + return fmt.Sprintf("volume %q has synced to it before, so the disk is most likely not mounted or the root moved; mount it and sync again (--init is only for a new, empty destination)", h.volumeDir) + } + return "re-run with --init to bootstrap (refusing in case the root is a typo or the disk is not mounted)" +} + +func (h *destinationRoot) volumeSyncedBefore(ctx context.Context) bool { + v, err := h.store.GetVolumeByName(ctx, h.volumeDir) + if err != nil { + return false + } + _, err = h.store.LatestSuccessfulSyncRun(ctx, v.ID, h.dest.Name) + return err == nil } func (h *destinationRoot) checkMarker(name string, data []byte) error { diff --git a/sync/handler.go b/sync/handler.go index 13b89c0..62ce018 100644 --- a/sync/handler.go +++ b/sync/handler.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "io/fs" "path/filepath" "github.com/mbertschler/squirrel/config" @@ -175,6 +176,9 @@ func openDestinationTransport(ctx context.Context, dest *config.Destination) (tr // bounded by progress. func openReadOnly(ctx context.Context, dest *config.Destination) (transport, error) { raw, err := openDestinationTransport(ctx, dest) + if dest.Type == "local" && errors.Is(err, fs.ErrNotExist) { + return nil, fmt.Errorf("destination %q has no root at %s — the disk may not be mounted, or the root is wrong: %w", dest.Name, dest.Root, err) + } if err != nil { return nil, err } diff --git a/sync/mirror_first_push_test.go b/sync/mirror_first_push_test.go index 8e9e8e4..70af042 100644 --- a/sync/mirror_first_push_test.go +++ b/sync/mirror_first_push_test.go @@ -153,3 +153,26 @@ func TestMirrorLeavesAppleDoubleCompanionsToTheSystem(t *testing.T) { }) } } + +// TestMarkerRefusalOfADestinationSyncedBefore: a destination the volume +// synced to before that has lost its root or its marker is refused as a +// disk that is most likely not mounted; the refusal does not steer toward +// --init, which would bootstrap an empty destination in its place. +func TestMarkerRefusalOfADestinationSyncedBefore(t *testing.T) { + f := setupMirrorFixture(t) + f.write(t, "a.txt", "alpha") + f.index(t) + f.mustPush(t) + for _, gone := range []string{f.dest(volmark.MarkerName), f.dst} { + if err := os.RemoveAll(gone); err != nil { + t.Fatal(err) + } + _, err := f.push(t, Options{}) + if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "most likely not mounted") || strings.Contains(err.Error(), "re-run with --init") { + t.Fatalf("push with %s gone = %v, want a refusal naming an unmounted disk", gone, err) + } + } + if _, err := VerifyRemote(t.Context(), f.store, nil, f.pair.Destination); err == nil || !strings.Contains(err.Error(), "may not be mounted") { + t.Fatalf("verify with the root gone = %v, want it named as a disk that may not be mounted", err) + } +} From 3632164037ba33f0481fbf904f051a5cb10e6c78 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 05:41:14 +0200 Subject: [PATCH 48/61] docs, design: say which destinations squirrel writes itself, and what usb no longer covers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The destinations page, the configuration reference and the README still said rclone writes local and sftp destinations and checks their host keys; squirrel writes every local destination and every sftp one without crypt, in any layout, and always checks the key. The content-addressed and packed pages said --dry-run is not supported on the push; it previews it. reference-setup.md: the usb arrow is native now, and the kopia leg says what the mirrors no longer cover — a native mirror plans from the index, so a file the indexer misses never reaches usb, and only cloudbox keeps rclone's own walk until crypt moves. --- README.md | 10 +++---- design/reference-setup.md | 16 +++++++++- .../docs/configuration/destinations.md | 30 +++++++++++-------- .../content/docs/layouts/content-addressed.md | 3 +- docs/src/content/docs/layouts/packed.md | 3 +- .../content/docs/reference/configuration.md | 26 ++++++++-------- 6 files changed, 55 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index ac93fdf..d0bf45f 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Squirrel works the same at any size: one machine backing up to one destination, ## Under the hood -Squirrel indexes a local file tree by BLAKE3 content hash and syncs it to one or more remote destinations (NAS, S3, B2, GCS, SFTP, …) via rclone. Peer syncs are BLAKE3-verified end-to-end; every other destination is checked by the strongest comparison it supports, and the index records which one ran. Destinations are append-only: an overwrite at the destination moves the prior bytes into `.squirrel-history/run-/`, never deletes them. +Squirrel indexes a local file tree by BLAKE3 content hash and syncs it to one or more destinations (a local disk, a NAS, SFTP, S3, B2, GCS, …): it writes local disks and plain SFTP servers itself, and reaches buckets and encrypted destinations through rclone. Peer syncs are BLAKE3-verified end-to-end; every other destination is checked by the strongest comparison it supports, and the index records which one ran. Destinations are append-only: an overwrite at the destination moves the prior bytes into `.squirrel-history/run-/`, never deletes them. ## Principle @@ -49,7 +49,7 @@ go install github.com/mbertschler/squirrel/cmd/squirrel@latest A source build reports its version as `0.0.0-dev` — the version is only stamped into the released binaries at build time. -You will also need [rclone](https://rclone.org) ≥ 1.71 on `PATH` to sync or restore against a **bucket destination** (1.71 added the sftp `hashes` option that [`hash_algo`](#offsite-verification-squirrel-verify) sets). Syncing to a **peer node** does not use it — those bytes stream over the peer's own sync API — so a machine whose only targets are peers needs no rclone at all: +You will also need [rclone](https://rclone.org) ≥ 1.71 on `PATH` to sync or restore against a **bucket destination** (`s3`, `b2`, `gcs`) or an **encrypted** one (1.71 added the sftp `hashes` option that [`hash_algo`](#offsite-verification-squirrel-verify) sets there). A `local` disk and a plain `sftp` server need no rclone — squirrel writes them itself — and neither does a **peer node**, whose bytes stream over the peer's own sync API, so a machine whose only targets are those needs no rclone at all: ``` brew install rclone # macOS @@ -88,11 +88,11 @@ bucket = "squirrel-backup" root = "/squirrel" ``` -Supported destination types: `local`, `sftp`, `s3`, `b2`, `gcs` (rclone-backed), and `kopia` (see [kopia destinations](#kopia-destinations)). Secrets accept either a literal string or an inline `{ env = "VAR_NAME" }` table that is resolved at load time. Unknown fields, missing required fields, and unset env vars are rejected immediately — squirrel will not invoke rclone with a misconfigured destination. +Supported destination types: `local`, `sftp`, `s3`, `b2`, `gcs`, and `kopia` (see [kopia destinations](#kopia-destinations)). squirrel writes `local` and `sftp` destinations itself, and rclone writes `s3`, `b2`, `gcs` and every encrypted destination. Secrets accept either a literal string or an inline `{ env = "VAR_NAME" }` table that is resolved at load time. Unknown fields, missing required fields, and unset env vars are rejected immediately — squirrel will not start a transfer to a misconfigured destination. Some optional params are specific to one backend type and rejected on the others (as an unknown field): -- **`sftp` host-key validation** — `known_hosts_file` points rclone at a known_hosts file so it validates the server's host key before transferring; `host_key_algorithms` is rclone's space-separated list pinning the accepted host-key algorithms. Both map to the rclone sftp options of the same name. **Without `known_hosts_file`, rclone does not validate the server's host key** and will connect to whatever host answers — set it (recommended) so a redirected or impersonated server is rejected. +- **`sftp` host-key validation** — `known_hosts_file` names a known_hosts file holding the server's host key; `host_key_algorithms` is a space-separated list pinning the accepted host-key algorithms. squirrel checks the key of every sftp destination it writes — every one without `crypt` — against `known_hosts_file`, or `~/.ssh/known_hosts` when unset, and refuses a server the file does not hold. On an encrypted sftp destination both map to the rclone sftp options of the same name, and **without `known_hosts_file`, rclone does not validate the server's host key** and will connect to whatever host answers — set it so a redirected or impersonated server is rejected. ```toml [destinations.nas] @@ -114,7 +114,7 @@ Some optional params are specific to one backend type and rejected on the others storage_class = "" # archive tiers cost less to store, more to read ``` -Squirrel writes its own `rclone.conf` next to the config (`~/.squirrel/rclone.conf`, mode 0600) on every sync invocation. You do not run `rclone config` and you should not edit `rclone.conf` by hand. +For the destinations rclone writes, squirrel writes its own `rclone.conf` next to the config (`~/.squirrel/rclone.conf`, mode 0600) on every sync invocation. You do not run `rclone config` and you should not edit `rclone.conf` by hand. ### Encrypted destinations diff --git a/design/reference-setup.md b/design/reference-setup.md index e24ccf2..d38dc18 100644 --- a/design/reference-setup.md +++ b/design/reference-setup.md @@ -53,9 +53,13 @@ run programs, so it is a dumb **destination**; the NAS can, so it is a ▲ │ └──── durability evidence flows back out to the edges ────┘ - homepc ──rclone──▶ usb (local destination, .squirrel-volume marker) + homepc ──native──▶ usb (local mirror, .squirrel-volume marker) ``` +`native` is squirrel's own transport ([native-mirror.md](native-mirror.md)): +every `local` destination and every `sftp` one without crypt, in any layout. +`rclone` carries the encrypted destinations and the buckets. + Initiation direction follows availability: the intermittently-awake machines (laptop, homepc) initiate toward the always-on nas; the nas initiates toward the always-on htpc. A sleeping laptop can't be dialed, @@ -114,6 +118,16 @@ the same disk, with its own end-to-end verification (`snapshot verify`) on every sync, recorded in squirrel's runs table like any other destination. +For usb the shared walker is literal: a native mirror plans from the +index, as the content layouts always did, so a file the indexer misses +never reaches it. An rclone mirror walked the source itself, which let a missed file +still reach it; of the household's copies only cloudbox keeps that until +crypt moves to the native transport, and then none does. What an +independent walk covered is kopia-mirror's job alone, and it covers only +photos and docs. A periodic check comparing a plain directory walk with +the index is the candidate that would give every layout some of that +back (native-mirror.md, decision 7). + Because its purpose is *implementation* redundancy, not geo redundancy (cloudbox and s3archive cover that twice), living on the nas's second disk group is fine: independent, cheap, fast to restore from. It is diff --git a/docs/src/content/docs/configuration/destinations.md b/docs/src/content/docs/configuration/destinations.md index 99addae..dd405ae 100644 --- a/docs/src/content/docs/configuration/destinations.md +++ b/docs/src/content/docs/configuration/destinations.md @@ -1,6 +1,6 @@ --- title: Destinations & secrets -description: Declare rclone-backed and kopia destinations, resolve secrets from environment variables, and let squirrel own rclone.conf. +description: Declare local, sftp, bucket and kopia destinations, resolve secrets from environment variables, and let squirrel own rclone.conf. --- A **destination** is a named remote (or local directory) that volumes sync to. @@ -27,10 +27,10 @@ root = "/squirrel" ## Supported types -| Type | Backing | Notes | +| Type | Written by | Notes | |---|---|---| -| `local` | rclone | A local directory; requires a `.squirrel-volume` marker (see [first use](/squirrel/guides/syncing/)). | -| `sftp` | rclone | Add `known_hosts_file` to validate the server host key. | +| `local` | squirrel | A local directory; requires a `.squirrel-volume` marker (see [first use](/squirrel/guides/syncing/)). | +| `sftp` | squirrel; rclone with `crypt` | The server's host key must be in `known_hosts_file` or `~/.ssh/known_hosts`. | | `s3` | rclone | Set `provider`, `region`, `bucket`; optional `storage_class`. | | `b2` | rclone | Backblaze B2. | | `gcs` | rclone | Google Cloud Storage. | @@ -46,12 +46,13 @@ password = { env = "NAS_PASSWORD" } ``` An unset environment variable is a hard error at config load — squirrel will not -invoke rclone with a misconfigured destination. +start a transfer to a misconfigured destination. :::caution[Never hand-edit rclone.conf] -Squirrel writes its own `rclone.conf` next to the config file -(`~/.squirrel/rclone.conf`, mode `0600`) on every sync invocation. You do not -run `rclone config` and you should not edit `rclone.conf` by hand. +For the destinations rclone writes, squirrel writes its own `rclone.conf` next +to the config file (`~/.squirrel/rclone.conf`, mode `0600`) on every sync +invocation. You do not run `rclone config` and you should not edit `rclone.conf` +by hand. ::: ## Backend-specific parameters @@ -61,9 +62,13 @@ field) on the others. ### SFTP host-key validation -Without `known_hosts_file`, **rclone does not validate the server's host key** -and will connect to whatever host answers. Set it so a redirected or -impersonated server is rejected. +squirrel checks the host key of every sftp destination it writes — every one +without `crypt` — against `known_hosts_file`, or `~/.ssh/known_hosts` when that +is unset, and refuses a server the file does not hold; the refusal prints the +line that trusts it. On an encrypted sftp destination rclone checks it, and +**without `known_hosts_file` rclone does not validate the server's host key**: +it connects to whatever host answers. Set it so a redirected or impersonated +server is rejected. ```toml [destinations.nas] @@ -76,7 +81,8 @@ known_hosts_file = "~/.ssh/known_hosts" # validate the server host key ( host_key_algorithms = "ssh-ed25519 ssh-rsa" # optional: pin accepted host-key algorithms ``` -Both map to the rclone sftp options of the same name. +On an encrypted destination both map to the rclone sftp options of the same +name. ### S3 storage class diff --git a/docs/src/content/docs/layouts/content-addressed.md b/docs/src/content/docs/layouts/content-addressed.md index 198fb12..9b19908 100644 --- a/docs/src/content/docs/layouts/content-addressed.md +++ b/docs/src/content/docs/layouts/content-addressed.md @@ -95,7 +95,8 @@ what's missing. own, or rclone and its `crypt` overlay — and re-hashes it before writing. When the local index itself is lost, the format is deliberately simple enough to [recover without squirrel](/squirrel/reference/formats/#disaster-recovery-without-squirrel). -- **`--dry-run` is not supported yet on the push** (it previews restore). +- **`--dry-run` previews the push**: the objects it would upload and their + bytes, written nowhere. ## Offsite verification diff --git a/docs/src/content/docs/layouts/packed.md b/docs/src/content/docs/layouts/packed.md index 9d685a4..e5a4b48 100644 --- a/docs/src/content/docs/layouts/packed.md +++ b/docs/src/content/docs/layouts/packed.md @@ -82,7 +82,8 @@ Properties match the content-addressed layout: - Verification is presence+size (recorded shallow). - The layout is chosen at first use and refuses to run against a differently-shaped history. -- `--dry-run` is not supported yet on the push. +- `--dry-run` previews the push: the objects and pack members it would upload, + written nowhere. - [`squirrel restore`](/squirrel/guides/restore/) **restores the layout**: it resolves each present path to its content in the local index, fetches each pack once to serve all its members, and re-hashes every extracted member diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md index 758a1ab..e9adeb0 100644 --- a/docs/src/content/docs/reference/configuration.md +++ b/docs/src/content/docs/reference/configuration.md @@ -70,19 +70,19 @@ See [Hooks](/squirrel/guides/hooks/). With neither `password` nor `key_file` set, squirrel logs in with the keys of the running ssh-agent (`SSH_AUTH_SOCK`). -A mirror without [crypt](/squirrel/layouts/encrypted/) is a -[native mirror](/squirrel/layouts/mirror/#how-a-mirror-is-written): squirrel -connects to the server itself, and **always checks its host key**, against -`known_hosts_file` or `~/.ssh/known_hosts` when that is unset. A server whose key -the file does not hold is refused; the message gives the key's fingerprint and -the known_hosts line that trusts it, to add once you have confirmed it. A key -that differs from the pinned one is refused too. Unless `host_key_algorithms` is -set, squirrel asks the server for the key types the file holds for it. `checkers` -and `hash_algo` tune rclone, so a native mirror rejects them. - -Every other sftp destination — an encrypted mirror, or the content-addressed and -packed layouts — is written by rclone, which checks the host key against -`known_hosts_file` and accepts whatever key the server presents when it is unset. +An sftp destination without [crypt](/squirrel/layouts/encrypted/), in any +layout, is written by squirrel itself: it connects to the server, and **always +checks its host key**, against `known_hosts_file` or `~/.ssh/known_hosts` when +that is unset. A server whose key the file does not hold is refused; the message +gives the key's fingerprint and the known_hosts line that trusts it, to add once +you have confirmed it. A key that differs from the pinned one is refused too. +Unless `host_key_algorithms` is set, squirrel asks the server for the key types +the file holds for it. `checkers` tunes rclone, so these destinations reject it, +and a mirror rejects `hash_algo`, since it runs no command on the server. + +An encrypted sftp destination is written by rclone, which checks the host key +against `known_hosts_file` and accepts whatever key the server presents when it +is unset. ### `s3` From e7f57a87a4ca00cc074eefacc27b9cfdca11f367 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 05:42:18 +0200 Subject: [PATCH 49/61] design: set native-mirror.md's status, map every required case to its tests, and record the benchmark MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The status is implemented in #217. "What the tests must cover" names the tests behind each case. Section 8 records the testbed benchmark against rclone: native pushes that write are several times slower — local disks pay for syncing every file and reading it back, sftp for about 30 sequential round trips per path — and unchanged pushes are faster. What to change is a new open question. --- design/README.md | 6 ++-- design/native-mirror.md | 75 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 75 insertions(+), 6 deletions(-) diff --git a/design/README.md b/design/README.md index 3eca205..d3840c7 100644 --- a/design/README.md +++ b/design/README.md @@ -14,9 +14,9 @@ each time. every supported destination type in play. - [`testbed.md`](testbed.md) — how the reference setup is simulated on one development machine with real commands and no containers. -- [`native-mirror.md`](native-mirror.md) — *proposed*: one planner shared - by every layout, a small transport, and the mirror layout on `local` and - `sftp` without rclone. +- [`native-mirror.md`](native-mirror.md) — *implemented in #217*: one + planner shared by every layout, a small transport, and every `local` and + plain `sftp` destination written without rclone. ## How to use this folder diff --git a/design/native-mirror.md b/design/native-mirror.md index a780094..93f27b6 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -1,6 +1,6 @@ # Native mirror layout: one planner, three layouts, a small transport -*Proposed, not adopted.* This is step 2 of replacing rclone with squirrel's own +*Implemented in #217.* This is step 2 of replacing rclone with squirrel's own transports. Peer sync dropped rclone in #210. #211 made the mirror's evidence honest. Step 3 is S3 for the packed and content-addressed layouts. @@ -614,6 +614,25 @@ The suite runs against the local transport. It runs against the sftp transport through an in-process `pkg/sftp` server. And it runs against both wrapped in the fault injector. +Where each case lives: + +| Case | Tests | +|---|---| +| Crash at every call, then a clean push | `TestMirrorCrashAtEveryTransportCall`, `TestNativeContentCrashAtEveryTransportCall` (`sync/crash_every_call_test.go`) | +| Random histories against a model | `TestMirrorModel` (`sync/mirror_model_test.go`) | +| File↔directory swaps | `TestMirrorFileDirectorySwap`, `TestMirrorNestedFileDirectorySwaps` | +| Unrecorded and changed entries at a target | `TestMirrorWriteDisplacesWhatThePathHolds`, `TestMirrorRecordChangedBehindSquirrelsBack` | +| A tree squirrel has no record of | `TestMirrorWatermarkRule`, `TestMirrorRefusesATreeItHasNoRecordOf` | +| Foreign entries in staging | `TestMirrorForeignStagingIsLeftAlone`, `TestMirrorLeavesForeignStagingAlone` | +| Symlinks at a target, along its parents, in place of a reserved directory, at an artifact's name | `TestMirrorNeverFollowsASymlinkAtATarget`, `TestMirrorNeverFollowsASymlinkedReservedDirectory`, `TestNativeContentNeverFollowsASymlinkAtAnArtifactName` | +| Names a destination folds | `TestMirrorProbesHowTheDestinationComparesNames`, `TestMirrorRefusesNamesTheDestinationCannotTellApart`, `TestMirrorRefusesTheSecondOfTwoNewNames`, `TestMirrorFollowsARenameThatChangesOnlyCase`, `TestMirrorFoldingMovesAFileOutOfADirectorysWay` (`sync/mirror_fold_test.go`, with a transport that folds names on any disk) | +| Disk full, unwritable history, drift while streaming | `TestMirrorDiskFullMidWrite`, `TestMirrorHistoryUnwritable`, `TestMirrorSourceDriftWhileStreaming`, `TestNativeContentSourceDriftWhileStreaming` (`sync/mirror_hostile_test.go`) | +| Rename onto an existing target | `RenameNeverReplaces` in the contract suite, and `TestSFTPServersRenameOverAnExistingName` | + +`checkInvariants` (`sync/mirror_test.go`) asserts the three invariants; +invariant 1 alone (`checkRecordsVouch`) also runs right after every +injected crash, since it holds at every point of a push. + ## 5. Evidence and verification (reverses #216) Until this step, a native mirror push advances its vector as `presence+size`. @@ -780,7 +799,8 @@ addressed local destinations by path; that restriction is gone. Concurrency is fixed. On sftp each file goes out as concurrent write requests (`pkg/sftp`'s default of 64 in flight); paths are written one at a time on both transports. The testbed benchmark against rclone (section 8) - decides whether several paths in flight are worth their bookkeeping. + was to decide whether several paths in flight are worth their bookkeeping; + it says they are, over sftp at any latency (open question 2). ## 8. What we give up @@ -794,7 +814,46 @@ addressed local destinations by path; that restriction is gone. - Decision 7 keeps a cheap mitigation as a candidate. - **Rclone's tuning and backend know-how.** Rclone brings parallel transfers, multi-threaded streams, and years of workarounds for sftp servers. The - switch should wait for a benchmark on the testbed against rclone. + switch should wait for a benchmark on the testbed against rclone: it ran on + 2026-09-24 (below), and native pushes that write are several times slower. + +### The benchmark + +One macOS laptop (arm64), `main`'s binary (rclone mirrors) against this +branch's (native mirrors), each on a fresh index and a fresh destination: + +- `usb`: an exFAT disk image, so rclone can't clone files on APFS; +- `box`: `rclone serve sftp` on loopback; +- `wan`: the same server behind a proxy that delays every chunk 10 ms each + way (20 ms round trip). + +`pics` is 4540 files, 724 MB (photo years and small documents, from +`test/testbed/gendata`); `trip` is 608 files, 114 MB. "Changed" rewrites 150 +files and adds 150 (30 and 30 on `trip`). Wall time in seconds: + +| Push | usb (pics) rclone | native | box (pics) rclone | native | wan (trip) rclone | native | +|---|---|---|---|---|---|---| +| first | 12.6 | 115.8 | 3.7 | 13.7 | 45.4 | 431.9 | +| unchanged | 0.63 | 0.13 | 2.11 | 0.09 | 7.72 | 1.80 | +| changed | 1.51 | 9.96 | 2.41 | 1.46 | 8.85 | 51.06 | + +A native first push to APFS on the internal disk took 86.4 s. + +- **Local disks pay for durability.** Every written file is synced to stable + storage — on macOS a full flush of the drive's cache — read back past the + cache, and after its rename both parent directories are synced; rclone + syncs nothing. That is about 18 ms per file on the internal SSD, and 25 ms + on the exFAT image. +- **sftp pays in round trips.** A written path costs about 30 sequential + requests: `Put` checks its target and each parent with `Lstat`, then + creates, writes, closes and sets the mtime; the staged copy, the path's + parents and the path are each looked up again, and the rename checks both + parent chains. At a 20 ms round trip that is about 0.7 s per path, against + rclone's four transfers in flight. +- **Unchanged pushes are faster natively** everywhere: they read squirrel's + records instead of listing both trees. + +What to change is open question 2. - **A new dependency:** `github.com/pkg/sftp`. ## 9. Order of work @@ -855,3 +914,13 @@ Open: 1. **Crypt byte-compatibility with rclone.** This blocks cloudbox only, and is to be discussed separately. +2. **Throughput of pushes that write** (section 8). Candidates, each with its + own cost: several paths in flight, which multiplies sftp throughput by + the concurrency and overlaps local syncs, at the price of concurrent + bookkeeping in the writer; checking each parent chain once per push + instead of once per call, which halves the sftp round trips but trusts a + directory for the rest of the push; syncing a batch of staged files + together before their renames, which keeps every copy durable before it + is committed but costs a second pass over staging. Whether the branch + switches `local` and plain `sftp` destinations before any of them lands + is the maintainer's call. From 333d10e7af123233f83d7d0d60b4781d0e6f6626 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 05:42:57 +0200 Subject: [PATCH 50/61] design: log the native mirror walk's findings F36 to F39 are the walk's findings this branch fixed; F40, the throughput of pushes that write, stays open with the design's open question 2. --- design/friction-log.md | 49 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/design/friction-log.md b/design/friction-log.md index df7f2c1..f5681a4 100644 --- a/design/friction-log.md +++ b/design/friction-log.md @@ -568,6 +568,55 @@ must configure `[agent] listen` + auth token anyway, because the scheduler lives inside the agent. A listener that exists to be unused is config noise and attack surface. +## Native mirror walk (2026-09-24, #217) + +A second, shorter walk: the native mirror's lifecycle on `homepc`'s seat — +bootstrap, steady state, changes, verify, an unplugged disk, restore with +and without the index, recover, the offload gate — against an exFAT disk +image on macOS and a plain sftp destination on `rclone serve sftp`, plus a +benchmark against `main`'s rclone mirrors +([native-mirror.md](native-mirror.md), section 8). The bootstrap refusals, +the host-key refusal (it prints the known_hosts line to add), repairs of a +copy verify found gone, and a rename that changed only case all behaved. + +**F36 · S1 — ~~a fresh index took over a tree it never wrote.~~ (fixed in +#217)** With no sync of the volume in the index, a push to a native mirror +started from nothing over whatever the volume's directory held: pointed at +a tree rclone wrote, it moved all 4690 files into history and wrote them +again, doubling what the disk holds, where the design refuses existing +trees. A volume's first push now refuses a directory that holds files +squirrel has no record of writing, and points at `squirrel recover --from` +for a native mirror whose index is gone. + +**F37 · S2 — ~~macOS's `._` files read as foreign.~~ (fixed in #217)** On +exFAT, macOS keeps every file's extended attributes in a `._` +companion. Every push warned about the last run's `._run-` in staging, +and an index-less restore brought back 619 `._` files as unchecked, +including those of `.squirrel-history` and the marker. A `._X` beside `X` +is now `X`'s. + +**F38 · S2 — ~~an unplugged disk was told to re-run with `--init`.~~ (fixed +in #217)** The refusal for a missing root or marker led with `--init` even +for a disk the volume had synced to, where `--init` would bootstrap an empty +destination on the bare mountpoint. It now says the disk is most likely not +mounted; `squirrel verify` on a missing root says the same instead of a raw +open error. + +**F39 · S4 — ~~the unsatisfiable-gate refusal forgot the local mirror.~~ +(fixed in #217)** Rejecting an sftp mirror in `offload_requires` listed every +target that can gate but the local mirror, which the same message's reason +names. + +**F40 · S1 — native pushes that write are several times slower than +rclone.** A first push took 116 s against rclone's 13 s on the exFAT image, +and 432 s against 45 s over sftp at a 20 ms round trip; unchanged pushes are +faster. Open: native-mirror.md, open question 2. + +Observed, by design: a copy corrupted in place on the local mirror, size and +mtime kept, passed three verify passes because each re-reads only a tenth of +the bytes; the restore's BLAKE3 refused it. Until its turn in the rotation, +the offload gate would count it. + ## Summary and priority *The verdict below is the walk's own, kept as written that night; the From 1bc4ff740052c536108364a7b9ce803debd8d5e0 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 05:43:07 +0200 Subject: [PATCH 51/61] design: the corrupted copy passed two verify passes, not three --- design/friction-log.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/friction-log.md b/design/friction-log.md index f5681a4..d35578b 100644 --- a/design/friction-log.md +++ b/design/friction-log.md @@ -613,7 +613,7 @@ and 432 s against 45 s over sftp at a 20 ms round trip; unchanged pushes are faster. Open: native-mirror.md, open question 2. Observed, by design: a copy corrupted in place on the local mirror, size and -mtime kept, passed three verify passes because each re-reads only a tenth of +mtime kept, passed two verify passes because each re-reads only a tenth of the bytes; the restore's BLAKE3 refused it. Until its turn in the rotation, the offload gate would count it. From c9a0db064bb95cbd260be7295c76cb7a07c60ffa Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 05:44:37 +0200 Subject: [PATCH 52/61] sync: fail the push when the fold plan cannot tell whether a path is present A store error while the plan checked whether an old spelling's path was still present skipped its displacement silently, so the write that followed would move the old version aside as unrecorded bytes and leave its row live. The error now fails the push. Two comments read better. --- sync/mirror.go | 2 +- sync/mirror_fold.go | 13 ++++++++++--- sync/mirror_write.go | 4 ++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/sync/mirror.go b/sync/mirror.go index 807a1f9..5a36dd8 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -101,7 +101,7 @@ func (h *mirrorHandler) rootEmpty(ctx context.Context) (bool, error) { } // treeEmpty reports whether dir holds no file beyond volume markers, -// walking it until the first one. A directory skip names is not walked. +// walking it until the first one. The directories in skip are not walked. func treeEmpty(ctx context.Context, tr transport, dir string, skip ...string) (bool, error) { entries, err := tr.List(ctx, dir) if err != nil { diff --git a/sync/mirror_fold.go b/sync/mirror_fold.go index 76fe941..2d4a3d0 100644 --- a/sync/mirror_fold.go +++ b/sync/mirror_fold.go @@ -162,7 +162,9 @@ func (w *mirrorWriter) planFolding(ctx context.Context, ops *mirrorOps) (foldPla plan.refuse(entities) } for _, key := range candidates { - plan.displaceOthers(groups[key], isPresent) + if err := plan.displaceOthers(groups[key], isPresent); err != nil { + return foldPlan{}, err + } } return plan, nil } @@ -315,12 +317,16 @@ func (p foldPlan) refuse(entities []foldEntity) { // displaceOthers plans, for every planned path that still lands at or // under one folded name, the move of each version recorded as a file there // under another spelling whose path is no longer present. -func (p foldPlan) displaceOthers(members []foldMember, isPresent func(string) (bool, error)) { +func (p foldPlan) displaceOthers(members []foldMember, isPresent func(string) (bool, error)) error { for _, stale := range members { if stale.dir || stale.planned || !stale.live { continue } - if present, err := isPresent(stale.path); err != nil || present { + present, err := isPresent(stale.path) + if err != nil { + return err + } + if present { continue } for _, m := range members { @@ -329,6 +335,7 @@ func (p foldPlan) displaceOthers(members []foldMember, isPresent func(string) (b } } } + return nil } // presentAtSource reports whether a path is present in the volume's diff --git a/sync/mirror_write.go b/sync/mirror_write.go index a2a87cd..9c9880e 100644 --- a/sync/mirror_write.go +++ b/sync/mirror_write.go @@ -29,8 +29,8 @@ type mirrorWriter struct { volumeID int64 tr transport live map[string]store.RemotePath - // fold is how the destination compares names, and names the plan - // around the collisions that causes. + // fold is how the destination compares names; names plans the + // writes around the collisions its folding causes. fold nameFolding names foldPlan From 68e6b819f279611dbfa7a9799f36918f5a57bc31 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 05:45:38 +0200 Subject: [PATCH 53/61] design: describe the testbed's exFAT disk and how the benchmark ran --- design/testbed.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/design/testbed.md b/design/testbed.md index 23bb284..964effa 100644 --- a/design/testbed.md +++ b/design/testbed.md @@ -15,7 +15,7 @@ machines are five processes on loopback ports. | cloudbox (pure SFTP, no programs) | `rclone serve sftp --user u123456 --pass …` on `127.0.0.1:2222`, serving an empty dir | Exactly the product shape: an SFTP endpoint you cannot run code on. Presents a real host key, so the `known_hosts_file` UX is exercised too | | s3archive | SeaweedFS `weed server -s3` on `127.0.0.1:8333` (same creds/config as `test/integration/s3config.json`) | Already the reference S3 endpoint for the integration tests; proven to produce the composite multipart ETags the fingerprint path depends on | | kopia-mirror | `kopia` binary + a repo directory | Same as production: squirrel drives the CLI | -| usb disk | a plain directory; "unplugging" = renaming it | `local` destination + marker semantics don't care about hardware | +| usb disk | a plain directory; "unplugging" = renaming it. On macOS, an exFAT disk image (`hdiutil create -fs ExFAT -type SPARSE`, attached with `-mountpoint`) is closer: it folds case, gets macOS's `._` companion files, and keeps rclone from cloning files on APFS; "unplugging" = `hdiutil detach` | `local` destination + marker semantics don't care about hardware | ### The sftp server and native mirrors @@ -48,6 +48,18 @@ refusal prints the known_hosts line to add. Serve with `--key ` to keep the key stable across restarts (without it, rclone reuses keys it generated in its cache directory). +### Benchmarking native against rclone + +The 2026-09-24 numbers ([native-mirror.md](native-mirror.md), section 8) +came from `main`'s binary and the branch's, each installed with +`GOBIN= go install ./cmd/squirrel` from its own tree, pushing +`gendata` trees on fresh indexes to the exFAT image and to `rclone serve +sftp`. Loopback hides what a real link costs per round trip, so a third +destination reached the same server through a TCP proxy that delays every +chunk by a fixed time each way, kept outside the repo. Restart `rclone serve +sftp` after removing files under its root behind its back: its directory +cache otherwise keeps answering for them. + Deliberately not simulated: Synology/QNAP packaging (below squirrel), b2/gcs (same shape as s3), real network partitions — a dead machine or dark destination is simulated by stopping its process, which is also From 9dda92664615bf14a1ed435aaab2765d5af69aaa Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 05:49:10 +0200 Subject: [PATCH 54/61] docs: frame restore, verify, offload and staging as they work on native destinations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A framing review of the pages this branch touched found them describing native destinations the rclone way: - an encrypted content-addressed or packed restore re-hashes to BLAKE3; only an encrypted mirror falls back to size+mtime; - a push whose objects all got a fingerprint as they landed advances content-verified by itself, so sync → verify → offloadable holds only where fingerprints stay pending; - every native mirror writes receipts, sftp included, and staging holds every native layout's in-flight writes; - the layout guard covers a native mirror's receipt, and a native mirror restore checks BLAKE3 against the index or the receipts; - index snapshots ride to every destination, not only buckets; - verify re-hashes a destination squirrel writes itself in full, and is metadata-only on buckets alone; - the marker goes through squirrel's transport on every native layout, a native mirror refuses a first push onto a tree it did not record, and native sftp has its own connect bound. Smaller slips: encrypted packed sftp has no hash_algo default, checkers is for rclone destinations only, a local destination takes no crypt, and crypt moves an sftp destination's host key check to rclone. SAFETY-AUDIT.md notes where #217 changed the marker (H7) and the upload-correctness gap (D2). --- SAFETY-AUDIT.md | 15 +++++++-- docs/src/content/docs/guides/agent.md | 5 +-- docs/src/content/docs/guides/offloading.md | 14 +++++--- docs/src/content/docs/guides/recovery.md | 21 ++++++------ docs/src/content/docs/guides/restore.md | 14 ++++---- docs/src/content/docs/guides/syncing.md | 10 ++++-- docs/src/content/docs/guides/verification.md | 33 +++++++++++-------- .../content/docs/layouts/content-addressed.md | 12 ++++--- docs/src/content/docs/layouts/encrypted.md | 15 +++++---- docs/src/content/docs/reference/cli.md | 11 ++++--- docs/src/content/docs/reference/formats.md | 4 +-- .../content/docs/reference/on-disk-layout.md | 4 +-- 12 files changed, 97 insertions(+), 61 deletions(-) diff --git a/SAFETY-AUDIT.md b/SAFETY-AUDIT.md index 2618537..51576cb 100644 --- a/SAFETY-AUDIT.md +++ b/SAFETY-AUDIT.md @@ -958,7 +958,12 @@ extended enforcement to remote rclone destinations (`sftp`, `s3`, `b2`, the mirror, content-addressed, and packed layouts, with the marker filtered out of every transfer, comparison, and restore. A read that fails for any reason other than a definite "not found" refuses without writing, so a -reachability blip cannot be mistaken for a fresh root. +reachability blip cannot be mistaken for a fresh root. Since +[#217](https://github.com/mbertschler/squirrel/pull/217), a `local` +destination and an `sftp` one without crypt read and write the marker +through squirrel's own transport, staged and renamed onto its name, in every +layout; a volume that synced there before is refused as a disk that is most +likely not mounted rather than steered toward `--init`. **Issue:** [#64 — sync: require .squirrel-volume markers on destination and source to gate against misconfiguration](https://github.com/mbertschler/squirrel/issues/64); [#150 — sync: enforce .squirrel-volume markers on remote rclone destinations](https://github.com/mbertschler/squirrel/issues/150) @@ -1625,7 +1630,13 @@ proves — `presence+size` is explicitly **not** content-verified, and `store.ContentVerifiedMethod`). So the *consequence* the finding worried about — a presence-only advance gating an offload — is gone. -The narrow original gap remains: nothing downloads an object back through +Since [#217](https://github.com/mbertschler/squirrel/pull/217), a +destination without crypt that squirrel writes itself closes the gap: each +artifact is staged, read back through BLAKE3 on a local disk or hashed by +the server's command on sftp, and only then renamed onto its name. The gap +stays for crypt destinations, which rclone writes. + +The narrow original gap remains there: nothing downloads an object back through the crypt overlay and BLAKE3s the plaintext, so a wrong-at-upload object that happens to preserve decrypted size is still theoretically undetected. No `--verify` mode exists. This stays a deliberate non-decision rather than diff --git a/docs/src/content/docs/guides/agent.md b/docs/src/content/docs/guides/agent.md index 55d58cf..cd72d7b 100644 --- a/docs/src/content/docs/guides/agent.md +++ b/docs/src/content/docs/guides/agent.md @@ -45,8 +45,9 @@ Syncs are dispatched **per destination**, so a cloud target that has gone dark does not hold up local NAS→HTPC replication behind it. Two bounds keep a sick destination from occupying its own worker forever: -- every automatic rclone transfer runs with connect and I/O timeouts, so a dead - endpoint fails rather than hanging; +- every automatic transfer has a connect bound — rclone's connect and I/O + timeouts, or a one-minute connect and handshake limit on an sftp destination + squirrel writes itself — so a dead endpoint fails rather than hanging; - a **stall timeout** (10 minutes without progress by default) covers the case those miss — an endpoint that is live but stuck, accepting the connection and then never moving bytes. diff --git a/docs/src/content/docs/guides/offloading.md b/docs/src/content/docs/guides/offloading.md index a81d55b..78cf746 100644 --- a/docs/src/content/docs/guides/offloading.md +++ b/docs/src/content/docs/guides/offloading.md @@ -74,9 +74,12 @@ Files failing the gate are skipped and reported per target — see ### How a component becomes content-verified -Content-addressed and packed uploads are recorded as `presence+size` at write -time — a crypt remote exposes no hash to compare, and a pack's members are not -individually addressable at the destination. They are **upgraded** when a +A content-addressed or packed push advances its component as +`fingerprint-verified` when every object and pack it holds got a fingerprint as +it landed: always on a local disk, on sftp when the server runs its hash +command, from the provider's checksum on a bucket. Otherwise the component +stays `presence+size` — a server that runs no programs, a crypt remote that +exposes no hash to compare — and is **upgraded** when a [`squirrel verify`](/squirrel/guides/verification/) pass finds every underlying object and pack fingerprint-verified: the component is re-stamped as content-verified and relays to peers that way, so a hub's certified archive can @@ -88,8 +91,9 @@ volume has such a copy, the push itself advances the component as `fingerprint-verified`. A copy a verify pass later finds gone or changed stops counting for its file until the next push writes it again. -The practical consequence: on a cold-archive target, offload becomes possible -after verification has run, not merely after the sync succeeded. Give +The practical consequence: on a cold-archive target whose fingerprints stay +pending, offload becomes possible after verification has run, not merely after +the sync succeeded. Give `verify` [its own agent cadence](/squirrel/guides/agent/) and this happens unattended; run it by hand and offload waits on you. diff --git a/docs/src/content/docs/guides/recovery.md b/docs/src/content/docs/guides/recovery.md index 53bcca2..c421142 100644 --- a/docs/src/content/docs/guides/recovery.md +++ b/docs/src/content/docs/guides/recovery.md @@ -17,11 +17,11 @@ the next sync treats the destination as fresh and re-uploads. Use it when a destination's recorded state no longer matches reality and a sync refuses to proceed. The classic case: after wiping a remote, or pointing an -existing destination name at a fresh `root`, the -[content-addressed](/squirrel/layouts/content-addressed/) or -[packed](/squirrel/layouts/packed/) layout guard refuses — its recorded history -under that destination name expects a manifest segment or placement map that is -no longer there. An emptied root is refused too while its upload records remain: +existing destination name at a fresh `root`, the layout guard refuses — its +recorded history under that destination name expects a +[content-addressed](/squirrel/layouts/content-addressed/) manifest segment, a +[packed](/squirrel/layouts/packed/) placement map, or a native +[mirror](/squirrel/layouts/mirror/)'s receipt that is no longer there. An emptied root is refused too while its upload records remain: a push would otherwise skip everything those records claim is still there. Before this verb, the only escape was hand-editing SQLite or renaming the destination across every machine's config. @@ -66,7 +66,7 @@ recovery legible. When an edge machine dies (the most likely disaster), rebuild it from the hub with a **reverse peer push** — the same peer-sync mechanism the hub uses to feed a receive-only node every day. There is no separate restore verb for -this: `squirrel restore` pulls from bucket destinations, not from peer nodes, +this: `squirrel restore` pulls from destinations, not from peer nodes, and the machinery to push a volume to a node already exists. The story, using the [reference setup](/squirrel/reference/configuration/) @@ -162,14 +162,15 @@ destination carries bytes but no catalog to recover the index from. For a [mirror](/squirrel/layouts/mirror/) destination (including an encrypted one), [`squirrel restore`](/squirrel/guides/restore/) pulls the volume back -byte-for-byte, decrypting on the way down and comparing checksums where the -destination exposes hashes. +byte-for-byte. A native mirror checks every file against the index's BLAKE3, or +against its receipts without an index; an rclone mirror decrypts on the way down +and compares checksums where the backend exposes them. ### Recovering the index too squirrel rides an [index snapshot](/squirrel/configuration/index-snapshots/) -along to destination buckets under `.squirrel-index/`. When the hub itself dies, -a restore-from-cloud yields the data *and* the index that explains it — fetch +along to its destinations under `.squirrel-index/`. When the hub itself dies, +a restore from a destination yields the data *and* the index that explains it — fetch the ride-along snapshot and swap it in as the live index with [`squirrel db restore`](/squirrel/reference/cli/#squirrel-db). `runs` and `query` answer immediately against the recovered catalog. diff --git a/docs/src/content/docs/guides/restore.md b/docs/src/content/docs/guides/restore.md index 245ed06..5130b99 100644 --- a/docs/src/content/docs/guides/restore.md +++ b/docs/src/content/docs/guides/restore.md @@ -34,11 +34,13 @@ Every restored file lands through a temporary file beside its path, which is flushed and then renamed over it, so a restore that stops halfway never leaves a truncated file behind. -:::note[Encrypted destinations are always size+mtime] -[Encrypted (`crypt`)](/squirrel/layouts/encrypted/) destinations cannot expose +:::note[Encrypted mirrors are always size+mtime] +An [encrypted (`crypt`)](/squirrel/layouts/encrypted/) mirror cannot expose content hashes through rclone, so restore from one falls back to a size+mtime comparison — recorded as shallow — **even without** `--shallow`, exactly as sync -does. Passing `--shallow` changes nothing for these destinations. +does. Passing `--shallow` changes nothing there. An encrypted content-addressed +or packed destination is different: its restore re-hashes every file to BLAKE3, +with or without crypt. ::: ## Restoring in place @@ -118,7 +120,7 @@ restore goes through the kopia CLI (`kopia snapshot restore`) instead. ## Restoring the index too For a full disaster-recovery scenario, remember that squirrel rides an -[index snapshot](/squirrel/configuration/index-snapshots/) along to destination -buckets under `.squirrel-index/`. A restore-from-cloud yields the data *and* the -index that explains it — use [`squirrel db restore`](/squirrel/reference/cli/#squirrel-db) +[index snapshot](/squirrel/configuration/index-snapshots/) along to its +destinations under `.squirrel-index/`. A restore from a destination yields the +data *and* the index that explains it — use [`squirrel db restore`](/squirrel/reference/cli/#squirrel-db) to swap that snapshot in as the live index. diff --git a/docs/src/content/docs/guides/syncing.md b/docs/src/content/docs/guides/syncing.md index 1e60d16..5e4712c 100644 --- a/docs/src/content/docs/guides/syncing.md +++ b/docs/src/content/docs/guides/syncing.md @@ -67,12 +67,16 @@ squirrel sync pictures --to mirror # every time after - **`local`, `sftp`, `s3`, `b2`, `gcs`** — write a `.squirrel-volume` marker under the destination's volume directory, through the same path the transfer - takes: squirrel's own transport on a native mirror, rclone and its overlay - everywhere else. On a `local` destination whose root does not exist yet, + takes: squirrel's own transport on a destination it writes itself (`local`, + or `sftp` without crypt, in any layout), rclone and its overlay everywhere + else. On a `local` destination whose root does not exist yet, `--init` also creates the root. Every later sync **requires** that marker and refuses if it is missing (a missing marker after the fact almost always means the root is wrong — an unmounted disk, a typo, or an unreachable remote). A marker that names a - *different* volume is always refused, with or without `--init`. This holds + *different* volume is always refused, with or without `--init`. A native + mirror also refuses a volume's first push, `--init` or not, onto a volume + directory that already holds files squirrel has no record of writing (see + [mirror](/squirrel/layouts/mirror/#how-a-mirror-is-written)). This holds across the mirror, content-addressed, and packed layouts: the marker sits at the volume root regardless of layout, and is filtered out of every transfer, comparison, and restore. diff --git a/docs/src/content/docs/guides/verification.md b/docs/src/content/docs/guides/verification.md index 15f6572..ee155f1 100644 --- a/docs/src/content/docs/guides/verification.md +++ b/docs/src/content/docs/guides/verification.md @@ -1,12 +1,14 @@ --- title: Offsite verification -description: squirrel verify re-checks what squirrel stored — content-addressed and packed objects by their scan-back fingerprint, a native mirror's copies by size, mtime and BLAKE3. +description: squirrel verify re-checks what squirrel stored — content-addressed and packed objects by their fingerprint, a native mirror's copies by size and mtime, and on a local disk by BLAKE3. --- Cold archive storage is exactly the copy you can't cheaply re-download and re-hash. [Content-addressed](/squirrel/layouts/content-addressed/) and -[packed](/squirrel/layouts/packed/) destinations therefore get a metadata-only -integrity check: the **scan-back fingerprint**. +[packed](/squirrel/layouts/packed/) destinations on a bucket therefore get a +metadata-only integrity check: the **scan-back fingerprint**. A destination +squirrel writes itself — `local`, or `sftp` without crypt — is re-hashed in +full instead (below). ## How the scan-back fingerprint works @@ -17,7 +19,7 @@ from the remote and records it in the index next to the upload. Verification then re-fetches the same metadata later and compares **provider value then vs provider value now** — squirrel never recomputes a provider checksum, so provider-specific composite forms are handled as opaque strings, and -**no object body is ever transferred**. +on a bucket **no object body is ever transferred**. The read is done via a direct S3 `ListObjectsV2` for `s3`, `rclone lsjson --hash` for every other backend rclone writes, and squirrel's own transport for @@ -42,9 +44,9 @@ a destination it writes itself (below). before it gets its name, and on every verify pass. Here the fingerprint is a content check too: an object's BLAKE3 must equal its name, a pack's its key. - **`sftp`** — the checksum computed server-side by the remote's hash command. - Content-addressed and packed sftp destinations default to **SHA-256** - (`hash_algo = "sha256"`); set `hash_algo` if your server only offers another - type. Without `crypt` squirrel runs the command itself — `md5sum`, `sha1sum`, + Content-addressed sftp destinations, and packed ones without crypt, default + to **SHA-256** (`hash_algo = "sha256"`); set `hash_algo` if your server only + offers another type. Without `crypt` squirrel runs the command itself — `md5sum`, `sha1sum`, `sha256sum` or `b3sum`, probed once per session — on the staged copy before it gets its name, and checks the answer against the bytes it sent. A server that runs no programs leaves every fingerprint pending, with a warning. The command @@ -68,9 +70,10 @@ and every [native mirror](#native-mirrors) in config. An explicit destination must be one of those, else it errors: a mirror rclone writes records nothing to re-check. -The pass lists the destination's `objects/` directory once (batched, -metadata-only; on a `local` destination squirrel re-reads every recorded -artifact), then per recorded object: +The pass lists the destination's `objects/` directory once (batched, and +metadata-only on a bucket; on a `local` destination squirrel re-reads every +recorded artifact, on plain sftp the server re-hashes each one), then per +recorded object: - a **match** stamps the object verified in the index; - an object **without a fingerprint yet** (uploaded before this feature, or whose @@ -96,8 +99,12 @@ gate refuses that method. When a pass leaves every object and pack of a durability vector to a content-verified method** and re-attempts any advance that was held back, relaying the upgraded method to peers. -So on a cold archive the sequence is sync → verify → offloadable, not sync → -offloadable. Giving verify [its own agent cadence](/squirrel/guides/agent/) +A push whose objects all got their fingerprint as they landed advances the +vector content-verified by itself: squirrel reads each one back on a local disk, +hashes it with the server's command on sftp, and scans it back right after the +upload elsewhere. Where a fingerprint stays pending — a server that runs no +programs, a backend that exposes none at upload — the sequence is sync → verify +→ offloadable, not sync → offloadable. Giving verify [its own agent cadence](/squirrel/guides/agent/) (`verify_every`) keeps that unattended. ## A mismatch latches an alarm @@ -163,7 +170,7 @@ mtime alone, and never gates offload. [destinations.archive] # ... hash_algo = "sha256" # sftp only: which server-side hash the fingerprint uses -checkers = 4 # cap rclone's concurrent checkers +checkers = 4 # rclone destinations only: cap rclone's concurrent checkers force_path_style = true # s3 only: path-style bucket addressing for the ETag reader ``` diff --git a/docs/src/content/docs/layouts/content-addressed.md b/docs/src/content/docs/layouts/content-addressed.md index 9b19908..1d0b119 100644 --- a/docs/src/content/docs/layouts/content-addressed.md +++ b/docs/src/content/docs/layouts/content-addressed.md @@ -4,8 +4,8 @@ description: An append-only, content-addressed layout for cold archive storage w --- By default a destination [mirrors](/squirrel/layouts/mirror/) the volume's tree. -Any destination but kopia — a `local` disk, an `sftp` server, `s3`, `b2` or -`gcs`, with or without a [`crypt`](/squirrel/layouts/encrypted/) block — can +Any destination but kopia — a `local` disk, or an `sftp` server, `s3`, `b2` or +`gcs` with or without a [`crypt`](/squirrel/layouts/encrypted/) block — can instead opt into an **append-only, content-addressed** layout, built for cold archive storage where objects should never be rewritten or moved. @@ -69,7 +69,8 @@ rclone. Durability is **transactional per run**: the run only counts as successful — and only then feeds the durability evidence squirrel records per destination — once *both* all its content objects *and* its manifest segment are confirmed on the -remote (each transfer's success plus a follow-up presence/size listing). +remote: squirrel confirms each artifact it writes itself as it lands, and +rclone's transfers are followed by a presence/size listing. A failed run may leave objects without a segment; they are harmless (nothing maps them) and the next run skips re-uploading anything already recorded, pushing only @@ -101,8 +102,9 @@ what's missing. ## Offsite verification Cold archive storage is exactly the copy you can't cheaply re-download and -re-hash. Content-addressed destinations therefore get a metadata-only integrity -check — the **scan-back fingerprint** — that never transfers an object body. See +re-hash. Content-addressed destinations on a bucket therefore get a +metadata-only integrity check — the **scan-back fingerprint** — that never +transfers an object body; one squirrel writes itself is re-hashed in full. See [Offsite verification](/squirrel/guides/verification/) for how it works per backend and how to run `squirrel verify`. diff --git a/docs/src/content/docs/layouts/encrypted.md b/docs/src/content/docs/layouts/encrypted.md index 749c501..5ed0041 100644 --- a/docs/src/content/docs/layouts/encrypted.md +++ b/docs/src/content/docs/layouts/encrypted.md @@ -1,11 +1,14 @@ --- title: Encrypted (crypt) -description: Any non-local destination can encrypt file contents client-side before upload via rclone's crypt overlay. On the append-only layouts the stored names are keyed too; verification falls back to size+mtime. +description: An sftp, s3, b2 or gcs destination can encrypt file contents client-side before upload via rclone's crypt overlay. On the append-only layouts the stored names are keyed too; an encrypted mirror compares by size+mtime. --- -Any non-`local` destination can add a `crypt` block to encrypt file contents -client-side before upload, via rclone's [crypt](https://rclone.org/crypt/) -overlay. +An `sftp`, `s3`, `b2` or `gcs` destination can add a `crypt` block to encrypt +file contents client-side before upload, via rclone's +[crypt](https://rclone.org/crypt/) overlay. rclone writes every encrypted +destination, so on sftp the crypt block also moves the server's host key check +to rclone, which accepts whatever key the server presents unless +`known_hosts_file` is set (see [sftp keys](/squirrel/reference/configuration/#sftp)). ```toml [destinations.offsite.crypt] @@ -115,11 +118,11 @@ Losing the passwords costs you the ability to *locate* an artifact as well as to decrypt it. ::: -### Verification falls back to size+mtime +### An encrypted mirror compares by size+mtime rclone crypt remotes cannot expose content hashes, so the checksum comparison (`--checksum`) cannot pass through the overlay. Transfers to and -from an encrypted destination compare by **size+mtime** instead — the same +from an encrypted mirror compare by **size+mtime** instead — the same comparison `--shallow` uses — and say so in the run output; the runs row records the transfer as shallow. diff --git a/docs/src/content/docs/reference/cli.md b/docs/src/content/docs/reference/cli.md index d197222..af65a9a 100644 --- a/docs/src/content/docs/reference/cli.md +++ b/docs/src/content/docs/reference/cli.md @@ -214,7 +214,7 @@ renders the same facts from the same query layer — see ## squirrel verify -**Re-check what squirrel recorded storing on a destination: objects and packs against their upload fingerprints, a native mirror's copies by size, mtime and BLAKE3.** +**Re-check what squirrel recorded storing on a destination: objects and packs against their upload fingerprints, a native mirror's copies by size and mtime, and on a local disk a rotating tenth of them by BLAKE3.** ``` squirrel verify [] @@ -315,7 +315,7 @@ Takes no arguments. Lists every kind of run — `index`, `sync`, `restore`, Under routine cadences most rows are no-ops (a pair checked, nothing to do). `--changes` keys on the count of files a run actually changed, so it folds away -bucket pushes and index runs too, not just peer-sync no-ops. Runs recorded +destination pushes and index runs too, not just peer-sync no-ops. Runs recorded before that count existed are shown rather than silently folded — their change count is genuinely unknown. @@ -424,9 +424,10 @@ A [native mirror](/squirrel/guides/restore/#native-mirrors) restore needs no rcl with an index it checks each path against it, and without one it walks the mirror and checks each file against the mirror's receipts. -Restore from an [encrypted (`crypt`)](/squirrel/layouts/encrypted/) destination -is always a size+mtime comparison (recorded shallow) even without `--shallow`, -because rclone crypt remotes don't expose content hashes. +Restore from an [encrypted (`crypt`)](/squirrel/layouts/encrypted/) mirror is +always a size+mtime comparison (recorded shallow) even without `--shallow`, +because rclone crypt remotes don't expose content hashes. An encrypted +content-addressed or packed restore re-hashes every file to BLAKE3. --- diff --git a/docs/src/content/docs/reference/formats.md b/docs/src/content/docs/reference/formats.md index 79fcfef..1aec702 100644 --- a/docs/src/content/docs/reference/formats.md +++ b/docs/src/content/docs/reference/formats.md @@ -25,8 +25,8 @@ sorted by `(path, status)`: | `size_bytes` | File size as indexed. | | `mtime_ns` | Modification time (nanoseconds) as indexed. | -A [mirror](/squirrel/layouts/mirror/) on a local disk writes the same format as -its receipt, at `/.squirrel-index/run-`; there the bytes of a +A native [mirror](/squirrel/layouts/mirror/) (`local`, or `sftp` without crypt) +writes the same format as its receipt, at `/.squirrel-index/run-`; there the bytes of a `present` path are at the path itself. ### Replaying segments diff --git a/docs/src/content/docs/reference/on-disk-layout.md b/docs/src/content/docs/reference/on-disk-layout.md index fa31c71..b4f93de 100644 --- a/docs/src/content/docs/reference/on-disk-layout.md +++ b/docs/src/content/docs/reference/on-disk-layout.md @@ -16,7 +16,7 @@ A tree shaped like the local volumes: pictures/ 2024/cat.jpg .squirrel-history/run-7/2024/cat.jpg # prior content of cat.jpg - .squirrel-index/run-12 # receipt for run 12 (local disks) + .squirrel-index/run-12 # receipt for run 12 (native mirrors) .squirrel-index/index-20260604T120000.000Z-run-12.db # global index snapshot (ride-along) docs/ invoice.pdf @@ -90,7 +90,7 @@ for user content: | `.squirrel-history/run-/` | Prior bytes of the files a sync run replaced on a [mirror](/squirrel/layouts/mirror/). | | `.squirrel-index/` | Ride-along [index snapshots](/squirrel/configuration/index-snapshots/), and a native mirror's receipts. | | `.squirrel-restore-history/run-/` | Files displaced by an [`--in-place` restore](/squirrel/guides/restore/). | -| `.squirrel-staging/run-/` | A native [mirror](/squirrel/layouts/mirror/)'s in-flight writes, renamed onto their paths once complete. | +| `.squirrel-staging/run-/` | In-flight writes on a destination squirrel writes itself, in any layout, renamed onto their names once confirmed. | One reserved **file** sits at the destination root rather than in a volume tree: `.squirrel-naming`, which records the artifact-naming scheme of an From c0ae689ec09b4f79730e44df28ba3da8f3ea89e8 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Thu, 24 Sep 2026 23:30:48 +0200 Subject: [PATCH 55/61] design: flush once per batch and write several paths at once (decision 8) Measured where a native push that writes spends its time: on local disks the three full flushes per file, not the read-back; over sftp 27 requests per path, one after another. Agreed with the maintainer: Put and Rename stop flushing and a new Transport.Flush makes a batch of at most 64 files or 256 MB durable before any record claims them, the full read-back runs after the batch's flush, several paths go in flight per the new concurrency key, and every per-call check stays. --- design/native-mirror.md | 250 +++++++++++++++++++++++++++++----------- 1 file changed, 185 insertions(+), 65 deletions(-) diff --git a/design/native-mirror.md b/design/native-mirror.md index 93f27b6..b858277 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -245,11 +245,15 @@ type transport interface { List(ctx context.Context, dir string) ([]entry, error) Get(ctx context.Context, name string) (io.ReadCloser, error) // Put creates name exclusively (fs.ErrExist if present), streams r into - // it, sets its mtime, and syncs it to stable storage before returning. + // it and sets its mtime. Its bytes are durable once a later Flush returns. Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error // Rename moves from to to, creating to's parents; fs.ErrExist if to exists. + // The move is durable once a later Flush returns. Rename(ctx context.Context, from, to string) error Remove(ctx context.Context, name string) error + // Flush returns once every Put and Rename that returned before it is on + // stable storage. + Flush(ctx context.Context) error Close() error } ``` @@ -284,6 +288,15 @@ type transport interface { That function is the whole audit surface for destroying or moving bytes on a destination. +- **Durability comes from `Flush`, once per batch.** `Put` and `Rename` + return once their effect is visible; one `Flush` then makes everything + before it durable. A layout records a location as holding bytes (a `live` + or `displaced` row, an upload record, a receipt that seals a run) only + after a `Flush` that follows the call that put the bytes there. It also + flushes staged bytes before renaming them into place, because reconcile + trusts size and mtime at a name. A flush per batch of files instead of + several per file is what makes a push that writes affordable on a local + disk (section 8). - **Object stores implement everything except `Rename`.** S3 can create exclusively with a conditional put. That is enough for the content-addressed and packed layouts in step 3. A mirror needs `Rename`, @@ -295,7 +308,10 @@ type transport interface { refuses to follow symlinks out of it. `os.Root` does follow symlinks that stay inside the root, so every call also checks its name's parent chain with `Lstat` and refuses a symlink anywhere along it (`sync/transport_local.go`). -- `Put` opens with `O_CREATE|O_EXCL`, copies, sets the times, then syncs. +- `Put` opens with `O_CREATE|O_EXCL`, copies, and sets the times. The file + stays open until the next `Flush`, and every directory whose entries a call + changed is remembered: a new file's, both sides of a rename, and the parent + of every directory a call created. - `Rename` avoids replacing its target in one of two ways: - **Preferred:** the platform's no-replace rename (`renameat2` with `RENAME_NOREPLACE` on Linux, `renamex_np` with `RENAME_EXCL` on macOS), @@ -306,10 +322,21 @@ type transport interface { writer from outside squirrel could still slip in between the check and the rename. Squirrel can't collide with itself here, because the run guard and the volume marker already exclude a second squirrel writer. -- After a rename, the parent directories are synced. +- `Flush` makes the remembered files and directories durable in one go: + - **macOS:** each file is `fsync`ed as its `Put` ends and each directory at + the flush, then one `F_FULLFSYNC` flushes the drive's cache. The `fcntl` + manual page guarantees that this also persists everything `fsync`ed on + the device before it. That is one full flush per batch instead of three + per file. + - **Linux:** `fsync` itself flushes the drive, so the flush `fsync`s every + remembered file and directory together, and the filesystem's journal + commits them at once. + - **Elsewhere:** each file is flushed as its `Put` ends, and directories + are flushed where the platform can. - **Every call is bounded by progress.** A call that makes none for `DefaultStallTimeout` (a `Put` progresses with every chunk it reads) fails the - push. A local call blocked in the kernel can't be interrupted and may still + push. A `Flush` is also allowed the time the bytes put since the last one + take at 1 MiB/s. A local call blocked in the kernel can't be interrupted and may still finish a move later, so a push refuses while a call an earlier push gave up on is still outstanding (`sync/transport_stall.go`). @@ -318,8 +345,14 @@ type transport interface { - Built on `golang.org/x/crypto/ssh`, already a dependency, and `github.com/pkg/sftp`, which is new (`sync/transport_sftp.go`). - `Put` opens with `SSH_FXF_CREAT|SSH_FXF_EXCL` and uses concurrent writes, so - high latency doesn't cap throughput. It syncs through `fsync@openssh.com` - when the server offers it. + high latency doesn't cap throughput. It flushes its file through + `fsync@openssh.com` when the server offers it. The protocol can't flush a + directory, so `Flush` has nothing left to do. +- **Paths in flight share one connection.** Every file a push writes at once + (`concurrency`, section 7) goes over the same SSH connection and sftp + session, which interleaves their requests. A server's cap on concurrent + connections is never the limit; one that serves a session's requests one + at a time, as OpenSSH's does, still hides the network's round trips. - **mtime is whole seconds.** Protocol version 3 carries only seconds, so the records store the mtime the server reports. - **`Put` and `Rename` check first.** The protocol's rename fails when the @@ -445,26 +478,35 @@ is treated as changed behind squirrel's back: its row becomes `lost` and the pat ### Writing one path +Execute writes the planned paths in batches of at most 64 paths or 256 MB, +several paths at a time: `concurrency` of them (section 7). Each step below +runs for the whole batch before the next begins. A path whose step fails drops +out of the batch, and the others go on. + 1. **Reconcile** (once, at push start). Squirrel settles every `committing` and `displacing` row for this destination by checking both locations (next table). Staging left by finished runs is removed. 2. **Stage.** The source is streamed into `.squirrel-staging/run-/`, and BLAKE3 is computed over the same bytes. The path key is the lowercase hex BLAKE3 of the volume-relative path: - the row doesn't exist yet (step 4 inserts it), and hex stays unique on a + the row doesn't exist yet (step 5 inserts it), and hex stays unique on a destination that folds case. If the hash doesn't match the indexed hash, the path fails and the run fails before its seal, so the watermark stays put. The staged file stays until the next push's reconcile removes it with the finished run's staging: the name guard removes no running run's staging. That is the `errContentDrift` contract. Here the hash covers exactly the bytes sent, which closes the re-hash-then-read gap - noted on `uploadOneObject`. -3. **Displace.** First any parent of the path that isn't a directory (a - file↔directory swap, a symlink) is displaced the same way. Then, if `Lstat` - finds an entry at the path: + noted on `uploadOneObject`. The batch's staged files are then flushed. +3. **Read back**, on a local disk: every staged file is read in full, past + the cache, through BLAKE3 (section 5). A mismatch fails the path before it + touches the live tree. +4. **Displace.** First any parent of a path that isn't a directory (a + file↔directory swap, a symlink) is displaced the same way, once per + directory, in path order. Then, for each path, if `Lstat` finds an entry + there: - **The entry's size and mtime match the live row:** 1. mark the row `displacing` with this run; 2. rename the entry to `.squirrel-history/run-/`; - 3. mark the row `displaced`. + 3. after the batch's flush, mark the row `displaced`. - **They don't match** (the file changed behind squirrel's back): 1. mark the row `lost`; 2. displace the entry as unrecorded bytes, which a warning and a @@ -472,24 +514,37 @@ is treated as changed behind squirrel's back: its row becomes `lost` and the pat A record never claims history holds bytes it doesn't. - **It is a directory** a file replaced: every live row under it becomes - `displacing`, the directory moves, and they become `displaced`; a row whose - bytes changed becomes `lost` first. + `displacing`, the directory moves, and they become `displaced` after the + flush; a row whose bytes changed becomes `lost` first. - **It is not a directory, or nothing**, while live rows sit under the path (a recorded directory replaced by a file or a symlink on the destination, or removed): those rows become `lost`, since their bytes can't be at their paths, and turn into repairs while the index holds their content. -4. **Commit:** +5. **Commit:** 1. insert the new row as `committing`; 2. rename the staged file to the path; - 3. mark the row `live`. + 3. after the batch's flush, mark the row `live`. Each move is recorded before it happens. Reconcile then finishes the record or withdraws it, based on where the bytes actually are. The destination never lacks a copy of something it held. Displaced bytes reach history before the new version is committed, and the new version stays in staging until then. -Between steps 3 and 4 the live path is briefly empty. That costs availability -until the next push, never content. +Between steps 4 and 5 the live path is briefly empty, for up to a batch. That +costs availability until the next push, never content. + +Each path still passes through the same states as a push that wrote one path +at a time: all of a batch's displacements are marked `displaced` before any of +its commits begins, so a path never holds a `displacing` and a `committing` row +at once. Only the step that confirms a move waits for the flush. + +**Paths in flight.** Within a step the batch's paths run `concurrency` at a +time. They can't collide: each stages under its own key, a path's displacement +moves only what sits at its own name, and both a parent in the way and a +version recorded under another spelling of the name (next section) are +displaced in the sequential pass that opens step 4. The writer's own +bookkeeping, the live records it keeps current and the report, is shared +behind one lock. ### Names the destination folds @@ -558,6 +613,12 @@ like any other foreign entry. | commit rename | new version at the path | staging gone and path present, so the row becomes `live` | | every write, before the seal | tree complete, no receipt | the watermark holds, and the next push translates every path to "already correct" | +A power cut can also undo whatever the last flush didn't cover. Every row +still finds its bytes at one of the two places the table checks: no row +leaves `displacing` or `committing` before the flush that covers its move, +and a staged file is flushed before it's renamed onto a path. The receipt is +flushed before the run is sealed. + `TestMirrorCrashTable` runs each row above; `TestMirrorTranslationRules` and `TestMirrorWriteDisplacesWhatThePathHolds` run the translation table. @@ -573,11 +634,15 @@ usual: - **Crash injection at every transport call** of a push, using a fault-injecting transport wrapper, then a clean push. The invariants below - must hold afterwards. + must hold afterwards. It writes one path at a time, so the calls come in + the same order on every run; `Flush` is a call like any other. +- **Power cuts.** The same wrapper can, at the crash, also undo every `Put` + and `Rename` since the last `Flush`: a put file vanishes or is cut short, + a rename is reversed. The invariants must hold after the next clean push. - **A model-based test.** It generates random index histories: add, modify, delete, re-add, file↔directory swaps, names that collide by case. It then - pushes with random crash points and compares the results against a - reference model. + pushes with several paths in flight and random crash points, some of them + power cuts, and compares the results against a reference model. - **File↔directory swaps**, in both directions and nested. - **Unexpected entries at a target:** - an unrecorded file (a foreign write, or a tree rclone wrote); @@ -619,6 +684,7 @@ Where each case lives: | Case | Tests | |---|---| | Crash at every call, then a clean push | `TestMirrorCrashAtEveryTransportCall`, `TestNativeContentCrashAtEveryTransportCall` (`sync/crash_every_call_test.go`) | +| Power cuts at every call | `TestMirrorPowerCutAtEveryTransportCall`, `TestNativeContentPowerCutAtEveryTransportCall` (`sync/crash_every_call_test.go`) | | Random histories against a model | `TestMirrorModel` (`sync/mirror_model_test.go`) | | File↔directory swaps | `TestMirrorFileDirectorySwap`, `TestMirrorNestedFileDirectorySwaps` | | Unrecorded and changed entries at a target | `TestMirrorWriteDisplacesWhatThePathHolds`, `TestMirrorRecordChangedBehindSquirrelsBack` | @@ -640,9 +706,11 @@ Every fingerprint stays pending, so the mirror still can't gate offload. That's the same as today, only the method name changes. This step changes it for local mirrors. -- **Read-back at write time, on local disks.** After staging and syncing, - squirrel re-reads the staged file and hashes it with BLAKE3 before - committing (`sync/readback.go`). The read bypasses the cache: on Linux the +- **Read-back at write time, on local disks.** Once a batch's staged files + are flushed to stable storage, squirrel re-reads each one in full and + hashes it with BLAKE3 before committing it (`sync/readback.go`). So every + fingerprint comes from reading bytes the disk has already reported + persisted; a copy never read back that way never counts for offload. The read bypasses the cache: on Linux the synced pages are dropped (`POSIX_FADV_DONTNEED`) before the read, and on macOS both the write and the read run with `F_NOCACHE`, because a read there is still served from pages the write left cached. It is best @@ -661,8 +729,9 @@ for local mirrors. paths never go on a server command line, so their fingerprints stay pending. - **Cost.** Read-back is a safety property, so it's always on for local - disks. Every written byte is read once more, roughly 1.5 to 2 times the push - time on a USB disk. + disks. Every written byte is read once more: about 2 ms for a 230 KB file + on the testbed's exFAT image, a tenth of what a push per file cost before + flushes were batched (section 8). - **Verify pass for mirrors.** `verify_every` becomes valid on native mirrors. Each pass does two things: - It checks the size and mtime of every `live` and `displaced` row with @@ -707,20 +776,27 @@ Content-addressed and packed destinations on `local`, and on `sftp` without The layouts land every object, pack, placement map and manifest segment through one small interface, `artifactStore` (`sync/artifacts.go`), whose other implementation is rclone's, for crypt destinations and for s3, b2 and -gcs. Each artifact: - -1. is streamed into `/.squirrel-staging/run-/` while BLAKE3 - hashes the bytes sent — the drift check, over exactly those bytes — and, on - sftp, the hash the server's command computes; -2. is confirmed before it gets its name: read back through BLAKE3 on a local - disk, hashed by the server's command on sftp. A match is the artifact's - fingerprint, recorded with its upload row at once; a mismatch fails the - artifact. A server without the command confirms nothing, and the - fingerprint stays pending, as it does under rclone for such a server; -3. is renamed onto its name. If the name already holds a file — a crash +gcs. Objects land in batches, like a mirror's paths: at most 64 or 256 MB, +`concurrency` at a time. Each step runs for the whole batch before the next: + +1. every artifact is streamed into `/.squirrel-staging/run-/` + while BLAKE3 hashes the bytes sent — the drift check, over exactly those + bytes — and, on sftp, the hash the server's command computes; then the + batch is flushed; +2. each is confirmed before it gets its name: read back through BLAKE3 on a + local disk, hashed by the server's command on sftp. A match is the + artifact's fingerprint; a mismatch fails the artifact. A server without + the command confirms nothing, and the fingerprint stays pending, as it + does under rclone for such a server; +3. each is renamed onto its name. If the name already holds a file — a crash between landing and recording, or a failed run's orphan — that file is - confirmed instead (downloaded and hashed when the server runs no command) - and recorded, or the artifact fails. Squirrel never replaces it. + confirmed instead (downloaded and hashed when the server runs no command), + or the artifact fails. Squirrel never replaces it; +4. the batch is flushed, and only then is each landed artifact's upload row + recorded, with its fingerprint. + +A pack, the placement map and the manifest segment land alone, through the +same steps. `squirrel verify` reads these destinations through the transport too (`sync/verify_native.go`): once the marker of every volume that synced there @@ -795,12 +871,15 @@ addressed local destinations by path; that restriction is gone. command the transport runs on the server: `md5`, `sha1`, `sha256` (the default, now for packed as well) or `blake3`, the hashes squirrel also computes to check the server's answer. rclone's other hashes (`crc32`, - `xxh3`, `xxh128`) stay valid behind crypt only. No key is added. - Concurrency is fixed. On sftp each file goes out as concurrent write - requests (`pkg/sftp`'s default of 64 in flight); paths are written one at a - time on both transports. The testbed benchmark against rclone (section 8) - was to decide whether several paths in flight are worth their bookkeeping; - it says they are, over sftp at any latency (open question 2). + `xxh3`, `xxh128`) stay valid behind crypt only. +- **`concurrency`** is how many files a push writes at once, on every + destination type: 4 by default on a local disk, 8 on sftp. A storage + server that limits concurrent connections, or a slow disk or USB bridge, + may want it lower. On a destination squirrel writes itself, the files share + one SSH connection (section 3), and each file on sftp also goes out as up + to 64 concurrent write requests (`pkg/sftp`'s default). On a destination + rclone writes, it becomes rclone's `--transfers`; together with + `checkers` it caps the connections rclone opens. ## 8. What we give up @@ -814,8 +893,9 @@ addressed local destinations by path; that restriction is gone. - Decision 7 keeps a cheap mitigation as a candidate. - **Rclone's tuning and backend know-how.** Rclone brings parallel transfers, multi-threaded streams, and years of workarounds for sftp servers. The - switch should wait for a benchmark on the testbed against rclone: it ran on - 2026-09-24 (below), and native pushes that write are several times slower. + switch waited for a benchmark on the testbed against rclone: it ran on + 2026-09-24 (below). Native pushes that wrote were several times slower, + and the fix is decided (open question 2, now decision 8). ### The benchmark @@ -839,21 +919,52 @@ files and adds 150 (30 and 30 on `trip`). Wall time in seconds: A native first push to APFS on the internal disk took 86.4 s. -- **Local disks pay for durability.** Every written file is synced to stable - storage — on macOS a full flush of the drive's cache — read back past the - cache, and after its rename both parent directories are synced; rclone - syncs nothing. That is about 18 ms per file on the internal SSD, and 25 ms - on the exFAT image. -- **sftp pays in round trips.** A written path costs about 30 sequential +That build wrote one path at a time: + +- **Local disks paid for durability.** Every written file was synced to + stable storage — on macOS a full flush of the drive's cache — read back + past the cache, and after its rename both parent directories were synced; + rclone syncs nothing. That was about 18 ms per file on the internal SSD, + and 25 ms on the exFAT image. +- **sftp paid in round trips.** A written path cost about 30 sequential requests: `Put` checks its target and each parent with `Lstat`, then creates, writes, closes and sets the mtime; the staged copy, the path's parents and the path are each looked up again, and the rename checks both - parent chains. At a 20 ms round trip that is about 0.7 s per path, against + parent chains. At a 20 ms round trip that was about 0.7 s per path, against rclone's four transfers in flight. - **Unchanged pushes are faster natively** everywhere: they read squirrel's records instead of listing both trees. -What to change is open question 2. +**Where the time went.** A push instrumented call by call, 1000 files of +231 MB shaped like the photo tree, on the same laptop: + +| per file | internal APFS disk | exFAT image | +|---|---|---| +| whole push | 19.0 ms | 26.2 ms | +| the three full flushes: the file, then both directories after the commit rename | about 13 ms | 11.5 ms, and they slow the calls after them | +| read-back | 2.0 ms | 1.7 ms | +| each call's parent-chain check for symlinks | 0.5 ms | 0.3 ms | +| the same push with a plain `fsync` in place of each full flush | 2.2 ms | 6.3–8.7 ms | + +So the cost was the number of full flushes, not reading back. +Several paths in flight, each still flushing on its own, took a stripped-down +reproduction only from 22 to 16 ms per file on the exFAT image (15.5 to 9.4 on +APFS); sharing each flush among the paths in flight reached 11 and 3.0; one +flush per step for a batch of 64 reached 3–6 and 0.7. On the exFAT image the +rest is that filesystem's slow file calls (create 0.8, set mtime 1.1, rename +1.7 ms) and the evidence itself: writing past the cache and reading back take +about 3 ms per file, which rclone doesn't spend. + +Over sftp a new path at depth two cost 27 requests, each waiting for the one +before: 20 `Lstat`s (14 re-checking parent chains, 6 the target), 2 lookups +while creating parents, open, write, set mtime, close and rename. At a 20 ms +round trip that measured 632 ms per path, 73% of it in `Lstat`. Several paths +in flight over the one connection scale linearly, with every check kept: 608, +152, 76 and 39 ms per path at 1, 4, 8 and 16 in flight. At 8 that is rclone's +time for the 608-file tree (45 s); rclone itself checks no parent chain and +writes through a symlinked directory (rclone 1.74.1 against the in-process +server). + - **A new dependency:** `github.com/pkg/sftp`. ## 9. Order of work @@ -910,17 +1021,26 @@ Decided on 2026-09-23: periodic check would compare a plain directory walk with the index's present set, which would restore some independence for every layout. +Decided on 2026-09-24: + +8. **Throughput of pushes that write** (section 8). Three changes, on this + branch before the switch: + - **One flush per batch.** `Put` and `Rename` stop flushing, and + `Transport.Flush` makes a batch durable (section 3). A mirror and a + content-addressed push write batches of at most 64 files or 256 MB, and + every record waits for the flush that covers its bytes (section 4). The + full read-back runs after the batch's staged files are flushed + (section 5). + - **Several paths in flight**, set per destination by `concurrency` + (section 7), on both transports. + - **Every per-call check stays.** Checking each parent chain once per push + would have cut the sftp round trips by half, but it trusts a directory + for the rest of the push; paths in flight reach rclone's speed without + it. + Open: 1. **Crypt byte-compatibility with rclone.** This blocks cloudbox only, and is to be discussed separately. -2. **Throughput of pushes that write** (section 8). Candidates, each with its - own cost: several paths in flight, which multiplies sftp throughput by - the concurrency and overlaps local syncs, at the price of concurrent - bookkeeping in the writer; checking each parent chain once per push - instead of once per call, which halves the sftp round trips but trusts a - directory for the rest of the push; syncing a batch of staged files - together before their renames, which keeps every copy durable before it - is committed but costs a second pass over staging. Whether the branch - switches `local` and plain `sftp` destinations before any of them lands - is the maintainer's call. +2. ~~**Throughput of pushes that write.**~~ Decided on 2026-09-24: + decision 8. From 8bca689831dd267dd8106108dc3ef60edb25e988 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Fri, 25 Sep 2026 00:01:48 +0200 Subject: [PATCH 56/61] config: concurrency sets how many files a push writes at once A positive integer on every destination but kopia. On a destination rclone writes it becomes rclone's --transfers, next to --checkers from the checkers key; the native writers take it up in the next commit. --- config/config.go | 4 ++ config/destinations.go | 26 +++++++++- config/fingerprint_knobs_test.go | 52 +++++++++++++++++++ .../content/docs/reference/configuration.md | 1 + sync/artifacts_rclone.go | 8 +-- sync/fingerprint.go | 16 +++--- sync/fingerprint_test.go | 21 ++++++++ sync/naming.go | 8 +-- sync/restore_archive.go | 2 +- sync/scanback.go | 2 +- sync/sync.go | 10 ++-- sync/verify_remote.go | 4 +- 12 files changed, 129 insertions(+), 25 deletions(-) diff --git a/config/config.go b/config/config.go index 1677acf..1a7ee48 100644 --- a/config/config.go +++ b/config/config.go @@ -186,6 +186,10 @@ type Destination struct { // invocations against this destination, for providers that cap // simultaneous connections. Zero leaves rclone's default in force. Checkers int + // Concurrency is how many files a push writes at once: squirrel's own + // paths in flight on a local or plain sftp destination, rclone's + // --transfers on one rclone writes. Zero leaves the default in force. + Concurrency int // PathStyle forces path-style bucket addressing (bucket in the URL // path, not the host) for the direct S3 client that reads scan-back // ETags. Settable on s3 destinations only, for S3-compatible providers diff --git a/config/destinations.go b/config/destinations.go index a295140..603a352 100644 --- a/config/destinations.go +++ b/config/destinations.go @@ -155,6 +155,10 @@ func resolveDestination(name string, raw map[string]any) (*Destination, error) { if err != nil { return nil, err } + concurrency, err := resolveConcurrency(raw, typ) + if err != nil { + return nil, err + } pathStyle, err := resolvePathStyle(raw, typ) if err != nil { return nil, err @@ -173,7 +177,7 @@ func resolveDestination(name string, raw map[string]any) (*Destination, error) { } return &Destination{ Name: name, Type: typ, Root: root, Layout: layout, Params: params, - Crypt: crypt, HashAlgo: hashAlgo, Checkers: checkers, PathStyle: pathStyle, + Crypt: crypt, HashAlgo: hashAlgo, Checkers: checkers, Concurrency: concurrency, PathStyle: pathStyle, PackThreshold: pack.threshold, PackSize: pack.size, ZstdLevel: pack.zstdLevel, VerifyEvery: verifyEvery, }, nil @@ -320,6 +324,24 @@ func resolveCheckers(raw map[string]any, typ string, native bool) (int, error) { return int(n), nil } +// resolveConcurrency validates the optional `concurrency` key: a positive +// integer, how many files a push writes at once. Kopia drives its own +// parallelism, so the key is rejected there. +func resolveConcurrency(raw map[string]any, typ string) (int, error) { + v, ok := raw["concurrency"] + if !ok { + return 0, nil + } + if typ == "kopia" { + return 0, errors.New("concurrency sets how many files squirrel or rclone writes at once, and a kopia destination is written by kopia") + } + n, isInt := v.(int64) + if !isInt || n <= 0 { + return 0, errors.New("concurrency must be a positive integer") + } + return int(n), nil +} + // resolvePathStyle validates the optional `force_path_style` key: a // boolean confined to s3 destinations, consumed by the direct S3 ETag // client (not rendered into rclone.conf — it governs only squirrel's own @@ -603,7 +625,7 @@ func validateCryptRemoteNames(dests map[string]*Destination) error { // unknown-field check that consumes them. var universalDestKeys = []string{ "type", "root", "crypt", "layout", - "hash_algo", "checkers", "force_path_style", + "hash_algo", "checkers", "concurrency", "force_path_style", "pack_threshold", "pack_size", "zstd_level", "verify_every", } diff --git a/config/fingerprint_knobs_test.go b/config/fingerprint_knobs_test.go index a1a9166..bbea6c7 100644 --- a/config/fingerprint_knobs_test.go +++ b/config/fingerprint_knobs_test.go @@ -202,6 +202,58 @@ layout = "content-addressed" } } +// TestLoadConcurrency: every destination but kopia accepts a positive +// concurrency, native and rclone-written alike, and it stays out of +// rclone.conf. +func TestLoadConcurrency(t *testing.T) { + cfg, err := Load(writeConfig(t, ` +[destinations.usb] +type = "local" +root = "/mnt/usb" +concurrency = 2 + +[destinations.archive] +type = "sftp" +host = "host.example" +user = "u" +root = "/data" +concurrency = 16 + +[destinations.archive.crypt] +password = "pw" +`)) + if err != nil { + t.Fatalf("Load: %v", err) + } + if got := cfg.Destinations["usb"].Concurrency; got != 2 { + t.Fatalf("usb Concurrency = %d, want 2", got) + } + archive := cfg.Destinations["archive"] + if archive.Concurrency != 16 { + t.Fatalf("archive Concurrency = %d, want 16", archive.Concurrency) + } + if strings.Contains(archive.RcloneSection(), "concurrency") { + t.Fatalf("concurrency leaked into rclone.conf (it is an invocation flag):\n%s", archive.RcloneSection()) + } +} + +func TestLoadRejectsBadConcurrency(t *testing.T) { + cases := []struct{ name, body string }{ + {"zero", "type = \"local\"\nroot = \"/mnt/usb\"\nconcurrency = 0"}, + {"negative", "type = \"local\"\nroot = \"/mnt/usb\"\nconcurrency = -1"}, + {"string", "type = \"local\"\nroot = \"/mnt/usb\"\nconcurrency = \"4\""}, + {"kopia", "type = \"kopia\"\nroot = \"/repo\"\npassword = \"pw\"\nconcurrency = 4"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + _, err := Load(writeConfig(t, "[destinations.d]\n"+c.body+"\n")) + if err == nil || !strings.Contains(err.Error(), "concurrency") { + t.Fatalf("err = %v, want concurrency rejection", err) + } + }) + } +} + func TestLoadForcePathStyle(t *testing.T) { cfg, err := Load(writeConfig(t, ` [destinations.bucket] diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md index e9adeb0..f73d594 100644 --- a/docs/src/content/docs/reference/configuration.md +++ b/docs/src/content/docs/reference/configuration.md @@ -47,6 +47,7 @@ See [Hooks](/squirrel/guides/hooks/). | `type` | all | `local`, `sftp`, `s3`, `b2`, `gcs`, or `kopia`. | | `root` | all | Base path (or bucket sub-path) at the destination. | | `layout` | every type but kopia | `mirror` (default), `content-addressed`, or `packed`. | +| `concurrency` | every type but kopia | How many files a push writes at once (optional; a positive integer). On a destination squirrel writes itself the default is `4` on `local` and `8` on `sftp`, where every file in flight shares one SSH connection; lower it for a slow disk or USB bridge, or a server that answers one request at a time. On a destination rclone writes (crypt, `s3`, `b2`, `gcs`) it caps rclone's concurrent transfers (`--transfers`), whose default applies otherwise. | ### `local` diff --git a/sync/artifacts_rclone.go b/sync/artifacts_rclone.go index ecf0f53..bf44347 100644 --- a/sync/artifacts_rclone.go +++ b/sync/artifacts_rclone.go @@ -38,14 +38,14 @@ func (a *rcloneArtifacts) markers(ctx context.Context, opts Options) error { } func (a *rcloneArtifacts) exists(ctx context.Context, name string) (bool, error) { - return a.rcl.statRemoteExists(ctx, a.where(name), checkersArgs(a.dest)...) + return a.rcl.statRemoteExists(ctx, a.where(name), concurrencyArgs(a.dest)...) } // rootEmpty reports whether the destination root holds no files beyond // squirrel's markers — a wiped or repointed destination, or one whose // recorded state was cleared by `squirrel destination reset`. func (a *rcloneArtifacts) rootEmpty(ctx context.Context) (bool, error) { - return a.rcl.remoteRootEmpty(ctx, remoteSubpathURI(a.dest, ""), rootMarkerNames(a.dest), checkersArgs(a.dest)...) + return a.rcl.remoteRootEmpty(ctx, remoteSubpathURI(a.dest, ""), rootMarkerNames(a.dest), concurrencyArgs(a.dest)...) } // reconcile returns at once: rclone lands every artifact under its own @@ -74,10 +74,10 @@ func (a *rcloneArtifacts) put(ctx context.Context, _ int64, name, src string, si return nil, fmt.Errorf("%w: %s now hashes to %s, indexed as %s", errContentDrift, src, hex.EncodeToString(digest), hex.EncodeToString(sum)) } uri := a.where(name) - if err := a.rcl.copyTo(ctx, src, uri, checkersArgs(a.dest)...); err != nil { + if err := a.rcl.copyTo(ctx, src, uri, concurrencyArgs(a.dest)...); err != nil { return nil, err } - landed, err := a.rcl.statRemote(ctx, uri, checkersArgs(a.dest)...) + landed, err := a.rcl.statRemote(ctx, uri, concurrencyArgs(a.dest)...) if err != nil { return nil, fmt.Errorf("confirm %s after upload: %w", uri, err) } diff --git a/sync/fingerprint.go b/sync/fingerprint.go index 838fdb3..0638f68 100644 --- a/sync/fingerprint.go +++ b/sync/fingerprint.go @@ -105,13 +105,17 @@ func algoHashType(algo string) string { return algo } -// checkersArgs renders dest's optional concurrent-checkers cap as rclone -// argv. -func checkersArgs(dest *config.Destination) []string { - if dest.Checkers <= 0 { - return nil +// concurrencyArgs renders dest's optional caps on rclone's concurrent +// checkers and transfers as rclone argv. +func concurrencyArgs(dest *config.Destination) []string { + var args []string + if dest.Checkers > 0 { + args = append(args, "--checkers", strconv.Itoa(dest.Checkers)) } - return []string{"--checkers", strconv.Itoa(dest.Checkers)} + if dest.Concurrency > 0 { + args = append(args, "--transfers", strconv.Itoa(dest.Concurrency)) + } + return args } // underlyingDirURI addresses a destination-root directory (objects/ or diff --git a/sync/fingerprint_test.go b/sync/fingerprint_test.go index d44c1bd..3fef160 100644 --- a/sync/fingerprint_test.go +++ b/sync/fingerprint_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "os" + "slices" "strings" "testing" @@ -394,3 +395,23 @@ func TestListedNameCryptSuffix(t *testing.T) { t.Errorf("plain remote name = %q, want abc (untouched)", got) } } + +// TestConcurrencyArgs: a destination rclone writes passes checkers and +// concurrency to rclone as --checkers and --transfers, and neither when +// unset, leaving rclone's defaults. +func TestConcurrencyArgs(t *testing.T) { + cases := []struct { + dest config.Destination + want []string + }{ + {config.Destination{}, nil}, + {config.Destination{Checkers: 2}, []string{"--checkers", "2"}}, + {config.Destination{Concurrency: 6}, []string{"--transfers", "6"}}, + {config.Destination{Checkers: 2, Concurrency: 6}, []string{"--checkers", "2", "--transfers", "6"}}, + } + for _, c := range cases { + if got := concurrencyArgs(&c.dest); !slices.Equal(got, c.want) { + t.Errorf("concurrencyArgs(%+v) = %v, want %v", c.dest, got, c.want) + } + } +} diff --git a/sync/naming.go b/sync/naming.go index 5dbb544..0de0bd6 100644 --- a/sync/naming.go +++ b/sync/naming.go @@ -142,7 +142,7 @@ func (h *rcloneArtifacts) checkNamingScheme(ctx context.Context) (namingStamp, e return stampNone, nil } uri := remoteSubpathURI(h.dest, namingMarkerName) - present, err := h.rcl.statRemoteExists(ctx, uri, checkersArgs(h.dest)...) + present, err := h.rcl.statRemoteExists(ctx, uri, concurrencyArgs(h.dest)...) if err != nil { return stampNone, fmt.Errorf("destination %q: stat %s at %s: %w", h.dest.Name, namingMarkerName, uri, err) } @@ -160,7 +160,7 @@ func (h *rcloneArtifacts) checkNamingScheme(ctx context.Context) (namingStamp, e // what it always did. func (h *rcloneArtifacts) classifyUnmarkedRoot(ctx context.Context) (namingStamp, error) { rootURI := underlyingDirURI(h.dest, "") - empty, err := h.rcl.remoteRootEmpty(ctx, rootURI, nil, checkersArgs(h.dest)...) + empty, err := h.rcl.remoteRootEmpty(ctx, rootURI, nil, concurrencyArgs(h.dest)...) if err != nil { return stampNone, fmt.Errorf("destination %q: list %s: %w", h.dest.Name, rootURI, err) } @@ -180,7 +180,7 @@ func (h *rcloneArtifacts) classifyUnmarkedRoot(ctx context.Context) (namingStamp func (h *rcloneArtifacts) holdsKeyedVolumeMarker(ctx context.Context) (bool, error) { uri := remoteSubpathURI(h.dest, path.Join(h.names().volumeDir(h.vol.Name), volmark.MarkerName)) - present, err := h.rcl.statRemoteExists(ctx, uri, checkersArgs(h.dest)...) + present, err := h.rcl.statRemoteExists(ctx, uri, concurrencyArgs(h.dest)...) if err != nil { return false, fmt.Errorf("destination %q: stat %s at %s: %w", h.dest.Name, volmark.MarkerName, uri, err) } @@ -190,7 +190,7 @@ func (h *rcloneArtifacts) holdsKeyedVolumeMarker(ctx context.Context) (bool, err // validateNamingScheme refuses the marker at uri when it will not parse or // records a scheme this binary does not write. func validateNamingScheme(ctx context.Context, rcl *Rclone, dest *config.Destination, uri string) error { - data, err := rcl.catRemote(ctx, uri, checkersArgs(dest)...) + data, err := rcl.catRemote(ctx, uri, concurrencyArgs(dest)...) if err != nil { return fmt.Errorf("destination %q: read %s at %s — a root written under other crypt passwords cannot be read with these: %w", dest.Name, namingMarkerName, uri, err) } diff --git a/sync/restore_archive.go b/sync/restore_archive.go index c8d23a1..c3a7c11 100644 --- a/sync/restore_archive.go +++ b/sync/restore_archive.go @@ -72,7 +72,7 @@ func restoreArchive(ctx context.Context, s *store.Store, rcl *Rclone, vol *confi func archiveFetcher(ctx context.Context, rcl *Rclone, dest *config.Destination, dryRun bool) (func(context.Context, string, string) error, func(), error) { if !dest.Native() { return func(ctx context.Context, name, localPath string) error { - return rcl.copyTo(ctx, remoteSubpathURI(dest, name), localPath, checkersArgs(dest)...) + return rcl.copyTo(ctx, remoteSubpathURI(dest, name), localPath, concurrencyArgs(dest)...) }, func() {}, nil } if dryRun { diff --git a/sync/scanback.go b/sync/scanback.go index 363584f..c055668 100644 --- a/sync/scanback.go +++ b/sync/scanback.go @@ -53,7 +53,7 @@ func (h *rcloneArtifacts) captureScanBackRclone(ctx context.Context, rep *Report dirURI := underlyingDirURI(h.dest, dirName) types := captureHashTypes(h.dest) for batch := range slices.Chunk(targets, fingerprintBatchSize) { - extra := checkersArgs(h.dest) + extra := concurrencyArgs(h.dest) for _, t := range batch { extra = append(extra, "--include", listedRemoteName(h.dest, t.name)) } diff --git a/sync/sync.go b/sync/sync.go index 167abb9..2951e5f 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -653,7 +653,7 @@ func ensureRemoteDestinationMarker(ctx context.Context, s *store.Store, rcl *Rcl // A stat that fails for any reason other than a definite absence // refuses without writing — a reachability blip must never be read // as a fresh root. - present, err := rcl.statRemoteExists(ctx, markerURI, checkersArgs(dest)...) + present, err := rcl.statRemoteExists(ctx, markerURI, concurrencyArgs(dest)...) if err != nil { return fmt.Errorf("destination %q: stat %s at %s: %w", dest.Name, volmark.MarkerName, markerURI, err) } @@ -665,7 +665,7 @@ func ensureRemoteDestinationMarker(ctx context.Context, s *store.Store, rcl *Rcl } // Present: read and validate. A volume mismatch or a corrupt/empty // marker always refuses and is never overwritten, even under --init. - data, err := rcl.catRemote(ctx, markerURI, checkersArgs(dest)...) + data, err := rcl.catRemote(ctx, markerURI, concurrencyArgs(dest)...) if err != nil { return fmt.Errorf("destination %q: read %s at %s: %w", dest.Name, volmark.MarkerName, markerURI, err) } @@ -713,7 +713,7 @@ func writeRemoteMarker(ctx context.Context, s *store.Store, rcl *Rclone, dest *c if err := tmp.Close(); err != nil { return fmt.Errorf("destination %q: stage marker: %w", dest.Name, err) } - if err := rcl.copyTo(ctx, tmp.Name(), markerURI, checkersArgs(dest)...); err != nil { + if err := rcl.copyTo(ctx, tmp.Name(), markerURI, concurrencyArgs(dest)...); err != nil { return fmt.Errorf("destination %q: write %s to %s: %w", dest.Name, volmark.MarkerName, markerURI, err) } return nil @@ -791,7 +791,7 @@ func buildRcloneArgs(vol *config.Volume, dest *config.Destination, runID int64, // the name is reserved on every layout. "--filter", "- /" + StagingDirName + "/**", } - args = append(args, checkersArgs(dest)...) + args = append(args, concurrencyArgs(dest)...) if !EffectiveShallow(dest, opts.Shallow) { args = append(args, "--checksum") } @@ -1148,7 +1148,7 @@ func buildRestoreArgs(vol *config.Volume, dest *config.Destination, runID int64, args = append(args, "--filter", "- /"+IndexDirName+"/**") args = append(args, "--filter", "- /"+StagingDirName+"/**") } - args = append(args, checkersArgs(dest)...) + args = append(args, concurrencyArgs(dest)...) if !EffectiveShallow(dest, opts.Shallow) { args = append(args, "--checksum") } diff --git a/sync/verify_remote.go b/sync/verify_remote.go index cc9a6ff..fc21cc9 100644 --- a/sync/verify_remote.go +++ b/sync/verify_remote.go @@ -394,7 +394,7 @@ func readObjectChecksums(ctx context.Context, rcl *Rclone, dest *config.Destinat } return byName, nil } - entries, err := rcl.listHashes(ctx, underlyingDirURI(dest, ObjectsDirName), verifyObjectHashTypes(dest, rows), checkersArgs(dest)...) + entries, err := rcl.listHashes(ctx, underlyingDirURI(dest, ObjectsDirName), verifyObjectHashTypes(dest, rows), concurrencyArgs(dest)...) if err != nil { return nil, err } @@ -510,7 +510,7 @@ func readPackChecksums(ctx context.Context, rcl *Rclone, dest *config.Destinatio } return byName, nil } - entries, err := rcl.listHashes(ctx, underlyingDirURI(dest, PacksDirName), verifyPackHashTypes(dest, packs), checkersArgs(dest)...) + entries, err := rcl.listHashes(ctx, underlyingDirURI(dest, PacksDirName), verifyPackHashTypes(dest, packs), concurrencyArgs(dest)...) if err != nil { return nil, err } From 650288e5cbe9f91878789db6467aac4e44db3813 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Fri, 25 Sep 2026 00:05:07 +0200 Subject: [PATCH 57/61] sync: flush once per batch and write several paths at once Put and Rename no longer flush; Transport.Flush makes everything before it durable. On macOS each file gets a plain fsync and one F_FULLFSYNC covers the batch; on Linux the batch's fsyncs run together at the flush. A mirror push and a content-addressed push now land batches of at most 64 files or 256 MB, concurrency paths at a time: stage, flush, read back in full, displace, flush, record displaced, commit, flush, record live. No record claims bytes before the flush that covers them, and a staged file's bytes are flushed before it is renamed onto its name. The marker, the ride-along snapshot and the receipt flush the same way. The fault transport gains a power-cut mode that takes back what no Flush covered, or keeps every name without its bytes. The crash suites run one path at a time and gain power cuts at every call, a first push is cut at every call too, and the model test runs with paths in flight and random power cuts. --- docs/src/content/docs/guides/offloading.md | 6 +- docs/src/content/docs/guides/verification.md | 4 +- .../content/docs/layouts/content-addressed.md | 14 +- docs/src/content/docs/layouts/mirror.md | 30 +- sync/artifacts.go | 35 +- sync/artifacts_rclone.go | 23 +- sync/artifacts_transport.go | 121 ++++- sync/batch.go | 79 +++ sync/batch_test.go | 65 +++ sync/content_addressed.go | 88 ++-- sync/content_native_test.go | 14 + sync/crash_every_call_test.go | 88 +++- sync/destination_marker.go | 20 +- sync/destination_root.go | 5 + sync/mirror.go | 8 +- sync/mirror_first_push_test.go | 47 ++ sync/mirror_fold.go | 4 +- sync/mirror_model_test.go | 27 +- sync/mirror_test.go | 14 + sync/mirror_write.go | 450 +++++++++++++----- sync/packed.go | 2 +- sync/snapshot.go | 2 +- sync/transport.go | 8 +- sync/transport_fault_test.go | 119 ++++- sync/transport_local.go | 113 ++++- sync/transport_local_darwin.go | 29 ++ sync/transport_local_linux.go | 21 + sync/transport_local_other.go | 14 + sync/transport_sftp.go | 5 + sync/transport_stall.go | 42 +- 30 files changed, 1243 insertions(+), 254 deletions(-) create mode 100644 sync/batch.go create mode 100644 sync/batch_test.go diff --git a/docs/src/content/docs/guides/offloading.md b/docs/src/content/docs/guides/offloading.md index 78cf746..9e55ac8 100644 --- a/docs/src/content/docs/guides/offloading.md +++ b/docs/src/content/docs/guides/offloading.md @@ -86,9 +86,9 @@ content-verified and relays to peers that way, so a hub's certified archive can open an edge machine's gate. A mirror on a `local` disk earns the same upgrade at push time: every copy is -read back through BLAKE3 before it is committed, so once every file of the -volume has such a copy, the push itself advances the component as -`fingerprint-verified`. A copy a verify pass later finds gone or changed stops +flushed to the disk, then read back through BLAKE3 before it is committed, so +once every file of the volume has such a copy, the push itself advances the +component as `fingerprint-verified`. A copy a verify pass later finds gone or changed stops counting for its file until the next push writes it again. The practical consequence: on a cold-archive target whose fingerprints stay diff --git a/docs/src/content/docs/guides/verification.md b/docs/src/content/docs/guides/verification.md index ee155f1..cf5a5ab 100644 --- a/docs/src/content/docs/guides/verification.md +++ b/docs/src/content/docs/guides/verification.md @@ -160,8 +160,8 @@ file's own copy until the next push writes the lost one again. The next push wri there, with a warning; the copy that was found keeps its place in history if the push has to move it aside. -A local mirror earns its fingerprints at push time: every copy is read back -through BLAKE3 before it is committed. An sftp mirror is checked by size and +A local mirror earns its fingerprints at push time: every copy is flushed to the +disk, then read back through BLAKE3 before it is committed. An sftp mirror is checked by size and mtime alone, and never gates offload. ## Related knobs diff --git a/docs/src/content/docs/layouts/content-addressed.md b/docs/src/content/docs/layouts/content-addressed.md index 1d0b119..44f8a02 100644 --- a/docs/src/content/docs/layouts/content-addressed.md +++ b/docs/src/content/docs/layouts/content-addressed.md @@ -44,16 +44,20 @@ uploads once. ## How it is written On a `local` disk, and on an `sftp` server without `crypt`, squirrel writes the -destination itself, without rclone. Each object, and each manifest segment: +destination itself, without rclone. Objects land in batches of up to 64, +several at once ([`concurrency`](/squirrel/reference/configuration/#common-keys)); +a manifest segment lands alone. Each: 1. streams into `/.squirrel-staging/run-/` while BLAKE3 hashes the - bytes sent, and is refused if they no longer match the index; + bytes sent, and is refused if they no longer match the index; the batch is + then flushed to stable storage; 2. is confirmed before it gets its name: read back through BLAKE3 on a local disk, hashed by the server's `hash_algo` command (`sha256sum` by default) on - sftp. A match is recorded as the object's fingerprint right away; + sftp. A match becomes the object's fingerprint; 3. is renamed onto its name. A file already at that name is never replaced: - squirrel checks that it holds the right bytes and records it, or fails the - object. + squirrel checks that it holds the right bytes, or fails the object; +4. is recorded, with its fingerprint, once a second flush has made the batch's + renames durable. A server that runs no programs takes every object all the same, but fingerprints nothing: those objects stay pending, with a warning, and the diff --git a/docs/src/content/docs/layouts/mirror.md b/docs/src/content/docs/layouts/mirror.md index 13f0a2b..8b038f2 100644 --- a/docs/src/content/docs/layouts/mirror.md +++ b/docs/src/content/docs/layouts/mirror.md @@ -26,18 +26,23 @@ On a `local` destination, and on an `sftp` destination without [crypt](/squirrel/layouts/encrypted/), squirrel writes the mirror itself: a *native* mirror. A push plans from the index: it sends the changes recorded since the destination's last confirmed -run, not what a fresh walk of the disk finds. For each changed path it: - -1. streams the file into `.squirrel-staging/run-/`, hashing the bytes as they - go, and refuses the path if they no longer match the index; -2. on a `local` disk, reads the staged copy back through BLAKE3, past the page - cache where the system allows, and refuses the path if the disk returns +run, not what a fresh walk of the disk finds. It writes the changed paths in +batches of up to 64 files, several at once +([`concurrency`](/squirrel/reference/configuration/#common-keys)). For each +batch it: + +1. streams every file into `.squirrel-staging/run-/`, hashing the bytes as + they go, and refuses a path if they no longer match the index; then it + flushes the batch to stable storage; +2. on a `local` disk, reads every staged copy back through BLAKE3, past the + page cache where the system allows, and refuses a path if the disk returns other bytes; -3. moves whatever the path holds into `.squirrel-history/run-/`; -4. renames the staged copy onto the path. The rename never replaces a file. +3. moves whatever each path holds into `.squirrel-history/run-/`; +4. renames each staged copy onto its path. The rename never replaces a file. -squirrel records each move before making it, so the next push finishes or -withdraws whatever a crashed or unplugged push left half done. Every successful +squirrel records each move before making it, and confirms it only once a flush +has made it durable, so the next push finishes or withdraws whatever a crashed +or unplugged push, or a power cut, left half done. Every successful push leaves a **receipt** at `.squirrel-index/run-`: the run's changes in the [manifest segment format](/squirrel/reference/formats/), so the mirror can be checked without the index. A push that finds no receipt for the last success it @@ -96,8 +101,9 @@ A native mirror push hashes every file with BLAKE3 as it streams out and confirms each written path's size and mtime. What else backs it depends on where the mirror lives: -- **On a `local` disk**, every copy is read back through BLAKE3 before it is - committed, and the match is recorded as the copy's fingerprint. Once every +- **On a `local` disk**, every copy is flushed to the disk, then read back in + full through BLAKE3 before it is committed, and the match is recorded as the + copy's fingerprint. Once every file of the volume has such a copy, the run advances the destination's durability evidence as `fingerprint-verified`. A local mirror can therefore be named in [`offload_requires`](/squirrel/guides/offloading/). diff --git a/sync/artifacts.go b/sync/artifacts.go index d9f1740..b74859c 100644 --- a/sync/artifacts.go +++ b/sync/artifacts.go @@ -24,11 +24,13 @@ type artifactStore interface { // reconcile clears what finished pushes left in flight, once at push // start. reconcile(ctx context.Context, rep *Report, runID int64) error - // put lands the local file src at name whole, and confirms it landed: - // its size, and bytes whose BLAKE3 is sum — errContentDrift when src - // no longer hashes to sum. It returns the fingerprint the landing - // already confirmed, or nil when capture must read one later. - put(ctx context.Context, runID int64, name, src string, size int64, sum []byte) (*remoteChecksum, error) + // putAll lands every artifact whole, confirms each landed — its size, + // and bytes whose BLAKE3 is its sum: errContentDrift when its source + // no longer hashes to it — and returns once each has landed durably or + // failed, so the caller may record what landed. Each result carries + // the fingerprint the landing already confirmed, or nil when capture + // must read one later; results follow items. + putAll(ctx context.Context, runID int64, items []artifactPut) []artifactResult // capture fills the fingerprints put left pending for this run's // artifacts under dir (ObjectsDirName or PacksDirName). capture(ctx context.Context, rep *Report, dir string, targets []captureTarget) @@ -41,6 +43,27 @@ type artifactStore interface { close() } +// artifactPut is one artifact to land: the local file src at name, size +// bytes whose BLAKE3 is sum. +type artifactPut struct { + name, src string + size int64 + sum []byte +} + +// artifactResult is how one artifact landed: the fingerprint the landing +// confirmed, if any, or why it failed. +type artifactResult struct { + fingerprint *remoteChecksum + err error +} + +// putArtifact lands one artifact through art. +func putArtifact(ctx context.Context, art artifactStore, runID int64, item artifactPut) (*remoteChecksum, error) { + r := art.putAll(ctx, runID, []artifactPut{item})[0] + return r.fingerprint, r.err +} + // putBytes lands body at name through art, staged in a temporary file. // what names the artifact in error messages. func putBytes(ctx context.Context, art artifactStore, runID int64, name string, body []byte, what string) error { @@ -57,7 +80,7 @@ func putBytes(ctx context.Context, art artifactStore, runID int64, name string, return fmt.Errorf("close %s: %w", what, err) } sum := blake3.Sum256(body) - if _, err := art.put(ctx, runID, name, tmp.Name(), int64(len(body)), sum[:]); err != nil { + if _, err := putArtifact(ctx, art, runID, artifactPut{name: name, src: tmp.Name(), size: int64(len(body)), sum: sum[:]}); err != nil { return fmt.Errorf("upload %s to %s: %w", what, art.where(name), err) } return nil diff --git a/sync/artifacts_rclone.go b/sync/artifacts_rclone.go index bf44347..732ecdf 100644 --- a/sync/artifacts_rclone.go +++ b/sync/artifacts_rclone.go @@ -52,6 +52,15 @@ func (a *rcloneArtifacts) rootEmpty(ctx context.Context) (bool, error) { // name, and squirrel records it only after it landed. func (a *rcloneArtifacts) reconcile(context.Context, *Report, int64) error { return nil } +// putAll copies the artifacts one after another. +func (a *rcloneArtifacts) putAll(ctx context.Context, _ int64, items []artifactPut) []artifactResult { + out := make([]artifactResult, len(items)) + for i, it := range items { + out[i].err = a.put(ctx, it.name, it.src, it.size, it.sum) + } + return out +} + // put re-hashes src immediately before the transfer and refuses // (errContentDrift) when the digest no longer matches sum, catching a // size+mtime-preserving in-place edit that a metadata stat would pass. The @@ -65,26 +74,26 @@ func (a *rcloneArtifacts) reconcile(context.Context, *Report, int64) error { ret // span, and the scan-back fingerprint pass (#109) re-reads the landed // object to upgrade the durability vector, catching any byte that slipped // through before the object is treated as content-verified. -func (a *rcloneArtifacts) put(ctx context.Context, _ int64, name, src string, size int64, sum []byte) (*remoteChecksum, error) { +func (a *rcloneArtifacts) put(ctx context.Context, name, src string, size int64, sum []byte) error { digest, err := hashLocalFile(src) if err != nil { - return nil, fmt.Errorf("re-hash %s before upload: %w", src, err) + return fmt.Errorf("re-hash %s before upload: %w", src, err) } if !bytes.Equal(digest, sum) { - return nil, fmt.Errorf("%w: %s now hashes to %s, indexed as %s", errContentDrift, src, hex.EncodeToString(digest), hex.EncodeToString(sum)) + return fmt.Errorf("%w: %s now hashes to %s, indexed as %s", errContentDrift, src, hex.EncodeToString(digest), hex.EncodeToString(sum)) } uri := a.where(name) if err := a.rcl.copyTo(ctx, src, uri, concurrencyArgs(a.dest)...); err != nil { - return nil, err + return err } landed, err := a.rcl.statRemote(ctx, uri, concurrencyArgs(a.dest)...) if err != nil { - return nil, fmt.Errorf("confirm %s after upload: %w", uri, err) + return fmt.Errorf("confirm %s after upload: %w", uri, err) } if landed != size { - return nil, fmt.Errorf("%s landed with size %d, want %d", uri, landed, size) + return fmt.Errorf("%s landed with size %d, want %d", uri, landed, size) } - return nil, nil + return nil } func (a *rcloneArtifacts) capture(ctx context.Context, rep *Report, dir string, targets []captureTarget) { diff --git a/sync/artifacts_transport.go b/sync/artifacts_transport.go index 356c7d9..5024334 100644 --- a/sync/artifacts_transport.go +++ b/sync/artifacts_transport.go @@ -10,6 +10,8 @@ import ( "io" "io/fs" "os" + gosync "sync" + "sync/atomic" "time" "github.com/zeebo/blake3" @@ -20,11 +22,14 @@ import ( // transportArtifacts is an artifact store squirrel writes itself: a // content-addressed or packed destination on a local disk, or on an sftp // server without crypt. Each artifact is staged in the volume's -// .squirrel-staging/run-/ while BLAKE3 hashes the bytes sent, read -// back — through BLAKE3 on a local disk, through the server's hash command -// on sftp — and renamed onto its name, so it lands whole or not at all. +// .squirrel-staging/run-/ while BLAKE3 hashes the bytes sent, flushed, +// read back — through BLAKE3 on a local disk, through the server's hash +// command on sftp — and renamed onto its name, so it lands whole or not at +// all. Artifacts land a batch at a time, several in flight. type transportArtifacts struct { *destinationRoot + + mu gosync.Mutex // noServerHash is why the sftp server fingerprinted nothing this push, // once a landing found out. noServerHash error @@ -73,25 +78,107 @@ func (a *transportArtifacts) reconcile(ctx context.Context, rep *Report, runID i return a.clearFinishedStaging(ctx, rep, tr) } -func (a *transportArtifacts) put(ctx context.Context, runID int64, name, src string, size int64, sum []byte) (*remoteChecksum, error) { +// artifactLanding is one artifact on its way through putAll. +type artifactLanding struct { + artifactPut + staged string + // sent is the server-side hash of the bytes sent, "" without one. + sent string + res *artifactResult +} + +// putAll takes the artifacts through the steps of a landing, each for all +// of them before the next: stage, flush, confirm, rename, flush. An +// artifact whose step fails drops out. +func (a *transportArtifacts) putAll(ctx context.Context, runID int64, items []artifactPut) []artifactResult { + out := make([]artifactResult, len(items)) tr, err := a.root(ctx, runID) if err != nil { - return nil, err + for i := range out { + out[i].err = err + } + return out } - staged := stagingName(a.volumeDir, runID, stagingKey(name)) - sent, err := a.stage(ctx, tr, staged, src, size, sum) - if err != nil { - return nil, err + ls := make([]*artifactLanding, len(items)) + for i, it := range items { + ls[i] = &artifactLanding{artifactPut: it, staged: stagingName(a.volumeDir, runID, stagingKey(it.name)), res: &out[i]} } - fingerprint, err := a.confirm(ctx, tr, staged, sum, sent, true) - if err != nil { - return nil, err + b := artifactBatch{a: a, tr: tr, n: pushConcurrency(a.dest)} + b.each(ctx, ls, b.stage) + b.flush(ctx, ls, "flush the staged artifacts") + b.each(ctx, ls, b.confirmStaged) + b.each(ctx, ls, b.rename) + b.flush(ctx, ls, "flush the landed artifacts") + return out +} + +// artifactBatch runs the steps of putAll over one batch. +type artifactBatch struct { + a *transportArtifacts + tr transport + n int + stalled atomic.Bool +} + +// each runs step for every artifact still on its way, n in flight; an +// artifact whose step fails drops out, and a stall starts no more. +func (b *artifactBatch) each(ctx context.Context, ls []*artifactLanding, step func(context.Context, *artifactLanding) error) { + inFlight(ctx, b.n, pendingArtifacts(ls), b.stalled.Load, func(l *artifactLanding) { + if err := step(ctx, l); err != nil { + l.res.err = err + if errors.Is(err, errTransportStalled) { + b.stalled.Store(true) + } + } + }) +} + +// flush makes the batch's last step durable; a flush that fails fails +// every artifact still on its way. +func (b *artifactBatch) flush(ctx context.Context, ls []*artifactLanding, what string) { + pending := pendingArtifacts(ls) + if len(pending) == 0 || b.stalled.Load() { + return } - err = tr.Rename(ctx, staged, name) - if errors.Is(err, fs.ErrExist) { - return a.confirm(ctx, tr, name, sum, sent, false) + if err := b.tr.Flush(ctx); err != nil { + for _, l := range pending { + l.res.err = fmt.Errorf("%s: %w", what, err) + } + } +} + +func pendingArtifacts(ls []*artifactLanding) []*artifactLanding { + var out []*artifactLanding + for _, l := range ls { + if l.res.err == nil { + out = append(out, l) + } + } + return out +} + +func (b *artifactBatch) stage(ctx context.Context, l *artifactLanding) error { + sent, err := b.a.stage(ctx, b.tr, l.staged, l.src, l.size, l.sum) + l.sent = sent + return err +} + +func (b *artifactBatch) confirmStaged(ctx context.Context, l *artifactLanding) error { + fingerprint, err := b.a.confirm(ctx, b.tr, l.staged, l.sum, l.sent, true) + l.res.fingerprint = fingerprint + return err +} + +// rename moves the staged artifact onto its name. A name that already +// holds a file is confirmed instead, and never replaced. +func (b *artifactBatch) rename(ctx context.Context, l *artifactLanding) error { + err := b.tr.Rename(ctx, l.staged, l.name) + if !errors.Is(err, fs.ErrExist) { + return err } - return fingerprint, err + fingerprint, err := b.a.confirm(ctx, b.tr, l.name, l.sum, l.sent, false) + l.res.fingerprint = fingerprint + return err } // stage streams src into staged, hashing the bytes sent with BLAKE3 and, @@ -145,7 +232,9 @@ func (a *transportArtifacts) confirm(ctx context.Context, tr transport, name str case !errors.Is(err, errNoServerHash): return nil, fmt.Errorf("hash %s on the server: %w", name, err) } + a.mu.Lock() a.noServerHash = err + a.mu.Unlock() if staged { return nil, nil } diff --git a/sync/batch.go b/sync/batch.go new file mode 100644 index 0000000..5c9ac52 --- /dev/null +++ b/sync/batch.go @@ -0,0 +1,79 @@ +package sync + +import ( + "context" + gosync "sync" + + "github.com/mbertschler/squirrel/config" +) + +// A native push writes in batches: every file of a batch is staged before +// one Flush makes the batch durable, and every record waits for the flush +// that covers its bytes. A batch holds at most batchMaxFiles files and +// batchMaxBytes bytes; a larger file goes alone. +const ( + batchMaxFiles = 64 + batchMaxBytes = 256 << 20 +) + +// Default paths in flight when a destination sets no concurrency: a local +// disk gains nothing past a few, a remote link hides its round trips +// behind more. +const ( + defaultLocalConcurrency = 4 + defaultSFTPConcurrency = 8 +) + +// pushConcurrency is how many files a push writes to dest at once. +func pushConcurrency(dest *config.Destination) int { + switch { + case dest.Concurrency > 0: + return dest.Concurrency + case dest.Type == "sftp": + return defaultSFTPConcurrency + default: + return defaultLocalConcurrency + } +} + +// batches splits items, in order, into runs of at most batchMaxFiles items +// and batchMaxBytes bytes by size. +func batches[T any](items []T, size func(T) int64) [][]T { + var out [][]T + var cur []T + var bytes int64 + for _, it := range items { + n := size(it) + if len(cur) > 0 && (len(cur) == batchMaxFiles || bytes+n > batchMaxBytes) { + out = append(out, cur) + cur, bytes = nil, 0 + } + cur = append(cur, it) + bytes += n + } + if len(cur) > 0 { + out = append(out, cur) + } + return out +} + +// inFlight calls fn for each item, at most n at a time and in order of +// starting, and returns once every call has returned. It starts no call +// once ctx is done or stop reports true. With n of 1 the calls run one +// after another, in order. +func inFlight[T any](ctx context.Context, n int, items []T, stop func() bool, fn func(T)) { + slots := make(chan struct{}, max(n, 1)) + var wg gosync.WaitGroup + for _, it := range items { + slots <- struct{}{} + if ctx.Err() != nil || stop() { + <-slots + break + } + wg.Go(func() { + defer func() { <-slots }() + fn(it) + }) + } + wg.Wait() +} diff --git a/sync/batch_test.go b/sync/batch_test.go new file mode 100644 index 0000000..4b447cd --- /dev/null +++ b/sync/batch_test.go @@ -0,0 +1,65 @@ +package sync + +import ( + "context" + "sync/atomic" + "testing" + "time" +) + +// TestBatches: a batch closes at batchMaxFiles items or before the item +// that would take it past batchMaxBytes; an item larger than that goes +// alone. +func TestBatches(t *testing.T) { + size := func(n int64) int64 { return n } + cases := []struct { + name string + items []int64 + want []int + }{ + {"none", nil, nil}, + {"by count", make([]int64, batchMaxFiles+1), []int{batchMaxFiles, 1}}, + {"by bytes", []int64{batchMaxBytes / 2, batchMaxBytes / 2, 1}, []int{2, 1}}, + {"too large alone", []int64{1, batchMaxBytes + 1, 1}, []int{1, 1, 1}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + var got []int + for _, b := range batches(c.items, size) { + got = append(got, len(b)) + } + if len(got) != len(c.want) { + t.Fatalf("batch sizes = %v, want %v", got, c.want) + } + for i := range got { + if got[i] != c.want[i] { + t.Fatalf("batch sizes = %v, want %v", got, c.want) + } + } + }) + } +} + +// TestInFlightBoundsTheCallsAtOnce: inFlight never runs more than n calls +// at once, runs every call, and starts none once stop reports true. +func TestInFlightBoundsTheCallsAtOnce(t *testing.T) { + var running, peak, calls atomic.Int64 + inFlight(context.Background(), 3, make([]int, 20), func() bool { return false }, func(int) { + now := running.Add(1) + for p := peak.Load(); now > p && !peak.CompareAndSwap(p, now); p = peak.Load() { + } + time.Sleep(time.Millisecond) + running.Add(-1) + calls.Add(1) + }) + if calls.Load() != 20 || peak.Load() > 3 { + t.Fatalf("calls = %d, peak = %d; want 20 calls, at most 3 at once", calls.Load(), peak.Load()) + } + var started atomic.Int64 + inFlight(context.Background(), 1, make([]int, 5), func() bool { return started.Load() == 2 }, func(int) { + started.Add(1) + }) + if started.Load() != 2 { + t.Fatalf("started %d calls, want 2 before stop", started.Load()) + } +} diff --git a/sync/content_addressed.go b/sync/content_addressed.go index 87674d2..b9d7c59 100644 --- a/sync/content_addressed.go +++ b/sync/content_addressed.go @@ -262,28 +262,32 @@ func (h *contentPusher) uploadObjects(ctx context.Context, rep *Report, runID in rep.RcloneResult.Checked += ops.recorded var pending []store.PathDelta var drifted int - for _, d := range ops.needed { - fingerprinted, err := h.uploadOneObject(ctx, runID, d) - if err != nil { - if errors.Is(err, errContentDrift) { + for _, batch := range batches(ops.needed, func(d store.PathDelta) int64 { return d.SizeBytes }) { + if err := ctx.Err(); err != nil { + return err + } + for i, res := range h.uploadBatch(ctx, runID, batch) { + d := batch[i] + switch { + case errors.Is(res.err, errContentDrift): drifted++ - rep.Warnings = append(rep.Warnings, err.Error()) + rep.Warnings = append(rep.Warnings, res.err.Error()) continue + case res.err != nil: + rep.RcloneResult.Errors++ + if int64(len(rep.RcloneResult.FailedFiles)) < maxFailedFiles { + rep.RcloneResult.FailedFiles = append(rep.RcloneResult.FailedFiles, + FailedFile{Object: d.Path, Message: res.err.Error()}) + } + continue + case res.fingerprint != nil: + rep.Fingerprints++ + default: + pending = append(pending, d) } - rep.RcloneResult.Errors++ - if int64(len(rep.RcloneResult.FailedFiles)) < maxFailedFiles { - rep.RcloneResult.FailedFiles = append(rep.RcloneResult.FailedFiles, - FailedFile{Object: d.Path, Message: err.Error()}) - } - continue - } - if fingerprinted { - rep.Fingerprints++ - } else { - pending = append(pending, d) + rep.RcloneResult.Transferred++ + rep.RcloneResult.Bytes += d.SizeBytes } - rep.RcloneResult.Transferred++ - rep.RcloneResult.Bytes += d.SizeBytes } h.captureFingerprints(ctx, rep, pending) if rep.RcloneResult.Errors > 0 { @@ -342,24 +346,36 @@ func plannedUploads(delta []store.PathDelta) []store.PathDelta { // the run so the watermark holds and the object is re-offered next run. var errContentDrift = errors.New("source content drifted from its indexed hash") -// uploadOneObject lands one content object and records the upload, with -// its fingerprint when the landing already confirmed one. It guards the -// content-addressed invariant — the bytes stored under a hash must be the -// bytes that produced it: the artifact store refuses a source that no -// longer hashes to the indexed hash (errContentDrift), catching a -// size+mtime-preserving in-place edit that a metadata stat would pass. The -// upload record is written only after the landing was confirmed, so a -// recorded hash is always a confirmed one; a crash in between lands the -// same bytes again on the next run. -func (h *contentPusher) uploadOneObject(ctx context.Context, runID int64, d store.PathDelta) (bool, error) { - src := filepath.Join(h.vol.Path, filepath.FromSlash(d.Path)) - cs, err := h.art.put(ctx, runID, h.objectName(d.Blake3), src, d.SizeBytes, d.Blake3) - if errors.Is(err, errContentDrift) { - return false, fmt.Errorf("%s: %w — run `squirrel index %s` and sync again", d.Path, err, h.vol.Name) +// uploadBatch lands one batch of content objects and records each upload +// that landed, with its fingerprint when the landing already confirmed +// one. It guards the content-addressed invariant — the bytes stored under +// a hash must be the bytes that produced it: the artifact store refuses a +// source that no longer hashes to the indexed hash (errContentDrift), +// catching a size+mtime-preserving in-place edit that a metadata stat +// would pass. An upload is recorded only once the store returned its +// landing confirmed and durable, so a recorded hash is always a confirmed +// one; a crash in between lands the same bytes again on the next run. +func (h *contentPusher) uploadBatch(ctx context.Context, runID int64, batch []store.PathDelta) []artifactResult { + items := make([]artifactPut, len(batch)) + for i, d := range batch { + items[i] = artifactPut{name: h.objectName(d.Blake3), src: filepath.Join(h.vol.Path, filepath.FromSlash(d.Path)), size: d.SizeBytes, sum: d.Blake3} } - if err != nil { - return false, err + results := h.art.putAll(ctx, runID, items) + for i, d := range batch { + res := &results[i] + if errors.Is(res.err, errContentDrift) { + res.err = fmt.Errorf("%s: %w — run `squirrel index %s` and sync again", d.Path, res.err, h.vol.Name) + } + if res.err == nil { + res.err = h.recordObject(ctx, runID, d, res.fingerprint) + } } + return results +} + +// recordObject records the upload of d's content, with the fingerprint +// its landing confirmed, if any. +func (h *contentPusher) recordObject(ctx context.Context, runID int64, d store.PathDelta, cs *remoteChecksum) error { obj := store.RemoteObject{ContentID: d.ContentID, Destination: h.dest.Name, UploadedRunID: runID} if cs != nil { obj.ChecksumAlgo = sql.NullString{String: cs.Algo, Valid: true} @@ -367,9 +383,9 @@ func (h *contentPusher) uploadOneObject(ctx context.Context, runID int64, d stor obj.VerifiedAtNs = sql.NullInt64{Int64: store.NowNs(), Valid: true} } if err := h.store.InsertRemoteObject(ctx, obj); err != nil { - return false, fmt.Errorf("record upload of %s: %w", hex.EncodeToString(d.Blake3), err) + return fmt.Errorf("record upload of %s: %w", hex.EncodeToString(d.Blake3), err) } - return cs != nil, nil + return nil } // hashLocalFile streams the file at path through BLAKE3 and returns the diff --git a/sync/content_native_test.go b/sync/content_native_test.go index 853b852..801e13f 100644 --- a/sync/content_native_test.go +++ b/sync/content_native_test.go @@ -130,6 +130,20 @@ func (f *nativeContentFixture) pushCrashing(t *testing.T, crashAt func(transport }) } +// pushCuttingPower runs one push that loses power at the first call +// crashAt selects, before or after it as mode says, keeping the oldest +// keep(n) of the n calls no Flush covered. +func (f *nativeContentFixture) pushCuttingPower(t *testing.T, crashAt func(transportCall) bool, mode crashMode, keep func(int) int) (Report, error) { + t.Helper() + return f.pushVia(t, func(tr transport) transport { + return &faultTransport{transport: tr, crashAt: crashAt, mode: mode, powerCut: true, keep: keep} + }) +} + +// oneAtATime makes the fixture's pushes land one artifact at a time, so +// their transport calls come in the same order on every push. +func (f *nativeContentFixture) oneAtATime() { f.pair.Destination.Concurrency = 1 } + // pushVia runs one push through wrap's transport. func (f *nativeContentFixture) pushVia(t *testing.T, wrap func(transport) transport) (Report, error) { t.Helper() diff --git a/sync/crash_every_call_test.go b/sync/crash_every_call_test.go index 77074fd..1c55019 100644 --- a/sync/crash_every_call_test.go +++ b/sync/crash_every_call_test.go @@ -77,6 +77,7 @@ func recordMirrorCalls(t *testing.T, b mirrorBackend, fold nameFolding) []transp t.Helper() f := setupMirrorFixtureOn(t, b) f.fold = fold + f.oneAtATime() mirrorCrashScenario(t, f) var rec *faultTransport rep, err := f.pushVia(t, Options{}, func(tr transport) transport { @@ -104,7 +105,9 @@ func TestMirrorCrashAtEveryTransportCall(t *testing.T) { for _, mode := range crashModesFor(c) { t.Run(fmt.Sprintf("%03d-%s-%s-%s", i, c.op, path.Base(c.name), crashModeNames[mode]), func(t *testing.T) { t.Parallel() - runMirrorCrashAt(t, b, fold, i, mode) + runMirrorCrashAt(t, b, fold, func(f *mirrorFixture) (Report, error) { + return f.pushCrashing(t, crashAtCall(i), mode) + }) }) } } @@ -113,12 +116,57 @@ func TestMirrorCrashAtEveryTransportCall(t *testing.T) { } } -func runMirrorCrashAt(t *testing.T, b mirrorBackend, fold nameFolding, i int, mode crashMode) { +// powerCutModes are the two moments a power cut can strike around a call: +// before it, after every record written since the call before, and after +// it. +var powerCutModes = []crashMode{crashBefore, crashAfter} + +// powerCut is one way a power cut can leave the disk: every call no Flush +// covered taken back, or every name kept but none of those calls' bytes. +type powerCut struct { + name string + mode crashMode + keep func(n int) int +} + +var powerCuts = []powerCut{ + {"before", crashBefore, nil}, + {"after", crashAfter, nil}, + {"names-kept", crashBefore, func(n int) int { return n }}, +} + +// TestMirrorPowerCutAtEveryTransportCall: a push that loses power around +// any one of its transport calls, taking back every call no Flush covered +// or keeping their names without their bytes, still leaves every record +// vouching for its bytes, because no record claims bytes before the flush +// that covers them and no staged file is renamed before its bytes are +// flushed; the next clean push settles the rest. +func TestMirrorPowerCutAtEveryTransportCall(t *testing.T) { + for _, b := range mirrorBackends { + for _, fold := range []nameFolding{{}, caseAndNormFolding} { + t.Run(fmt.Sprintf("%s/folds=%v", b.name, fold.folds()), func(t *testing.T) { + for i, c := range recordMirrorCalls(t, b, fold) { + for _, cut := range powerCuts { + t.Run(fmt.Sprintf("%03d-%s-%s-%s", i, c.op, path.Base(c.name), cut.name), func(t *testing.T) { + t.Parallel() + runMirrorCrashAt(t, b, fold, func(f *mirrorFixture) (Report, error) { + return f.pushCuttingPower(t, crashAtCall(i), cut.mode, cut.keep) + }) + }) + } + } + }) + } + } +} + +func runMirrorCrashAt(t *testing.T, b mirrorBackend, fold nameFolding, crash func(*mirrorFixture) (Report, error)) { f := setupMirrorFixtureOn(t, b) f.fold = fold + f.oneAtATime() mirrorCrashScenario(t, f) before := f.contentHashes(t) - if rep, err := f.pushCrashing(t, crashAtCall(i), mode); !crashedOn(rep, err) { + if rep, err := crash(f); !crashedOn(rep, err) { t.Fatalf("crashing push: status=%q err=%v failures=%+v, want the injected crash", rep.Status, err, rep.RcloneResult.FailedFiles) } f.checkRecordsVouch(t, "tampered.txt") @@ -160,6 +208,7 @@ func contentCrashScenario(t *testing.T, f *nativeContentFixture) { func recordContentCalls(t *testing.T, b contentBackend, layout string) []transportCall { t.Helper() f := setupNativeContentFixture(t, b, layout) + f.oneAtATime() contentCrashScenario(t, f) var calls []transportCall rep, err := f.pushCrashing(t, func(c transportCall) bool { @@ -185,7 +234,33 @@ func TestNativeContentCrashAtEveryTransportCall(t *testing.T) { for _, mode := range crashModesFor(c) { t.Run(fmt.Sprintf("%03d-%s-%s-%s", i, c.op, path.Base(c.name), crashModeNames[mode]), func(t *testing.T) { t.Parallel() - runContentCrashAt(t, b, layout, i, mode) + runContentCrashAt(t, b, layout, func(f *nativeContentFixture) (Report, error) { + return f.pushCrashing(t, crashAtCall(i), mode) + }) + }) + } + } + }) + } + } +} + +// TestNativeContentPowerCutAtEveryTransportCall: a content push that loses +// power around any one of its transport calls, taking back every call no +// Flush covered or keeping their names without their bytes, records no +// artifact the destination does not hold; the next clean push lands the +// rest. +func TestNativeContentPowerCutAtEveryTransportCall(t *testing.T) { + for _, b := range contentBackends { + for _, layout := range contentLayouts { + t.Run(b.name+"/"+layout, func(t *testing.T) { + for i, c := range recordContentCalls(t, b, layout) { + for _, cut := range powerCuts { + t.Run(fmt.Sprintf("%03d-%s-%s-%s", i, c.op, path.Base(c.name), cut.name), func(t *testing.T) { + t.Parallel() + runContentCrashAt(t, b, layout, func(f *nativeContentFixture) (Report, error) { + return f.pushCuttingPower(t, crashAtCall(i), cut.mode, cut.keep) + }) }) } } @@ -194,11 +269,12 @@ func TestNativeContentCrashAtEveryTransportCall(t *testing.T) { } } -func runContentCrashAt(t *testing.T, b contentBackend, layout string, i int, mode crashMode) { +func runContentCrashAt(t *testing.T, b contentBackend, layout string, crash func(*nativeContentFixture) (Report, error)) { f := setupNativeContentFixture(t, b, layout) + f.oneAtATime() contentCrashScenario(t, f) before := hashesOutsideStaging(t, f.dst) - if rep, err := f.pushCrashing(t, crashAtCall(i), mode); !crashedOn(rep, err) { + if rep, err := crash(f); !crashedOn(rep, err) { t.Fatalf("crashing push: status=%q err=%v failures=%+v, want the injected crash", rep.Status, err, rep.RcloneResult.FailedFiles) } f.checkArtifactsVouch(t) diff --git a/sync/destination_marker.go b/sync/destination_marker.go index ad99617..228d870 100644 --- a/sync/destination_marker.go +++ b/sync/destination_marker.go @@ -95,8 +95,9 @@ func (h *destinationRoot) checkMarker(name string, data []byte) error { } // writeMarker stages the marker, then renames it onto name, so a write -// that fails halfway never leaves a marker that does not parse. A copy an -// earlier --init left staged is cleared first. +// that fails halfway never leaves a marker that does not parse; its bytes +// are flushed before the rename and the rename before it returns. A copy +// an earlier --init left staged is cleared first. func (h *destinationRoot) writeMarker(ctx context.Context, tr transport, name string) error { m, err := selfMarker(ctx, h.store, h.volumeDir) if err != nil { @@ -113,12 +114,25 @@ func (h *destinationRoot) writeMarker(ctx context.Context, tr transport, name st if err := tr.Put(ctx, staged, bytes.NewReader(data), time.Now()); err != nil { return fmt.Errorf("destination %q: write %s: %w", h.dest.Name, h.where(staged), err) } - if err := tr.Rename(ctx, staged, name); err != nil { + if err := landStaged(ctx, tr, staged, name); err != nil { return fmt.Errorf("destination %q: write %s: %w", h.dest.Name, h.where(name), err) } return nil } +// landStaged renames a staged file onto name, flushing its bytes before +// the rename and the rename after it, so neither a crash nor a power cut +// leaves name holding anything but the whole file. +func landStaged(ctx context.Context, tr transport, staged, name string) error { + if err := tr.Flush(ctx); err != nil { + return err + } + if err := tr.Rename(ctx, staged, name); err != nil { + return err + } + return tr.Flush(ctx) +} + // where names a destination-relative name for a message: the path on a // local disk, host:path on an sftp server. func (h *destinationRoot) where(name string) string { diff --git a/sync/destination_root.go b/sync/destination_root.go index fb47a99..e0aa2d0 100644 --- a/sync/destination_root.go +++ b/sync/destination_root.go @@ -9,6 +9,7 @@ import ( "path" "strconv" "strings" + "sync/atomic" "time" "github.com/mbertschler/squirrel/config" @@ -27,6 +28,9 @@ type destinationRoot struct { openTransport func(context.Context, *config.Destination) (transport, error) // stallTimeout bounds every transport call by progress. stallTimeout time.Duration + // unflushed counts the bytes put since the last Flush, which the + // Flush is allowed the time to write. + unflushed atomic.Int64 raw transport // opened on first use, closed by close } @@ -48,6 +52,7 @@ func (h *destinationRoot) guarded(ctx context.Context, guard nameGuard) (transpo transport: guardedTransport{transport: h.raw, guard: guard}, timeout: h.stallTimeout, stalled: stalledCounter(h.dest.Name), + unflushed: &h.unflushed, }, nil } diff --git a/sync/mirror.go b/sync/mirror.go index 5a36dd8..56379b5 100644 --- a/sync/mirror.go +++ b/sync/mirror.go @@ -154,8 +154,9 @@ func (h *mirrorHandler) foreignHistory(runID int64) error { return fmt.Errorf("destination %q: the last successful sync (run %d) left no receipt at %s, so the root holds a tree this mirror did not write (by rclone, or another layout) or was emptied while squirrel still records uploads to it; a native mirror does not adopt an existing tree: point the destination at a fresh or emptied root, and after emptying it run `squirrel destination reset %s`: %w", h.dest.Name, runID, h.receiptName(runID), h.dest.Name, ErrRefused) } -// seal writes the run's receipt, the manifest segment of its delta, and -// confirms it landed at its size. +// seal writes the run's receipt, the manifest segment of its delta, +// confirms it landed at its size, and flushes it: the run succeeds only on +// a receipt a power cut cannot take back. func (h *mirrorHandler) seal(ctx context.Context, _ *Report, runID int64, p pushPlan, _ *mirrorOps) error { body, err := encodeManifestSegment(p.delta) if err != nil { @@ -176,6 +177,9 @@ func (h *mirrorHandler) seal(ctx context.Context, _ *Report, runID int64, p push if e.size != int64(len(body)) { return fmt.Errorf("receipt %s landed with size %d, want %d", name, e.size, len(body)) } + if err := tr.Flush(ctx); err != nil { + return fmt.Errorf("flush receipt %s: %w", name, err) + } return nil } diff --git a/sync/mirror_first_push_test.go b/sync/mirror_first_push_test.go index 70af042..edd7e95 100644 --- a/sync/mirror_first_push_test.go +++ b/sync/mirror_first_push_test.go @@ -2,6 +2,7 @@ package sync import ( "errors" + "fmt" "io/fs" "os" "path/filepath" @@ -101,6 +102,52 @@ func TestMirrorRetriesAFirstPushThatCrashed(t *testing.T) { } } +// TestMirrorFirstPushSurvivesAPowerCutAtEveryCall: a first push displaces +// nothing, so only the flush after staging stands between a staged file's +// bytes and the rename that commits it. A power cut around any call, even +// one that keeps every name but loses the bytes no Flush covered, leaves +// every record vouching for its bytes, and the retry lands the rest. +func TestMirrorFirstPushSurvivesAPowerCutAtEveryCall(t *testing.T) { + for _, b := range mirrorBackends { + t.Run(b.name, func(t *testing.T) { + var rec *faultTransport + if _, err := firstPushFixture(t, b).pushVia(t, Options{}, func(tr transport) transport { + rec = &faultTransport{transport: tr} + return rec + }); err != nil { + t.Fatal(err) + } + for i := range rec.calls { + for _, cut := range powerCuts { + t.Run(fmt.Sprintf("%03d-%s", i, cut.name), func(t *testing.T) { + t.Parallel() + f := firstPushFixture(t, b) + if rep, err := f.pushCuttingPower(t, crashAtCall(i), cut.mode, cut.keep); !crashedOn(rep, err) { + t.Fatalf("push cut short = %v, want the injected crash", err) + } + f.checkRecordsVouch(t) + f.mustPush(t) + f.checkInvariants(t, nil) + }) + } + } + }) + } +} + +// firstPushFixture is a fixture about to push three files for the first +// time, one path at a time. +func firstPushFixture(t *testing.T, b mirrorBackend) *mirrorFixture { + t.Helper() + f := setupMirrorFixtureOn(t, b) + f.oneAtATime() + f.write(t, "a.txt", "alpha") + f.write(t, "b.txt", "beta") + f.write(t, "d/c.txt", "gamma") + f.index(t) + return f +} + // TestMirrorLeavesAppleDoubleCompanionsToTheSystem: the "._X" files macOS // keeps beside X on a disk without extended attributes are X's, not // foreign: one beside the marker leaves a root empty, one beside a diff --git a/sync/mirror_fold.go b/sync/mirror_fold.go index 2d4a3d0..17c36dc 100644 --- a/sync/mirror_fold.go +++ b/sync/mirror_fold.go @@ -359,13 +359,15 @@ func (w *mirrorWriter) presentAtSource(ctx context.Context) func(string) (bool, // spelling of a planned path's name, unless an earlier path of this push // already did. func (w *mirrorWriter) displaceSpelling(ctx context.Context, rel string) error { - if _, ok := w.live[rel]; !ok { + if _, ok := w.liveAt(rel); !ok { return nil } return w.displace(ctx, rel) } func (w *mirrorWriter) refuseCollision(rel, other string) { + w.mu.Lock() + defer w.mu.Unlock() w.collided++ w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: %s is not written: the destination cannot tell its name apart from %s (it ignores case or Unicode normalization); rename one of them at the source", w.h.dest.Name, rel, other)) diff --git a/sync/mirror_model_test.go b/sync/mirror_model_test.go index 4a49b4a..c509e32 100644 --- a/sync/mirror_model_test.go +++ b/sync/mirror_model_test.go @@ -78,10 +78,11 @@ var sourceFolding = caseAndNormFolding // TestMirrorModel runs random histories — adds, changes, deletes, re-adds, // file↔directory swaps, nested, renames that change only case, and on a -// folding destination names that collide — through a native mirror, each -// push preceded now and then by one that crashes at a random transport -// call. After every clean push the destination's live records and its tree -// match the reference model, and the three invariants hold. +// folding destination names that collide — through a native mirror +// writing several paths at once, each push preceded now and then by one +// that crashes or loses power at a random transport call. After every +// clean push the destination's live records and its tree match the +// reference model, and the three invariants hold. func TestMirrorModel(t *testing.T) { for _, b := range mirrorBackends { for _, fold := range []nameFolding{{}, caseAndNormFolding} { @@ -262,8 +263,7 @@ func (r *modelRun) push() { } } if r.rng.IntN(3) == 0 { - mode := []crashMode{crashBefore, crashAfter, crashMidway}[r.rng.IntN(3)] - _, _ = f.pushCrashing(t, crashAtCall(r.rng.IntN(60)), mode) + r.crashingPush() f.checkRecordsVouch(t) f.checkOnlyGrew(t, before) } @@ -276,6 +276,21 @@ func (r *modelRun) push() { r.checkAgainstModel() } +// crashingPush pushes once with a crash at a random transport call: the +// process dies, or half the time the power goes, keeping a random oldest +// part of what no Flush covered. +func (r *modelRun) crashingPush() { + at := crashAtCall(r.rng.IntN(60)) + if r.rng.IntN(2) == 0 { + mode := []crashMode{crashBefore, crashAfter, crashMidway}[r.rng.IntN(3)] + _, _ = r.f.pushCrashing(r.t, at, mode) + return + } + seed := r.rng.Uint64() + keep := func(n int) int { return rand.New(rand.NewPCG(seed, seed)).IntN(n + 1) } + _, _ = r.f.pushCuttingPower(r.t, at, powerCutModes[r.rng.IntN(2)], keep) +} + // collide records another spelling of a file the destination holds as // present and pushes: the push refuses that spelling alone and fails. func (r *modelRun) collide() bool { diff --git a/sync/mirror_test.go b/sync/mirror_test.go index 95ca994..6abf378 100644 --- a/sync/mirror_test.go +++ b/sync/mirror_test.go @@ -170,6 +170,20 @@ func (f *mirrorFixture) pushCrashing(t *testing.T, crashAt func(transportCall) b }) } +// pushCuttingPower runs one push that loses power at the first call +// crashAt selects, before or after it as mode says, keeping the oldest +// keep(n) of the n calls no Flush covered. +func (f *mirrorFixture) pushCuttingPower(t *testing.T, crashAt func(transportCall) bool, mode crashMode, keep func(int) int) (Report, error) { + t.Helper() + return f.pushVia(t, Options{}, func(tr transport) transport { + return &faultTransport{transport: tr, crashAt: crashAt, mode: mode, powerCut: true, keep: keep} + }) +} + +// oneAtATime makes the fixture's pushes write one path at a time, so +// their transport calls come in the same order on every push. +func (f *mirrorFixture) oneAtATime() { f.pair.Destination.Concurrency = 1 } + func (f *mirrorFixture) handler(t *testing.T) *mirrorHandler { t.Helper() h, err := HandlerFor(f.store, Tools{}, f.pair) diff --git a/sync/mirror_write.go b/sync/mirror_write.go index 9c9880e..d34aa97 100644 --- a/sync/mirror_write.go +++ b/sync/mirror_write.go @@ -12,6 +12,7 @@ import ( "path" "path/filepath" "strings" + gosync "sync" "time" "github.com/zeebo/blake3" @@ -21,36 +22,47 @@ import ( ) // mirrorWriter carries one run's execution: the guarded transport, the -// live records it keeps current, and the tally for the report. +// live records it keeps current, and the tally for the report. Several +// paths are in flight at once, so the records and the tally are shared +// behind mu, which is never held across a transport call. type mirrorWriter struct { h *mirrorHandler rep *Report runID int64 volumeID int64 tr transport - live map[string]store.RemotePath // fold is how the destination compares names; names plans the // writes around the collisions its folding causes. fold nameFolding names foldPlan + // concurrency is how many paths are in flight at once. + concurrency int progress func(runevents.Progress) total int - done int - drifted int - collided int + + mu gosync.Mutex + live map[string]store.RemotePath + // displacing is the rows this batch moved into history, which the + // batch's flush lets it record as displaced. + displacing []int64 + done int + drifted int + collided int + stalled bool } -// execute confirms or writes every planned path. A failure on one path -// is counted and the rest still run — every version that lands now is -// recorded and saves work on the retry — but any failure fails the run -// before its receipt is written, so the watermark holds. +// execute confirms or writes every planned path, a batch at a time. A +// failure on one path is counted and the rest still run — every version +// that lands now is recorded and saves work on the retry — but any failure +// fails the run before its receipt is written, so the watermark holds. func (h *mirrorHandler) execute(ctx context.Context, rep *Report, runID int64, ops *mirrorOps) error { tr, err := h.root(ctx, runID) if err != nil { return err } - w := &mirrorWriter{h: h, rep: rep, runID: runID, volumeID: ops.volumeID, tr: tr, live: ops.live, progress: h.progress, total: len(ops.paths)} + w := &mirrorWriter{h: h, rep: rep, runID: runID, volumeID: ops.volumeID, tr: tr, live: ops.live, + concurrency: pushConcurrency(h.dest), progress: h.progress, total: len(ops.paths)} rep.AlreadyCorrect = ops.inSync if ops.repairs > 0 { rep.Changed = knownChanged(rep.Changed.Int64 + ops.repairs) @@ -59,19 +71,27 @@ func (h *mirrorHandler) execute(ctx context.Context, rep *Report, runID int64, o if err := w.learnNames(ctx, ops); err != nil { return err } - for _, p := range ops.paths { + for _, batch := range batches(ops.paths, writtenBytes) { if err := ctx.Err(); err != nil { return err } - if stalled := w.land(ctx, p); stalled { + w.writeBatch(ctx, batch) + if w.isStalled() { break } - w.done++ - w.emitProgress() } return w.result() } +// writtenBytes is what a planned path adds to its batch: its bytes when +// it may be written, nothing when it is only confirmed. +func writtenBytes(p mirrorPath) int64 { + if p.current { + return 0 + } + return p.delta.SizeBytes +} + // learnNames probes how the destination compares names before the first // path lands, and on a destination that folds them plans around the // collisions that causes. @@ -87,44 +107,231 @@ func (w *mirrorWriter) learnNames(ctx context.Context, ops *mirrorOps) error { return err } -// land confirms or writes one planned path, or refuses it when its name -// collides with another's; it reports whether the transport stalled. -func (w *mirrorWriter) land(ctx context.Context, p mirrorPath) bool { - if other, ok := w.names.refused[p.delta.Path]; ok { - w.refuseCollision(p.delta.Path, other) - return false +// landing is one planned path on its way through a batch. +type landing struct { + p mirrorPath + staged stagedVersion + // commitID is the path's committing row, once inserted. + commitID int64 + // settled: the path needs no further step, because it was confirmed + // in place, refused, or failed. + settled bool +} + +// writeBatch takes one batch through the steps of a write, each for the +// whole batch before the next: confirm or stage every path, flush, read +// back, clear the way, displace, flush and record the displaced versions, +// commit, flush and record the committed ones. A path whose step fails +// drops out; a stalled transport ends the batch where it is, and the next +// push's reconcile settles what it left recorded in flight. +func (w *mirrorWriter) writeBatch(ctx context.Context, batch []mirrorPath) { + ls := make([]*landing, len(batch)) + for i, p := range batch { + ls[i] = &landing{p: p} + } + steps := []func(context.Context, []*landing){ + w.each(w.prepare), + w.flushOrDrop, + w.readBackAll, + w.clearTheWay, + w.each(w.displaceLanding), + w.recordDisplaced, + w.each(w.commit), + w.recordCommitted, + } + for _, step := range steps { + step(ctx, ls) + if w.isStalled() || ctx.Err() != nil { + return + } } - if err := w.apply(ctx, p); err != nil { - w.fail(p.delta.Path, err) - return errors.Is(err, errTransportStalled) +} + +// each is the step that runs fn for every path still on its way, with +// w.concurrency of them in flight. A path fn fails drops out. +func (w *mirrorWriter) each(fn func(context.Context, *landing) error) func(context.Context, []*landing) { + return func(ctx context.Context, ls []*landing) { + inFlight(ctx, w.concurrency, active(ls), w.isStalled, func(l *landing) { + if err := fn(ctx, l); err != nil { + w.drop(l, err) + } + }) } - return false } -func (w *mirrorWriter) apply(ctx context.Context, p mirrorPath) error { - if p.current { - ok, err := w.confirm(ctx, p.delta) - if err != nil || ok { +// active is the batch's paths still on their way. +func active(ls []*landing) []*landing { + var out []*landing + for _, l := range ls { + if !l.settled { + out = append(out, l) + } + } + return out +} + +// prepare refuses a path whose name collides with another's, confirms an +// already-correct one in place, and stages every other. +func (w *mirrorWriter) prepare(ctx context.Context, l *landing) error { + rel := l.p.delta.Path + if other, ok := w.names.refused[rel]; ok { + w.refuseCollision(rel, other) + w.settle(l) + return nil + } + if l.p.current { + ok, err := w.confirm(ctx, l.p.delta) + if err != nil { return err } + if ok { + w.settle(l) + return nil + } + } + staged, err := w.stage(ctx, l.p.delta) + l.staged = staged + return err +} + +// flushOrDrop makes the batch's staged files durable; a flush that fails +// drops every path still on its way. +func (w *mirrorWriter) flushOrDrop(ctx context.Context, ls []*landing) { + if len(active(ls)) == 0 { + return + } + if err := w.tr.Flush(ctx); err != nil { + w.dropAll(ls, fmt.Errorf("flush the staged files: %w", err)) + } +} + +// readBackAll reads every staged file back on a disk squirrel reads back. +func (w *mirrorWriter) readBackAll(ctx context.Context, ls []*landing) { + if !readsBack(w.h.dest) { + return + } + w.each(func(ctx context.Context, l *landing) error { + return w.readBackStaged(ctx, l.p.delta, &l.staged) + })(ctx, ls) +} + +// clearTheWay moves aside, one path after another, what stands in the +// way of more than one path's name: versions recorded under another +// spelling of it, and a parent that is not a directory. Each directory is +// looked at once per batch. +func (w *mirrorWriter) clearTheWay(ctx context.Context, ls []*landing) { + cleared := map[string]bool{} + for _, l := range active(ls) { + if w.isStalled() { + return + } + if err := w.clearFor(ctx, l.p.delta.Path, cleared); err != nil { + w.drop(l, err) + } + } +} + +func (w *mirrorWriter) clearFor(ctx context.Context, rel string, cleared map[string]bool) error { + for _, other := range w.names.displace[rel] { + if err := w.displaceSpelling(ctx, other); err != nil { + return err + } + } + return w.clearParents(ctx, rel, cleared) +} + +func (w *mirrorWriter) displaceLanding(ctx context.Context, l *landing) error { + return w.displace(ctx, l.p.delta.Path) +} + +// recordDisplaced flushes the batch's moves into history, then records +// them as displaced. Until then their rows stay displacing, which the +// next push's reconcile settles from where the bytes are. +func (w *mirrorWriter) recordDisplaced(ctx context.Context, ls []*landing) { + w.mu.Lock() + ids := w.displacing + w.displacing = nil + w.mu.Unlock() + if len(ids) == 0 { + return + } + err := w.tr.Flush(ctx) + if err == nil { + err = w.h.store.ConfirmRemotePathsDisplaced(ctx, ids...) + } + if err != nil { + w.dropAll(ls, fmt.Errorf("record the versions moved into history: %w", err)) + } +} + +// recordCommitted flushes the batch's commits, then records them live +// and counts them. Until then their rows stay committing, which the next +// push's reconcile settles from where the bytes are. +func (w *mirrorWriter) recordCommitted(ctx context.Context, ls []*landing) { + var ids []int64 + for _, l := range active(ls) { + ids = append(ids, l.commitID) + } + if len(ids) == 0 { + return + } + err := w.tr.Flush(ctx) + if err == nil { + err = w.h.store.ConfirmRemotePathsLive(ctx, ids...) + } + if err != nil { + w.dropAll(ls, fmt.Errorf("record the committed paths: %w", err)) + return + } + w.mu.Lock() + defer w.mu.Unlock() + for _, l := range active(ls) { + w.rep.RcloneResult.Transferred++ + w.rep.RcloneResult.Bytes += l.p.delta.SizeBytes + w.settleLocked(l) + } +} + +func (w *mirrorWriter) settle(l *landing) { + w.mu.Lock() + defer w.mu.Unlock() + w.settleLocked(l) +} + +// settleLocked takes l off its way, counts it done and reports progress; +// w.mu is held, so progress arrives in order. +func (w *mirrorWriter) settleLocked(l *landing) { + l.settled = true + w.done++ + if w.progress == nil { + return } - return w.write(ctx, p.delta) + w.progress(runevents.Progress{ + Stage: runevents.StageUploading, + Done: int64(w.done), + Total: int64(w.total), + BytesDone: w.rep.RcloneResult.Bytes, + }) } // confirm checks an already-correct path with one Lstat. A path whose size // or mtime disagrees with its record was changed behind squirrel's back: // the record becomes lost, and the path is written again. func (w *mirrorWriter) confirm(ctx context.Context, d store.PathDelta) (bool, error) { - live := w.live[d.Path] + live, _ := w.liveAt(d.Path) e, err := w.tr.Stat(ctx, w.h.liveName(d.Path)) if err != nil && !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, errParentNotDir) { return false, err } if err == nil && matchesRecord(e, live) { + w.mu.Lock() w.rep.RcloneResult.Checked++ + w.mu.Unlock() return true, nil } + w.mu.Lock() w.rep.AlreadyCorrect-- + w.mu.Unlock() if err := w.loseRecord(ctx, live, "no longer matches its record"); err != nil { return false, err } @@ -141,33 +348,11 @@ type stagedVersion struct { verifiedAtNs int64 } -// write lands one path: stage the content while hashing it, clear the way -// (displacing whatever the path and its parents hold, under any spelling -// the destination resolves to them), then commit. -func (w *mirrorWriter) write(ctx context.Context, d store.PathDelta) error { - staged, err := w.stage(ctx, d) - if err != nil { - return err - } - for _, other := range w.names.displace[d.Path] { - if err := w.displaceSpelling(ctx, other); err != nil { - return err - } - } - if err := w.clearParents(ctx, d.Path); err != nil { - return err - } - if err := w.displace(ctx, d.Path); err != nil { - return err - } - return w.commit(ctx, d, staged) -} - // stage streams the source into this run's staging and hashes the same -// bytes, then confirms what landed: its size, and on a local disk its -// bytes, read back. A source that drifted from its indexed hash fails the -// path with errContentDrift; its staged file stays until the next push's -// reconcile removes it with this run's staging. +// bytes, then confirms what landed: its size. A source that drifted from +// its indexed hash fails the path with errContentDrift; its staged file +// stays until the next push's reconcile removes it with this run's +// staging. func (w *mirrorWriter) stage(ctx context.Context, d store.PathDelta) (stagedVersion, error) { src := filepath.Join(w.h.vol.Path, filepath.FromSlash(d.Path)) f, err := os.Open(src) @@ -193,14 +378,11 @@ func (w *mirrorWriter) stage(ctx context.Context, d store.PathDelta) (stagedVers return stagedVersion{}, fmt.Errorf("staged %s landed with size %d, want %d", d.Path, e.size, d.SizeBytes) } staged.mtime = e.mtime - if readsBack(w.h.dest) { - return staged, w.readBackStaged(ctx, d, &staged) - } return staged, nil } -// readBackStaged confirms the staged bytes are the content squirrel sent, -// and records the fingerprint that earns. +// readBackStaged confirms the staged bytes, flushed, are the content +// squirrel sent, and records the fingerprint that earns. func (w *mirrorWriter) readBackStaged(ctx context.Context, d store.PathDelta, staged *stagedVersion) error { sum, err := readBack(ctx, w.tr, staged.name) if err != nil { @@ -211,26 +393,43 @@ func (w *mirrorWriter) readBackStaged(ctx context.Context, d store.PathDelta, st } staged.checksum = hex.EncodeToString(sum) staged.verifiedAtNs = store.NowNs() + w.mu.Lock() w.rep.Fingerprints++ + w.mu.Unlock() return nil } // clearParents displaces the first parent of rel that is not a directory -// — a file, a symlink — so rel's directory can be created. -func (w *mirrorWriter) clearParents(ctx context.Context, rel string) error { +// — a file, a symlink — so rel's directory can be created. cleared holds +// what this batch already found at each parent: a directory (true) or +// nothing (false), below which nothing exists either. +func (w *mirrorWriter) clearParents(ctx context.Context, rel string, cleared map[string]bool) error { parts := strings.Split(rel, "/") for i := 1; i < len(parts); i++ { parent := strings.Join(parts[:i], "/") + if isDir, seen := cleared[parent]; seen { + if !isDir { + return nil + } + continue + } e, err := w.tr.Stat(ctx, w.h.liveName(parent)) if errors.Is(err, fs.ErrNotExist) { + cleared[parent] = false return nil } if err != nil { return err } - if e.kind != kindDir { - return w.displace(ctx, parent) + if e.kind == kindDir { + cleared[parent] = true + continue + } + if err := w.displace(ctx, parent); err != nil { + return err } + cleared[parent] = false + return nil } return nil } @@ -257,7 +456,7 @@ func (w *mirrorWriter) displace(ctx context.Context, rel string) error { return err } } - if live, ok := w.live[rel]; ok { + if live, ok := w.liveAt(rel); ok { if matchesRecord(e, live) { return w.moveRecorded(ctx, rel, []int64{live.ID}) } @@ -275,11 +474,8 @@ func (w *mirrorWriter) displace(ctx context.Context, rel string) error { // under it; a record whose bytes changed becomes lost first. func (w *mirrorWriter) displaceDir(ctx context.Context, dir string) error { var ids []int64 - for rel, live := range w.live { - if !w.fold.under(rel, dir) { - continue - } - e, err := w.tr.Stat(ctx, w.h.liveName(rel)) + for _, live := range w.liveUnder(dir) { + e, err := w.tr.Stat(ctx, w.h.liveName(live.Path)) if err != nil && !errors.Is(err, fs.ErrNotExist) { return err } @@ -297,14 +493,15 @@ func (w *mirrorWriter) displaceDir(ctx context.Context, dir string) error { if err := w.moveRecorded(ctx, dir, ids); err != nil { return err } - w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: directory %s was replaced by a file; it moved into %s with the %d version(s) squirrel recorded in it and anything else it held", + w.warn(fmt.Sprintf("destination %q: directory %s was replaced by a file; it moved into %s with the %d version(s) squirrel recorded in it and anything else it held", w.h.dest.Name, dir, w.historyName(dir), len(ids))) return nil } // moveRecorded records the move of ids, renames rel into history, and -// confirms. If the rename fails the rows stay displacing, and the next -// push's reconcile settles them from where the bytes are. +// leaves the rows for the batch's flush to confirm. If the rename fails, +// or the push ends before that flush, the rows stay displacing, and the +// next push's reconcile settles them from where the bytes are. func (w *mirrorWriter) moveRecorded(ctx context.Context, rel string, ids []int64) error { if err := w.h.store.BeginRemotePathsDisplace(ctx, w.runID, ids...); err != nil { return err @@ -312,9 +509,9 @@ func (w *mirrorWriter) moveRecorded(ctx context.Context, rel string, ids []int64 if err := w.tr.Rename(ctx, w.h.liveName(rel), w.historyName(rel)); err != nil { return fmt.Errorf("displace %s: %w", rel, err) } - if err := w.h.store.ConfirmRemotePathsDisplaced(ctx, ids...); err != nil { - return err - } + w.mu.Lock() + defer w.mu.Unlock() + w.displacing = append(w.displacing, ids...) for r := range w.live { if r == rel || w.fold.under(r, rel) { delete(w.live, r) @@ -334,7 +531,7 @@ func (w *mirrorWriter) moveUnrecorded(ctx context.Context, rel string, e entry) if err := w.tr.Rename(ctx, w.h.liveName(rel), to); err != nil { return fmt.Errorf("displace unrecorded %s: %w", rel, err) } - w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: %s held bytes squirrel did not write (%d bytes); they are preserved at %s", w.h.dest.Name, rel, e.size, to)) + w.warn(fmt.Sprintf("destination %q: %s held bytes squirrel did not write (%d bytes); they are preserved at %s", w.h.dest.Name, rel, e.size, to)) return nil } @@ -346,10 +543,12 @@ func (w *mirrorWriter) noteUnrecordedMove(ctx context.Context, note string) erro }) } -// commit records the intent, renames the staged version onto rel, and -// confirms. If the rename fails the row stays committing, and the next -// push's reconcile withdraws it. -func (w *mirrorWriter) commit(ctx context.Context, d store.PathDelta, staged stagedVersion) error { +// commit records the intent and renames the staged version onto its +// path, leaving the row for the batch's flush to confirm. If the rename +// fails, or the push ends before that flush, the row stays committing, +// and the next push's reconcile settles it. +func (w *mirrorWriter) commit(ctx context.Context, l *landing) error { + d, staged := l.p.delta, l.staged id, err := w.h.store.BeginRemotePathCommit(ctx, store.RemotePathWrite{ Destination: w.h.dest.Name, FolderID: d.FolderID, @@ -366,24 +565,20 @@ func (w *mirrorWriter) commit(ctx context.Context, d store.PathDelta, staged sta if err := w.tr.Rename(ctx, staged.name, w.h.liveName(d.Path)); err != nil { return fmt.Errorf("commit %s: %w", d.Path, err) } - if err := w.h.store.ConfirmRemotePathsLive(ctx, id); err != nil { - return err - } + l.commitID = id + w.mu.Lock() w.live[d.Path] = store.RemotePath{ID: id, ContentID: d.ContentID, WrittenRunID: w.runID, State: store.RemotePathLive, MtimeNs: staged.mtime.UnixNano(), Path: d.Path, SizeBytes: d.SizeBytes} - w.rep.RcloneResult.Transferred++ - w.rep.RcloneResult.Bytes += d.SizeBytes + w.mu.Unlock() return nil } // loseRecordsUnder marks lost every live record below rel, whose // directory the destination no longer holds. func (w *mirrorWriter) loseRecordsUnder(ctx context.Context, rel string) error { - for r, live := range w.live { - if w.fold.under(r, rel) { - if err := w.loseRecord(ctx, live, "is gone: "+rel+" is not a directory on the destination"); err != nil { - return err - } + for _, live := range w.liveUnder(rel) { + if err := w.loseRecord(ctx, live, "is gone: "+rel+" is not a directory on the destination"); err != nil { + return err } } return nil @@ -391,7 +586,7 @@ func (w *mirrorWriter) loseRecordsUnder(ctx context.Context, rel string) error { // loseRecordAt marks the live record at rel lost, if there is one. func (w *mirrorWriter) loseRecordAt(ctx context.Context, rel, why string) error { - if live, ok := w.live[rel]; ok { + if live, ok := w.liveAt(rel); ok { return w.loseRecord(ctx, live, why) } return nil @@ -401,20 +596,58 @@ func (w *mirrorWriter) loseRecord(ctx context.Context, live store.RemotePath, wh if err := w.h.store.MarkRemotePathsLost(ctx, live.ID); err != nil { return err } + w.mu.Lock() delete(w.live, live.Path) - w.rep.Warnings = append(w.rep.Warnings, fmt.Sprintf("destination %q: %s %s — it was changed behind squirrel's back, so its record no longer counts as a copy, and a push writes it again while the index holds it", w.h.dest.Name, live.Path, why)) + w.mu.Unlock() + w.warn(fmt.Sprintf("destination %q: %s %s — it was changed behind squirrel's back, so its record no longer counts as a copy, and a push writes it again while the index holds it", w.h.dest.Name, live.Path, why)) return nil } +// liveAt is the live record at rel, if there is one. +func (w *mirrorWriter) liveAt(rel string) (store.RemotePath, bool) { + w.mu.Lock() + defer w.mu.Unlock() + live, ok := w.live[rel] + return live, ok +} + +// liveUnder is every live record below dir, as the destination resolves +// names. +func (w *mirrorWriter) liveUnder(dir string) []store.RemotePath { + w.mu.Lock() + defer w.mu.Unlock() + var out []store.RemotePath + for rel, live := range w.live { + if w.fold.under(rel, dir) { + out = append(out, live) + } + } + return out +} + +func (w *mirrorWriter) warn(msg string) { + w.mu.Lock() + w.rep.Warnings = append(w.rep.Warnings, msg) + w.mu.Unlock() +} + func (w *mirrorWriter) historyName(rel string) string { return historyName(w.h.vol.Name, w.runID, rel) } -func (w *mirrorWriter) fail(rel string, err error) { - if errors.Is(err, errContentDrift) { +// drop takes l out of its batch, counting why. +func (w *mirrorWriter) drop(l *landing, err error) { + rel := l.p.delta.Path + w.mu.Lock() + defer w.mu.Unlock() + defer w.settleLocked(l) + switch { + case errors.Is(err, errContentDrift): w.drifted++ w.rep.Warnings = append(w.rep.Warnings, err.Error()) return + case errors.Is(err, errTransportStalled): + w.stalled = true } w.rep.RcloneResult.Errors++ if int64(len(w.rep.RcloneResult.FailedFiles)) < maxFailedFiles { @@ -422,6 +655,19 @@ func (w *mirrorWriter) fail(rel string, err error) { } } +// dropAll takes every path still on its way out of the batch. +func (w *mirrorWriter) dropAll(ls []*landing, err error) { + for _, l := range active(ls) { + w.drop(l, err) + } +} + +func (w *mirrorWriter) isStalled() bool { + w.mu.Lock() + defer w.mu.Unlock() + return w.stalled +} + func (w *mirrorWriter) result() error { if n := w.rep.RcloneResult.Errors; n > 0 { return fmt.Errorf("%d path(s) failed to land on %q; the receipt for run %d was not written and the durability vector did not advance", n, w.h.dest.Name, w.runID) @@ -435,18 +681,6 @@ func (w *mirrorWriter) result() error { return nil } -func (w *mirrorWriter) emitProgress() { - if w.progress == nil { - return - } - w.progress(runevents.Progress{ - Stage: runevents.StageUploading, - Done: int64(w.done), - Total: int64(w.total), - BytesDone: w.rep.RcloneResult.Bytes, - }) -} - // matchesRecord reports whether an entry found at a path is the version // its live record describes, by kind, size and mtime. func matchesRecord(e entry, live store.RemotePath) bool { diff --git a/sync/packed.go b/sync/packed.go index 66d31c2..5d6d516 100644 --- a/sync/packed.go +++ b/sync/packed.go @@ -437,7 +437,7 @@ func (h *packedHandler) buildOnePack(srcs []store.PathDelta, start int, level zs // decrypted length, which is the compressed pack, so it compares directly. func (h *packedHandler) uploadPack(ctx context.Context, runID int64, pack assembledPack) (*remoteChecksum, error) { defer func() { _ = os.Remove(pack.tmpPath) }() - fingerprint, err := h.art.put(ctx, runID, h.packName(pack.key), pack.tmpPath, pack.compressedSize, pack.key) + fingerprint, err := putArtifact(ctx, h.art, runID, artifactPut{name: h.packName(pack.key), src: pack.tmpPath, size: pack.compressedSize, sum: pack.key}) if err != nil { return nil, fmt.Errorf("upload pack %s: %w", hex.EncodeToString(pack.key), err) } diff --git a/sync/snapshot.go b/sync/snapshot.go index cc4bff7..5315ab7 100644 --- a/sync/snapshot.go +++ b/sync/snapshot.go @@ -244,7 +244,7 @@ func (s transportShelf) upload(ctx context.Context, localPath, name string) erro if err := tr.Put(ctx, staged, f, fi.ModTime()); err != nil { return err } - return tr.Rename(ctx, staged, path.Join(s.dir(), name)) + return landStaged(ctx, tr, staged, path.Join(s.dir(), name)) } func (s transportShelf) snapshots(ctx context.Context) ([]string, error) { diff --git a/sync/transport.go b/sync/transport.go index 9777cc3..dc92ade 100644 --- a/sync/transport.go +++ b/sync/transport.go @@ -15,6 +15,8 @@ import ( // slash-separated and relative to the root, and a name whose path crosses // a symlink is refused. Put creates exclusively and Rename fails on an // existing target, so every call leaves bytes already there in place. +// Their effects are durable once a later Flush returns: a caller records +// a location as holding bytes only after that. type transport interface { // Stat describes name itself, a symlink as a symlink; fs.ErrNotExist // when absent. @@ -24,12 +26,14 @@ type transport interface { // Get opens the regular file at name for reading. Get(ctx context.Context, name string) (io.ReadCloser, error) // Put creates name exclusively (fs.ErrExist if present), creating its - // parents, streams r into it, sets its mtime, and syncs it to stable - // storage before returning. + // parents, streams r into it, and sets its mtime. Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error // Rename moves from to to, creating to's parents; fs.ErrExist if to // exists. Rename(ctx context.Context, from, to string) error + // Flush returns once every Put and Rename that returned before it is + // on stable storage, as far as the destination can make it so. + Flush(ctx context.Context) error // Remove deletes the file or empty directory at name. Remove(ctx context.Context, name string) error // ServerHash is the destination's own hash of the file at name, run diff --git a/sync/transport_fault_test.go b/sync/transport_fault_test.go index 9cda2f0..044063c 100644 --- a/sync/transport_fault_test.go +++ b/sync/transport_fault_test.go @@ -1,9 +1,13 @@ package sync import ( + "bytes" "context" "errors" "io" + "io/fs" + "strings" + "sync" "time" ) @@ -27,35 +31,96 @@ const ( // faultTransport stands in for a process that dies at one transport call: // the first call crashAt selects behaves as mode says, and every call after -// it fails, as if nothing were left to make it. +// it fails, as if nothing were left to make it. With powerCut the machine +// loses power instead: the crash also takes back every Put and Rename +// since the last Flush, newest first, except the oldest keep(n) of those n +// (none without keep), as a disk that persists its names in order does. +// A kept Put's name survives but not its bytes: it holds as many zeros, +// with its mtime. Calls run one at a time, so a crash lands between whole +// calls. type faultTransport struct { transport - crashAt func(transportCall) bool - mode crashMode - crashed bool - calls []transportCall + crashAt func(transportCall) bool + mode crashMode + powerCut bool + keep func(n int) int + + mu sync.Mutex + crashed bool + calls []transportCall + unflushed []transportCall } // do runs one call through the crash point. call receives whether it // should land only part of its effect. func (f *faultTransport) do(c transportCall, call func(midway bool) error) error { + f.mu.Lock() + defer f.mu.Unlock() f.calls = append(f.calls, c) if f.crashed { return errInjectedCrash } if f.crashAt == nil || !f.crashAt(c) { - return call(false) + err := call(false) + f.landed(c, err) + return err } f.crashed = true switch f.mode { case crashAfter: - _ = call(false) + f.landed(c, call(false)) case crashMidway: - _ = call(true) + f.landed(c, call(true)) + } + if f.powerCut { + f.cutPower() } return errInjectedCrash } +// landed notes what a call that succeeded leaves for the next Flush. +func (f *faultTransport) landed(c transportCall, err error) { + if err != nil { + return + } + switch c.op { + case "put", "rename": + f.unflushed = append(f.unflushed, c) + case "flush": + f.unflushed = nil + } +} + +// cutPower takes back the puts and renames no Flush covered: a put file +// vanishes, a rename is reversed, and a put file whose name survives loses +// its bytes. +func (f *faultTransport) cutPower() { + kept := 0 + if f.keep != nil { + kept = f.keep(len(f.unflushed)) + } + ctx := context.Background() + for i, c := range f.unflushed[:kept] { + if c.op == "put" { + f.loseBytes(ctx, followRenames(c.name, f.unflushed[i+1:kept])) + } + } + for i := len(f.unflushed) - 1; i >= kept; i-- { + c := f.unflushed[i] + switch c.op { + case "put": + if err := f.transport.Remove(ctx, c.name); err != nil && !errors.Is(err, fs.ErrNotExist) { + panic(err) + } + case "rename": + if err := f.transport.Rename(ctx, c.to, c.name); err != nil { + panic(err) + } + } + } + f.unflushed = nil +} + func (f *faultTransport) Stat(ctx context.Context, name string) (entry, error) { var e entry err := f.do(transportCall{op: "stat", name: name}, func(bool) error { @@ -91,6 +156,44 @@ func (f *faultTransport) Rename(ctx context.Context, from, to string) error { }) } +// loseBytes replaces the file at name with as many zeros and its mtime. +func (f *faultTransport) loseBytes(ctx context.Context, name string) { + e, err := f.transport.Stat(ctx, name) + if errors.Is(err, fs.ErrNotExist) { + return + } + if err != nil { + panic(err) + } + if err := f.transport.Remove(ctx, name); err != nil { + panic(err) + } + if err := f.transport.Put(ctx, name, bytes.NewReader(make([]byte, e.size)), e.mtime); err != nil { + panic(err) + } +} + +// followRenames is where the file put at name sits after renames, which +// may move it or a directory above it. +func followRenames(name string, renames []transportCall) string { + for _, c := range renames { + switch { + case c.op != "rename": + case c.name == name: + name = c.to + case strings.HasPrefix(name, c.name+"/"): + name = c.to + strings.TrimPrefix(name, c.name) + } + } + return name +} + +func (f *faultTransport) Flush(ctx context.Context) error { + return f.do(transportCall{op: "flush"}, func(bool) error { + return f.transport.Flush(ctx) + }) +} + func (f *faultTransport) Remove(ctx context.Context, name string) error { return f.do(transportCall{op: "remove", name: name}, func(bool) error { return f.transport.Remove(ctx, name) diff --git a/sync/transport_local.go b/sync/transport_local.go index 72982a1..e2c2056 100644 --- a/sync/transport_local.go +++ b/sync/transport_local.go @@ -10,7 +10,9 @@ import ( "path" "path/filepath" "runtime" + "slices" "strings" + "sync" "time" ) @@ -20,9 +22,15 @@ import ( // symlink anywhere along it, because os.Root follows symlinks that stay // inside the root. Put and Get keep their pages out of the cache where // the platform allows (bypassCache), so reading back a file just written -// reads what reached the disk. +// reads what reached the disk. Flush makes durable in one go every file +// Put left open and every directory whose entries changed since the last +// one (flushLocal). type localTransport struct { root *os.Root + + mu sync.Mutex + pending []*os.File + dirty map[string]bool } func openLocalTransport(dir string) (*localTransport, error) { @@ -30,10 +38,18 @@ func openLocalTransport(dir string) (*localTransport, error) { if err != nil { return nil, fmt.Errorf("open destination root %s: %w", dir, err) } - return &localTransport{root: root}, nil + return &localTransport{root: root, dirty: map[string]bool{}}, nil } -func (t *localTransport) Close() error { return t.root.Close() } +func (t *localTransport) Close() error { + t.mu.Lock() + for _, f := range t.pending { + _ = f.Close() + } + t.pending = nil + t.mu.Unlock() + return t.root.Close() +} func (t *localTransport) Stat(_ context.Context, name string) (entry, error) { if err := t.checkName(name); err != nil { @@ -102,17 +118,36 @@ func (t *localTransport) Put(ctx context.Context, name string, r io.Reader, mtim return err } bypassCache(f) + t.markDirty(path.Dir(name)) if err := t.fill(ctx, f, name, r, mtime); err != nil { _ = f.Close() return err } - if err := f.Close(); err != nil { - return fmt.Errorf("close %s: %w", name, err) + return t.settle(f, name) +} + +// settle moves a filled file toward the disk as the platform does it +// (settleFile), and holds it open for the next Flush where that flush +// needs it. +func (t *localTransport) settle(f *os.File, name string) error { + keep, err := settleFile(f) + if err != nil { + _ = f.Close() + return fmt.Errorf("sync %s: %w", name, err) + } + if !keep { + if err := f.Close(); err != nil { + return fmt.Errorf("close %s: %w", name, err) + } + return nil } - return t.syncDir(path.Dir(name)) + t.mu.Lock() + t.pending = append(t.pending, f) + t.mu.Unlock() + return nil } -// fill streams r into the freshly created f, stamps mtime, and syncs. +// fill streams r into the freshly created f and stamps mtime. func (t *localTransport) fill(ctx context.Context, f *os.File, name string, r io.Reader, mtime time.Time) error { if _, err := io.Copy(f, ctxReader{ctx: ctx, r: r}); err != nil { return fmt.Errorf("write %s: %w", name, err) @@ -120,10 +155,6 @@ func (t *localTransport) fill(ctx context.Context, f *os.File, name string, r io if err := t.root.Chtimes(filepath.FromSlash(name), mtime, mtime); err != nil { return fmt.Errorf("set mtime of %s: %w", name, err) } - if err := f.Sync(); err != nil { - return fmt.Errorf("sync %s: %w", name, err) - } - bypassCache(f) return nil } @@ -143,10 +174,29 @@ func (t *localTransport) Rename(_ context.Context, from, to string) error { if err := renameNoReplace(t.root, from, to); err != nil { return err } - if err := t.syncDir(path.Dir(from)); err != nil { - return err + t.markDirty(path.Dir(from)) + t.markDirty(path.Dir(to)) + return nil +} + +// Flush makes every file Put left open, and every directory a call +// changed, durable, then releases the files. +func (t *localTransport) Flush(context.Context) error { + t.mu.Lock() + files, dirty := t.pending, t.dirty + t.pending, t.dirty = nil, map[string]bool{} + t.mu.Unlock() + defer func() { + for _, f := range files { + _ = f.Close() + } + }() + dirs := make([]string, 0, len(dirty)) + for d := range dirty { + dirs = append(dirs, d) } - return t.syncDir(path.Dir(to)) + slices.Sort(dirs) + return flushLocal(t.root, files, dirs) } func (t *localTransport) Remove(_ context.Context, name string) error { @@ -175,26 +225,47 @@ func (t *localTransport) lstat(name string) (fs.FileInfo, error) { return t.root.Lstat(filepath.FromSlash(name)) } +// mkdirParents creates name's missing parents, one at a time, so the +// directory holding each new one is flushed with the next Flush. func (t *localTransport) mkdirParents(name string) error { dir := path.Dir(name) if dir == "." { return nil } - if err := t.root.MkdirAll(filepath.FromSlash(dir), 0o755); err != nil { - return fmt.Errorf("create %s: %w", dir, err) + if fi, err := t.lstat(dir); err == nil && fi.IsDir() { + return nil + } + parts := strings.Split(dir, "/") + for i := range parts { + p := strings.Join(parts[:i+1], "/") + err := t.root.Mkdir(filepath.FromSlash(p), 0o755) + switch { + case err == nil: + t.markDirty(path.Dir(p)) + case !errors.Is(err, fs.ErrExist): + return fmt.Errorf("create %s: %w", dir, err) + } } return nil } -// syncDir flushes a directory, so a name created or moved in it survives -// a power cut. -func (t *localTransport) syncDir(dir string) error { - f, err := t.root.Open(filepath.FromSlash(dir)) +func (t *localTransport) markDirty(dir string) { + t.mu.Lock() + t.dirty[dir] = true + t.mu.Unlock() +} + +// syncDir flushes a directory's entries where the filesystem can. +func syncDir(root *os.Root, dir string, flush func(*os.File) error) error { + f, err := root.Open(filepath.FromSlash(dir)) + if errors.Is(err, fs.ErrNotExist) { + return nil + } if err != nil { return fmt.Errorf("open %s to sync it: %w", dir, err) } defer f.Close() - if err := f.Sync(); err != nil && !dirSyncUnsupported(err) { + if err := flush(f); err != nil && !dirSyncUnsupported(err) { return fmt.Errorf("sync %s: %w", dir, err) } return nil diff --git a/sync/transport_local_darwin.go b/sync/transport_local_darwin.go index 4299116..9a46bca 100644 --- a/sync/transport_local_darwin.go +++ b/sync/transport_local_darwin.go @@ -30,6 +30,35 @@ func bypassCache(f *os.File) { _, _ = unix.FcntlInt(f.Fd(), unix.F_NOCACHE, 1) } +// settleFile moves f's bytes to the device with a plain fsync. The drive's +// cache is flushed once for the whole batch by flushLocal, so f stays open +// until then. +func settleFile(f *os.File) (bool, error) { + return true, unix.Fsync(int(f.Fd())) +} + +// flushLocal fsyncs every changed directory, then flushes the drive's +// cache once with F_FULLFSYNC (os.File.Sync), which also persists +// everything fsynced on the device before it: the files settleFile +// fsynced included. A file carries that flush where there is one, since +// some filesystems cannot flush a directory. +func flushLocal(root *os.Root, files []*os.File, dirs []string) error { + for _, d := range dirs { + if err := syncDir(root, d, fsyncPlain); err != nil { + return err + } + } + if len(files) > 0 { + return files[0].Sync() + } + if len(dirs) == 0 { + return nil + } + return syncDir(root, ".", (*os.File).Sync) +} + +func fsyncPlain(f *os.File) error { return unix.Fsync(int(f.Fd())) } + // dirSyncUnsupported reports a filesystem that cannot flush a directory. func dirSyncUnsupported(err error) bool { return errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOTSUP) diff --git a/sync/transport_local_linux.go b/sync/transport_local_linux.go index ff59b63..40e81de 100644 --- a/sync/transport_local_linux.go +++ b/sync/transport_local_linux.go @@ -2,6 +2,7 @@ package sync import ( "errors" + "fmt" "os" "golang.org/x/sys/unix" @@ -29,6 +30,26 @@ func bypassCache(f *os.File) { _ = unix.Fadvise(int(f.Fd()), 0, 0, unix.FADV_DONTNEED) } +// settleFile leaves f to flushLocal: fsync flushes the drive itself on +// Linux, so each file is fsynced once, at the flush. +func settleFile(*os.File) (bool, error) { return true, nil } + +// flushLocal fsyncs every pending file and changed directory together, so +// the filesystem's journal commits the batch at once. +func flushLocal(root *os.Root, files []*os.File, dirs []string) error { + for _, f := range files { + if err := f.Sync(); err != nil { + return fmt.Errorf("sync %s: %w", f.Name(), err) + } + } + for _, d := range dirs { + if err := syncDir(root, d, (*os.File).Sync); err != nil { + return err + } + } + return nil +} + // dirSyncUnsupported reports a filesystem that cannot flush a directory. func dirSyncUnsupported(err error) bool { return errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOTSUP) diff --git a/sync/transport_local_other.go b/sync/transport_local_other.go index d81c20f..d91fc70 100644 --- a/sync/transport_local_other.go +++ b/sync/transport_local_other.go @@ -14,6 +14,20 @@ func renameNoReplace(root *os.Root, from, to string) error { // read may be served from it. func bypassCache(*os.File) {} +// settleFile flushes f as its Put ends: this platform offers squirrel no +// flush that covers several files. +func settleFile(f *os.File) (bool, error) { return false, f.Sync() } + +// flushLocal flushes every changed directory where the platform can. +func flushLocal(root *os.Root, _ []*os.File, dirs []string) error { + for _, d := range dirs { + if err := syncDir(root, d, (*os.File).Sync); err != nil { + return err + } + } + return nil +} + // dirSyncUnsupported: a directory cannot be flushed through a handle on // this platform, so the sync is best effort. func dirSyncUnsupported(error) bool { return true } diff --git a/sync/transport_sftp.go b/sync/transport_sftp.go index 6d37352..90e2c41 100644 --- a/sync/transport_sftp.go +++ b/sync/transport_sftp.go @@ -162,6 +162,11 @@ func (t *sftpTransport) Rename(_ context.Context, from, to string) error { return nil } +// Flush has nothing left to do: each Put flushed its file through +// fsync@openssh.com where the server offers it, and the protocol cannot +// flush a directory. +func (t *sftpTransport) Flush(context.Context) error { return nil } + func (t *sftpTransport) Remove(_ context.Context, name string) error { if err := t.checkName(name); err != nil { return err diff --git a/sync/transport_stall.go b/sync/transport_stall.go index c664a31..5fd4add 100644 --- a/sync/transport_stall.go +++ b/sync/transport_stall.go @@ -32,11 +32,14 @@ const stallBytesPerSecond = 1 << 20 // stallTransport bounds every call of the transport it wraps by progress // rather than wall-clock: a call that makes none for timeout fails with -// errTransportStalled. A Put makes progress with every chunk it reads. +// errTransportStalled. A Put makes progress with every chunk it reads; a +// Flush is also allowed the time the bytes put since the last one take at +// stallBytesPerSecond, counted in unflushed where the push keeps a count. type stallTransport struct { transport - timeout time.Duration - stalled *atomic.Int64 + timeout time.Duration + stalled *atomic.Int64 + unflushed *atomic.Int64 } // bounded runs call on its own goroutine and returns its result, or @@ -105,9 +108,29 @@ func (s stallTransport) Get(ctx context.Context, name string) (io.ReadCloser, er } func (s stallTransport) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + body := &progressingReader{timeout: s.timeout} _, err := bounded(ctx, s, "put "+name, func(ctx context.Context, progress func(time.Duration)) (struct{}, error) { - return struct{}{}, s.transport.Put(ctx, name, &progressingReader{r: r, timeout: s.timeout, progress: progress}, mtime) + body.r, body.progress = r, progress + return struct{}{}, s.transport.Put(ctx, name, body, mtime) }) + if s.unflushed != nil { + s.unflushed.Add(body.read()) + } + return err +} + +func (s stallTransport) Flush(ctx context.Context) error { + var pending int64 + if s.unflushed != nil { + pending = s.unflushed.Load() + } + _, err := bounded(ctx, s, "flush", func(ctx context.Context, progress func(time.Duration)) (struct{}, error) { + progress(s.timeout + time.Duration(pending/stallBytesPerSecond)*time.Second) + return struct{}{}, s.transport.Flush(ctx) + }) + if err == nil && s.unflushed != nil { + s.unflushed.Add(-pending) + } return err } @@ -177,22 +200,25 @@ func (r *stallReader) Close() error { } // progressingReader reports each chunk it reads as progress, and at the -// end of the body allows the final sync time to flush what it read. +// end of the body allows the time to settle what it read. A Put given up +// on may still be reading, so the count is atomic. type progressingReader struct { r io.Reader timeout time.Duration progress func(time.Duration) - n int64 + n atomic.Int64 } func (p *progressingReader) Read(b []byte) (int, error) { n, err := p.r.Read(b) - p.n += int64(n) + total := p.n.Add(int64(n)) switch { case errors.Is(err, io.EOF): - p.progress(p.timeout + time.Duration(p.n/stallBytesPerSecond)*time.Second) + p.progress(p.timeout + time.Duration(total/stallBytesPerSecond)*time.Second) case n > 0: p.progress(p.timeout) } return n, err } + +func (p *progressingReader) read() int64 { return p.n.Load() } From f2c3cfcb147a37252a0b60efc14dab3c29c47d44 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Fri, 25 Sep 2026 00:45:31 +0200 Subject: [PATCH 58/61] sync: land only what the final flush covers, and flush what reconcile relies on A content batch that stalled or was cancelled returned the artifacts it never reached as landed, and the push recorded them: the next push then skipped content the destination does not hold. putAll now fails every artifact short of its final flush, and the push stops after a batch that stalled. A push that stops before its flush leaves moves the disk may still take back. Reconcile now flushes every directory along both places of each unsettled row before recording any settlement; Flush takes those directories. A rename that finds its target taken also flushes that directory, so an adopted artifact's name is durable when it is recorded. Unrecorded moves into history are flushed before the batch's commits, like recorded ones, and a Put that returns after the transport closed releases its file. --- config/destinations.go | 16 ++++++--- design/native-mirror.md | 31 +++++++++++------ sync/artifacts_transport.go | 39 +++++++++++++++------ sync/content_addressed.go | 7 +++- sync/content_native_test.go | 66 ++++++++++++++++++++++++++++++++++++ sync/mirror_reconcile.go | 63 +++++++++++++++++++++++++++------- sync/mirror_test.go | 42 +++++++++++++++++++++++ sync/mirror_write.go | 25 +++++++++----- sync/transport.go | 8 +++-- sync/transport_fault_test.go | 4 +-- sync/transport_local.go | 27 +++++++++------ sync/transport_sftp.go | 8 ++--- sync/transport_stall.go | 4 +-- 13 files changed, 270 insertions(+), 70 deletions(-) diff --git a/config/destinations.go b/config/destinations.go index 603a352..d20e3af 100644 --- a/config/destinations.go +++ b/config/destinations.go @@ -151,11 +151,7 @@ func resolveDestination(name string, raw map[string]any) (*Destination, error) { if err != nil { return nil, err } - checkers, err := resolveCheckers(raw, typ, native) - if err != nil { - return nil, err - } - concurrency, err := resolveConcurrency(raw, typ) + checkers, concurrency, err := resolveParallelism(raw, typ, native) if err != nil { return nil, err } @@ -324,6 +320,16 @@ func resolveCheckers(raw map[string]any, typ string, native bool) (int, error) { return int(n), nil } +// resolveParallelism validates the keys that cap how much a push does at +// once: `checkers` and `concurrency`. +func resolveParallelism(raw map[string]any, typ string, native bool) (checkers, concurrency int, err error) { + if checkers, err = resolveCheckers(raw, typ, native); err != nil { + return 0, 0, err + } + concurrency, err = resolveConcurrency(raw, typ) + return checkers, concurrency, err +} + // resolveConcurrency validates the optional `concurrency` key: a positive // integer, how many files a push writes at once. Kopia drives its own // parallelism, so the key is rejected there. diff --git a/design/native-mirror.md b/design/native-mirror.md index b858277..a10af0c 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -251,9 +251,10 @@ type transport interface { // The move is durable once a later Flush returns. Rename(ctx context.Context, from, to string) error Remove(ctx context.Context, name string) error - // Flush returns once every Put and Rename that returned before it is on - // stable storage. - Flush(ctx context.Context) error + // Flush returns once every Put and Rename that returned before it, and + // the entries of dirs, are on stable storage. dirs names directories an + // earlier process may have changed, which the caller is about to rely on. + Flush(ctx context.Context, dirs ...string) error Close() error } ``` @@ -495,7 +496,8 @@ out of the batch, and the others go on. staged file stays until the next push's reconcile removes it with the finished run's staging: the name guard removes no running run's staging. That is the `errContentDrift` contract. Here the hash covers exactly the bytes sent, which closes the re-hash-then-read gap - noted on `uploadOneObject`. The batch's staged files are then flushed. + noted on the rclone artifact store's `put`. The batch's staged files are + then flushed. 3. **Read back**, on a local disk: every staged file is read in full, past the cache, through BLAKE3 (section 5). A mismatch fails the path before it touches the live tree. @@ -617,7 +619,10 @@ A power cut can also undo whatever the last flush didn't cover. Every row still finds its bytes at one of the two places the table checks: no row leaves `displacing` or `committing` before the flush that covers its move, and a staged file is flushed before it's renamed onto a path. The receipt is -flushed before the run is sealed. +flushed before the run is sealed. A push that stopped before its flush — +cancelled, stalled, killed — leaves moves the disk may still take back, so +reconcile flushes every directory along both places of each unsettled row +before it records any settlement. `TestMirrorCrashTable` runs each row above; `TestMirrorTranslationRules` and `TestMirrorWriteDisplacesWhatThePathHolds` run the translation table. @@ -636,9 +641,12 @@ usual: fault-injecting transport wrapper, then a clean push. The invariants below must hold afterwards. It writes one path at a time, so the calls come in the same order on every run; `Flush` is a call like any other. -- **Power cuts.** The same wrapper can, at the crash, also undo every `Put` - and `Rename` since the last `Flush`: a put file vanishes or is cut short, - a rename is reversed. The invariants must hold after the next clean push. +- **Power cuts.** The same wrapper can, at the crash, also take back what no + `Flush` covered: every `Put` and `Rename` since the last one undone (a put + file vanishes, a rename is reversed), or every name kept but none of those + files' bytes. The invariants must hold after the next clean push. A first + push, which displaces nothing, runs it too: there only the flush after + staging stands between a staged file's bytes and its commit. - **A model-based test.** It generates random index histories: add, modify, delete, re-add, file↔directory swaps, names that collide by case. It then pushes with several paths in flight and random crash points, some of them @@ -684,7 +692,7 @@ Where each case lives: | Case | Tests | |---|---| | Crash at every call, then a clean push | `TestMirrorCrashAtEveryTransportCall`, `TestNativeContentCrashAtEveryTransportCall` (`sync/crash_every_call_test.go`) | -| Power cuts at every call | `TestMirrorPowerCutAtEveryTransportCall`, `TestNativeContentPowerCutAtEveryTransportCall` (`sync/crash_every_call_test.go`) | +| Power cuts at every call | `TestMirrorPowerCutAtEveryTransportCall`, `TestNativeContentPowerCutAtEveryTransportCall` (`sync/crash_every_call_test.go`), `TestMirrorFirstPushSurvivesAPowerCutAtEveryCall` | | Random histories against a model | `TestMirrorModel` (`sync/mirror_model_test.go`) | | File↔directory swaps | `TestMirrorFileDirectorySwap`, `TestMirrorNestedFileDirectorySwaps` | | Unrecorded and changed entries at a target | `TestMirrorWriteDisplacesWhatThePathHolds`, `TestMirrorRecordChangedBehindSquirrelsBack` | @@ -793,7 +801,8 @@ gcs. Objects land in batches, like a mirror's paths: at most 64 or 256 MB, confirmed instead (downloaded and hashed when the server runs no command), or the artifact fails. Squirrel never replaces it; 4. the batch is flushed, and only then is each landed artifact's upload row - recorded, with its fingerprint. + recorded, with its fingerprint. An artifact a stall or cancellation kept + from that flush fails, and the push stops after a batch that stalled. A pack, the placement map and the manifest segment land alone, through the same steps. @@ -873,7 +882,7 @@ addressed local destinations by path; that restriction is gone. computes to check the server's answer. rclone's other hashes (`crc32`, `xxh3`, `xxh128`) stay valid behind crypt only. - **`concurrency`** is how many files a push writes at once, on every - destination type: 4 by default on a local disk, 8 on sftp. A storage + destination type but kopia: 4 by default on a local disk, 8 on sftp. A storage server that limits concurrent connections, or a slow disk or USB bridge, may want it lower. On a destination squirrel writes itself, the files share one SSH connection (section 3), and each file on sftp also goes out as up diff --git a/sync/artifacts_transport.go b/sync/artifacts_transport.go index 5024334..c98c2d8 100644 --- a/sync/artifacts_transport.go +++ b/sync/artifacts_transport.go @@ -89,7 +89,8 @@ type artifactLanding struct { // putAll takes the artifacts through the steps of a landing, each for all // of them before the next: stage, flush, confirm, rename, flush. An -// artifact whose step fails drops out. +// artifact whose step fails drops out; one a stall or cancellation kept +// from the final flush fails too, since only that flush lands it. func (a *transportArtifacts) putAll(ctx context.Context, runID int64, items []artifactPut) []artifactResult { out := make([]artifactResult, len(items)) tr, err := a.root(ctx, runID) @@ -105,10 +106,14 @@ func (a *transportArtifacts) putAll(ctx context.Context, runID int64, items []ar } b := artifactBatch{a: a, tr: tr, n: pushConcurrency(a.dest)} b.each(ctx, ls, b.stage) - b.flush(ctx, ls, "flush the staged artifacts") - b.each(ctx, ls, b.confirmStaged) - b.each(ctx, ls, b.rename) - b.flush(ctx, ls, "flush the landed artifacts") + if b.flush(ctx, ls, "flush the staged artifacts") { + b.each(ctx, ls, b.confirmStaged) + b.each(ctx, ls, b.rename) + if b.flush(ctx, ls, "flush the landed artifacts") { + return out + } + } + b.abandon(ctx, ls) return out } @@ -133,17 +138,31 @@ func (b *artifactBatch) each(ctx context.Context, ls []*artifactLanding, step fu }) } -// flush makes the batch's last step durable; a flush that fails fails -// every artifact still on its way. -func (b *artifactBatch) flush(ctx context.Context, ls []*artifactLanding, what string) { +// flush makes the batch's last step durable and reports whether it did. +// A flush that fails fails every artifact still on its way; a stalled or +// cancelled batch goes no further. +func (b *artifactBatch) flush(ctx context.Context, ls []*artifactLanding, what string) bool { pending := pendingArtifacts(ls) - if len(pending) == 0 || b.stalled.Load() { - return + if len(pending) == 0 || b.stalled.Load() || ctx.Err() != nil { + return false } if err := b.tr.Flush(ctx); err != nil { for _, l := range pending { l.res.err = fmt.Errorf("%s: %w", what, err) } + return false + } + return true +} + +// abandon fails every artifact the batch stopped short of landing. +func (b *artifactBatch) abandon(ctx context.Context, ls []*artifactLanding) { + why := ctx.Err() + if why == nil { + why = fmt.Errorf("%w: the batch stopped before the artifact landed", errTransportStalled) + } + for _, l := range pendingArtifacts(ls) { + l.res.err = why } } diff --git a/sync/content_addressed.go b/sync/content_addressed.go index b9d7c59..b321de0 100644 --- a/sync/content_addressed.go +++ b/sync/content_addressed.go @@ -11,6 +11,7 @@ import ( "os" "path" "path/filepath" + "slices" "strconv" "github.com/zeebo/blake3" @@ -266,7 +267,8 @@ func (h *contentPusher) uploadObjects(ctx context.Context, rep *Report, runID in if err := ctx.Err(); err != nil { return err } - for i, res := range h.uploadBatch(ctx, runID, batch) { + results := h.uploadBatch(ctx, runID, batch) + for i, res := range results { d := batch[i] switch { case errors.Is(res.err, errContentDrift): @@ -288,6 +290,9 @@ func (h *contentPusher) uploadObjects(ctx context.Context, rep *Report, runID in rep.RcloneResult.Transferred++ rep.RcloneResult.Bytes += d.SizeBytes } + if slices.ContainsFunc(results, func(r artifactResult) bool { return errors.Is(r.err, errTransportStalled) }) { + break + } } h.captureFingerprints(ctx, rep, pending) if rep.RcloneResult.Errors > 0 { diff --git a/sync/content_native_test.go b/sync/content_native_test.go index 801e13f..ae3edc6 100644 --- a/sync/content_native_test.go +++ b/sync/content_native_test.go @@ -6,10 +6,13 @@ import ( "encoding/hex" "errors" "fmt" + "io" "os" "path/filepath" "strings" + "sync/atomic" "testing" + "time" "github.com/mbertschler/squirrel/config" "github.com/mbertschler/squirrel/index" @@ -256,6 +259,69 @@ func TestNativeContentPushWithoutRclone(t *testing.T) { // TestNativeContentWithoutServerHash: an sftp server that runs no programs // still takes every artifact, whole, but fingerprints nothing: the objects // stay pending with a warning and the vector stays presence+size. +// stallingPuts holds the nth Put into staging, and every one after it, +// until release is closed. +type stallingPuts struct { + transport + n int32 + seen *atomic.Int32 + release chan struct{} +} + +func (s stallingPuts) Put(ctx context.Context, name string, r io.Reader, mtime time.Time) error { + if strings.Contains(name, "/"+StagingDirName+"/run-") && s.seen.Add(1) >= s.n { + <-s.release + } + return s.transport.Put(ctx, name, r, mtime) +} + +// TestNativeContentStallRecordsOnlyWhatLanded: a content-addressed push +// whose transport stalls halfway through a batch records no object it did +// not land and flush, so the push after the stall clears lands the rest. +func TestNativeContentStallRecordsOnlyWhatLanded(t *testing.T) { + f := setupNativeContentFixture(t, contentBackends[0], config.LayoutContentAddressed) + f.oneAtATime() + bodies := []string{"one", "two", "three", "four", "five"} + for _, b := range bodies { + f.write(t, b+".txt", b) + } + f.index(t) + h, err := HandlerFor(f.store, Tools{}, f.pair) + if err != nil { + t.Fatal(err) + } + root := h.(*contentAddressedHandler).art.(*transportArtifacts).destinationRoot + release := make(chan struct{}) + root.stallTimeout = 50 * time.Millisecond + root.openTransport = func(ctx context.Context, d *config.Destination) (transport, error) { + raw, err := openDestinationTransport(ctx, d) + return stallingPuts{transport: raw, n: 3, seen: new(atomic.Int32), release: release}, err + } + rep, err := h.Push(context.Background(), Options{}) + if err == nil || len(rep.RcloneResult.FailedFiles) == 0 || !strings.Contains(rep.RcloneResult.FailedFiles[0].Message, errTransportStalled.Error()) { + t.Fatalf("stalled push = %v, failures %+v; want it failed on the stall", err, rep.RcloneResult.FailedFiles) + } + for _, b := range bodies { + if _, recorded := f.remoteObject(t, b); recorded { + if _, err := os.Stat(f.objectPath(b)); err != nil { + t.Errorf("object %q is recorded but not at its name: %v", b, err) + } + } + } + close(release) + deadline := time.Now().Add(5 * time.Second) + for stalledCounter("vault").Load() > 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + f.mustPush(t) + f.checkArtifactsVouch(t) + for _, b := range bodies { + if _, recorded := f.remoteObject(t, b); !recorded { + t.Errorf("object %q not recorded after the push that followed the stall", b) + } + } +} + func TestNativeContentWithoutServerHash(t *testing.T) { f := setupNativeContentFixture(t, sftpContentNoPrograms, config.LayoutContentAddressed) f.write(t, "a.txt", "alpha") diff --git a/sync/mirror_reconcile.go b/sync/mirror_reconcile.go index f979754..422bf75 100644 --- a/sync/mirror_reconcile.go +++ b/sync/mirror_reconcile.go @@ -5,13 +5,16 @@ import ( "errors" "fmt" "io/fs" + "path" "github.com/mbertschler/squirrel/store" ) // reconcile settles, once at push start, every move an earlier push // recorded but may not have finished, deciding each from where the bytes -// actually are, then removes the staging finished runs left behind. +// actually are, then removes the staging finished runs left behind. The +// earlier push may have stopped before flushing its moves, so the +// directories they touched are flushed before any settlement is recorded. func (h *mirrorHandler) reconcile(ctx context.Context, rep *Report, volumeID, runID int64) error { tr, err := h.root(ctx, runID) if err != nil { @@ -21,14 +24,47 @@ func (h *mirrorHandler) reconcile(ctx context.Context, rep *Report, volumeID, ru if err != nil { return fmt.Errorf("list unsettled mirror paths on %q: %w", h.dest.Name, err) } - for _, r := range rows { - if err := h.settle(ctx, tr, r); err != nil { + settlements := make([]settlement, len(rows)) + var dirs []string + for i, r := range rows { + if settlements[i], err = h.settle(ctx, tr, r); err != nil { + return fmt.Errorf("reconcile %s on %q: %w", r.Path, h.dest.Name, err) + } + dirs = append(dirs, h.movedThrough(r)...) + } + if len(rows) > 0 { + if err := tr.Flush(ctx, dirs...); err != nil { + return fmt.Errorf("flush the moves an earlier push left in flight on %q: %w", h.dest.Name, err) + } + } + for i, r := range rows { + if err := h.recordSettlement(ctx, r, settlements[i]); err != nil { return fmt.Errorf("reconcile %s on %q: %w", r.Path, h.dest.Name, err) } } return h.clearFinishedStaging(ctx, rep, tr) } +// movedThrough is every directory along the two places an unsettled +// row's version can be: the rename that moved it may have moved a +// directory above it. +func (h *mirrorHandler) movedThrough(r store.RemotePath) []string { + other := stagingName(h.vol.Name, r.WrittenRunID, stagingKey(r.Path)) + if r.State == store.RemotePathDisplacing { + other = historyName(h.vol.Name, r.DisplacedRunID.Int64, r.Path) + } + return append(ancestors(h.liveName(r.Path)), ancestors(other)...) +} + +// ancestors is every directory above name, below the root. +func ancestors(name string) []string { + var out []string + for d := path.Dir(name); d != "."; d = path.Dir(d) { + out = append(out, d) + } + return out +} + // settlement is how reconcile resolves one unsettled row. type settlement int @@ -36,33 +72,32 @@ const ( settleLive settlement = iota settleDisplaced settleLost + settleNothing ) // settle looks at both places an unsettled row's version can be and -// records where it is. -func (h *mirrorHandler) settle(ctx context.Context, tr transport, r store.RemotePath) error { +// decides where it is. +func (h *mirrorHandler) settle(ctx context.Context, tr transport, r store.RemotePath) (settlement, error) { at, err := statMatch(ctx, tr, h.liveName(r.Path), r) if err != nil { - return err + return settleNothing, err } - var s settlement switch r.State { case store.RemotePathCommitting: staged, err := present(ctx, tr, stagingName(h.vol.Name, r.WrittenRunID, stagingKey(r.Path))) if err != nil { - return err + return settleNothing, err } - s = settleCommitting(staged, at) + return settleCommitting(staged, at), nil case store.RemotePathDisplacing: inHistory, err := statMatch(ctx, tr, historyName(h.vol.Name, r.DisplacedRunID.Int64, r.Path), r) if err != nil { - return err + return settleNothing, err } - s = settleDisplacing(inHistory, at) + return settleDisplacing(inHistory, at), nil default: - return nil + return settleNothing, nil } - return h.recordSettlement(ctx, r, s) } // settleCommitting decides a committing row: its version is live once the @@ -92,6 +127,8 @@ func settleDisplacing(inHistory, atPath bool) settlement { func (h *mirrorHandler) recordSettlement(ctx context.Context, r store.RemotePath, s settlement) error { switch { + case s == settleNothing: + return nil case s == settleLost: return h.store.MarkRemotePathsLost(ctx, r.ID) case r.State == store.RemotePathCommitting: diff --git a/sync/mirror_test.go b/sync/mirror_test.go index 6abf378..0399f17 100644 --- a/sync/mirror_test.go +++ b/sync/mirror_test.go @@ -940,6 +940,48 @@ func TestMirrorProgressEvents(t *testing.T) { } } +// flushRecorder notes the directories each Flush was asked to cover. +type flushRecorder struct { + transport + flushes *[][]string +} + +func (r flushRecorder) Flush(ctx context.Context, dirs ...string) error { + *r.flushes = append(*r.flushes, dirs) + return r.transport.Flush(ctx, dirs...) +} + +// TestMirrorReconcileFlushesWhatItSettles: a push that died after renaming +// a staged file onto its path, before the flush that makes the rename +// durable, leaves its row committing; the next push flushes the path's +// directories and the staging directory before it records the row live. +func TestMirrorReconcileFlushesWhatItSettles(t *testing.T) { + f := setupMirrorFixture(t) + f.oneAtATime() + f.write(t, "d/a.txt", "alpha") + f.index(t) + crash, err := f.pushCrashing(t, func(c transportCall) bool { + return c.op == "rename" && path.Base(c.to) == "a.txt" + }, crashAfter) + if !crashedOn(crash, err) { + t.Fatalf("crashing push = %v, want the injected crash", err) + } + if got := f.rowsAt(t, "d/a.txt"); len(got) != 1 || got[0] != store.RemotePathCommitting { + t.Fatalf("d/a.txt rows = %v, want one committing", got) + } + var flushes [][]string + if _, err := f.pushVia(t, Options{}, func(tr transport) transport { return flushRecorder{tr, &flushes} }); err != nil { + t.Fatal(err) + } + staging := path.Dir(stagingName("pics", crash.RunID, stagingKey("d/a.txt"))) + if len(flushes) == 0 || !slices.Contains(flushes[0], "pics/d") || !slices.Contains(flushes[0], staging) { + t.Fatalf("first flush covered %v, want pics/d and %s", flushes, staging) + } + if got := f.rowsAt(t, "d/a.txt"); len(got) != 1 || got[0] != store.RemotePathLive { + t.Fatalf("d/a.txt rows = %v, want one live", got) + } +} + // blockingTransport holds every Stat until release is closed. type blockingTransport struct { transport diff --git a/sync/mirror_write.go b/sync/mirror_write.go index d34aa97..c3d5c61 100644 --- a/sync/mirror_write.go +++ b/sync/mirror_write.go @@ -24,7 +24,7 @@ import ( // mirrorWriter carries one run's execution: the guarded transport, the // live records it keeps current, and the tally for the report. Several // paths are in flight at once, so the records and the tally are shared -// behind mu, which is never held across a transport call. +// behind mu; transport calls run outside it. type mirrorWriter struct { h *mirrorHandler rep *Report @@ -44,8 +44,10 @@ type mirrorWriter struct { mu gosync.Mutex live map[string]store.RemotePath // displacing is the rows this batch moved into history, which the - // batch's flush lets it record as displaced. + // batch's flush lets it record as displaced; movedAside counts every + // move into history, recorded or not. displacing []int64 + movedAside int done int drifted int collided int @@ -244,19 +246,20 @@ func (w *mirrorWriter) displaceLanding(ctx context.Context, l *landing) error { return w.displace(ctx, l.p.delta.Path) } -// recordDisplaced flushes the batch's moves into history, then records -// them as displaced. Until then their rows stay displacing, which the -// next push's reconcile settles from where the bytes are. +// recordDisplaced flushes the batch's moves into history, so they land +// before any commit, then records the recorded ones as displaced. Until +// then their rows stay displacing, which the next push's reconcile +// settles from where the bytes are. func (w *mirrorWriter) recordDisplaced(ctx context.Context, ls []*landing) { w.mu.Lock() - ids := w.displacing - w.displacing = nil + ids, moved := w.displacing, w.movedAside + w.displacing, w.movedAside = nil, 0 w.mu.Unlock() - if len(ids) == 0 { + if moved == 0 { return } err := w.tr.Flush(ctx) - if err == nil { + if err == nil && len(ids) > 0 { err = w.h.store.ConfirmRemotePathsDisplaced(ctx, ids...) } if err != nil { @@ -512,6 +515,7 @@ func (w *mirrorWriter) moveRecorded(ctx context.Context, rel string, ids []int64 w.mu.Lock() defer w.mu.Unlock() w.displacing = append(w.displacing, ids...) + w.movedAside++ for r := range w.live { if r == rel || w.fold.under(r, rel) { delete(w.live, r) @@ -531,6 +535,9 @@ func (w *mirrorWriter) moveUnrecorded(ctx context.Context, rel string, e entry) if err := w.tr.Rename(ctx, w.h.liveName(rel), to); err != nil { return fmt.Errorf("displace unrecorded %s: %w", rel, err) } + w.mu.Lock() + w.movedAside++ + w.mu.Unlock() w.warn(fmt.Sprintf("destination %q: %s held bytes squirrel did not write (%d bytes); they are preserved at %s", w.h.dest.Name, rel, e.size, to)) return nil } diff --git a/sync/transport.go b/sync/transport.go index dc92ade..2b8ca1f 100644 --- a/sync/transport.go +++ b/sync/transport.go @@ -31,9 +31,11 @@ type transport interface { // Rename moves from to to, creating to's parents; fs.ErrExist if to // exists. Rename(ctx context.Context, from, to string) error - // Flush returns once every Put and Rename that returned before it is - // on stable storage, as far as the destination can make it so. - Flush(ctx context.Context) error + // Flush returns once every Put and Rename that returned before it, and + // the entries of every directory in dirs, are on stable storage, as far + // as the destination can make it so. dirs names directories an earlier + // process may have changed, which a caller is about to rely on. + Flush(ctx context.Context, dirs ...string) error // Remove deletes the file or empty directory at name. Remove(ctx context.Context, name string) error // ServerHash is the destination's own hash of the file at name, run diff --git a/sync/transport_fault_test.go b/sync/transport_fault_test.go index 044063c..e04fcda 100644 --- a/sync/transport_fault_test.go +++ b/sync/transport_fault_test.go @@ -188,9 +188,9 @@ func followRenames(name string, renames []transportCall) string { return name } -func (f *faultTransport) Flush(ctx context.Context) error { +func (f *faultTransport) Flush(ctx context.Context, dirs ...string) error { return f.do(transportCall{op: "flush"}, func(bool) error { - return f.transport.Flush(ctx) + return f.transport.Flush(ctx, dirs...) }) } diff --git a/sync/transport_local.go b/sync/transport_local.go index e2c2056..fb3b99b 100644 --- a/sync/transport_local.go +++ b/sync/transport_local.go @@ -31,6 +31,7 @@ type localTransport struct { mu sync.Mutex pending []*os.File dirty map[string]bool + closed bool } func openLocalTransport(dir string) (*localTransport, error) { @@ -46,7 +47,7 @@ func (t *localTransport) Close() error { for _, f := range t.pending { _ = f.Close() } - t.pending = nil + t.pending, t.closed = nil, true t.mu.Unlock() return t.root.Close() } @@ -142,8 +143,11 @@ func (t *localTransport) settle(f *os.File, name string) error { return nil } t.mu.Lock() + defer t.mu.Unlock() + if t.closed { + return f.Close() + } t.pending = append(t.pending, f) - t.mu.Unlock() return nil } @@ -171,18 +175,21 @@ func (t *localTransport) Rename(_ context.Context, from, to string) error { if err := t.mkdirParents(to); err != nil { return err } + t.markDirty(path.Dir(to)) if err := renameNoReplace(t.root, from, to); err != nil { return err } t.markDirty(path.Dir(from)) - t.markDirty(path.Dir(to)) return nil } -// Flush makes every file Put left open, and every directory a call -// changed, durable, then releases the files. -func (t *localTransport) Flush(context.Context) error { +// Flush makes every file Put left open, every directory a call changed, +// and dirs durable, then releases the files. +func (t *localTransport) Flush(_ context.Context, dirs ...string) error { t.mu.Lock() + for _, d := range dirs { + t.dirty[d] = true + } files, dirty := t.pending, t.dirty t.pending, t.dirty = nil, map[string]bool{} t.mu.Unlock() @@ -191,12 +198,12 @@ func (t *localTransport) Flush(context.Context) error { _ = f.Close() } }() - dirs := make([]string, 0, len(dirty)) + sorted := make([]string, 0, len(dirty)) for d := range dirty { - dirs = append(dirs, d) + sorted = append(sorted, d) } - slices.Sort(dirs) - return flushLocal(t.root, files, dirs) + slices.Sort(sorted) + return flushLocal(t.root, files, sorted) } func (t *localTransport) Remove(_ context.Context, name string) error { diff --git a/sync/transport_sftp.go b/sync/transport_sftp.go index 90e2c41..73f8535 100644 --- a/sync/transport_sftp.go +++ b/sync/transport_sftp.go @@ -162,10 +162,10 @@ func (t *sftpTransport) Rename(_ context.Context, from, to string) error { return nil } -// Flush has nothing left to do: each Put flushed its file through -// fsync@openssh.com where the server offers it, and the protocol cannot -// flush a directory. -func (t *sftpTransport) Flush(context.Context) error { return nil } +// Flush returns at once: each Put already flushed its file through +// fsync@openssh.com where the server offers it, and flushing a directory +// is beyond the protocol. +func (t *sftpTransport) Flush(context.Context, ...string) error { return nil } func (t *sftpTransport) Remove(_ context.Context, name string) error { if err := t.checkName(name); err != nil { diff --git a/sync/transport_stall.go b/sync/transport_stall.go index 5fd4add..7fcc0c8 100644 --- a/sync/transport_stall.go +++ b/sync/transport_stall.go @@ -119,14 +119,14 @@ func (s stallTransport) Put(ctx context.Context, name string, r io.Reader, mtime return err } -func (s stallTransport) Flush(ctx context.Context) error { +func (s stallTransport) Flush(ctx context.Context, dirs ...string) error { var pending int64 if s.unflushed != nil { pending = s.unflushed.Load() } _, err := bounded(ctx, s, "flush", func(ctx context.Context, progress func(time.Duration)) (struct{}, error) { progress(s.timeout + time.Duration(pending/stallBytesPerSecond)*time.Second) - return struct{}{}, s.transport.Flush(ctx) + return struct{}{}, s.transport.Flush(ctx, dirs...) }) if err == nil && s.unflushed != nil { s.unflushed.Add(-pending) From a16ca44f55b827a72bfaced056b988ec52d7e7c5 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Fri, 25 Sep 2026 00:46:10 +0200 Subject: [PATCH 59/61] design: record the benchmark after decision 8 Rerun on the testbed against main's rclone mirrors and the branch before the change: sftp at a 20 ms round trip is at rclone's speed with the default concurrency, and the exFAT image is 2-3 times faster than before, about twice rclone's time, the rest being the read-back. F40 is fixed. --- design/friction-log.md | 13 +++++++++---- design/native-mirror.md | 28 ++++++++++++++++++++++++++++ design/testbed.md | 5 ++++- 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/design/friction-log.md b/design/friction-log.md index d35578b..6890672 100644 --- a/design/friction-log.md +++ b/design/friction-log.md @@ -607,10 +607,15 @@ open error. target that can gate but the local mirror, which the same message's reason names. -**F40 · S1 — native pushes that write are several times slower than -rclone.** A first push took 116 s against rclone's 13 s on the exFAT image, -and 432 s against 45 s over sftp at a 20 ms round trip; unchanged pushes are -faster. Open: native-mirror.md, open question 2. +**F40 · S1 — ~~native pushes that write are several times slower than +rclone.~~ (fixed in #217)** A first push took 116 s against rclone's 13 s on +the exFAT image, and 432 s against 45 s over sftp at a 20 ms round trip; +unchanged pushes are faster. The cost was three full flushes per file on a +local disk and 27 sequential requests per path over sftp. Decision 8 in +native-mirror.md flushes once per batch and writes several paths at once +(`concurrency`); rerun, the first push takes 42 s against rclone's 19–24 s +on the exFAT image, where reading every byte back is the remaining cost, +and 50 s against 47 s at a 20 ms round trip. Observed, by design: a copy corrupted in place on the local mirror, size and mtime kept, passed two verify passes because each re-reads only a tenth of diff --git a/design/native-mirror.md b/design/native-mirror.md index a10af0c..b559f12 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -974,6 +974,34 @@ time for the 608-file tree (45 s); rclone itself checks no parent chain and writes through a symlinked directory (rclone 1.74.1 against the in-process server). +**After decision 8** (2026-09-25, same laptop). Three binaries this time — +`main`'s (rclone), this branch just before the change, and this branch with +it — on the same trees regenerated by `gendata` (`pics` 4540 files, 716 MB; +`trip` 608 files, 123 MB), each on a fresh index and destination. The exFAT +image fills as runs pile up and its timings drift with it, so every `usb` run +got a freshly created image, and ran twice (ranges below). Wall time in +seconds: + +| Push | usb (pics) rclone | before | after | box (pics) rclone | before | after | wan (trip) rclone | before | after | +|---|---|---|---|---|---|---|---|---|---| +| first | 19.0–24.2 | 116.1–127.4 | 41.4–43.6 | 3.1 | 16.6 | 5.7 | 46.9 | 409.4 | 49.7 | +| unchanged | 2.7–3.5 | 0.14–0.20 | 0.11 | 1.84 | 0.10 | 0.09 | 7.22 | 1.89 | 1.88 | +| changed | 1.8–2.8 | 9.1–10.1 | 2.9–3.9 | 1.99 | 1.30 | 0.78 | 8.38 | 45.66 | 8.05 | + +- **sftp at a 20 ms round trip is at rclone's speed**, with the default of 8 + paths in flight: 49.7 s against 46.9 s, from 409 s. The instrumented push + measured 91.5 ms per path at 8, 56.5 at 16 and 37.4 at 32, so a + destination on a slow link can go past rclone by raising `concurrency`. +- **A local disk is 2–3 times faster than before, and about twice rclone's + time on the exFAT image.** The instrumented push went from 27.6 to 5.3 ms + per file there (19 to 1.2 on the internal disk). What is left is the + evidence — writing past the cache and reading every byte back — and exFAT's + slow file calls. More paths in flight don't help that disk: 9.2 ms per + file at 1, 5.3 at 4, 5.7 at 8, which is why a local disk defaults to 4. +- **Unchanged pushes stay faster than rclone everywhere, and so do changed + ones** except on the exFAT image, where a changed push takes about 1.4 + times rclone's time. + - **A new dependency:** `github.com/pkg/sftp`. ## 9. Order of work diff --git a/design/testbed.md b/design/testbed.md index 964effa..d252835 100644 --- a/design/testbed.md +++ b/design/testbed.md @@ -58,7 +58,10 @@ sftp`. Loopback hides what a real link costs per round trip, so a third destination reached the same server through a TCP proxy that delays every chunk by a fixed time each way, kept outside the repo. Restart `rclone serve sftp` after removing files under its root behind its back: its directory -cache otherwise keeps answering for them. +cache otherwise keeps answering for them. The 2026-09-25 rerun after +decision 8 added the branch's binary from before the change as a third +column, and gave every exFAT run a freshly created image: a sparse image's +timings drift as it fills. Deliberately not simulated: Synology/QNAP packaging (below squirrel), b2/gcs (same shape as s3), real network partitions — a dead machine or From d07821b16afa4c2071ffa924652334c544ac5f7d Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Fri, 25 Sep 2026 17:02:29 +0200 Subject: [PATCH 60/61] sync: count live records per directory so a push stays linear For every path with nothing at it, the mirror writer scanned every live record for records below it, under the lock the paths in flight share: a first push was quadratic in its file count. At 30,000 files the displace step took 62 s. The writer now keeps a count of the live records below each directory, as the destination resolves names, and asks it first; the same push's displace step takes 0.6 s. --- sync/mirror_fold.go | 2 +- sync/mirror_live.go | 71 +++++++++++++++++++++++++++++++++++++ sync/mirror_live_test.go | 76 ++++++++++++++++++++++++++++++++++++++++ sync/mirror_write.go | 38 +++++++++----------- 4 files changed, 165 insertions(+), 22 deletions(-) create mode 100644 sync/mirror_live.go create mode 100644 sync/mirror_live_test.go diff --git a/sync/mirror_fold.go b/sync/mirror_fold.go index 17c36dc..d88b731 100644 --- a/sync/mirror_fold.go +++ b/sync/mirror_fold.go @@ -185,7 +185,7 @@ func (w *mirrorWriter) foldGroups(ops *mirrorOps) map[string][]foldMember { } interest[key] = true } - for rel := range w.live { + for rel := range w.live.byPath { if c, ok := claims[rel]; ok { c.live = true continue diff --git a/sync/mirror_live.go b/sync/mirror_live.go new file mode 100644 index 0000000..5435160 --- /dev/null +++ b/sync/mirror_live.go @@ -0,0 +1,71 @@ +package sync + +import ( + "github.com/mbertschler/squirrel/store" +) + +// liveRecords is the live records a push keeps current, by path, with a +// count of the records below every directory as the destination resolves +// names. Asking what lies below a path that holds nothing — every new +// path of a push asks — costs one lookup, so a push stays linear in the +// paths it writes. The writer's lock guards it. +type liveRecords struct { + fold nameFolding + byPath map[string]store.RemotePath + below map[string]int +} + +func newLiveRecords(fold nameFolding, rows map[string]store.RemotePath) *liveRecords { + l := &liveRecords{fold: fold, byPath: make(map[string]store.RemotePath, len(rows)), below: map[string]int{}} + for _, r := range rows { + l.set(r) + } + return l +} + +func (l *liveRecords) at(rel string) (store.RemotePath, bool) { + r, ok := l.byPath[rel] + return r, ok +} + +// set records r as the live record at its path. +func (l *liveRecords) set(r store.RemotePath) { + l.remove(r.Path) + l.byPath[r.Path] = r + l.countAncestors(r.Path, 1) +} + +func (l *liveRecords) remove(rel string) { + if _, ok := l.byPath[rel]; !ok { + return + } + delete(l.byPath, rel) + l.countAncestors(rel, -1) +} + +// under is every live record below dir. +func (l *liveRecords) under(dir string) []store.RemotePath { + if l.below[l.fold.key(dir)] == 0 { + return nil + } + var out []store.RemotePath + for rel, r := range l.byPath { + if l.fold.under(rel, dir) { + out = append(out, r) + } + } + return out +} + +// countAncestors adds by to the count of every directory above rel. +func (l *liveRecords) countAncestors(rel string, by int) { + key := l.fold.key(rel) + for i := range len(key) { + if key[i] != '/' { + continue + } + if l.below[key[:i]] += by; l.below[key[:i]] == 0 { + delete(l.below, key[:i]) + } + } +} diff --git a/sync/mirror_live_test.go b/sync/mirror_live_test.go new file mode 100644 index 0000000..c0c5ad1 --- /dev/null +++ b/sync/mirror_live_test.go @@ -0,0 +1,76 @@ +package sync + +import ( + "maps" + "math/rand/v2" + "slices" + "strings" + "testing" + + "github.com/mbertschler/squirrel/store" +) + +// TestLiveRecordsMatchAScan: through random sets and removes, on a +// destination that folds names and one that doesn't, under always returns +// what a scan of every record returns, and the counts that let it answer +// in one lookup always match a recount. +func TestLiveRecordsMatchAScan(t *testing.T) { + for _, fold := range []nameFolding{{}, caseAndNormFolding} { + rng := rand.New(rand.NewPCG(7, 7)) + randomPath := func() string { + elems := make([]string, 1+rng.IntN(3)) + for i := range elems { + elems[i] = []string{"a", "A", "b", "é", "é"}[rng.IntN(5)] + } + return strings.Join(elems, "/") + } + l := newLiveRecords(fold, map[string]store.RemotePath{"a/b": {Path: "a/b"}, "b": {Path: "b"}}) + for step := range 2000 { + if p := randomPath(); rng.IntN(3) == 0 { + l.remove(p) + } else { + l.set(store.RemotePath{Path: p, ID: int64(step)}) + } + dir := randomPath() + if got, want := sortedPaths(l.under(dir)), scanUnder(l, dir); !slices.Equal(got, want) { + t.Fatalf("folds=%v step %d: under(%q) = %v, want %v", fold.folds(), step, dir, got, want) + } + } + if want := recountBelow(l); !maps.Equal(l.below, want) { + t.Fatalf("folds=%v: counts = %v, want %v", fold.folds(), l.below, want) + } + } +} + +func sortedPaths(rs []store.RemotePath) []string { + out := make([]string, 0, len(rs)) + for _, r := range rs { + out = append(out, r.Path) + } + slices.Sort(out) + return out +} + +func scanUnder(l *liveRecords, dir string) []string { + out := []string{} + for rel := range l.byPath { + if l.fold.under(rel, dir) { + out = append(out, rel) + } + } + slices.Sort(out) + return out +} + +func recountBelow(l *liveRecords) map[string]int { + out := map[string]int{} + for rel := range l.byPath { + key := l.fold.key(rel) + for i := range len(key) { + if key[i] == '/' { + out[key[:i]]++ + } + } + } + return out +} diff --git a/sync/mirror_write.go b/sync/mirror_write.go index c3d5c61..a3fe9d1 100644 --- a/sync/mirror_write.go +++ b/sync/mirror_write.go @@ -42,7 +42,7 @@ type mirrorWriter struct { total int mu gosync.Mutex - live map[string]store.RemotePath + live *liveRecords // displacing is the rows this batch moved into history, which the // batch's flush lets it record as displaced; movedAside counts every // move into history, recorded or not. @@ -63,7 +63,7 @@ func (h *mirrorHandler) execute(ctx context.Context, rep *Report, runID int64, o if err != nil { return err } - w := &mirrorWriter{h: h, rep: rep, runID: runID, volumeID: ops.volumeID, tr: tr, live: ops.live, + w := &mirrorWriter{h: h, rep: rep, runID: runID, volumeID: ops.volumeID, tr: tr, concurrency: pushConcurrency(h.dest), progress: h.progress, total: len(ops.paths)} rep.AlreadyCorrect = ops.inSync if ops.repairs > 0 { @@ -95,16 +95,20 @@ func writtenBytes(p mirrorPath) int64 { } // learnNames probes how the destination compares names before the first -// path lands, and on a destination that folds them plans around the -// collisions that causes. +// path lands, keys the live records the way it does, and on a destination +// that folds them plans around the collisions that causes. func (w *mirrorWriter) learnNames(ctx context.Context, ops *mirrorOps) error { if len(ops.paths) == 0 { return nil } var err error - if w.fold, err = w.probeFolding(ctx); err != nil || !w.fold.folds() { + if w.fold, err = w.probeFolding(ctx); err != nil { return err } + w.live = newLiveRecords(w.fold, ops.live) + if !w.fold.folds() { + return nil + } w.names, err = w.planFolding(ctx, ops) return err } @@ -516,11 +520,10 @@ func (w *mirrorWriter) moveRecorded(ctx context.Context, rel string, ids []int64 defer w.mu.Unlock() w.displacing = append(w.displacing, ids...) w.movedAside++ - for r := range w.live { - if r == rel || w.fold.under(r, rel) { - delete(w.live, r) - } + for _, r := range w.live.under(rel) { + w.live.remove(r.Path) } + w.live.remove(rel) return nil } @@ -574,8 +577,8 @@ func (w *mirrorWriter) commit(ctx context.Context, l *landing) error { } l.commitID = id w.mu.Lock() - w.live[d.Path] = store.RemotePath{ID: id, ContentID: d.ContentID, WrittenRunID: w.runID, State: store.RemotePathLive, - MtimeNs: staged.mtime.UnixNano(), Path: d.Path, SizeBytes: d.SizeBytes} + w.live.set(store.RemotePath{ID: id, ContentID: d.ContentID, WrittenRunID: w.runID, State: store.RemotePathLive, + MtimeNs: staged.mtime.UnixNano(), Path: d.Path, SizeBytes: d.SizeBytes}) w.mu.Unlock() return nil } @@ -604,7 +607,7 @@ func (w *mirrorWriter) loseRecord(ctx context.Context, live store.RemotePath, wh return err } w.mu.Lock() - delete(w.live, live.Path) + w.live.remove(live.Path) w.mu.Unlock() w.warn(fmt.Sprintf("destination %q: %s %s — it was changed behind squirrel's back, so its record no longer counts as a copy, and a push writes it again while the index holds it", w.h.dest.Name, live.Path, why)) return nil @@ -614,8 +617,7 @@ func (w *mirrorWriter) loseRecord(ctx context.Context, live store.RemotePath, wh func (w *mirrorWriter) liveAt(rel string) (store.RemotePath, bool) { w.mu.Lock() defer w.mu.Unlock() - live, ok := w.live[rel] - return live, ok + return w.live.at(rel) } // liveUnder is every live record below dir, as the destination resolves @@ -623,13 +625,7 @@ func (w *mirrorWriter) liveAt(rel string) (store.RemotePath, bool) { func (w *mirrorWriter) liveUnder(dir string) []store.RemotePath { w.mu.Lock() defer w.mu.Unlock() - var out []store.RemotePath - for rel, live := range w.live { - if w.fold.under(rel, dir) { - out = append(out, live) - } - } - return out + return w.live.under(dir) } func (w *mirrorWriter) warn(msg string) { From ced1380ff5d36c44fd0d501eff322f788982b566 Mon Sep 17 00:00:00 2001 From: Martin Bertschler Date: Fri, 25 Sep 2026 17:02:29 +0200 Subject: [PATCH 61/61] design: correct the exFAT benchmark The first rerun's exFAT column followed the old build's runs while the host disk was still working off their flushes. Settled, and broken into steps: the read-back costs about 2 s of the push, the symlink checks nothing measurable, and a quadratic scan 2.3 s, now fixed. With the fix a first push to the exFAT image takes 15-29 s against rclone's 19-25 s. --- design/friction-log.md | 6 +++--- design/native-mirror.md | 37 ++++++++++++++++++++++++++++++------- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/design/friction-log.md b/design/friction-log.md index 6890672..cb15507 100644 --- a/design/friction-log.md +++ b/design/friction-log.md @@ -613,9 +613,9 @@ the exFAT image, and 432 s against 45 s over sftp at a 20 ms round trip; unchanged pushes are faster. The cost was three full flushes per file on a local disk and 27 sequential requests per path over sftp. Decision 8 in native-mirror.md flushes once per batch and writes several paths at once -(`concurrency`); rerun, the first push takes 42 s against rclone's 19–24 s -on the exFAT image, where reading every byte back is the remaining cost, -and 50 s against 47 s at a 20 ms round trip. +(`concurrency`), and a scan that made a first push quadratic in its file +count is gone. Rerun, a first push to the exFAT image takes 15–29 s against +rclone's 19–25 s, and 50 s against 47 s at a 20 ms round trip. Observed, by design: a copy corrupted in place on the local mirror, size and mtime kept, passed two verify passes because each re-reads only a tenth of diff --git a/design/native-mirror.md b/design/native-mirror.md index b559f12..fb141e8 100644 --- a/design/native-mirror.md +++ b/design/native-mirror.md @@ -992,15 +992,38 @@ seconds: paths in flight: 49.7 s against 46.9 s, from 409 s. The instrumented push measured 91.5 ms per path at 8, 56.5 at 16 and 37.4 at 32, so a destination on a slow link can go past rclone by raising `concurrency`. -- **A local disk is 2–3 times faster than before, and about twice rclone's - time on the exFAT image.** The instrumented push went from 27.6 to 5.3 ms - per file there (19 to 1.2 on the internal disk). What is left is the - evidence — writing past the cache and reading every byte back — and exFAT's - slow file calls. More paths in flight don't help that disk: 9.2 ms per +- **A local disk is several times faster than before.** The instrumented + push went from 27.6 to 5.3 ms per file on the exFAT image (19 to 1.2 on + the internal disk). More paths in flight don't help that disk: 9.2 ms per file at 1, 5.3 at 4, 5.7 at 8, which is why a local disk defaults to 4. + The `usb` "after" column overstates native's time: each of those runs + followed the old build's, and the host disk was still working off their + flushes (below). - **Unchanged pushes stay faster than rclone everywhere, and so do changed - ones** except on the exFAT image, where a changed push takes about 1.4 - times rclone's time. + ones** except on the exFAT image, where a changed push took about 1.4 + times rclone's time in those runs. + +**exFAT, settled** (2026-09-25 afternoon). A timed build broke the first +push to a fresh image into its steps, with the host disk left 30 s to settle +before each run. Staging writes swing between runs (7–25 s) with the host +disk, and so does rclone; the other steps hold still: + +| First push, `pics` to a fresh exFAT image | seconds | +|---|---| +| rclone (`main`) | 18.9–24.9 | +| native, as benchmarked above | 18.5–31.8 | +| native, without the read-back | 19.9–29.9 | +| native, with the live-record fix | 15.4–29.1 (15.4 twice, against rclone's 22.4–22.6) | + +- **The read-back costs about 2 s** of the push (1.7–2.1 s for 716 MB), a + tenth; the per-call symlink checks cost nothing measurable, and renaming + staged copies onto their paths about 5 s. +- **A quadratic scan cost 2.3 s.** For every path with nothing at it, the + writer looked through every live record for records below it, under the + lock the paths in flight share. The writer now counts the live records + below every directory (`sync/mirror_live.go`), so that question is one + lookup: at 30,000 files the displace step fell from 62 s to 0.6 s, and the + whole first push from 81 s to 17 s. - **A new dependency:** `github.com/pkg/sftp`.