Repository navigation
sync: native mirror layout for local and sftp on one shared planner - #217
Merged
Merged
Conversation
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.
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.
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.
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.
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.
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.
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.
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-<id>/, hashing the bytes it sends, moves whatever the path and its parents hold into .squirrel-history/run-<id>/ (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 <volume>/.squirrel-index/run-<id>, 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.
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.
RemotePath drops the fields no reader uses, and the transport, guard and planner comments state what the code does.
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.
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.
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.
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.
The Snapshotter no longer holds an rclone wrapper. Each push hands over the shelf its ride-along lands on — the destination's <volume>/.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.
…sport recover --from a native mirror lists its <volume>/.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.
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.
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.
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.
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.
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.
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.
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.
… 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.
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.
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.
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.
A guard held by a content-addressed or packed push commits this run's staging onto objects/<hex>, packs/<hex>, 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.
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.
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.
…sitively 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.
…e-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.
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.
…tories 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.
…nknown runs 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.
…ave 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-<id> 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.
…al 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.
… usb no longer covers 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.
… tests, and record the benchmark 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.
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.
…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.
…ve destinations 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).
…n 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.
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.
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.
… 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.
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.
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.
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.
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Critical marker-validation gaps and additional moderate findings remain unresolved.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 4
Open (5)
What changed in this PR
This PR replaces rclone with native local and plain-SFTP transports, adding durable mirror planning, verification, restore, recovery, batching, and concurrency support.
Changes:
- Adds native local/SFTP transports, staging, receipts, flushing, and host-key validation.
- Adds mirror evidence persistence, verification, restore/recovery, and offload integration.
- Updates CLI behavior, configuration, documentation, design notes, and tests.
Review findings: unresolved critical marker-validation gaps remain in mirror restore and verification, with additional moderate concurrency and dry-run issues plus a documentation omission.
| File | Reviewed changes |
|---|---|
sync/verify_remote_test.go |
Remote verification coverage |
sync/verify_native.go |
Native artifact verification |
sync/vector_wiring_test.go |
Evidence and vector wiring tests |
sync/transport.go |
Transport abstraction and durability operations |
sync/transport_stall_test.go |
Stall-timeout coverage |
sync/transport_sftp_hostkey.go |
SFTP host-key validation |
sync/transport_sftp_hash_test.go |
SFTP hash behavior tests |
sync/transport_local_other.go |
Fallback local transport operations |
sync/transport_local_linux.go |
Linux local transport implementation |
sync/transport_local_dirs.go |
Local directory operations |
sync/transport_local_darwin.go |
macOS local transport implementation |
sync/snapshot_test.go |
Snapshot behavior tests |
sync/scanback.go |
Scan-back behavior |
sync/restore_place_test.go |
Atomic restore placement tests |
sync/recover.go |
Native snapshot recovery |
sync/readback.go |
Local read-back verification |
sync/rclone.go |
Remaining rclone integration |
sync/push_test.go |
Push behavior and safety tests |
sync/node.go |
Reserved paths and node handling |
sync/naming.go |
Artifact naming and collision handling |
sync/naming_test.go |
Naming tests |
sync/mirror_translate.go |
Mirror delta translation |
sync/mirror_sftp_test.go |
Native SFTP mirror tests |
sync/mirror_live.go |
Live-record tracking |
sync/mirror_live_test.go |
Live-record tests |
sync/kopia.go |
Snapshot integration |
sync/handler.go |
Native handler dispatch |
sync/handler_test.go |
Handler tests |
sync/fingerprint.go |
Fingerprint operations |
sync/fingerprint_test.go |
Fingerprint tests |
sync/content_addressed_test.go |
Content-addressed layout tests |
sync/batch.go |
Batching and concurrency |
sync/batch_test.go |
Batch behavior tests |
sync/artifacts.go |
Artifact storage abstraction |
sync/artifacts_rclone.go |
Rclone artifact handling |
sync/appledouble.go |
AppleDouble handling |
store/schema.sql |
Updated schema snapshot |
store/runs_audit.go |
Run and foreign-data auditing |
store/remote_paths_evidence.go |
Mirror path evidence persistence |
store/path_delta.go |
Path delta tracking |
store/path_delta_test.go |
Path delta tests |
store/migrations.go |
Database migrations |
store/migrate_v27_test.go |
Migration tests |
store/destination_run_ids.go |
Destination run evidence |
store/destination_reset.go |
Destination reset handling |
store/content_presence.go |
Destination content presence |
SAFETY-AUDIT.md |
Native transport safety audit |
offload/native_mirror_test.go |
Native mirror offload coverage |
go.mod |
SFTP and transport dependencies |
docs/src/content/docs/reference/on-disk-layout.md |
On-disk layout documentation |
docs/src/content/docs/reference/formats.md |
Format documentation |
docs/src/content/docs/reference/cli.md |
CLI reference updates |
docs/src/content/docs/layouts/packed.md |
Packed layout documentation |
docs/src/content/docs/layouts/encrypted.md |
Encrypted layout documentation |
docs/src/content/docs/layouts/content-addressed.md |
Content-addressed layout documentation |
docs/src/content/docs/guides/syncing.md |
Syncing guide updates |
docs/src/content/docs/guides/restore.md |
Restore guide updates |
docs/src/content/docs/guides/recovery.md |
Recovery guide updates |
docs/src/content/docs/guides/offloading.md |
Offloading guide updates |
docs/src/content/docs/guides/agent.md |
Agent guide updates |
docs/src/content/docs/configuration/destinations.md |
Destination configuration documentation |
design/testbed.md |
Native testbed documentation |
design/reference-setup.md |
Reference setup documentation |
design/README.md |
Design documentation index |
design/friction-log.md |
Friction-log updates |
config/pack_test.go |
Packed configuration tests |
config/offload_capability_test.go |
Offload capability tests |
config/layout_test.go |
Layout configuration tests |
config/config.go |
Configuration and concurrency settings |
config/config_test.go |
Configuration tests |
cmd/squirrel/verify.go |
Verification command integration |
cmd/squirrel/verify_test.go |
Verification CLI tests |
cmd/squirrel/sync.go |
Sync command dispatch |
cmd/squirrel/sync_test.go |
Sync CLI tests |
cmd/squirrel/status_test.go |
Status command tests |
cmd/squirrel/restore.go |
Restore command integration |
cmd/squirrel/restore_test.go |
Restore CLI tests |
cmd/squirrel/recover.go |
Recovery command integration |
cmd/squirrel/recover_test.go |
Recovery CLI tests |
cmd/squirrel/main_test.go |
Main command tests |
cmd/squirrel/destination_reset.go |
Destination reset command |
cmd/squirrel/content_native_test.go |
Native content-layout tests |
cmd/squirrel/agent_scheduler.go |
Scheduler integration |
cmd/squirrel/agent_scheduler_test.go |
Scheduler CLI tests |
agent/sync.go |
Agent reserved-path handling |
agent/sync_test.go |
Agent sync tests |
agent/scheduler.go |
Native scheduling |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| if err != nil || !empty { | ||
| return false, err | ||
| } | ||
| case e.kind == kindFile && e.name == volmark.MarkerName: |
Comment on lines
+57
to
+61
| 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) | ||
| } |
Comment on lines
+34
to
+35
| if len(rows) == 0 { | ||
| return nil |
Comment on lines
+135
to
+136
| if dest.NativeMirror() { | ||
| return rep, verifyMirror(ctx, s, dest, &rep) |
Comment on lines
+84
to
+93
| 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: | ||
|
|
||
| | Directory | Purpose | | ||
| |---|---| | ||
| | `.squirrel-history/run-<id>/` | 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-<id>/` | 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-<id>/` | Files displaced by an [`--in-place` restore](/squirrel/guides/restore/). | | ||
| | `.squirrel-staging/run-<id>/` | In-flight writes on a destination squirrel writes itself, in any layout, renamed onto their names once confirmed. | |
4 tasks
20 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Replaces rclone for
localmirrors and plainsftpmirrors, following the design indesign/native-mirror.md. Three layers do the work:localandsftpimplementations.This is step 2 of the rclone replacement, following #211 / #216. S3 comes afterwards, on its own branch. Crypt mirrors (cloudbox) stay on rclone until the crypt byte-compatibility question is settled.
The design also records a live bug, which section 1 fixes. When a root is wiped but its upload records remain, squirrel treats it as a fresh start. The next content-addressed push then skips everything and still reports
success.Working on this branch
Four sessions work through this branch one after another, one session each.
git switch native-mirror && git pull --no-rebase.AGENTS.mdanddesign/native-mirror.md.go vet ./...,go test ./...andgolangci-lint rungreen. That includes the docs golden tests for any flag, config key or run kind you add.design/native-mirror.mdin the same commit.Sessions
1. Planner, store, local transport, local mirror.
pushPlan, thelayoutinterface and the single push driver fromsync/content_addressed.goandsync/packed.go.remote_paths, which isSTRICTand has the statescommitting,live,displacing,displacedandlost.ContentPresentOnDestinationgainsremote_pathsas a third source.destination resetclears the table..squirrel-stagingjoins the reserved names.store/schema.sql.transportinterface and the name guard.os.Root: exclusive create, no-replace rename with its exFAT fallback, and parent-directory sync.local:lost, commit..squirrel-index/run-<id>.--shallow, progress events and a no-progress timeout per operation.mainand passes here.TestPushRefusesWipedRootWithUploadRecordsfails onmainand passes here.TestMirrorPushWithoutRclonepushes with no rclone wrapper. The tables are covered byTestMirrorTranslationRules,TestMirrorWriteDisplacesWhatThePathHoldsandTestMirrorCrashTable.design/native-mirror.md):ContentPresentOnDestinationdoes not gainremote_paths. Its only callers are the content layouts' upload-once checks, and a mirror copy isn't atobjects/<hash>. Mirror records left behind by a switch to a content layout would skip those objects and still seal the run.DestinationHasUploadRecordsdoes countremote_paths. Maintainer: please confirm.layoutis generic over its operations and gainsmarkers,rootEmpty,foreignHistoryandreconcile.sealandadvanceMethodtake the report.run-<id>/<hex BLAKE3 of the path>, because the row doesn't exist yet at staging time.lost.os.Rootfollows symlinks that stay inside the root, so the local transport also checks each name's parent chain withLstat. Windows always uses the check-then-rename fallback.already_correctcounts every in-sync live path, which keeps friction item F7 (the CLI test pins it).Report.Layoutkeys the CLI summary..squirrel-staging.Pair.DrivesRcloneis still true for local mirrors, because the ride-along, restore and recover still use rclone. Flip it once they run on the transport..squirrel-index/index-*.db.runTransportContractinsync/transport_contract_test.go. Its harness must plant symlinks.mirrorHandler.openTransportis the opener seam, andHandlerFordispatches onType == "local".liveover the other spelling's bytes. That breaks invariant 1 and loses no data. Session 4's suite lists it; it needs fixing before merge.reference-setup.md(theusbarrow and the kopia leg) is left to session 4, per its checklist.destination reset, a packed destination never re-uploads content that is already in a pack.HasPackMemberignores the destination, so a second packed destination never gets that content either. Worth its own issue.2. sftp, and every mirror command without rclone.
x/crypto/sshandpkg/sftp.fsync@openssh.comwhen the server offers it.Lstatbefore every rename.checkerson native destinations, andhash_algoon native sftp mirrors.O_TRUNCwrite.recover --fromdiscovery, and the remote marker gate.pkg/sftpserver and against the testbed's server, with rename onto an existing target pinned as failing.localand plainsftpmirrors need no rclone for any command.configuration.mdandtestbed.mdare updated.pkg/sftpserver and againstrclone serve sftp(TestSFTPTransportContractAgainstRcloneServe, which runs wherever rclone is on PATH, CI included).RenameNeverReplacespins the transport's rename onto an existing target failing on both;TestSFTPServersRenameOverAnExistingNamepins that both servers' raw rename replaces it.design/native-mirror.md):Putalso checks its target withLstatfirst: protocol version 3 has no "already exists" status.host_key_algorithmsis set). Otherwise a server that prefers ed25519 is refused when only its RSA key is pinned.pkg/sftp's 64 requests in flight); paths are still written one at a time. Session 4's benchmark decides whether parallel paths are worth it.shelf(runID) snapshotShelf, andSnapshotterholds no rclone wrapper.--initonly, before a run exists —.squirrel-staging/volume-markeronto.squirrel-volume.--initstill creates a missing local root. The rclone marker gate's refusals now wrapErrRefused.Getand each of its reads are bounded by the stall timeout (marker, receipts, restore, recover). sftp'sClosedrops the ssh connection first, so a hung server cannot wedge a push.--in-placepreserves only what it replaces.--shallowchanges nothing on a native mirror restore, as on archive restores.openReadOnly(ctx, dest)gives a stall-bounded transport whose guard refuses every move;dialSFTPandhostKeysare ready for the content layouts on sftp.Pair.DrivesRcloneandrcloneFor(cmd/squirrel/sync.go) key onDestination.NativeMirror(). Widen both when the content layouts leave rclone.CanEverGateOffloadnames every native mirror (local and sftp) as presence+size; flip local there.rclone serve sftpoffers nofsync@openssh.com, so the testbed never exercises the flush;pkg/sftp's server doesn't either.known_hosts_fileis unset. Rendering~/.ssh/known_hostsinto rclone.conf would close that;configuration.mdstates what each path does today. Maintainer's call.3. Evidence, and the content layouts on the transport.
remote_paths.verify_everybecomes valid on native mirrors. The pass checksliveanddisplacedrows withLstat, and on local mirrors it re-hashes a rotating slice.lost, and those rows feed the planner as repairs.localandsftp:TestOffloadGatesOnNativeLocalMirrorcovers it with and without a verify cadence, andTestLoadAcceptsLocalMirrorOffloadRequirescovers config load. An sftp mirror is refused at load and before the offload walk, and the refusal names the reason.localand plainsftpdestinations need no rclone in any layout, for sync, verify, restore and recover. TheTestNativeContent*tests run on both transports, andTestCLIContentLayoutsOnLocalWithoutRcloneruns with rclone hidden.Pair.DrivesRclonekeys onDestination.Native.artifactStore: staged, confirmed (a local read-back, or the sftp server's hash), then renamed. An artifact already at its name is confirmed and adopted, never replaced.design/native-mirror.md):local("addressed by filesystem path"). That rule is gone, and native content destinations, local ones included, are gated on.squirrel-volumelike a native mirror.--init, for mirrors too. Before, it failed with a raw open error.remote_objectshas noloststate, and a changed object can't be replaced in place.fingerprint-verifiedcomponents topresence+size(DemoteFingerprintVerifiedVector). Without the demotion, a gate with a verify cadence still offloaded a file whose only mirror copy verify had found gone; the review reproduced this. The next push that leaves nothing pending upgrades the components again.mirrorRereadShare). Maintainer: change the share if another suits better.hash_algoacceptsmd5,sha1,sha256orblake3, because squirrel computes the same hash to check the server's answer.crc32,xxh3andxxh128stay valid behind crypt only. Thesha256default now also applies to native packed destinations.<volume>/.squirrel-staging/run-<id>/<hex>, so a mismatch never reaches the artifact's name. The probe runs once per session and is remembered only once the server has answered.unchecked, a new counter insquirrel verify. It is no longer reported as mismatched.remote_pathsby content, and adds a partial index on itslostrows.F_NOCACHE, because a read there is served from pages the write left cached.nativeContentFixture.pushCrashing), the adopt path, a server without a hash command, and symlinks at artifact names.sftpSettings(t, dst, commands)builds an sftp destination whose test server runs sum commands.DemoteFingerprintVerifiedVectoron a dirty content pass would close it. Maintainer's call.remoteSubpathURI'slocalbranch, andSynconto a local destination, are now reached only by tests.--dry-runisn't supported on the push. That was already stale and is untouched here.4. Hardening and wrap-up.
AGENTS.md.Done: everything above.
TestMirrorModelruns random histories with random crashes on both transports and compares them against a reference model. The histories cover adds, changes, deletes, re-adds, nested file↔directory swaps, case-only renames and colliding spellings.Bugs found and fixed:
live. They now becomelostand are repaired.recover --from. The content layouts still adopt artifacts they find at their names.._files on exFAT (F37). Every push reported one as foreign staging, and an index-less restore brought back 619 of them.--init, even for a disk the volume had synced to before.Deviations (each amended in
design/native-mirror.md):.squirrel-staging/fold-probe-é, is removed within the push, and the name guard gains that oneRemove.Photos/tophotos/, files land in the existingPhotos/, and an index-less restore puts them there too.Benchmark (2026-09-24, macOS arm64). Each run used a fresh index and a fresh destination.
usbis an exFAT disk image.boxisrclone serve sftpon loopback.wanis the same server behind a proxy that adds a 20 ms round trip.picsis 4540 files, 724 MB;tripis 608 files, 114 MB. "Changed" rewrites 150 files and adds 150 (30 and 30 ontrip). Times are seconds:Open items:
localand plainsftpswitch before any of them lands is the maintainer's call. None of them is on this branch.known_hosts_fileis unset (session 2).5. Throughput of pushes that write (decision 8, agreed with the maintainer on 2026-09-24).
Where the time went (measured with an instrumented push, design section 8):
Done:
PutandRenameno longer flush; a newTransport.Flushmakes a batch durable (oneF_FULLFSYNCper batch on macOS, the batch'sfsyncs together on Linux).concurrencykey (default 4 on local disks, 8 on sftp; rclone's--transferson destinations rclone writes). Every per-call symlink check stays.Flushcovered, or keep the names without the 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; the model test runs with paths in flight and random power cuts. Each new check was confirmed to fail when its flush is removed.Review fixes: a stalled content batch recorded artifacts it never landed (now failed, and the push stops); reconcile now flushes the directories an unfinished push's moves touched before recording them.
Benchmark (2026-09-25, same laptop, three binaries):
Quadratic scan fixed: for every new path the writer scanned every live record under the shared lock; it now counts live records per directory (
sync/mirror_live.go). At 30,000 files the displace step fell from 62 s to 0.6 s, the first push from 81 s to 17 s.Open items:
concurrencydefaults to 8 on sftp; 16 measured about 40% faster at a 20 ms round trip. Maintainer's call whether to raise it.Decisions
The decisions are recorded in section 10 of the design doc (2026-09-23):
.squirrel-index/.Decided on 2026-09-24 (decision 8): throughput. One flush per batch instead of several per file, several paths in flight set by
concurrency, and every per-call check stays.Still open: crypt byte-compatibility with rclone. It blocks only cloudbox, which is outside this branch.