Alpha software, not for production data. Bugs can cause data loss, formats may change without migration, and the cryptography has not been independently audited. Keep your own backups and check that you can restore from them.
Varsto alpha.16

Alpha-0 storage format and sync model

From docs/spec/alpha-0-format.md in the repository, rendered 2026-11-12. These documents describe the main branch; the released version is 0.0.1-alpha.16. Sections marked 'after 0.0.1-alpha.16' are not in a release yet.

Format version 0, alpha. Implemented in crates/varsto-core. It may change without a migration path; every released alpha keeps a reader (see format-versions.md). Nothing here has been reviewed or audited. Post-quantum hybrid signatures and key exchange exist since 0.0.1-alpha.3 (section 11); algorithm identifiers in every object allow later changes.

1. What alpha-0 does

  • Content-defined chunking of files (Gear rolling hash, FastCDC-style normalisation, with a Gear table keyed per folder since format 2; block sizes by file size: under 1 MiB one block; below 32 MiB 256 KiB to 4 MiB, average 1 MiB; below 1 GiB 1 to 16 MiB, average 4 MiB; larger files 2 to 16 MiB, average 8 MiB; the size and the folder alone decide, so the same file is cut the same way on every device of the folder; section 62).
  • Client-side authenticated encryption of every chunk, manifest, ledger batch and record before it reaches a storage. Storage sees opaque objects and their sizes only; since format 2 every block is inside a pack, so a storage sees pack sizes, never the size of a block (section 62).
  • alpha-0: one storage backend, a local directory (covers local disks, removable disks and network mounts); since alpha.3 S3-compatible buckets and rclone remotes, section 12.
  • A per-device, append-only, signed ledger replicated through every storage. Devices that are never online at the same time converge through the storage ("mailbox").
  • Two-way folder sync between devices with version vectors; concurrent edits produce a deterministic winner and a conflict copy; deletions go to a local trash (since section 43, to a vault-wide trash restorable on every device).
  • fsck: compares the ledger with what the storages actually hold and can verify every object by hash.
  • Cold storages are written but never read (requirement F-043 default).
  • A local desktop interface (varsto desktop): a web page served from the binary on 127.0.0.1 with a per-session token and a Host check, the first shape of the local control API (plan 6.8, 6.32).

Not in alpha-0 (see section 10 and 11 for what later alphas added): sharing with other users, peer-to-peer transfer, hybrid post-quantum signatures and key agreement, FIDO2 security keys, Strongroom, placeholders, policies and alerts, packs, mobile, MCP, daemon. alpha-0: keys are shared between devices out of band (the "vault key"); pairing with a code since alpha.7, section 9.

2. Identifiers

Identifier Construction Visible to storage
vault id 16 random bytes yes (vault/meta.json)
device id first 16 bytes of BLAKE3(device public key) yes (object names)
folder id 16 random bytes yes (object names)
chunk id keyed BLAKE3 of the chunk plaintext, key = folder hash key no (inside encrypted manifests and ledger)
object name BLAKE3 of the chunk ciphertext yes (object names)
content hash keyed BLAKE3 of the whole file, folder hash key no

Object names are plain hashes of ciphertext, so a peer or a scrub can verify an object without any key. Chunk ids are keyed, so the storage cannot test whether a known file is present (plan 6.11).

3. Keys

Superseded by section 77 (storage format 3): folder keys are random and arrive only as signed grants (no folder key is derived from K3), and every record's key id is inside its signature (77.1). Kept as the history of format 2.

Subset of key-hierarchy.md. All keys are 256 bits. Derivation uses BLAKE3 derive_key with the context e2ee-sync-format/0/<purpose> and length-prefixed scope identifiers (vault, folder, device, chunk) in the key material.

Key Purpose Derived or wrapped
master key (K3) root of the vault random; shown once as the hex "vault key" for joining other devices; wrapped locally under the passphrase key
passphrase key (K4) wrap the master key and device signing key on one device Argon2id (fixed minimums: 64 MiB, 3 passes, 1 lane; readers refuse weaker parameters)
device signing key (K6/K7) sign this device's ledger batches alpha.3: Ed25519 + ML-DSA-65 hybrid (alpha-0: Ed25519 only), random per device, wrapped with K4
ledger key encrypt ledger batch bodies derive(K3, ledger)
device-registry key encrypt device records derive(K3, device-registry)
folder-record key encrypt folder records derive(K3, folder-record)
local-keyring key encrypt the local copy of folder keys derive(K3, local-keyring)
folder key (K9) per folder random; published in the creating device's folder record
folder hash key (K11) chunk ids and content hashes derive(K9, dedup-hash, folder)
chunker seed (K12) Gear table of the folder's chunker (format 2) derive(K11, chunker-seed, folder)
folder metadata key (K10) manifests derive(K9, folder-metadata, folder)
chunk key (K14) one chunk derive(K9, chunk-key, folder, chunk id)
chunk nonce one AEAD input keyed_hash(derive(K9 of the epoch, chunk-nonce, folder), packed bytes), first 24 bytes (format 2)
pack tombstone key tombstone lists of packs (format 2) derive(K3 of epoch 0, pack-tombstones)

Alpha-0 decision (convergent chunk keys). The chunk key is derived from the chunk's keyed hash and the nonce from the exact bytes encrypted (the packed chunk, section 16; format 2, section 62), so the same content packed the same way encrypts to the same object on every device of the vault, and two different encodings of one chunk (another zstd version, raw against compressed) never share a nonce under the chunk key. Two devices that ingest the same file offline therefore produce one object, deduplication works without coordination, and a future peer-to-peer swarm can advertise object names. The cost: rotating a folder key re-encrypts its data, and anyone holding the folder key can test for known content inside that folder. Shared folders keep convergent keys inside a key epoch and get a new random folder key when a member is removed (section 24, which explains why random per-chunk keys were not chosen). Rationale and alternatives: plan section 8, "Avainnettu hash, lohkot ja padding".

4. Encryption and associated data

Superseded by section 77 (storage format 3): the associated data binds format 3 and binary ids (aad_for_format, 77.5). Kept as the history of format 2.

AEAD is XChaCha20-Poly1305. Every object is nonce (24 bytes) || ciphertext || tag. The associated data is a length-prefixed list that always starts with the format version and the AEAD identifier, then the object type and its scope:

Object Associated data fields
chunk vault id, folder id, key epoch, chunk id, plaintext length, packed length (format 2)
pack index format, pack-index, vault id, folder id, device id, sequence (section 62)
tombstone list format, tombstones, vault id, empty scope, device id, sequence (section 62)
manifest vault id, folder id, device id, manifest sequence
ledger batch body device id, batch sequence
device record vault id, device id
folder record vault id, creating device id, folder id
key file vault id, device id
local keyring vault id, device id

A storage cannot move, rename or replay an object into another place without the AEAD check failing.

5. Storage layout

Superseded by section 77 (storage format 3): no chunk object, .enc record or JSON batch is written; published objects are SignedRecords (<kind path>/<seq>-<part>.rec) and blocks live only in packs (77.2, 77.5). Kept as the history of format 2.

vault/meta.json                          format version, vault id (plaintext)
vault/devices/<device>.enc               device record: name, public key (Ed25519 || ML-DSA-65; 32 bytes = legacy Ed25519 only)
vault/folders/<device>/<folder>.enc      folder record: name, folder key
vault/storage-id.json                    random identity of this storage (plaintext, first writer wins)
vault/storage-names/<device>/<utc>.enc   a device's storage names and their identities (section 20)
ledger/<device>/<seq 16 digits>.json     signed batch envelope (body encrypted)
ledger/<device>/checkpoint-<seq 16 digits>.json  signed checkpoint of that device's batches up to seq (section 22)
vault/share-*/<folder>/...               share epochs, keys, grants, member records and tokens of shared folders (section 24)
vault/access/<folder>/<device>/<utc>.enc a device's last-accessed times for a folder (section 13)
vault/trash/<folder>/<device>/<utc>.enc  a device's trash record of a folder: its deletions, restores and purges (section 43) and the versions it replaced (section 50)
vault/trash-settings/<device>/<utc>.enc  the vault's trash days, trash storage and history days (sections 43, 50)
org/manifest/<seq>-<attempt>.json        organization: administrators, signed by the root key (section 27)
org/roster/<seq>-<attempt>.json          organization: people, devices, policy, signed by an administrator device (section 27)
org/log/<device>/<seq>-<attempt>.json    organization: one administrator device's chained log (section 27)
manifests/<folder>/<device>/<seq>.enc    full folder view of one device
snapshots/<backup>/<device>/<seq>.enc    one snapshot of a backup, never changed (section 31)
packs/<first two hex>/<pack id>          encrypted chunks one after another; pack id = BLAKE3 of the pack (format 2, section 62)
packs/index/<device>/<seq>.enc           a device's pack index of one push and folder (section 62)
packs/tombstones/<device>/<seq>.enc      a device's list of deleted pack members (section 62)

Every path has one writer: a device writes only under its own device id, and packs are content-addressed and written with put-if-absent. Since format 2 no block is an object of its own (chunks/ is not written); a block keeps its object name (the BLAKE3 hash of its bytes), which the ledger, verification and peers use, and lives at an offset in a pack (section 62). No conditional writes, locks or leases are needed on the storage. Objects are never overwritten.

6. Ledger

Superseded by section 77 (storage format 3): the ledger is pack-level (pack_stored, pack_verified, pack_dropped, record_published, ...), its batches are SignedRecords, not JSON, and the per-block events (chunk_stored, chunk_verified, chunk_on_device, chunk_dropped, manifest_published) are not written (77.4). Kept as the history of format 2.

Model B of ledger-signing-notes.md: events are grouped into batches; each batch carries the device id, a sequence number, the hash of the previous batch of the same device, a Lamport clock and its events; the body is encrypted, and the signature covers device || seq || BLAKE3(encrypted body). Event types:

Event Meaning
device_enrolled this device joined (name)
folder_added this device created a folder
chunk_stored this device wrote an object to a storage (a claim)
chunk_verified this device fetched the object from a storage and the hash matched
chunk_on_device this device holds the plaintext as part of a file
manifest_published this device published manifest seq of a folder
storage_retired the storage was removed from the vault: claims on it made before this event no longer count (section 20)
chunk_dropped this device deliberately removed the object from a storage: claims on that storage made before this event no longer count, later ones count again (section 23)
snapshot_taken this device wrote snapshot seq of a backup, with its times, size and the hash of the stored object (section 31)
snapshot_expired a snapshot of a backup expired and is deleted with the blocks only it used (section 31)
backup_stopped a backup takes no more snapshots (section 31)

A batch may hold event types a reader does not know (written by a newer version); since 0.0.1-alpha.9 such events are read as unknown and ignored, and the rest of the batch counts. Earlier versions reject the whole batch (section 23, Compatibility).

Not every signer may make every event: the key id of a batch and the signer's role decide what of it counts (section 58). A trusted full device's batches (ledger, ledger@<epoch>) count in full; a replica's (replica) only for object claims; a member's (share:<folder>[@<epoch>]) only for block claims, drops and manifests of that folder. Other events are left out and counted (events_refused in the view and in ledger_health).

Replaying every batch yields the location view: for each (folder, chunk) the object name, size, which storages claim it (by whom) and which devices verified it there. Applying a batch is order-independent: sets are unions, times are maxima, and where events disagree (the object name and size of a chunk, a device's name) the event with the largest (Lamport time, device, sequence, position) wins. A device therefore keeps the view in ledger/view.enc (zstd-compressed JSON, XChaCha20-Poly1305 under a key derived from the device's root key, associated data vault and device) with the last sequence number applied per device, applies only new batches, and rebuilds it from the batches when the keys it can open or the revocation cut-offs change. Retirements, replica claims and forks are applied on top of the cached view at every read, exactly as after a full replay. A storage copy counts as verified only when a device other than the writer has verified it. varsto status reports chunks without any storage copy and chunks verified elsewhere.

Mailbox rules:

  • on every pull a device lists, on every hot storage and for every device whose key it knows, only the batches after the newest one it holds of that device (list_after: S3 start-after, a directory listing elsewhere), and ingests them after checking the signature against the device registry and the hash chain; a batch under a key the device does not hold (a shared folder it is not a member of, a key epoch it has not adopted yet) is kept unread and read once the key arrives, instead of being downloaded again on every pull;
  • the head of a device is the end of the unbroken chain held: a batch whose predecessor is missing waits in ledger/<device>/pending/ and does not move the head, and every pull asks every storage for the batches after the head again, so a storage that withholds one batch is caught by any other storage that has it, and by the acknowledgements of other devices when none does (section 58). A batch that does not parse or verify on one storage is skipped (counted) and does not stop the pull; a batch with a Lamport time more than 2^40 ahead of the reader's clock is refused;
  • on every push it uploads its own batches that a storage lacks, listing from the newest batch it last confirmed there (ledger/pushed.json); when that batch is gone the storage is filled again from the first batch;
  • two different batches with the same device and sequence number are a fork: the device is marked forked in the local heads (so are a checkpoint that contradicts a batch and two different checkpoints at the same sequence number, section 22);
  • if the mailbox holds batches of this device's own identity that it never wrote (a copy restored from an old backup, or a clone), the device fences itself: it stops signing and push fails. Only an object that verifies with the device's own key counts: anything else under its name (junk anyone with the storage's credentials can write) is reported (junk_objects) and deleted by varsto ledger clean-junk --yes, and never fences the device (section 58). varsto ledger rebuild continues from those batches when they are this device's own later history, and refuses (pair the device again) when two copies of the identity signed different histories (section 38).

Batching: one user action seals at most one batch. A sync seals one batch for the pull and push of every folder together (and pulls the ledger once); applying a placement suggestion and acting on a selection of files in the interface seal one batch each; a verification run seals one. Fetching a single file does not seal a batch: its chunk_on_device and chunk_verified events wait in ledger/pending.json for the next batch (usually the next sync) and count in the device's own view meanwhile. Enrolment, joining a shared folder, folder creation, storage removal and Strongroom changes are sealed and pushed at once, because other devices act on them.

Lamport clocks: each device keeps one logical clock, incremented on every local change and raised to any larger value seen in batches or manifests. The clock lives in memory; clock.json holds the end of a reservation of 1000 values and is written (atomically, with fsync) only when the reservation is used up or an observed value passes it, not on every change. A process that starts from the file continues after the reserved end, so a crash or an exit wastes at most the unused rest of a reservation; that is harmless, because the values only have to grow and never repeat, and the file is never lowered. Two processes on one device (the command line beside the background service) each read the file before reserving and start after the higher of its end and their own value, so they never hand out the same value.

7. Manifests and merging

Superseded by section 77 (storage format 3): manifests are a base and deltas per writer, announced in the ledger; the merge rules of this section still apply to the files (77.7). Kept as the history of format 2.

Each device publishes its full view of a folder as a manifest (seq increases per device). A file state has: path, version vector (device -> clock of that device's last change), deleted flag, size, mtime (change detection only), content hash, chunk list (chunk id, object name, size), and the device and clock of the last change.

A file whose size or mtime changes while the scan reads it (its chunks would not add up to the size from before the read, and every reader refuses a manifest with such an entry) is not made a version that round: its index entry stays as it was, so the next scan reads it again.

Merge rules for the same path, local versus remote:

  • remote dominated by local: keep local; local dominated by remote: take remote;
  • concurrent with identical content: keep, version = element-wise maximum;
  • concurrent, one side deleted: the modification wins (a deletion never destroys a concurrent edit);
  • concurrent, different content: the state with the larger (clock, device id) wins; the loser is kept as name.conflict-<device>-<clock>.ext, a new file with its own version; the merged version vector is the element-wise maximum so both devices converge without a further round. Where the loser is this device's own file, the file moves to the conflict name only when the winner is downloaded and takes its place; a winner that cannot be fetched yet leaves the file where it is and is retried from pending_remote (before, the path stayed empty and the next scan published a deletion).

A deleted file keeps its last version in the vault's trash, restorable on any device for the trash days; a device that applies another device's deletion also moves its own copy to <home>/trash/<folder>/<path>.<time>, never removing it outright (F-025). Section 43 describes the trash.

8. Local device directory

vault.json      vault id, device id, device name, format version
keys.enc        master key and signing key, wrapped under the passphrase
keyring.enc     folder records known to this device (encrypted)
config.json     storages and folder mounts (no secrets)
devices.json    device registry cache (public keys)
org-state.json  the organization as last verified: manifests, roster, log (section 27; absent without one)
org-request.enc   a device waiting for an organization's approval: its request keys, sealed under the device passphrase (removed on join; alpha.16 wrote them in clear as org-request.json, which the next read seals and removes)
clock.json      Lamport clock
ledger/         local copy of every device's batches, the heads file, pushed.json (own batches confirmed per storage), pending.json (events waiting for the next batch) and view.enc (the cached location view, encrypted); since section 38 also fork.json (a fork a rebuild found), discarded/ (own batches never published, set aside) and <file>.damaged-<utc> (local files that did not read)
state/<folder>.json  merged file states, local index, last seen manifests
trash/          copies of files deleted by other devices (`<folder>/<path>.<time>`), kept for the trash days
state/trash/    trash records: own and other devices' entries per folder, the settings, blocks waiting to be dropped (section 43)

9. Known limitations

These were the limits of alpha-0; the sections below record what later versions changed.

  • Pairing was "copy the vault key". Since alpha.7 a nine-digit code pairs devices over the LAN (SPAKE2); since alpha.10 an organization approves a device through a token sealed to its hybrid KEM key (section 27). Since section 51 the codes and sealed tokens can also be shown and scanned as QR codes; there is still no second factor. The vault key is the master key in hex; losing it and every device means losing the data (no escrow).
  • alpha-0 signed with Ed25519 only; since alpha.3 every batch carries sig_alg = "ed25519+ml-dsa-65" (section 11). The sig_alg field made the switch possible without rewriting stored data.
  • Whole files are chunked in a stream, but a changed file is re-read twice during a push (once to hash, once to upload) when a chunk is new. Packs for small files exist since alpha.12 (section 30).
  • Manifests are full views; very large folders will need incremental manifests (listing and pruning exist, section 25).
  • Verification of cold copies (section 20), policies (section 14), placeholders (section 10), sharing (sections 10 and 24) and P2P (section 15) exist since the versions those sections name.
  • alpha-0 had no logging; local debug logs with the redaction rules of docs/architecture/logging.md are in section 45 (new in 0.0.1-alpha.14).
  • The passphrase is NFKC-normalised before stretching since alpha.10; key files written earlier by a passphrase that normalisation changes are opened with the raw string as a fallback.

10. Additions in 0.0.1-alpha.2

Background service, tray and menu-bar apps

varsto service run watches attached folders (inotify, kqueue, FSEvents or ReadDirectoryChangesW through the notify crate), syncs within seconds of a change and on a timer, serves the local interface and writes service.json (pid, port, token, mode 0600) so that the tray app, the CLI and the mobile shells can find it. On Linux and macOS the service runs as a systemd user unit or a launch agent shared by the app and the command line, set up by any command once a vault exists (until varsto uninstall); varsto tray (Linux: StatusNotifier over D-Bus; Windows: system tray, which starts and supervises the service as a child process) and the macOS app only start a service when none answers. A supervisor restarts the service after a self-update (exit code 75). varsto service install registers a login item (LaunchAgent, autostart entry, Startup folder).

Self-update

varsto update, and the automatic check in the page, the tray and the menu bar (which offer an update only when a newer version exists), fetch manifest.json, manifest.json.minisig, SHA256SUMS and SHA256SUMS.sig from the download page with the system curl (base URL https://varsto.net/downloads/, one constant in update.rs, overridable with VARSTO_UPDATE_URL; varsto.net serves /downloads/; the old host redirects there). The update is refused unless SHA256SUMS.sig verifies against the release public key built into the binary (release-key.pub; minisign format: Ed25519 over the BLAKE2b-512 hash of the file, plus a signed trusted comment that must name the version being installed), the archive named in the manifest is listed in the signed file, and the downloaded archive has that SHA-256. Second channel: the SHA256SUMS attached to the GitHub release v<version> is fetched too and must list the archive with the same checksum; if GitHub cannot be reached (or the release has no checksum list), the update waits and says why, unless varsto update --allow-single-source is given (section 60). Then the running binary is replaced (rename-over on Unix, rename-aside on Windows). varsto verify-release <file> [--github] runs the same checks on a file downloaded by hand. The private key is kept offline by the maintainer; see RELEASING.md.

File-manager integration. varsto paths fetch|free <paths> downloads or frees files given by their paths on disk, through the running service (POST /api/paths) or, without one, on the vault directly; varsto open-placeholder <path> downloads a placeholder and opens the file with the desktop's default application. On Linux, varsto install adds a MIME type application/x-varsto-placeholder (*.varsto-placeholder) with a hidden handler entry (double-click downloads and opens), Nautilus scripts (Scripts > Varsto > Download / Free up space), a Dolphin service menu and Nemo actions (Download / Free up space with Varsto); Thunar's custom actions live in one shared uca.xml and are not touched (add a custom action with the command varsto paths --notify fetch -- %F by hand). On Windows, varsto install registers per-user (HKCU) context-menu verbs on all files and the .varsto-placeholder association. varsto uninstall removes all of it. macOS uses Finder Services in the native app.

Selective sync and placeholders (F-039)

A folder mount can be selective. Files the device has not fetched exist as <name>.varsto-placeholder (a few bytes of JSON: size and time). Placeholders are never treated as deletions; fetch downloads one file and pins it so later updates are downloaded too; free replaces a local file with a placeholder, but only when every chunk is on a storage that is not a carrier (or on a replica). The interface lists files with their state and shows encrypted thumbnails.

Transferrer disks (F-048)

A local-directory storage can be marked carrier. The engine writes to it only chunks that no other device holds yet, and after every pull it deletes from the carrier the chunks that both this device and another device hold. Carriers are ignored by fsck's "claim without object" check and never count as the only durable copy for free.

Untrusted replicas (F-045)

A replica device holds a replica token (<vault-id>.<key>), where the key is derive(K3, "replica-ledger"). It mirrors every object from a source directory to a target directory, verifies chunk objects against their names, and records claims in its own ledger batches, sealed under the replica key with key_id = "replica" and signed with its own Ed25519 key. Its device record is published at vault/replicas/<device>.enc under the same key. Owner devices read those batches, fold the claims into the chunk records by object name (the replica cannot know chunk ids), and count them as verified copies. The replica never holds a key that opens content, names or manifests.

Shared folders (F-047)

A share token is <vault-id>.<folder-id>.<folder-key>.<name>. The recipient creates a member device: a device directory with a local random root key, the owner's vault id and that one folder record. Member records live at vault/shares/<folder>/<device>.enc under derive(folder key, "share-registry"); member batches are sealed per folder under derive(folder key, "share-ledger") with key_id = "share:<folder>". Owner devices and members resolve those keys from the folder key, so everyone holding the folder key sees everyone's claims for that folder and nothing else. Members cannot create folders, issue replica tokens or read the owner's device registry. Limitation: one device directory per shared vault; key exchange is manual. Confirming the requester, removing members and revoking tokens: section 24.

Encrypted thumbnails (F-046)

For image and video files, the device that holds the plaintext generates a JPEG thumbnail (longest side 256 px; videos through ffmpeg, found also outside a short PATH, or Quick Look (qlmanage) on macOS without ffmpeg; the Android and iOS apps make video frames natively and hand them in with POST /api/thumbnail), encrypts it under the folder metadata key with associated data (thumbnail, vault, folder, content hash) and stores it at thumbs/<folder>/<content hash>.enc on every hot, non-carrier storage. Any device with the folder key can show the preview, including for placeholders it never fetched. The thumbnail pass runs in every push, for every current image and video that has none yet (tracked per content hash in the folder state, and checked against the storages), so a folder added or attached with files already in it gets its thumbnails without a change to those files. It is bounded and resumable: an early pass of at most 48 files or 8 s runs before the upload (a first screenful while a large folder uploads), and a pass after the upload stops at 200 files or 20 s; the next sync continues, and a thumbnail already on a storage is not made again. With no storage to put thumbnails on nothing is made and nothing is marked done, so pictures that were there before the first storage still get theirs. No thumbnail is written in clear text on disk. Since section 39, ffmpeg decodes with hardware acceleration where it can (-hwaccel auto, seeking before the input) and falls back to software decoding by itself.

Mobile shells

Android: a foreground service runs the same varsto service binary (shipped as libvarsto.so), the activity shows the local interface in a WebView. iOS: varsto-ffi exposes varsto_start and varsto_url for an in-process service behind a WKWebView; the Xcode project is generated with xcodegen on a Mac.

Folders kept encrypted on a device (block cache)

A folder mount may be marked encrypted in config.json (phones default to it). Such a device never writes a plain file of that folder:

  • Block cache. The device keeps the folder's encrypted objects, byte for byte as the storages hold them and under the same layout, in <device dir>/block-cache/chunks/<first two hex>/<object name>. Objects are content-addressed: an object is accepted only when the hash of its bytes is its name, and every fetched object is also decrypted in memory and checked against its chunk id before it is stored. Writes go through a temporary file and a rename. The folder directory stays empty.
  • State. In the folder state (state/<folder>.json), block_cache: true marks that local_index describes the cache: a path is in it exactly when every block of its current version is cached (state "local" in the file list; otherwise "placeholder"). No placeholder files are written.
  • Selective sync works as in any folder. Not selective: every current file is cached on each sync. Selective: new versions of files that are pinned (fetched) or already cached are cached, the others stay placeholders. Freeing a file (or a whole folder) removes it from the index and makes the folder selective; it is refused unless every block of the file is on a storage that is not a transferrer (or on a replica). After a sync and after freeing, cached objects that no cached file uses are deleted if a storage holds them; an object the ledger knows on no storage is kept (it may be the only copy), and one the ledger does not know at all is kept for an hour (an upload being encrypted).
  • Reading. The viewer, read_file and MCP read chunks from the cache first, then from peers and storages, decrypting in memory. On an explicit "open in another app" or "share", POST /api/export writes a decrypted copy to <device dir>/exports/<random>/<file name>; that directory is emptied when the vault locks and whenever the service starts. Locking deletes nothing else: everything else on the device is ciphertext.
  • Writing. POST /api/upload, write_file and the camera upload stream the content through the same content-defined chunker and deterministic chunk encryption as a push of a plain file (an existing chunk keeps its key epoch); only the resulting objects are written, to the cache, without holding the service state while the bytes arrive. The new version is then recorded, the objects are uploaded from the cache and the manifest is published. Moves record a tombstone and the moved version; mkdir writes nothing (folders exist through their files).
  • Peers. The block cache is served to peers as a local object root, so cached objects are answered verbatim.
  • Conversion. States without block_cache come from versions that decrypted such folders into their directory while unlocked. On the next sync while unlocked, every plain file found in the directory is encrypted into the cache and recorded (a file that differs from the synced version becomes a new version and is pushed), the state is saved, and only then is the plain file deleted; placeholder files and empty directories are removed and the index keeps only what is cached. While the vault is locked at service start, plain copies whose content is exactly the synced version are replaced by placeholders, as before.

11. Post-quantum hybrid cryptography (0.0.1-alpha.3)

Every place a public key is used now combines a classical and a post-quantum algorithm, so that stored data and signatures stay trustworthy if either is broken.

Signatures: Ed25519 + ML-DSA-65

  • A device signing key is an Ed25519 seed and an ML-DSA-65 (FIPS 204) seed, serialised as 64 bytes inside keys.enc. The public key is the Ed25519 key followed by the ML-DSA-65 encapsulation of the verifying key (32 + 1952 bytes) and is what the device record publishes; the device id is the keyed hash of these bytes.
  • A signature is the Ed25519 signature followed by the ML-DSA-65 signature over the same message (64 + 3309 bytes). sig_alg is ed25519+ml-dsa-65. Verification requires both parts; a batch whose post-quantum half is missing or damaged is rejected even if the Ed25519 half is valid.
  • Downgrade protection: a key that carries a post-quantum part never accepts sig_alg = "ed25519". Batches signed by alpha-0 devices (32-byte public keys, sig_alg = "ed25519") remain valid for those devices; such a device keeps signing Ed25519-only until it is re-enrolled, because changing its key would change its device id. No stored object had to be rewritten: the algorithm identifier on every batch selects the verification rule.
  • Cost: about 3.3 KB per batch. Batches already group many events (model B), so the ledger grows by a few kilobytes per sync, not per file.

Key encapsulation: X25519 + ML-KEM-768

  • Used wherever a secret must reach another party's public key. Today that is the share token: the recipient runs varsto share request, which keeps a private key in its device directory (share-request.enc, sealed under the passphrase the device will have, Argon2id as keys.enc; alpha.16 wrote it in clear as share-request.json, which the next read seals and removes) and prints a request code vsr1.<X25519 key || ML-KEM-768 key> (1216 bytes, hex). The owner runs share create <folder> --to <code>.
  • The owner encapsulates to both halves, derives one key with derive_key("e2ee-sync-format/0/hybrid-kem/x25519+ml-kem-768", len-prefixed(x25519_ss, mlkem_ss, ciphertext, encapsulation_key)), and encrypts the folder key with XChaCha20-Poly1305 under associated data (share-token, vault id, folder id, name). The sealed token vst1.<vault>.<folder>.<kem-alg>.<kem-ct>.<sealed-key>.<name> carries only ciphertext and can travel over any channel; only the requesting device can open it. The plain token format of alpha.2 still exists and is marked as carrying the key.
  • Confirming that a request code came from the intended person (a six-word fingerprint both sides compare), version-2 tokens, removing members and revoking tokens are in section 24. QR codes: section 51 (new in 0.0.1-alpha.14).

12. Remote storages: S3-compatible buckets and rclone remotes (0.0.1-alpha.3)

The storage abstraction (put-if-absent, get, exists, list, delete) now has three backends. Every object is ciphertext before it reaches any of them; a storage learns object names and sizes only.

  • S3-compatible (varsto storage add-s3): plain HTTPS with AWS Signature Version 4, no SDK. Works with AWS S3, Scaleway, Hetzner Object Storage, Backblaze B2, Cloudflare R2, MinIO and rclone serve s3. Path-style URLs by default (--virtual-host for bucket.host). An http:// endpoint is refused unless its host is a loopback address (localhost, 127.0.0.0/8, ::1) or the storage was added with --insecure-http (allow_insecure_http in config.json; --s3-insecure-http on join and share join, insecure_http in the local API), because the request signatures and the encrypted objects would otherwise travel without transport encryption. Writes PUT with If-None-Match: *, so an existing object is never overwritten. Whether the server honours the condition is probed on the first write of a process: a probe object under vault/.probe-<random> is written twice with the condition and deleted; 412 on the second write means honoured, 200 means the header is ignored, 400 or 501 means it is refused. The answer is kept in config.json (conditional_writes, by storage name) so later processes skip the probe, and varsto storage list shows conditional writes: unsupported where it was negative. A server that honours the condition gets one PUT per object (412 means the object was already there); one that does not gets HEAD-then-PUT, with one warning in the log per storage, which is safe because every object name is content-addressed or owned by a single writer. Listing uses ListObjectsV2 with continuation. A storage class (--storage-class DEEP_ARCHIVE, GLACIER_IR, ...) is sent with every PUT; archive classes mark the storage cold automatically, and a GET that returns InvalidObjectState is reported as "must be restored first", never retried silently. The secret access key is kept in secrets.enc (XChaCha20-Poly1305 under derive(master, "storage-secrets"), mode 0600), never in config.json; VARSTO_S3_SECRET_<NAME> is the fallback for scripts.
  • rclone (varsto storage add-rclone <name> remote:path): runs the user's own rclone (rcat, cat, lsjson --stat, lsf -R, deletefile). Credentials stay in rclone's configuration; Varsto never reads them. Any of rclone's backends (SFTP, WebDAV, Google Drive, OneDrive, Storage Box, ...) becomes a Varsto storage this way.
  • Local directory: unchanged.

Opened once per operation. The engine keeps every storage it opens (the S3 connection pool, the rclone remote, the view of a storage's packs) for the whole sync, push or pull and hands the same backend to every phase, instead of opening the storage again in each; disk pools are opened anew every time, because their disks come and go. The backends are dropped at the end of the operation, so a changed bucket, secret or setting is seen by the next one. rclone version runs once per process, not once per open. The uploader threads of a push (section 30) take one work item per target set and batch (one pack, written to every storage of the set), so several sets are written side by side rather than one after the other.

Tests: the S3 backend is exercised against rclone serve s3 (a local S3 server with access keys) and the rclone backend against a local-path remote, both through the full two-device sync, in crates/varsto-core/tests/remote_storages.rs. They skip when rclone is not installed.

13. Last-accessed times and the MCP server (0.0.1-alpha.3)

Last accessed. Each device keeps its own record of when a file was last used through Varsto: fetching a placeholder, opening or downloading it from the interface, reading it through the MCP server, and the filesystem access time observed at scan (never older than the modification time). A use while another process holds the device directory (a sync of the service, section 77) is not recorded rather than waited for. The record lives in the per-folder state (state/<folder>.json, field accessed). last_accessed_utc (reported by varsto folder files --json, /api/files and the MCP file list, and used by the idle-file advice) is the newest use on any device of the folder, merged as described below.

Access records (0.0.1-alpha.9). Every device publishes its map as one object per folder, vault/access/<folder>/<device>/<written utc, 20 digits>.enc: zstd-compressed JSON {device, folder, written_utc, accessed: {path: utc}}, sealed with XChaCha20-Poly1305 under derive(current metadata key of the folder, "access-record", folder) with associated data (access-record, vault, folder, device, written_utc). After a sync, at most once an hour (ACCESS_INTERVAL_SECS), a device writes a new record for every attached folder whose map changed and deletes its older ones, then lists the folder's records and reads the newest of every other device that is newer than the one it holds (state/access/<folder>.json). Records of devices that are not known (vault registry or folder members) or that were removed are ignored; locked Strongrooms are skipped. The merged time of a path is the maximum over this device and the others, so "idle for 90 days" means idle on every device. Reasons for an object rather than ledger events: access times change with every use, while the ledger is append-only and replicated forever (checkpoints bound its replay, not its history); one replaceable object per device and folder costs O(files) bytes no matter how often files are used, and the ledger format does not change. Limits: an hour's delay; a member of a shared folder contributes its use too (it is a device of the folder); a path moved on one device keeps its old name in the others' records until they use it again; the times are hints for advice and are not signed.

MCP server. The MCP server was removed and is not part of the program.

Interface: files now show "last used" and an Open link; /api/open downloads a file and records the access; /api/move and /api/advice back the same operations.

14. Durability policies with alerts (0.0.1-alpha.3, F-032)

A policy belongs to a folder: a minimum number of copies on any storage (transferrers never count), a minimum per place, and a window within which every chunk must have been verified by a device other than the one that wrote it. Places are labels on storages (--place when adding one; a directory defaults to home, a bucket or rclone remote to cloud; replicas count as replica, storages this device does not know as other).

Policies travel with the folder: varsto policy set writes the folder record locally and publishes an append-only policy record at vault/policies/<folder>/<device>/<updated_utc>.enc under the folder record key; every device adopts the newest it can read. Evaluation (varsto policy check, the interface, the service after every sync) uses the ledger alone: for every chunk of every current file, the storages that claim it, whether an independent verification exists and when (batches now carry claim and verification times). States: ok; at_risk when a verification is older than three quarters of the window, or the copy count is met exactly and one copy sits on cold storage or absent media; violated when a rule is broken; unknown when a storage could not be opened. varsto policy check exits 0, 1, 2 or 3 accordingly, so a cron job or a monitoring probe can use it. The service raises a desktop notification (notify-send on Linux, Notification Center on macOS) when a folder's state gets worse, and the interface shows the state next to the folder and a banner on top.

Grace for new data. A block is not counted against the verification window until it has been stored for longer than the larger of the window and policy::NEW_DATA_GRACE_SECS (24 hours; the one constant to change). Its age is the earliest claim time the ledger records for it on any storage; a block with no claim time counts as old. Inside the grace an unverified block is verification pending: it adds nothing to reasons, PolicyReport.chunks_verification_pending counts it, chunks_unverified_in_window does not, and the folder stays ok (the interface shows a neutral "stored, verification pending" tag, not an alert). After the grace the block violates the window as before. Copy-count and per-place rules get no grace: a requirement that cannot be met (more copies than storages exist, a place with no storage) still reports violated at once, and only for that reason.

Honest limits: verification comes from another device's automatic verification (section 20), from varsto fsck --verify or a replica run, and from downloads during pull. Place labels are per device: two devices should label storages the same way, which the registry does not enforce yet; storage names may differ between devices for automatic verification, which matches storages by identity.

15. Peer-to-peer transfer (0.0.1-alpha.4; NAT traversal 0.0.1-alpha.6)

Superseded by section 77 (storage format 3): peers speak TLS only (no plaintext HTTP over TCP), tokens are bound to the TLS connection instead of the p2p-auth vault key, peer records and beacons are signed (sections 75 and 77.8). Kept as the history of format 2.

Every device that holds a file can serve its chunks as exactly the objects the storages hold, because chunk keys and nonces are deterministic per folder: the service keeps a snapshot (folder keys plus an index object name -> file, offset, length, rebuilt after every sync) and re-encrypts a piece on request, or serves it verbatim from a local-directory storage. A device that needs a chunk asks its peers or its (non-cold) storages, verifies every object against its content-addressed name (the same check as for storage copies), and falls back to the other source when the first lacks the object; how it chooses is under Downloading below. PullReport.chunks_from_peers and the service counter show how much came from peers.

Transport: two transports share one request handler and one port number. Peer-to-peer is on by default on every platform (TCP and UDP port 17893; varsto p2p disable turns it off, and enable or disable take effect in the running service at once). HTTP over TCP serves the LAN and user-forwarded ports as before; QUIC over UDP on the same number (0.0.1-alpha.6) is the transport that crosses NATs. Objects are ciphertext, so nothing further is encrypted on the wire for its own sake; every request carries X-Varsto-Peer: <device>:<unix time>:<keyed hash> (the QUIC line X-Varsto-Auth), where the hash is keyed_hash(derive(master, "p2p-auth"), device || time || path), valid for five minutes, so only a holder of the vault key can fetch and a listener learns object names only. Members of shared folders are not peers yet (they lack the master key).

Downloading (0.0.1-alpha.9): requests run side by side in a window that starts at 16 and moves between 8 and 32 in steps of 4 by hill climbing on throughput: the bytes per second of each round (at least half a second and 8 objects) are compared with the previous round's; a gain keeps the window moving the same way, a loss of more than 5 % turns it round. (Answer times cannot steer it: with fewer requests in flight, kept connections idle long enough for TCP to restart slowly, so answers get slower.) Each object goes to the peers or to the storages: peers first while the storages have no sample (every 16th object asks the storages, to get one); then each source gets a share of the objects in proportion to its speed (mean seconds per object), the peers' speed counted 1.25 times, since peer-to-peer costs nothing per gigabyte. A source that lacks objects rests: the storages after 2 misses in a row for 30 s (a bucket whose blocks were moved away), the peers after 4 for 10 s; statistics older than two minutes are dropped. Among the peers, those with a working route are asked first; among them a peer that lacked the last objects asked goes after those that had them, and among equals the one expected to answer first goes first: its mean seconds per object times its requests in flight plus one, so two devices that hold the folder (the writer and another device pulling it too) share the requests by their speed instead of the first taking all. A peer that lacked an object, or was never measured, is asked first again once its probe is due: 250 ms after a miss, doubling per miss in a row up to 30 s; one request takes the probe, so the requests beside it do not all ask the lacking peer. So with peer-to-peer on, a download uses both sources instead of waiting on the slower one. Over TCP the client keeps connections to each peer address open between requests (HTTP/1.1 keep-alive, up to 32 per address, closed after 20 s unused; a kept connection that fails is replaced and the request asked again once); the listener sets TCP keep-alive (60 s, then every 15 s), which accepted connections inherit, so a peer that vanished is noticed. Peers of earlier versions close the connection after each request, which the client handles as before. The server is a small HTTP/1.1 server of its own (GET only): a thread per connection, at most 256 connections, one idle for 30 s is closed; producing objects is limited to twice as many at a time as there are cores (8 to 32). It produces a requested object by first encrypting the block uncompressed and checking the name, which matches for incompressible blocks and saves compressing them again, and otherwise compresses as at upload; objects it had to compress are kept in memory for other devices asking for the same blocks (VARSTO_P2P_CACHE_MB, default 64, 0 off). A device pulling a folder serves each file it puts in place right away (p2p::FreshPieces): the engine adds the file's blocks (path, offset, length, chunk, epoch and the folder keys) to a set the snapshot answers from after its own pieces, checked against the chunk id when read as every piece is, and empties it when it builds the next snapshot, which covers those files. So readers that pull the same folder at the same time help each other: a block one has written can come from it. Folders kept encrypted here are served from the block cache as before; a file still being written is not served until it is complete.

The UDP socket is driven through quinn-udp's socket state so that every datagram carries its addresses: a server bound to 0.0.0.0 on a multi-homed host (a cloud machine with a private network, LAN plus VPN, Docker bridges) answers from the address the request arrived at (IP_PKTINFO in, source address out), as TCP does by itself. Without this the kernel picks the source by its routing table and the client's QUIC stack drops the answer as coming from an unknown remote.

QUIC identity: the service creates, on its first start, a self-signed ECDSA P-256 certificate per device (p2p-cert.der, p2p-key.der in the device directory, with quinn, rustls with the ring provider and rcgen); its SHA-256 travels in the peer record. A client pins the hash the record announced (a custom server-certificate verifier; names and dates play no part) and presents its own certificate; the server demands one and accepts only hashes of devices whose records it has read, plus its own. A stranger, or a vault device whose record has not arrived yet, fails the handshake; the request header above remains as a second layer behind it. ALPN is varsto-p2p/1. Framing is one bidirectional stream per request: GET <path>\nX-Varsto-Auth: <token>\n\n, answered by <status> <length>\n and the body; REGISTER <device>\n... on a stream makes the connection a relay registration (below).

Discovery: on the LAN a multicast beacon (239.255.77.77:17892, VARSTO1 <tag> <device> <port>, where the tag is a keyed hash of the vault id, so beacons cannot be linked to a vault) every five seconds; across the internet a rendezvous record vault/peers/<device>.enc, encrypted under the device registry key. Record version 1 (alpha.6; version 0 records without the new fields are still read) carries version, device, name, port, lan_addrs, public_addrs (what the user configured with --public), updated_utc, and the traversal fields: udp_public (addresses STUN servers saw for our UDP socket), udp_local (the interface addresses with the UDP port), cert_sha256, nat (none, cone, symmetric or unknown), relay_via (reachable devices this one holds a relay registration with) and reachable (a public address answered the device's own probe, or the user configured one). The service republishes the record when any field other than the timestamp changed, and once an hour regardless.

STUN: the service asks the servers in p2p.stun (default stun.l.google.com:19302, stun.cloudflare.com:3478, stun.nextcloud.com:443; an empty list disables it) with an RFC 5389 Binding Request from the QUIC socket itself at start and every ten minutes, reading XOR-MAPPED-ADDRESS (MAPPED-ADDRESS as fallback, IPv4 and IPv6). Two servers agreeing on the mapped port means a cone NAT, disagreeing a symmetric one, a mapped address that is one of our own means no NAT, fewer than two answers no guess. The guess is recorded as such: it cannot see every NAT behaviour. The STUN servers only ever see an empty Binding Request from the UDP port; nothing about the vault.

Hole punching: when fetching from a peer, the client tries the route that worked last time first, then in order (a) its TCP addresses (LAN beacon, lan_addrs, public_addrs), (b) QUIC to its udp_public, public_addrs and udp_local addresses while sending an 8-byte punch datagram (VARSTOPU) every quarter second for up to three seconds (LAN addresses get no punches and a short wait), (c) a relay. A keeper task punches toward every known peer's public UDP address every twenty seconds, which keeps our own NAT mapping alive and opens a path for peers that try to reach us. The outcome per peer is remembered: a dead peer costs one round of timeouts per minute. A storage error while listing records keeps the last good list, because an empty peer table would stop the punches (letting the mapping lapse) and make the QUIC server refuse every peer's certificate. The service asks STUN again (at most every 30 s, otherwise every ten minutes) when a punched connect failed or the keeper paused for longer than a mapping survives, since the mapping may have changed in the meantime. Every path decision, punch set, QUIC connect and relay step is one p2p: line in the service log.

Relay: every device whose record says reachable relays for its vault; there is no vendor relay. A device that is not reachable opens a QUIC connection to each reachable peer at service start (a failed attempt is retried after 30 s, then with doubling waits up to five minutes; a lost registration is retried at once, and a success republishes the record immediately so peers learn relay_via), sends REGISTER <device> on the first stream (the relay checks the token for /p2p/register/<device> and that the client certificate is the one that device's record announces), and from then on accepts the streams the relay opens on that connection and serves them exactly like incoming requests; QUIC keep-alives hold the NAT mapping. The relay answers GET /p2p/via/<device>/<rest> by checking the token for /<rest>, opening a stream on that device's registration connection, forwarding the request and copying the answer back (502 when nobody is registered under that device). A fetcher picks the relay from the target's relay_via. The relay sees ciphertext objects and object names, nothing else, and it is one of the user's own devices.

Since section 83: when no device of the vault is reachable, the rendezvous service is the last route: it coordinates the punch (both sides at once, from addresses it observed) and, when that fails, splices the two devices' pinned TLS session over WebSocket. The limits below about vaults whose devices are all behind NAT no longer hold while the rendezvous is on.

Status: varsto p2p status and GET /api/p2p report the NAT guess, the observed public address, whether the device is reachable, the relays it is registered with, and per peer the path in use or last tried (direct-lan, direct, relayed via <name>, unreachable, or untried); the Peers page shows the same. Without a running service the command probes over TCP and asks STUN from a temporary socket, whose mapping differs from the service's.

Traffic: the service counts, per peer and direction, the object bodies it received and sent (bytes, objects, requests in flight, path and address of the latest exchange) over every transport, and what it forwarded between two other devices as their relay. GET /api/p2p/traffic and varsto p2p traffic [--watch] report current speeds (average over the last 5 seconds), totals since the service started and one-second samples of the last minute; the Peers page draws them as a flow diagram. The endpoint is answered by the HTTP dispatcher without the service state, so it stays live during a long sync. Nothing of this goes over the wire.

Honest limits: tested on localhost (QUIC with pinned certificates, rejection of an unknown certificate, a relayed fetch A -> R -> B, the multi-homed reply source), on the maintainer's own networks, and on a rig of three devices (a public cloud machine as relay, a device behind a Linux MASQUERADE NAT on it, a device behind a home NAT) in both directions, direct and with direct UDP blocked (relayed). A Linux NAT keeps one external port for all flows of an internal socket until a peer's punch arrives while no flow of ours is alive (service start, a pause): then the port is in use and the NAT picks a random one for every later flow, so the published udp_public is stale until the next STUN probe, which is why probes are repeated on suspicion. Symmetric NATs on both sides are not punchable and fall back to the relay, which needs one reachable device in the vault (a home server, a VPS, a forwarded port); a vault whose devices are all behind NAT has no path across the internet. There is no DHT and no packaged self-hosted relay for vaults without a reachable device; IPv6 is parsed but the sockets are IPv4; port-restricted and symmetric cases are guessed, not measured with a second port.

Hardening of the STUN side channel, the TCP request head and the QUIC limits: section 60.

16. Compression (0.0.1-alpha.4, format version 1)

Ciphertext does not compress, so compression happens once, before encryption, on the chunk: the payload is one method byte (0 raw, 1 zstd) followed by the data. Format 2 compresses at zstd level 3 (level 12 before), and only when a probe says it pays: the chunk's first 64 KiB are compressed at level 1, and when that saves less than 5 % the chunk is stored raw without compressing the rest; otherwise the whole chunk is compressed and kept when it saves at least 5 %. The decision depends on the content alone, so every device packs a chunk alike, and photos and video cost a cheap probe and one byte. Two devices on different zstd versions may pack a chunk differently: that gives two objects (two names), never two inputs under one nonce, because the nonce follows the packed bytes (section 3). The gain reaches every copy and every transfer alike: cloud, disks, transferrers and peers on the LAN or across the internet, with no transport-level compression to tune. Format version 0 objects are not readable by this version (see format-versions.md).

17. Strongroom folders (0.0.1-alpha.4, S-012)

A Strongroom folder's key is never at rest anywhere: the keyring and the published folder record carry an empty key and a strongroom block (method, credential id, 32-byte salt, the folder key wrapped under derive_key(context, hmac_secret) with XChaCha20-Poly1305 and the vault id and the folder id as associated data, so a wrap copied into another vault's record does not open there; wraps made before the vault id was bound in do not open any more, there is no compatibility path). The secret comes from the FIDO2 hmac-secret extension (credential and salt in, 32 bytes out, after a touch), so the same physical key opens the folder on every device of the vault, and nothing derivable from the vault's master key does. Enforcement is cryptographic: without the unwrapped key no manifest, name or chunk of the folder can be read.

Backends: fido2 runs the libfido2 command-line tools (fido2-cred -M -h, fido2-assert -G -h), which exist for Linux, macOS and Windows, so the core carries no native HID dependency; software keeps the secret in a file and exists for the tests and the lab (it protects nothing beyond the passphrase and says so); it is built in only with the software-key cargo feature, which release binaries do not have, so --software is hidden and refused there, and a Strongroom enrolled with a software key cannot be opened by such a binary. Enrolling takes two touches (credential, then wrap); unlocking one.

Behaviour: varsto strongroom create makes a new folder, and varsto strongroom convert turns an existing one into a Strongroom (below). Strongroom mounts are selective, so files are placeholders until fetched. An unlock holds the key in the process memory for a window (default 15 minutes) and hands it to the running background service over the local API so the service can sync; when the window ends the key is forgotten and sync skips the folder. Locked folders are skipped by sync, refused by direct operations, never shared, and never visible to the MCP server.

Honest limits: files fetched while unlocked stay on disk until freed (the interface reminds you); malware active during the window sees what you see; the libfido2 tools prompt for the PIN on the terminal, so the first unlock happens on the command line even when the interface is used afterwards; a lost key with no backup key means a lost folder (enrol a backup key before trusting it with anything); the recovery kit does not cover Strongroom folders.

Key commitment and PIN. The strongroom block also carries check_hex = keyed_hash(derive(folder_key, "strongroom-check"), folder_id) (written when the Strongroom is made and when it is re-keyed or converted; kept when a key is added or removed). A folder key that comes by hand (POST /api/strongroom/unlock {key_hex}, the key_hex and old_key_hex of convert and rekey) is accepted only when its commitment matches, compared in constant time; a wrong key is refused with "that is not the key of this Strongroom" and nothing is changed (before, any 32 bytes "unlocked" the folder, and a conversion with them corrupted the manifests). A block without check_hex (enrolled by an earlier version) refuses key-by-hand operations; unlocking with the security key itself needs no commitment, the wrap authenticates. Both libfido2 tools are run with -t pin=true, so the PIN is asked for at every unlock, not only when the credential is made; varsto strongroom --uv ... (or VARSTO_FIDO2_UV=1) adds -t uv=true. CTAP2.1 derives a different CredRandom for a user-verified assertion, so an enrolment made before this change, and one made with or without --uv, opens only the way it was made: enrol such a Strongroom again (convert it back, or add a new key and remove the old one) after the change.

Backup keys. A Strongroom can have several security keys. Each enrolled credential has its own salt and its own wrap of the same folder key; the first key stays in the top-level fields of the strongroom block (so records written before backup keys read unchanged) and the others are listed in backups (method, credential, salt, wrapped key, optional label, time added), with updated_utc stamping the list. Unlocking tries every enrolled key in turn. varsto strongroom add-key <folder> needs one touch of an enrolled key (to unwrap the folder key) and two of the new one; strongroom keys lists them; strongroom remove-key <folder> <number|label|credential> refuses to remove the last one. A changed list is published as vault/strongroom-keys/<folder>/<updated_utc>.enc (sealed under the folder-record key, newest wins on every device); older lists are deleted and the folder record is rewritten with the current list, so devices that join later see it too. Removing a key removes its wrap from the storages but does not change the folder key: a removed key that someone kept, together with an older copy of the records (on a device or in a backup of a storage), still opens the folder until the Strongroom is re-keyed (below).

Re-keying (0.0.1-alpha.9). varsto strongroom rekey <folder> rotates the folder key, for example after removing a key someone may have kept or on suspicion of a leak. It is the conversion below, from a Strongroom to a Strongroom: the command line unlocks the folder with an enrolled key (one touch), makes a new folder id and a new random key, and wraps the key for every enrolled security key with a fresh salt (strongroom::rewrap_enrolled, one touch each; a key that does not answer stops the command, so remove a key that is gone first). The rest runs in the background service when one is running (POST /api/strongroom/rekey {folder, folder_id, key_hex, old_key_hex, info, minutes}), otherwise in the command: every current file is re-encrypted under the new key, the conversion record (now with rekey: true) is published, the device switches, and the old chunks, manifests, thumbnails, policy records, folder record and key lists (vault/strongroom-keys/<old folder>/) are deleted from every storage. The journal keeps only the old record without a key, so no key is at rest during a re-key; an interruption resumes with the same command (one touch for the old key, one for the new). Other devices adopt it like a conversion: the mount moves to the new folder, locked, and synced plain copies become placeholders. The interface shows the command next to the enrolled keys. Limits: the same as for a conversion (copies made earlier, local trash, replicas and storage backups are not reached); every enrolled key must be present.

Converting an existing folder. varsto strongroom convert <folder> (two touches; with a running background service the command line touches the key and the service does the rest over the local API, POST /api/strongroom/convert). The converted folder gets a new folder id and a new random key, so its chunk ids, objects, manifests and ledger facts never mix with the old ones. Steps, each safe to repeat:

  1. The conversion is journalled in the device's encrypted keyring (old folder record, new id, the new key's wraps); the folder is pulled and pushed under its old key. It is refused while versions from other devices could not be downloaded, and for shared folders.
  2. Every current file is re-encrypted under the new key: from the local copy when it is the synced version, otherwise downloaded under the old key first (placeholders). The old keyed content hash is checked while reading. Each chunk is put on every storage that takes it; every chunk must be on at least one non-carrier storage. The manifest of the new folder is published and the ledger batch committed.
  3. A conversion record vault/converted/<old folder>.enc (sealed under the folder-record key; old and new id, converting device, and the highest manifest sequence of each device that the converted copy includes) is published, then the device switches: the keyring holds the new Strongroom record (empty key), the mount points at the new folder and becomes selective, the key stays unlocked for the chosen window, and the new folder record is published.
  4. The old copies are deleted from every storage of the device, cold ones included: the chunk objects the ledger and the old manifests name, every old manifest, thumbnails, policy records and the old folder record (which held the old key under the vault key). Only when every storage is clean does the journal, and with it the old key, leave the keyring; otherwise the clean-up is retried on every sync.

An interruption before step 3 leaves the old folder exactly as it was (new objects may already exist; they are reused on resume); running the command again resumes under the same new key after one touch. An interruption after step 3 is finished by the next sync.

Other devices adopt the conversion on their next sync, once both the conversion record and the new folder record are readable: the mount moves to the new folder (selective, locked), plain copies whose content is the synced version are replaced with placeholders, the old key is dropped from the keyring after the device has removed the old copies from its own storages (disk pools are per device). Files changed there since the converted copy was made stay as they are; after the next unlock they are synced like new local files (identical content merges, different content becomes a conflict copy, a deletion made after the snapshot is undone). If the device published changes after the converted copy was made, none of its plain copies are removed. Limits: a device that already had the old key could have kept it, and anything it copied stays readable to whoever holds it; files in a device's local trash, replica devices and backups of a storage are not reached; the ledger keeps its signed facts about the old folder (chunk ids and object names, no content).

18. Recovery kit (0.0.1-alpha.5, F-042)

varsto recovery kit prints the vault key as 24 BIP-39 English words (256 bits plus the standard 8-bit checksum, so a miscopied word is detected) in a printable layout with the vault id and the rules: paper or metal, several places, never a photo or a cloud note, test yearly. With --shares it adds three Shamir shares over GF(256) (any two rebuild the key; one reveals nothing), each as an index and 24 words; varsto recovery combine "<index>: <words>" "<index>: <words>" rebuilds the key, and varsto join --words "..." enrols a device from the words directly. The kit also prints a key check, the first 8 hex digits of BLAKE3.derive_key("varsto recovery key check v1", key): combine --check <key check> refuses a rebuilt key that does not match it (a share from another kit, or a copying mistake the word checksums let through), and combine refuses two shares with the same index before interpolating. Shares are Shamir shares over GF(256) from the blahaj crate (a fork of sharks that fixes RUSTSEC-2024-0398, random coefficients drawn from 1..=255 instead of 0..=255; the share encoding, the x coordinate followed by the 32 y bytes, is unchanged, so kits printed earlier still combine). Only an unlocked owner device can print the kit; member devices hold folder keys only. SLIP-39-compatible shares are not provided and there is no QR code for the recovery kit: words are what survives on paper.

19. Disk pool (0.0.1-alpha.6, plan 6.35 and 6.41)

A pool is one storage made of removable disks that are attached and detached over time. It holds chunk objects only: records, ledger batches, manifests and thumbnails go to the other storages, so a pool is never a device's only storage. The pool itself never formats, mounts or unmounts a disk; on Linux the disk init, disk insert and disk unmount commands of section 34 do that around it.

Disk layout. A disk is a directory (its mount point) with two things of Varsto's:

<mount>/.varsto-disk.json      marker: { pool_id, disk_id, label, vault_tag, created_utc, format: 1 }
<mount>/varsto/packs/<xx>/<pack id>   packs of encrypted chunks, the local-directory layout of section 5 (format 2, section 62)
<mount>/varsto/index.json      the disk's own index: { format, pool_id, disk_id, label, written_utc, objects: { key: size } }

pool_id is keyed_hash(derive(K3, "disk-pool"), "pool:<name>")[..16] and vault_tag is keyed_hash(derive(K3, "disk-pool"), "vault:<vault id>")[..16]: both are computed from the vault key, so every device of the vault derives the same pool id for the same pool name and recognises its disks, while the marker reveals neither the vault id nor the pool name. disk_id is 16 random bytes. Objects are written to a temporary name, fsynced and renamed, exactly as in a local-directory storage.

Device state. <home>/pool-<pool id>.json maps every object key to the disk that holds it (with its size), keeps deletions queued for disks that were away (pending_deletes, per disk) and the disk registry: id, label, last mount path, capacity, bytes used, last seen, last verified, retired. config.json carries the pool (kind: "pool": name, place, reserve_percent default 5, min_reserve_bytes default 2 GiB, optional scan_roots) and mirrors the registry. The pool index is per device, like the rest of config.json; a disk filled by another device is adopted when it is first seen attached: its marker names the pool, its tag matches the vault, and its index.json tells what it holds.

Attach detection. A disk is attached when a directory with its marker is found at its last mount path or by scanning the platform's mount roots: /media/*/*, /run/media/*/* and /mnt/* on Linux, /Volumes/* on macOS, every drive letter on Windows, plus the pool's scan_roots. Scanning reads one small file per candidate directory. The background service checks every 30 seconds and logs and notifies "data-01 attached" / "data-01 detached"; an attach asks for a sync, so files waiting for the disk arrive.

Behaviour as a storage. put picks the attached, non-retired disk with the most free space whose free space after the write stays above max(reserve_percent × capacity, min_reserve_bytes); with no disk attached (or no room) the pool is left out of that push and tried again on the next one (PushReport.storages_unavailable). get reads the disk if attached; otherwise it fails with a typed NeedsDisk { label, disk_id, place } error, which pull reports as attach disk <label> (<place>) (PullReport.disks_needed, and the file stays in pending_remote), /api/fetch returns as {"needs_disk": {"label", "disk_id", "place"}}, and the interface shows as "This file is on disk

Life cycle. varsto storage add-pool <name> --place <place> [--reserve-percent N] [--scan-root <dir>] creates the pool. varsto disk add <mount-path> --pool <name> --label <label> writes the marker and the disk index, registers the disk and fills it with every object of a current file that the pool holds on no disk, largest first, within the reserve; objects come from the other hot storages or are re-encrypted from local files, and no other storage is changed. varsto disk list shows every disk: attached (mount, free space) or offline, blocks and bytes used, last verified, pending deletes, retired. varsto disk check <label> [--full] is the reattach routine: verify the marker, apply the queued deletions, verify every object's size (--full: re-hash it; a full check also publishes chunk_verified events), drop bad objects from the index, adopt objects on the disk the index did not know, then fill with new objects; it prints checked 3.2 GB, 0 bad, 410 MB removed, 620 MB added. varsto disk eject <label> writes the disk's index, syncs the directories and prints "safe to remove"; unmounting is the user's. varsto disk retire <label> marks the disk so nothing new goes there and prints how many objects exist only on it. The local API has the same operations: GET /api/disks, POST /api/disk/add {mount, pool, label}, POST /api/disk/check {label, full}, POST /api/disk/eject {label}, POST /api/disk/retire {label}, and POST /api/storage {kind: "pool", name, place, reserve_percent}.

Not done. Disk groups (several copies on disks in different places) came in 0.0.1-alpha.9, section 23; no SMART or health reading; no transfer-time estimate in the "attach this disk" prompt; the service does not run disk check by itself on attach (the scrub of section 33 reads attached disks on its schedule, after 0.0.1-alpha.13); imports of git-annex repositories are in section 42 (0.0.1-alpha.14); a disk unplugged in the middle of a write fails that push instead of being retried; a disk's index.json is rewritten whole, so very large disks pay for it at every eject; members of shared folders cannot use pools (they lack the vault key the pool id is derived from).

Verification reads. disk check, the verification step of disk insert and the scrub of a disk read it according to its medium (section 39): a spinning disk strictly one object after another in key order, as before; a solid-state disk with a few readers in parallel.

Packs (format 2). A pool holds packs like every other storage (section 62): the pool index, the disks' index.json, placement, queued deletions and disk groups work on pack keys. A push places a whole pack on one disk; a fill packs the blocks the pool lacks into new packs of up to 64 MiB on the disk being filled, and a further copy under a disk group rule copies a whole pack to a disk of another place. A disk check and a scrub hash each pack against its id and count every block the ledger places in it; a block counts as verified, missing or kept elsewhere through its pack (with_pack_ids, blocks_by_pack), and the tidy step of disk insert removes a pack only when the ledger dropped it from the pool (section 34).

20. Automatic verification, storage prices and placement (0.0.1-alpha.8)

Automatic verification (F-032). The background service verifies blocks that other devices wrote, so a policy's "verified by another device within N days" stays true without anyone running fsck --verify by hand. After a sync, when the schedule says a run is due, the device pulls the ledger and lists every copy (folder, chunk, storage) that another device claimed and that this device can read without asking: cold storages and transferrers are never read, replicas are not storages of this device, and a copy on a pool disk that is away is counted as offline. A copy is due when no other device has verified it, at half the folder's verified_within_days window after its last independent verification (well before the policy turns "at risk" at three quarters), or after reverify_days (default 30) in folders without a window. Due copies are taken oldest deadline first, folders with a window first on ties, until the budget of the run is spent (default 2000 blocks or 256 MiB; the first block is always taken). Each one is downloaded and its ciphertext hashed against its object name; a match is recorded as chunk_verified, the same event fsck --verify and pull record, and a mismatch or a missing object is reported, raises a desktop notification and is queued for automatic repair (section 26). Schedule and budget are per device in config.json (verify: enabled default true, interval_hours default 24, max_bytes, max_blocks, reverify_days); the last run is kept in state/auto-verify.json. Nothing runs while the service is paused or locked.

Storage names are local: one device may call a bucket "box" and another "primary", and the ledger names a copy by its writer's name. Every storage therefore gets a random identity object, vault/storage-id.json, written with put-if-absent by the first device that needs it (the first writer wins), and every device publishes its names with their identities at vault/storage-names/<device>/<utc>.enc, sealed under the device registry key; readers take the newest per device. A copy the writer calls "box" is read from the local storage with the same identity and the check is recorded under the writer's name, so it meets the writer's claim. A writer that has not published its names yet (an older version) is matched by equal name.

Commands: varsto verify (schedule, last and next run), varsto verify run (one run now, whatever the schedule says; exit code 1 on a corrupt or missing object), varsto verify set [--on|--off] [--interval-hours N] [--max-mib N] [--max-blocks N] [--reverify-days N]. API: GET /api/verify, POST /api/verify {enabled, interval_hours, max_mib, max_blocks}, POST /api/verify/run; GET /api/service carries auto_verify and a one-line auto_verify_text, which varsto service status prints. The interface shows the status on the Policies page with Run now, Schedule and Turn off/on.

Storage prices. Each storage can have a price: storage per GB-month, egress per GB, retrieval per GB and a minimum storage duration for cold classes, in one currency. The user's figures live in config.json (prices, by storage name); a figure the user did not set comes from the built-in price data (data/providers) when an S3 storage's endpoint, region and class are recognised (Amazon S3 in eu-central-1 and Scaleway in fr-par today, the regions the data was verified for), with the source and verification date. Unknown means unknown, never free. The monthly cost of a storage is the bytes the ledger records on it times its price; a folder's cost is the sum over the storages that hold its current files, kept per currency and never converted. varsto storage price <name> [--gb-month X] [--egress X] [--retrieval X] [--min-days N] [--currency EUR] [--clear] shows or sets the figures, varsto storage list shows price, stored bytes and monthly cost, GET /api/storage/costs and POST /api/storage/price {name, gb_month, egress, retrieval, min_days, currency, clear} back the Price button on the Storages page, and varsto advice and /api/advice include the storages and per-folder costs.

Placement. In this release Varsto wrote every block to every storage, so the placement change it could carry out was freeing idle files on this device (section 23 adds per-folder placement and moving blocks between storages): a suggestion free-idle:<folder> lists a folder's files that have not been used for the idle threshold (default 90 days), are on this device and are not pinned, with the storages that keep them (cheapest first by the price model), what that costs per month, what reading them back would cost, and the disk space it frees. The storage bill does not change and the confirmation says so. varsto advice apply <id> (asks for confirmation unless --yes), POST /api/advice/apply {id, idle_days} and the button on the suggestion in the interface carry it out: the folder is pushed first, then a file's local copy is replaced by a placeholder only when every block has a copy on a storage this device reads without confirmation (cold storages and transferrers do not count), the folder's copy rules (min_copies, per place) still hold for the file from the ledger, and the file on disk is the synced version (free_file). A block whose readable copies nobody has verified yet is downloaded and hash-checked first and the check is recorded. Files that cannot go stay and are listed with the reason.

Not done. Moving data between storages came in 0.0.1-alpha.9 (section 23). Prices are per device and not synced. The built-in data covers two providers and one region each; rclone remotes, directories and pools have no built-in price.

The storages of the vault, on every device; the same storage twice. Credentials are per device and never shared, but the storages' names and identities are: a device publishes its names (vault/storage-names) when it adds a storage (not only when a verification or a drain happens to run), so every device can list every storage of the vault. Engine::storage_directory, varsto storage list and GET /api/storage/known show the storages configured here and, merged by identity whatever each device calls them, the ones only other devices have as "known from another device, not configured here: add its credentials here" (the interface offers "Add credentials" with the name filled in). Both directions work the same: a storage added on the phone shows on the computer and one added on the computer shows on the phone. Adding a storage is refused when it is the same place as one already in the vault: by location where the two can be compared without reading anything (StorageSpec::location_key: S3 by endpoint host, bucket and prefix with scheme, default port, case and slashes ignored; rclone by remote and path, an alias remote followed through rclone config dump, which is read only for each remote's type and an alias's remote, never a token; a directory by its path) and, once the new storage is opened, by its identity (vault/storage-id.json, first writer wins), against the storages configured here and the identities other devices published. The message names the existing storage ("this is the same bucket as 'macbook-s3', already in your vault: use that one, or add its credentials here under the same name 'macbook-s3'"); adding the other device's storage under that device's own name is how its credentials are given here and is allowed. Two entries of one vault with the same identity or location (made before this check) get a warning in storage list and the interface.

21. Removing a device: revocation, key epochs and remote wipe (0.0.1-alpha.8)

Superseded by section 77 (storage format 3): epoch records are signed records (no bare or unsigned epoch record), and folder keys come from grants and folder epochs, not from the vault epoch (77.1, 77.6, 77.20). What a removed device can still read in format 3, and which folders are re-keyed by whom, is in 77.20 ("Device removal"). Kept as the history of format 2.

varsto device revoke <name|id> [--wipe], or "Remove device…" under Devices on the Peers page, removes a lost or stolen full device from the vault from any other full device. It implements section 6 of key-hierarchy.md for this format, with the differences listed at the end.

Why a new vault key. Every full device holds the vault key, and the ledger, registry, folder-record and peer-authentication keys are derived from it; folder keys are published under it. Taking a device out therefore needs a vault key the removed device never sees. The vault key now has epochs: epoch 0 is the key the vault was created with (the one in the recovery kit of that time), and each revocation starts the next epoch with a new random key.

Objects (new, under vault/):

Object Content Protection
vault/kem/<device>.json the device's hybrid KEM public key (X25519 + ML-KEM-768, the construction of section 11), published by every full device with its records and on its first sync signed by the device key; checked against the device record
vault/revocations/<device>/<issuer>.json the removed device and its name, the issuer, the time, the ledger cut-off (the removed device's newest batch the issuer held), the wipe flag and the new epoch body encrypted under the epoch-0 registry key, so every device that ever belonged to the vault, the removed one included, can read it; signed by the issuer over the vault, both device ids, the key epoch and the ciphertext hash
vault/epochs/<epoch>.enc the previous vault key, the issuer, the time, the full devices that stay, the removed device, the folders that keep their key XChaCha20-Poly1305 under derive(K_epoch, "epoch-record"), associated data vault and epoch: only holders of the new key can read or write it, and the chain of previous keys lets the current key open every older epoch
vault/grants/<epoch>/<device>/<issuer>.json the epoch's vault key, sealed to one device hybrid KEM to the device's KEM key, AEAD with vault, epoch, device and issuer as associated data, signed by the issuer

On the device, vault-keys.enc (encrypted under a key derived from the device's own root key, like keyring.enc) holds the vault key of every epoch the device knows, its KEM private key, the member list of the newest epoch and the folders that keep their key.

Revoking (device A removes C). A pulls the registry and the ledger, then checks the guard rails: C is a current full device of the vault, it is not A itself (a device resets itself instead), it is not the last full device, and no newer epoch than A's exists on the storages. A writes the epoch record with put-if-absent (two devices rotating at the same instant through the same first storage collide there and the second gives up), writes the signed revocation, adopts the new key and seals it to every remaining device that has published a KEM record. A device that has not (it has not run this version yet) is listed as pending; any device of the new epoch seals the key to it on its first sync after it publishes one.

On every pull a full device, before it ingests ledger batches: publishes its KEM record where it is missing; looks for key epoch numbers held by two different signed records (below); reads revocations and accepts those that verify against a trusted device and whose key epoch backs them (section 58: vault/epochs/<new_epoch> is a signed record of the revocation's issuer that, once the device holds that epoch's key, names the revoked device; the revoked device itself checks the issuer's signed envelope, as it never gets the key), in the order of their key epochs (new_epoch, issuer), so a device revoked in an earlier epoch cannot revoke anyone later; adopts key epochs one at a time from the lowest above its own, each one whose grant is signed by a trusted device, opens with its KEM key, has a chain of epoch records that leads back to the key the device holds, and whose member list names the device, applying the revocations it backs before the next is considered; and seals the current key to members that lack a valid grant. The revocation's issued_utc is shown, never used for ordering. "Trusted" means a known full device that is not revoked and that the newest epoch kept, or whose device record opens only under the current key (it joined later).

Effects:

  • Ledger. Batches of the removed device with a sequence number above the cut-off are not ingested, and are left out of the ledger view if they were stored before the revocation arrived. Its manifests count only up to the last one its accepted batches announced, so files it writes afterwards never reach other devices. New batches are sealed under the newest epoch's ledger key with key id ledger@<epoch> (epoch 0 keeps ledger).
  • Registry. Device, folder, policy and rendezvous records are written under the newest epoch's keys and read with the key of any epoch. A device record that opens only under an older key, of a device the newest epoch does not list, is not trusted: a device enrolled with an out-of-date vault key (the removed device joining again under another name, or someone with an old recovery kit) cannot sign revocations, grants or ledger batches that others accept. join with an out-of-date key is refused outright, with a message that asks for the current key.
  • Peers. Revoked devices are dropped from the peer list: their rendezvous records and LAN beacons are ignored, so the QUIC server stops accepting their certificate; the request handler refuses tokens that name them; and the peer authentication key is derived from the newest epoch, so the removed device cannot make a valid token for a device that has adopted it. A device re-seals its rendezvous record under the new registry key when it adopts an epoch, so its addresses stop being readable to the removed device at once.
  • Folders. The folder key of epoch e >= 1 is derive(K_e, "folder-epoch", vault, folder). New chunks, manifests and thumbnails use the newest epoch; a chunk reference in a manifest records its epoch (epoch, omitted when 0, so older manifests are unchanged), and manifests and thumbnails are opened with the newest metadata key that fits. The keyed-hash key stays that of epoch 0, so chunk ids and content hashes do not change: a file that did not change keeps its objects and is not uploaded again, and deduplication and merging work across epochs. A chunk the folder already references keeps its object even inside an edited file. Folders shared with other people and Strongroom folders are frozen: they keep writing under their epoch-0 key (or a shared folder's newest share epoch, section 24), because members of a shared folder hold only the keys they were given and a Strongroom key never comes from the vault key. Sharing a folder that was re-keyed works since 0.0.1-alpha.9: the folder first gets a share epoch, and the token carries its vault-epoch folder keys so the member reads the older data.
  • The removed device. When it next reaches a storage it finds its revocation, writes removed.json and from then on refuses to sync, pull, push or sign (the error is DeviceRemoved; the interface shows who removed it and when). It never receives the new key.
  • Exporting the key. Pairing and varsto recovery kit use the newest epoch's key, which opens the older epochs through the epoch records. Print a new recovery kit after a revocation: the old kit holds the old key, which join refuses.

Remote wipe. With --wipe the revocation carries a wipe order. The removed device carries it out only when the revocation verifies against a trusted device of the vault that it knows; a forged order (signed by a key the registry does not know, a known device id with another key's signature, or garbage) is ignored, so the storage provider cannot trigger it. Anyone who holds the vault key can: with it a device joins the vault (section 8), becomes a trusted full device, and may sign a revocation with a wipe order like any other full device (see Limits: there is no vault identity key or second factor). The device then:

  1. empties every attached folder root: every file, synced or not, with links removed and never followed; the root directory itself stays. A root that is the file system root, the user's home directory or a directory that contains the device directory is too wide to empty blindly: there only the files the folder state names (and their placeholders) are removed;
  2. removes from its device directory the keys, keyring, storage secrets, vault keys, ledger, sync state, trash, configuration, MCP grants, disk pool indexes, peer certificate and service log;
  3. writes wiped.json (who removed it and when, nothing secret); the service drops the vault and the interface shows the setup screen with that notice.

Nothing outside the folder roots and the device directory is touched, and the storages are left alone. Changes that exist only on the wiped device are lost: that is the point of wiping a device that is gone. Revoke without --wipe when it might come back.

What a removed device can still read. Everything it could read before: a key cannot be recalled, and every key it held still opens what it protected. In detail: all content, names and ledger entries written before the revocation; whatever other devices write before they adopt the new key (until each one's next sync); everything in frozen folders, including what is added to them later; rendezvous records until they are re-sealed; replica batches (the replica key stays derived from epoch 0, so replicas keep working, but the removed device can still read replica claims, which name objects, and could publish claims as a fake replica); and it can still recognise the vault's pool disks and LAN beacons (pool ids and the beacon tag also stay derived from epoch 0). It cannot read new ledger batches, device, folder, policy and rendezvous records, manifests, thumbnails or chunks of re-keyed folders, and it cannot authenticate to peers that have adopted the new key.

Limits.

  • Storage credentials are not rotated: the removed device can still list, read (ciphertext only) and delete objects on the storages until the credentials are changed at the provider. Varsto cannot do that for you.
  • There is no vault identity key (K5) and no second factor yet: any full device that is not revoked can revoke any other. A thief with an unlocked device who acts first can remove your other devices. Revocations are applied in the order of the key epochs they started, which put-if-absent on the storages decides; a backdated revocation written after another device removed its issuer does not win (section 58).
  • The wipe order travels through the storages only, not through peers, and runs only when the device runs Varsto again and reaches a storage. It does not reach copies made earlier, removable disks, backups or files opened in other apps.
  • Two devices revoking at the same instant through different first storages can each create an epoch with the same number. A device that sees both records them in epoch-fork.json (ledger health epoch_fork), applies neither epoch's revocations, adopts neither key and signs nothing until the user keeps one with varsto device resolve-epoch <n> --keep <device> (the kept device must be trusted; a device that already adopted the other record's key cannot switch and is paired again). A device that saw only one of them acted on it.
  • A device enrolled while the revocation was being issued, which the revoking device had not seen, is not in the new member list and has to be paired again.
  • Every remaining device must run 0.0.1-alpha.8 or later: older versions neither publish a KEM key nor understand epoch keys.
  • Existing data is not re-encrypted. Re-encrypting a folder under new keys (so that even a copy of the old keys and the storage reveals nothing) is a separate, expensive action that does not exist yet.

Differences from the key hierarchy draft: no K5 (membership statements are signed by device keys); the rotated key is the vault key K3 rather than per-folder K9 epochs wrapped to K8 keys; chunk keys are convergent (section 3), so they are not re-wrapped and only new chunks use the new keys; storage credentials are not rotated.

Tests: crates/varsto-core/tests/revocation.rs (three devices: A removes C, A and B keep syncing, C's later batches and manifest are ignored, nothing written afterwards opens with C's keys, a new device joins with the current key and is refused with the old one; a wipe order empties C's folder and device directory; forged wipe orders are ignored), unit tests in engine/membership.rs (revocation and grant signatures) and p2p.rs (a revoked device's token is refused).

22. Ledger upkeep: checkpoints and pruning (0.0.1-alpha.8)

Superseded by section 77 (storage format 3): checkpoints are SignedRecords over the pack-level view (77.4). Kept as the history of format 2.

Every sync, fetch, verification run or disk check used to add a batch of about 8 KB (mostly the hybrid signature) that every device kept forever, on every metadata storage and locally, and every pull listed the whole ledger/ prefix while every read of the view replayed every batch. Section 6 now describes the incremental mailbox, the cached view and one batch per action; this section adds checkpoints, acknowledgements and pruning, which bound what is stored.

Measured with 20 000 synthetic batches of three devices on one local directory (cargo test --release -p varsto-core ledger_scale_benchmark -- --ignored --nocapture): a pull with nothing new went from 20 004 listed keys and 668 ms to 3 empty listings and 65 ms; the view from 434 ms (replay) to 37 ms; after checkpoints and pruning the storage holds 29 objects and 5.2 MB instead of 20 003 objects and 171 MB, and a device that joins reads three checkpoints and a few batches (0.5 s) instead of ingesting every batch (35 to 57 s).

Acknowledgements. A batch body has a new field seen (omitted when empty): the newest batch of every other device that the writer held when it sealed the batch. The view keeps, per device, the highest value it acknowledged for each other device (acks, merged by maximum). After a sync a device that holds a checkpoint of another device newer than what it last acknowledged seals a batch, empty if nothing else is pending, so others learn it.

Checkpoints. ledger/<device>/checkpoint-<seq 16 digits>.json, written by the device itself:

Field Content
format_version, sig_alg, key_id as in a batch; key_id is ledger or ledger@<epoch>, the current epoch's ledger key
device, seq the checkpoint covers batches 1..=seq of this device
head_hash hash of batch seq; batch seq + 1 names it as prev
body_hex XChaCha20-Poly1305 under the ledger key, associated data device, seq, head_hash, of zstd-compressed JSON {device, seq, head_hash, created_utc, view}
hash, sig_hex BLAKE3 of the ciphertext; signature over device || seq || head_hash || hash (domain ledger-checkpoint-signature, distinct from batches)

view is the location view that the device's own batches 1..=seq produce on their own (readers keep only what the signer itself said, see Reading), before retirements and replica claims are folded in: chunk records with the stamps that decide object names and sizes, manifest sequence numbers, the device name, folders, retirements, acknowledgements, the number of batches and the largest Lamport time. Because applying batches is order-independent (section 6), merging this view gives exactly what replaying those batches gives.

A full device writes a checkpoint after a sync when its own batches since the last checkpoint reach at least 256 and at least the size of the last checkpoint divided by 8 KiB, so checkpoints cost at most about as much as the batches they replace (a device with 6 667 batches of synthetic claims wrote a checkpoint of 0.83 MB). It is pushed with the batches to every metadata storage, cold ones included. Members of shared folders and replicas write none.

Reading. A pull also sees the checkpoints of each device (their names sort after every batch name, so a listing after the local head always includes them). Checkpoints are read only from trusted full devices (or removed ones, within their cut-off): never from replicas or members, which write none. The newest one within the device's revocation cut-off is fetched when it is newer than the one held; it is kept when its signature verifies against the device record, it opens, it agrees with the batch held at seq if any (otherwise the device is marked forked), and it lies at most 65 536 beyond the newest batch held of the device, like a batch, unless the storage also holds the batch it ends at, signed by the device with the hash the checkpoint names (a device that joins long after the others pruned). A checkpoint speaks for its signer only: when it is merged, every claim, verification, block held, manifest, name, snapshot and acknowledgement it attributes to another device is left out (section 58); retirements, drops, folders, stopped backups and the expiry of other devices' snapshots stay, since a full device may make those. Batches it covers are then neither downloaded nor kept. The view of each device's contribution starts from its newest checkpoint whose key this device holds and that lies within the cut-off, and applies only the batches after it; batch seq + 1 is chained to head_hash. A new checkpoint as starting point rebuilds the cached view (from the checkpoints, which is fast).

Pruning. The readers are the full devices of the vault that are trusted and not revoked (section 21). Members of shared folders and replicas do not read the vault ledger and are not asked. When every reader other than the device itself has acknowledged at least seq of its newest checkpoint:

  • the device deletes, on every hot metadata storage that holds that checkpoint, its own batches up to seq - 8 and its older checkpoints, and drops its local copies of them; the last 8 batches before the checkpoint and everything after it stay;
  • every device drops its local copies of another device's batches up to that device's newest checkpoint once the same condition holds for it.

Cold storages are never pruned (early deletion is billed and saves nothing there). Progress per storage is kept in ledger/pushed.json. A storage that lost the batches, or a new storage, receives the checkpoint and the batches after the pruned range.

Fork detection. A copy of a device restored from a backup older than the checkpoint still finds batches or a checkpoint of its own identity after its own head, fences itself and refuses to sign or push (test checkpoints_prune_after_everyone_has_seen_them). Observers detect a checkpoint that contradicts a batch they hold, two checkpoints at the same sequence number with different head_hash, and a batch after the checkpoint that does not chain to it.

Compatibility. Versions before this one read only the numeric names under ledger/<device>/ and skip the checkpoint names, and they ignore the seen field (unknown fields are ignored). They never acknowledge, so nothing is pruned while a full device of an older version is in the vault: they keep reading every batch. New fields in local files (base and dropped in the heads file, pruned in pushed.json) have defaults.

Limits.

  • A full device that never syncs again (lost, reset without being removed) blocks pruning of every other device's batches until it is revoked.
  • Members of shared folders and replicas keep all their batches. Folder manifests are listed incrementally and pruned since section 25.
  • A checkpoint under a key epoch this device has not adopted yet is downloaded again on every pull until it has.
  • Each pruned batch is one delete request; the first checkpoint of a device with a long history decrypts all its batches once.
  • varsto ledger and /api/ledger list only the batches still held locally.
  • If a revocation's cut-off lies below the newest checkpoint a device holds of the revoked device, that checkpoint is not used and the batches up to the cut-off are used where they are still held. Local copies are dropped only after every reader acknowledged the checkpoint, so a cut-off set by a reader cannot lie below it; a cut-off taken by a device that had not seen the checkpoint (it was offline) leaves out the revoked device's claims it no longer holds: copies count less, never more.
  • What a checkpoint means for signatures and audits is in ledger-signing-notes.md, section 9.

Tests: ledger::tests::checkpoint_stands_in_for_its_batches, ledger::tests::cached_view_equals_full_replay (random arrival orders, unknown keys, cut-offs, checkpoints, save round trips), engine::ledger_upkeep::tests (mailbox_reads_only_what_is_new, push_refills_a_storage_that_lost_batches, restored_copy_is_fenced_by_incremental_listing, cached_view_survives_restarts, sync_seals_one_batch, fetch_is_sealed_with_the_next_batch, one_batch_seals_on_failure, checkpoints_prune_after_everyone_has_seen_them, and the ignored ledger_scale_benchmark).

23. Data placement: per-folder placement, moving data and disk groups (0.0.1-alpha.9)

Until this release every block went to every storage of the device that wrote it. A folder can now name where it is written, blocks can be moved from one storage to another (so that idle data costs less), and a disk pool can keep copies on disks in different places.

Dropping a copy: chunk_dropped. A new ledger event {type: "chunk_dropped", folder, chunk, object, storage} records that the device removed the object from the storage on purpose. The view keeps, per chunk record, the newest drop per storage (dropped: storage -> Lamport time, merged by maximum) and, per copy, the newest claim alone (claimed_lamport, merged by maximum; lamport stays the newest claim or verification). Once every batch is applied, a copy on a storage with a drop counts only if its newest claim is later than the drop (Lamport time; on a tie the drop wins). A verification made after a drop does not bring the copy back: it may have read the object just before it was deleted. A claim made later (a new upload, or a move back) counts again. A copy whose claim predates this release has no claimed_lamport and is compared by lamport. Like retirements, drops are applied after all batches, so the result does not depend on arrival order; the cached view (ledger/view.enc, format 3, rebuilt once from the batches after an update) and checkpoints carry dropped and claimed_lamport, so a reader that starts from a checkpoint sees the drops its batches held. The finished view keeps dropped, so writers know that a block was moved away from a storage (ChunkRecord::dropped_from).

Per-folder placement. A folder record has an optional placement with storages (names), storage_ids (name -> storage identity, vault/storage-id.json, section 20) and places; none, or an empty one, means every storage. It is published like a policy, append-only, at vault/placement/<folder>/<device>/<updated_utc 20 digits>.enc (XChaCha20-Poly1305 under the folder-record key, associated data placement-record, vault id and folder id, JSON {folder_id, device, updated_utc, placement}), and every device adopts the newest one it can read. A device writes a folder's blocks to the storages the placement names: by name, by place, or by identity when it names a storage differently than the device that set the placement (two devices calling one bucket "box" and "primary" write the same way). When none of the named storages or places exists on a device it writes to every storage rather than nowhere, and placement says so. Transferrers keep their own rules. Records, ledger batches, manifests and thumbnails still go to every storage. Placement decides only where pushes and disk fills write: blocks already stored stay until they are moved, policies still count every copy the ledger records, and a block that was moved away from a storage is not written back to it by a later push while another copy exists (a block whose only copies are gone is written again anywhere the placement allows).

Setting a placement checks that every named storage is configured here (and is not a transferrer) and that every named place has a storage here. varsto folder placement <folder> shows it and the storages it means on this device; --storage X (repeatable), --place P (repeatable) set it; --every clears it. API: GET /api/placement (every folder, with the storages), POST /api/placement {folder, storages, places, every}. The interface shows it in a "Written to" column of the policy table, with a Change button (and a Placement button on phones).

Moving data. Engine::move_data (varsto move <folder> --from A --to B [--idle-days N] [--dry-run] [--confirm-cold-read] [--yes], POST /api/data/move {folder, from, to, idle_days, dry_run, confirm_cold_read}) moves a folder's blocks, or with idle_days only those of files not used for that many days and that no other current file uses, from storage A to storage B. The device first pulls the ledger, then plans from it:

  1. a block is a candidate when the ledger records a claim on A; a block already recorded as dropped from A counts as moved;
  2. it stays on A when the copies left afterwards (every storage with a claim except A and transferrers, plus B) would break the folder's copy rules (min_copies, min_per_place), and when the only readable copy is on a cold A and the cold read is not confirmed (copies on this device and on other hot storages need no cold read);
  3. the plan reports blocks and bytes, the fewest copies any block keeps and where, the monthly cost of the bytes leaving A and arriving on B and the difference (from the price model of section 20, per currency, never converted; storages without a price are listed), reading the blocks this device lacks from A once, what A still bills for its minimum storage duration, and for a cold B what reading back needs and costs.

With --dry-run that is all. Otherwise blocks are moved in groups of 64: each block is written to B unless B already has it (re-encrypted from the files on this device, each file read once and its access time put back so idle files stay idle; else from the block cache, another hot storage, or A itself when A may be read), then checked on B (read back and hash-checked; on a cold B without a confirmed cold read only its presence is checked), then chunk_stored and (when read back) chunk_verified for B and chunk_dropped for A are recorded. The group's events are sealed into a batch and pushed before anything is deleted from A; then the objects are deleted from A, except an object another ledger record still claims there. A move that is interrupted is carried on by running it again: blocks already on B are not copied again, and blocks recorded as dropped that are still on A (the batch was pushed but the delete did not happen) are deleted (leftovers_removed). A move never deletes a copy whose replacement was not written and checked, never one the copy rules need, and never the last one. Moving a whole folder (no idle_days) also changes its placement, once no block was kept, to the storages it was written to with A replaced by B, so new blocks go to B too; moving idle files leaves the placement alone, and a file that changes later is written to the hot storages again. The CLI asks for confirmation with the plan's summary unless --yes and exits with code 1 when blocks were kept.

Cold storage. A cold storage is still never read without an explicit confirmation. Blocks moved to cold storage are not read by pulls; a device that does not hold such a file sees it as unavailable until the blocks are moved back (varsto move <folder> --from <cold> --to <hot> --confirm-cold-read; without the confirmation they come from this device's files when it has them). Writing to cold storage needs no read; checking a copy there by content does.

The suggestion. Besides free-idle:<folder>, the placement advice (section 20) now offers cold-idle:<folder> when a move lowers the bill: for each hot storage with a storage price and each cold storage with a lower one in the same currency, it plans the idle-files move (idle_days of the advice) and suggests the one that saves most per month, if any saves anything. The suggestion carries kind (free-idle or cold-idle), move_from, move_to, monthly_saving, one_time_cost, the plan's summary (copies afterwards, the change in the bill, cold-read notes) and the blocks that would stay. varsto advice apply cold-idle:<folder> (asks unless --yes), POST /api/advice/apply {id} and the "Move to X" button (with a confirmation that states the same) carry it out; the report has moved with the move's report.

Disk groups. A disk of a pool has a place (place in the disk registry and in the disk's own index.json; empty means the pool's place), set with varsto disk add ... --place P, varsto disk place <label> <place> or POST /api/disk/place {label, place}. A pool has a rule copies (default 1, omitted when 1): keep that many copies of every object on disks in different places (varsto storage add-pool <name> --copies N, varsto disk group <pool> --copies N, POST /api/disk/group {pool, copies}; varsto disk group and GET /api/disk/groups show every pool's rule, its places with their disks, the objects short of the rule and why the rule cannot be met as configured). The pool index keeps, per object, the first disk and extra disks holding further copies (older versions ignore extra and know the first copy only). A put writes the first copy as before and further copies to attached disks of other places that have room; disk add and disk check fill a disk with every object the pool lacks or holds in fewer places than copies and not yet in the disk's place (copies come from the pool's other attached disks, other hot storages or local files); a read uses any attached disk with a copy; a delete removes every copy (queued for disks that are away); a check that finds a bad or missing copy forgets that copy only. The ledger still records one claim per pool. Policies count one copy per disk holding the object, at the disk's place, so "one copy at home and one offsite" can be met by one pool; a folder with a policy whose blocks on a pool with copies > 1 are held in fewer places gets a violation ("N chunks have fewer than K copies on disks of pool P in different places"), and disk check reports group_copies and group_short. The interface shows each disk's place, a Place button per disk, the rule of each pool with a Disk group button, a Place field when adding a disk and a copies field when adding a pool. With placement, a folder can be kept on disks only (varsto folder placement <folder> --storage <pool>), as many times as the rule says.

Compatibility. Devices of 0.0.1-alpha.8 and earlier cannot decode a batch that holds chunk_dropped: their ingest fails and so does their pull, from the first move on. Update every device before moving data. This version reads unknown event types as unknown and ignores them, so later event types will not break it. Older versions also ignore dropped and claimed_lamport in checkpoints, placement records (they write every folder to every storage) and the extra disks of a pool index. Storage format version stays 1: objects, records and batch envelopes are unchanged.

Limits.

  • Storage names in the ledger are the writer's names; a drop recorded under one device's name for a storage applies to the claims made under that name (as retirements do).
  • A device that wrote a block to A without having seen a drop, with a later Lamport time than the drop, may record a claim on A for an object the move deleted just after; the copy then counts until verification reports it missing.
  • A file whose blocks are only on cold storage cannot be fetched or opened until they are moved back; pulls do not ask for a cold read.
  • Varsto's own reads of a file at scan and upload still update its access time, so a file reads as used right after it changed or was uploaded to a new storage.
  • The ledger records one claim per pool; which disks hold copies is in the pool index of each device (adopted from the disks' own indexes).
  • Strongroom conversion re-encrypts into every storage; the new folder keeps the placement for later writes.
  • Moves are not scheduled by the service; the suggestion and varsto move are the ways to run one. Moves to a disk pool that go on over several disks, with the service continuing them, are move jobs (section 59).

Tests: crates/varsto-core/tests/placement.rs (a_drop_removes_earlier_claims_and_later_claims_count_again with the cached view and a checkpoint, unknown_event_types_are_read_and_ignored, placement_writes_only_to_the_chosen_storages_on_every_device with two devices that name storages differently, moving_keeps_the_policy_and_lowers_the_bill with the cold-storage suggestion and a second device, moving_a_whole_folder_changes_its_placement_and_never_drops_the_last_copy, a_pack_that_cannot_be_deleted_is_collected_later, disk_groups_keep_copies_in_different_places), and ledger::tests::cached_view_equals_full_replay, whose random events now include drops.

The default placement writes the fewest storages that keep the policy. A folder without a placement of its own (and with a policy) is no longer written to every storage. A device writes every block to all its storages in the "home" place (directories, disks, pools: no recurring cost), and, of the other places, to as many storages as the policy asks for: min_per_place for each place, then more until min_copies is met (the default policy asks for one "cloud" copy, so one S3 bucket or rclone remote of the several a device has). Among the candidates it prefers a storage that already holds the folder's blocks, then a warm one over a cold one, then the cheaper (price per GB-month, unknown last), then the name. A block that already has the external copies the policy asks for (another device wrote it, under whatever name) is not written to one more. A policy that asks for two external copies writes two; a folder without any policy (cleared by hand) and a folder with an explicit placement behave as before (every storage, or exactly the placement). The transferrer and trash rules are unchanged. varsto folder placement and the interface show the storages the folder is written to on this device.

24. Shared folders: confirming the requester, removing members, share epochs (0.0.1-alpha.9)

Superseded by section 77 (storage format 3): no share token travels (vst1, vst2 and plain tokens, share keys and SHARE_EPOCH_BASE are gone): an owner writes a folder record and a grant to the requester's K8 (77.6, 77.20). Kept as the history of format 2.

Code: crates/varsto-core/src/share.rs (objects, fingerprint) and engine/share_ops.rs.

Fingerprint. A request code is vsr1.<X25519 key || ML-KEM-768 key, hex>[.<name>]; varsto share request --name <name> (or the device name in the interface) binds a name. Both sides derive six BIP-39 English words from it: derive_key("varsto share-request fingerprint v1", len-prefixed(public key, trimmed name)) (this context string is deliberately outside the e2ee-sync-format/0 family, so it does not change with the format version), the top 66 bits, 11 per word. The derivation does not depend on the format version, so two users on different versions see the same words. The recipient sees them next to its code; the owner sees them for the code it received (share create --to <code> asks "Do the six words match exactly?", --fingerprint "<words>" or --yes answer it; the interface shows the words and asks before sealing; POST /api/share/fingerprint {code}). The two compare them over another channel (a call, in person). A changed key or name gives other words. 66 bits make a second preimage (a code of the attacker's with the victim's words) cost about 2^66 key generations.

Version-2 tokens. vst2.<vault>.<folder>.<kem-alg>.<kem-ct>.<sealed>.<name> has the fields of vst1, but the sealed part is a JSON payload {key_hex, epoch_keys, fingerprint, owners} under associated data (share-token-v2, vault, folder, name, kem ciphertext): the folder key, the folder keys of later epochs (a folder re-keyed with the vault key, share epochs), the fingerprint the owner confirmed and the owner's device ids. The recipient's device refuses a token whose confirmed fingerprint is not its own request's (the code was changed on the way and the owner did not notice). A token without these extras is still sealed as vst1, which older versions read. A plain token (<vault>.<folder>.<key>.<name>) cannot carry later keys and is refused once a folder has them.

Tokens and members on record. Every token the owner issues is recorded at vault/share-invites/<folder>/<invite>.enc under the folder-record key (owner devices only): invite id (hex(BLAKE3(request key))[..32], or plain-<random>), the request key, the bound name, the fingerprint, issuer and time. Owner devices that see an invitation for a folder mark it shared. A member keeps its request key as its key-exchange key and publishes it at vault/share-kem/<folder>/<device>.json (the KEM record of section 21, signed by the member's device key); the owner ties a member to the token it accepted by that key. varsto share members <folder> and GET /api/share/members?folder= list the owner's devices, members (active or removed, with the fingerprint the owner confirmed) and tokens not accepted yet (pending or revoked). The Shared page lists the same under each shared folder.

Share epochs. varsto share revoke <folder> <member|invite id|fingerprint|all> --yes, POST /api/share/revoke {folder, member, confirm: true} and Remove…/Revoke… on the Shared page start a share epoch:

Object Content Protection
vault/share-epochs/<folder>/<epoch, 10 digits>.enc folder, epoch, issuer, time, older (every earlier folder key except epoch 0: earlier share epochs and vault-epoch folder keys), participants (owner devices and members that stay), owners, removed (device, name, ledger cut-off), revoked_invites, kept_invites XChaCha20-Poly1305 under derive(K_e, "share-epoch-record", folder), associated data vault, folder, epoch: only holders of the new key read it
vault/share-keys/<folder>/<epoch>.enc the new folder key K_e the vault's folder-record key (owner devices of every later vault epoch)
vault/share-grants/<folder>/<epoch>/<recipient>/<issuer>.json K_e for one member (<device>) or one open token (inv-<invite id>) hybrid KEM to the member's key or the token's request key; AEAD with vault, folder, epoch, recipient and issuer as associated data; signed by the issuing owner device
vault/share-members/<folder>/<epoch>/<device>.enc a participant's device record derive(K_e, "share-registry", folder)

Share epoch numbers start at 2^20 (SHARE_EPOCH_BASE) so they never meet vault epochs in a chunk reference. K_e is random. A folder writes under its newest share epoch: chunks (chunk-key, chunk-nonce from K_e, convergent within the epoch), manifests and thumbnails (folder-metadata), access records, member ledger batches (derive(K_e, "share-ledger", folder), key id share:<folder>@<epoch>), member records. The keyed-hash key stays that of epoch 0, so chunk ids and content hashes, deduplication and merging do not change; a chunk the folder already references keeps its object and epoch.

The owner device that revokes: pulls the ledger (the cut-off of a removed member is the newest batch of it held there); writes the epoch record at the first epoch number whose record and key paths are free on the first storage (another owner device may have taken one at the same moment, and anyone who can write to the storage can occupy a name), then the key record; adopts the epoch; seals the key to every participant member that has published a key-exchange key and to every token still open; republishes its records under the new key. Every owner device, on each sync, adopts share keys it lacks, applies their epoch records, and seals its own grant to participants that still lack one (a member running an older version gets it once it publishes a key). A member adopts an epoch whose grant to it (or to its token) opens and is signed by one of the owner's devices: the token names them, and each adopted epoch record updates the list. A member that joined before tokens named the owner's devices accepts a grant from any participant whose record it holds.

Effects, on owner devices and on the members that stay:

  • Ledger. The removed member is entered as revoked with its cut-off (devices.json), exactly like a revoked device (section 21): its batches after the cut-off are not ingested or counted, and its manifests count only up to the last one its accepted batches announced. Its new batches are sealed under the old key anyway, which the others still hold.
  • Member records. Once a folder has a share epoch, a member record that opens only under an older key is accepted only for a device the newest epoch kept, an owner device, a removed member (for its batches before the cut-off) or a device already known; its device id must be the hash of its key. A removed member therefore cannot come back as a new device with the key it kept; manifests of a shared folder with a share epoch are read only from known devices.
  • The removed member keeps everything it could read: a key cannot be recalled. It sees that a newer epoch exists and that no grant reaches it (access_lost, shown by share members and the Shared page); since section 58 a newer epoch counts only when an owner device signed a grant of it to some participant, so a name planted under share-epochs/ does not cut a member off or hide its errors. Its sync no longer fails on manifests it cannot open, and it receives nothing written under the new key. It is not told who removed it.
  • A revoked token opens as before but brings nothing written after the revocation; a device that accepts it is not a participant, so it is ignored as above. Tokens still open get the new key through the grant addressed to their request key, so revoking one token does not break another.
  • Sharing again works: the token carries every later key, and the new member's record is written under the newest key.
  • Sharing a folder re-keyed with the vault key starts a share epoch first (nobody removed), so the token's keys and everything written from then on stay away from the device the vault revocation removed.

Why not random per-chunk keys. The key hierarchy proposed random chunk keys (K14) wrapped under the folder key, so that a removal re-wraps keys instead of re-encrypting data. They were not adopted: chunk objects must stay byte-identical across devices for offline deduplication and for peers that re-encrypt a piece from plaintext on request (section 15), and storing a key per chunk in every manifest would make manifests much larger. Within one share epoch keys stay convergent; across epochs a random folder key gives what matters after a removal: nothing written afterwards opens with what the removed member holds, and it cannot even tell whether new chunks match content it knows, since chunk keys and nonces now come from a key it lacks. What a removal does not do (and random chunk keys would not have done without re-encryption either): existing data stays under the old keys, so the removed member keeps reading what it had; it still knows the epoch-0 keyed-hash key and can recognise chunk ids of content it knows in a manifest or ledger batch it can open, which are all old ones.

Limits. The storage stays shared: a removed member can still list, read (ciphertext) and delete objects, or occupy object names, until its access to the storage is taken away; storage credentials are the user's. Revocations by two owner devices at the same moment produce two epochs, both applied. A member that did not publish a key-exchange key (an older version) gets the new key only after it does. A device of the owner removed from the vault (section 21) keeps the share keys it already held, as before; a share epoch started afterwards is out of its reach. The removed member is not notified explicitly. Tests: crates/varsto-core/tests/sharing.rs (fingerprint on both sides, a swapped name; three users and two owner devices: the removed member reads nothing new and its later changes and a new device of it are ignored, the remaining member and the owner's other device read on, sharing again; revoking a token not accepted while keeping another; removing everyone; sharing a re-keyed folder; access records merged across devices), share::tests, and tests/strongroom.rs (rekeying_a_strongroom_re_encrypts_it_under_a_new_key_for_every_enrolled_key).

25. Manifest listing and pruning (0.0.1-alpha.9)

Superseded by section 77 (storage format 3): a pull reads the manifest records the ledger announced and never lists a folder in full; pruning waits for every reader (77.7, 77.18). Kept as the history of format 2.

Every push that changes a folder publishes a full manifest (section 7), and a pull used to list manifests/<folder>/ in full on every hot metadata storage, so a pull with nothing new cost one listing whose length grew with every manifest any device had ever published, and nothing was ever deleted.

Listing. Every manifest is announced in its writer's ledger batch (manifest_published, sealed in the same action as the upload), and a pull reads the ledger first. A pull of a folder therefore lists only the devices whose newest announced manifest of the folder (the manifests map of the location view, which for a revoked device counts only batches within its cut-off) is newer than the one this device has applied (last_seen in the folder state), and for each only the keys after that one: list_after("manifests/<folder>/<device>/", "manifests/<folder>/<device>/<last seen 16 digits>.enc"). With nothing new, nothing is listed and nothing is read. The newest key found across storages is fetched, capped for a revoked device as before, and applied with the usual merge rules; conflicts and forks are handled exactly as with a full listing because the same manifest is chosen.

A full listing of the folder still runs on the first pull of a folder on a device, once every six hours per folder (state/manifests.json keeps the time), and always on members of shared folders, which do not read the vault ledger. It finds manifests whose announcement this device cannot read yet (a key epoch not adopted, an older device). A folder converted into a Strongroom has a new folder id, so its first pull is a full listing of the new prefix.

Pruning. A reader only ever applies the newest manifest of a device, or for a revoked device the newest one its accepted batches announced. After a sync a full device notes, per folder, its newest published manifest P with its own newest batch H (the batch that announced P is H or earlier; nothing is pending at that point). Let m be the largest noted P whose H every reader has acknowledged in the seen field of its batches (the readers and acknowledgements of section 22: trusted full devices that are not revoked). The device then deletes its own manifests of the folder below m on every hot metadata storage that holds manifest m; cold storages are never pruned. Progress per storage is kept in state/manifests.json, so each prune lists only the device's own keys from the last pruned one.

Why it is safe: every reader holds the batch announcing m, so it knows of m or newer and its next pull lists from its own last applied manifest, finding m or newer. A revocation cut-off taken by any reader lies at or above the batches it acknowledged, so the newest manifest within the cut-off is m or newer, and everything from m on is kept. A pull that listed a key just before its writer pruned it skips the missing object and finds the newer one on the next pull. Members of shared folders read only the newest manifest and are not waited for; they and replicas prune nothing of their own.

Measured with cargo test -p varsto-core --test manifests manifest_listing_benchmark -- --ignored --nocapture (three devices on one local directory, one of them publishing 300 versions of a folder; debug build): a sync with nothing new listed 310 manifest keys in one listing before (a full listing on every pull) and none after; a sync with one new manifest of another device lists one key and reads one manifest. With pruning, the 302 manifests of the busy device on the storage (208 KB of manifests in all) went down to its newest 2 (12.6 KB in all), so even the six-hourly full listing returns 6 keys instead of 310. Acknowledgements travel in the readers' next batches, so in a quiet vault pruning waits until the other devices write something.

Limits. A full device that never syncs again blocks pruning, as for the ledger, until it is revoked. Devices of older versions never acknowledge, so nothing is pruned while one is in the vault. A device whose announcement this device cannot read is found only by the six-hourly full listing. Manifests are still full views of a folder; incremental manifests are not built.

Tests: crates/varsto-core/tests/manifests.rs (pull_lists_only_new_manifests: nothing listed or read when nothing is new, one key and one read for one new manifest; pruning_waits_for_every_reader: a quiet device keeps the manifests it has not acknowledged, they go once it has, everyone converges and a device that joins later reads the few left), revocation.rs and strongroom.rs (cut-offs and conversions with incremental listing), unit test engine::manifest_upkeep::tests.

26. Automatic repair (0.0.1-alpha.9)

Verification (section 20) and fsck found damage and only reported it. They now also put each damaged copy in a repair queue, state/repair.json: one entry per (object, storage of this device) with the folder, chunk, kind (missing or corrupt), who found it and when. fsck queues objects that the ledger claims on a hot storage of this device that the listing lacks (claims made by this device, or blocks of current files, because storage names are local and another device's "box" may be another place), blocks of current files that no hot storage has at all (for every hot storage that takes every block), and with --verify objects whose hash does not match. Verification queues the missing and corrupt copies it finds, under the local name of the storage it read.

A repair run sorts the queue by the number of other copies the ledger knows (fewest first), then by age, and for each copy within the budget:

  1. It drops the entry when the storage is no longer configured here (a storage that is gone for good: removing a storage is its own action), when the storage is cold or a transferrer (repair never writes those; transferrers only take what another device lacks), when the copy was dropped from the storage on purpose (chunk_dropped, section 23, and no claim since) or the folder's placement does not take the storage (a data move is never undone), or when the folder is attached here and no current file uses the block any more.
  2. It reads the copy again. An intact copy (another device repaired it, a disk came back) is recorded as chunk_verified. A storage that cannot be reached, or a pool disk that is away, is tried again after an hour.
  3. It looks for the same ciphertext elsewhere and checks it against the object name: the encrypted block cache; the other hot storages of this device; this device's plain copy of a file that holds the block (only when the file on disk is the synced version), re-encrypted, which gives the very object because chunk encryption is deterministic (section 3); a peer (section 15). A cold storage is read only when the user confirmed it (varsto repair --from-cold, or the button in the interface, which warns about retrieval fees and delays).
  4. It deletes a corrupt copy, writes the object with put-if-absent, reads it back, checks the hash, and records chunk_stored for the storage in the ledger (one batch per run). Repair is the one exception to "objects are never overwritten", and only for a copy whose bytes do not match its own content-addressed name.

A copy for which nothing is found stays in the queue with the reason ("a copy is on cold storage deep; run varsto repair --from-cold", "the other copy is on a disk of pool shelf that is not attached", "no other copy can be read, and the Strongroom is locked", or "no intact copy anywhere this device can read") and is tried again a day later, when a peer may be online or a disk attached.

Where it runs. The background service runs the queue after every sync and after automatic verification, when something is due, with a budget of 500 blocks or 256 MiB per run; it never reads cold storage. Every copy that could not be repaired raises one desktop notification ("2 block copies could not be repaired: "); the same copy is not notified again while it stays unrepaired. varsto repair [--dry-run] [--from-cold] [--no-scan] [--max-mib N] [--max-blocks N] compares the ledger with the hot storages first (an fsck without downloads), then repairs everything queued, without a budget unless one is given; --dry-run says what would be rewritten from where and writes nothing; the exit code is 1 when a copy could not be repaired. varsto fsck --repair repairs what that fsck found. API: GET /api/repair (queue, last run, open losses), POST /api/repair {dry_run, from_cold, scan}, POST /api/fsck {verify, repair} (the report then carries repair); GET /api/service carries repair and a one-line repair_text ("automatic repair: last run …: 3 copies repaired, 1 could not be repaired: why"), which varsto service status prints. The interface shows it on the Policies page (Automatic repair: status, open losses, Check and repair now, Preview, Repair from cold storage when a loss needs it), verification and repair run on their own in the service; the interface has no manual check.

Limits. Only storages of this device are repaired; a copy on another device's storage that this device cannot reach is repaired by that device. Blocks of folders that are not attached here are repaired only from ciphertext (another storage, the cache or a peer), and without a current-file check, so a block of an old version may be rewritten. A peer is asked only when the service (or a command-line run with peer-to-peer enabled) knows peers. Disk pools are repaired through their attached disks; filling a replacement disk stays varsto disk add.

Tests: crates/varsto-core/tests/repair.rs (from another storage with a dry run first, a corrupt and a missing copy from the local file through fsck --verify and the service's run, damage found by verification on another device, from a peer over TCP, cold storage read only with from_cold and counted reads, an unrepairable loss reported once, transferrers never written, a block moved off a storage not written back).

27. Organizations: administrators, approvals, removing a person (0.0.1-alpha.10)

Code: crates/varsto-core/src/org.rs (objects, request codes, approval tokens) and engine/org_ops.rs. Plan 6.44, phase A; it realises the vault identity key K5 of key-hierarchy.md as an organization root key plus administrator device signatures.

Why. A vault has no people in it: only devices, and every full device is equal, so any device could remove any other (section 21) and anyone holding the vault key belonged. A company needs someone who decides which devices belong, can remove a person with every device of theirs, and can show afterwards who did what. An organization adds that as a layer on top of the vault. A vault without one is unchanged: no new objects, no new checks, nothing in the interface beyond the Use with a team card under Settings.

Keys. The organization has a root key: a random 256-bit secret shown once as 24 BIP-39 words (varsto org create, Set up an organization… under Settings) and never stored on any device. The root signing key is the hybrid Ed25519 + ML-DSA-65 pair whose seeds are derive(root, "org-root-ed25519") and derive(root, "org-root-ml-dsa"); the organization id is the first 16 bytes of the hash of its public key. The root key signs the manifest only (who the administrators are); everything else is signed by administrator device keys, the ordinary device signing keys of section 3. Bodies are encrypted under derive(K_epoch, "org-record") with the vault key of the epoch named in the envelope, so the storage reads nothing and a device that joined later opens older objects through the epoch chain.

Objects (under org/ on every metadata storage, written with put-if-absent):

Object Content Protection
org/manifest/<seq, 8 digits>-<attempt, 3 digits>.json org id, name, seq, hash of the previous manifest as stored, time, root public key, administrators (device id and name) body encrypted; signed by the root key over vault, org id, seq, key epoch and the ciphertext hash
org/roster/<seq>-<attempt>.json org id, seq, hash of the previous roster, the manifest that made the issuer an administrator, issuer, time, members (device, user, name, when and by whom added), removed (device, user, name, when, by whom, wipe), policy body encrypted; signed by the issuing administrator device
org/log/<device>/<seq>-<attempt>.json one entry of that administrator device's log: seq, hash of its previous entry, time, event body encrypted; signed by the issuing administrator device

A manifest, a roster and each device's log are hash chains with contiguous sequence numbers. The roster is a snapshot, not a delta: the newest valid one is the truth. Rosters carry the policy: whether members may share folders with people outside the vault, add or remove storages, set policies and placement, or add devices and print the recovery kit. Every flag is off by default; administrators may do everything.

What a device accepts (sync_org, run on every pull before revocations are read and again after a new key epoch is adopted): the next manifest in sequence whose previous-hash matches, signed by the root key the device already knows (the first manifest it ever sees pins that key; a vault whose storages hold a manifest the device cannot read refuses to create another); the next roster in sequence whose issuer is an administrator in the manifest it names and is not revoked; the next log entry of each device that is or was an administrator. Anything else is ignored. The result is kept in org-state.json.

Who belongs. Once a roster exists, a full device is trusted (section 21: its records, ledger batches, revocations and grants count) only if the roster lists it. A device that joins with the vault key alone therefore reads everything the key opens, but the others ignore what it writes, and the organization page lists it under "not in the organization" until an administrator adds it (varsto org add-device <device> --user <person>). Devices that existed when the organization was created are listed under its founder.

Approval. A new device runs varsto org request [--name <device>] (the name defaults to the computer's name) (or Join your organization on the setup screen): it asks for the passphrase the device will have, creates its key-exchange key and its device signing key, keeps both sealed under that passphrase in org-request.enc (Argon2id, as keys.enc; org join needs the same passphrase), and prints vor1.<KEM public key, hex>.<device id>[.<name>] with a six-word fingerprint over the key, the device id and the name (the derivation of section 24). An administrator pastes the code, compares the words with the person, names the person and approves: the device goes into the roster (so its id is known before it writes anything), the log gets device_approved, and the device receives vot1.<vault id>.<KEM ciphertext>.<sealed>: the pairing bundle of section 9 (vault key of the current epoch, storages with their secrets) plus org id, name, user, approver and the confirmed fingerprint, sealed through the hybrid KEM to its request key. varsto org join --token (or the setup card) refuses a token whose confirmed fingerprint is not its own, joins through the first reachable storage like pairing, and signs with the key it made at request time.

Removing. Only administrators can revoke devices, and only epochs and revocations issued by administrators are adopted; a member device that tries gets an error, and a forged epoch record from a member is ignored. varsto org remove-user <person> --yes [--wipe] (Remove … on the Organization page) revokes every current device of the person in one key epoch (revoke_many: one epoch record naming them all, one signed revocation each, the new key sealed to the devices that stay), moves them to the roster's removed list and logs user_removed. Removing a single device with varsto device revoke on an administrator device keeps the roster and the log in step. The founder cannot remove the person who owns the device it runs on; another administrator does that. What a removed device can still read is exactly what section 21 says: nothing new, everything old; storage credentials are not rotated.

Administrators. varsto org admin add <device> and admin remove (the 24 root words are asked for without echo, or come from --root-words-file, VARSTO_ORG_ROOT_WORDS or standard input) publish the next manifest; the root words are typed, used and dropped. An organization keeps at least one administrator. A revoked administrator's old rosters stay valid (they were valid when written); new ones are refused because the issuer is revoked.

Log. Events: org_created, admin_added, admin_removed, device_approved, device_added, device_removed, user_removed, policy_changed, each with the names at the time. varsto org log [--json], GET /api/org/log and Export as JSON on the page give the merged, verified log, oldest first. Nobody can change an entry afterwards without the chain breaking on every other device.

Interfaces. CLI: varsto org create|status|request|approve|join|add-device|remove-user|policy|admin add|admin remove|log; varsto device list shows each device's person and role. API: POST /api/org/request, POST /api/org/join (without a vault), GET /api/org, GET /api/org/log, POST /api/org/create|fingerprint|approve|add-device|remove-user|policy|admin. Interface: Use with a team under Settings creates one; the Organization page (sidebar, and More on a phone) appears only when the vault has one and shows people and devices, approvals, the policy, administrators and the log; members see the page without the administrator actions. StatusReport.org carries org id, name, whether this device is an administrator and listed, and its user.

Limits. A member's device holds the vault key, so a modified client can read everything the key opens and can hand the key on; the policy flags are enforced by every honest device and by the roster (an unapproved device is ignored), not by the storage. Storage credentials are shared and not rotated (plan 6.44 phase B). Existing data is not re-encrypted after a removal (phase C). There is no second factor on administrator actions and no dual control. Two administrators writing the same roster or manifest sequence at the same moment collide on the first storage; the second one syncs and tries again. A device listed in the roster but removed from the vault by an administrator of an older manifest stays removed. Tests: crates/varsto-core/tests/organization.rs (create, a member's limits, approve and join, an unapproved device ignored until added, removing a person in one epoch with a wipe, a single-device removal, the policy, a forged roster ignored, appointing and dismissing administrators with the root words), crates/varsto-cli/tests/org_cli.rs (the commands end to end) and org::tests.

28. Hardening against other devices, storages and peers (0.0.1-alpha.10)

A security review of alpha.10 looked at what a device holding the vault key, a storage provider, a peer on the network or a local user could do. These changes follow from it.

Paths from other devices. Every manifest is validated when it is opened: each entry's map key must equal its path; the path must be a valid vault path (relative, no .., . or empty components, no NUL; util::check_rel_path, section 46 since original names are kept: until then backslashes, :, control characters and Windows device names were refused too); chunk sizes must lie between 1 byte and 16 MiB; and a file's size must equal the sum of its chunks. A manifest that fails is ignored. Manifests, snapshots and records have no size cap yet. Before a remote file, placeholder or trash copy is written, its local path (section 46) is joined to the folder root again with util::safe_join, which refuses to write through a symbolic link anywhere on the way and, on Windows, any character Windows reads as a drive, a stream or a separator. Before this, a device with the folder key could write, overwrite or move files outside the folder on every other device, and have a picture outside the folder thumbnailed and uploaded. Reading a file through the API checks the path and requires it to be in the folder's state.

Object keys. Every storage backend (directory, S3, rclone, disk pool) checks object keys with the same rule, so keys listed from someone else's storage (an untrusted replica's source) or from a disk's own index cannot leave the storage's root. A pool disk's index counts an object only when the file is there with the claimed size. rclone runs with -- before remote paths, and only its exit codes 3 and 4 mean "not found"; any other failure is an error, so an unreachable remote never looks empty.

Bounds. Decompression capacity is bounded by the 16 MiB chunk limit. Reads from storages are not bounded by it: the S3 backend reads a response body of up to 2 GiB into memory (s3::MAX_BODY; manifests and ledger batches have no size cap, and a storage that answers with a huge body makes the device allocate that much), the QUIC transport caps a peer's body at 64 MiB and the TCP transport at 64 MiB for bodies without a length. Bounding storage reads to what the object kind can legitimately be is an open hardening item (S-series). A ledger batch more than 65 536 sequence numbers beyond the newest batch held (or the checkpoint) is not kept until the gap closes, so a device cannot make every reader walk to an absurd number; since section 58 the same holds for checkpoints. A Lamport clock seen elsewhere is adopted only when it is at most 2^40 ahead of the local one, and the local clock never wraps; since section 58 a batch with such a Lamport time is refused outright. Manifests, snapshots and records have no size cap yet.

Signed records. Epoch records (section 21) are wrapped in an envelope signed by the issuing device (SignedEpoch), in an organization since this section and in every vault since section 58 (the bare form is neither written nor read any more); a number taken by an unsigned or unverifiable object is skipped, not waited for, and a new epoch takes the first number above everything present. The chain of epochs records the previous epoch number, so it can step over skipped numbers. A device joining with the vault key tries the epoch numbers from the top down and uses the first one its key opens. Policy and placement records are wrapped in an envelope signed by the device that wrote them (SignedRecord); the <device> in the object name must be the signer. In an organization only signed records from trusted devices are adopted (and only an administrator's unless members may set policies). A vault without an organization writes and reads the older, unsigned forms of policy and placement records: any of its devices may set policies anyway, so a signature would prove nothing more, and devices still on alpha.9 keep working with devices on alpha.10 (tested in the lab: sync both ways, policies set on either version, a device removed by either version, an upgrade in place).

Organizations (section 27). Object names carry an attempt number; a writer claims the lowest free attempt of the next sequence number with put-if-absent on its first storage, skipping junk, so nobody can block the chain by writing first. Readers take, among the objects of one sequence number from every storage in name order, the first that verifies; a device whose own roster lost that race steps back and adopts the winner. A manifest records the newest roster when it was written; a roster or log entry counts only if its issuer is an administrator in the manifest in force for its sequence number, so a dismissed administrator cannot keep writing by naming an older manifest, while its earlier rosters stay valid. A roster issuer must also be listed in the previous roster. Revocations are read before and after the organization on every sync. An approval token carries the root public key, which the joining device pins before its first read, so a manifest chain replaced on the storage is refused. A device that was approved but never joined can be approved again for the same person to get a new token. The request file is created owner-readable only. Removing a person pulls the newest ledger first, like removing a device.

Peers. A peer token now carries a random nonce, and the answering device accepts each nonce once inside the time window; a relay checks a token without spending it. The time window check cannot overflow. Devices the organization's roster does not list are refused by peers like revoked ones. Chunked HTTP bodies are bounds-checked, bodies without a length are capped at 64 MiB, malformed object names are refused, and a panicking connection thread no longer leaks a connection slot. Pairing confirmations are compared in constant time.

Local service. The session token is no longer printed on the service's output (which the tray and launchd write to service.log), and service.log is created owner-readable only. Download names in Content-Disposition are encoded per RFC 6266 instead of crashing the API thread on a non-ASCII name. The S3 secret given while joining is removed from the process environment as soon as the storage is open, so child processes do not inherit it. The self-update unpacks into a fresh private directory with a random name and refuses an archive with more than one binary. The MCP server's grant on every folder no longer reaches Strongroom folders; they need a grant by name.

Tests: util::tests, manifest::tests, ids::tests, p2p::tests (chunked bodies, one-time tokens), crypto::tests, and in crates/varsto-core/tests/organization.rs junk under organization and epoch names, two administrators writing at once, a dismissed administrator, and a forged policy record.

Further hardening of the local service, storage reads, passphrases, names and temporary files: section 60.

29. Background by default, block sizes by file size, peer-to-peer during uploads (0.0.1-alpha.11)

No manual buttons. The interface has no Sync, Refresh, Check storage, re-hash or Check for updates buttons any more: the service syncs within seconds of a change and on its timer, automatic verification and repair run on their own (sections 20 and 26), the page refreshes after every sync, and updates are looked for at start and every six hours in the page, the tray and the macOS menu bar and offered only when a newer version exists. The macOS app replaces the whole bundle from the signed disk image and starts again; varsto update does the same from inside the bundle. A copy that cannot install a newer version says so instead of "up to date".

The service everywhere. On Linux and macOS any command sets up the login service once a vault exists (a systemd user unit, a launch agent), for the default device directory in a terminal, until varsto uninstall, which leaves a service-off marker. Only one service runs per device directory. With a service running, folder add, attach, detach, remove and selective go through it; the service also reloads config.json and the keyring when another process changes them. Each process reserves its own block of Lamport clock values in clock.json (section 6), so two processes on one device never hand out the same value. A passphrase from VARSTO_PASSPHRASE unlocks a waiting service like a typed one. Device names default to the computer's name.

Peer-to-peer on by default. P2pConfig gains user_disabled; without it peer-to-peer is on (port 17893). A device that published something new sends /p2p/changed to its peers, which sync at once. A push with peers publishes the file list and its ledger batch before the upload, refreshes what the peer-to-peer server offers and tells the peers, so devices that can reach it fetch new files while the upload to the storages runs. A peer marked unreachable is tried again at once when its record changes (a new relay, new addresses).

Block sizes. The chunker parameters follow the file size: below 32 MiB 64 KiB to 1 MiB (average 256 KiB), below 1 GiB 256 KiB to 4 MiB (average 1 MiB), larger 1 to 16 MiB (average 4 MiB). Format 2 changes the tiers and keys the chunker (section 62). The size alone decides; no compatibility with the single set of earlier versions is kept. Memory stays bounded: at most 128 MiB of encrypted data waits for the uploaders, and about 96 MiB of blocks is in flight per downloaded file.

Default policy. A folder without a policy of its own uses 1 copy on any storage, 1 at place cloud, 1 at place home (a directory storage or a disk pool; copies on devices never count), verified by another device within 30 days. In a vault with no storage in place home, the default policy does not report a violation for the missing home copy: the report carries one warning ("No copy on your own disks: this vault has no disk pool or directory storage. Add one, or change the folder's policy on the Policies page.") and the state is at_risk (policy::evaluate_for_report); a policy set on purpose that asks for home is reported as violated. Reasons read "N chunks have no copy on your own disks" for a minimum of 1 and "N chunks have fewer than M copies on your own disks" otherwise. policy clear stores an empty policy, so the default does not return. A move keeps a copy only when dropping it makes the policy worse; freeing advice ignores places the vault has no storage in.

Other. varsto transfers [--watch] [--json] lists uploads and downloads running in the service (/api/progress field transfers) with peer traffic. S3 refusals are explained in words before the technical detail. Turning selective sync off downloads the placeholders on the next sync. Temporary files of atomic writes are unique per write.

30. Packs for small blocks (0.0.1-alpha.12)

Superseded by section 77 (storage format 3): no pack index, tombstone list or per-block claim exists; places are in the folder block maps and packs are collected by garbage collection (77.2, 77.3). Kept as the history of format 2.

Replaced by format 2 (section 62): every block of every storage is in a pack, pack indexes are encrypted and per push, deletions are encrypted tombstone lists, and readers find blocks from the ledger instead of listing indexes. .idx files and .del. markers are no longer written or read. What follows describes format 1.

Why. A folder of small files is one block per file, and every block was one object on every storage: twenty thousand notes meant twenty thousand uploads, list entries and verifications, and on storage classes with a minimum billable object size each one cost as much as a much larger object.

Layout. A push collects the encrypted objects of blocks up to 128 KiB and writes them together once 4 MiB or 256 of them are waiting (and what is left at the end of the push):

  • packs/<id[..2]>/<id>.pack: the objects' bytes one after another, unchanged (each is still ciphertext named by its hash);
  • packs/<id[..2]>/<id>.idx: JSON {"format": 1, "pack": <id>, "members": [{"object", "offset", "len"}]}, written after the pack, which makes its objects visible;
  • packs/<id[..2]>/<id>.del.<object>: an empty marker per object deleted from the pack.

<id> is the hex hash of the pack's bytes, so writing the same pack twice is harmless. Packs are written to hot storages that are not transferrers (S3 buckets, rclone remotes, directories); cold storage, transferrers and disk pools keep one object per block, because restores, deliveries and disk placement work per object there. A storage may hold both single objects and packs.

Reading. Every storage is opened through a layer that knows its packs (packs::PackAware): it lists packs/ once, reads the indexes and markers it has not seen, and answers chunks/<xx>/<object> for a packed object with a ranged read of the pack (Range on S3, rclone cat --offset --count, a seek on directories). A miss reloads the indexes at most every 30 seconds. Listing chunks/ includes packed objects, so verification, fsck and repair see them like any other; every reader checks the object's hash as before.

Deleting. Deleting a packed object writes its marker; when every object of a pack is marked, the pack, its index and the markers are deleted. A repair of a damaged packed object marks it deleted and writes a single object in its place. The ledger is unchanged: it records objects by name, wherever their bytes are.

31. Backups (0.0.1-alpha.13)

What. A backup keeps read-only snapshots of a directory of one device, encrypted like every folder, on the storages only: never on the vault's other devices (no device records chunk_on_device for it, and peers neither serve nor are asked for its blocks) and never on a transferrer. Each snapshot is kept for a number of days (90 unless the user chooses otherwise) and then deleted from the storages. Files come back only by restoring a snapshot into a directory the user names (varsto backup restore, the interface's Backups page).

Record. A backup is a folder record (section 5) with a backup field: {source_device, source_path, retention_days, created_utc}. It has its own folder key, key epochs, placement (default: every storage of the source device that is not a transferrer) and ledger chunk records like any folder, but it is never mounted and only the source device writes it. Keyring::find and the folder listings leave backups out; sync, sharing, manifests, the peer-to-peer snapshot and folder attach never see one, and folder and backup names are unique together. The source device keeps its own settings in config.json (backups: path, schedule manual or {"every_hours": N}, retention for the next snapshots, last snapshot time and sequence number, stopped).

Snapshot. snapshots/<backup>/<device>/<seq 16 digits>.enc: zstd-compressed JSON {format_version, backup, device, seq, taken_utc, expires_utc, retention_days, files, skipped} encrypted with XChaCha20-Poly1305 under the backup's folder metadata key of the newest epoch, associated data snapshot, vault, backup, device, seq. files maps paths to file states as in a manifest (live files only) and passes the same checks when opened; skipped names files that could not be read or stored completely. expires_utc is fixed when the snapshot is taken, so a later retention change applies to later snapshots only. A snapshot is written once with put-if-absent to every metadata storage that is not a transferrer, cold ones included, and never changed; a sequence number an interrupted attempt already wrote is skipped.

Ledger.

Event Fields View
snapshot_taken backup, seq, taken_utc, expires_utc, files, bytes, snapshot_hash (BLAKE3 hex of the stored object) snapshots[(backup, device, seq)] set; the event with the largest stamp wins if two disagree
snapshot_expired backup, device, seq that snapshot is marked expired (in any arrival order)
backup_stopped backup added to backups_stopped

The view (and with it checkpoints, section 22) carries both maps; the cached view's format is 4. A member device sealing per-folder batches files these events under the backup.

Taking a snapshot (source device only, varsto backup take, the schedule):

  1. Pull the ledger; scan the directory read-only (files that cannot be read are skipped, not fatal); upload the blocks the storages lack (never to a transferrer; blocks dropped by an earlier expiry are written again).
  2. Every live file must have each block claimed on a storage in the view; a file that is not is scanned and uploaded once more, and left out (named in skipped) if it still is not.
  3. Seal and write the snapshot, record snapshot_taken, seal and push the batch. A snapshot is written also when nothing changed.
  4. Pull the ledger again and write back any block of the snapshot that another device dropped meanwhile (an expiry that had not seen the snapshot yet).

Restoring. A snapshot is chosen by number, latest, or a day YYYY-MM-DD (the newest one taken by the end of that day, UTC). Its object is read from the first metadata storage whose copy has the hash recorded in snapshot_taken; a copy that differs is refused ("altered"), and cold storages are read only when confirmed. The target directory must be empty unless overwriting is asked for; files (or only the given paths and the directories under them) are fetched from storages only, checked like any block, written through a temporary file and given their recorded modification times. Paths pass safe_join. Any full device of the vault can restore; nothing is recorded as held on a device.

Expiry. A snapshot is due once expires_utc plus a grace day has passed, except the newest live snapshot of a backup that is not stopped: it is never due, whatever its age, so retention never leaves a backup without a snapshot (also when its source directory is gone and no newer one can be taken). The source device expires its backups' snapshots; another device does so only when the backup is stopped, the source device was removed from the vault, or two days have passed since expires_utc. The service looks at most every six hours; varsto backup expire runs it at once. For each backup with something due:

  1. Record snapshot_expired for each due snapshot.
  2. Read the live snapshots (cached per device in state/backups/<backup>.json); if one cannot be read, nothing is deleted this time.
  3. The candidates are the backup's blocks that no live snapshot uses (and that no other folder names, as a safeguard). Record chunk_dropped for every storage of this device that claims one, then seal and push the batch before deleting anything.
  4. List snapshots/<backup>/ again; a snapshot the ledger does not know yet is read (after pulling the ledger once more) and its blocks are kept.
  5. Delete the candidates from this device's storages (packed ones through their deletion markers, section 30) and the expired snapshot objects.

A stopped backup whose last snapshot has expired is removed from the vault like a removed folder with its data purged (vault/removed/, blocks, snapshots/<backup>/). Stopping deletes nothing early.

Other parts. Storage removal plans and fsck count the blocks of the live snapshots a device has read or written; repair rewrites a backup's damaged copies from another storage (never from a peer). The service takes scheduled snapshots after a sync and reports the last snapshot, failing backups and the last expiry run in its summary. Local API: GET /api/backups, GET /api/backup/snapshots?backup=, POST /api/backup (add; initial takes the first snapshot), /api/backup/take, /restore, /set, /stop, /expire.

Limits.

  • Expiry follows each device's clock: a device whose clock runs days ahead deletes early (the grace day and the two days for other devices soften this).
  • A snapshot written to a storage and not yet listed there (no read-after-write) could lose blocks to a concurrent expiry by another device; step 4 of taking a snapshot writes them back while the files are unchanged.
  • The default durability policy is not applied to backups yet: they are not in the policy reports.
  • Storage names are local: only the source device's storages receive snapshots, and another device deletes only from its own storages.
  • The first snapshot of a large directory holds the engine for as long as its upload takes.

Tests: crates/varsto-core/tests/backups.rs (byte-identical restores by number, date and latest, paths, refusal of a non-empty directory, restores on another device, nothing on devices or transferrers, altered snapshots refused, expiry deleting only unused blocks including packed ones while other folders stay, other devices waiting for the source, a stopped backup removed with its last snapshot, schedules), snapshot::tests, engine::backups::tests and the random-event view tests in ledger::tests.

32. Live activity between devices (0.0.1-alpha.14)

Every device tells the other devices of the vault what it is doing right now (checking the blocks of a disk, uploading a folder, restoring a backup), so that one device's interface can show "laptop: checking the blocks of disk «Blue 4TB» 42 %, ready about 14.35". Nothing of it is stored: not in the ledger, not in a log, not on disk. The detail of a transfer carries the current file name, and it reaches every authenticated device of the vault.

Tasks. A device keeps an in-memory list of the long operations running in it (activity): folder scans (sync_scan), uploads (upload), downloads during a pull (download), disk checks (disk_check, steps verify and fill), filling a new disk (disk_fill), backup snapshots (backup_snapshot) and restores (restore), repair (repair), automatic verification (verify), fsck (fsck, steps scan and verify), data moves (data_move), storage removal (storage_removal, steps copy and delete) and the trash (trash_restore, trash_purge, trash_move; section 43). A task is listed once it has run for two seconds. A command run in a terminal while the service runs sends its tasks to the service every second over the local API (POST /api/activity/report); the service counts them as the device's own and forgets them five seconds after the last report.

GET /p2p/activity is served on both transports and through relays like every other peer request, with the same membership token (X-Varsto-Peer, section 15). A revoked device, a token of another vault or a replayed token gets 403; a locked service 503. The answer is JSON:

{"device": "<device id>", "name": "laptop", "state": "busy", "service_version": "0.0.1-alpha.13", "updated_utc": 1791876245,
 "tasks": [{"id": 3, "kind": "disk_check", "phase": "verify", "subject": "Blue 4TB", "done": 13314398618, "total": 31675383808,
            "unit": "bytes", "percent": 42, "started_utc": 1791875900, "updated_utc": 1791876245, "rate": 85000000, "eta_utc": 1791876461}]}

state is idle when tasks is empty. total 0 and percent null mean the amount is not known (a pull learns it file by file). rate is units per second over the last twenty seconds; eta_utc is set when a total and a rate are known. detail (optional) is the file being uploaded or downloaded: its name only. Unknown fields and kinds are ignored, and a device that answers 404 runs an older version.

What is shared, and with whom. The kind and step of each task, the display name of the folder, disk, backup or storage it works on, the current file name of a transfer (in detail, visible to every authenticated device of the vault), the counts, rate and finish time, the device name and version. Never file contents and never paths. Names are user data that every full device of the vault already holds, and they travel only to authenticated devices of the vault, over the same paths as blocks. Those paths are not all encrypted: QUIC is TLS; HTTP over TCP (the LAN, user-forwarded ports and relays, section 15) is plain, because blocks are ciphertext anyway. An activity answer over TCP therefore crosses the network in clear: task kinds, folder, disk, backup and storage names, the current file name of a transfer, counts and times. Encrypting the TCP transport (or carrying activity only over QUIC) is an open hardening item. In an organization (section 27) a device answers, and asks, only the devices the roster gives to the same user, as with the other details of one's own devices; a device not in the roster answers nobody. Members of a shared folder (section 24) hold no vault key and cannot ask.

Rate limits. A device asks its peers only while someone watches: the local interface or varsto activity asked GET /api/activity within the last fifteen seconds. It then asks each peer that the peer table does not rest (an unreachable peer rests as for blocks, section 77.8) at most every 2.5 seconds, all peers at once, with the short timeouts of block requests, and keeps the answers in memory. Nothing is pushed: polling while watched costs nothing when nobody looks, and a push on every start and end of a task would wake every device for syncs that last milliseconds. Answering costs one lock and a few hundred bytes.

Local API. GET /api/activity (answered without waiting for a sync): {"me": <the device's own answer>, "peers": [{"device", "name", "status", "stale", "age_secs", "activity"}]} with status one of ok, pending (not asked yet), unreachable, unsupported (an older version), refused (another user's device in an organization), and stale when the last answer is older than ten seconds. The command line prints it with varsto activity [--watch]; the interface shows a "Now" card on the Overview and a progress line under every device, hidden when all are idle.

Tests: activity::tests (task lifecycle, nesting, the quiet period, rate and finish time, throttled samples, tasks of other processes, no asking while nobody watches), p2p::tests::activity_is_told_to_authenticated_devices_of_the_audience_only, crates/varsto-core/tests/activity.rs (a device sees another device's slow fsck with its progress over TCP), crates/varsto-cli/tests/activity_cli.rs (a terminal command's task in the service's activity) and the lab scenario activity.

33. Bit-rot check (scrub)

Why. Automatic verification (section 20) re-reads only copies that other devices wrote, because that is what a policy counts; a device never re-read its own writes, and a synced file on a device was never re-hashed while its size and modification time stayed the same (change detection, section 7), so a flipped bit on a storage or on a local disk could go unnoticed for ever. A scrub re-hashes everything this device can read, on a rolling schedule, and repairs or restores what decayed. Its checks are not recorded in the ledger: a writer re-reading its own copy is not an independent verification, and policy semantics are unchanged (verified_within_days still needs another device).

What is checked. One run reads, per target:

  • Storages (directories, S3, rclone): every object the ledger places on the storage, whoever wrote it (this device's own claims under the local name; other devices' claims through the storage identities of section 20, or by equal name for a writer that published none). Blocks are read with a ranged read of their pack at the place the ledger gives (section 62); automatic verification reads the blocks due in one pack with one request. The ciphertext is hashed against the object name; an object the storage does not return is missing. Objects the ledger does not know are not read.
  • Pool disks (section 19): every attached disk is a target of its own, and its own copy of each object it holds is read (with disk groups, each disk's copy, not only the first one found). Since format 2 these objects are packs, hashed against their id; a lost pack queues a repair of every block in it. A disk that is away waits; one not seen for scrub_days is reported ("disk away for long").
  • Local files: in every attached folder that is not kept encrypted on this device and not a locked Strongroom, every file whose local index entry and merged file state have the same content hash (a synced file; placeholders and deleted files have none) and whose size and modification time on disk still match the index. The content is hashed with the folder's keyed content hash; the size and time are read again afterwards, and a file that changed meanwhile is left to the next scan.
  • Block cache (folders kept encrypted on this device): every object, against its name.

Transferrers are never read (they are emptied on purpose). Cold storages are left out unless the user opted the storage in for scheduled runs (config.json scrub.cold, set only with an explicit confirmation that retrievals may be billed: varsto scrub set --cold NAME --confirm-cold-read) or includes cold storage in one run (varsto scrub --include-cold --confirm-cold-read).

Schedule. Each target is swept in key order (object key, path) with a cursor in state/scrub.json: sweeps[target] = {label, cursor, pass_started_utc, last_run_utc, last_pass_done_utc, checked_in_pass}, targets named storage:<name>, disk:<pool>/<disk id>, files:<folder id> and block-cache. The items after the cursor are the ones checked longest ago or never, so taking them in order is oldest first, and the state stays a few lines per target however many objects there are; an item added behind the cursor is first read in the next pass. A pass should end within scrub_days (default 90) of its start. The service runs a scrub after a sync when interval_hours (default 24) have passed since the last full run, after automatic verification and before repair; such a run takes, of each target, the share of the bytes left in the pass that the time since the target's last run stands for (left × elapsed / (deadline − last run), at least one item), so reads spread evenly over the period. A pass past its deadline takes all that is left. Targets whose pass began longest ago go first.

Budgets. Per run, at most max_local_bytes (default 2 GiB) from this device's disks (local files, the block cache, directory storages and attached pool disks) and max_remote_bytes (default 1 GiB) from S3 and rclone storages; the first item of a run is always read, so a large object cannot stall a pass. A target whose pass cannot end in time within the budget is reported as behind. A run asked for by hand (varsto scrub, the interface's Check now) is not paced: it reads as much as the budgets allow; --full reads everything selected from the start, without budgets. A run restricted to some storages or to local files does not move the schedule.

Reads. Each target is read according to its medium (section 39): spinning disks one item after another in key order with the hashing of one item overlapping the read of the next, solid-state disks and network storages with several readers. The results are taken in key order whatever order the reads finish in, so the cursor never passes an item that was not checked, the budgets are spent exactly as in a sequential run, and a run's findings are the same.

Damaged copies. A missing or corrupt object on a storage is put in the repair queue (section 26) with found_by: "scrub"; the service's repair run, which follows, rewrites it from another copy (a corrupt pack member through a tombstone and a new pack, section 62). A bad copy on a pool disk is deleted from that disk and forgotten in the pool index first (as disk check --full does); it is queued for repair only when no other disk holds a copy, otherwise the disk group rule restores the copy at the next disk check. A corrupt block cache object is deleted and fetched again from a peer or a storage; when no intact copy can be had, the files that need it are no longer counted as cached here and the next sync fetches them when it can.

Damaged files. A local file whose content no longer matches the recorded hash although its size and modification time did not change is treated as bit rot, but it is never overwritten: it may be an edit by a program that kept the time. The recorded version is downloaded first (peers, then storages, as a pull does) into a temporary file next to it; only then is the damaged file renamed to <stem>.damaged-<YYYYMMDD><.ext> (photo.jpg becomes photo.damaged-20261013.jpg; -2, -3, … when taken; a name without an extension gets the suffix at the end) and the recorded version, with the recorded modification time, takes its place. The local index then describes the restored file, so the next scan sees no change; the damaged copy is an ordinary new file of the folder and syncs as one (with content-defined chunking only its changed blocks are new), so nothing is lost and the user can compare and delete it. A file read error counts as damage. When no good copy can be downloaded, the file is left exactly as it is, recorded in state/scrub.json (unrestored) and tried first on every run until it is restored, edited (its size or time changed) or gone. Every damaged file raises a desktop notification in the service.

Surfaces. varsto scrub [--storage NAME]... [--local] [--full] [--include-cold --confirm-cold-read] [--no-repair] runs once (only the named storages, only local files and the block cache with --local alone, everything otherwise) and repairs the queued copies right away unless --no-repair; it prints {scrub, repair} with --json and exits with 1 when a damaged copy or file is left. varsto scrub status shows the schedule, the last run, every target's pass and the damaged files waiting; varsto scrub set [--on|--off] [--interval-hours N] [--days N] [--local-mib N] [--remote-mib N] [--cold NAME --confirm-cold-read] [--no-cold NAME] changes them. API: GET /api/scrub, POST /api/scrub {enabled, interval_hours, scrub_days, local_mib, remote_mib, cold: {name: bool}, confirm_cold_read}, POST /api/scrub/run {storages, local, full, include_cold, confirm_cold_read} (repair follows when something was queued); GET /api/service carries scrub and a one-line scrub_text, which varsto service status prints. The interface shows a Bit-rot check card on the Policies page: last run, objects and files checked, problems found and files restored, damaged files waiting, Check now, Schedule and Turn off/on. While it runs, each target is a live activity task (section 32) of kind scrub with the step storage, disk, files or cache, the storage, disk label or folder name as its subject, and the bytes planned for the target as its total. The report of a run: objects, files and cached blocks checked with their bytes, corrupt and missing copies, copies queued for repair, damaged files (moved to, restored, reason), cache objects dropped, copies on disks that are away, disks away for long, targets not read with the reason, and each target's progress.

Limits.

  • An edit that keeps both the size and the modification time to the nanosecond cannot be told from bit rot; it is kept as the .damaged- copy, never lost.
  • Only objects the ledger places on a storage are read; objects nobody claims (left over by an interrupted write) are not.
  • The first pass over a large vault takes scrub_days at least; with the default budgets a device reads at most about 2 GiB local and 1 GiB remote a day, so a storage holding more than about 90 GiB (remote) per 90 days is reported as behind until the budget or the period is raised. Remote reads may cost egress fees.
  • A scrub holds the engine while it runs, as verification does; a run of the full budget can take minutes on a slow link.
  • Folders kept encrypted on this device are checked through the block cache only; a locked Strongroom's files are skipped until it is unlocked.
  • Pool disks are scrubbed only while attached; the cursor of a disk survives its absence.

Tests: crates/varsto-core/tests/scrub.rs (a corrupt single object, a corrupt packed object and a lost object that this very device wrote are found on one storage, queued and repaired, and nothing is recorded in the ledger; a one-byte budget reads one object per run until the pass ends; a scheduled run reads a share; cold storage left out until included or opted in with a confirmation; a flipped byte in a local file with its time restored is moved to .damaged-<date> and the recorded version restored with its time; an edited file with a new time is not touched; a damaged file without a good copy is left in place and restored on a later run; a bad copy on a pool disk dropped and rewritten, and a disk away for long reported; a corrupt block cache object dropped and fetched again, or the files needing it uncached), scrub::tests (oldest after the cursor first, budget across targets, pacing over the period and catching up when behind, cold and transferrer inclusion, damaged names, defaults) and crates/varsto-cli/tests/upkeep_cli.rs (scrub, scrub --storage, cold confirmation, scrub set, scrub status).

34. Whole drives for disk pools: init, insert, unmount, verified writes

Section 19 works on directories that are already mounted. On Linux the command line also prepares whole drives, mounts them when they are plugged in again and unmounts them safely. Elsewhere these commands say they are Linux only.

Safety checks before erasing. varsto disk init <device> --pool <pool> --label <name> [--place P] [--confirm <device>] first checks that the pool exists and the label is free, then reads lsblk -J -b -o NAME,KNAME,PATH,TYPE,SIZE,MODEL,SERIAL,TRAN,RM,RO,MOUNTPOINTS,FSTYPE,PKNAME,PARTUUID,LABEL,MAJ:MIN, /proc/swaps and the device numbers of /, /boot, /home, the Varsto directory and the running program. A /dev/disk/by-id/... name is resolved to its kernel device. It refuses: a device lsblk does not know; a partition (it names the drive to give instead); anything whose type is not disk (loop, rom, mappings); a read-only drive; a drive any of whose partitions or mappings is mounted or in use as swap; a drive with a volume manager, RAID, encryption or pooled filesystem signature anywhere on it (LVM2_member, linux_raid_member, crypto_LUKS, zfs_member, bcache, ...); a drive with a device-mapper or RAID device built on it; and a drive holding the root filesystem, /boot, /home, the Varsto directory or the program. It then shows the drive (model, serial, size, transport, removable) and its current partitions with their filesystems and labels, and asks the user to type the device path exactly; without a terminal it needs --confirm with the same path and refuses otherwise.

Preparing. One privileged call runs a fixed script (blockdev::INIT_SCRIPT) through sudo, or pkexec where sudo is missing (one password prompt), or directly as root; the command says which. The drive, partition UUID, names and owner are passed as arguments, never pasted into the script. Steps: sgdisk -Z and sgdisk -o (a new GPT), sgdisk -n 1:1M:0 -t 1:8300 -u 1:<uuid> -c 1:varsto-<label> (one Linux partition from 1 MiB to the end of the drive, section 66, its PARTUUID chosen at random beforehand, name at most 36 characters), partprobe, udevadm settle until /dev/disk/by-partuuid/<uuid> exists, and mkfs.ext4 -F -L <label> -m 0 -i 65536 -E root_owner=<uid>:<gid>. The filesystem label is the sticker name reduced to ASCII letters, digits, - and _, at most 16 bytes. No blocks are reserved for root (the pool keeps its own reserve, section 19) and the user owns the filesystem root. The inode ratio is one per 64 KiB: pools store one file per encrypted block and do not pack, blocks average 256 KiB for files below 32 MiB and a small file is one small block, so -T largefile4 (one inode per 4 MiB) would run out of inodes on a drive of small files; one per 64 KiB costs 0.4 % of the drive. The new partition is found again with lsblk and must be ext4. Then it is recorded in disks.conf, mounted, added to the pool exactly as disk add does (marker, disk index) and filled with progress.

<home>/disks.conf. Plain text, written atomically (temporary file, fsync, rename); comment lines (#) and blank lines are kept as they are. One line per partition: PARTUUID<TAB>POOL<TAB>LABEL, the PARTUUID in lower case, the label being the rest of the line (spaces allowed, tabs not); a label appears at most once. disk init writes it, and disk add adds the partition mounted at the given directory when there is one. The disk's marker remains the authority on which disk of which pool and vault it is; disks.conf only maps partitions to the names on the stickers, for mounting and for varsto disk list, which shows every drive of the file with its pool and PARTUUID and whether it is plugged in (its partition) and mounted (--json: partuuid, plugged_in and partition on the matching disk rows).

Mounting. A drive is mounted with udisksctl mount --no-user-interaction -b /dev/disk/by-partuuid/<uuid> (no password for a drive in a USB dock; it appears under /run/media/<user>/ or /media/<user>/, which the pool scans). Where udisks is missing or refuses (no polkit permission, for example over SSH or for an internal SATA port), it is mounted through sudo or pkexec at /mnt/varsto-<label> with noatime,nodev,nosuid; /mnt/* is scanned too. File system check before every mount. Before Varsto mounts a pool partition for work (disk insert, each disk of a fetch plan; not right after disk init, whose file system is new) it runs a forced check, e2fsck -f -p <partition> (preen: only the fixes that are always safe), through the same privilege helper, with a progress bar (-C 0) on a terminal. Only ext4, ext3 and ext2 partitions are taken; any other file system is refused for pool work ("prepare the drive with varsto disk init"). A partition the desktop already mounted is unmounted first (udisks, else umount as root), checked, then mounted. Exit codes are read as a bit mask: 0 clean, mount; 1 (and 2, "reboot", which concerns only a root file system) errors corrected, mount and warn "file system errors were found and corrected" on the terminal and as a desktop notification; 4 errors left: nothing is mounted, read or written, and the command fails with "The file system on

varsto disk insert [<label>] [--no-verify] [--no-fill]. For every drive of disks.conf that is plugged in (or the named one): mount it, then run the insert routine:

  1. Ledger. Pull the ledger when the storages answer, so blocks another device just wrote are known.
  2. Tidy, from listings only (no file is read). Check the marker; apply the deletions queued while the disk was away; remove temporary files of interrupted writes older than an hour; forget copies the index places on the disk that are missing, and remove and forget copies of the wrong size; adopt files the ledger holds on the pool, and files the disk's own index.json lists, that the pool index did not place here (their first check is due at once). A pack file is removed only when the pull read every hot metadata storage, the ledger shows the pack dropped from the pool, the disk's own index does not list it, and the file is older than the grace period (7 days, the orphan window). A pack the ledger has merely not seen is kept. A pull that returns success after skipping a storage (it did not answer, or none is configured) is not a complete pull: that removal is skipped and the report says so (ledger_note).
  3. Verify. Re-hash every copy on the disk whose last check is older than the pool's verify_after_days (default 180; varsto disk pool-set <pool> --verify-after-days N; 0 re-hashes everything every time), oldest check first. The pool index keeps per copy when it was last read back and hashed (checked: disk id to time, next to extra in the object entry); a copy without one was never checked by this device and is due. A good copy records its check and a chunk_verified event; a bad or missing one is removed from the disk and forgotten (filled again in step 4 if a source has it). Afterwards the disk's last_verified_utc is its oldest copy check, which is what policies use for a disk that is away.
  4. Fill with what the pool lacks while the reserve allows (below).
  5. Sync. Write the disk's index and fsync the data directory and the mount.

Progress (phase, blocks, bytes, rate and time left) goes to stderr on a terminal; --json prints a summary per drive (tidy, verified_objects, bad, missing, fill, ledger_note, message). At the end it prints, and shows as a desktop notification, "

varsto disk unmount <label> [--no-power-off]. With the service paused the same way: write the disk's index and fsync (as disk eject), sync, unmount (udisksctl unmount, else umount through sudo, removing an empty /mnt/varsto-* directory), sync, and power the drive off with udisksctl power-off. Each step is reported. A failed unmount fails the command and names fuser -vm <mount> to find what holds it; a power-off that fails or is impossible (no udisks) is reported as a note, since the drive is already safe to unplug.

Verified writes. Every object a pool writes (pushes, disk add, disk init, disk check, disk insert) goes to a temporary file that is fsynced, renamed and its directory fsynced, and is then read back and hashed before the write counts: on Linux the file's cached pages are dropped with posix_fadvise(POSIX_FADV_DONTNEED) and it is read with O_DIRECT into an aligned buffer (a plain read where the filesystem refuses direct reads; elsewhere a plain read). The BLAKE3 of what came back must equal the object name. On a mismatch the file is deleted and written once more; a second mismatch fails with WriteNotVerified ("the disk, its cable or dock may be failing"), and a fill stops writing to that disk and reports it. This is best effort: neither the dropped cache nor a direct read reaches past the drive's own cache, so a drive that acknowledges data it later loses is caught by the next periodic re-hash, not at the write. Checks by disk check --full and fsck --verify read the same way and record checked for the copies they hashed.

Filling. A fill takes blocks of current files that the pool holds on no disk, or (disk groups, section 23) in fewer places than its rule asks and not yet in the disk's place, within the disk's reserve. It chooses before it writes. Files are ordered: files with blocks the pool lacks entirely before files that only need further copies; then files whose blocks have the fewest copies on any storage (from the ledger); then larger files first; then older files. Whole files that fit go to the disk first (first fit decreasing, which keeps files together and fills the disk well); then files that could not fit whole on any disk of the pool are split; finally the space that is left takes parts of the largest remaining files rather than staying empty, so at most a few files end up split per disk. A push keeps writing to the disk that took the previous block while it has room, so a file's blocks stay on one disk there too. Blocks come from the pool's other attached disks, the other hot storages, the block cache or the local files, as before.

Fetching from pool disks. When a file is fetched (varsto folder fetch, the interface's download, POST /api/fetch) and the pool has disks, a plan compares two ways of getting its blocks. The network: for every block the cheapest remote copy (hot storages before cold ones; transferrers and pools do not count), costed at the storage's egress plus retrieval price (section 20; a cold storage without a price is unknown, a hot one without a price free), timed at link_mbit_per_sec. The disks: no fee, overhead_secs per disk that has to be fetched from the shelf plus the bytes at disk_mb_per_sec. Settings are per device in config.json (disk_fetch: threshold_bytes default 2 GiB, overhead_secs default 120, link_mbit_per_sec default 100, disk_mb_per_sec default 120; varsto disk fetch-set [--threshold-mib N] [--overhead-secs N] [--link-mbit N] [--disk-mb-per-sec N]). Per-request fees are not in the price data and are not counted. Disks are proposed when some blocks are on pool disks only, or when the fetch is at least threshold_bytes or the remote copies are cold, and only disks that pay off are taken: disks already attached first (no insertion), then repeatedly the disk holding the most wanted bytes not covered yet, each taken if it holds blocks no remote storage has, or reading it is faster than the network for its bytes, or (large or cold fetch) its blocks cost something remotely. Each disk is visited once. Blocks on no chosen disk come from the network. The plan (recommend "disks" or "remote", reason, the steps with disk, label, place, bytes and whether attached, disks_secs, the network part, and the network alternative with bytes, cost, currency, time, cold and storages) is kept in <home>/disk-fetch/plan.json; varsto fetch-plan <folder> <path>... prints it.

Running a plan goes disk by disk: "Insert disk "Blue 4TB" (offsite) into the dock and press Enter (s = skip, use the network; q = stop)". The drive is mounted as for disk insert (a drive disks.conf does not know must be mounted by the user), its marker checked (the pool finds it only by its marker), and only the plan's blocks for that disk are read, each hashed against its object name, into <home>/disk-fetch/<pool>/chunks/<xx>/<object>. Every file of the plan that waits for no other disk is then written to its place: download_to takes staged blocks before asking any peer or storage (runs of staged blocks are read locally, the runs between them fetched as usual) and records chunk_verified for the pool. Then the disk's index is written and synced, the drive unmounted and powered off (a disk attached when the plan was made stays mounted), and "Got 812 blocks (3.4 GB) from Blue 4TB: you can now remove it" is printed; then the next disk. A skipped disk's blocks come from the network at the end; stopping keeps the plan and the staged blocks, and the next fetch of the same files counts staged blocks as already there. When every file is written the staging directory and the plan are removed. varsto folder fetch --from-disks ask|always|never (default ask: shown and asked on a terminal; without one the network is used when it has every block) chooses; the running service is paused meanwhile.

The local API: POST /api/fetch {folder, path} answers {"plan": ...} instead of fetching when the plan recommends disks (from: "network" skips the plan); GET /api/fetch/plan; POST /api/fetch/plan/step {step} mounts the step's drive, copies, writes complete files, unmounts and powers it off, and answers {outcome: {label, objects, bytes, failed, files_done, message}, unmount, plan, finished} or {needs_disk} when the disk is not there; POST /api/fetch/plan/skip {step}; POST /api/fetch/plan/network (every remaining disk skipped, the rest from the network); POST /api/fetch/plan/cancel. The interface shows a dialog per disk with the plan, the reason, "Disk inserted" (or "Copy from the disk" for an attached one), "Fetch from the network instead" with its cost and time, and Stop, in English, Finnish and Swedish.

Live activity. These operations are tasks of section 32, so the device's own interface and the other devices show them with their counts, rate and finish: disk_init (partitioning and formatting, no counts), disk_fsck (the check before mounting, no counts), disk_insert with the steps tidy, verify (bytes re-hashed) and fill (bytes written and read back), disk_fill (the fill of disk add and disk init), disk_fetch with the steps copy (bytes copied from the disk) and write (the files written from them), and disk_unmount. A command-line run reports them to the running service as other commands do.

Not done. The interface has no buttons for init, insert or unmount yet (they are command-line only); udisks is not used on macOS or Windows; the service does not run the insert routine on its own when a drive appears; S.M.A.R.T. health is not read. Disk fetch plans cover single files from the command line and the interface (the engine takes several); the link speed is a setting, not measured; folder pulls of selective files and backup restores do not plan disks yet.

Tests: crates/varsto-core/src/blockdev.rs (lsblk parsing, every refusal with fixtures: system disk, mounted partition, swap, LVM, LUKS, partition given, a disk holding the program; the privileged script call with a recorded runner; mount fallback; unmount steps and a busy drive; the check before mounting for exit codes 0 to 3, 4, 5, 8, 12, 16, 32 and 128, an automounted partition unmounted first, a non-ext file system refused), crates/varsto-core/src/diskconf.rs (round trip with comments and spaces, duplicate labels, malformed lines), crates/varsto-core/tests/disk_pool.rs (a disk that returns wrong bytes once and twice; the insert routine on a directory disk: unneeded files and leftovers removed, only stale copies re-hashed, a bad copy found and refilled, the reserve respected), crates/varsto-core/tests/disk_fetch.rs (fills keep files whole and split one file only to use the last space; a large, priced fetch proposes the disk and a small one stays remote; disks ordered attached first, then by bytes; a file split over two disks fetched disk by disk byte-identical with the network copies gone, each disk released; a skipped disk's file comes from the network), the lab scenario disk-fetch-plan (two virtual drives, a file on both, fetched with scripted Enter, each drive unmounted after its blocks), and the lab scenario disk-init (a virtual drive attached to a VM: init, partition table, filesystem and PARTUUID, every object hashed, unmount, detach and reattach, insert, stale verification, fill after new files, unmount; a wrong free-block count made with debugfs is corrected by the check and the insert goes on; the data directory's inode cleared with debugfs stops the insert unmounted).

35. Backups with restic

Why. Varsto's own backups (section 31) and copies live in Varsto's format on Varsto's storages: restoring them needs Varsto and the vault key. A second, independent line of defence — another program, another format, another place — protects against a bug in Varsto, a lost vault key or a mistake that reaches every copy. restic is that program: one device of the vault keeps a full plaintext copy of the vault, and restic backs it up into a repository that lives outside the vault's storages. Restoring needs only restic and the repository password.

The mirror. One device is the restic device. varsto restic setup --root ROOT --repo REPO (--password-command CMD | --password-file FILE) attaches every folder of the vault (--folders all, the default) or the named ones (--folders a,b) at ROOT/<folder name> as ordinary folder mounts: full (not selective), plain files (not "encrypted on this device"). The folder name is the directory name (names with /, \, . or .., VARSTO-SNAPSHOT.txt and .varsto… are left out and reported). Left out unless asked for: Strongroom folders (a plaintext copy is what a Strongroom avoids; --include-strongroom, and then they must be unlocked for every run) and folders shared with other people (--include-shared). Backups (section 31) are never mounted and so never in the mirror; neither is Varsto's metadata (the device directory, the ledger, keys) nor its trash (home/trash, outside the mirror). A folder already attached elsewhere on the device is refused with its place named, unless --move: then its directory is renamed into the mirror (same file system only; otherwise the user detaches it and the mirror downloads it) and its mount path changes, so what the device knows of it stays valid. A root inside or around another attached folder, or inside the device directory, is refused. Setup first opens the repository (restic cat config); with no repository there (restic's exit code 10) it is refused unless --init, which runs restic init. With --folders all, a folder whose record arrives later is attached at ROOT/<name> at the next sync (Engine::restic_auto_attach, after the folder records are read), unless that directory exists and is not empty. The mirror is an ordinary synced copy: a file edited or deleted there is edited or deleted in the vault; nothing should work in it.

Settings. config.json restic (this device only, never published): root, repository, password ({"command": "..."} or {"file": "..."} — the password itself is never stored), env_file (optional KEY=VALUE lines handed to restic, e.g. cloud credentials), binary (default restic), folders ("all" or {"named": [folder ids]}), include_shared, include_strongroom, keep {daily, weekly, monthly} (default 7/5/12), check_every_days (default 7), check_subset (default 5%), schedule ({"every_hours": 24} by default, or "manual"), and, fixed at setup, vault_short (the vault id's first 8 characters), host (the device name) and created_utc. restic gets RESTIC_REPOSITORY, RESTIC_PASSWORD_COMMAND or RESTIC_PASSWORD_FILE, RESTIC_PROGRESS_FPS=1 and the environment file's variables; RESTIC_PASSWORD, RESTIC_PASSWORD_FILE, RESTIC_PASSWORD_COMMAND, RESTIC_REPOSITORY and RESTIC_REPOSITORY_FILE of the caller's environment are removed first.

A run (varsto restic run [--no-forget] [--check|--no-check] [--dry-run] [--rehash-all]), under the run lock home/restic.lock (flock; one run at a time, by hand or scheduled):

  1. Sync every attached folder (pull and push), as varsto sync does.
  2. Hold the mirror folders: state/restic-hold.json = {token, folders, pid, started_utc, until_utc}. While a hold is in force, this device's Varsto does not write into those folders: a sync skips them, and pull, push, fetch, free, write, mkdir, move, turning selective sync on or off and the bit-rot check's restores refuse or skip them. The hold is a lease: until_utc is five minutes ahead and the run renews it every minute; it is not in force once until_utc has passed or its pid is gone, so a run that dies stops syncing for at most five minutes. With the background service running, the hold is taken through POST /api/restic/hold {token, pid}, which the service answers while it holds its engine: once it answers, no sync of the mirror is under way and none starts. Without a service, the command takes the hold itself.
  3. Completeness (Engine::restic_check, under the hold; the engine working for the run's token is not stopped by it). For every mirror folder, every live file — every file of the merged state this device applied that is not deleted, and every newer version it knows but could not download yet (pending_remote) — must be on disk as a regular file, with no placeholder, recorded in the local index with the same content hash as the merged state, with the size and modification time (nanoseconds) of the local index, and its content must hash (the folder's keyed content hash) to the recorded hash. Problems: missing, placeholder, not_downloaded, changed (size or time differ, or the disk holds another version: edited after the last sync), hash_mismatch, unreadable (also a folder whose key is not at hand, a locked Strongroom). A folder the mirror should keep but that is not attached at its place makes the mirror incomplete too. Hashing is spared by state/restic-verified.json: folders[folder id][path] = {size, mtime, hash} for each file whose content was hashed and matched at the last check; a file whose size and time are the same takes its hash from there (--rehash-all reads everything). The cache holds only what the last check verified. Then, fixes: a file that is missing, a placeholder or not downloaded is downloaded (peers, then storages, as a pull does; never over a file that is there); a file with a hash mismatch under an unchanged size and time is restored as the bit-rot check restores (section 33: the recorded version is downloaded first, the damaged one kept beside it as .damaged-<date>); a changed file is never touched. After fixes the check runs again. Files on disk that the folder does not know (a .damaged- copy, a file written after the sync) do not make the mirror incomplete; they are listed and backed up as they are. Varsto's temporary files (.varsto…) are ignored. If anything is still missing or mismatched, the hold is released and the run ends without running restic (exit code 1).
  4. Describe: ROOT/VARSTO-SNAPSHOT.txt — vault short id, device name, time, mirror root, Varsto version, and per folder its name, id, live files, bytes, this device's manifest sequence and hash, the newest manifest sequence applied from every other device, and a state digest (BLAKE3 over every live path and its keyed content hash, so equal folder states have equal digests and nothing about contents is revealed); the folders left out with the reason. No keys.
  5. Back up: restic backup ROOT --tag varsto --tag vault:<short id> --host <device name> --exclude-caches --exclude '.varsto-*' --exclude '*.varsto-placeholder' --json (--dry-run with --dry-run). Its JSON status lines become a progress line on the terminal (every half second on a terminal, every 30 s otherwise; none with --json) and the progress of the activity task; the summary gives the snapshot id, files, bytes processed and bytes added. restic's exit code 3 (some files could not be read) counts as a failure: the snapshot would not be whole.
  6. Release the hold (also when anything above failed).
  7. Forget, unless --no-forget: restic forget --tag varsto,vault:<short id> --host <device name> [--keep-daily N] [--keep-weekly N] [--keep-monthly N] --prune --json (a rule of 0 is left out). Only this vault's snapshots from this device are considered; the counts kept and removed are recorded.
  8. Check the repository when due (check_every_days since the last check, or --check; never with --no-check): restic check --read-data-subset <check_subset>.

Exit codes: 0 done (also a dry run), 1 the mirror was incomplete or the run could not start (no hold, no vault), 2 restic failed (backup, forget or check; when forget or check failed after a good backup the snapshot still counts as the last good one). --json prints {result, record, completeness, repository_check, error}. The record of runs is state/restic.json: last_run, last_success ({started_utc, finished_utc, result, snapshot_id, files, bytes, bytes_added, duration_secs, message, forget: [kept, removed], scheduled}), last_check ({utc, ok, subset, message}) and runs; dry runs are not recorded.

Schedule. With schedule.every_hours = N, the background service, after each sync and the other upkeep, starts varsto restic run --scheduled as a child process (output in home/restic-run.log) when N hours have passed since the last good snapshot's start, or an hour after a failed or incomplete attempt if that is later; never while a hold is in force, never two at once (the run lock). The child talks to the service's API for the sync, the hold and the check, so it needs no passphrase. A failed run raises a desktop notification with the first line of the reason. A good snapshot older than twice the interval (at least 48 hours) raises a warning, at most once a day, and varsto restic status says so.

Not a policy condition. A durability policy (section 14) is evaluated on every device from the ledger alone, so that every device reaches the same verdict; a restic snapshot is known only to the restic device (nothing about it is in the ledger). "A restic snapshot no older than N days" is therefore not a policy condition: the restic device's status and the service warning above cover it.

Surfaces. varsto restic setup … (above; also --env-file, --restic-bin, --keep-daily/--keep-weekly/--keep-monthly, --check-every-days, --check-subset, --every-hours N or --manual, --move, --init), varsto restic run …, varsto restic status (settings, folders in and out of the mirror, the last run and the last good snapshot, the last check, the next scheduled run, a stale warning, whether a hold is in force, and whether the mirror is complete now by a quick check — presence, size and time, no hashing), varsto restic snapshots (restic snapshots --tag varsto,vault:<id> --compact, or --json) and varsto restic restore-hint (the exact export RESTIC_REPOSITORY=… RESTIC_PASSWORD_FILE=…, restic snapshots, restic ls latest, restic restore latest --target … and restic restore latest:ROOT/<folder> --target … commands, all filtered by tag and host). API (service): GET /api/restic (the status), POST /api/restic/setup {config, folders, move}, POST /api/restic/hold {token, pid}, POST /api/restic/check {token, rehash_all, fix, quick}; GET /api/service carries a one-line restic_text. The recovery kit (varsto recovery kit) ends with a note naming the restic repository and the restic device and reminding that the restic password is kept separately; it never contains that password. The completeness check, the backup, forget and the repository check are live activity tasks (section 32) of kind restic with the steps check, backup, forget and repo_check and no subject; there is no other interface.

Restore with restic only. Every snapshot holds ROOT with its absolute path: restic restore latest --tag varsto,vault:<id> --host <device> --target /tmp/restore gives /tmp/restore/ROOT/<folder>/… and VARSTO-SNAPSHOT.txt; restic restore latest:ROOT/<folder> --target DIR gives one folder. The files are the vault's plaintext files with their modification times; nothing of Varsto is needed. Putting them back into the vault is adding or copying them into a folder like any other files.

Limits.

  • The restic device needs disk space for a full plaintext copy of every mirrored folder, and it holds that copy unencrypted (restic encrypts the repository).
  • A file edited on the restic device after the sync and before the hold makes the run incomplete (changed); the next run, after a sync, takes it. Another device's edit made during a run arrives after the hold.
  • The hash cache trusts an unchanged size and modification time since the last check, as change detection does (section 7, "mtime (change detection only)"); --rehash-all and the bit-rot check (section 33) cover silent changes.
  • Only this device's Varsto is held: another program writing into the mirror during the backup is not stopped.
  • With a service running, the completeness check runs inside the service and holds its engine while it hashes (as a scrub does).
  • The repository password and the environment file are read by restic only; Varsto never reads, prints or stores the password.

Tests: varsto_core::restic::tests (backup, forget, check and snapshots arguments, tags and excludes; the environment names only the repository and the password source; environment files; check subsets and folder directory names; restic's JSON status, summary and error lines and forget's counts; the hold's lease, renewal, release and dead process; the exclusive run lock; schedule, retry and staleness; the verified-hash cache; the restore instructions), crates/varsto-core/tests/restic_mirror.rs (setup attaches every folder; a complete mirror is hashed once and then taken from the cache; a flipped byte under the same size and time passes with the cache, is found with rehash_all and restored with the damaged copy kept; a missing file and a placeholder are found, by the quick check too, and fetched; an edit after the sync is reported and never overwritten; a folder added later is attached at the next sync; a file whose blocks are lost stays not_downloaded; folders attached elsewhere are refused unless moved, a root inside a folder is refused, a chosen folder is moved in and the other left out; a hold keeps sync, pull and fetch out of the mirror while the run's own check works, and a lapsed hold stops nothing) and crates/varsto-cli/tests/restic_cli.rs (with the real restic: setup refused without a repository and --init, the password not in the configuration; a run backs up two folders and restic restore gives device A's folders back byte for byte with VARSTO-SNAPSHOT.txt, without Varsto's temporary files; a file whose blocks are lost makes the run exit 1 with no snapshot added and the hold released; forget with one daily snapshot keeps one; --no-forget --no-check; the cache spares re-reading; status, restore-hint, snapshots and the recovery kit's note). Lab scenario restic (not run automatically).

36. File analyses

Why. An assistant that reorganises files must know what they contain, and reading every file again for every question is slow on a local model. Every file can therefore carry an analysis: a text saying what the file contains, with tags. A local LLM reads a synced plain file from its local_path (section 13), records what it saw with varsto_set_analysis, and later finds files by content with varsto_search_analyses before moving them. The user can read, write and clear analyses by hand. Varsto maintains them: they are synced to every device of the folder, follow the file when it is renamed or moved, are marked stale when the file changes, and go away with the file.

Record. Per file: analysis (UTF-8 text, at most 16 KiB, trailing white space trimmed, not empty), tags (at most 32, each at most 64 characters, trimmed, repeats dropped case-insensitively, no control characters), content_hash (the file's keyed content hash when it was analysed), device and device_name (where it was written), optional by (at most 128 characters: the model or tool, as the assistant said), analysed_utc, and for merging updated_utc, updated_by (the device that last wrote the entry) and cleared (a tombstone). Paths are manifest paths.

Storage. Each device keeps the folder's merged map in state/notes/<folder>.json and publishes it as one object per folder, vault/notes/<folder>/<device>/<written utc, 20 digits>.enc: zstd-compressed JSON {device, folder, written_utc, entries: {path: entry}}, sealed with XChaCha20-Poly1305 under derive(current metadata key of the folder, "notes-record", folder) with associated data (notes-record, vault, folder, device, written_utc), and deletes its older ones. After every sync a device follows renames and deletions (below), publishes when its map changed, and every five minutes (NOTES_READ_INTERVAL_SECS) lists the folder's records and reads the newest one of every other device that is newer than the one it read before. Records of devices that are not known or were removed are ignored, entries over the limits or with invalid paths are not taken, and locked Strongrooms and backups are skipped.

Merge. Newest wins per path: the entry with the larger (updated_utc, updated_by) is kept; a device writing an entry makes it at least one second newer than the one it replaces. Clearing writes a tombstone, which wins over the older text and is forgotten after 180 days (TOMBSTONE_KEEP_SECS); a device that comes back with an older text after that brings it back. Every device republishes the merged map, so an analysis outlives the device that wrote it, also when that device is removed.

Following files. move_file (the interface, varsto_move) moves the analysis with the file. A rename or move done outside Varsto is seen by the scan as a deletion and a new file with the same content: after the sync, an analysis whose path is deleted in the merged file state moves to every live file whose content hash is the one it was written for and that has no analysis of its own; when there is none, it is dropped (a tombstone). Deleted files therefore lose their analysis at once; a file restored later is analysed again. An analysis of a path this device does not know yet (its manifest has not arrived) is kept and not shown. A file whose current content hash differs from the analysed one is reported with stale: true (analysis_stale in listings): the analysis may no longer be right, and the assistant should read the file again.

Why not the ledger. Analyses can be many and long and are rewritten as often as an assistant likes, while ledger batches are signed (about 8 KB of signature each), append-only and kept on every device; the ledger keeps facts about data. One replaceable object per device and folder costs O(analyses) bytes however often they change, and needs no ledger format change.

Privacy. Analyses describe file contents, so they are kept like other folder metadata: sealed under the folder's key, never in the clear on a storage, which sees only object sizes and times. The local copy in the device directory is plain JSON, like the folder's sync state. Members of a shared folder read and write its analyses like any device of the folder. A folder converted into a Strongroom keeps its analyses (the converting device carries them over under the new key and content hashes); a removed folder's analyses are deleted with --purge. Contents never pass through the MCP server: only what the assistant chooses to write.

Surfaces. Engine: set_analysis, clear_analysis, analysis, analyses, search_analyses (every word of the query must occur case-insensitively in the analysis, a tag or the path; every tag given must be on the file; scored tags 3, path 2, text 1 per occurrence; a snippet of about 200 characters around the first match), exchange_notes; list_files entries carry analysis (first 500 characters), analysis_truncated, analysis_tags, analysis_utc, analysis_stale, analysis_by and analysis_author. Local API: GET /api/analysis?folder&path ({analysis: null | {...}}), GET /api/analyses?folder, POST /api/analysis {folder, path, analysis, tags, by}, POST /api/analysis/clear {folder, path} ({cleared}), POST /api/analysis/search {folder, query, tags}. MCP: varsto_set_analysis {folder, path, analysis, tags?, by?} and varsto_clear_analysis {folder, path} (grant an or rw), varsto_get_analysis {folder, path}, varsto_search_analyses {query?, folder?, tags?, limit?} over one or every granted folder, returning {total, hits: [{folder, path, state, snippet, tags, stale, analysed_utc, by, score, local_path}]}. Command line: varsto analysis show|set|clear|list (set FOLDER PATH --text TEXT | --from-file FILE|- [--tag TAG]... [--by NAME]) and varsto search WORDS... [--folder F] [--tag T]..., through the service's API when it runs. Interface: the file details pane shows the analysis with tags, device, model, date and a Stale badge, with Write/Edit (a dialog with a text area and comma-separated tags) and Clear; analysed files are marked in the list, and a filter box on the Files page matches every word in the path, tags and the listed part of the analysis.

Limits. Publishing waits for the next sync and reading for the five-minute interval (varsto sync and varsto_sync publish at once); a record holds the whole folder's analyses, so a folder with very many long analyses rewrites a large object after each change; two devices that write the same file's analysis in the same second keep the one of the larger device id; the interface filter sees only the first 500 characters of each analysis (the search tools see all of it).

Tests: crates/varsto-core/tests/analyses.rs (set and read back, listings cut to 500 characters, limits, search by text, tag and path, clearing; two devices merge newest first, a cleared analysis stays cleared and the record on the storage holds no text, tag or path in the clear; an analysis follows a rename on disk by content hash and a move directly, also on the other device, is stale after an edit on both devices and is dropped with a deleted file), engine::notes::tests, crates/varsto-cli/tests/mcp.rs (an analyse grant records, lists, gets, searches by text and tag with local_path, and clears analyses, but cannot move or create files; a read-only folder takes no analysis) and crates/varsto-cli/tests/analysis_cli.rs (the commands without a service and through the service's API).

37. MCP keys

The MCP server was removed and is not part of the program.

Limits. A key limits what a client can do through the service; it is not a sandbox: a process that can read the device directory can read the session token too. Untrusted assistants belong in another account or a container that sees only the synced folders.

Tests: mcp_keys::tests (create, check, list, revoke, routes and scopes) and crates/varsto-cli/tests/mcp.rs (a key with an analyse scope on one folder against a real service: allowed route, a folder out of scope and a non-MCP route 403, move refused, MCP end to end without a passphrase, no service no access, expired and revoked keys 401, mcp key list, mcp config).

The MCP server was removed and is not part of the program. The notes below describe the keys it used to have.

38. Losing ledger copies and rebuilding them

Why. The ledger is held by every metadata storage and every full device, so one lost copy should cost nothing. Two copies matter more than the others: a device's own history, because a device that forgets how far it has signed signs a number that exists already (a fork that other devices reject), and the whole ledger, because without it no device knows where the blocks are, which policies, repair and verification read. Manifests (section 7) and blocks survive both losses; what is lost can be taken back from the storages or rebuilt from them.

Scenarios.

Loss Detected by Command line Service and interface
S1 A storage lost its ledger/ objects, or a storage is new the push lists from the newest batch it last confirmed there (pushed.json, section 6) nothing to do: the next push fills it from the first batch (or the checkpoint and the batches after it) the same, at the next sync
S2 The device's local ledger/ directory was deleted, or a file in it does not read (heads.json, pushed.json, pending.json, a batch, view.enc) when the engine opens: heads.json missing on a full device (every full device signs its enrolment when it is created), heads.json unreadable, pushed.json naming an own batch above the local head, the newest own batch missing; before every signature: one listing of this identity's objects after the local head on the first hot storage (usually empty) commands that sign stop: "...; run varsto ledger rebuild"; commands that only read print a warning on stderr restored automatically before the first sync, then a notification; a banner while it runs
S3 The device was restored from an old backup (its head is behind the storages) the listing before signing, the pull's own-identity listing (section 6), and a check of one hot storage at service start and every hour push/sync stop as for S2; varsto ledger rebuild adopts the later batches when they are this device's own, otherwise refuses a banner ("Continue from the storages") whose button runs the same rebuild; a device that holds nothing of its own (head 0) continues automatically
S4 No ledger anywhere: every storage and every device lost it; vault key, keyring, folder records, manifests and blocks remain after a sync (and in fsck, ledger status): the view holds no block claim at all while the newest manifests or snapshots name blocks; checked at most hourly, and only when there are no claims varsto ledger rebuild says so; varsto ledger rebuild --from-storage rebuilds rebuilt automatically after the restore of S2, with an activity task ledger_rebuild, then a notification
S5 ledger/view.enc is damaged or out of date it does not open, or names batches beyond the heads nothing to do: rebuilt from the batches the same

Damaged local files. A local ledger file that does not parse is never deleted: it is renamed <name>.damaged-<utc> and the engine opens without it (before this section an unreadable heads.json stopped the device from opening). A damaged pushed.json only makes the next push list each storage from the start. Events in a damaged pending.json (block holdings and verifications of single fetches, section 6) are lost; the next sync records the files it scans again, and the rest comes back with the next fetch or verification. A damaged batch file is set aside and fetched again.

Rebuild (varsto ledger rebuild, S2 and S3). In this order, signing nothing until the end:

  1. Local heads. The heads are rebuilt from the batch and checkpoint files held locally: each device's head is the end of the unbroken run of batches after its newest checkpoint, so whatever is missing after it is fetched again; fork marks are kept.
  2. Own history. Every metadata storage is listed for this identity (ledger/<device>/; cold storages are listed, but read only with --confirm-cold-read; an unreachable hot storage stops the rebuild, which the service retries). From the local head down, the local and stored batches of the same number are compared until one matches; equal hashes at a number mean equal histories up to it, because each batch names the hash of the one before. Local batches above that point that no storage holds under their number with the same content were never published: they are moved to ledger/discarded/ and their events are signed again in the next batch (pending.json). Every stored copy of a batch it compares or adopts is read: storages that hold different batches of this device under one number, or a storage holding this device's version of a batch it would set aside, mean two histories were published, and the rebuild refuses. Then the newest stored checkpoint after the local head is taken (signature by this device's key, it opens, it agrees with a local batch of its number), and every stored batch after what is held, each checked by signature and chained to the one before (prev) here or to the checkpoint's head_hash. A batch that does not chain is a fork: the rebuild refuses.
  3. Other devices. A normal pull with the rebuilt heads downloads their batches and checkpoints again.
  4. View. view.enc is dropped and rebuilt from the batches.
  5. Manifest numbers. A folder whose state names an older own manifest than the ledger or a storage holds (a device restored from a backup) goes on after the newest one, so no manifest number is published twice; that later manifest's files come back through the other devices' manifests.
  6. Enrolment. A full device of which nothing was found on any storage signs its enrolment again (batch 1).
  7. Claims (S4). With --from-storage, or in the service when no ledger is left anywhere, see below.

A refused rebuild writes ledger/fork.json; the device stays fenced across restarts (ledger_health.state = "forked") and the advice is to pair it again as a new device. Nothing is signed after a refusal, and what was adopted before it is kept.

Rebuild from the storages (--from-storage, S4). For every folder whose keys this device holds (a locked Strongroom is skipped), the newest manifest of every device is read from the hot metadata storages, and for every backup every snapshot; their chunk lists map each block object to its folder, block and size. Every hot storage that is not a transferrer is listed (chunks/, packs included); cold storages only with --confirm-cold-read. Each object found is verified before it is claimed (fetched and hashed against its name): all of them when --verify is given or when they total at most 1 GiB, otherwise up to --verify-budget-mib (default 1024) and the rest claimed unread; --no-verify reads none. A damaged object is not claimed and is queued for repair (found_by: "ledger_rebuild"). The rebuild then signs, as this device's own events, in batches of at most 2 000 events: chunk_stored for every object and storage the ledger does not already place there, chunk_on_device for the blocks of the files this device holds (not for folders kept encrypted here), manifest_published and snapshot_taken for this device's own newest manifests and snapshots, device_enrolled and folder_added where missing; it republishes this device's device and folder records if a storage lost them. Claims already in the ledger are not repeated, so it can run again. These claims are self-attested like every chunk_stored (section 6): they do not count as verified by another device until automatic verification (section 20) re-reads them from another device.

Health. ledger_health is carried by varsto status (and GET /api/status), varsto fsck (and POST /api/fsck), GET /api/service (with a one-line ledger_text) and GET /api/ledger/health: {state, problems: [{code, detail}], notes, automatic, suggestion, own_head, storage_ahead}, state one of ok, rebuild_needed, fenced, forked, no_ledger, repairing; problem codes local_ledger_missing, local_files_damaged, local_batches_missing, behind_pushed, behind_storage, fenced, forked, no_ledger_anywhere. The command line prints "rebuild recommended: run varsto ledger rebuild" (or --from-storage, or the re-pairing advice) when it is not ok. varsto ledger status (GET /api/ledger/status) lists every device's head, newest checkpoint, the batches dropped locally and its fork mark, and where its batches are held: this device and every metadata storage (count, first and last, checkpoints); it exits with 1 when a rebuild is recommended. varsto ledger rebuild [--from-storage] [--verify|--no-verify] [--verify-budget-mib N] [--confirm-cold-read] runs the rebuild (through the service when it runs, POST /api/ledger/rebuild {from_storage, verify, verify_budget_mib, confirm_cold_read}). varsto ledger and varsto ledger list list the batches held here as before. The interface shows a banner on the Overview only when the state is not ok: what happened, and a button ("Restore now", "Continue from the storages", "Rebuild now") where a rebuild helps.

Cost. Opening reads only local files. A signing action lists this identity's objects after the local head on one hot storage, which is empty unless something is wrong (one list_after request per batch). The service checks one hot storage at start and hourly. The "no ledger anywhere" check reads manifests only when the view holds no claims at all, at most hourly. A rebuild lists ledger/<device>/ of this device on every metadata storage, compares as few batches as it takes to find the agreement point, and pulls as a new device does; a rebuild from the storages lists every block object once and reads the objects it verifies.

Limits.

  • A copy restored from a backup and a live copy of the same identity cannot be told apart while the live copy has not signed anything the restored one lacks: the restored copy adopts that history and continues, and the live copy is fenced at its next signature (both then sign nothing until one is paired again).
  • When the storages pruned this device's batches between the local head and the newest checkpoint, the checkpoint is adopted on its signature alone: whether it continues the local history cannot be checked from batches that are gone.
  • Events in a lost or damaged pending.json that the next sync does not record again (verifications of single fetches) are lost; nothing depends on them but the verification counts.
  • After S4 the rebuilt claims are this device's: who wrote each object first, and the verifications other devices made, are gone; automatic verification re-establishes "verified by another device" over the following runs. Snapshots of backups written by other devices are found and their blocks claimed, but their snapshot_taken events can only be signed by their source device (its own rebuild from the storages does it); until then their snapshots are not listed for restore.
  • Members of shared folders do not hold the vault ledger: S4 is rebuilt on one of the owner's devices; a member's own lost history (S2) is restored as above.
  • Blocks named only by manifests older than each device's newest, and objects nobody names, are not claimed.

Tests: crates/varsto-core/tests/ledger_loss.rs (S1 a storage refilled and a joining device sees all; S2 a deleted ledger/ directory: signing and sync stop with the advice, status reads, the rebuild restores the own head and the other device's batches, the next batch is the old head + 1 and the other device accepts it without a fork; S2 after pruning: the own checkpoint is adopted; S2 damaged heads.json, pushed.json, pending.json set aside and noted, a missing newest batch fetched again; S3 a restored device fenced by the storage check, adopts its later batches and continues, the other device sees no fork; S3 two copies of one identity that published different batches: refused, remembered across restarts, the original undisturbed; S4 the ledger gone from the storage and both devices: restore finds nothing and re-enrols, --from-storage writes the claims, verifies everything, runs again idempotently, a new device pulls byte-identical files and fsck --verify is clean, the second device re-enrols and syncs; S4 in the service: one automatic rebuild, a damaged object not claimed but queued for repair; S5 a garbage view.enc rebuilt; ledger status), engine::ledger_recovery::tests (batches signed after a restore and never published are set aside, their events signed again, no fork) and the lab scenario ledger-loss (S2 with the command line and S4 with the service on two VMs and an S3 bucket).

39. Media-aware parallel verification and hardware-decoded thumbnails

Why. Every path that re-hashes stored data read one object, hashed it on the same thread, then read the next. On an SSD or a network storage that leaves the disk or the link idle most of the time; on a spinning disk, by contrast, parallel reads only add seeks. Verification now reads in parallel wherever the medium allows it and stays strictly sequential on spinning disks.

Medium detection (crate::media, per path, at the start of each run):

  • Linux and Android: the filesystem type of the mount holding the path (/proc/self/mountinfo, longest mount point): nfs, nfs4, cifs, smb3, 9p, ceph, glusterfs, FUSE mounts of network tools (fuse.sshfs, fuse.rclone, fuse.s3fs, fuse.davfs2, fuse.gcsfuse, …) and the like are network; tmpfs is solid-state; other FUSE filesystems (mergerfs, encfs, …), ZFS and overlay are unknown. Otherwise the path's device (st_dev; for filesystems with anonymous devices such as btrfs, the mount's source device node) is looked up in /sys/dev/block/MAJ:MIN: a partition is followed to its whole disk, a device-mapper or md device to its slaves (rotational when any slave is, so dm-crypt or LVM over a spinning disk counts as spinning whatever its own queue reports), and queue/rotational decides.
  • macOS: statfs names network filesystems (nfs, smbfs, afpfs, webdav, macFUSE); otherwise diskutil info -plist <mount> gives SolidState, cached per device for the life of the process.
  • Windows: a remote drive (GetDriveTypeW) is network; otherwise the volume is asked for its seek penalty (IOCTL_STORAGE_QUERY_PROPERTY, StorageDeviceSeekPenaltyProperty).
  • iOS: solid-state.
  • S3 and rclone storages are network; a directory storage is whatever its path is on; a pool read as a whole (by fsck --verify and automatic verification, which take whichever attached disk holds a copy) is the slowest of its attached disks, while each disk read on its own (scrub, disk check, disk insert) is its own medium.

Anything not recognised is unknown and read like a spinning disk: sequential reads are never wrong, only slower.

Readers (crate::parverify). Each place read is a lane with its own reader threads: rotational and unknown one; solid-state min(4, cores / 2) (at least one); network 8, as many as the uploader threads. One reader takes its lane's items strictly in their order, so a spinning disk is read exactly as before; a pool of hasher threads (at most one per core) hashes what the readers loaded, so even with one reader the hashing of an item overlaps the read of the next. The override is config.json verify_parallelism, a map from a storage or pool name, folder:<name>, block-cache or * (every place not named) to "auto" (the default), "sequential" or a number of readers (1 to 32), for when detection is wrong. BLAKE3's own multithreading (rayon) is not used: it would add a dependency set the program does not otherwise have, and hashing several objects at once already keeps the cores busy.

Order and bounds. Callers hand over their items in the order a sequential loop would read them (keys in order for a scrub target; the planned order for automatic verification; object by storage for fsck --verify), and get the results back in that order on their own thread, whatever order the reads complete in. Their loops are unchanged: they count progress, collect damage and advance a scrub cursor only past items they have seen, and may stop at any item (a read error, a storage that became unreachable), after which nothing more is started and whatever was read ahead is dropped unseen. A crash therefore never skips an unchecked item, budgets (planned before reading, section 33; max_blocks and max_bytes of section 20) are spent exactly, the ledger events, repair queue entries and reports equal those of a sequential run, and live activity counts as before. Memory is bounded: an item's size is reserved from 256 MiB before it is read and returned once it is hashed (an item larger than that is read alone), and nothing more than 256 items ahead of the one awaited is started. Local files are hashed as a stream with a 1 MiB buffer; a file whose recorded entry changes before its turn (restored earlier in the same run) is hashed again in turn.

Where. Bit-rot checks of storages, pool disks, local files and the block cache (section 33); fsck --verify; automatic verification (section 20); disk check (also its pass over objects the index does not know) and the verification step of disk insert (section 34). Snapshot completeness checks of backups (section 31) look only at the ledger and read nothing, so they are unchanged.

Hardware-decoded thumbnails. Video frames for thumbnails (section 10) are taken with ffmpeg -hwaccel auto -ss <t> -i <file> -an -frames:v 1 -vf scale=… -f image2pipe -vcodec mjpeg -: the seek comes before the input, so ffmpeg jumps to the nearest key frame instead of decoding up to the position; with no -hwaccel_output_format, hardware-decoded frames are copied back to system memory, where the scale filter and the JPEG encoder run. When that attempt exits with an error or gives no image, the same frame is taken once more in software; when the software attempt then works, the process remembers that hardware decoding fails here and decodes later videos in software straight away (a clip with no frame at one second, or a file ffmpeg cannot read at all, says nothing about the hardware and is not remembered). The 20-second limit applies to each attempt. config.json thumbnails.hwaccel is "auto" (default) or "off" (software only). Android and iOS make video frames with their own media frameworks and are unchanged.

Not done. Medium detection does not look through ZFS pools, mergerfs or loop devices backed by files; a medium detected wrongly is corrected with verify_parallelism, which has no command or interface yet (edit config.json). Reads across the disks of one pool read as a whole are not spread per disk. The ffmpeg path does not choose a specific accelerator; -hwaccel auto takes the first one ffmpeg finds.

Tests: media::tests (fake /sys trees: a spinning and a solid-state disk, partitions, dm-crypt over a spinning partition, md over mixed disks, dm over md, dm over an SSD; mountinfo parsing with escaped spaces, network and FUSE types, btrfs through its source device, tmpfs; device number decoding; the diskutil plist; combined media), parverify::tests (settings and their config.json spellings; one reader reads in key order; a spinning lane stays sequential and in order next to a parallel one; SSD lanes read in parallel and hand back in order; a stop is never passed and nothing after it is handed back; memory under the cap and an item larger than the cap; budget picks read exactly; a panicking reader does not hang the caller; an ignored benchmark of 2000 objects of 256 KiB), thumbs::tests (with a fake ffmpeg: hardware first, off, a hardware failure falls back and is remembered, a short clip does not count against the hardware; settings; an ignored test with a real ffmpeg making a test video with -f lavfi -i testsrc and taking its thumbnail both ways), and the unchanged scrub, disk pool, repair, upkeep and verification tests.

40. Disk bookkeeping and the next disk to dock

A pool with several disks on a shelf raises the question which one to fetch next. The device keeps per-disk bookkeeping and ranks the disks from it, without reading any disk, so the background service recomputes the ranking after every sync and whenever a disk comes or goes.

Bookkeeping. The disk registry of the pool index (section 19) also keeps, per disk, free_bytes and space_measured_utc next to capacity_bytes: the file system's free and total bytes (statvfs; GetDiskFreeSpaceExW on Windows) as measured at every attach (at most once a minute while attached), disk add, the end of the tidy, verify and fill phases of disk insert, disk check, after a fill or a push wrote to the disk (when its index is flushed), and disk eject. write_failed_utc records a write that read back wrong twice (section 34) and is cleared by the next write that reads back right. varsto disk list --json, GET /api/disks and the rows of the service summary carry, per disk:

  • free_bytes (live while attached, else the last measurement), capacity_bytes, used_bytes (by Varsto), reserve_bytes (max(reserve_percent × capacity, min_reserve_bytes)), space_measured_utc;
  • pending_deletes and pending_delete_bytes (deletions queued while the disk was away), unneeded_objects and unneeded_bytes (copies on the disk of objects the ledger no longer has a record for, or that were dropped from this pool on purpose), and reclaimable_bytes, their sum: what the next insert frees;
  • verify_after_days, oldest_check_utc (the oldest per-copy checked; 0 when a copy was never checked here, null when the disk holds nothing), copies_overdue and bytes_overdue (copies whose last check is older than verify_after_days, every copy with 0) and overdue_share (their share of the disk's copies);
  • only_copy_objects, only_copy_bytes and only_copy_overdue: objects this disk holds and no other disk of the pool, and no other storage in the ledger (transferrers do not count), and how many of those are overdue;
  • lacking_bytes: what the pool lacks that this disk could take, i.e. blocks of current files whose placement takes the pool and that the pool holds on no disk (estimated ciphertext size), plus, under a disk group rule, blocks held in fewer places than the rule asks and not yet in this disk's place; fill_potential_bytes = min(free − reserve, lacking_bytes), 0 for a retired or failing disk;
  • repair_objects (objects on the disk whose copies are in the repair queue, section 26) and fetch_objects and fetch_bytes (what a pending step of the fetch plan reads from it, section 34);
  • fsck: the last forced file system check of the disk's partition from disk-checks.json, found through disks.conf by pool and label; failing and failing_reason, set when that check left errors (uncorrected) or could not run (failed), or when write_failed_utc is set; last_seen_utc, last_verified_utc, retired.

The ledger-derived fields (unneeded_*, only_copy_*, lacking_bytes, fill_potential_bytes, repair_objects, fetch_*) are null in the service's 30-second disk listing, which reads only the pool index; disk list and /api/disks compute them (Engine::disk_report). varsto disk list [--sort name|free|used|checked|reclaimable|seen] [--reverse] prints a table (name on the sticker, pool, place, state, free / total, reclaimable, oldest check with the overdue share, last seen, file system check). Each column sorts in its useful direction: name A to Z, free, used and reclaimable largest first, checked and seen oldest first; unknown values last, ties by name; --reverse flips it.

Ranking. Engine::disk_suggestions (varsto disk suggest [--pool P] [--json], GET /api/disk/suggest[?pool=P]) scores every disk with the sum of these factors, each giving one reason in words:

Factor Points
Overdue checks 100 × s × (1 + min(late / verify_after_days, 1)), where s is the overdue share of the disk's bytes and late how far the oldest check is past the limit (a factor of 1 with verify_after_days 0)
Only copy 80 × only_copy_overdue / copies, plus 10 when the disk holds any only copy
Fetch plan 70 when a pending step reads from the disk
Repair 50 when a queued repair needs an object on it
Fill 40 × fill_potential_bytes / lacking_bytes
Reclaimable 30 × min(reclaimable_bytes / (capacity / 3), 1)
File system 25 when the last check corrected errors, plus 10 × min(days since it / 365, 1)
Unseen 20 × min(days since last seen / 365, 1); 20 for a disk this device never saw
Mailbox 60 × the disk's share of the staged bytes waiting for a target, 45 × its share of the bytes waiting to be read from a disk, each at least 5 (section 78)

X bytes overdue give at least 100 × X / used points and X bytes to free at most 90 × X / capacity, so at equal sizes a check always outranks reclaiming. Disks that are away are ranked by score, then the one seen longest ago, then label; the first is suggested when it scores at least 5, with its reasons ("«Blue 4TB»: 62 % of its copies (1.2 TB) were last checked over 180 days ago (oldest 2025-11-02); 41.0 GB can be freed; last seen 3 months ago") and the command to run next, varsto disk insert "Blue 4TB". Attached disks are scored the same way and listed apart (they need checking, not docking). Retired and failing disks are never suggested; they are listed with a warning (and with how many objects exist only on them). The JSON answer is {suggestions: {computed_utc, top, ranked, attached, excluded, overdue}, settings: {notify_overdue}}; each suggestion has pool, label, disk_id, place, attached, score, reasons: [{kind, points, text}], last_seen_utc, summary, command.

Reminder. config.json disk_suggest.notify_overdue (default on; varsto disk suggest --remind on|off, POST /api/disk/suggest/settings {notify_overdue}, a checkbox on the Storages page) lets the service raise a desktop notification at most once a week (<home>/state/disk-reminder.json) when a disk that is away has overdue copies, naming the disk, its reasons and the command.

Interface. Each pool card on the Storages page shows its disks as a table whose column headers (name, place, free space, used, reclaimable, last checked, last seen, file system) sort it, the choice kept in the browser; above it "Suggested next: «Blue 4TB» — reasons" with the varsto disk insert command and a copy button, since the interface does not mount drives. An attached disk that scores is offered with Check now (disk check), and retired or failing disks are shown with their warnings. In English, Finnish and Swedish.

Tests: crates/varsto-core/src/disksuggest.rs (overdue beats reclaimable at equal size, later checks and larger shares weigh more, only-copy risk, retired and failing disks excluded, ties by last seen with attached disks apart, fill, fetch and fsck reasons, sorting by every column, quoting), crates/varsto-core/src/pool.rs (every bookkeeping field from the index and given ledger facts, a failing write recorded and cleared, a retired disk takes nothing), crates/varsto-core/tests/disk_pool.rs (space measured at add, check, insert and eject and kept while away; overdue copies, queued deletions and what the pool lacks; the suggestion, the weekly reminder, a failed fsck excluding a disk), crates/varsto-cli/src/desktop.rs (the API) and crates/varsto-cli/tests/cli_smoke.rs (disk list --sort, disk suggest).

41. Recovery package guide and the progress bar at the top

Recovery package guide. varsto recovery guide [--format text|markdown|html] [--output FILE] (--json for the structure) and GET /api/recovery/guide (?format=text for the English text) describe what to keep outside the devices so that the whole vault can be restored after every device is lost, and the restore steps for a new device. User documentation: docs/recovery.md. The guide is built from this device's configuration and keyring only (Engine::recovery_guide, recovery_guide::build, which is pure): storages (endpoint, bucket, region, prefix, class, place; rclone remote and the section of rclone.conf; directory paths; transferrers marked as no recovery source), disk pools (disks by label and place, last seen, the copies rule, the matching disks.conf lines), Strongroom folders (enrolled key labels; one key or a software key is flagged), the organization (name, administrators), backups, the other devices and replicas, and restic settings when config.json has them (the repository with any user:password@ replaced by placeholders, the paths of the password and credentials files, never their contents or the password command). No secret is read: not the vault key, the S3 secret keys (nor the access key IDs), rclone's tokens or the restic password. Printing the kit records state/recovery-kit.json (printed_utc, key_epoch, shares), so the kit item is "done", "out of date" (printed before a key epoch change) or left to the user.

Help page. GET /api/help and varsto help-now (--json for the structure) tell where this device stands and what to do next: the phase (no_vault, locked, ready; the endpoint answers without a vault and while the vault is locked), where the data is (devices, storages with their quota and drain state, folders with the storages and devices holding them, bytes by kept copies, pool disks, trash, backups, restic), what needs attention (policies, ledger, repair and bit-rot findings, quotas, drains, overdue disks, paused or stopped service, failed snapshots, low disk space, organization approvals, recovery kit not printed or out of date), and the next steps chosen by fixed rules, most urgent first, each with why, how, an interface action (page and element or dialog) and the command line equivalent. It is built by help::build (pure) from Engine::help_inputs, which reads only the configuration, the ledger view, the folder states, the cached trash and what the service already measured: no storage is listed and nothing goes over the network. Sentences are {t, p} templates like the recovery guide's, translated by the interface.

Every sentence is {t, p}: an English template with {name} placeholders and their values. The command line renders the templates in English; the interface translates the template like any other string (ui/i18n/<lang>.json) and inserts the values untranslated, so the facts come from one place and the wording is translated with the rest of the interface. Commands are shell lines with <...> placeholders and are never translated; each varsto line is parsed with the command-line definition in the tests. The interface page (Recovery package; Settings links to it) keeps the user's ticks in localStorage per vault, prints through a print stylesheet that leaves only the checklist, and downloads the checklist as text in the page's language with the ticks.

Restore order in the guide: install and verify the release; rebuild the words from shares if needed; varsto join (it asks for the words) through a hot bucket, else a directory (an rclone-only vault mounts the remote first, since join takes a directory or a bucket); the organization's devices (an administrator adds the new device; the root words appoint administrators only among listed devices); the other storages under their old names; pool disks one at a time (disk insert with the saved disks.conf lines on Linux); folders (folder attach, Strongroom folders selective, then strongroom unlock); backups (backup restore); files only on cold storage (repair --from-cold, move --confirm-cold-read); revoking the lost devices and printing a new kit. A restic repository is listed as a way without Varsto.

Progress bar at the top. The interface shows, under the top bar, this device's task that has run for 5 seconds or more (the oldest when several, "N tasks · ..." in front): its sentence from the same templates as the Now card, the percentage and the expected finish, a determinate bar or a striped one when the total is unknown, role="progressbar" with aria-valuenow (absent when unknown) and aria-valuetext. When the last task ends it shows "Done" for a second and hides. GET /api/activity?mine=1 answers with this device's tasks only and does not make the service ask the peers; the page asks every second while the bar shows or a request the user started is running, every five seconds otherwise (on Overview and Peers the Now card's two-second answers feed it), and not while the page is hidden. New task kinds: download with step file (fetching one file: folder fetch, the interface's download, a placeholder) and export (decrypting a file of a folder kept encrypted on the device), folder_purge (deleting a removed folder's data from the storages) and strongroom_convert (re-encrypting a folder into a Strongroom or under a new key).

Tests: recovery_guide::tests, crates/varsto-core/tests/recovery_guide.rs (a vault with a directory, a pool with a disk and its disks.conf line, a cold archive bucket, a hot bucket with a prefix, an rclone remote, a Strongroom and restic settings: every item and step present, the kit status before and after printing and after a key change, a member device, and the vault key, words, passphrase, S3 secret and access key ID, restic password and repository password found in none of the text, Markdown, HTML and JSON forms), varsto binary tests recovery_guide_tests (every varsto command of guides for a bucket, directory, rclone-only and member vault parses with the CLI), crates/varsto-core/tests/activity_coverage.rs (fetching one large file and purging a folder are tasks with their totals).

42. Importing git-annex repositories, cloud drives and local directories

Why. Data that already lives elsewhere (dozens of disks holding clones of git-annex repositories, a Dropbox or OneDrive account, an old drive) should come under Varsto's management without being copied by hand, and without anything at the source being changed except, on request, emptying a local directory once its files are safe. crates/varsto-core/src/import/ reads the sources, engine/imports.rs brings them in.

One folder per source. Each source becomes one Varsto folder, recognised by its identity: a git-annex repository by the root commits of its git-annex branch (every clone shares them, so each disk holding a clone continues the same folder; a repository whose branch has two roots after two independently created repositories were merged matches either); an rclone remote by rclone:<type>:<remote name>:<path>; a local directory by dir:<absolute path>. A new folder is named by --folder, else after the source (the repository's directory name, the last path component of the remote path or "Dropbox"/"OneDrive"/"Google Drive" for a whole drive, the directory name). An existing folder of that name that holds anything else is refused; a source imported before always continues its own folder (a different --folder is refused).

The import book. Per folder, state/imports/<folder>.json holds: kind and identity; display (where it came from); repositories (git-annex UUID to description, from every uuid.log) and dead (from trust.log); imported (content id to {hash, size, utc, from, verified, sha256?}: the folder's keyed content hash of the file, where it was read from, whether it was checked against the source's hash, and for local directories the SHA-256 of what was read); damaged (content id to the copies whose content did not match: {from, path, utc, detail}); tree (path to {id, size, mtime_ns}, the source's files as last listed), tree_ref (a commit id, or the listing time) and tree_utc; missing_holders (content ids not imported, to the git-annex UUIDs whose location logs claim them); gone_at_source (paths listed before and gone now); runs (per copy of the source, the git-annex UUID or the identity: name, location, device, last time, ids present, imported, bytes, damaged, failed, and whether everything it held was in the vault afterwards); removals (local directories: {path, size, sha256, removed_utc} per removed source file) and source_path. Content ids: a git-annex key; git:<blob id> for a file committed to git itself; rclone:<hash type>:<hash>:<path> or rclone:<size>:<mtime ns>:<path> without a hash; dir:<size>:<mtime ns>:<path>.

The book is synced: each device publishes its whole book as vault/imports/<folder>/<device>/<written utc, 20 digits>.enc on its metadata storages, zstd-compressed JSON {device, folder, written_utc, book} sealed with XChaCha20-Poly1305 under folder metadata key.derive("import-book", [folder id]) with associated data ("import-book", vault, folder, device, written), deleting its older records (the pattern of the access records, section 13). Readers take the newest record per device, skip removed devices, and merge: identities, repositories, imported ids, damage and removals are unions (the first imported entry of an id is kept), the file list with the newest tree_utc wins, runs keep the newest per copy. A device continuing an import first merges the others' books, so another device can carry on from other disks. A book is published at the end of a run and every ten minutes during one. Why not the ledger: the book is replaced as a whole, can be large, and only matters to devices that import.

A run. Engine::import_run(source, options): merge the books; find or create the folder; attach it here when it is not (selectively by default: imported files are placeholders and their blocks are only on the storages; with --dest DIR without --selective, a full copy in DIR; a folder kept encrypted on this device is refused) and pull it; list the source; plan; read; save. The plan, per listed path: the folder already has it with the imported content hash: done. A different file is at the path in Varsto (edited after the import, or there before it), or the path was deleted in Varsto after it was imported and the source did not change: kept as it is and reported (Varsto's side wins; nothing at the source is lost either). An unknown file (or placeholder) in the way on this device: kept and reported. Content already imported under another path: the new path gets the same blocks without reading (linked). Content readable here: read. Otherwise: awaiting import. Every content id is read once, however many paths use it.

Reading. Content is streamed: chunked with the block size for its size, hashed with the folder's keyed hash, encrypted and written to the folder's write targets (placement and pools as for a push; a pool without an attached disk or without room is left out for the rest of the run; transferrers are not written) by four upload threads, while the source's hash is computed over the same bytes: git-annex SHA256, SHA512, SHA384, SHA224, SHA1, MD5 and BLAKE2B160/224/256/384/512, BLAKE2S256 keys and their E variants (the hash is the key name up to the first dot); git-sha1:<size> / git-sha256:<size> blob ids; the rclone hashes dropbox (SHA-256 over the SHA-256 of each 4 MiB block), quickxor (Microsoft's QuickXorHash, 160 bits, little-endian, hex), sha256, sha1, md5 and blake3. The size is checked against the key's or the listing's size. Only when everything matches does the content count: chunk_stored events for every copy written (and chunk_on_device with a full local copy), and a new version of every path that uses it (a FileState with this device's clock, as a local edit). On a mismatch nothing counts: objects this content alone put on the storages are deleted again, the copy is recorded as damaged with its key, path and the two hashes, and the paths stay awaiting import, to be taken from another disk. A read error is reported as failed. Content without a hash (WORM and URL keys, remotes without hashes, local files) is imported unverified and counted as such. --no-verify skips the checks. With a selective attachment every block must have reached a storage, or the run stops (nothing would hold it).

Awaiting import. A path whose content is not readable here is never put in a manifest: other devices see neither an empty file nor a deletion, and a device that does not know about imports sees nothing at all. It is listed by the book: varsto folder files and the interface's file list show it with state awaiting_import and the size (and time) from the source (Engine::list_files_with_pending); varsto import status --missing lists them. A later run (any device, any disk) that can read the content completes them.

Resuming. During a run, every 500 imported ids or 20 seconds, the ledger events are committed first, then the folder state, then the book is saved (so the book never names content the state lacks); the manifest and the book are published every ten minutes and at the end, also when the run fails. A run that was interrupted is simply started again: ids in the book are not read again, and an id read but not yet saved is read once more (its new version is identical and no new version is made).

git-annex. Read with git plumbing only (GIT_OPTIONAL_LOCKS=0): git config annex.uuid, git for-each-ref (the local git-annex branch and every refs/remotes/*/git-annex), git rev-list --max-parents=0, git ls-tree -r -z -l --full-tree <commit> (default HEAD; --ref a branch or tag), and one git cat-file --batch for symlink targets, small blobs (pointer files /annex/objects/<key>, files kept in git) and the logs. A key's object is .git/annex/objects/<hashdir>/<key>/<key> with hashDirMixed (non-bare) or hashDirLower (bare; both are tried), read directly in on-disk path order. No git-annex command runs; no lock is taken; nothing is written to the repository. Symbolic links that are not annexed files and submodules are reported, not imported. After a run the missing ids are looked up in the location logs (<hashDirLower>/<key>.log on every git-annex branch; per UUID the newest line, present when its status is 1; this repository and dead ones left out) and summed per repository: "Insert next: «disk-07 photos» (has 1 234 of the missing files, 210 GiB)". Location logs can be out of date, which the report says. git-annex metadata (.log.met) is not imported: Varsto has no tags on files yet.

rclone. The user's own rclone (VARSTO_RCLONE, else rclone) with the user's configuration (RCLONE_CONFIG passes through). varsto import dropbox|onedrive check the remote's type with rclone config dump, of which only type is kept (tokens are dropped unread), and print how to create one (rclone config create <name> dropbox; the sign-in is the user's own step in the browser) when it is missing. The hash type is the provider's own (dropbox: dropbox, onedrive: quickxor, drive: sha256, s3 and similar: md5, b2, box, pcloud, mega: sha1; other backends: the first of those rclone backend features lists; none for local, alias, crypt and other wrappers) unless --hash-type says otherwise. Listing: rclone lsjson -R --files-only --no-mimetype [--hash-type T], read line by line as rclone writes it. Entries without a size (Google Docs, Dropbox Paper, OneNote: documents only the provider opens) are reported, not imported; names are imported as they are (section 46; only empty, ., .. and NUL components and names starting with .varsto are reported); names that differ only in case are imported and noted. Reading: batches of up to 256 files or 1 GiB copied with one rclone copy --files-from-raw <list> --transfers N --checkers N --no-traverse into a staging directory (one process per batch: 300 small files took 0.07 s this way against 19 s with one rclone cat each, measured with the local backend), each file handed over and deleted. The staging directory is on the destination folder's filesystem, <folder>/.varsto-import-staging/batch-<pid>/ (hidden from scans like every .varsto name), or in the directory --staging DIR names; earlier versions used state/import-downloads/ in the device directory, which could fill the system disk. Before each batch the staging filesystem must have the batch's size plus 1 GiB free, else the import stops with a message naming the directory, what is free and what is needed (free some space or give --staging on a disk with room; the next run continues where this one stopped). The batch directory is removed after every batch and however the run ends, and the default staging directory with it. A file the batch did not put where its name says (rclone writes : and the like as look-alike characters on Windows) is copied once more under a plain staging name with rclone copyto. A file that does not match its hash is downloaded again once (rclone copyto) before it counts as damaged. --transfers defaults to 4. Running the import again brings changed files over as new versions and skips unchanged ones (same id); files deleted at the source are kept in Varsto and reported (there is no --mirror-deletes yet; it could move them to the trash, section 43).

Local directories. Walked in path order without following symbolic links (reported, never followed or removed), special files and unreadable entries reported, names starting with .varsto left out. A source that is, holds or lies inside an attached Varsto folder or the Varsto home is refused, as are a destination inside the source and a source inside the destination.

Removing source files (varsto import dir --remove-source, varsto import cleanup <folder>, the interface's checkbox). Opt in only; refused for git-annex repositories (a .git/annex or annex/objects directory) besides the refusals above. A file is removed only when, checked at removal time: (1) it is a regular file reached without links, with the size and modification time recorded at import, and its SHA-256 read now equals the one recorded; (2) the folder's state has that path with the imported content hash; (3) every block has a copy claimed on a storage that is not a transferrer, and one such copy was read back now and hashed to its object name; (4) the folder's policy (its own, else the default policy of section 14) evaluates to ok for this file's blocks (policy::evaluate over these blocks only, so "verified by another device within N days" must hold for each). A folder whose policy was cleared needs (1) to (3). Files that do not qualify stay and are listed with the reason ("waiting for the policy (…): 3 chunks were not verified by another device within 30 days"); they go on a later run or import cleanup once eligible. Removal deletes the file, then directories left empty up to (never including) the source root. Each removal is logged in the book. The command line lists the count and bytes and asks before removing unless --yes; import cleanup --dry-run and a plan remove nothing.

Status and completion. varsto import status [<folder>] [--missing]: per imported folder the identity, files and content ids total, imported, missing (and bytes), awaiting, damaged ids still without a good copy and damaged copies seen, files gone at the source, every copy read (name, location, last import, imported, damaged, complete), which copies to insert next, and removals. varsto import verify <folder> (exit code 1 unless complete): every path of the source's list is in the folder with the imported content, every block has a storage copy and the folder's policy is met, with the copies of the source that held nothing the vault lacks; then the source (an annex disk) is no longer needed. Nothing at a source is ever deleted by verify.

Surfaces. varsto import git-annex <repo> [--ref R] [--no-verify], varsto import rclone|dropbox|onedrive <remote:path> [--hash-type T] [--transfers N] [--staging DIR], varsto import dir <dir> [--remove-source] [--yes], each with [--folder NAME] [--dest DIR] [--selective] [--dry-run] [--json]; without --dest a folder that is not attached here goes selectively to the folder root (VARSTO_FOLDER_ROOT, else ~/Varsto/<folder>). The background service is paused during an import. Progress: an activity task (section 32) of kind import with the steps list, read (bytes) and cleanup (files), shown as a progress line on a terminal. API: GET /api/import/status, POST /api/import/dir {source, folder, dest, selective, remove_source} (the report, with the removal plan as cleanup when asked), POST /api/import/cleanup {folder, apply}. The interface's Import page and the list of every import: Import page and the job list below.

Import page and the job list. One page for every source (ui/index.html data-page="import", ui/app.js, crates/varsto-cli/src/import_jobs.rs). Step 1 is a choice of source as cards: a local folder or disk, a git-annex repository, a cloud drive through rclone (any remote, Dropbox, OneDrive), a torrent (section 81) and YouTube (section 82); step 2 shows only that source's fields: the destination (placeholders or a full copy) for the first three, the removal of source files for a local folder, the ref and "do not check content" for git-annex, the remote and parallel downloads for a cloud drive (setting a remote up, rclone config, signs in through a browser and stays a command, which the page shows); a magnet link or a .torrent file (read by the page, sent as base64), the free-space reserve, the download directory, the storage (the folder's placement, cheapest, or a storage) and the copies for a torrent; the address with a toggle "One video" / "Whole channel or playlist" (detected from the address, changeable: a watch address with list= becomes the playlist), the storage, the reserve, the spool directory and, under Advanced, the throttle with the defaults of section 82 (25-65 s, 2 s, 600K, one fragment), the format, the browser for cookies, thumbnails, subtitles and the refresh interval for YouTube. A source the device cannot run says why instead of a form: torrents on Linux only (a local transmission-daemon), YouTube not on phones, only local folders on phones, and a missing yt-dlp, transmission-daemon, rclone or git is named. Every source starts from the page: POST /api/import/start {kind, folder, ...} checks what it can at once (an address, a magnet link or the metainfo, a reserve, a throttle), answers 202 with the id of a run (run:<n>), and a thread of its own takes the service's state when it is free and calls the same engine function as the command line (Engine::import_run with a DirSource, AnnexSource or RcloneSource, Engine::torrent_add, Engine::youtube_add); nothing is run through the command line. The run is in the list meanwhile (waiting while a sync or another import holds the state, running, then done with the report or failed with the error); a torrent or YouTube run gives way to its job once the job is registered. The service steps running torrent and YouTube jobs every 20 s between syncs as well (only when the state is free and the service is not paused). GET /api/import/jobs (answered without the state) is {jobs, platform, tools, defaults}; jobs is one uniform row per import, unfinished first: {id, kind, folder, title, source, state, text, done, total, unit (files | videos), bytes_done, bytes_total, current, speed, last_error, retry_utc, already_stored, conflicts, failed[{id, title, reason, attempts, next_try_utc, gave_up}], finished, pending, started_utc, updated_utc, actions[]}, for torrent jobs (torrent:<info hash>), YouTube jobs (youtube:<id>), the page's runs (run:<n>) and imports another command of this device reports as activity (activity:<n>, no actions); progress, the speed and the file in hand come from the import's activity task when one runs for the folder. POST /api/import/jobs/<id>/{pause,resume,remove,retry} (retry: YouTube) answers 202 at once and does the action when the state is free (the row shows it as pending); remove of a finished or failed run takes it off the list, a running run cannot be stopped half-way (running the import again carries on). Every change of the list is the event import.jobs (section 32's event stream); the page reloads the list on it and on import activity, and polls every 5 s while something is unfinished (30 s otherwise). The page shows In progress at the top: per row the source's kind, state, a progress bar, files or videos done of the total, bytes, speed, the current item, the error and the time of the next try, the YouTube counts of videos already stored and the failed videos with their reasons, and the row's actions; finished runs below it, then the imported folders with status and the removal of safe files as before. English, Finnish and Swedish; the same page on phones (one column) and in dark mode.

Limits of the page: a directory, annex or cloud import holds the service's state while it runs (as import_run always has: the rclone source downloads inside it), so syncs wait for it; reads of the interface are answered from the last answers meanwhile. Torrent and YouTube steps run under the state as the service's upkeep does. Tests: import_jobs::tests (the rows of torrent and YouTube jobs and of a finished run, finding jobs by prefixed and bare names), desktop::tests::import_jobs_are_one_list_answered_without_the_state (the shape of GET /api/import/jobs while the state is held, an action queued and shown as pending, refusals, a queued action failing on a locked vault), crates/varsto-cli/tests/torrent_cli.rs and youtube_cli.rs (import jobs for both kinds), scripts/test/import-ui.test.js (what a YouTube address names, the page's wiring), and the lab scenarios torrent-spool and youtube-spool (import jobs list).

Limits.

  • A git-annex repository's content is matched by key; files committed to git directly are read from the git objects. Special remotes, the git-annex journal (uncommitted log changes), metadata and unlocked files' working-tree copies are not read (an unlocked file's content is read from the annex object store, where git-annex keeps it).
  • Location logs may be stale or missing for disks never synced with this clone; the suggestions are hints.
  • Names are kept as they are (section 46): 12:30.jpg from a git-annex repository or a cloud drive keeps its name. Only names that are not UTF-8, have an empty, . or .. component or a NUL, or start with .varsto, are reported as not imported. The report counts the names a Windows device writes under a mapped local name (mapped_on_windows, N name(s) ... hold characters Windows does not allow on the command line); that is information only.
  • The source's file list is kept in memory and in the book (about 200 bytes per file); a listing of millions of files needs that much memory.
  • One run at a time per folder; a run holds the engine.
  • Content whose hash cannot be checked (WORM and URL keys, local files, remotes without hashes) is imported as read.

Tests: crates/varsto-core/tests/import_annex.rs (a repository with locked, unlocked, WORM, git-only, duplicate and nested files built with git-annex; a clone on a second "disk"; an interrupted run resumed; a damaged object on disk one taken from disk two; awaiting files listed with the disk that has them; another device continuing from disk two without reading anything already imported; the result byte-identical through a third device; import status, --missing and verify; a name clash refused), crates/varsto-core/tests/import_rclone.rs (the local backend with a temporary configuration: Dropbox hashes checked, a re-run reads nothing, a changed file comes over, a deleted one is kept and reported, a wrong hash retried and reported with its objects deleted, a case-only difference noted, a missing or mistyped remote; 10 000 files ignored by default), crates/varsto-core/tests/import_dir.rs (removal only when eligible, a file changed after import kept, files waiting for another device's verification removed once it happened, empty directories pruned and the root kept, a link never followed, refusals, dry runs), and unit tests of keys, hash directories, logs, pointer files, Dropbox and QuickXor vectors (from rclone), lsjson lines, times and book merging.

43. Trash (0.0.1-alpha.14)

Superseded by section 77 (storage format 3): trash entries are the device's trash record stream and the settings are the settings record (kind 18), not <utc>-named objects (77.7, 77.17). Kept as the history of format 2.

What it is. A file deleted on any device of the vault is kept in the vault's trash for a number of days (the trash days: 30 unless set otherwise, per vault and per folder) and can be restored on every device that holds the folder key, from the storages. Before this the only trash was the local copy a device keeps when it applies another device's deletion (section 7); that copy remains, follows the same days, and is the fast way to restore when present.

Records. A trash entry is the last live version of a deleted file: path, size, modification time, content hash, block list (chunk id, object name, size, key epoch), deletion time (UTC), deleting device and the Lamport clock of the deletion; its id is the first 16 bytes of BLAKE3 over a fixed label, folder, path, device and clock. Each device keeps the entries of the deletions it found (a scan that sees a file gone) and the entries it took out of the trash (removals: id, time, device, restored or purged, deletion time) in one trash record per folder, vault/trash/<folder>/<device>/<written utc, 20 digits>.enc: zstd JSON sealed with XChaCha20-Poly1305 under derive(folder metadata key, "trash-record", folder), associated data trash-record, vault, folder, device, time; written to every metadata storage when it changed (with the push that found the deletion), the device's older records deleted, the newest one per device read (like access records, section 13). Readers open it with any metadata key of the folder (members of a shared folder too), skip devices they do not know or that were removed, and accept an entry only if the writer is the deleting device, its id recomputes and its path and block sizes pass the manifest checks (section 28). A file whose content is still in the folder under another path when the deletion is found (a rename or move) is not trashed. Why not the tombstones of the manifests: a tombstone carries no blocks and is replaced as soon as a new file takes the path, while the trash must keep the deleted version also then.

The trash of a folder is the union of the entries of every device's newest record, less the entries any device removed, less those older than the trash days. On an owner device the removals written by members of a shared folder (other people) do not count, so another person cannot take entries out of the owner's trash. A record keeps an entry, and a removal, seven days past the entry's expiry so every device sees it go; then the writer forgets it.

Settings. vault/trash-settings/<device>/<utc>.enc holds the days, the days per folder and the trash storage (its name on the writing device and its identity, vault/storage-id.json, so devices that name it differently find it); JSON sealed under derive(folder-record key, "trash-settings"), associated data trash-settings, vault, device, time; the newest record of a trusted device wins. Members of shared folders cannot read or change them and keep 30 days. Days run from 1 to 3650; a folder set to 0 follows the vault again.

Blocks of the trash are in use. Until an entry expires or is purged its blocks count like those of a current file:

  • a data move of a whole folder (section 23) moves them too (a move of idle files does not);
  • removing a storage (section 20) copies first every block of the trash that would otherwise lose its last copy (one copy is required; the folder's copy rules are for current files);
  • fsck counts them as referenced (not as unreferenced objects) and counts a claim on a cold storage, which it does not list, as a copy;
  • a device that holds a file with the same content again, or a restored file, writes the blocks back to the folder's storages: a copy on the trash storage does not keep a current file's block off them (WriteTargets::wants).

Policies (section 14) and repair (section 26) are about current files; the trash's blocks are not counted there.

Dropping blocks. When an entry expires or is purged, its blocks are queued on the device that sees it (state/trash/drops.json). Before blocks are judged the device pulls every attached folder, so a file restored or created again elsewhere is known. A queued block is dropped only if no current file, no version still to be downloaded, no entry still in the trash and no other folder (a backup included) uses its object; then chunk_dropped is recorded for every storage of this device that holds it, the batch is sealed and pushed, and only then is the object deleted where no newer claim exists (as for data moves, section 23). On a cold storage whose price model has a minimum storage duration (varsto storage price), a block is not deleted before that many days after it was stored there; it waits in the queue. Folders not attached here, or that could not be pulled, are judged later. Each device drops what is on its own storages; one that never runs leaves its copies in place (space, not data, is lost).

Trash storage. varsto trash set --storage NAME names a storage of the vault, typically a cheap or cold one. It takes no blocks of current files (unless a folder's placement names it). The upkeep copies each block that only trash entries use to it (from the block cache, a warm storage or a peer), checks the copy (read back from a warm storage; by name only on a cold one, as data moves do), records chunk_stored (and chunk_verified when read back), records chunk_dropped for this device's other warm storages, seals and pushes, and then deletes those copies. Copies on other cold storages stay. A device that does not have the trash storage keeps the trashed blocks where they are. Setting a trash storage runs the upkeep at once.

Restore. varsto trash restore <folder> <path>... [--to DIR] [--confirm-cold-read] restores entries: a path names a file or every entry under a directory; per path the newest deletion. A file goes back to its own path when that is free (no current file, no version waiting, nothing on disk or as a placeholder), otherwise to name (restored).ext, name (restored 2).ext, ...; with --to under that directory of the folder (the part of the path below the selected path's parent kept). Nothing is overwritten. The content comes from this device's local trash copy when one has the entry's size and content hash, otherwise from the blocks (block cache, peers, the storages), each checked against its object name and chunk id, the whole file against the content hash. A block that no warm storage of this device and no cache holds but a cold storage does needs --confirm-cold-read; without it the restore stops before reading anything and says how much is on which cold storage and what reading it costs (trash_restore_plan). The restored file is written into the folder under its local name (section 46; local trash copies are looked for under the local form of their names too), or into the block cache in a folder kept encrypted here, with the deleted version's modification time and pushed as a new version, so every device gets it and its blocks go back to the folder's storages; the entry is recorded as restored and leaves the trash everywhere; the local trash copy used is removed.

Purge. varsto trash purge <folder> <path>... | --all [--yes] removes entries for good (removal "purged") and drops their blocks as above at once, on this device's storages; other devices drop theirs at their next upkeep. Local trash copies of the entries are deleted.

Upkeep. Engine::trash_upkeep runs in the background service once a day after a sync (varsto trash upkeep runs it by hand): read every device's records and the settings, queue the blocks of entries that expired or were purged since, forget long-expired entries in this device's record and publish it, move trashed blocks to the trash storage, drop what is queued, and delete local trash copies older than the trash days.

Commands, interface, activity. varsto trash list [--folder F] [--json] (path, size, when and by which device deleted, expiry, whether a local copy exists, whether restoring needs a cold read), varsto trash status (settings, totals, bytes per storage, local copies, next expiry, blocks waiting), varsto trash set [--days N] [--folder F --days N] [--storage NAME | --no-storage], restore, purge and upkeep as above; the API is /api/trash (GET, ?folder=), /api/trash/status, POST /api/trash/restore-plan, /api/trash/restore, /api/trash/purge, /api/trash/set, /api/trash/upkeep. The interface has a Trash page (under More on phones): search and folder filter, restore to the original place or another directory (a dialog with the fee warning before a cold read), delete permanently, empty the trash (typed confirmation), and the days and trash storage. Activity kinds trash_restore, trash_purge and trash_move.

Limits.

  • Only deletions found by a version with the trash are recorded; deletions made earlier are only in the local trash copies.
  • A file overwritten by a new version is not in the trash: only deletions are; the version history (section 50) keeps replaced versions.
  • A Strongroom conversion or re-key (section 17) moves the folder to a new id; its trash stays with the old id and is not reached, and the old blocks are deleted by the conversion.
  • Removing a folder with --purge deletes its trash records with the rest; without --purge they stay on the storages.
  • The race of any garbage collection remains: a device that wrote a file with the same content as a purged or expired entry, and did not upload a block because the ledger showed it stored, finds the block missing only after the drop is in the ledger; its next push writes it back (upload_missing checks every current file against the ledger). Restored files are not affected (their entries are never queued).
  • Repair (section 26) does not rewrite copies on the trash storage, and filling a pool disk takes current files only.
  • Members of a shared folder see the owner's trash of that folder and can restore from it; their purges and restores do not take entries out of the owner's trash, and they cannot change the settings.
  • A device removed from the vault: its records are no longer read, so its deletions leave the trash (their blocks stay until another device's storage removal or folder purge).

Tests: varsto_core::engine::trash::tests (restored names, path selection, checks of other devices' entries), crates/varsto-core/tests/trash.rs (a deletion on device A is listed on device B at once with device and expiry; B restores from the storages after losing its local copy, byte for byte, to the original path, and A gets the file back while the entry leaves both trashes; a path taken again gives name (restored).ext; a whole directory restores into another directory; a rename is not trashed; the local trash copy is used when the storage lost every block and is cleared after the trash days; a whole-folder data move takes trashed blocks along, storage removal copies them first, fsck counts them, and the file restores afterwards; a folder's own days postpone expiry, after the vault's days expired blocks are dropped (recorded in the ledger) while blocks a current file uses again and the kept file's blocks stay; purging one entry and emptying the trash on B leave only the kept file's blocks and empty A's list; a cold trash storage receives no current blocks, takes the trashed ones off the warm storage, B's restore is refused without the cold read and succeeds with it, the restored blocks are back on the warm storage, and a purge waits for the cold minimum duration until a later upkeep; the daily schedule) and crates/varsto-cli/tests/trash_cli.rs (list, status, set, restore of a directory, purge with and without confirmation, upkeep).

44. Storage quotas and draining a storage

Why. Switching providers means emptying one storage onto the others, and that must never leave a folder with fewer copies than its policy asks for, not even for a moment. Some storages also have a limit (an S3 bucket with a quota, a plan of so many terabytes) that Varsto must not run into.

Shared storage settings. A storage's quota and drain are vault-wide: a quota only one device knows would be broken by the others' uploads, and a storage being emptied must stop receiving blocks from every device. Prices stay a device's own estimate in config.json (section 20); these settings are published like a folder's placement (section 23). Every change is one sealed record, vault/storage-settings/<storage key>/<device>/<updated_utc>.enc (20-digit time), on every storage that holds records, drained ones included; in an organization it is signed as placement records are (storage-settings-signature over vault, storage key, device, time and ciphertext hash; the signed envelope's folder field carries the storage key). It is encrypted under the folder-record key of the current epoch with AAD storage-settings-record + vault id + storage key, and contains {storage, name, device, updated_utc, settings: {quota_bytes?, quota_objects?, drain?: {phase: draining|drained, started_utc, driver, remove_when_empty, budget_bytes_per_day?, confirm_cold_read, drained_utc?}}}. The newest record of a storage wins on every device (pull_registry); records from devices that are not trusted, or, in an organization, from non-administrators when members may not add storages, are ignored. A device keeps its copy in config.json (storage_settings, by its own storage name, with the record time, also when the settings are empty so an older record does not come back).

The storage key names a storage the same way on every device although names are local: the storage identity of section 20 (vault/storage-id.json) when it can be read (cached in state/storage-keys.json), the pool identity for a disk pool, and otherwise (a cold class, offline) a keyed hash of the name under a key derived from the vault key. While any storage has settings, every device publishes its storage names with their identities (section 20) and keeps the other devices' names for its own storages (state/storage-aliases.json), so that usage and drains count copies the ledger records under another device's name for the same storage.

Quotas. quota_bytes (and optionally quota_objects) is the most Varsto keeps on the storage. Usage is counted from the ledger: every object claimed there and not dropped, once, under any device's name for the storage, plus an estimate of the records, ledger batches, manifests and thumbnails (the size of this device's ledger plus 64 KiB and 8 objects per folder, or what varsto storage quota <name> --measure found by listing the storage and reading its records). Writers keep 1 % of the quota free (usable = quota - quota/100) and take room per object as they plan writes:

  • a push writes a block to every storage its placement takes that has room; a storage without room is skipped, the push report names it (storages_full: "storage X is at its quota (Y of Z)") and the block goes to the folder's other storages; when none has room the block stays on this device (chunks_without_storage_copy) and the next push tries again;
  • a data move (section 23) keeps a block whose new storage has no room, and so does moving trashed blocks to the trash storage (section 43; a trash storage being drained takes none); storage removal (plan_storage_removal) copies only to storages with room; repair re-writes existing copies and is not limited;
  • the status (storage list, /api/storage/quotas) shows used_bytes, used_objects, percent, and state ok, warning (90 % or more) or full; the background service notifies once when a sync found a storage at its quota, and a policy that is at risk or violated lists the full storages among its reasons ("... : new blocks cannot go there").

Disk pools keep space free on each disk instead (section 19) and transferrers empty themselves, so neither takes a quota.

Draining. varsto storage drain <name> publishes drain with phase: draining and this device as the driver. From then on no device writes new blocks there: WriteTargets::wants refuses a storage being drained or drained, for pushes, backups, repair, disk inserts and data moves, and a placement that names only storages being drained falls back to every storage. The storage stays readable. The driver works through the blocks in runs (the service runs one after each sync, at most 4096 blocks or 2 GiB per run, and the command line runs one at once unless --background), within budget_bytes_per_day (bytes copied to other storages per UTC day; the first block of a day always goes):

  1. Every block some claim places on the storage, under any device's name for it (section 20 identities), is worked out from the ledger. The copies that stay are the other claimed copies on storages this device knows (transferrers excluded, replicas included). The folder's copy rules (min_copies, min_per_place; not the verification window) are capped at what the copies met before, the storage being drained included, exactly as for a move (section 23): a drain never makes a policy weaker, and does not make a policy it did not meet a reason to keep a copy elsewhere.
  2. A block of a current file (or a known snapshot) is copied to every storage the folder's placement takes (drained storages excepted) that lacks it and has room under its quota; a block nothing uses any more only needs one copy elsewhere. Then the rules must hold for the copies that stay plus the planned ones, and there must be at least one; otherwise the block stays and the reason is reported ("folder X needs 2 copies in external storage (S3 and the like) and no other storage there can take them: add another cloud storage or lower the policy", with "(storage Y is at its quota (...))" when a quota is why). A block whose only readable copy is on a cold storage being drained stays until confirm_cold_read.
  3. Blocks that only need dropping come first (no egress), then the others oldest first. The ciphertext comes from the files on this device (re-encrypted, which is deterministic), the block cache, another readable storage, or the storage being drained. Each new copy is written, read back and hash-checked (a cold target is checked by name only), and recorded (ChunkStored, ChunkVerified); the rules are checked again with the copies actually made; then the copy is recorded as dropped under every name it was claimed under (ChunkDropped). Each group of 64 blocks is sealed and pushed as one ledger batch before any of its objects is deleted from the storage, and an object still claimed there, or claimed on a storage this device cannot match to one of its own, is not deleted.
  4. When no claim places a block on the storage, the block objects still there that no claim counts are deleted (drops recorded by an interrupted run), and every other object on the storage except its identity (vault/storage-id.json) is copied to every other storage that holds records and lacks it: ledger batches, manifests, records, snapshots and thumbnails. If there is no such storage, or a record can be read only there (a cold class), the drain waits and says so. Then phase: drained is published: no device writes to the storage or reads records from it any more (metadata_storages leaves it out). With remove_when_empty the driver then removes it from its configuration as storage remove does (StorageRetired); otherwise it stays, empty and marked drained, until the user removes it or stops the drain to use it again.

--stop (POST /api/storage/drain {name, stop: true}) publishes the settings without drain: the storage takes new blocks again, and blocks already moved stay where they are (a dropped copy is not written back while another exists, section 23). Running storage drain <name> on another device makes that device the driver. Progress is kept by the driver in state/drains.json (bytes when it started, bytes today, bytes moved, the reasons blocks wait); varsto storage drain status and GET /api/storage/drains show phase (draining, blocked when the last run moved nothing because of those reasons, drained), blocks and bytes left, percent by bytes, an estimated finish (the pace so far, at most the daily budget), the budget and the reasons. The live activity of a run is kind drain, steps copy and records (section 32).

varsto storage drain <name> --plan and GET /api/storage/drain-plan?name= show the plan without changing anything: blocks and bytes on the storage, blocks that are only dropped, blocks copied first with the bytes per receiving storage, bytes read from the storage itself with their egress and retrieval cost from the price data (section 20), what the storage still bills for its minimum storage duration, days at the daily budget, whether every folder's policy holds without it and why not, and notes (cold storage, quotas, cold targets). The interface shows the same in the Drain dialog of each storage row, with the budget, "remove when empty" and, for cold storage, the cold-read confirmation; the row then shows the drain's progress bar and a Stop button. The Prices and quota dialog sets the quota, and the row shows a usage bar against it.

Commands and API. varsto storage drain <NAME> [--plan] [--stop] [--remove-when-empty] [--budget-gb-per-day N] [--confirm-cold-read] [--background], varsto storage drain status, varsto storage quota <NAME> [--bytes 1TB | --clear] [--objects N] [--measure] (sizes in kB, MB, GB, TB or KiB, MiB, GiB, TiB), --json on all of them; storage list shows the quota, use and drain state. GET /api/storage/quotas, POST /api/storage/quota {name, bytes ("1TB", bytes, or "" to clear), objects, clear}, GET /api/storage/drains, GET /api/storage/drain-plan?name=&budget_gb_per_day=&confirm_cold_read=, POST /api/storage/drain {name, stop, remove_when_empty, budget_gb_per_day, confirm_cold_read} (the service runs it after its next sync).

Limits.

  • Usage is an estimate between --measure runs: records are estimated, objects inside packs count one each, and another device's claims count under this device's name only once that device has published its storage names (it does at its next sync while any storage has settings). Two devices writing at the same moment can together pass the 1 % margin; the next push of each sees the claims and stops.
  • A quota is not a provider's hard limit: a write the provider refuses is an ordinary write error.
  • A device that has not synced since a drain started can still write a block there; the driver sees the claim and moves it, also after the drain finished.
  • The policy rules a drain keeps are the copy rules; the verification window (verified_within_days) starts again for the new copies, which the drain itself reads back (a check by the writer, not by another device).
  • Copies on storages this device does not know (another device's own storage under a name that maps to nothing here) are not counted as copies that stay, and their objects on the storage being drained are not deleted.

Tests: varsto_core::storage_settings::tests (sizes, the margin, records open only for their storage and writer and, when required, signed), crates/varsto-core/tests/storage_drain.rs (a drain copies every block to the new storage, reads it back and records the check before the drop, the policy is never weaker after any batch, the records are on the other storages, a drained storage takes no writes, stopping makes it an ordinary storage again; a policy that cannot be met elsewhere stops the drain with "add another cloud storage or lower the policy" and nothing leaves until a storage is added; a drain resumes after the device stops and removes the storage when empty; a quota sends what does not fit to the other storage, makes blocks wait when no storage has room, puts the reason in the policy report and lets them go when there is room; a drain fills a storage only up to its quota and says so; quotas and drains reach a device that names the storages differently, which respects them, and that device's copies are moved by the other device's drain).

Placement and drain agree. A drain is refused while a folder's placement still names the storage (by name, or by its place when it is the only open storage in that place); the message names the folders and says to change their placement first, in the CLI, the API and the interface alike. In the other direction a storage being drained or drained cannot be named by a placement (set_placement refuses it), so a folder is never left with a target that takes nothing. A drain also ends by dropping every location the view still lists on the storage, claims or a verification made by a device that had not yet seen the drop, for every file: a verification alone, after a drop, no longer brings the storage back into the view (ledger::apply_drops).

45. Local debug logs

Each program writes a local debug log (see docs/architecture/logging.md): home/logs/varsto-<component>.log (service, desktop-app, cli, tray, mcp, ffi-ios, ffi-android, app), lines of <RFC 3339 UTC time with ms> <LEVEL> <component>[<pid>/<thread>] <module>: <message> key=value…, rotated at 10 MiB into varsto-<component>.<n>.log.zst (n = 1 newest … 4), at most 64 MiB in the directory (phones: 4 MiB, 3 rotated, 24 MiB). Directory 0700, files 0600. Default level debug; --log-level, then VARSTO_LOG, then log_level in config.json (a level or a filter like debug,varsto_core::p2p=trace).

The logs are local files of the device, like state/: they are not part of the vault format, never written to a storage, never synced or served to peers, and their format may change between versions without migration.

Never in a log: key material of any kind (vault, device, folder, share, replica, peer, signing and KEM keys), passphrases, recovery words and shares, the service token, MCP keys, share, replica and organisation tokens, storage secrets (S3 secret access keys, rclone tokens), restic passwords, security-key secrets, plaintext file contents, decrypted manifests and other decrypted metadata. Allowed: file and folder names and paths, device and storage names, endpoints and buckets, object names, sizes, timings, peer addresses, error messages. Secret types redact themselves, fields with secret names are redacted, and every line passes a scrubber for registered secrets, registered keys (by keyed hash), token shapes and recovery-word runs.

Diagnostics bundle (varsto log bundle, POST /api/logs/bundle): a zstd-compressed tar varsto-logs/… of the log files (decompressed, scrubbed again), the end of service.log and restic-run.log, about.json, status.json (the service's /api/state, when it runs) and config.json.

Restic settings are not secrets to the scrubber. The restic password itself never reaches a log (tests/log_secrets.rs). The repository string (section 35), which may carry user:password@ for REST and SFTP repositories, and the password command are configuration: they are in config.json and so in the diagnostics bundle, the repository string appears in restic-run.log and in log lines about restic runs, and the recovery guide (section 41) prints the repository with user:password@ replaced by placeholders but names the password command's existence. Registering the repository's userinfo and the password command with the scrubber, and redacting them in the bundle, is an open hardening item (S8). API: GET /api/logs → {dir, level, source: flag|env|config|default, bytes, files, can_open}, POST /api/logs/level {level} (saved as log_level), POST /api/logs/open (computers). Mobile library: void varsto_log(int level, const char *msg) (1 error … 5 trace) writes an app line under module app.

Tests: varsto_core::logging (filters, format, timestamps, rotation and cap, tar, scrubber shapes and field names) and crates/varsto-core/tests/log_secrets.rs (every secret type through every log macro form, in the files and in a bundle; file modes).

The scrubber also cuts the login of every URL, and a support bundle carries a redacted config.json: section 60.

46. Original names and local name mapping

File names are kept as they are everywhere: in manifests, imports, conflict copies, the interface and the command line. A device whose filesystem does not take a name writes the file under a local name and maps it back when it scans, so the vault path never changes because of one device's filesystem.

Vault paths (names::check_vault_path, also util::check_rel_path). A vault path is UTF-8, at most 4096 bytes, relative, with / as the separator; every component is a non-empty name other than . and .., and no NUL appears. Anything else is part of a name: :, \, ?, *, ", <, >, |, control characters 1-31 and 127, a trailing dot or space, a Windows device name (CON.txt), emoji, combining characters. A manifest with any other path is refused (section 28). Unicode normalisation is not changed: a scan records the bytes the filesystem returns (a Linux or APFS name stays as written, NFC or NFD; HFS+ returns NFD, so a NFC name written there comes back NFD and looks renamed, as it did before this section). Names that are not UTF-8 are not synced (a scan skips them; imports report them). Object keys on storages keep the stricter rule (util::check_portable_rel_path: no :, backslash, control character or Windows device name), because every platform writes them as they are.

Showing names. The interface and the command line show names as they are, : and \ included; control characters and the direction overrides U+202A-U+202E and U+2066-U+2069 are shown as \u{..} escapes (names::display, show in the command line, showName in the interface), so that a name cannot move the cursor, recolour a terminal or pass for another name. --json output, the API and MCP carry the names unchanged.

The Windows mapping (names::windows_encode_component, windows_decode_component). Per name component: each of < > : " \ | ? * and each control character 1-31 is written as the private-use character U+F000 + its code (: is U+F03A; the scheme of Cygwin, Samba and the Windows SFM driver, so Explorer shows a look-alike character); a trailing dot or space is written as U+F02E or U+F020; and a Windows device name (CON, PRN, AUX, NUL, COM1-COM9, LPT1-LPT9, COM¹-COM³, LPT¹-LPT³, CONIN$, CONOUT$, any case, with any extension, ignoring spaces before the first dot) gets the last character of the device name mapped the same way: CON.txt is written CO\u{F04E}.txt, nul is written nu\u{F06C}. Decoding turns U+F000 + c back into c only for the characters the encoder maps (those above, ., space, ASCII letters and digits, $ and ¹²³), never into / or NUL, so it is the exact inverse on every name without private-use characters. On Windows a scan therefore reads private-use characters U+F001-U+F0FF in local names as escapes: a file a person names a\u{F03F}b on Windows is stored as a?b. That interpretation applies on Windows only; on Linux and macOS such characters are ordinary characters.

Per platform. Linux and Android (ext4 and the like): names as they are. Windows: the Windows mapping, and case-insensitive. macOS: names as they are (: is legal at the POSIX layer and Finder shows it as /), case-insensitive on the default APFS and HFS+ volumes. Whether a folder's filesystem ignores case is probed once per folder directory and process: an entry already in the directory is looked up with its case swapped (the same file, by device and inode, means case-insensitive; nothing is written, so a backup's source is left alone), and an empty directory gets a probe file .varsto-case-probe-<random> that is looked up in upper case and removed at once (exFAT and FAT on Linux are case-insensitive too). A directory that does not exist yet, or cannot be written, gets the platform's default (case-insensitive on Windows and macOS). A Linux disk formatted exFAT, FAT or NTFS refuses some names Linux takes: before a name with a character Windows forbids or a trailing dot or space is written, its directories are created and an empty file is tried; when that fails with EINVAL (or ENOENT) the path falls back to the Windows mapping. Storages are not affected (objects are named by hashes).

Case collisions. On a case-insensitive filesystem two vault paths that differ only in case (or, folded, in Unicode normalisation: names are compared lower-cased and NFC) would be one file. The first one written keeps its name; the next gets a local name with (2) ( (3), ...) before the extension (photo.jpg becomes photo (2).jpg next to Photo.JPG), and a directory takes the spelling already on disk (dir/y.txt is written into an existing Dir/). The pull report lists such files (renamed_locally: "photo.jpg -> photo (2).jpg"), the command line and the interface's log show them; nothing is lost, and editing the renamed copy edits the vault file it stands for. Which one of the two gets the suffix depends on the order they arrive in.

The local name map (names::LocalNames, local_names in state/<folder>.json, absent when empty). Per folder and device: vault path -> local path (both with /), for every file whose local path differs from its vault path (mapping, fallback, collision, a directory's other spelling) or whose local name a scan would decode differently. Placement (LocalNames::place, used for every file Varsto writes into a folder: pulls, placeholders, conflict copies, fetches, imports, uploads through the API, moves, restored backups) reuses a recorded local path, else computes one as above and records it. A scan maps every local path back through the map, else through the platform's decoding (Windows) or as it is; a file that a scan maps through decoding but that would be written under another name is recorded too. So a mapped file never looks deleted, added or renamed. Records go when the file is deleted (pulled or scanned) or found gone. Every reader of a local file (thumbnails, uploads, the viewer, MCP local_path, list_files' disk, the file-manager actions through locate_path, scrub, the restic mirror check, wipes) goes through the same map. Trash copies and exported files use the platform's mapping; damaged copies set aside by scrub are named from the local name and reported by their vault name.

Limits. The probe tells only whether the folder's top directory ignores case; a case-sensitive directory below a case-insensitive root (or the reverse) is not detected. A Linux exFAT driver that silently drops trailing dots instead of refusing them makes such a file look renamed. Case folding follows Rust's Unicode lower-casing and NFC, close to but not exactly the tables of NTFS and APFS. The map lives on one device: another device does not know this one's local names.

Tests: names::tests (vault path rules, traversal refused, the Windows mapping round trip and injectivity on the affected set, device names, case collisions with directories and normalisation twins, the exFAT fallback with a simulated refusal, symbolic links refused), crates/varsto-core/tests/original_names.rs (:, \, ?, *, ", <, |, trailing dot and space, CON.txt, nul, a control character, emoji and both normalisations of a name round-trip between two Linux devices byte for byte; a simulated Windows device writes the mapped names, reads them back without a change, updates and deletes through them and stores a name typed with an escape decoded; a simulated case-insensitive device keeps colliding files under (2) and edits flow back; traversal refused), the import tests (12:30.jpg and others keep their names from git-annex, a directory and rclone; the staging directory is on the destination folder's filesystem or where --staging says, removed afterwards, and a batch that does not fit stops the run with the free-space message).

47. Folder safety: the folder marker, the mass-deletion guard, send-only and receive-only folders

Why. A synced folder whose disk is not mounted leaves an empty mount point. A scan of it found every file gone, and the deletions reached every device (only a missing root stopped the scan). The same happens when a script or a slip deletes most of a folder at once. And some devices should take part in a folder one way only: a camera phone that sends its pictures but should never get the others' edits, or a laptop that follows a folder without publishing what is changed on it. These ideas come from Syncthing (folder marker, send-only and receive-only folders); crates/varsto-core/src/engine/folder_safety.rs implements them.

The marker. Every folder mounted with plain files has a file .varsto-folder in its root: JSON {"varsto": "folder", "folder_id": "<hex>", "name": "<name>", "note": "..."} (the name is informational). It is written when the folder is created or attached here, when the restic mirror attaches it, and moved with the directory (the restic mirror's move, Strongroom conversions rewrite it with the new folder id). Like every .varsto* name it is never a file of the folder (scans skip it, restic excludes it). Before anything reads the directory as the folder's state or writes into it (pull, push, fetch, placeholders, writes through the app), the root must carry the folder's own marker:

  • missing (an empty mount point, a deleted marker, a missing root): the folder is paused on this device with "folder X: the marker .varsto-folder is missing at — is the disk mounted? Nothing is synced until it is back; varsto folder repair-marker X if the directory is right";
  • another folder's id, or unreadable: paused the same way ("belongs to another folder () — is the right disk mounted?").

A paused folder is not scanned, so nothing reads as deleted, and nothing is downloaded into it. sync reports the pause per folder (PullReport.paused: folder, kind marker-missing / marker-other / deletions-held, message, path) and goes on with the other folders; pull, push and fetch return it as an error. status shows it per folder (paused), the service notifies once per pause, and the interface shows a banner with "The directory is right" (repair-marker). Once the marker is back the folder resumes by itself.

Older mounts. A mount from before markers has none. This device records in state/<folder>.marked that the marker was seen; until then a root without a marker is adopted (marked now) when no current file of the folder is known yet, or when at least half of its current files (or their placeholders) are in the directory; otherwise it is paused as missing (the upgrade happened while the disk was not mounted). Folders kept encrypted on this device hold their files in the block cache under the vault home, so the rule does not apply to them; a backup's source is only read and is not a mount.

The mass-deletion guard. Per folder and device (FolderMount.deletion_guard, absent = default): deletions are held when more than percent % of the folder's current files and more than min_files files, or more than max_files files, go at once (default: more than 50 % and more than 100, or more than 1000; percent of 100 or more turns the share rule off, max_files 0 the count rule; enabled: false turns the guard off).

  • This device's scan finds more files gone than that: the deletions are not made versions (nothing is published), the folder's state records them (FolderState.held: paths, the folder's file count, time) and the folder is paused. Files that come back (a disk mounted again, files moved back) leave the hold; when none is left the folder resumes by itself. varsto folder confirm-deletions X makes them deletions (published with the next sync; files back meanwhile are left out); --discard restores them from the storages or peers (in a selective folder an unpinned file comes back as a placeholder; files that cannot be fetched now stay held).
  • Another device's file list would delete more files here than that: the deletions of that manifest are held with the remote tombstones, the manifest is not applied and the device's last_seen is not advanced (so nothing of it is lost), and the folder is paused. confirm-deletions applies the held deletions (the files go to this device's trash as usual); the manifest is then read again and its deletions match. --discard keeps the files: each one gets a new version of this device that includes the tombstone's version vector, so it is newer than the deletion and every device gets the file back.

Modes. Per folder and device (FolderMount.mode: normal, send-only, receive-only; varsto folder mode X <mode>, the interface's Sync settings dialog):

  • send-only: the device publishes its changes but applies no other device's change to its files. Pull still reads their manifests; every remote state that would change something here is kept in FolderState.not_applied (and files waiting for a copy move there too); entries this device's own changes have caught up with are dropped. Status counts them (remote_not_applied), varsto folder pending X lists them, and varsto folder override X (interface: "Override: make everyone match this device") replaces each with a new version of this device's state (its content, or a deletion for a file it never had) whose version vector includes the remote one, published with the next sync. Back to normal, what waited is merged and applied at the next pull.
  • receive-only: the device applies other devices' changes but publishes none of its own. Its scan notes added, modified and deleted files in FolderState.local_changes instead of making versions (their blocks are not offered either); the published manifest stays the vault's state. Status counts them (local_changes), varsto folder revert X (interface: "Revert: restore the vault version") moves changed and added files to this device's trash and fetches the vault's versions (deleted ones are fetched back). A remote change of a locally changed file replaces it the same way, the local copy going to the trash first. Back to normal, the noted changes are scanned again and published. Not offered for folders kept encrypted on this device.

With the other features. A folder this device holds as a read-only member (section 55) is guarded by the viewer's own scan, which keeps local changes aside instead of noting them: send-only is refused for it and receive-only adds nothing. On a receive-only device, metadata changes (section 49) are not published either, and a version (section 50) is not restored into the folder. Paths the ignore rules cover (section 48) are neither noted nor counted by the mass-deletion guard. A file that waits for disk space (section 53) after its local change went to the trash shows as a local deletion until it arrives. Local names (section 46) are used for the marker checks, the held deletions and restores. A folder that pauses is announced once as a folder.paused event (section 54).

Download order. When many files are fetched, the newest (by the manifest's modification time) come first: a pull orders each manifest's files newest first (and files waiting for a copy, and what waited in send-only mode), the first sync after attaching included; turning selective sync off fills placeholders newest first; folders kept encrypted here fill their block cache newest first; restoring held deletions and reverting go newest first. A fetch plan from pool disks keeps its grouping by disk (one disk after another, as chosen) and copies the blocks of the newest files first on each disk; its files are written newest first. Repairs of storage copies keep their own order.

Commands and interface. varsto folder repair-marker X, confirm-deletions X [--discard], mode X [normal|send-only|receive-only], override X, revert X, pending X (what waits for a decision; who changed what is varsto changes, section 57), deletion-guard X [--percent N] [--min-files N] [--max-files N] [--off] [--default]; with the service running they go through it (POST /api/folder/safety with folder and action), otherwise the command syncs the folder after the change. varsto status and sync print pauses and waiting changes. The interface shows one banner per folder that is paused or has changes waiting, with the actions and a list of the files, a "paused" and a mode pill, and a Sync settings dialog (mode, deletion guard). English, Finnish and Swedish.

Tests: crates/varsto-core/tests/folder_safety.rs (an empty mount point without its marker publishes no deletion, pauses the folder and resumes with nothing lost; a missing root; another folder's marker until repaired; pull and fetch write nothing into an unmarked root; older mounts adopted only when their files are there; a local mass deletion held, discarded and restored, released when the files come back, confirmed and then held again on the other device until confirmed there, or discarded there and restored on every device; deletions below the threshold and a per-folder guard; send-only ignores remote changes, still publishes and overrides; send-only back to normal; receive-only keeps local edits unpublished and reverts with the local copies in the trash, a remote update of a locally changed file, back to normal publishes; downloads newest first through a recorded download order, for a pull and for placeholders filled).

Camera upload folders (Android). The camera card creates its folder send-only (POST /api/folder {name, plain, mode: "send-only"}): the phone publishes the photos and never applies other devices' changes into it. Unless the user ticks "Keep plain files on this phone" the folder is kept encrypted on the phone (section 10), as every folder added on a phone is; and freeing an uploaded file no longer turns an encrypted folder selective (a freed file turns a plain folder selective, as before), so the folder shows as an ordinary one.

48. Ignore rules

Why. Folders collect files nobody wants on every device: editor swap files, .DS_Store, build output, a phone's thumbnails cache. Rules say which paths Varsto leaves alone (crates/varsto-core/src/ignore_rules.rs, engine/folder_rules.rs).

Where rules live. A .varstoignore file at the folder's root is an ordinary file of the folder: it is scanned, published and pulled like any other, so every device shares it (it is the one .varsto* name that is synced; restic leaves out only .varsto-*). A .varstoignore in a subdirectory applies to that subtree, its patterns relative to its directory. Device-local patterns are kept in this device's configuration (FolderMount.ignore_local, a list of lines) and never leave it. Files of more than 256 KiB are read up to that size; lines longer than 1024 bytes are skipped.

Syntax (gitignore): one pattern per line; blank lines and lines starting with # are skipped; trailing spaces are dropped unless escaped (\ ); ! re-includes; \# and \! are literal; a trailing / matches directories only; a leading or middle / anchors the pattern to the directory of its file, otherwise it matches a name at any depth below it; * matches any run of characters within one path component, ? one character, [...] a class (ranges, ! or ^ to negate; an unclosed [ is literal); ** as a whole component matches zero or more components (**/x, a/**/b), a trailing /** everything inside (not the directory itself); \ escapes the next character. Matching is case-sensitive, on manifest paths (/ separators).

Deciding. The last matching pattern of a source decides. Sources by precedence, highest first: this device's local patterns, then the .varstoignore of the deepest directory containing the path, up to the root's. The first source with a match decides. A path inside an ignored directory is ignored whatever patterns say about the path itself (it cannot be re-included, as in git): the directories above a path are decided first. The matcher is written for Varsto (about 300 lines with tests) rather than taken from the ignore crate, which would bring regex, globset and crossbeam.

Effect. Only on devices that keep plain files of the folder (not a folder kept encrypted on a device, section on block caches, and not a backup's source, which has its own selection).

  • Scan: ignored directories are not entered and ignored files are not read; they are neither added nor updated. A path in the folder's state that the rules cover is not deleted when it disappears here: ignored files are not published and not deleted elsewhere. A file already in the vault that becomes ignored stays in the vault as its last version: this device no longer updates it (its edits and its removal stay local) while other devices still may. PushReport.files_ignored counts ignored entries (an ignored directory once).
  • Pull: an incoming version (or deletion) of a path this device's rules cover is not written: it is kept aside in the folder state (ignored_remote, path to the newest such version) and reported once per version (PullReport.files_ignored). When the rule no longer covers it (a rule removed, a .varstoignore changed), the next pull applies the kept version if it is newer than this device's (a file made here meanwhile stays, and the other devices resolve the conflict when they see it).
  • The rules in force are read at the start of each scan and pull: a .varstoignore that arrives in a pull applies from the next one.

Suggestions. The interface offers, never applies by itself: .DS_Store, Thumbs.db, desktop.ini, ~$*, *.tmp, .~lock.*#.

Surfaces. varsto folder ignore <folder> [--list] [--add P]... [--remove P]... [--local] (without --local the root .varstoignore is edited: a line added at the end or every equal line removed; the change is published by the next sync; with --json the listing {folder, synced, nested, local, suggested, applies_here}); varsto folder check-ignore <folder> <path> (a trailing / or an existing directory asks about a directory) answers {ignored, pattern, source, line, matched_path} (source is the .varstoignore path or local; matched_path the path or the ignored directory above it). API: GET /api/folder/ignore?folder=, POST /api/folder/ignore {folder, synced?, local?} (text of the root file, an empty text removes it; the local list), POST /api/folder/check-ignore {folder, path, synced?, local?} (the texts being edited stand for the saved ones: a preview). MCP keys have no access to these routes. The interface: Files, the folder's settings button: a text box with the shared file, the suggestions as buttons that add a line, a list of this device's own patterns, and a "test a path" box; English, Finnish and Swedish.

Limits. Case-sensitive everywhere (also on case-insensitive filesystems). Rules are not applied to what other devices publish into the vault: they only decide what this device sends and writes. A device that keeps the folder encrypted ignores nothing.

Tests: ignore_rules unit tests (names at any depth, comments and escapes, negation and last-match-wins, no re-inclusion under an ignored directory, anchoring, ** forms, directory-only patterns, wildcards and classes, nested files, local precedence, lazy reading from disk, line editing); crates/varsto-core/tests/ignore_and_metadata.rs (ignored files neither published nor deleted elsewhere, a file that becomes ignored kept in the vault, check-ignore and a preview, local rules not synced, incoming ignored files skipped and reported once, a held-back version applied once the rule is removed); crates/varsto-cli/tests/cli_smoke.rs (the commands with --json).

Why. Syncing only content loses what makes a script executable, a link a link, or a Finder tag a tag. Varsto syncs the metadata each device can represent, and never lets a device that cannot represent something erase it (crates/varsto-core/src/fsmeta.rs).

Record. FileState has an optional meta (absent: nothing known; manifests without metadata are unchanged):

"meta": {"v": 1, "mode": 493, "symlink": "../shared/config",
         "xattrs": {"user.xdg.tags": "cmVk"},
         "owner": {"uid": 1000, "gid": 1000, "user": "ana", "group": "ana"}}

Every field but v is optional, and absent means not known, never none ("xattrs": {} means known to have none). v is the record version (1); a device that meets a higher version neither applies nor changes the record: it carries it unchanged in its own versions. mode: the permission bits, rwx for user, group and others (0o777); setuid, setgid and sticky are neither recorded nor applied, so no device can plant a setuid file on another (a record with them is accepted, the bits are masked when applied). symlink: the entry is a symbolic link with this target, exactly as read (relative targets stay relative; an absolute target, starting with /, \ or a drive letter, is synced as given and flagged in listings, since it may point elsewhere on another device); a link entry has size 0, no chunks, and content_hash = keyed hash (folder hash key) of "varsto-symlink\0" ‖ target, which no file content can share. xattrs: name to value in standard base64. owner: numeric ids and, where known, names.

Change identity. A file's identity for sync is its content hash together with meta: a scan that sees the content unchanged but the metadata changed makes a new version (this device's clock in the version vector) with the same chunks, so nothing is uploaded or downloaded (PushReport.metadata_changed); a pull whose content hash matches the file on disk only applies the metadata. Manifest::files_hash covers meta, so such a version is published. In a merge, concurrent versions with the same content (deleted alike, same content hash) whose metadata differs pick the later change deterministically (higher modified_clock, then device id) with the merged version vector and no conflict copy; other concurrent edits merge as before (section on manifests).

Observing without flapping. Per file the local index keeps meta_seen, what this device last saw on disk. A scan observes the entry (fsmeta::observe: only what this system can see and the folder's settings allow) and publishes, per property, the observed value only when it differs from meta_seen; otherwise the vault's value stays (fsmeta::combine). A property this device cannot see (setting off, no support, a filesystem that does not keep it) is never part of what is observed, so its value in the vault is carried into this device's new versions unchanged: such a device never publishes its removal. After a pull writes a file and its metadata, meta_seen is what the disk shows afterwards, so a filesystem that silently drops a property (mode bits on exFAT, FAT, many phone storages) does not report the difference back as a change. Attributes this system cannot hold (a com.apple.* name on Linux) are kept from the vault's value when the observed set changes. A metadata change on such a device publishes only the property that changed.

Platform rules.

Linux macOS Windows Android, iOS
permissions mode bits mode bits read-only flag only: marking read-only clears the write bits of the vault's mode, clearing it sets the owner's write bit; other bits kept mode bits (where the storage keeps them; otherwise carried)
symbolic links created created created when allowed (Developer Mode or the privilege), else a note created
extended attributes user.* only all synced names none (carried) none (carried)
ownership as below as below none (carried) none (carried)

A folder kept encrypted on a device has no plain files: metadata is carried, links are kept in the vault only.

Symbolic links. Links are never followed: the scan reads them with readlink (walkdir without following, so a link to a directory is one entry and nothing below it is scanned); a target that is not UTF-8 or longer than 4096 bytes leaves the link out (not published, not deleted). A link is written as a link (<path> replaced atomically by renaming a new link over it; a directory is never replaced), deleted by moving the link itself to the trash. Where the system refuses a link, a JSON note <path>.varsto-link ({varsto: "symbolic link", target, hint}) is written instead and reported (PullReport.links_as_notes); the scan treats the note as the link being present (neither a change nor a deletion). Every path Varsto writes, removes or reads is refused when a directory above it inside the folder is a link (fsmeta::join_entry, check_no_link): reading a file through Varsto (interface, MCP, viewer) refuses a link or a path through one, so a link received from another device cannot expose files outside the folder. Thumbnails are not made for links. Dangling links sync like any other. With links off on a device, its links are left out (neither published nor deleted), and incoming links are kept aside like ignored files (PullReport.links_skipped) and created once links are turned on.

Extended attributes. Never synced: com.apple.quarantine, com.apple.provenance, com.apple.macl, com.apple.lastuseddate#PS, com.apple.rootless, com.apple.decmpfs, com.apple.system.Security, the code-signature names com.apple.cs.* listed in fsmeta, and the security., system., trusted. and com.apple.system. namespaces (per-device noise, or writable only by the system or root). Read and written without following links (llistxattr and friends on Linux, XATTR_NOFOLLOW on macOS); not on links. At most 64 KiB of names and values per file: a file with more has its attributes left as the vault has them (not observed). Applying makes the synced attributes this system can hold equal to the record (removing ones the record lacks); others on disk are left alone.

Ownership. Off by default per folder (ownership), because ids rarely mean the same on two devices. Observed as uid, gid and their names. Applied (lchown) only when running as root (names first, ids where a name is unknown here) or when both names exist here with the same ids as recorded; otherwise ignored (nothing reported). As a non-root user that means the change is a no-op or refused quietly.

Settings (per folder, per device, FolderMount.meta, written only when not default): permissions (on), symlinks (on), xattrs (on), ownership (off). Off: the property is neither observed nor applied on this device; the vault's value is carried. With permissions off (or without mode bits here) a file whose content is downloaded gets the mode a new file gets on this device (0666 less the umask), not the vault's. varsto folder set <folder> [--permissions on|off] [--symlinks on|off] [--xattrs on|off] [--ownership on|off] (without options: shows them); GET /api/folder/settings?folder= ({settings, caps}, what this system can represent) and POST /api/folder/settings {folder, permissions?, symlinks?, xattrs?, ownership?}; the interface: checkboxes in the folder's settings, and the file details show the link target (flagged when absolute), permissions (rwxr-xr-x (0755)), owner and attribute names. varsto folder files shows -> target for links.

Validation. A manifest entry's meta is refused when mode has bits beyond 0o7777, a link target is empty, longer than 4096 bytes or has a NUL, an attribute name is empty, longer than 255 bytes or has a NUL, a value is not base64, names and values exceed 64 KiB, an owner name is empty, longer than 256 bytes or contains NUL, / or :, or a link entry has content.

Elsewhere. Backups record metadata like folders (default settings) and a restore creates links as links and applies permissions and attributes this system can hold. The restic mirror counts a link as complete when the link in the mirror has the recorded target. Scrub's repaired copies and fetched placeholders get their metadata applied.

Failure model.

  • A device that cannot represent a property, or has it off, cannot remove it from the vault; but it also cannot change it: a chmod on Windows other than the read-only flag is lost, and so is an attribute added on a phone.
  • Concurrent metadata changes on two devices: the later one wins everywhere, without a conflict copy; the earlier one is lost (content never is).
  • A filesystem that drops what is applied keeps the vault's value without reporting it; the file on that device simply differs. metadata_problems in the pull report lists what could not be applied (a refused chmod, setxattr).
  • A malicious device can publish links pointing anywhere and any permission bits: Varsto never follows links itself and never applies setuid, setgid or sticky; making a file executable or world-writable is possible, as with any synced change. Trust in other devices of the vault is as before (section 28).
  • The ownership rule cannot tell whether a name means the same person on two machines; that is why it is off by default.

Tests: fsmeta unit tests (a property taken only when it changed here, Windows read-only mapping, attributes this system cannot hold kept, newer records carried, ownership as non-root left alone, validation, mode text) and manifest (concurrent metadata changes need no conflict copy); crates/varsto-core/tests/ignore_and_metadata.rs: a chmod syncs with chunks_uploaded == 0 and chunks_downloaded == 0 and is applied, nothing flaps back; a device simulated without mode bits (Engine::set_meta_caps) edits the content and the mode survives; settings off: incoming permissions not applied (also to a file whose content is downloaded) and local ones not published, ownership off by default and published when turned on; links round trip (relative, absolute and flagged, dangling, to a directory, out of the folder) and are never followed (a read through a link or through a linked directory is refused), a changed target and a deleted link arrive, links off on a device; Linux user.* attributes round trip, change and removal (skipped where the temporary filesystem has none), and attributes off keep them.

50. Version history (0.0.1-alpha.14)

Superseded by section 77 (storage format 3): the history days travel in the settings record (kind 18) and replaced versions in the trash records (77.7, 77.17). Kept as the history of format 2.

What it is. When a file is replaced by a new version, the previous version is kept as a history entry and can be restored on every device that holds the folder key, from the storages, on a thinning schedule (Syncthing's "staggered versioning"): every version for an hour, then at most one per hour for a day, one per day for 30 days and one per week until the history days (90 by default, per vault and per folder, or off). 90 days is three times the trash days: a mistaken overwrite is often noticed later than a deletion, and the thinning keeps it cheap (one version per week after the first month). The machinery is the trash's (section 43): the same records, the same liveness rules for blocks, the same trash storage, upkeep and restore checks.

Entries. A history entry has the shape of a trash entry: path, size, modification time and content hash of the replaced version, its block list, when it was replaced (UTC), the replacing device, the Lamport clock of the new version and (new, also in trash entries) the device that wrote the version (author, shown, not checked). Its id is computed like a trash entry's from folder, path, replacing device and clock; a deletion and a replacement never share a clock, so ids do not collide. The device that writes the new version records the previous one: a scan that finds a file's content changed, a write into a folder kept encrypted here (record_cached), a restore. A device that applies another device's new version records nothing (the writer did), and a conflict keeps the losing version as a conflict copy as before. A version whose blocks are on no storage and in no cache of the writing device (written and replaced between two uploads) cannot be restored and is not recorded. Backups (section 31) keep no history.

Records. Entries are in the device's trash record of the folder (vault/trash/<folder>/<device>/<utc>.enc, section 43) under versions; readers accept them with the same checks as trash entries (writer is the replacing device, the id recomputes, path and block sizes pass the manifest checks). Records written before this section have none; older readers ignore the field. The history of a folder is the union of every device's newest record, revoked devices aside, thinned as below.

Thinning. For each path separately, with t the time a version was replaced and now the device's clock: a version is kept if now - t is under an hour; otherwise only if no newer version (by time, then clock, then id) was replaced in the same clock hour (t / 3600) while it is under a day old, the same UTC day (t / 86400) while under 30 days, or the same week counted from the Unix epoch (t / 604800) until the history days; older ones are let go. The buckets are fixed and nested, and a version's bucket only grows as it ages, so a version let go never becomes kept again, and every device that knows the same versions keeps the same ones (history_kept). A version this device has queued for dropping is never kept again, also if its clock goes back.

Settings. The vault's history days and the days per folder are fields of the trash settings record (vault/trash-settings/<device>/<utc>.enc, section 43): history_days (90 when absent, 0 = off) and folder_history (folder id → days, 0 = off). Off stops recording new versions; versions already kept age out on the vault's schedule (90 days when the vault is off too). Days run from 1 to 3650. Members of shared folders cannot read or change them and keep 90 days.

Blocks. Content-defined chunking (section 4) means a version shares every unchanged block with the current file and the other versions: only the changed blocks cost space, and they are stored once. The blocks of kept versions count as used exactly like the trash's (section 43): whole-folder data moves take them along, removing a storage copies first those that would lose their last copy (one copy required), fsck counts them as referenced, and the trash storage takes the blocks only versions or trash entries use (copied, checked, recorded, then dropped from this device's other warm storages). When the upkeep finds versions let go since its last run, their blocks are queued and dropped as in section 43: only if no current file, version still to download, trash entry, kept version or other folder uses the object; sealed and pushed before deletion; never before a cold storage's minimum duration. A device forgets its own let-go versions from its record seven days after it first saw them go.

Restore. varsto history restore <folder> <path> <version|time> [--to DIR | --as NAME] [--confirm-cold-read]. The version is named by its id (six or more characters) or a time in UTC (YYYY-MM-DD meaning the end of that day, YYYY-MM-DD HH:MM[:SS]): the version current then, i.e. the first one replaced after it (the nearest kept one when the history thinned it). Without --to/--as the version becomes the current file at its path: the folder is synced first (so a change on disk not yet seen is recorded and uploaded), the restore stops if the file changed after that, the content is fetched and checked against block names, chunk ids and the content hash, then written over the file (into the block cache in a folder kept encrypted here) and pushed as a new version, so the replaced current version becomes a history entry itself and nothing is lost; restoring the current content is refused. --to DIR writes it under that directory of the folder (as name (restored).ext when taken); --as NAME writes it beside the file under that name (or at that folder path) and is refused when the name exists. Blocks only a cold storage holds need --confirm-cold-read (history_restore_plan tells how much, where and what it costs). Activity kind history_restore.

Commands, interface. varsto history <folder> <path> lists the versions newest first (short id, time replaced, size, the bytes it does not share with the current file and newer versions, author and replacing device, whether restoring needs a cold read); varsto history set [--days N | --off] [--folder F] (with --folder, --days 0 follows the vault again); varsto history status (settings, the schedule, versions and the bytes of blocks only versions use per folder and per storage); restore as above. The daily trash upkeep (varsto trash upkeep) does the history's upkeep and counts the versions let go. API: GET /api/history?folder=&path=, GET /api/history/status, POST /api/history/restore-plan, /api/history/restore, /api/history/set. The interface shows a Versions list in a file's details on the Files page (restore over the current file, or as a copy under a new name; a dialog with the fee before a cold read), and a Version history card beside the trash settings (on or off, days, one folder's own days or off, versions and extra bytes per folder and storage).

Limits.

  • Only replacements made by a version with the history are recorded; a file changed several times between two scans keeps only the version the scan saw.
  • A file replaced while its old version was never uploaded (changed again before the push) has no entry for that version.
  • A device whose clock runs ahead lets versions go early on its own storages; other devices list them until their clocks pass the same point (as for trash expiry).
  • Thinning follows the replacement times, not the versions' modification times.
  • Renames and moves are not replacements; a file moved over another file's path replaces that file only when the scan sees new content there.
  • Turning the history off does not delete the versions already kept; they age out.
  • A device where the folder is receive-only (section 47) refuses to restore a version into it: the restored file would be a local change it does not publish. A send-only device restores as usual.
  • The limits of section 43 for Strongroom conversions, folder removal and members apply to versions as to trash entries.

Tests: varsto_core::engine::history::tests (times in UTC, ties within a bucket, expiry, clocks ahead), crates/varsto-core/tests/history.rs (an overwrite on device A is listed on device B with author and replacing device; B restores it over the current file byte for byte, the replaced version is listed, A gets the restored file; restoring the current content is refused; a restore under a new name and into a directory, refused over an existing name; a version picked by date; a small edit of a large file stores few new blocks and the status counts only the replaced ones; the thinning schedule with a simulated clock keeps exactly every version of the last hour, one per hour, day and week, nothing past the days, and never brings back a version let go; with a simulated clock thinned versions' own blocks are dropped while kept versions', the current file's and shared blocks stay, then everything expires and only the current files' blocks are left, fsck clean; a cold trash storage takes the blocks only versions use, B's restore asks for the cold read and succeeds with it; a folder with the history off keeps no versions, its own days and back to the vault's, the vault off; a folder kept encrypted on a phone keeps the version an app write replaced and restores it).

Code: crates/varsto-core/src/qr.rs (links, compact forms, parts, rendering, decoding); varsto-cli (share qr, open-link, the interface's QR and scanner); the native shells register the scheme.

Request codes (section 24), sealed tokens (vst1/vst2) and the nine-digit pairing codes (crates/varsto-core/src/pair.rs) were passed by copy and paste. They can now travel as varsto:// links, shown as QR codes and scanned with a camera, or opened from a message.

Links.

Link From → to Value
varsto://share/request?c=<value> recipient → owner the request code: public KEM key and bound name, nothing secret
varsto://share/token?t=<value> owner → recipient a sealed token, which only the requesting device opens
varsto://pair?c=<nine digits>[&a=<host:port>,…][&rv=<32 hex>][&rvu=<url>] your device → your new device the pairing code (the SPAKE2 password), the offer's addresses, the token of its rendezvous registration (section 83.3) and, when that is not the default service, the rendezvous base URL it is registered at

The scheme is matched without regard to case; the path must be one of the three; every parameter must be known and appear once; a fragment is refused; the whole link is at most 16 KiB. Addresses must parse as socket addresses; rv= is 32 lowercase hex digits (16 bytes); rvu= is a percent-escaped rendezvous base URL that the joiner would accept as its setting (https://, plain http:// only to a loopback or LAN address, no login, query or fragment), written only when the offerer's rendezvous is not https://varsto.net/rv, so a link to the default service stays short. rv= and rvu= are new with the rendezvous (section 83): versions before it refuse a link that carries it (an unknown parameter), so an old app cannot read a new pairing link or its QR code; the code typed by hand still works with them. c=/t= take the compact value below or the text form (vsr1.…, vst2.…, percent-escaped), so a hand-made link works too. Everything that took a request code or a token takes the link instead: share create --to, share accept [--token] <token or link> (now also positional), pair join --code <digits or link> (the link's addresses best first, then discovery by the code; section 68), POST /api/share/fingerprint, /api/share/create, /api/share/accept. Plain tokens (<vault>.<folder>.<key>.<name>, the folder key itself) are never put in a link or a QR code.

Compact values. A request code is 2,437 characters of hex and a sealed token about 2,800; in a QR code's byte mode that needs a version-38 code at error correction L. The value is therefore binary, Base32 encoded (RFC 4648, upper case, no padding), so that the QR encoder puts it in alphanumeric mode (5.5 bits a character, 69 % of byte mode's cost for Base32; hex in alphanumeric mode would cost 23 % more):

  • request: format (1) | key length (u16 BE) | key (X25519 32 + ML-KEM-768 1,184 bytes) | name (UTF-8, the rest); decoding rebuilds exactly vsr1.<hex>[.<name>], so the fingerprint is the same on both sides;
  • token: version (1 or 2) | vault id (u8 length) | folder id (u8) | KEM algorithm (u8) | KEM ciphertext (u16, 1,120 bytes) | sealed payload (u16) | folder name (UTF-8, the rest); the encoder checks that decoding gives back the very same text (the token's AEAD binds the text of its fields).

Sizes (measured by tests/qr_invites.rs; a vst2 token with one owner device and no later epochs; every later folder key adds about 110 Base32 characters):

Payload Text form Link One QR code As parts (560 Base32 characters each)
request code, name "Robin" 2,443 1,984 version 27, 125 modules, ECC L 4 codes, version ≤ 16, ECC M
sealed token vst2 2,802 2,289 version 29, 133 modules, ECC L 5 codes, version 16, 81 modules, ECC M
pairing code with one address 11 46 version 4, 33 modules, ECC M (never split)

Error correction and parts. A code uses ECC M when that still fits version 25, else L: a screen is flat and sharp, and capacity matters more than damage tolerance. One code is shown by default so that a phone's own camera app can open the link (and Varsto with it). A dense code is read easily by a phone from a laptop screen; a fixed-focus laptop camera reading a phone screen may fail, so the interface offers "Camera cannot read it? Show smaller codes" and varsto share qr --parts shows the same link as a sequence of smaller codes, one every 0.9 s. A part is varsto://share/<kind>?p=<index>.<count>.<group>&<c|t>=<slice>: the slices concatenated give the value, group is the first four bytes of BLAKE3 of the whole value (hex), which tells sequences apart and checks the reassembly. 2 to 64 parts; the scanner collects them in any order, starts over when a part of another sequence appears and reports "2 of 5 parts". Only Varsto reads parts; a part opened by the system is refused with a hint. A value that does not fit one version-40 code is always shown in parts.

Why not a rendezvous. A short code with a locator and a key, the payload fetched elsewhere, was considered: the recipient has no access to the owner's storage before it accepts, and the LAN pairing listener serves one offer of one vault. Both payloads are public-safe as they are (the request code is a public key; the sealed token opens only with the requester's private key), so size was the only problem, and the compact form with optional parts solves it without a server, a listener or a lifetime to manage.

Threat model.

  • Whoever photographs a request code learns a public key and a name. Swapping it on the way gives other fingerprint words; the owner still compares the six words with the requester over another channel before sealing, as before, and the interface shows the words under the code and in the confirmation (section 24).
  • Whoever photographs a sealed token cannot open it: it is bound to the requester's KEM key, and the requester's device also checks the fingerprint the owner confirmed. This is why only sealed tokens get QR codes.
  • Whoever photographs a pairing code within its ten minutes can pair one device into the vault, exactly as with the digits read off the screen: the offer serves one device, closes after three failed attempts, and the offering device names the device it sent the vault to. Show it only to the device being added.
  • A link opened from outside (a web page, a message) only fills in a form or opens the share dialog: nothing is sealed, accepted or paired without the user's own confirmation, and a request link still goes through the fingerprint comparison. POST /api/link and every other endpoint need the session token as before.
  • Camera frames are read in memory by POST /api/qr/scan (one grey byte a pixel, at most 4096×4096, or an image file such as a screenshot) and dropped; nothing is stored or logged. Where the browser has BarcodeDetector the page decodes frames itself. The decoder is rqrr (pure Rust); codes are drawn by qrcode as SVG.

Interface. The request code (Accept a shared folder), a newly sealed token (Shared page) and an open pairing offer (Devices, Add a device) are shown as QR codes next to the text, with the fingerprint words under a request code. "Scan QR code" (Pair with your other device, Accept a shared folder, and in the owner's Share dialog) opens the camera with getUserMedia (rear camera preferred), polls a frame every 0.3 s, and also takes a screenshot file or pasted text; a code of the wrong kind is named ("This is not a sealed share token."). Endpoints: POST /api/qr {text, parts} → kind, text, link, fingerprint/name (request), folder (token), code/addresses (pairing) and codes (SVG, version, modules, ECC); POST /api/link/parse {text | texts} → the same, or {part, have, count} while parts are missing; POST /api/qr/scan?w=&h= or ?image=1 → {texts}; GET /api/pair/status now includes uri.

Opening links from the system. varsto open-link <link> (hidden; registered by varsto install on Linux as x-scheme-handler/varsto in varsto-link.desktop and mimeapps.list, and on Windows as HKCU\Software\Classes\varsto with URL Protocol) checks the link, starts the service if needed, hands it over with POST /api/link, and opens the page; the page takes it with GET /api/link (once) when it loads, unlocks or regains focus. The macOS app declares CFBundleURLTypes and posts the link to the service the same way; Android (an intent filter on MainActivity, singleTask) and iOS (CFBundleURLTypes in project.yml, onOpenURL) pass it to the page as #link= on the first load or by calling window.varstoOpenLink. The page then routes by kind: a pairing link fills the pairing form and a token fills Accept a shared folder (both only on a device without a vault); a request link asks the owner which folder to share and continues with the fingerprint comparison. Camera access: NSCameraUsageDescription on macOS and iOS (WKUIDelegate grants capture to the local page only), the CAMERA permission on Android, asked for when the scanner opens (WebChromeClient.onPermissionRequest, local origin only). The native changes are not compiled in this change's tests.

Command line. varsto share qr <code | token | link> [--parts] [--light] prints the code with Unicode half blocks (two modules a character row; light modules as blocks for a dark terminal, --light for a light one), the caption (fingerprint of a request, folder of a token) and the link; --parts cycles through the parts until Ctrl-C; --json prints the links instead. share request --qr, share create … --qr and pair offer --qr add the code to their output.

Tests: qr::tests (round trips of request, token and pairing links; unknown paths, parameters, repeated parameters, fragments, bad addresses and malformed parts refused; parts reassembled in any order, a missing part and a foreign sequence; SVG, terminal and greyscale rendering decoded again, an inverted PNG screenshot), crates/varsto-core/tests/qr_invites.rs (a whole share made through links that went through rendered and decoded QR codes, the token both as parts in reverse order and as one code; another device cannot open the token; sizes), crates/varsto-cli/tests/qr_cli.rs (the CLI share flow with links only, share qr text and JSON, plain tokens refused, /api/qr, /api/link/parse with parts, /api/qr/scan with a camera frame, open-link through /api/link), filemanager tests (the Linux scheme handler and the Windows URL protocol), and scripts/test/qr-scan-browser.py (Chromium with a fake camera playing the codes: the token in parts and as one dense code fills Accept a shared folder, a pairing link fills the pairing form).

Limits. A dense single code needs a decent camera; parts need the Varsto scanner. A request link opened on a device without folders, or a token or pairing link on a device that already has a vault, is only explained, not acted on (accepting a share still needs a device directory of its own). Organization request codes and approval tokens (section 27) are not offered as QR codes yet. The iOS, Android and macOS changes have not been compiled or tried on devices.

52. Router port mapping for peer-to-peer (PCP, NAT-PMP, UPnP IGD)

Why. Hole punching (section 29 and before) fails behind symmetric NATs and relays cost a reachable device's upload. Most home routers will forward a port on request; a forwarded port makes the device directly reachable, which is the fastest route and lets it relay for the others.

Order. Before the NAT traversal of p2p::stun and p2p::quic, the service (P2p::spawn_portmap_thread, p2p::portmap::PortMapper) asks the router to forward the peer-to-peer port (the TCP and UDP listeners share the number), TCP and UDP, trying in order and stopping at the first protocol that maps anything:

  1. PCP (RFC 6887): a MAP request (version 2, opcode 1) to the default gateway's UDP port 5351, with the client address as an IPv4-mapped IPv6 address, a random 12-byte nonce kept for renewals and removal, the protocol (6 or 17), the internal port, the same number as the suggested external port, and ::ffff:0.0.0.0 as the suggested external address. A version-0 answer (a NAT-PMP-only server) or no answer moves on.
  2. NAT-PMP (RFC 6886): the public address request (opcode 0), then a mapping request (opcode 1 UDP, 2 TCP) to the same port 5351.
  3. UPnP IGD: an SSDP M-SEARCH to 239.255.255.250:1900 for InternetGatewayDevice:2 and :1; only answers whose LOCATION is an IP literal of the answering host on the LAN are followed. From the device description the WANIPConnection:2, else :1, else WANPPPConnection:1 service on that same host is used, by SOAP over HTTP: GetExternalIPAddress, GetSpecificPortMappingEntry, AddPortMapping (description Varsto P2P), AddAnyPortMapping (version 2, when the port is taken by another computer) and DeletePortMapping.

Default gateways come from the routing table (/proc/net/route on Linux and Android, route -n get default on macOS, route print -4 0.0.0.0 on Windows), else the .1 of each private /24 the device has an address in. The three clients are written in portmap.rs rather than taken from crates (the UPnP crates bring a URL and XML stack of some thirty crates and no GetSpecificPortMappingEntry).

Leases. One hour is asked for (PCP, NAT-PMP and UPnP alike); a mapping is renewed at half of what the router granted, with the same nonce or parameters. A failed renewal is retried every minute until the lease runs out; then everything is mapped again from the start. A UPnP router that only takes permanent mappings (error 725) gets one, removed like the others. When nothing could be mapped, the protocols are tried again after 30 minutes (another network, UPnP switched on), and at once when the device's local address changes (checked every minute; the old mappings are removed first). Mappings are removed when the setting is turned off, when peer-to-peer stops and when the service stops (Quit, and now also SIGTERM and SIGINT, which end the service loop like Quit; should a sync hold it, the process exits ten seconds later as before).

Respecting others. Only the peer-to-peer port is ever mapped. An existing UPnP entry for the external port that points at another computer is never replaced: version 2 asks the router for any free port (AddAnyPortMapping), version 1 tries three random external ports (20000-59999), each checked first; a router's own conflict error (718) moves on as well. An entry that points at this device and port but carries another description was made by hand: it is used as it is, never renewed or removed (status "already open"). An entry with our description is a leftover of an earlier run and is taken over. PCP and NAT-PMP servers never replace another client's mapping by design. A router whose own external address is not public (private, CGNAT 100.64/10, unspecified) gains nothing: its mappings are removed again and the protocol counts as failed.

Publishing. The rendezvous record (PeerRecord, now version 2) has mapped_tcp and mapped_udp: the external addresses. Other devices try them right after the LAN addresses over TCP and first over QUIC (PeerRecord::addrs, udp_addrs); the record is republished when they change. After a mapping the service probes its own mapped UDP address (Node::probe_self); when that leads back (the router loops it back), the record says reachable and the device may relay for the others. There is no DHT record on this version.

Fallback. Every failure is silent: no router answering, refusals and timeouts end in the existing ways (STUN, punching, relays through own devices). Details go to the log only with VARSTO_P2P_DEBUG. A whole failed round costs about four seconds on the mapping thread, never the sync.

Setting and status. P2pConfig::port_mapping (config.json, default on): varsto p2p port-mapping on|off, POST /api/p2p {"port_mapping": bool} (applied within a second), the checkbox "Open the port on the router automatically" on the Peers page. varsto p2p status, GET /api/p2p (portmap: state off, trying, mapped or unavailable; method pcp, nat-pmp or upnp; tcp, udp, lease_secs, existing, verified, detail; and portmap_text) and the Peers page say "router port opened via UPnP: 203.0.113.5:17893" or "not available". VARSTO_NO_PORT_MAPPING turns it off for one process: the tests and any throwaway service set it, so that they never touch the router of the network they run in.

Tests: p2p::portmap::tests: encoders and parsers, route tables, an in-process PCP server and a NAT-PMP server on loopback (mapping of TCP and UDP, the fallback from PCP to NAT-PMP, renewal at half the lease with the same nonce, a short lease renewed in time, a failed renewal retried and a lapsed mapping mapped again, removal with lifetime 0, a router without a public address refused), a fake IGD (SSDP responder plus an HTTP server with the description and SOAP control: mapping after PCP and NAT-PMP fail, renewal, removal, another computer's entry left alone, AddAnyPortMapping on version 2, a hand-made mapping used and never touched, our leftover taken over on a permanent-only router), SSDP answers pointing elsewhere ignored, and nothing answering at all; p2p::tests (record order with mapped addresses). The lab has no router VM that offers UPnP yet.

A mapping is published only after the probe through it succeeded: section 60.

53. Minimum free disk space

Why. A sync that fills a disk breaks the device for everything else, and a full disk is the worst moment to write a ledger or a database. Like Syncthing's minDiskFree, Varsto stops writing new data before a disk runs full.

Limits. A limit is a share of the disk ("5%", "2.5%") or an amount ("10GB", "500MB", "1.5GiB": decimal units are powers of 1000, binary ones of 1024; a plain number is bytes; "0" is no limit), stored as that string (freespace::MinFree). The default is 5 %. Where it applies:

  • the disk holding a synced folder: FolderMount::min_free in config.json (this device only): pulls, fetches of placeholders, conflict copies, imports with a full local copy, the restic mirror (whose folders are folders), and the block cache of a folder kept encrypted on this device (the folder's limit, measured at the device directory's disk);
  • a local-directory storage's disk: StorageSpec::LocalDir::min_free: block objects (chunks/, packs/); records, ledger batches and manifests are small and still written;
  • the device directory's disk for blocks staged from pool disks (disk_fetch), and a restore target outside the folders: the default.

Pool disks keep their own reserve (section 34), 5 % or at least 2 GiB, unchanged; S3 and rclone storages have no disk here.

Behaviour. A write of n bytes is refused when the free space minus n would be below the limit (freespace::check), with freespace::LowSpace: "disk of folder Photos has 3 % free, below the 5 % limit; downloads paused", or, when the write itself would cross it, "disk of folder Photos has 6 % free; 2.0 GB more would leave less than the 5 % limit; downloads paused" (storages: "uploads paused"). A pull keeps such files pending (pending_remote) and counts them (PullReport::files_waiting_for_space, low_space), not as unavailable; smaller files that still fit are fetched. A push leaves a full storage out for the rest of the push (PushReport::storages_unavailable, as a pool without room) while the other storages get the blocks. A fetch, a restore or a staging step fails with the message; an import stops and continues when run again. Reading, uploading, deleting and moving to the trash go on. Places refused are remembered in the process (freespace::short_places); the service measures them again after every sync and every 30 seconds (recheck), and one that has room for the refused write again is dropped, logged ("disk of folder Photos has room again; downloads resume") and a sync starts at once. The service notifies once per place while it stays short. A disk whose space cannot be read is never refused.

Surfaces. varsto folder set <folder> --min-free 10%|10GB|default and varsto storage set <name> --min-free ... (through the running service when there is one); POST /api/folder/min-free {folder, min_free} and POST /api/storage/min-free {name, min_free} (empty or "default" resets); GET /api/status folders carry min_free (as set, or null) and min_free_text; storage list shows "(keeps 5 % free)" for directories; GET /api/service has low_space (the places short now, with text). The interface: "Free space…" in a folder row's menu and on directory storages (a dialog with the limit, Default resets), the storage line says "keeps 5 % free", and a banner on the Overview lists the places short of space, one line each. English, Finnish and Swedish.

Tests: freespace::tests (parsing and wording, refusal, recheck and resumption with a byte limit), crates/varsto-core/tests/free_space.rs with the fake provider (pool::set_fake_space): a pull below the limit writes nothing and keeps the files pending, resumes when space is back, a folder's own limit and the default again, a placeholder fetch refused and then done; a full directory storage left out of a push while another storage gets every block, filled in after its limit is lowered; a folder kept encrypted here waiting for space in the device directory.

54. Event stream for the interface

Why. The interface asked the service every few seconds (the service summary every 5 s, the Now card every 2 s, the progress bar every 1-5 s, the traffic view every second), most of the time for nothing new. Now the service tells.

GET /api/events. Server-Sent Events (text/event-stream), answered on a thread of its own without the state lock (sse.rs; at most 16 at a time, more get 503 with Retry-After). The token comes in X-Varsto-Token or Authorization: Bearer, never in the address (section 60); the page reads the stream with fetch. The response has no length and no chunking; every event is written and flushed as it happens, and the stream ends when the client goes away or the service stops. It starts with retry: 3000 and an unnumbered hello event (last_id, this device's activity as in /api/activity?mine=1, the transfers as in /api/progress); a comment line goes out after 15 seconds of silence.

Each event is id: <n>, event: <kind>, data: {"id", "kind", "utc", "data"}. Numbers count up per service process (varsto_core::events); the last 1024 events are kept. A client that reconnects sends Last-Event-ID (the browser does by itself; ?last_id= works too) and gets what it missed, or an unnumbered reset (last_id) when its number is older than the ring or larger than the newest (the service started again): the client loads everything again. Nothing is written to disk.

Events. Counts, names and states only; never file names or contents.

Event Data
sync.started reason (files changed, requested, interval), folder for a requested one
sync.finished ok; on success folders, updated, deleted, conflicts, uploaded, unavailable, waiting_for_space, syncs; on failure error
files.new folder, count (files that came from other devices)
trash folder, count (files deleted by other devices, moved to the trash)
activity.started, activity.progress the task (activity::TaskView); progress at most once a second per task, only when done, total, step, file or percentage changed
activity.finished id, kind, subject
transfers download, transfers (as /api/progress), at most once a second while anything moves
peer.connected, peer.disconnected device, name, path, addr: a peer that exchanged anything within the last minute, or no longer
storage.problem, storage.ok storage, text: a storage a push had to leave out (no disk, full, below its free-space limit), and when it is back
space.low, space.ok place (folder:<name>, storage:<name>, device, path:<dir>), text (section 53)
folder.paused folder, text: a folder paused on this device (its marker is missing, or deletions are held; section 47), once per new reason
notification title, body: every desktop notification the service raises
config.changed source (api with the path of a successful POST, or file when config.json changed under the service)
policy.changed folder, state (ok, at_risk, violated, unknown)
ledger.health state, text, warnings (also published when the warnings change, section 74)
backup name (or restic), ok, text
move.waiting, move.done id, folder, to, and for a waiting job kind, disk, bytes_left, text; for a finished one from, bytes, disks (section 59)

Two unnumbered events only for a connection that asks: ?traffic=1 adds traffic (the report of /api/p2p/traffic) every second; ?peers=1 adds activity.peers (peers, as in /api/activity) whenever it changes, and the service keeps asking the other devices while such a connection is open. Tasks, transfers and peers are sampled once a second by one thread while any stream is open.

The interface. One EventSource while the page is shown (closed while it is hidden, reopened with the last number when it shows again; reopened with other flags when a page that needs the peers' activity or the traffic is entered or left). The progress bar at the top and the Now card follow the activity.* events, the Peers page's traffic the traffic events, a download button's note the transfers events; syncs, changes, problems and notifications make the page load the service summary once (several events in a row ask once), configuration changes and resets also the status. The polls of section 41 and before run only while the stream is down; the service summary is still asked once a minute as a safety net. When the browser gives up reconnecting, the page tries again after 1 s, doubling up to a minute.

Measured (Chromium 2026-10, a throwaway vault and service of this build, 60 s per page after the page settled, one sync started from outside in the middle; old interface served by intercepting app.js): requests per minute on Overview 38 before, 13 after (the 11 requests reloading the page's data after the sync are in both); Peers 76 before, 5 after; Files 27 before, 4 after. Idle, without the sync: Overview 37 before, 2 after; Peers 66 before, 4 after; Files 16 before, 3 after (what is left after: the once-a-minute summary, the update check at start, reopening the stream with other flags when the page changes).

Tests: events::tests (numbering, ring, reset after a restart or a gap, waiting), sse::tests (hello, live events, resume after the last seen, reset, the traffic event, the sampler turning a task into started, progress and finished), and the measurement above with Playwright.

55. Read-only members of shared folders

Superseded by section 77 (storage format 3): roles are in folder records and grants, not in tokens or role records (77.6, 77.20). Kept as the history of format 2.

Code: crates/varsto-core/src/share.rs (ShareRole, ShareRoles, SignedShareRoles, JoinProof) and engine/share_roles.rs.

Why the others enforce it. A member of a shared folder holds the folder key, and the folder key opens and encrypts: chunk keys, manifests and ledger batches are all derived from it. Nothing cryptographic can stop a key holder from writing objects to the storage. A viewer is therefore read-only because nobody takes what it writes: the owner's devices and the editors do not merge its manifests, do not count its ledger batches and ignore its records for the folder (file analyses, section 36; last-accessed times, section 13). Its own client refuses to write as well. An editor reads and writes, as every member did before roles existed; the owner's devices always write.

Role record. vault/share-roles/<folder>/<seq, 10 digits>-<issuer device>.json, written by one of the owner's devices: an envelope {format_version, folder, seq, issuer, epoch, body_hex, sig_alg, sig_hex}. The body is {folder, seq, issuer, issued_utc, share_epoch, roles} with roles mapping member device ids to {role: "editor"|"viewer", name, since_utc, editor_until_clock, editor_until_seq}, encrypted with XChaCha20-Poly1305 under derive(K_e, "share-roles", folder) where K_e is the folder key of share epoch epoch (section 24; 0 is the folder key itself), associated data ("share-roles", vault, folder, seq, issuer, epoch). The signature is the issuer's device signature over ("share-roles-signature", vault, folder, seq, issuer, epoch, BLAKE3(body ciphertext)). A record is a snapshot: every reader adopts the valid record with the highest (seq, issued_utc, issuer) and never goes back to a lower one. Valid means: the issuer is one of the owner's devices as the reader knows them (on the owner's devices a trusted device of the vault, section 21 and 27; on a member the owners its token and the share epoch records named), the issuer is not revoked, the signature verifies with the issuer's key (the vault registry, or on a member the issuer's member record), the body opens and agrees with the envelope. A member cannot give itself or anyone a role: its signature does not count.

Who is what. Without any role record every member is an editor (folders shared before roles, and folders that never had a viewer). Once a folder has one, a member device the record does not list is a viewer: a new member writes only once an owner device has listed it. The first role record is written when the owner makes the first viewer token or changes the first role; it lists every member there at that moment as an editor.

Tokens carry the role. share create --to <code> --role viewer|editor puts the role, the invitation id (invite_id of the request key) and a random 256-bit join secret into the sealed token (vst2 payload {…, role, invite, join_secret_hex}); the invitation record (vault/share-invites/…, section 24, readable by the owner's devices only) keeps the role and the secret. The member keeps both in its local folder record (share_join, never published) and publishes a join proof vault/share-join/<folder>/<device>.json = {folder, device, invite, proof_hex} with proof = derive(join secret, "share-join-proof", folder, device). An owner device that sees a member without an entry looks up the invitation, checks the proof (constant-time comparison) and writes the next role record listing the member under the invitation's role. The proof binds the role to the device that opened the token: a viewer that copies another member's KEM key or request code does not know that invitation's secret. A plain token (<vault>.<folder>.<key>.<name>) has no room for a role; once a folder has a role record, plain tokens are refused, and --role viewer requires --to.

Changing a role. varsto share role <folder> <member> viewer|editor, POST /api/share/role {folder, member, role} and the role selector in the Shared page's member list write the next role record (owner devices only; in an organization only where the policy lets members share, or an administrator). Making an editor a viewer records editor_until_clock, the largest Lamport clock of the member's changes in the owner device's merged state, and editor_until_seq, its newest ledger batch held there: what it wrote while it was an editor stays valid. Making a viewer an editor takes its newest manifest from then on.

Enforcement on the owner's devices and the editors.

  • Manifests: a pull does not open the manifest of a viewer (and does not advance last_seen for it, so a later editor role takes its newest one). PullReport.writes_refused names the viewers whose newer manifests were not taken.
  • File versions relayed by others: a version whose modified_by is a viewer and whose modified_clock is above its editor_until_clock is not merged, whichever device's manifest carries it, so an editor that has not seen the role record yet cannot launder a viewer's change.
  • Ledger: a viewer's batches after editor_until_seq are neither pulled nor counted (devices.json share_viewers, part of the ledger view's context like revocation cut-offs, so the view is rebuilt when roles change). Its claims and verifications of blocks therefore do not count toward policies either.
  • Records: analyses and last-accessed records of viewers are skipped.

The viewer's own client. share_read_only is true on a member device whose own role is viewer (the newest role record listing it, else the role its token gave; unlisted in a folder with roles: viewer). Then a scan publishes nothing: a file changed or created in the folder is moved to <home>/kept-aside/<folder name>/<path>.<utc> (outside the folder, never synced), a changed or deleted file is put back from the shared version on the next pull, and files written by a pull lose their write permission (set_readonly, where the platform has it). Push publishes no manifest and uploads nothing; PushReport.read_only and kept_aside, PullReport.kept_aside, the command line ("read-only: your changes were not published") and the service's last result report it. Writes through the interface and the API (write_file, uploads, mkdir, moves, the block cache of an encrypted folder) are refused. share members shows this_role, the Files and Shared pages a "read only" mark.

Interfaces. CLI: varsto share create <folder> --to <code> --role viewer|editor, varsto share role <folder> <member> viewer|editor, varsto share members (each member's role, and a token's role). API: POST /api/share/create {…, role}, POST /api/share/role, GET /api/share/members (members carry role; the list carries this_role and roles_in_use); FolderStatus.read_only. Interface: a Role choice in the share dialog, a role selector and an Editor/Viewer mark per member in the Shared page's member list; English, Finnish and Swedish.

Threat model. A viewer keeps everything it can read and can copy it anywhere: no key can prevent that, as with any member (section 24). What the role gives is integrity for everyone else: nothing a viewer's devices publish for the folder is accepted, so they cannot add, change, delete or rename files of the others, even with a modified client. A viewer can still write objects to a storage it can reach (and delete or occupy names there, as section 24 says of a removed member), and can plant a thumbnail for content that has none yet (thumbnails are written once per content hash and are not attributed). Those are storage-level powers the storage credentials grant, not changes anyone merges.

Limits. Changes a modified client published while it was a viewer are taken if the owner later makes it an editor (its newest manifest is read then). Two owner devices writing role records at the same moment: the later (seq, issued_utc, issuer) wins and the other change is lost until it is made again. A member that joined with a plain token or before tokens named the owner's devices cannot verify role records and treats everyone as an editor; the owner's devices still refuse what a viewer writes, also when that member relays it. A new editor's first changes wait until an owner device has seen its join proof. Tests: crates/varsto-core/tests/share_roles.rs (a viewer reads, its changes are kept aside and undone, deletions undone, interface writes refused; a modified client that publishes anyway is refused by the owner and the editor; an editor writes; making the viewer an editor and a viewer again takes effect, with its editor-time change kept and readable by a new device; a forged role record is ignored; members cannot set roles; plain tokens refused once a folder has viewers).

56. Organizations: which device platforms may belong

Code: crates/varsto-core/src/org.rs (OrgPolicy::allowed_platforms, min_app_version, refuses, request codes) and engine/org_ops.rs, engine/devinfo.rs, engine/membership.rs (trusted, belongs).

Policy. Only in a vault with an organization (section 27). The roster's policy gains allowed_platforms (any of linux, macos, windows, android, ios; empty: every platform) and min_app_version (the oldest Varsto version a device may run, compared as major.minor.patch[-pre.N]; empty: any). Like the rest of the policy they are part of the roster signed by an administrator device, and every change is logged as policy_changed with the whole policy. Rosters that do not verify (section 27) never change it, so neither does a policy forged by a member or written by anyone with the storage credentials. Device kinds (desktop, phone, …) and hardware-backed keys are not in the policy: the code does not know a device's kind reliably. An administrator cannot set a policy that refuses its own device ("this policy would lock out this device"); unknown platform names are refused; listing every platform is stored as no list.

What a device's platform is. A device says it: (1) its request code vor2.<KEM key>.<device id>.<platform>[.<name>] names its platform, and the six-word fingerprint covers it (derive_key("varsto share-request fingerprint v1", key, "<device> <platform> <name>"), the context of section 24, outside e2ee-sync-format/0), so a platform changed on the way changes the words; vor1 codes (no platform) are still read; the roster entry of an approved device keeps platform; (2) every full device publishes its details (vault/devinfo/<device>/<utc>.enc, section "Device details") with platform and app_version, now signed by the device's own key over ("device-details-signature", vault, the details as JSON without the signature). Readers keep only details whose signature verifies with that device's registry key, reading past newer records someone else planted under its name (at most 16), so a holder of the vault key cannot make another device look like another platform. A sync republishes them when they change (and at least every six hours, as before). The platform used is the signed details' one, else the roster's. Mobile shells set VARSTO_OS.

Enforcement. With a restricting policy:

  • Approval. org approve refuses a request whose platform the policy does not allow ("the organization does not allow Android devices"), and a vor1 code, which does not say ("update Varsto on the device and make a new request"). The version is checked later, from the signed details.
  • Devices already in the organization. trusted(device) (section 21, 27) is false for a device whose platform is refused or unknown, or whose version is older than the minimum or unknown. Hence the other devices do not pull or count its ledger batches, do not merge its manifests (a pull now skips the manifests of every full device that is not trusted and not revoked; they stay unread and are taken once it is trusted again), refuse its peer connections, accept no revocation, grant or roster from it, and seal it no new vault key: a key epoch started meanwhile keeps it as a member (belongs: listed and not revoked, platform aside), and the key is sealed to it once it is allowed again. An administrator can still remove it.
  • The device itself. When the signed policy it holds refuses its own platform or version, ensure_active fails with "this organization (Acme) does not allow Windows devices: this device does not sync or open the vault until an administrator allows it": sync, pull, push, fetching and reading files, the viewer and every action that changes the vault stop. It still reads the registry, revocations, key epochs and the organization's objects at the start of each sync, so a policy that allows it again (sealed under a key epoch started meanwhile, after its grant arrives) is seen and it carries on. StatusReport.org.blocked, OrgSummary.this_device_blocked and the banner of the interface say why.

Interfaces. CLI: varsto org policy platforms --allow linux,macos,windows | --allow-all [--min-version 0.0.1-alpha.14|any] (prints the policy and the devices it locks out), varsto org policy shows the platforms and minimum version, varsto org status shows each device's platform and "LOCKED OUT", varsto org approve shows the code's platform. API: POST /api/org/policy takes the two fields, GET /api/org gives policy, per device platform and refused, and this_device_blocked, this_platform; POST /api/org/fingerprint gives the code's platform. Interface: platform checkboxes and the minimum version in the Organization page's policy card, a "Locked out" mark per device, the platform in the approval question, and a banner on a locked-out device; English, Finnish and Swedish.

Limits. The platform and version are what the device's own app says: a modified app can claim another platform, so this binds honest apps (and makes a policy visible and enforced by every honest device), not an attacker who holds the vault key, who can read everything the key opens anyway (section 27). A device that has not published signed details yet (one that never synced with this version) counts as an unknown platform and is locked out once the policy restricts platforms, until it syncs once; a locked-out device does publish them. Tests: crates/varsto-core/tests/org_platforms.rs (an approval for a refused platform and a code without one refused, the platform in the fingerprint and the roster; a Windows device locked out after the policy changes: its files not taken, its own sync and reads refused, no key from a removal meanwhile; allowed again: its files taken, the key sealed to it, syncing again; a roster forged by a member and device details forged in another device's name ignored; a policy that would lock out the administrator refused), crates/varsto-cli/tests/org_cli.rs (org policy platforms).

57. Change history of files

Code: crates/varsto-core/src/changes.rs (events, the index, limits) and engine/changes_ops.rs.

Sources. Who changed what and when is read from manifests only, never from a local log of what this device did: a version is a FileState that a manifest names, identified by (path, modified_by, modified_clock). A pull records the versions of every manifest it takes (the same manifests it merges: not those of read-only members, section 55, nor of untrusted devices, section 56, and not versions a viewer made), whether or not they win the merge; a device records its own versions when it publishes its manifest. Each event keeps the time of the first manifest that named it (created_utc, the publisher's clock), the device that made it, the device whose manifest carried it (source), and verified: the manifest's BLAKE3 hash matched the hash the publisher's signed ledger batch announced for it (manifest_published; the ledger view keeps the hash of each device's newest announced manifest, view cache format 5). A device's own versions are always verified; a member of a shared folder cannot read the owner's vault ledger, so the owner's manifests are unverified there.

Actions. For each path, with the versions recorded before: deleted (the version is a deletion; the event names the content that was there), created (no earlier version, or a deleted path coming back with content it never had), restored (a deleted path coming back with content it had before), modified. Among the versions recorded together (one manifest), a deletion and a creation of the same content by the same device are a rename: the old path's event says renamed with to, the new path's renamed with from. A move that also changes the content is a deletion and a creation. A file's history follows renames back: asking for the new path also lists the old path's versions before the move (up to 16 moves).

Storage and bounds. state/changes/<folder>.jsonl: one event per line, {path, action, from?, to?, device, clock, time_utc, size, hash (first 16 hex digits of the keyed content hash), source, verified, backfilled?}, appended. state/changes/<folder>.json: the index, per path the versions recorded (device, clock, deleted, content hash), so each version is recorded once, and whether the history was started. config.json changes: {per_file, per_folder} (defaults 100 and 20 000) bounds both: a path keeps its newest per_file versions (older ones offered later are ignored), and the events file is rewritten with the newest per_folder events once it grows a quarter past that. Both files survive restarts; they are local and never published.

Starting. The first pull of a folder on a device with this version (or varsto changes on a device that has not pulled since) reads the newest manifest of every device on the storages whose writes it takes, then adds the other devices' versions it holds that no manifest names any more, at the file's modification time (backfilled, unverified). Manifests are pruned to each device's newest (section 25), so older versions made before the history began on a device are not known to it: a device that joins later starts with the newest version of every file.

Queries. varsto changes <folder> [<path>] [--device <name|id>] [--user <person>] [--since <YYYY-MM-DD[THH:MM]|seconds|7d|12h>] [--limit N] [--json] (the name varsto log is left to logging): with a path that has versions, that file's versions (file: true); with any other path, the changes under it as a directory; without, the folder's recent changes; newest first, default 100 (0: all), truncated when more matched. --user matches the organization's person of the device (section 27). GET /api/changes?folder=&path=&device=&user=&since=&limit= gives {folder, path, file, changes: [{…event, device_name, user?, source_name}], truncated}. Interface: a Changes list in the file details and a Recent changes panel on the Files page with filters for a directory, a device, a person and a time; English, Finnish and Swedish.

Limits. Times are the publishers' clocks, and a change seen first through another device's manifest gets that manifest's time. A version made and replaced before any manifest named it (two edits between syncs) is not seen. Content events only: moving data between storages, placement and pool disks are not in it. Tests: crates/varsto-core/tests/changes.rs (edits on two devices with the right devices and order, verified against the ledger; a rename shown as a rename and followed back; a deletion and a restore; the folder feed by device, directory, time and limit; by person in an organization; the history surviving a restart; a device joining later starting from the manifests), changes::tests (actions, renames, limits, dates) and crates/varsto-cli/tests/cli_smoke.rs.

58. Ledger authorization and gap handling

Superseded by section 77 (storage format 3): batches are judged by the acceptance rule of signed records and the scopes of 77.4 and 77.11. Kept as the history of format 2.

A security review (2026-10-13) found that the ledger took every event from every signer whose batch opened, and decided fencing, gaps and revocations from object names and timestamps. Replicas and members of shared folders hold storage credentials and sign batches; the storages can withhold, reorder, replay and write junk. These rules follow. The storage format does not change: batch envelopes, checkpoints and epoch records keep their fields (the epoch record is now always the signed form of section 28).

Who may say what. The key id of a batch names the role it claims, and the signer must have that role in the device's registry (EventScope, Engine::event_scope):

Key id Scope Signer Events that count
ledger, ledger@<epoch> full a trusted full device, or a removed one up to its cut-off every event
replica replica a registered replica chunk_stored and chunk_verified with an empty folder (object claims)
share:<folder>[@<epoch>] member of <folder> a known member device (or this device) chunk_stored, chunk_verified, chunk_on_device, manifest_published, chunk_dropped of that folder

device_enrolled (the signer's own name) and unknown event types count in every scope; everything else outside the scope is left out when the batch is applied and counted (LedgerView::events_refused, ledger_health.events_refused). A member never retires a storage, adds a folder, takes or expires a snapshot or stops a backup; a replica only claims objects. snapshot_expired and backup_stopped therefore count only from full devices: the backup's source device or another trusted full device of the vault (section 31). Acknowledgements (seen) count only from full devices. A batch whose signer has no scope (a key id it has no role for) does not count at all. The scope of every device is part of the cached view's context, so a change of role rebuilds the view (view format 6).

A manifest that does not open with any key this device holds stops the folder's pull only when a trusted full device wrote it (a newer vault key has not arrived yet); from anyone else (a member, a replica, a removed device, or a name planted on the storage) it is skipped.

Checkpoints speak for their signer. Checkpoints are read only from full devices. When one is merged (LedgerView::restricted_to), every claim, verification, block held, manifest announcement, device name, snapshot and acknowledgement that names another device as its author is dropped; object and size stamps of other devices are dropped with them. Retirements, drops, folders, stopped backups and expiries of other devices' snapshots stay (a full device may make those), but of another device's snapshot only that it expired: its hash, which a restore trusts, and its times and sizes do not. A checkpoint more than 65 536 beyond the newest batch held of its device is refused unless the batch it ends at is beside it on the storage, signed by the device with the checkpoint's head_hash.

Gaps. The head of a device is the end of the unbroken chain of its batches held here (after its checkpoint). A batch whose predecessor is missing is kept in ledger/<device>/pending/<seq>.json (the signed batch, and the predecessor hash its body names when this device could open it) without moving the head. Every pull lists every storage after the head, so the missing batch is asked for again everywhere; when it arrives, the waiting batches follow it in order, each checked against the hash of the one before (one that names another predecessor marks the device forked). A checkpoint that covers waiting batches drops them (one at its own number must agree with it). A device restoring its own history from the storages (varsto ledger rebuild, section 38) still moves past a gap no storage can fill, so it never signs a number it used.

Freshness. After every pull, a device compares what the full devices acknowledged (seen in their signed batches, section 22) with its own heads: when another device says it holds batches of device A up to 50 while this device's head for A is 30 (never beyond a removed device's cut-off), or batches of A wait for a predecessor, it records ledger_health.behind = {device, name, held: 30, seen: 50, pulls}; the pull just asked every storage for 31..50. When the same gap is still there after three pulls in a row, ledger_health.warnings says "a storage may be withholding ledger batches of ", varsto status and varsto ledger status show it after "ok", and the Help page shows a warning (English, Finnish, Swedish). The record is kept in ledger/watch.json.

Damaged and absurd batches. A batch that does not parse, names another device or number, or does not verify on one storage is skipped and counted (ledger_health.batches_malformed, last pull) instead of stopping the pull: another storage may hold the real one. A batch whose Lamport time is more than 2^40 ahead of the reader's clock is refused (Ingest::Refused, ledger_health.batches_refused) and not applied, so one value cannot win every later ordering. A batch under a key this device does not hold yet is checked when it is applied, not when it is stored: see Limits.

Fencing only on verified objects. A device fences itself (section 6) only when an object under its own name verifies with its own key and is not its own (another copy of the identity signed it). Anything else under ledger/<device>/ (a file that does not parse, another device's batch copied there, a checkpoint that does not verify) is junk: it is noted once per storage and object (ledger/watch.json), never read again, reported as ledger_health.junk_objects with a warning, and deleted by varsto ledger clean-junk --yes (without --yes it lists them; the device's genuine objects are never touched). The same rule holds for the check before every signature (own_objects_ahead), for pushes (a name occupied by junk is skipped on that storage) and for varsto ledger rebuild (the newest checkpoint and batches that verify are used).

Key epochs. Every vault writes epoch records as signed envelopes (SignedEpoch); a number taken by anything that does not parse or verify against a trusted device (an administrator, in an organization) is skipped by a removal, which takes the next free number. A name under vault/share-epochs/<folder>/ makes a member see itself removed (access_lost) only when an owner device (a participant, for members from before tokens named the owners) signed a grant of that epoch to someone.

Revocations in epoch order. A revocation counts only when vault/epochs/<new_epoch> exists as a signed record of the revocation's issuer and, once this device holds that epoch's key (adopted through a chain of epoch records from a key it held), opens and lists the revoked device among those it removed; the revoked device itself, which never gets the key, checks the issuer's signed envelope. Revocations are applied in the order (new_epoch, issuer) and key epochs are adopted one at a time from the lowest, the revocations of each applied before the next: a device removed in epoch 1 can neither revoke anyone in epoch 2 nor hand out its key. issued_utc is shown, never used for ordering.

Two epochs under one number. Two devices removing at the same instant through different first storages can each write epoch n. A device that finds two different signed records under one number at or above its current epoch (verified with their issuers' device keys) records both issuers in epoch-fork.json in its device directory, applies neither record's revocations, adopts neither key, reports ledger health epoch_fork and signs nothing (ledger batches, removals) until the user runs varsto device resolve-epoch <n> --keep <device>; the kept device must be trusted. From then on only the kept issuer's record, grants and revocations of epoch n count. A device that already adopted the other record's key refuses the choice: pair it again.

Limits.

  • A storage that withholds a batch from every reader and the acknowledgements that would reveal it (all of them) is not caught by the storage alone: there is nothing signed there to compare with. Since the release after 0.0.1-alpha.15 devices also compare their heads with what trusted full devices tell them over peer-to-peer (section 74), so a storage that is the only channel between the devices, and withholds everything including the rendezvous records, is still not caught: the devices must meet. Batches of devices that never acknowledge or send statements (members, replicas) are only caught by a later batch of theirs that waits for the missing one.
  • The Lamport check needs the batch opened: a batch kept unread (a key this device does not hold yet) is applied as it is once the key arrives.
  • A trusted full device can still sign a checkpoint and the batch it ends at far ahead and make readers jump; full devices are trusted with the vault anyway.
  • key_id is not covered by the batch signature yet (a storage can relabel it); a relabelled batch then does not open, or opens under a scope its signer does not have and does not count. Signed key ids are a format change (planned).
  • Manifests, trash records and snapshots are still accepted on the folder key alone; signing them is a format change (planned).
  • The removed device trusts the signed envelope of its own revocation's epoch: a thief who acts first still removes the others (section 21).

Tests: ledger::tests::checkpoint_cannot_speak_for_other_devices, ledger::tests::checkpoint_far_ahead_is_refused, crates/varsto-core/tests/sharing.rs (a_members_batch_cannot_reach_outside_its_folder, junk_share_epoch_does_not_cut_a_member_off), crates/varsto-core/tests/backups.rs (a_replica_cannot_expire_snapshots), crates/varsto-core/tests/ledger_gaps.rs (a withheld batch, acknowledgements that reveal one and the warning after three pulls, a malformed batch on one storage, an absurd Lamport time), crates/varsto-core/tests/revocation.rs (junk_under_a_devices_ledger_name_does_not_fence_it, junk_epoch_record_does_not_block_revocation, a_backdated_revocation_does_not_win, two_epochs_under_one_number_wait_for_a_choice), and the lab scenario ledger-withhold (section 74 adds ledger-rollback).

59. Staged moves to disk pools

Code: crates/varsto-core/src/staged_move.rs (the job file), engine/staged_moves.rs (running jobs) and the move commands in crates/varsto-cli/src/placing.rs.

Why. A move (section 23) copies a folder's blocks from one storage to another in one run. A pool of removable disks (section 19) is filled while the disks are docked one at a time, so a two-terabyte download in a cloud storage cannot be moved onto a stack of 500 GB disks in one run: a pool without an attached disk, or without room, is simply left out. A move job is a move that goes on over as many runs as it takes: it moves what fits on the disks attached now, stops, says which disk to attach next, and carries on by itself when one is attached. Optionally the data then leaves the cloud storage, once the pool holds the copies the policy needs.

Commands.

  • varsto move <folder> --from <storage> --to <pool|storage> [--path <dir-or-file>]... [--idle-days N] [--keep-source] [--job] [--dry-run] [--confirm-cold-read] [--yes]. A move to a pool, or with --path, --keep-source or --job, is recorded as a job and run once with the disks attached now; other moves behave as in section 23. --path (repeatable) limits the job to the files at or under those paths, which are relative to the folder or absolute inside its directory on this device; a path that holds no current file is refused. --keep-source copies and checks but never drops from --from. The same request while its job is open continues that job instead of starting another. The CLI asks (with the plan's summary) unless --yes, and exits with code 1 when blocks of a finished job stay on the source.
  • varsto move status [id] lists open and paused jobs (or one job, finished or not) with bytes done, bytes left and the disk each waits for; varsto move pause <id>; varsto move resume <id> (opens a paused job and runs it now); varsto move cancel <id>. These need no passphrase except resume. Cancelling never deletes anything: what was moved stays moved and what was copied stays copied, so the ledger and the storages stay consistent; a new job for the same folder picks up the rest.
  • varsto status lists the open jobs under the folders, one line each (status --json adds move_jobs when the service answers). GET /api/moves lists the jobs; POST /api/move/state {id, action: pause|resume|cancel} changes one; the service summary has move_jobs.

The job file. <home>/state/moves/<id>.json, id = mv- and eight hex digits, written atomically after every group of blocks and at the end of every run: folder (name) and folder_id, paths, from, to, idle_days, keep_source, confirm_cold_read, policy (the folder's copy rules when it started, in words), state (open, paused, done, cancelled), bytes_total, bytes_done, bytes_remaining, blocks_total, blocks_done, need_second_place_bytes, disks_used (labels), started_utc, last_progress_utc, finished_utc, runs, waiting (kind disk, place or room; disk, the known disk with room that continues the job; text), room_sig, room_needed, kept_blocks and errors (the last 20). The file holds no block names. What is left to move is worked out from the ledger at every run, so the counters are informative: a run recomputes bytes_remaining and corrects bytes_done (done = total - left), and a crash, a restart or another device finishing part of the move changes nothing but the numbers. A process that runs a job holds <id>.lock (created exclusively, refreshed after every group, taken over when older than ten minutes), so the service and the command line never move the same blocks at once.

A run. It pulls the ledger, plans the move as in section 23 (limited to paths; with keep_source the folder's copy rules do not keep blocks, nothing is dropped), then moves the blocks in groups of 64: write to the target unless it has the block, read back and hash-check, record chunk_stored and chunk_verified for the target, and (unless keep_source) record chunk_dropped for the source, seal and push the batch, then delete from the source, exactly as in section 23. The source copy of a group's block is dropped only when the target copy is checked and the policy still holds. A pool target is written through the pool itself (section 19): a block that finds no attached disk with room within the reserve, or no disk at all, is neither copied nor kept; the run notes the size and skips every block at least that large without reading it, and goes on with smaller blocks. A storage at its quota (section 44) waits the same way. When a run has moved what fits, the job stays open with waiting: kind: "disk" and the label of the known disk with the most room (its last measurement, section 40) or "attach a new disk" when no known disk has room. The service limits a run to 16 groups and goes on at its next turn.

Disk groups. For a pool with a copies rule (section 23) a block counts as moved only when the pool holds it in that many different places. After writing, the run adds copies on attached disks of other places; while a block is held in fewer places its source copy stays and the block is counted in need_second_place_bytes (waiting.kind is place: "N GB need a copy on a disk kept in another place"). With the second disk attached the next run adds the copies and drops the sources. With keep_source a block counts as done under the same rule.

Done. A job is done when nothing in its scope is left waiting. Blocks that stay on the source because the folder's policy needs the copy there, a cold read is not confirmed, or no readable copy was found are listed in errors and kept_blocks; they do not hold the job open. A finished whole-folder job (no paths, no idle_days, no keep_source, nothing kept) also replaces the source with the target in the folder's placement, as a whole-folder move does (section 23), so new blocks go to the pool too. Until then the folder's placement should name the source, otherwise disk add and pushes would fill the pool with the whole folder by themselves.

Automatic continuation. The background service (every 30 seconds, with its disk listing, and after every sync) asks which open jobs are ready and runs them within its share. A job to a pool is ready when an attached disk has at least room_needed bytes (the smallest block that found no room) and the attached disks with their room differ from what the job saw when it last waited (room_sig): a disk was attached (disk add, disk insert, disk check, a mount appearing) or a disk's space changed (blocks freed, files deleted). A job to an ordinary storage is ready after every sync. A paused service, a locked vault and paused or finished jobs run nothing. disk add, disk init, disk insert and disk check say which jobs can continue with the disks attached (varsto move resume <id> does it at once).

Next disk to dock. Engine::disk_suggestions (section 40) takes the open jobs that wait for room on a pool (moves: id, folder, pool, bytes_left, need_second_place_bytes, room_needed). A disk of that pool whose free space within its reserve is at least room_needed gets a reason of kind move: "continue the move of : N GB left; this disk has M GB free", worth 65 × min(room / bytes left, 1) points (at least the suggestion threshold), so a known disk that can continue a job is suggested before one that is merely overdue for a check; attached disks with room are listed apart as before. When no attached or known disk of the pool has room, new_disk_needed lists the job with "a new disk is needed" and the commands varsto disk init <device> --pool <pool> --label <name> or varsto disk add <mount> --pool <pool> --label <name>; varsto disk suggest prints them.

Interface and events. The Storages page shows, in each pool card, a line per waiting job with the bytes left, the bytes that need a second place and "Attach disk «X»" or "A new disk is needed"; a banner under the page header lists the waiting jobs from the service summary. The Help page (section 41) has a step and an attention line per waiting job. The event stream (section 54) has move.waiting (id, folder, to, kind, disk, bytes_left, need_second_place_bytes, text), sent when a run ends waiting with a different reason than the run before, and move.done (id, folder, from, to, bytes, disks). The service raises a desktop notification for both.

Limits. Jobs are per device (<home>/state): another device does not see them, though it sees the moved blocks in the ledger. The room of a pool is the free space the file system reports; a disk whose reserve leaves less than the smallest remaining block counts as full. A group rule needs disks in enough different places to exist; a job cannot finish with fewer. Moving a block to a pool does not change which disks a later disk check fills.

Tests: crates/varsto-core/tests/staged_move.rs (a folder moved to a pool disk by disk with the suggestion and the service trigger, --keep-source, --path, a disk group rule needing two places, pause and cancel, a job resumed after the engine is dropped between groups, an ordinary storage target and the run lock), crates/varsto-core/src/disksuggest.rs (ranking for waiting jobs), crates/varsto-cli/tests/cli_smoke.rs (staged_move_jobs_through_the_cli) and the scenario staged-move-to-pool of the lab (scripts/test/lab/scenarios.py).

60. Service and transport hardening

Changes that tighten the local service, the peer transport and the reads from storages. None of them changes an object or record on a storage.

STUN side channel (section 52). The shared UDP socket queues a datagram that looks like STUN only while Node::stun has a request open, only when bytes 8 to 20 equal the transaction id of that request, and into a bounded queue of 64 entries (try_send). Everything else is dropped without allocating and counted. Before, any host on the internet could grow the queue of an unbounded channel without limit by sending STUN-shaped datagrams to the UDP port. Test: p2p::quic::tests::unsolicited_stun_flood_is_not_queued.

Session token out of addresses and argv (S3). The service no longer hands the browser an address with the session token. varsto desktop, the tray, varsto open-link, the service's own browser start and the FFI varsto_url open http://127.0.0.1:<port>/?boot=<code>: a code of 32 random bytes (64 hex digits) that is valid for 60 seconds and works once (POST /api/session/boot, authenticated by the token header, mints it; at most 256 codes are kept). The page trades it with POST /api/session {"boot": "<code>"} for {"token": …}, keeps the token in sessionStorage, and removes the parameter from the address at once; a second use or an expired code answers 401. The token stays what it was: random per service start, written to service.json (0600), read by the CLI, the tray and the MCP server from there. The ?token= parameter is not accepted on any route. The token is read from X-Varsto-Token or Authorization: Bearer. Thumbnails are fetched by the page with the header and shown from blob URLs. A download (/api/open) or viewer (/api/view) link, which a browser opens without headers, carries ticket=<random> from POST /api/ticket {route, folder, path}: the ticket opens exactly that route, folder and path, for ten minutes, any number of times (a video asks for ranges). Every answer under /api/ has Cache-Control: no-store. The FFI adds varsto_token() for the mobile shells' own API calls. Tests: desktop::tests::boot_code_opens_the_session_once, expired_boot_code_is_refused, the_token_is_never_accepted_in_the_address, tickets_open_exactly_one_file.

Request handling (S2). Query values are decoded on bytes (%XX with two ASCII hex digits, else the byte as it is), so a malformed escape such as %aé cannot split a character; a panic in a request handler answers 500 and the API worker carries on (before, the one worker thread died and every stateful route hung). Test: desktop::tests::percent_decode_survives_malformed_escapes.

Strongroom key commitment (S4, section 17). See section 17: check_hex, -t pin=true, --uv. Test: crates/varsto-core/tests/strongroom.rs::a_wrong_folder_key_is_refused_by_unlock_convert_and_rekey.

Passphrases and secrets off the command line (S5, section 28). A device passphrase must be at least 12 characters after NFKC normalisation (crypto::check_passphrase, checked by Keys::save and before init, join, pair, share accept and org join create anything; the interface's forms say "At least 12 characters"). Keys already written with a shorter passphrase still open. Nothing secret is taken from the command line any more, because every process of the user can read it (ps, /proc/<pid>/cmdline) and the shell keeps it in its history. The options join --vault-key and --words, --s3-secret-access-key (join, share accept), storage add-s3 --secret-access-key, mcp --key, the positional shares of recovery combine and org admin add|remove --root-words are gone. Each secret now comes from, in order: a file named by --key-file (join; the file holds 64 hex digits or the 24 words), --s3-secret-file, --file (recovery combine, one share per line), --root-words-file, --key-file (mcp); the environment variable VARSTO_VAULT_KEY, VARSTO_S3_SECRET, VARSTO_ORG_ROOT_WORDS, VARSTO_MCP_KEY; standard input when it is not a terminal (join, recovery combine, org admin, share accept, storage add-s3); otherwise a prompt without echo. On macOS the passphrase is stored in the login keychain by feeding add-generic-password to security -i on standard input instead of -w <passphrase> in the arguments. Tests: crates/varsto-cli/tests/cli_smoke.rs::secrets_stay_off_the_command_line (a short passphrase refused with nothing written, the removed options refused, join reading the key from standard input), main::tests (key text parsing). The recovery guide, the kit text and the lab scenarios use the new forms.

Updater freeze and rollback protection (S6, section 14). A download site that serves an old signed release, or withholds a newer one, cannot make a client install the old one. (a) manifest.json must carry a valid release signature (manifest.json.minisig, trusted comment file:manifest.json, the version it names must equal _version); an unsigned manifest is refused. (b) The signing time in the trusted comment of SHA256SUMS.sig must not be older than the newest one accepted before, kept in update-state.json in the device directory ({last_timestamp, last_version}, moved forward only after the archive passed every check); an older one is refused as a rollback. A signed list more than 90 days old is accepted with a warning, since it may simply be the newest release. (c) MIN_ACCEPTED_VERSION is the version compiled into the binary: a version equal to or older than it is never installed. (d) The GitHub cross-check is required: when the release list there cannot be fetched, the update is postponed with the reason, and varsto update --allow-single-source goes on with the signature alone (the interface never does). scripts/sign-release.sh signs manifest.json next to SHA256SUMS and --verify checks both; website/deploy.sh refuses to publish a manifest without a valid signature. Tests: update::tests (update_refuses_a_checksum_list_older_than_the_last_accepted, the_manifest_must_carry_the_release_signature, the_same_or_an_older_version_is_never_installed, update_waits_when_github_does_not_answer, a_signed_list_that_is_months_old_is_reported).

Bounded storage reads and pack index validation (S7, sections 28 and 30). No read from a storage can make the program allocate more than the object kind allows. Storage::get_bounded(key, max) refuses an object larger than max; get is get_bounded with storage::read_limit(key): MAX_CHUNK_SIZE + 64 (16 MiB and 64 bytes) for chunks/ and packs/, 256 MiB for records (vault/, manifests/, ledger/, org/ and the rest). The local directory and pool disks check the file size before reading and read at most one byte past the limit; S3 refuses a Content-Length over the limit before reading the body, caps the body it reads (it was 2 GiB for every request) and uses checked arithmetic for ranges; rclone is run with --count max+1 and its output is read through a cap (a listing may be up to 1 GiB), and the process is killed when it runs past it. A block read in the engine (fetch, scrub, verify, repair) is bounded by MAX_CHUNK_SIZE + 64. A claimed range (offset, len of a pack member) is clamped to a block object, with overflow-checked addition. PackIndex::validate(key) checks an index read from a storage: its pack id is 64 lowercase hex digits and equals the id in the index's own key, at most 4096 members, every member name is 64 lowercase hex digits (names were sliced with [..2], which panics in the middle of a multi-byte character), 0 < len <= MAX_CHUNK_SIZE + 64, and offset + len does not overflow and is at most 64 MiB. An index that fails is skipped, logged and counted (PackAware::invalid_indexes): not trusted, not a panic. A panic while reading one object during scrub, verify, repair or a fetch (storage::guarded) is an error for that object, not the end of the pass. Tests: packs::tests::an_index_that_lies_is_rejected_not_trusted, hostile_indexes_in_a_storage_do_not_panic_a_listing, s3::tests::a_response_that_claims_two_gib_is_refused_without_reading_it, a_block_read_is_capped_at_a_chunk_not_a_record, storage::bounded_read_tests. Format 2 (section 62) replaces the limits of packs/ objects and the JSON pack indexes; see "Read limits" there.

restic details out of logs and support bundles (S8, sections 35 and 45). The log scrubber cuts the login of every URL: scheme://user:password@host/... becomes scheme://[redacted]@host/... (redact::scrub), so rest:https://u:p@h/r and s3:https://K:S@h/b never reach a log line, wherever they came from. The repository is not logged at all: a debug line for a restic call names the repository's kind and host only (restic::repository_summary: rest:https://h, sftp:nas). Messages, varsto restic status and the recovery kit's note show the repository without its login (restic::display_repository), and the status shows only the first word of a password command (the rest of a command line may hold the password). The config.json copy in a support bundle (bundle_extras, redact::redact_config_json) has restic.password, restic.env_file and every access_key_id and secret_access_key replaced by [redacted], and the login of every URL cut; it is no longer copied as it is. Tests: redact::tests::url_userinfo_is_cut_everywhere, a_config_copy_for_a_bundle_has_no_credentials, restic::tests::repositories_are_shown_without_their_login, restic (CLI) tests::status_and_kit_show_no_login_and_no_password_command_arguments.

MCP keys (S9, section 37). The time a key was last used is kept in mcp-keys-used.json ({key id: seconds}, at most one write a minute), not in mcp-keys.json: checking a key reads the key file and never writes it, so a check running while revoke writes the file can no longer put the revoked key back (it used to read the whole file, set the time and write it back). A revoked key's use record goes with it. varsto mcp without a key is refused while the service runs ("the MCP server then needs an MCP key"): the session token would give the assistant everything; with no service it still opens the vault itself with VARSTO_PASSPHRASE. GET /api/status with a scoped key answers {"folders": [...]} with the folders the key may read and nothing else: no devices, no storages, no vault identity. Tests: mcp_keys::tests::a_check_never_rewrites_the_keys_and_cannot_resurrect_a_revoked_key, crates/varsto-cli/tests/mcp.rs (a_scoped_key_reaches_only_its_folders_through_the_service).

Names that cannot redraw the terminal (S10, sections 27, 46 and 51). names::check_display_name refuses a name of a device or a person with a control character (ESC[2A moves the cursor and redraws the fingerprint line), a zero-width character (U+200B to U+200F, U+2060 to U+2064, U+FEFF), a line or paragraph separator, a bidirectional control (U+202A to U+202E, U+2066 to U+2069, U+061C), or more than 64 characters. It runs when a name is made (device names at init, join, pair, share accept and org join; the names bound into a share request or an organization request) and again when a name is read from a code (ShareRequest::parse, OrgRequest::parse, a QR link), because a code is made by someone else. The command line shows every name through names::display (the same characters, if one gets in anyway, as \u{..} escapes): the QR caption, the approval questions and the member table. The page puts names in with textContent. Tests: names::tests::display_names_refuse_control_invisible_and_direction_characters, vault::tests::request_codes_with_control_or_direction_characters_are_refused, org::tests::request_names_with_control_or_direction_characters_are_refused.

Disk markers carry a MAC (S11, section 34). .varsto-disk.json holds the pool id and the vault tag in plain text on every disk of a pool, so anyone who has held one disk could copy the two fields under a new disk id and make a disk that every device of the vault adopted (and, with the most free space, chose as the favourite write target). A marker now also carries mac_hex = keyed_hash(derive(root, "disk-pool-marker"), aad("disk-pool-marker", pool_id, disk_id, created_utc)) (length-prefixed fields; aad is the same framing as elsewhere). A disk that is not in the pool's registry is adopted on sight only when its MAC is valid (constant-time comparison); a marker with the pool id and vault tag but no valid MAC makes it an unknown disk: it gets no writes and is not in the registry, varsto disk list names it ("unknown disk ... carries no valid marker MAC ... run varsto disk add <mount> --pool <pool> --label <label>"), and varsto disk add (also init and insert, which register or re-attach drives) takes it in on purpose and writes the MAC; disk list and a re-attach add the MAC to the marker of a known disk that predates it. A copy of a real marker with another disk id fails the MAC (the disk id is in the message), as does the real MAC copied along with it. A disk already in the registry is recognised by its id as before. Tests: pool::tests::a_copied_marker_without_a_valid_mac_is_never_adopted, crates/varsto-core/tests/disk_pool.rs::a_disk_with_a_copied_marker_is_not_adopted_until_the_user_adds_it.

Small network and file fixes (S12, sections 15, 28, 52).

  • Port mappings. A router mapping (mapped_tcp, mapped_udp of the peer record, section 52) is published only after the probe through the mapped UDP address came back to us (PortMapStatus.verified); before that the record carries none and a mapping alone does not make the device "reachable". Test: service::tests::a_mapping_is_published_only_after_the_probe_reached_us.
  • TCP peer server (section 15). A request head must arrive within 5 seconds of its first byte; a new connection that starts none is closed after 5 seconds (a connection kept open between requests still has 30 seconds). At most 8 connections of one address may hold a request head that has begun and is not whole; the next one to begin a head is closed at once. A head normally arrives in one piece and then takes no slot, so a peer with many parallel requests (the fetch window is 32) is not held back, while a slowloris fills its eight slots and loses them at the deadline. Test: p2p::tests::unfinished_request_heads_are_limited_and_time_out.
  • QUIC. ServerConfig::max_incoming is 256, a connection may have 64 bidirectional streams open (the fetch window is 32) and no unidirectional ones.
  • Temporary files. The files Varsto writes beside a folder's files while downloading (.varsto-tmp-<pid>-<random>), writing through the engine (.varsto-upload-…) and importing (.varsto-import-…) are created with O_EXCL under a random name and mode 0600, so a link or file another local user plants under the old name .varsto-tmp-<pid> is never written through. The mode the folder records for the file (default: what a new file gets here) is set with fchmod on the open file before it is renamed into place; before, the file had the default mode from the rename until the metadata step. A download also gives the open file the modification time of the file state (the writer's, as a restore does), and the local index takes the time the disk then shows; before, a pulled file was dated when it was downloaded. Any error between creating a temporary file and renaming it into place (a storage that fails, a full disk, a refused rename) removes it. A scan of a folder (not of a backup's source) removes the temporary files a stopped process left: a regular file named exactly .varsto-<tmp|upload|import>-<pid>-<16 hex digits> or .varsto-scrub-<16 hex digits> whose modification time is at least 24 hours old (a transfer in progress writes its file continually); other names beginning .varsto are left alone. Tests: crates/varsto-core/tests/temp_files.rs, crates/varsto-core/tests/ignore_and_metadata.rs::pulled_files_keep_their_modification_time, util::tests::only_varstos_own_temporary_names_count_as_folder_temporaries.
  • Paths. A manifest, a trash record or a note that names a path with a component beginning .varsto (except .varstoignore) or ending .varsto-placeholder or .varsto-link is refused (names::check_synced_path): those are Varsto's own files and are never synced, so an honest device never writes such a path, and one that did would overwrite the folder marker or a placeholder of another device. Tests: names::tests::synced_paths_never_name_a_file_of_varsto_itself, manifest::tests::a_manifest_cannot_name_files_of_varsto_itself.

62. Format 2: blocks, packs and the keyed chunker

Superseded by section 77 (storage format 3): packs are padded to size classes, blocks are found through the folder block maps, and nothing writes block objects, pack indexes or tombstones (77.2, 77.3). Kept as the history of format 2.

A security review (2026-10-13, findings H1 and H8) found that the nonce of a chunk object was derived from the chunk id while the encrypted input was the zstd output, which is not guaranteed to be the same across zstd versions, and that a storage could recognise a known file from the sizes of its block objects, because cut points were a public function of the content and every block was an object of its own. Format 2 changes the blocks; the records (signed envelopes, grants, recovery) change alongside it in their own section. Vaults are created fresh; nothing older is read. FORMAT_VERSION is 2 (varsto_core::FORMAT_VERSION, bound into every associated-data string and written to vault/meta.json and vault.json): a build refuses a vault of any other value before it reads a block, and the message says what to do (varsto_core::format_mismatch): for format 1, the vault of 0.0.1-alpha.14 and earlier, that it has to be recreated (varsto reset --yes, varsto init, sync the files into the new vault); for a newer format, to update. Measured in the lab (scenario upgrade-from-alpha-14): a build with format 1 still in FORMAT_VERSION opened an alpha.14 vault (status worked) but found none of its 3135 blocks, since they are objects of their own under chunks/ and no longer read; the bump turns that into a clear refusal. Alpha.14 itself refuses a format 2 vault with its own text, "vault format version 2 is not readable by this version (1)".

Nonce and associated data. A chunk object is nonce || ciphertext || tag (XChaCha20-Poly1305) as before, made by one function (chunk_seal::seal_chunk) for every writer: a push, the block cache, an import, a data move, a Strongroom conversion and a peer serving a block again. The key is derive(K9 of the epoch, "chunk-key", folder, chunk id); the nonce is the first 24 bytes of keyed_hash(derive(K9 of the epoch, "chunk-nonce", folder), packed), where packed is the exact AEAD input (section 16); the associated data is (format, AEAD, chunk, vault, folder, epoch, chunk id, plaintext length, packed length). A reader (chunk_seal::open_chunk) takes the packed length from the object's length, opens it, checks that the nonce is the one the packed bytes give (an object with a nonce of its own choosing is refused), unpacks it and checks the plaintext against the chunk id. The same bytes therefore always give the same object (deduplication and content addressing hold); two encodings of one chunk give two objects and two nonces, never one nonce over two inputs.

Compression. zstd level 3 after a 64 KiB level-1 probe, as section 16 describes. Measured on one core of the build machine (release build, 64 MiB in 1 MiB chunks): log-like text 51 MB/s at level 12 against 560 MB/s now, stored as 12.2 % and 14.7 % of the input; random data 1.7 GB/s against 19.5 GB/s (stored raw either way).

Keyed chunker and size tiers. The Gear table is 256 words of the BLAKE3 output keyed by the folder's chunker seed derive(K11, "chunker-seed", folder) (chunking::gear_table). K11 is fixed at the folder's first epoch, so a key rotation moves no cut point and deduplication survives it. Block sizes follow the file size (ChunkerParams::for_size(size, seed)): under 1 MiB one block; 1 to 32 MiB 256 KiB to 4 MiB, average 1 MiB; 32 MiB to 1 GiB 1 to 16 MiB, average 4 MiB; from 1 GiB 2 to 16 MiB, average 8 MiB. Content of unknown size (an import from a stream, the block cache without a size) is cut with the 1 MiB tier. A file entry cut with the tiers of its size says chunking: 2 (absent otherwise), so a device can cut the file again the same way.

Packs. Every block a device writes to a storage is appended to a pack: packs/<xx>/<pack id>, the block objects one after another, then random padding (below), where the pack id is the BLAKE3 hash of the pack's bytes, padding included and <xx> its first two hex digits. A push collects, per target set (the storages a block goes to, with cold storages apart from the others because their largest class differs), the blocks that set needs until a pack's worth is together: 64 MiB on hot, local, pool and transferrer storages, 256 MiB on cold ones; each pack is built once and the same bytes are written to every storage of the set, so it has one id on all of them. Packs are written with put-if-absent; on S3 an object above 64 MiB is written as a multipart upload in 16 MiB parts (each part's ETag is the MD5 of its bytes; a server that refuses the upload gets one PUT, and a HEAD first finds a pack that is there, since the name is the hash of the bytes). The bytes a push holds are bounded by the pack sizes of the storages it writes (128 to 768 MiB); when the bound is reached, what each storage collected is written as it is, so a pack may be smaller than the target. Data moves, drains and moves to the trash storage write each group of blocks (up to 64) as one call, so as packs too; a staged move to a pool whose disk has no room for the whole group splits it in halves until the parts fit, so a disk fills to its edge. A repair collects the good copies per storage, a storage removal the copies per target, and a Strongroom conversion the re-encrypted blocks of many files, each up to a pack's worth, before writing; an import collects the blocks of many contents into packs of up to 64 MiB exactly like a push (two packs written at a time, one queued, one filling), so that a small file is no pack of its own; a content counts as imported, and its blocks are recorded in the ledger, once every pack with one of its blocks is written, and the packs collected so far are written, however small, before each checkpoint of the run (every 500 contents or 20 seconds) and at its end.

Size classes. A pack is not its members' size: after the last member the writer appends random bytes (the operating system's CSPRNG), and the length of a pack is exactly one size class: 256 KiB, 1, 4, 16 or 64 MiB on hot, local, pool and transferrer storages, and the same plus 256 MiB on cold ones. A pack closes when the next member would pass the largest class of its storage (a member is at most 16 MiB and 41 bytes, so it always fits), the members of a push are placed first-fit decreasing so that full packs are nearly all members, and the pack of what is left takes the smallest class its members fit in. Every pack written is padded: a push, a move, a repair, a conversion, an import, a disk fill, and the rewrite of a pack in garbage collection. Nothing addresses the padding. Members are found by (offset, len) from the ledger place or the pack index; the pack id is the hash of the whole padded object; pack_len in claims, indexes and tombstones is the padded length; verification of a whole pack (disk check, scrub) hashes the whole object; replicas copy the pack whole. Format 2 reads a pack, place, index or tombstone entry of any length up to storage::MAX_PACK (exactly 256 MiB): packs of older builds, which are not padded, are still read, verified and collected; only writes produce size classes. A format 3 reader (feature format3) refuses a length that is no class (pack <id> has length <n>, not a size class). The padding is bounded by the next class: a pack is never larger than the next class above its members (a 1-byte push is a 256 KiB object, 256 KiB + 1 byte is 1 MiB, 5 MiB is 16 MiB, 70 MiB on a hot storage is a full 64 MiB pack and a second one of 8 MiB, which takes the 16 MiB class). The change needs no new format version: the padding is trailing bytes nobody addresses. A device on a build before it reads padded packs but, in garbage collection, leaves a padded pack alone, and an emptied one stays until a newer device removes it. Format 3 keeps packs as the unit and the size classes; the padding carries over. A push builds one pack per target set: two hot storages a block goes to hold the same pack under the same id. A storage of the set that holds one of the members already (another device wrote it there), or a pool without a disk, is not written the shared pack: the first builds its own pack of the members it lacks, the second takes nothing this time (storages_unavailable) without stopping the others. Imports, data moves, drains, repairs, forwarding, staged moves and conversions still build their packs per storage.

No block is an object of its own any more: chunks/ is not written. A block keeps its object name, the hash of its bytes, which the ledger, verification and peers use, and every reader still checks it.

Where a block is. The chunk_stored event carries pack: {pack, offset, len, pack_len} beside the object name: the place the writer's storage holds the block at. In the location view (section 6) each storage location of a chunk keeps the place from the newest claim that names one (Lamport time, then the larger place, so applying batches in any order gives the same view; view format 7). Whenever the view changes, the engine hands every place in it to the pack layer it shares with every storage it opens (packs::PackContext), with the places of packs it wrote itself; a chunks/<xx>/<object> read is a ranged read of the pack at that place, on a storage that lists the pack (packs/ is listed once per process and again at most every 30 seconds on a miss). Readers therefore need no index: the ledger they hold says where every block is. An engine hands the view over before it opens its first storage, so a fresh process (a single CLI command) finds blocks too; a place the view drops (a block whose drop was just sealed) stays known to the process, so the deletion that follows finds the block. A read that misses the listed packs tries every live place it knows with a ranged read, also in packs another thread listed meanwhile. Events recorded before their storage's pack existed get their place when they are sealed or kept for the next batch.

Pack index. At the same moment the packs written since are listed in packs/index/<device>/<seq>.enc, one record per storage and folder: (pack, offset, length, pack length, object name, chunk id) for every block whose claim is in the batch, as fixed-width binary entries (format byte 2, kind, count, then 32 + 8 + 8 + 8 + 32 + 32 bytes per entry), zstd-compressed, encrypted under the folder's metadata key K10 with associated data (format, pack-index, vault, folder, device, seq). seq is the next free number of the device's indexes on that storage (tombstone lists are numbered the same way). The index is for fsck, ledger rebuild (which reads every index it can open before it lists blocks, section 38), devices that join later, and members of shared folders: they do not hold the vault ledger, so before each pull of a shared folder a member reads the indexes it has not read yet that open under the folder's metadata keys and learns the places from them (an index no key opens is tried again when the folder keys change); the record envelope of the records work replaces the AEAD wrapper through record_shim.

Deletion and garbage collection. Deleting a block marks it dead in its pack and adds it to this device's tombstone list for the storage; the list is written as packs/tombstones/<device>/<seq>.enc (same binary entries without the chunk id, kind tombstones) at the end of each operation that deleted blocks, one list per folder: under the folder's metadata key K10 with associated data (format, tombstones, vault, folder, device, seq) for the blocks the view places in a folder whose key the device holds, so every device of the folder (members of a shared folder too) reads what the others deleted; under a key derived from the vault key of epoch 0 (pack-tombstones, empty scope) for the rest. Each device reads the lists it has not read when it lists a storage's packs, trying the vault key and then the metadata keys of its folders; a list no key opens is tried again once the device's folder keys change. A tombstone of another device kills a member only where no live claim of the view places a block on that storage at that pack and offset: a member of a shared folder, or a device whose ledger is behind, cannot make another device drop or rewrite away a block the ledger still holds (a hostile tombstone only makes reads of that copy go elsewhere). A device's own deletions count at once. A pack whose every byte is dead is deleted by whoever kills its last block; when that deletion fails (a read-only directory, a storage that refuses), the block stays dead and the pack is left to garbage collection. A hot pack more than half dead is rewritten by pack_upkeep (run at the end of the trash upkeep): its live blocks are read from one GET of the pack, checked against their names, written into a new pack and claimed there in one batch, then the old pack is deleted. A device rewrites only packs whose every live block belongs to a folder whose key it holds and whose bytes it can account for completely (live blocks and tombstones cover the pack); cold packs are never rewritten, their dead space goes with the pack.

Verification and repair. Automatic verification groups the blocks due by pack and reads each group with one ranged request spanning them (packs::read_members); a pool disk check and a scrub of a disk hash each pack against its id and count it for every block the ledger places in it. The scrub of other storages reads each block at its place. A repair of a corrupt block writes a tombstone for it and a new pack with the good copy.

Pools and transferrers. Pools and transferrers keep packs like any storage (section 19). A pool reads a block with a ranged read of the pack file on the disk that holds it. A pool holds blocks only: it gets no pack indexes and no tombstone lists. Its packs are known from the ledger (each claim names its pack), and a disk insert tidies away a pack only when the ledger dropped it from the pool (section 34), so neither record is needed to find or remove it. A staged move (section 59) writes packs to the pool and counts a disk group rule by the places that hold the pack. A disk's tidy, check and fake-capacity measurement list packs/ beside chunks/; a fill counts blocks, also for a pack it copies whole to another place.

Read limits. Section 60 (S7) bounds every storage read by the kind of object; format 2 keeps the bounds and changes the kinds. A block read (chunks/<xx>/<object>) is at most 16 MiB and 64 bytes; a pack (packs/<xx>/<id>) at most storage::MAX_PACK, the largest size class (256 MiB, cold); pack indexes and tombstone lists are records (256 MiB). A pack store reads a whole pack (garbage collection) up to its own top size class, so a 64 MiB storage never reads a 256 MiB object. A place from the ledger is used only when it fits in a pack of at most MAX_PACK bytes (PackLoc::valid), and a ranged read, of one block or of the span of several in verification, is clamped to MAX_PACK. Pack ids and object names are sliced without splitting a character.

Replicas. A replica copies packs whole, each checked against its id, and copies pack indexes and tombstone lists as they are. It claims a pack by its id (object and chunk id in an object claim, section 58); the owner's view gives every block placed in that pack on any storage a copy on the replica at the same place.

Peers. Peers still ask for single block objects. A device serves a block from a pack on a local-directory storage at the place the ledger gives, from the block cache, or encrypts it again from the local file, which gives the stored object because key, nonce and packing are deterministic for one zstd version (otherwise the name does not match and the peer asks elsewhere).

What a storage learns. Pack size classes (256 KiB, 1, 4, 16, 64 or 256 MiB; the data's size only to within the class), at most one push and folder per pack, the number and timing of pack indexes and tombstone lists, and which packs go away; not the size or number of blocks in a pack, nor where one ends. The same file pushed to two folders is cut at other places and packed into other packs. A pack index and a tombstone list are opaque.

Limits.

  • Pack places come from the ledger: a device whose ledger lacks a claim (not pulled yet, or lost) finds the block only after the next pull or by reading the pack indexes (ledger rebuild). A reader with an old place for a block that garbage collection moved misses it until it pulls the claim of the new place.
  • A device lists the tombstones of a block under the vault key when its view places the block in no folder whose key it holds; devices without the vault key (members of shared folders) cannot read those.
  • A block deleted on one device while another device skips writing it because it is still in the pack survives a rewrite of the pack only if the rewriting device's view already holds the second device's claim; otherwise verification reports the missing copy and repair writes it again.
  • The last pack of a push, move, repair, conversion or import, and a pack written because a checkpoint or the buffer bound forced it, is smaller than the target; padding hides its size inside a class. The class still tells a storage the order of magnitude of the data, and the number of full packs tells the size of a large push to within a pack. Cost: a 1-byte push stores a 256 KiB object, anything above 256 KiB less than four times its size, and a large push one padded last pack; a hot pack more than half dead counts padding as free space, so a pack is rewritten when more than half of its members' bytes are dead.
  • Garbage collection and the removal of an emptied pack account for the members from offset 0; what follows the last known member must be the padding of the pack's class. A member this device does not know that lies after the last known one hides in the padding (one in the middle still shows as a gap); a pack has one writer and one push, so this takes a device whose ledger lacks the claims of that push's last blocks and no others of the pack.
  • Measured on the benchmark data (scripts/bench/gen-data.py, release build, one local directory storage): a push of 50 000 small files (1 456 959 306 bytes) stores 22 packs of 1 476 395 008 bytes, 1.3 % over the data; a push of one 1 GiB incompressible file (blocks of 1 to 16 MiB) stores 17 packs, 1 090 519 040 bytes (16 of 64 MiB and a last one of 16 MiB), 1.6 % over the data. A push collects per target set one pack's worth plus one block, fills a pack from that buffer first fit decreasing (packs::first_fit_decreasing) and keeps the rest for the next one, so only the last pack is not full. Moves, repairs, drains, forwarding and conversions fill a buffer to the target first and let the writer split what passes it, so each of their batches can end in a padded tail pack.
  • An import that is stopped keeps the contents already recorded; the blocks of a content found damaged after some of them were written stay in their pack, claimed by no one.
  • A pool pack keeps its dead bytes until every block in it is gone: packs on removable disks are not rewritten.
  • .idx files and .del. markers of format 1 are not read.

Tests: chunk_seal::tests (no two encodings of a chunk share a nonce over 200 chunks and six encodings each, the same bytes give the same nonce, a chosen nonce is refused), pack::tests (round trips of 1, 63, 64, 4095, 4096, 300 000 and 16 MiB bytes; the probe), chunking::tests (different seeds cut differently, the same seed alike; size tiers), packs::tests (blocks of those sizes through a pack, packs cut at the target, tombstones and an emptied pack, rewriting a mostly dead pack, index and tombstone bodies, one request per pack, folder-scoped tombstone lists read by another device of the folder, a hostile tombstone that cannot kill a claimed block, places outside the read limits refused), storage::bounded_read_tests (a pack is read up to MAX_PACK), s3::tests::large_objects_are_uploaded_in_parts, tests/packs.rs (the same 10 MiB file in two folders gives other pack layouts and no block objects; a mostly dead pack is rewritten and a device that joins afterwards reads the moved block), tests/chunk_sizes.rs, and every test that damages, loses or counts blocks through tests/common (packs are found through the record of packs a debug build keeps of what it wrote, packs::debug_registry).

63. Folder protection: the safety indicator of the interface

Why. The folder list and the navigation show, for every folder, whether its files are safe. The answer is computed by the service from the ledger view, not guessed by the page, and is part of every folder in GET /api/status (FolderStatus.protection; a key limited to some folders sees it for those only). Nothing is stored; no format changes.

What counts. For a folder, the unique blocks of its current files (a block used by several files counts once; a deleted file counts nothing), weighted by their plaintext size (the same bytes as the folder's bytes, deduplicated). A block has a copy in a class when the ledger shows a claim on a storage of that class (Location.claimed_by not empty):

  • cloud: external storage, an S3 or rclone storage by its kind (the storage's place label does not change this).
  • disks: the user's own disks, a directory storage or a disk pool. A pool disk that is away still counts: the copy exists, only its reading waits.
  • devices: a device holds the plaintext (this device's files, judged from the local index like the data map; other devices as the ledger lists them for the block) or an untrusted replica (replica: storages) holds the block. A storage that is not configured on this device and is not a replica is counted here too, never as external: the safe reading.

Transferrers (carriers) keep no copy and count nowhere. A block can count in several classes.

Fields. protection has state, pct, total_bytes, total_blocks, the classes cloud, disks, devices (each bytes, pct, blocks, verified_bytes, verified_pct), external_bytes, unprotected_bytes, unprotected_blocks, missing_bytes and policy_state. A percentage is rounded down to one decimal and is 100 only when every byte is covered. pct is the share of bytes with a copy in cloud or disks. Verified is the part that a device other than the writer has read back (Location::independently_verified); the state is decided by claimed copies, so a vault with one device is not shown as unsafe for lack of a second checker, and the interface shows the verified share beside it. unprotected_* are the blocks with a copy in neither cloud nor disks; missing_bytes are those that no device holds either. policy_state is the folder's durability policy verdict (section 14: ok, at_risk, violated, unknown) or absent without a policy. FolderStatus.last_change_utc is the newest modification time of a current file.

States. state is the first that holds:

state meaning interface colour
empty no current file in the ledger grey
cloud every byte has a copy in external storage green, "100 % in external storage"
disks every byte has a copy on own disks, not all in the cloud blue, "100 % on your own disks only (no cloud copy)"
mixed every byte has an external copy, but neither class has them all blue, dashed
partial some bytes have an external copy amber, "Partly protected: N %"
device no byte has an external copy red, "Only on devices: no external copy"

The interface (ui/folders.js) uses colour-blind-safe hues (Okabe-Ito), an icon and words for each state, in both themes. The badge is shown in the navigation, in the folder overview on the Files page and on a phone's folder cards; a tooltip (and the folder header) lists the classes with their verified shares, what has no copy outside devices and the policy verdict.

Limits. The ledger is what this device knows: claims of devices it has not pulled yet are not counted. A folder whose file list this device never fetched is empty. A file published but not yet pushed to any storage is device.

Tests: crates/varsto-core/tests/protection.rs (unpushed, directory, transferrer, cloud via rclone, disk pool, claimed versus verified on two devices), engine::protection::tests, and desktop::tests::status_carries_the_protection_of_each_folder (the API field).

64. Live visualization (/api/viz)

Why. One screen, readable from across a room, that shows where the data is, what moves where right now, whether it is safe and what it costs. The page (Visualization in the navigation, ui/viz.js) draws an isometric board on one <canvas> from a single snapshot; it needs no other request.

GET /api/viz. The session token as for the other /api routes (X-Varsto-Token or Authorization: Bearer; 401 without), answered on a thread of its own without waiting for the state lock (section 71), Cache-Control: no-store. The page asks once a second while it is shown. The snapshot is joined from two parts that the engine computes only when the lock is free and the service keeps: the ledger part (devices, storages, folders, copies, policies; one pass over the ledger view and the folder states; at most every 20 s) and the small part (pool disks from the pool indexes, drains, staged moves, repair, verification and bit-rot schedules, backups; at most every 3 s). While a sync holds the engine the last parts are served with "stale": true; the live part (tasks of this device and of the peers, peer traffic) is always current. Nothing is read from a storage. A locked or empty vault gives "unlocked": false and empty lists; the page then draws demo data and says so.

All figures are bytes, bytes per second, UTC seconds or counts; eta_utc is null when it cannot be told (the page shows a dash). Names are display names. Node ids tie flows to nodes: d:<device id>, s:<storage name>, p:<disk label>.

Key Contents
v, utc, unlocked, stale, data_utc, light_utc layout version (1), the service's clock (the page corrects its own by it), whether the vault is open, whether engine parts are old, when each part was computed
this_device, vault_name, key_epoch, member, total_bytes this device's id and name, the vault key epoch (section 21), a member device of another user's vault, bytes of the current files' blocks
devices[] id, name, role (this, peer, replica, member), platform, online, busy, path (direct-lan, direct, relayed via ...), rx_bps, tx_bps, app_version, last_sync_utc; removed devices are left out
storages[] name, id, kind (directory, s3, rclone, pool, transferrer, replica, unknown), place, configured, cold, carrier, data_bytes, verified_bytes (checked by a device other than the writer), used_bytes, quota_bytes, percent, state (none, ok, warning, full; section 44), price (per_gb_month, egress_per_gb, retrieval_per_gb, currency, source), monthly_cost, read_all_cost, drain (phase, percent, bytes_left, eta_utc, last_error) or null
disks count, docked (labels), working_on (the label a disk task runs on), list[]: pool, label, place, docked, retired, capacity_bytes, used_bytes, free_bytes, objects, last_verified_utc, overdue_share, failing (reason or null), reclaimable_bytes, phase (verify, fill, tidy, fsck, fetch, init, unmount, idle, wanted, away), progress (percent), eta_utc, wanted_by (id of a move that waits for a disk of the pool)
folders[] name, bytes, files, blocks, mode, shared, read_only, strongroom, paused, policy (in words), policy_state (none, ok, at_risk, violated, unknown; section 14), policy_reasons, policy_warnings, blocks_short_of_copies, blocks_unverified_in_window, oldest_verification_days, unprotected_blocks, verified_blocks, unverified_blocks, local_only_blocks, missing_blocks, storages and devices (bytes by name or id), targets (the storages new blocks go to on this device)
copies blocks and bytes by kept copies (0, 1, 2, 3 or more) and the byte-weighted average
flows[] id, kind (upload, download, disk_fill, drain, move, p2p, relay), from, to (node ids), folder, bps, unit, done, total, remaining, eta_utc; an upload has one flow per target storage sharing the task's rate; a download comes from the storage holding most of the folder; p2p and relay come from the traffic counters (section 15)
jobs[] the activity tasks of this device and of the peers (section 32): id, kind, phase, subject, detail, device, device_name, done, total, unit, percent, rate, eta_utc, started_utc; eta_utc is the task's own, or from rate and the remaining count
moves[], drains[], backups[] open staged moves (section 59) with waiting (disk, room, place) and waiting_disk; drains (section 44); backups with the last and the next snapshot
alerts[] level (bad, warn, info), code, subject, text: a ledger problem, forked devices, a policy at risk or violated, missing blocks, a paused folder, a full or nearly full storage, a blocked drain, a failing disk, damaged copies, a move waiting for a disk
health overall (ok, warn, bad), ledger, verify and scrub (enabled, last_run_utc, next_run_utc, last_error), repair (queued, losses, last_error)
traffic rx_bps, tx_bps, relay_bps, active and the last 60 seconds of each (section 15)
cost estimate (always true), month and read_all_once (amount by currency, never converted), unpriced (storages holding data with no price), note; the prices are the user's or the built-in data of section 20 and exclude request fees and tax

The page. Reached from the navigation (and the More page on a phone); a plain <canvas> with no scripts from elsewhere, the files /viz.js, /viz.css and /viz/*.webp are static assets of the service under the page's strict content security policy (/viz/manifest.json gives each sprite's floor anchor and its width in metres). The sprites are the website's Blender objects (laptop, phone, tablet, monitor, NAS, disk in four states, shelf, USB stick, cloud, bucket, archive, and the disk dock: an open-top docking bay with a status LED and a power button, alone or with a 3.5-inch drive standing in its slot in the drive's state) rendered on a transparent background by website/tools/render/viz_sprites.py in the light and the dark palette at 512 and 1024 px. The board has three rows (devices, home, cloud); flows are tubes with particles running from sender to receiver, their label showing folder, rate and estimated finish. The particles move at a speed that follows bytes per second but is bounded by the size of the board: a board width takes between 14 and 7 seconds, nothing is faster than 240 CSS pixels per second, and no more than two particles passing a point per second; it is computed from the time between frames, not from the canvas size, the pixel ratio or the refresh rate, and with prefers-reduced-motion they only creep (4 px/s). A flow's label keeps its place: the place is chosen once per flow (same two nodes, kind and folder) and kept while it is free; a label that overlaps something moves only after 3 seconds of continuous overlap; a refresh changes the text only, and the label's width grows at once but shrinks only after 10 seconds, so changing numbers do not move or breathe it; parallel flows keep their lanes (they are ordered by their key, not by the order of the data). Verification, repair and drain run as pulsing rings; a docked disk stands in the dock's slot (its own picture, light or dark) with its phase beside the dock and its progress above it; storages show their fullness, price estimate and verified share. Full screen (button or F; Esc and the button leave it, and so does Back on a phone) is built in layers so that it is really the whole screen wherever the page runs: the board always switches to a cover mode (it moves to the document body and fills the viewport, 100dvw by 100dvh, with all other page content and the scrollbars hidden); on top of that, inside an app shell the shell is asked to put its window into full screen (Android: VarstoAndroid.setFullscreen hides the system bars, the page answers the Back key itself; macOS: the varstoShell script message toggles the window's full-screen mode; Windows window: window.ipc message varsto:fullscreen:1|0 sets borderless full screen), and in a browser the Fullscreen API is used; a shell tells the page about its own changes through window.varstoShellFullscreen(on). The mouse pointer and the bar are hidden after 4 idle seconds in full screen; the canvas is sized from the element's CSS size times devicePixelRatio (up to 8192 px and 36 megapixels) and sized again on resize, a change of the screen, an orientation change and a change of the pixel ratio; the display's native size (screen.width x devicePixelRatio) is shown beside the canvas size. The 1024 px sprites are used when a sprite is drawn wider than 440 device pixels. Drawing is limited to about 30 frames per second while a flow or ring moves and once a second otherwise (with prefers-reduced-motion about 8 frames per second). The background follows the theme, or is Light, or pure black (#000, with the dark sprites) from a control that is kept in localStorage (varsto-viz-bg). Below 1100 px the panels stack under the picture.

What the page shows before and without data. The page draws only what /api/viz has answered; it has no example content of its own to fall back on. Until the first answer it shows a quiet "Loading..." note over an empty board (no devices, flows, costs or panels); a first answer that fails shows "No answer from the service" with a "Try again" button; a locked vault shows that it is locked; an unlocked vault without storages draws its devices and says that no storage has been added. Every time the page is opened it starts again from nothing, so an earlier session's picture is never shown as current. An answer marked stale (the service is busy) or a later failed request keeps the last real data but draws it dimmed with the age of the last live answer in the status line, never as live. The built-in example scene used for the screenshots is reachable only when the screenshot driver sets window.__VARSTO_VIZ_TEST = true before the page loads; no URL parameter, stored value or service answer enables it. Tests: the state machine in scripts/test/viz-rules.test.js, viz::tests::page_has_no_demo_scene_entry_points, and scripts/test/viz-first-paint.py (Playwright at 390 x 844 with a delayed and a failing first answer).

Tests: tests/viz_snapshot.rs (a fixture vault with a home storage, a priced cloud storage, a pool with one docked disk and a running upload and a running disk check given by hand: storages, price and cost, the docked disk's phase and progress, one flow per target with the shared rate and the finish time, determinism; the empty snapshot), viz::tests in the command line (the token rules, the static assets and their types, no external address or inline script in the new files, every sprite present, Finnish and Swedish for every word the page shows), and scripts/test/viz-rules.test.js (node; run from viz::tests: particle speed bounds and the label rules), and Playwright screenshots at 3840 x 2160 (pixel ratio 1 and 2) and at phone width.

65. The Windows window, installer and automatic updates

The interface of section 10 is one web page served by the background service on 127.0.0.1. Every platform shows that same page in a window of the platform's own kind, so the screens are alike and only the frame follows the system: the macOS app in a WebKit view (apps/macos), the Android app in a WebView (apps/android), and on Windows varsto-window.exe (crates/varsto-window) in a WebView2 view through the wry and tao crates. Linux keeps the browser (a WebKitGTK shell would need system libraries the static musl build cannot carry).

Window. varsto-window [--home DIR] reads service.json, starts varsto.exe tray (which starts the service) when no service answers, and opens http://127.0.0.1:<port>/?boot=<code> with a one-time code from POST /api/session/boot, exactly as the browser flow of section 10. When service.json changes (the service restarted after an update) it opens the page again with a new code. The view is in-private (the session token and the page's storage never reach the disk), allows the camera for the QR scanner and nothing else, keeps navigation on 127.0.0.1 and hands every other address to the default browser. One window per user: a named mutex, and a second launch finds the first by a window property and brings it to the front. Size, position and the maximised state are kept in %LOCALAPPDATA%\Varsto\window.json and dropped when their monitor is gone. Closing the window ends only the window program. The tray's "Open Varsto" starts it (varsto-window.exe beside varsto.exe), and falls back to the browser when the file is missing. Without the WebView2 runtime, or when the view cannot start, the interface opens in the default browser and a message offers Microsoft's bootstrapper. varsto-window --background is the login starter: it starts the tray app invisibly and exits.

Installer. installer/windows/varsto.iss (Inno Setup) builds Varsto-<version>-setup.exe from varsto.exe, varsto-window.exe and the icon (make-ico.py, from brand/png). The AppId never changes; a new setup reads the installed version from the uninstall entry, says whether it upgrades, repairs or downgrades, closes the window, the tray and the service of that installation (tray first, because it restarts the service; the service is asked to quit; what remains is ended), replaces the files, runs varsto install (Explorer verbs, section 10) and starts the tray again. A downgrade is a question in the wizard and refused when silent. The data folder (%APPDATA%\Varsto or VARSTO_HOME) is never touched by an upgrade, and by an uninstall only when asked (/DELETEDATA=1 when silent). Login start is a Run key naming varsto-window.exe --background. Per-user is the default; "for all users" asks for elevation.

Automatic updates. A copy installed by the setup program (its unins000.exe sits beside the binary) takes Varsto-<version>-setup.exe as its update file: it is listed in the signed SHA256SUMS like every file and passes the same checks as an archive (section 10, section 60: signature, version named in the trusted comment, signing time not older than the last list accepted, GitHub as the second channel, SHA-256 of the download), is saved in a private folder and run detached with /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /CLOSEAPPLICATIONS; the setup program restarts Varsto itself. Windows has no other package: there is no portable zip, and a copy the setup program did not install (an old portable alpha.14) does not update itself; varsto update and varsto update --daily tell it to download and run the installer once, after which updates continue automatically. The service checks once a day (the first check two minutes after it starts; auto-update-checked in the device directory); where the setup program installed it, it installs by itself, elsewhere it shows a notification once per version. The setting auto-update (file in the device directory; varsto config auto-update on|off, GET/POST /api/update/settings, the Service card of the settings page) turns the daily check off. Nothing is ever installed without the signature chain.

66. What formatting a drive means: GPT, one aligned partition, one filesystem choice

Every place that formats a drive for Varsto follows one layout, defined in varsto_core::diskformat and nowhere else.

Layout. A GPT partition table (never MBR/msdos) with its protective MBR, so that old tools see a fully used drive and leave it alone; exactly one partition that starts at 1 MiB (sgdisk -n 1:1M:0; sgdisk rounds the start up to its own alignment, so 512e, 4Kn, SSD and RAID drives are all aligned) and runs to the last usable sector; the GPT partition type that fits the filesystem (Linux filesystem data 0fc63daf-8483-4772-8e79-3d69d8477de4, 8300, for ext4; Microsoft basic data ebd0a0a2-b9e5-4433-87c0-68b6b72699c7, 0700, for exFAT and NTFS; Apple APFS 7c3457ef-0000-11aa-aa11-00306543ecac, AF0A, for APFS); a random PARTUUID chosen beforehand (it is how disks.conf finds the disk again, section 34); the partition name varsto-<disk name> (36 characters at most); and a volume label reduced to ASCII letters, digits, - and _ (16 bytes for ext4, 11 for exFAT, 32 for NTFS), which is also what makes the label safe inside a shell or PowerShell string. FAT32 is never made.

Filesystem choice. ext4 stays the default on Linux and is the only filesystem varsto disk init makes: a pool keeps one file per encrypted block, needs POSIX permissions and rename, is checked with e2fsck before every mount (section 34) and was always ext4, so nothing changes for existing disks. The other choices are defined for the platforms that cannot make ext4: exFAT is the cross-platform filesystem for a drive that moves between Linux, macOS and Windows (no 4 GiB file limit, no extra driver on macOS or Windows), APFS is for a drive only a Mac reads, NTFS for one only Windows reads. Fs::default_for(os) is ext4 on Linux and exFAT on macOS and Windows; Fs::supported_on(os) says what each system can make.

Commands. Pure functions turn a device, a name and a filesystem into command lines and run nothing:

  • Linux (linux_commands, run by blockdev::INIT_SCRIPT in one privileged call): sgdisk -Z, sgdisk -o, sgdisk -n 1:1M:0 -t 1:8300 -u 1:<uuid> -c 1:varsto-<name>, partprobe, mkfs.ext4 .... A unit test substitutes the script's arguments into its sgdisk lines and compares them with the pure list.
  • macOS (macos_commands, defined, not yet run because disk init is still Linux only): diskutil unmountDisk /dev/diskN, then diskutil eraseDisk ExFAT|APFS <name> GPT /dev/diskN. eraseDisk with GPT writes the table with its protective MBR and aligns the partitions itself; it also adds the small EFI system partition every Mac GPT disk has.
  • Windows (windows_commands, defined, not yet run): Clear-Disk -Number N -RemoveData -RemoveOEM, Initialize-Disk -Number N -PartitionStyle GPT, New-Partition -DiskNumber N -UseMaximumSize -Alignment 1048576 -GptType '{ebd0a0a2-...}' | Format-Volume -FileSystem exFAT|NTFS -NewFileSystemLabel '<label>'.

Refusals. Only whole drives are formatted, and only the one the user named and confirmed. Linux: the path must be a block device lsblk lists as a whole disk (not a partition, not a mapping), with nothing mounted or used as swap on it, no volume manager, RAID or encryption signature, and none of /, /boot, /home, Varsto's directory or the program on it (section 34); the path must be under /dev with no .. (prepare_drive refuses /tmp/disk.img before running anything), and the existing confirmation (typing the device path, or --confirm) still applies. macOS: only /dev/diskN with N above 0, never a slice (disk4s2) or raw node. Windows: only a decimal disk number above 0. A filesystem the system cannot make is an error, never a silent substitute.

Existing disks. Nothing changes for them: a drive is recognised by the PARTUUID in disks.conf and must be ext4 (section 34), whatever table it has. Earlier disk init runs already made a GPT with a partition at sector 2048 (1 MiB), type 8300 and the same name, so those drives match the layout above. A disk that was made by hand with an MBR table keeps working as long as it is ext4 and listed in disks.conf; Varsto never converts a table in place. To move such a disk to GPT, first make sure the pool holds its blocks elsewhere (or copy the pool files off the drive), then run varsto disk init on the drive under a label that is free: that erases the drive, makes the layout above and fills the new disk like any other; the old label is retired by hand.

Tests: diskformat::tests (the exact Linux, macOS and Windows command lists, GPT and no legacy tools in any of them, 1 MiB start and alignment, partition types per filesystem, defaults and support per system, refusals of partitions, raw nodes, disk 0, .. paths, injection through names, unsupported filesystems; an end-to-end run of the plan's sgdisk commands on a 64 MiB image file, skipped where sgdisk is missing, that checks the GPT header, the protective MBR (type 0xEE, signature 55AA, a pre-existing fake MBR gone), first sector 2048, type GUID, PARTUUID and name), blockdev::tests::init_script_matches_the_pure_command_list, prepare_refuses_a_path_that_is_not_a_device_before_running_anything and the unchanged drive-check tests. No test touches a block device.

67. The daily update channel (varsto update --daily)

Daily builds (development builds of the main line, published at https://<site>/daily/) can be installed by varsto update --daily (and checked by varsto update --check --daily). The channel is separate from releases (sections 10, 60 and 65) in its key, its files, its state and its trust.

Key and files. The channel has its own minisign-compatible Ed25519 key (daily-key.pub, built in beside release-key.pub; its private half is kept away from CI and the web server). The updater trusts the daily key only for the daily list and the release key only for releases: verify_signature takes the key it is given and the key id in the signature must be that key's, so a signature of one channel never validates the other, and the daily check also requires channel:daily in the signed comment. The files, below daily/latest/, are SHA256SUMS (stable names varsto-daily-linux-x86_64.tar.gz, varsto-daily-windows-setup.exe, varsto-daily-windows-x86_64.zip, varsto-daily-macos-apple-silicon.dmg, varsto-daily-android-debug.apk, varsto-daily-ios-unsigned.ipa) and SHA256SUMS.sig. The signed trusted comment is timestamp:<unix seconds>\tfile:SHA256SUMS\tchannel:daily\tbuild:<YYYYMMDD-commit>. latest.json and the page are unsigned and are not read by the updater.

Checks, in this order. Signature; channel, file and build in the comment (the build id must be YYYYMMDD- and 7 to 40 lowercase hex digits); signing time not older than the newest accepted so far (update-state-daily.json in the device directory, written like update-state.json of section 60 and only after the download has been verified), not more than one day ahead of the clock, and not more than 30 days old (a frozen site or a replay is refused, not just reported); the build not older than the installed daily build by the date in its id (a different build of the same day is newer only when its list was signed later; the same build is "up to date"); the file for this platform listed in the signed list; the SHA-256 of the download equal to the signed value. The package version is not used: daily builds of one version share it. There is no second channel for daily lists, so --allow-single-source has no effect on them.

Installing. The file is installed like a release file of the same kind (section 10; section 65 for Windows): a .tar.gz replaces the binary by a rename from a staging file beside it, the setup program runs silently (the only Windows file), and the service is restarted. The macOS disk image, the Android APK and the iOS package are named but not installed by the command line, which says so and points at the daily page. After a successful install update-channel.json (channel, build, signed_at, version, binary_sha256) records the build and the SHA-256 of the binary now in place; varsto --version and varsto status then name daily build <id>. The record speaks for the running copy only while the running binary's SHA-256 (hashed once per process) equals binary_sha256: a binary installed by hand shows no build id, and update --daily treats it as an unknown build (any signed daily build is an update, neither "up to date" nor "older than the installed build"). The Windows setup program replaces the binary after the updater exits, so its record carries replaces_sha256 (the old binary's hash) instead, and the first copy that runs with another hash takes the record over. A record without a hash (written by an older version) speaks for no binary. A release installed later removes the record. The background updater and the interface never take the daily channel; they stay on releases.

Switching. --daily and --stable exclude each other. --stable (the default) goes back to releases only when the newest release is newer than the running binary, since an update never installs an older or equal version (MIN_ACCEPTED_VERSION, section 60); otherwise the command says which release to download by hand and verify with varsto verify-release.

68. Pairing: which address to offer, and how joining falls back

Code: crates/varsto-core/src/netif.rs (interfaces, ranking), crates/varsto-core/src/pair.rs (join, Connector, NotFound, discovery), crates/varsto-cli (pair join, POST /api/pair/join, GET /api/pair/join-status, the pairing form). Pairing itself (SPAKE2 on the nine digits, section 9 and 51) is unchanged; no stored format changes.

Why. An offer used to list one address: the one the OS would use towards a public host. With a VPN on the default route (or any tunnel the OS prefers) that is the tunnel address, which a phone on the shared Wi-Fi cannot reach, and the same single interface was used for the multicast and broadcast discovery queries, so "find the device by code" failed too.

Candidates. The offering device lists every IPv4 interface address (getifaddrs on Linux, macOS, iOS and Android; elsewhere only the old default-route address) and ranks them (netif::rank). Skipped: loopback, interfaces that are not up and running, 0.0.0.0, 169.254.0.0/16, multicast and broadcast addresses, and interfaces a peer cannot reach by name prefix (docker, br-, veth, virbr, vmnet, vboxnet, awdl, llw, bridge, lo, container and VM bridges). The same address is listed once. Order: private addresses (Lan), then public ones, then overlay ones (tunnel interfaces utun, tun, tap, wg, tailscale, ppp, … and 100.64.0.0/10), each group in the OS order; at most 8. IPv6 is not offered (the listener is IPv4). The offer's addresses and the a= parameter of the pairing link (section 51) carry all of them as host:port, best first, so the link format needs no new field: old readers already accept up to 16 addresses and take the first as before. The interface shows the first in the address field and in the text under the code.

Joining. Order of attempts (pair::join): (1) the typed address, (2) the addresses of the scanned link, those on a subnet this device is on first (netif::sort_by_reach), (3) a search of the local network by the code (multicast and the subnet's directed broadcast, sent from every usable interface, not only the default route), whose answers are tried the same way. An address is tried once. Each connection attempt has a 3 s timeout, the search runs 8 s. The code's digits are the SPAKE2 password: an offer that answers and rejects the code counts as one of its three attempts, so a wrong code (WrongCode) ends joining at once instead of being retried on other addresses. The address field stays optional and editable; a typed address that is not an address is reported and skipped.

Progress and errors. The service publishes the current step while POST /api/pair/join runs (GET /api/pair/join-status → {active, step: trying|looking, address, tried}); the form shows "Trying 192.168.1.20:41234 …" and "Looking for the device on the network …" and logs them, and pair join prints the same lines to stderr. When nothing worked the error is NotFound, and the response carries tried: [{what, why}] (why: no answer, refused, unreachable, connection closed, not an address) and found (offers the search found): the page names every address with its reason, whether the network search found anything, and what to check (same Wi-Fi, guest network or client isolation, VPN or firewall).

Joining without a storage. The bundle carries vault_epochs, every vault key epoch of the offering device, each sealed to the joiner's K8 on the wire like the vault key and put back into the bundle by the joining side; None for an organization's approval. When Engine::join_paired finds no storage of the bundle that answers and the bundle has at least one S3 or rclone storage, it does not fail: it builds the device from the keys (join_deferred: vault epochs, new device keys, created_utc set to now), writes the storage settings and secrets without contacting them and saves state/pending-join.json ({storages, since_utc}). The next sync starts with finish_pending_join: the first storage that holds vault/meta.json must be this vault and format 3 and must open with the newest vault key (Membership::join, which also refuses a key from before a removal); then created_utc is taken from it, the storages are added in the usual way (those that still do not answer stay as settings and are retried like any storage), the registry and ledger are read, the enrolment is published and the file is removed. While no storage answers, sync fails with "joining is not finished" and the file stays (Engine::join_pending). A bundle whose storages are directories or disk pools that are not on the new device still fails as before. The trade-off: the keys are accepted before any storage confirmed the vault; a wrong bucket or key shows only at the finishing step, which says to run varsto reset --yes and pair again.

Across networks (section 83). Before, there was no rendezvous or relay path for pairing: the new device knows nothing of the vault's storages and no server was involved, so the code's LAN search was the only route without an address, and pairing across networks needed a reachable typed address. Now the offer also registers, in the background, at the rendezvous service under a slow tag of the code and under a random token carried in the link (rv=); a join that finds nothing on the LAN looks the offer up there, tries its addresses, asks for a coordinated punch and, last, runs the same SPAKE2 exchange over a relayed stream. With the rendezvous off or unreachable, pairing works exactly as above.

Tests: netif::tests (ranking tables for a MacBook with VPN, VM bridge and link-local addresses, a Linux host with Docker, down interfaces, duplicates and Tailscale, an Android phone; subnet ordering; directed broadcast), pair::tests (order of attempts with an injected connector: typed, link, search; no repeats; a wrong code stops at once; the final error names what was tried; a refused real port falls through to the next address), qr::tests (a pairing link with ranked candidates round trips in order and fits one QR code at the maximum).

70. Forwarding: devices that carry other devices' blocks to the storages

Why. A phone sends its camera folder to the vault, but only the laptop has the credentials of the S3 bucket the folder's policy wants a copy on (or the phone's own upload is blocked by a quota, a slow link or a storage the phone cannot reach). Until now a device wrote a block to its storages only when it held the file: a laptop that attached the folder with selective sync (placeholders) never wrote the phone's blocks anywhere, so the policy stayed violated for as long as the files were only on the phone. Forwarding lets any device that is attached to the folder and holds its key carry those blocks from a peer to the storages it can write, without keeping the files.

Attaching with a choice. The interface's "Attach on this device?" (and on phones "Add to this phone?") asks how to keep the folder: Full sync (every file is downloaded and kept) or Selective sync (files are placeholders until opened or pinned); desktops also ask the direction: Both ways, Send only or Receive only (section 47). POST /api/folder/attach takes selective (as before) and mode (normal, send-only, receive-only; absent: normal; receive-only is refused for a folder kept encrypted on the device, as varsto folder mode refuses it), and varsto folder attach <folder> <path> [--selective] [--mode send-only|receive-only] does the same. Forwarding works in every one of these: it does not depend on whether the device keeps files.

Who forwards. A device forwards a folder when all of these hold:

  • the folder is attached here (a mount and a folder state exist) and this device holds its key now: a locked Strongroom is skipped (no_key in the report) and so is a folder this device has no record of; a member of a shared folder forwards nothing (it is not a peer of the vault, section 15);
  • forwarding is on (config.json forward.enabled, default true; varsto forward set --on|--off, POST /api/forward {enabled});
  • the vault is unlocked and the service is not paused (the service runs it after a sync).

What it forwards. For every block of every current file of the folder (each block once), the device works out from the ledger the storages a push from this device would write it to and that do not hold it yet: the folder's write targets (WriteTargets::wants: the placement, or the default fewest storages that keep the policy, section 23; storages being drained take nothing, a block moved away from a storage is not put back), transferrers and cold storages left out (transferrers carry for devices, not for the policy), within the vault-wide quotas (section 44). A block is forwarded only when that list is not empty and the block's copies do not keep the folder's copy rules yet (min_copies, min_per_place, counted from the ledger as the policy check counts them, section 14; the verification window plays no part), or, in a folder without a policy, when it has no storage copy at all. So a block that the phone already put on storages that keep the policy is not written again, and the push of a device that holds the file stays the usual path: forwarding takes what is left.

Where the bytes come from. In this order, the first that has them: this device's block cache; a peer (section 15), usually the device that wrote the file, since peer-to-peer costs nothing per gigabyte (peers that lacked 32 blocks in a row are not asked again in the same run); another hot, non-transferrer storage of this device that the ledger says holds the block (a copy from one storage to another, which a storage may bill as egress). Cold storages are never read, and are not written by forwarding either (a push from a device with the file, or a data move, puts copies there). The quota room for a block is taken before it is fetched, so a block that no target can take is not asked of anyone. Every object is checked before it is written: the hash of its bytes must be its name, and it must open under the folder's key as the block of the file entry (chunk_seal::open_chunk with the chunk id, epoch and size of the entry), so neither a peer nor a storage can hand in another object, and a device without the folder key cannot forward at all.

Writing and recording. Blocks are collected in memory per target storage and written as packs (section 62) when the buffer (forward.buffer_mib, default 64 MiB) is full and at the end of the run; each written block is read back and its hash checked, then recorded as chunk_stored for that storage by this device. Every group is sealed into a ledger batch and pushed before the next group is read, so a run that stops halfway keeps what it wrote and the next run continues with what is still missing (the ledger says what is done). There is no new event type. The forwarding device is the writer of the copy, so its own read-back is not recorded as a verification, and the copy counts as verified only when another device verifies it (sections 6 and 20). No chunk_on_device is recorded either: the forwarding device does not keep the plaintext. Nothing is written to disk on the forwarding device apart from its ledger and state files: the buffer is memory and is dropped after every group, so a selective folder stays as it was (placeholders) and the block cache does not grow.

Two forwarders: leases. Two devices that could forward the same blocks (two laptops with the same bucket, or with two buckets of the same place) would write them twice, in different packs. Before forwarding a folder, a device takes a lease on every hot, non-transferrer storage of this device that holds records: vault/forward-leases/<folder id>/<slot, 12 digits>.json, JSON {"device": "<id>", "taken_utc": <utc>}, written with put-if-absent, where the slot is the UTC time divided by 600 seconds. A lease of another device in the current or the previous slot on any of those storages means that device is forwarding the folder: this device leaves the folder for this run (busy, with the holder's name) and deletes the leases it took in this attempt, so that the holder (or whoever comes first in a later run) can take them all. A device that holds the leases forwards for at most 480 seconds from taking them (it never works past the time the others honour the lease), deletes its leases when the folder has nothing left to forward, and keeps them when it stopped for its budget or the time limit, so that another device does not start on the same blocks meanwhile; they lapse by themselves after at most two slots. Stale leases (older than the previous slot) are deleted by whoever sees them. A lease that does not parse counts as another device's. Leases are not encrypted: they reveal the folder id (as thumbs/<folder>/ already does), a device id and a time; anyone who can write the storage can delay forwarding with them, which is less than such a writer can do anyway. On S3 without conditional writes (section 12) two devices can both believe they took a lease; the result is a block written twice in two packs, which costs space, not correctness. Once a forwarder's batch is pushed, every other device sees the claims and has nothing left to forward.

Limits per run. The service runs forwarding after every sync, after repair: at most forward.max_mib (default 1024 MiB, 256 MiB on phones) and 4096 blocks per run, the first block always taken. The device that serves the blocks keeps its own limits: a phone answers peers only while its service runs, its camera upload keeps its Wi-Fi-only and charging-only conditions for its own uploads, and the forwarder asks it for one object at a time, not with the download window of a pull. Metered networks are not detected by the core: a phone that should not forward over mobile data turns forwarding off.

Report and interface. Engine::forward(&ForwardOptions) returns a ForwardReport: per folder the blocks and bytes forwarded, per target storage and per source (block cache, storage <name>, peer <name>), the devices whose blocks were carried (holders in the ledger), blocks waiting because no source had them (unavailable) or no target could take them (waiting_for_target), objects refused by the check (rejected), folders skipped without a key (no_key) or held by another device's lease (busy), storages that could not be written, and whether work is left. The last run is kept in state/forward.json; GET /api/service carries forward and a one-line forward_text ("forwarding: last run …: 12 blocks (48.0 MiB) of camera for phone"), varsto forward prints the status, varsto forward run runs once now, and GET /api/forward and POST /api/forward {enabled} back them. While it runs, the activity list (section 32) shows a forward task, "Forwarding blocks to the storages for «phone: camera»", with bytes done and total; the visualization lists it like the other tasks.

Failure cases. No peer online and no other copy: the block is counted unavailable and tried again on the next run. A target storage that fails a write: it is left out for the rest of the run (storages_failed), the blocks stay missing and the next run tries again; a block whose read-back does not match is not claimed. The vault locked, the service paused, the ledger not writable or forked: nothing runs. A peer that disappears halfway: what was written is recorded, the rest is unavailable. The device holding the lease crashes: its leases lapse within two slots (at most 20 minutes) and another device forwards.

Transfers. Inside a run every block is a transfer (engine/forward.rs): the block (chunk id, object name, epoch, size), its targets (storages of this device), its source once found (block cache, a peer, or a storage of this device) and a state: waiting for source (no source has it now), waiting for target (no target can take it now: quota, a write that failed), held (read and checked; held in memory by forwarding) and recorded (written, read back, claimed). Only recorded is a copy anywhere: a held block counts for no policy. Copying is by ciphertext object, named by its hash, so the model does not depend on the kind of storage at either end. The report counts waiting_for_target beside unavailable.

Mailbox for offline disks. Built in section 78, on the same idea of transfers: any storage as source or target, a pool disk that is only sometimes docked included, the states waiting for source (the disk is away) and held (now also in a durable outbox on the device), and only a recorded target copy counting as a copy. Where section 78 differs from the plan that stood here: the outbox has no fixed size limit but keeps a free-space reserve on the device's disk and is the first thing removed when the device needs space; tasks come from three rules (a pool's disk group rule, a folder's copy rules for another storage of the device, open move jobs) rather than from every policy shortfall; and the device where the target is docked takes staged blocks over peer-to-peer from a published list of what each device holds.

Tests: crates/varsto-core/tests/forwarding.rs (a phone whose only storage is full and a laptop with selective sync and an S3-like directory: the phone's blocks reach the bucket through the laptop from the phone as a peer, the laptop keeps placeholders and caches nothing, the policy that needs a cloud copy goes from violated to ok, the claims are the laptop's and are not counted as verified by it; a locked Strongroom is not forwarded until it is unlocked; two laptops with the same bucket: the second leaves a folder the first holds a lease on, a budget stops a run halfway and the next run continues, and every block is on the bucket exactly once; forwarding turned off), and desktop tests for the attach request with selective and mode.

71. A responsive interface: reads during long operations

Why. The service keeps its state (the engine and the service's own summary) behind one lock. A sync, a verification, a scrub or a ledger merge holds it for seconds to minutes on a big vault, and every request of the interface used to wait for it in one queue: on a vault of 50 000 files the summary (/api/status) took 30 to 70 s to answer during a sync, the browser's few connections to the service filled with waiting polls, and the page froze until the sync ended.

Reads. A GET with the session token in a header (X-Varsto-Token or Authorization: Bearer) of a route that only reads (the list readcache::ROUTES: /api/state, /api/service, /api/status, /api/folders, /api/files, the policy, verification, scrub, repair, ledger, trash, history, storage, disk, backup, organization and folder-settings reads) is answered on a thread of its own, at most 32 at a time (beyond that it joins the queue of the other requests). It waits at most 50 ms for the state. When it gets the state it answers fresh and the service keeps the answer, by address (path and query), at most 128 addresses and 64 MiB (an answer over 32 MiB is not kept). When the state stays busy it answers with the last kept answer of the same address, with the headers X-Varsto-Stale: 1 and X-Varsto-Age-Ms: <age>; a JSON object also gets "stale": true and "stale_ms". With no kept answer it waits for the state as before. Every request that is not a GET empties the kept answers when it arrives and again when it has been answered, so a page never gets an answer from before its own change; the requests that only run something (/api/sync, /api/verify/run, /api/scrub/run, /api/fsck) keep them, as the service's own syncs and checks do: while the state is busy the answers from before are sent marked stale, and the next fresh answer replaces them. A request with an MCP key (section 37) is not answered from them. /api/viz (section 64) is computed on a thread of its own as well, so the page's assets, the event stream and the activity routes are never held up by it.

The service's own work. After a sync the service runs its upkeep (ledger, verification, scrub, repair, drains, backups, trash, restic checks, staged moves, disk suggestions, device details) one step at a time and lets go of the state between the steps, so that a waiting request gets it. A sync itself still holds the state from start to end (the remaining cause, listed in the change that introduced this section).

The page. A background read (one that no pressed button started) is asked once at a time per address: a poll that comes while the same read is on its way shares its answer. The summary is drawn once at a time (asked again meanwhile, it runs once more afterwards), and an answer equal to the one drawn, or a stale one, changes nothing on screen when the page asked by itself (after a sync or an event). The file list draws 300 rows at a time and more as the end of the list comes into view (or with "Show more files"), keeps the rows already drawn when it is drawn again, is not drawn again for an equal answer, and filters the rows it has without asking again. While answers are stale a line under the title says that the service is busy; while the service cannot be reached it says that the page reconnects; the page is never reloaded for either. The visualization (section 64) stops asking while the page is hidden and asks at once when it shows again.

Measuring. scripts/bench/ui-latency.py <varsto> <work dir> [--files 50000] [--browser 60] creates a vault of that many files and four folders under a throw-away home, times every read the interface makes idle and while a sync and a verification run, and optionally counts long tasks, requests per minute and the JS heap of the page in Chromium.

Tests: readcache::tests (kept by address until a change, bounded, an answer computed before a change is not kept, a held state answered from the cache after the short wait and waited for without one, stale marking, the route list) and desktop::tests::reads_are_answered_while_a_long_operation_holds_the_state and a_change_through_the_api_drops_the_cached_reads (a real server whose state a test thread holds).

72. Remembering the passphrase without a desktop session

Why. The background service starts locked unless it finds the passphrase. varsto service remember used to store it only in the desktop keyring (Secret Service), so over SSH, on a server or in a session without a D-Bus session bus it refused. No stored format changes: the passphrase is never part of the vault.

Stores, in this order. remember uses the first that works and says which one:

  1. Desktop keyring. Linux: Secret Service through secret-tool (skipped without a desktop session: no display and either an SSH login or no session bus; skipped when the keyring is locked and no display could show the unlock window). macOS: the login keychain through security -i (the passphrase on standard input); over SSH a failure adds the advice to unlock the keychain or use varsto unlock.
  2. systemd-creds (Linux, systemd 256 or newer, user manager running). systemd-creds encrypt --user --name=varsto-passphrase - - gets the passphrase on standard input and writes the credential to standard output, which is stored as passphrase.cred in the device directory with mode 600 (atomic write). With a TPM2 the key is bound to it, otherwise to the host key. The service reads the file with systemd-creds decrypt --user --name=varsto-passphrase - - (file on standard input, passphrase on standard output), so it works without a desktop session and after a restart. The credential name is bound into the file. A file that cannot be decrypted (another computer, TPM cleared) is logged and ignored: the service stays locked.
  3. Kernel keyring (Linux). A user key varsto:<device directory> in the user keyring (@u) through add_key and keyctl, readable by its owner only (KEY_POS_ALL | KEY_USR_ALL) so the service, another process of the same user, finds it. It lives in kernel memory only: gone when the computer restarts or the user has no process left. The message says so and points to varsto unlock.

Windows and Android do not use remember (unchanged). The passphrase is never written in plain text to a file, never put in the environment or an environment file, never in a process argument and never printed. Note that without a TPM2, systemd-creds binds the file to the host key, which protects against copying the file elsewhere but not against root on the same computer.

Reading. At service start the stores are read cheapest first: passphrase.cred, the kernel keyring, then the desktop keyring (whose lookup may wait up to 20 seconds on a locked keyring). VARSTO_PASSPHRASE still wins over all of them. After a successful remember the copies in the other stores are removed, so one store holds the truth and an old passphrase never shadows a new one.

Forgetting and reporting. varsto service forget removes the passphrase from every store (the credential file, the kernel key, the keyring entry, the keychain item) and reports which ones held it; the running service stays unlocked until it restarts. varsto service status shows passphrase: remembered in the desktop keyring, ... encrypted with systemd-creds, ... in the kernel keyring (until this computer restarts) or not remembered; its JSON has passphrase_store (keyring, systemd-creds, kernel-keyring, keychain or null) and passphrase_text.

When nothing works the error lists each store tried and why it failed, then names the alternatives: VARSTO_PASSPHRASE for the service, or varsto unlock. The passphrase is read as before (the VARSTO_PASSPHRASE variable, else a terminal prompt) and checked against the vault before it is stored.

Tests: remember::tests (injected backends: a failing keyring falls to systemd-creds, then to the kernel keyring; the failure text names everything tried; a new store clears older copies; forget removes whichever store was used and is idempotent; the status and message texts; an end-to-end round trip with the real systemd-creds (mode 600, no plain text in the file, replace, forget) and with the real kernel keyring, each skipped where the tool or syscall is unavailable) and crates/varsto-cli/tests/remember_cli.rs (the command line with a throw-away home: service remember, service status, service forget).

73. A device that joined shows at once; a device is never its own peer

Why. Two reports from daily use. After pairing, the new device showed on the first one only minutes later; and a phone's traffic view showed peer-to-peer traffic from the phone to itself.

Finding the new device. A device learns of a joined device from three things, and each was refreshed only by the periodic sync (every 300 s by default): its device record under vault/devices/, its rendezvous record under vault/peers/ (published only when its first sync ended) and the LAN beacon (heard at once, used at the next sync). The /p2p/changed message from the joiner covered the device list when the joiner reached the first device over peer-to-peer, once, after its own first sync; it never covered the peer table or the paths. Measured on two throw-away homes with a local-directory storage and both services on loopback (debug build, the first device started 20 s earlier, the joiner's service started after pair join / join; seconds from the joiner's service start): the first device listed the joiner after 3 s (through the message), but showed it as a peer only after 303 s, and the joiner showed the first device as a working path after 303 s.

What the service does now.

  • Device watch. While the vault is unlocked the service lists the device records (Engine::refresh_devices: one pass over the registry, no ledger) 4 s after it starts or the vault is unlocked, after a pairing offer of this device was taken up, and after a peer announced a change (/p2p/changed); the gap doubles after every look up to 60 s and starts over whenever something may have added a device. A new device found this way makes the service sync at once (the ledger holds its enrolment) and publish the event devices.changed.
  • Peer table. The same look compares the rendezvous records on the storages with the ones the peer table was built from, and a LAN device nobody had heard before (the beacon thread sets a flag) rebuilds the table at once instead of at the next sync. The new table is asked once on a thread of its own (/p2p/info), the paths it found replace the displayed ones, and peers.changed is published, so the first path to a new device is known within seconds.
  • Announcing. Before its first sync after a start, a device publishes its rendezvous record, builds its serving snapshot and sends /p2p/changed, instead of after the sync: a device that joined a big vault no longer stays invisible while it downloads.
  • Cached reads. The kept answers of section 71 are emptied (readcache::invalidate_all, a process-wide counter every cache follows) when the watch finds a device or the table changes, so a poll that finds the state busy during the sync that follows is not given a device list from before.
  • Interface. devices.changed and peers.changed make the page load the service summary and status once and, on the Peers page, the peer-to-peer card.

Measured the same way after the change: the first device listed the joiner and showed it as a working path after 2.7 s and the joiner showed the first device as a working path after 2.5 s (vault-key join and pairing alike; with a pairing the first device already listed the joiner when the joiner's service started, 8 s after the join).

A device is never its own peer. The traffic view showed the device's own entry because a request carrying its own device id reached its own server: another record (an old id of the same install that still carries its certificate, or a record whose address is one of the device's own) led the peer table to an address that was this device. The server counted the answer to the asker, which was itself. Now:

  • The server refuses a request whose token carries its own device id: 403 with the body self, no traffic counted (over TCP and QUIC alike).
  • The client that gets that answer from an address remembers the address as its own (Peers::is_self_addr) and does not try it again; the table is rebuilt every sync and carries the knowledge over.
  • A record that carries this device's own certificate is dropped when the peer table is built; a QUIC connection to a pinned certificate equal to the own one is refused before the handshake, and a QUIC client presenting the own certificate is closed.
  • The reachability self-probe (quic::Node::probe_self, which decides reachable in the rendezvous record) is a path of its own: a fresh QUIC connection pinned to the own certificate, never kept or counted, carrying one PROBE <nonce>; a server that sees its own certificate answers only that verb, by echoing the nonce, and then closes. Until this was added the probe went through the ordinary connect, which the rule above refuses, so it never succeeded and only configured public addresses made a device reachable.
  • A TCP request retried on a new connection after a kept one dropped carries a fresh token (TcpPool::get makes one per attempt): the peer may have spent the first one before the connection went, and would refuse it as replayed.
  • The traffic counters ignore this device as a peer and a relayed flow from a device to itself (Traffic::record, begin, record_relay, the report), and the visualization (section 64) drops any peer-to-peer or relay flow whose ends are the same device.

Tests: crates/varsto-core/tests/device_discovery.rs (a joined device is found by one look without a sync, found once, three devices), tests/nat.rs::a_device_is_never_its_own_peer (a record with the own id or certificate gives no peer, a handshake with the own certificate is refused, an address that answers self is learned and not asked again, nothing is counted), p2p::tests::a_request_from_this_very_device_is_refused_and_never_counted, p2p::quic::tests::the_self_probe_reaches_us_while_dialling_our_own_certificate_stays_refused, p2p::tests::a_retry_after_a_dropped_kept_connection_carries_a_fresh_token, p2p::traffic::tests::nothing_is_counted_for_this_device_itself, tests/viz_snapshot.rs::flows_of_a_device_with_itself_are_filtered, readcache::tests::work_of_the_service_itself_empties_the_answers.

74. Ledger heads between peers

Superseded by section 77 (storage format 3): the head exchange carries signed heads and proofs over the TLS transport (p2p::v3::heads, 75, 77.8). Kept as the history of format 2.

Why. Section 58 (Limits) said a storage that withholds a ledger batch from every reader, or rolls the whole ledger back to an older state, is not caught: nothing signed is compared with another source, because devices learned of each other's progress only from the seen acknowledgements inside batches that the same storage serves. Devices that can talk to each other directly have a second source.

No format change. FORMAT_VERSION stays 2. Batches, checkpoints and the storage layout are unchanged. What is new is a peer-to-peer message, one optional field in the rendezvous record and a local file; older versions ignore all three (the unknown path answers 404, the field is skipped, the file is never read).

The statement. A head statement (ledger_heads::HeadStatement) is signed with the sender's device key (the hybrid signature of section 11) and holds: the vault id, the sender, its Lamport clock and wall clock when it signed, and a list of at most 512 entries {device, seq, hash, checkpoint}: for every device of the vault whose ledger the sender holds, the end of its unbroken chain (seq), the hash of that batch and the newest checkpoint held (checkpoint, 0 for none). What the sender signs about its own ledger is limited to what a storage is known to hold (pushed.json): a batch not pushed yet is not one a storage withheld. A device that signs no ledger batches (a member of shared folders, a removed device) sends none. The size is about 5 KB plus 130 bytes per device.

Where it travels. In every peer-to-peer session, whatever the transport (TCP, QUIC, through a relay):

  • GET /p2p/heads answers with the statement of the device asked (404 while it has none). The service asks every peer in its table, at most every ten seconds and never for more than three seconds at a time, before a ledger pull.
  • GET /p2p/changed (a device announcing that it published something, section 73) now carries the sender's statement as a path segment, /p2p/changed/<base64url of the statement> when the path stays under 24 KB (about 150 devices; larger vaults send the bare message and are asked for /p2p/heads), and is answered with the receiver's statement instead of ok. One message exchanges both directions. The head of a request, which was limited to 16 KB over TCP and 8 KB over QUIC, is limited to 32 KB for both.
  • The rendezvous record (vault/peers/<device>.enc, section 15) carries a statement of the sender with just its own head, signed with the device key like the larger one (PeerRecord::head; the record is encrypted as before). Devices that only meet through the storage still compare their progress with what others published. A record is republished when the head it names changes, not when it is signed again (same_as).

What a receiver does. A statement is kept only when the sender is a trusted full device of this vault other than this one (not removed, not a replica or a member), the vault matches, the signature verifies against the registry's key for the sender, the times are not absurd (Lamport clock not beyond the reader's clock by more than 2^40, wall clock not more than a day ahead), and it is newer than the one kept from that sender (by Lamport clock, then wall clock, then the sum of the heads). Anything else is dropped silently. The newest statement of each sender is kept in ledger/heads-seen.json in the device directory; what a sender said is forgotten when it is removed. Statements heard on the server side (/p2p/changed) or read from records are queued and checked at the next ledger pull, because the server has no engine.

What it does with it. A statement never moves a head, ingests a batch, retires anything or makes this device refuse a batch; it only raises the question of section 58's freshness check. After a pull, for every device A that the sender lists and this device knows, the reach of the sender (the larger of its seq and its checkpoint, never beyond a removed device's cut-off) is compared with this device's head for A, exactly as the seen acknowledgements are: when it is higher, ledger_health.behind records {device, name, held, seen, pulls, source} with source peer (acks for a gap learned from acknowledgements, pending for batches waiting for a predecessor). The pull just asked every storage for the missing numbers. When the same gap is still there after three pulls in a row, ledger_health.warnings says "a storage may be withholding or rolling back ledger batches of (a peer holds #, the storages give #)"; varsto status and varsto ledger status show it after "ok", the Help page shows a warning (English, Finnish, Swedish) and the event ledger.health is published again with the warnings. The gap and the warning go as soon as a storage delivers the batches. Statements older than two weeks are not compared.

Limits. Said plainly:

  • A storage is not caught when it is the only channel: no peer-to-peer path to any other full device and rendezvous records the storage withholds or replays as well. Devices must meet, directly or through a relay, or read each other's rendezvous record at a time the storage still serves it.
  • A rollback is noticed by a device that has not yet pulled the lost batches; a device that already holds them keeps them (heads only move forward) and does not warn about its own copy. Its next push does not restore other devices' batches.
  • A statement is the word of one trusted full device: a device that is itself compromised can raise a false warning (and nothing more: no batch is refused or moved). A sender that is not reachable, or pushed nothing yet, adds nothing.
  • A gap that is real but explained by a storage that is only unreachable looks the same until the next successful pull.
  • The statement of the sender's own head counts what its pushed.json says; a device that lost that file understates its head until it pushes again.

Tests: ledger_heads::tests (a statement round trips and verifies; an edited, renamed, foreign or wrongly signed one is refused; only a newer one replaces the kept one; a statement rides a /p2p/changed path and a large one does not; heard statements are kept per vault), crates/varsto-core/tests/ledger_gaps.rs (a_peers_heads_reveal_batches_the_storage_withholds: two devices on a directory storage, the storage drops the newest batches of A for B, B meets A over loopback peer-to-peer and shows behind with source peer and, after three pulls, the warning, in describe, in the Help page and with nothing ingested; a_rolled_back_storage_is_caught_by_a_peer; statements_from_removed_or_forged_senders_are_ignored; a_rendezvous_record_carries_the_senders_own_head; the_changed_message_exchanges_statements), and the lab scenario ledger-rollback (not run when it was written).

75. Format 3 peers and transport (behind the format3 feature)

Since the switch (section 77) this is what every build does: the format3 feature and the format-2 paths named below are gone.

Work package 9 of format-3-design.md (its section 8). Built behind the format3 cargo feature as library code that the engine switches to with the format (work package 12): the format-2 transport of sections 15, 60, 73 and 74 is unchanged in every build, with or without the feature, and nothing here is unconditional. The TCP listener, the QUIC node and the peer table take a format-3 mode (Server::with_tls, quic::Node::start_v3, Peers::build_v3); everything else is in p2p::v3, pair::v3 and fingerprint.

Peer records (p2p::v3::peer). A SignedRecord of kind peer at vault/peers/<device hex>/<seq 16>-0000.rec, key id registry@<e>, newest seq wins. Body (postcard): device, seq (both checked against the envelope), name (at most 128 bytes), port, lan_addrs (ranked as section 68 ranks them), public_addrs, udp_public, udp_local, mapped_tcp, mapped_udp (at most 32 each), cert_sha256 (32 bytes, the TLS pin, never zero), nat, relay_via (at most 16 device ids), reachable, heads (at most 256 (device, seq, body_hash)), pushed (at most 64 (storage identity, seq)). A writer publishes put-if-absent at the next free seq and then deletes its records older than the one before, so the stream holds two. The directory is the newest accepted record (acceptance rule of the design's section 5: a trusted full device's signature, the registry key) of every device; it leaves out this device, any record carrying this device's certificate, and a certificate two devices claim (neither is admitted).

Admission. The TLS server of both transports admits a client certificate only when the directory names it; this device's own certificate is never dialled or served as a peer: on QUIC the handshake lets it through for the reachability self-probe alone (section 73: one PROBE <nonce>, echoed, nothing else answered), and TLS over TCP refuses it. ALPN varsto-p2p/3.

Request tokens (p2p::v3::token): X-Varsto-Auth: <device>:<responder>:<unix>:<nonce 32 hex>:<mac 64 hex>, mac = keyed_hash(exporter, aad3("p2p-token", [device, responder, unix le, nonce, path])), exporter = the TLS exporter of the connection (label EXPORTER-varsto-p2p-token, empty context, 32 bytes). The responder requires: the certificate of the connection belongs to a device of the directory and that device is device; responder is itself; |unix - now| <= 300 s; the nonce unseen (at most 65 536 kept). Chosen over a per-request K6 signature (the design's wording, "tied to the TLS connection itself"): the client's identity is already proved by the mutually authenticated handshake against a pin from a signed record, so a MAC keyed by the exporter adds the binding to this connection, path and responder at the cost of one keyed hash instead of a 3.3 KB hybrid signature per request (a download asks for thousands of blocks). No vault secret is involved; the p2p-auth key is not used.

Relays. A token cannot travel past the connection it was made for. The relay checks the asker's token (for the full /p2p/via/<device>/<path> path, responder = the relay) and asks the registrant on its registration connection with a token of its own for <path> plus X-Varsto-For: <asker>. The registrant accepts X-Varsto-For only on its registration connection with a relay of its directory and only for a device of its directory, and answers as to that device.

Rendezvous relay (section 83). When no peer relay exists, the last route is a session spliced by the rendezvous service: the TLS over TCP below runs unchanged over that byte stream (a WebSocket relay stream instead of a TCP socket), the asker as client pinning the target's certificate, the target as server admitting only certificates of its directory; tokens are keyed with that session's exporter as on any connection. The service carries TLS records only.

TLS over TCP (p2p::v3::tls): the TCP listener runs a TLS 1.3 handshake (5 s) with the same certificate, pin and client verification as QUIC before reading any request. The 5 s is an overall deadline, checked on every read and write: complete_io loops while bytes arrive, so a trickle must not stretch it. At most 64 connections from one address may sit in that handshake; the place is freed when the handshake finishes, so an authenticated peer is not limited by it and one address cannot occupy all 256 connection slots. Inside the session the requests are those of section 15. A client that does not start with a TLS handshake gets a TLS alert and the connection closes; no request is read and no byte of the protocol is sent in the clear. Kept-alive sessions are pooled per (address, pinned certificate). TCP is kept rather than removed: section 15 measured QUIC slower than TCP beyond the LAN, and QUIC remains the path through NATs.

LAN beacons (p2p::v3::beacon): VARSTO3 <tag> <device hex> <port> <seq> <sig hex>, sig the Ed25519 part of K6 (64 bytes) over aad3("p2p-beacon", [tag, device, port le, seq le]). A listener ignores a beacon that does not parse, is of another vault tag, is its own, is from a device that is not a trusted full device, does not verify, or whose seq is not above the highest it accepted from that device. Sequence numbers start at unix seconds << 16 and rise per beacon. An address from a beacon is added only to a device of the directory (one with a pinned certificate); a beacon of a device without a record adds nothing.

Pairing (pair::v3): the joining device's hello is {"v": 3, "name", "spake", "k6", "k8"} (hex public keys); both key confirmations are keyed_hash(spake key, "varsto-pair/3 confirm <side>" || BLAKE3(aad3("pair-hello", [name, k6, k8]))), so keys swapped by a device in the middle fail the confirmation. After the confirmation the offering device calls its Approve with the name, both keys and the six-word fingerprint (fingerprint::of_keys: the section 24 construction over K6 and K8, context varsto format-3 device fingerprint v1, the same words as folder requests of work package 8a) and sends nothing when the person declines ({"error": "declined"}, the offer closes). The bundle travels under the SPAKE2 key with vault_key empty; the vault key is sealed to the joiner's K8 inside it (hybrid KEM, AEAD with aad3("pair-vault-key", [vault id, BLAKE3(k8)])). Discovery answers to rendezvous(code), 10 bits of derive_key("e2ee-sync-format/3/pair-rendezvous", digits) as a decimal number: concurrent offers are told apart as well as by three digits, a listener learns no more about the code than from three digits (about a million candidates stay, three online tries), and no part of the password is sent.

Head exchange (p2p::v3::heads), built on section 74's occasions: a device's head list (at most 256 (device, seq, body_hash)) travels in its peer record and in /p2p/changed/<list> and /p2p/heads/<list> (postcard, base64url; the bare paths ask for everything). The answer (postcard) is the responder's list and, for every device where it holds a newer batch, that batch's envelope with an empty body, at most 64 and 512 KiB. An envelope verifies with the writer's K6 (kind batch, zero scope, one part, a ledger@ key, this vault) and proves the head; the writer's own entry in its accepted peer record proves it as well. Proofs are kept per writer in ledger/watch.json. The batches a device lacks up to a proof are fetched from the peer that proved it (GET /p2p/ledger/<device hex>/<seq>, the whole record, at most 64 per device and round), checked by the acceptance rule under their storage name, the proved one against the proved hash, and handed to the ledger store, which does not push them. Head lists a peer sends are its claim only; the responder keeps the newest per sender for the engine.

Rollback warning. After every pull, for each (storage S, device D) where S is expected to hold D's batch n (D's accepted peer record lists S in pushed with a seq of at least n, or this device pushed there itself), S was listed, and a proof of n older than the pull exists: when S shows less than n, the pair is suspect; after two such pulls in a row the warning is "storage may be withholding or rolled back: it shows ledger batches of up to , but proved ", once a day as a notification. A storage that was not reachable is not judged and keeps its state; the pair clears when S shows the batch or D's record stops listing S. Showing the warning in varsto status, varsto ledger status, the Help page and notifications (with Finnish and Swedish text) is the engine's part (work package 12).

Tests (p2p::v3::tests, pair::v3::tests, fingerprint::tests, run by CI with the feature): newest peer record wins, untrusted and foreign-key records are refused and counted, a record with this device's certificate and a contested certificate are left out; tokens for another responder, connection, device or path, stale, replayed or garbage tokens are refused, and X-Varsto-For counts only on a registration; TLS over TCP admits only certificates of the directory and refuses an unpinned server; a handshake that trickles bytes is closed at 5 s and one address cannot fill the listener before it authenticates; a token of one TLS connection is refused on another; a plain HTTP client gets an alert record (0x15) and no protocol bytes; the own certificate is refused when dialling and when accepting, over TCP and QUIC; QUIC serves directory devices with connection-bound tokens and refuses others; a relay checks the asker's token and asks with its own, also through the peer table; beacons that are unsigned, forged, foreign, unknown, own or replayed are ignored; pairing shows name, keys and fingerprint, delivers a vault key that only the joiner's K8 opens, sends nothing to a declined device, shows nothing for a wrong code, and is found by its tag; head exchange proves a withheld batch and the peer hands it over, heads ride on /p2p/changed and in the peer record, forged or foreign proofs and mismatched batches are refused; the rollback warning comes after two pulls and only for a storage the writer confirmed.

76. Format 3 folder membership for people: requests, approval, roles, removal, recovery copies (behind the format3 feature)

Since the switch (section 77) this is what every build does: the format3 feature and the format-2 paths named below are gone.

Work package 8b of format-3-design.md (section 6). The records are the ones of work package 8a (membership3); this section is how a person reaches them. Nothing here changes a stored format, FORMAT_VERSION stays 2, and a build without the format3 feature has the same commands and routes, which answer "not available in this build".

Where the keys come from until the format flips. The engine of a format-2 vault stands in for the device keys of format 3 (Engine::f3_*, engine/membership3_ops.rs): K6 is the device signing key, K8 the KEM key that vault-keys.enc already holds (made on first use), K3 the vault key (every epoch the engine holds). Each operation opens a Membership over the metadata storages and publishes this device's device record when the registry lacks it. Work package 12 replaces this with the keys varsto init makes.

Commands (varsto): folder request <folder> [--role editor|viewer] prints this device's six words; folder requests [<folder>] lists pending requests (device name, role asked, six words) for the folders this device owns; folder approve <folder> <device> [--role editor|viewer] [--yes] prints the device's name and six words to standard error and asks "Do the six words match? [y/N]" on standard input, then issues the folder record entry and the grant (an answer other than y writes nothing; --yes skips the question); folder deny <folder> <device>; folder members <folder> (participants with roles, denied devices, pending requests, folder epochs two owners started at once); folder role <folder> <device> <owner|editor|viewer> (an owner's folder record and a grant carrying the role; a lower role does not take keys back); folder remove <folder> <device> [--yes] (asks; starts folder epoch e+1 through start_folder_epoch, with the device's newest ledger batch as the cut-off); folder resolve-epoch <folder> <n> --keep <device>; recovery escrow [<folder>] [--with-recovery-key] [--recovery-file F] writes the escrow records that missing_escrows lists, with the recovery words from a file, VARSTO_RECOVERY_WORDS, a pipe, or a hidden prompt (never the command line; --with-recovery-key uses the environment copy only); recovery kit --recovery-words | --new-recovery-key prints escrow::kit_text (both word sets). A folder is a name or an id (hex prefix of four digits or more), a device a name or an id likewise. varsto status prints warning: folder <name> has no recovery copy: run varsto recovery escrow <name> for every folder epoch this device holds with no escrow, on standard error (and through the service's /api/status as recovery_warnings). join --recovery-words is a stub that says what work package 12 connects (Membership::recover_all_folders). folder create-f3 <name> (hidden) makes a folder in the membership records until folder add does.

Local API. GET /api/folder/requests[?folder=], POST /api/folder/request {folder, role}, POST /api/folder/approve {folder, device, role?, fingerprint?, fingerprint_confirmed: true} (refused unless fingerprint_confirmed is the boolean true; with fingerprint the words must still be the request's), POST /api/folder/deny {folder, device}, GET /api/folder/members[?folder=] (all folders without it), POST /api/folder/role {folder, device, role}, POST /api/folder/remove {folder, device, confirm: true} (the same path as the vault-wide folder removal, which takes name; a body with device is a removal from the folder), POST /api/folder/resolve-epoch {folder, epoch, keep}, GET /api/recovery/escrow (the missing copies), POST /api/recovery/escrow {words, folder?}. /api/state says format3. A successful change publishes folder.changed on the event stream and asks for a sync; the service publishes folder.request once per new pending request (and a notification) after each sync round. MCP keys reach none of these routes.

The background service never answers a request. It lists (f3_requests) and announces; approving, denying, granting, changing roles, removing and writing recovery copies need a person at a command line or the page. A test in service.rs reads its own source and fails if any of those calls appears.

Pairing, offering side. POST /api/pair/start {"format": 3} opens Offer::start_v3; its Approve callback holds the joining device's name and fingerprint (ask in GET /api/pair/status, with the folders this device owns) and blocks up to five minutes. POST /api/pair/answer {allow, folders[], fingerprint?, role?} writes, for the ticked folders (default none), a folder record entry and a grant sealed to the K8 of the joining device's hello (Membership::grant_to_joiner: the hello's keys stand in for a device record, which the joiner publishes after joining), and only then lets the vault key go out; allow: false declines. The page opts in only when the device owns a format-3 folder. The joining side shows its own fingerprint once its keys exist (work package 12 wires the joining engine).

Page. The Files page has a "Folder access" card per folder: requests with name, role asked and six words and Approve/Deny (Approve opens a dialog with the words and a box "The six words match on both devices" that must be ticked), members with a role selector and Remove (the confirmation names the consequence: a new folder epoch; the device keeps what it read), unresolved folder epochs, and a banner with "Write recovery copies…" that asks for the recovery words.

Tests: crates/varsto-cli/tests/folder_approval_cli.rs (the commands through the binary), desktop.rs tests (each route, the refusal without fingerprint_confirmed, pairing with ticked, no and declined folders, the not-available answers), service.rs (the_service_never_approves_or_grants), the interface coverage tests (fi, sv).

77. Format 3 (shipped)

Status. Storage format 3 is the format of every build: FORMAT_VERSION is 3, there is no cargo feature for it, and nothing older is read (no migration, 77.15). This section describes the code: a pack-level ledger, folder block maps and signed records. Where the code is silent the binding text is format-3-design.md; a line marked As built names where the code and the design differ. 77.1 to 77.16 describe the parts as the work packages built them; 77.17 to 77.21 describe the switch of the engine to them, area by area; 77.22 says what is left of format 2; 77.23 describes three behaviours restored after it. Vaults are created fresh. Sections 75 and 76 describe the peers and the membership commands of the same series in their own words; this section repeats only what the other parts need.

Notation is that of the design. Ids are binary on the wire: vault, device, folder and backup 16 bytes; chunk id, object name, pack id and body hash 32 bytes; hex only in object names on a storage. Integers are little-endian. "postcard" is the postcard 1.x encoding of the Rust struct as written, "zstd" is level 3, aad(type, fields) is crypto::aad_for_format (length-prefixed format number, AEAD id, type and fields; the records bind format 3, 77.5), derive(K, purpose, scope...) is BLAKE3 derive_key with the context e2ee-sync-format/3/<purpose> and length-prefixed scope ids (membership3::derive3).

Part Where Subsection
keys membership3::{keys, grants, escrow} 77.1
packs and size classes packs, storage 77.2
folder block map, marks, collection, repair blockmap, gc3 77.3
ledger ledger3 77.4
signed records record 77.5
folder membership and recovery membership3, fingerprint, the commands of section 76 77.6
manifests, trash, history, snapshots manifest3, trash3, snapshot3 77.7
peers and transport p2p::v3, pair::v3 (section 75) 77.8
replicas, pools, transferrers, moves, drains, quotas storages3 77.9
fsck, rebuild, scrub fsck3, rebuild3, scrub3 77.10
authorization, what each party learns, limits, tests 77.11 to 77.14

77.1 Keys

All keys are 256 bits. Changes against section 3 (and sections 21, 24, 62):

Key Purpose Made Change from format 2
K1 recovery key escrow of every folder key epoch 256 random bits, 24 BIP-39 words, optional Shamir 2-of-3 (recovery::split) designed in format 2 and never shipped; now the second word set of the kit (77.6)
K2 = derive(K1, recovery-wrap) wraps escrow derived as designed
K3ₑ vault key, epoch e registry, vault ledger, peer records, vault epoch records, local keyring, pool markers 256 random bits; epoch 0 is the first word set of the kit; later epochs only as vault grants (77.6) no longer derives any folder key
K4 device unlock key wraps K3ₑ, K6, K8 on one device Argon2id (64 MiB, 3, 1) of the NFKC passphrase unchanged
K6 device signing key signs every record, batch, checkpoint and peer token binding Ed25519 + ML-DSA-65, made on the device signs records, not only batches; the device id is BLAKE3(K6 public)[..16] and the device record carries K6
K8 device KEM key receives grants and vault keys X25519 + ML-KEM-768, made on the device in the device record (no separate vault/kem/ file)
K9ₑ folder key, folder epoch e one folder, one epoch 256 random bits, made by the owner that starts the epoch never derived from K3; grants and escrow carry it; folder records carry no key
K10ₑ = derive(K9ₑ, folder-metadata, folder) manifests, maps, trash and history, snapshots, thumbnails, notes, access records derived also block maps
K11 = derive(K9₀, dedup-hash, folder) chunk ids and content hashes, fixed at the folder's first epoch derived once, carried in every grant and escrow unchanged
K12, K14, chunk nonce chunker seed, chunk key, nonce as section 62 unchanged
K13ₑ Strongroom key as K9ₑ for a Strongroom folder as section 17; escrowed like K9 only if the user opts in never under K3 (design only: no Strongroom code is part of this series)
registry key = derive(K3ₑ, device-registry) device, folder, request, peer, policy, placement, settings and storage-name records derived also folder records and requests
ledger key = derive(K3ₑ, ledger) vault ledger batches and checkpoints derived unchanged
vault epoch record key = derive(K3ₑ, epoch-record) the record of vault epoch e derived new; the design names the epoch@<e> key without a derivation
share-ledger key = derive(K9ₑ, share-ledger, folder) folder-scoped batches of members derived unchanged
escrow key = derive(K2, folder-escrow, vault, K3₀) escrow records derived new (77.6)

Removed: folder keys derived from K3, folder keys in folder records, the pack-tombstones key, the p2p-auth token key (77.8), plain and vst1 share tokens, bare (unsigned) epoch records and SHARE_EPOCH_BASE: with no vault-derived folder keys, one folder epoch sequence 0, 1, 2, ... serves removals of own devices and of members alike.

Key ids name the key that opens a body and are inside every signature (77.5): registry@<e>, ledger@<e>, epoch@<e>, meta:<folder hex>@<e>, share-ledger:<folder hex>@<e>, kem:<recipient device hex>, recovery, replica, none. The grammar is strict (record::KeyId::parse): lower-case hex, decimal epochs without leading zeros, at most MAX_KEY_ID = 64 bytes, so one key has one spelling. none (body not encrypted) is allowed for request records only.

What a holder of K3 alone sees. A device joined with the vault words and not yet approved for any folder reads the registry (device names, folder names and settings, participants), the vault ledger (pack ids and size classes, which storages hold which packs, folder ids, writers, record announcements) and the peer records. It can verify packs against their ids, copy packs between storages and sign vault batches. It cannot open any manifest, map, trash record, snapshot or block, and learns no chunk id, object name or place of a block (test a_device_with_the_vault_words_sees_names_and_no_content).

77.2 Blocks and packs

Blocks are as in section 62: the keyed chunker with size tiers (chunking: 2), chunk id = keyed BLAKE3(K11, plaintext), pack(plain) = method byte || payload, the chunk object nonce (24) || ciphertext || tag (16) under K14 with the derived nonce, object name = BLAKE3(chunk object), and the readers' three checks (nonce against the packed bytes, plaintext against the chunk id, object against its name). One function seals (chunk_seal::seal_chunk), one opens (chunk_seal::open_chunk).

Pack layout. packs/<xx>/<pack id hex>: member objects back to back from offset 0, then random padding, nothing else: no header, trailer or index. The pack id is the BLAKE3 hash of all bytes, padding included. Padding is bytes of the operating system's CSPRNG (packs::build); a zero tail would show where the members end to anyone holding the pack.

Size classes. The length of a pack is exactly one class: 256 KiB, 1, 4, 16 or 64 MiB on hot, local, pool and transferrer storages, and the same plus 256 MiB on cold storages (KiB = 2^10, MiB = 2^20). The class code is 0 for 256 KiB up to 5 for 256 MiB (ledger3::events::class_bytes: 2^(18 + 2c) bytes). packs::padded_len takes the smallest class that holds the members, never above the storage's top class (top_class: 64 MiB, or 256 MiB for a storage with a pack target above 64 MiB). A reader refuses a pack, a place list entry or a map pack reference whose length is no class: "pack <id> has length <n>, not a size class" (packs::Reader::loc under the feature; blockmap::BlockMap::check_limits and verify_pack for maps and verification). storage::MAX_PACK is the largest class, 256 MiB. Members never overlap and never pass the end of the members area, and a member object is at least 41 bytes (method byte, nonce and tag) and at most MAX_CHUNK_SIZE + 1 + 40 (16 MiB, the method byte, nonce and tag; packs::MAX_OBJECT).

Choosing the class. A push (and an import, a repair, a data move, a rewrite) collects members in a buffer and places them first-fit decreasing into bins of at most the storage's top class (packs::first_fit_decreasing; blocks of one file stay in their original order inside a pack); a pack closes when the next member would pass the top class, and the last pack of an operation takes the smallest class its members fit in. Padding is therefore below the next class step: a pack is never larger than the next class above its members. Measured on the benchmark data (section 62's Limits): 50 000 small files stored 22 packs, 1.3 % over the data; one 1 GiB incompressible file stored 17 packs, 1.6 % over the data. Imports collect contents across files exactly like pushes, so a pack never shows one file's size. A content counts as imported, and its blocks are claimed, once every pack holding one of its blocks is written.

Writing. Put-if-absent; S3 multipart in 16 MiB parts above 64 MiB; a HEAD before the PUT finds a pack that is there. Packs are written before the map record that lists them and before the batch that claims them (77.3, "Writer").

Format-2 readers keep lenient reads (the amendment to section 62 made with the size classes): a build without the feature reads a pack, place, index or tombstone entry of any length up to storage::MAX_PACK, so packs of older builds (not padded) are still read, verified and collected, and only writes produce size classes; only a format-3 reader refuses a length that is no class. A build from before the size classes (0.0.1-alpha.15) reads padded packs but, in garbage collection, leaves a padded pack alone, and an emptied one stays until a newer device removes it; garbage collection in format 2 accounts for the members from offset 0, and what follows the last known member must be the padding of the pack's class.

As built. The design builds one pack per target set (the set of storages a group of blocks goes to), so that a pack is byte-identical on every storage of the set and has one id there. The push path builds one pack per target set (section 62): the storages a block goes to, cold storages apart, get the same pack under the same id; imports, data moves, drains, repairs and forwarding still build per storage. The ledger and the map handle one pack held on several storages under one id, and rewrites, compaction, whole-pack copies, replica rounds and moves write it byte-identical. Cost of small pushes: one small edit costs a 256 KiB pack on every storage it goes to, until compaction folds them (77.3).

77.3 The folder block map

The block map says, for every block of a folder, in which pack and at which offset it is. It is per folder, per writer device, and sequence-numbered; it takes over from format 2's pack indexes, tombstones and per-block claims.

Stream and record. maps/<folder hex>/<device hex>/<seq 16 digits>-<part 4 digits>.rec, a SignedRecord (77.5) of kind block-map, scope = the folder, key id meta:<folder>@<e> with e the newest folder epoch the writer holds, announced in the writer's batch (record_published). seq starts at 1 and rises by 1 per record. Body (blockmap::BlockMap; postcard, then zstd, then sealed):

BlockMap {
  folder: [u8;16], device: [u8;16], seq: u64, lamport: u64,
  base: u64,                 // seq of the base this record builds on; == seq for a base
  prev: [u8;32],             // record_hash of record seq-1; zeros for seq 1
  packs: Vec<PackRef>,       // table, referenced by index
  entries: Vec<MapEntry>,    // base: every live place this writer wrote; delta: places added since seq-1
  marks: Vec<Mark>,          // dead / undead / lost marks on places of any writer of the folder
}
PackRef  { id: [u8;32], class: u8 }     // 0 = 256 KiB ... 5 = 256 MiB
MapEntry { object: [u8;32], chunk: [u8;32], pack: u32, offset: u32, len: u32, plain_len: u32, epoch: u32, flags: u8 }
Mark     { object: [u8;32], pack: [u8;32], offset: u32, kind: u8 }   // 1 dead, 2 undead, 3 lost

A place is identified by (pack id, offset); object repeats the object name so a reader checks every place it uses; len is the object length (packed length = len - 40), plain_len the plaintext length (the chunk AAD needs both). flags bit 0 (FLAG_DEAD) is the writer's own settled view that its place is dead, kept in bases until the place is collected; other bits must be 0. Limits (check_limits, step 6 of the acceptance rule): at most 4 194 304 entries and 1 048 576 marks per part and 65 536 packs, offset + len within the class size, a class of at most 5, an object of at most packs::MAX_OBJECT bytes, plain_len at most 16 MiB, mark kinds 1 to 3, an index into packs for every entry, seq ≥ 1 and base between 1 and seq, and the body's folder, device and seq equal to the envelope's. As built: the per-part limits are applied as that many times the record's part count (parts are byte ranges of one compressed body), and the 65 536 packs are counted over the whole record; the map record accepts any class from 0 to 5 whatever the storage, the cold-only rule of the 256 MiB class is checked where the storage is known (fsck, 77.10).

Base and delta. A base lists every live place the writer wrote (its packs that the view still shows on at least one storage) and the marks it made that are not gone with their place; a delta lists places added since seq - 1 (new packs, rewrites, repairs) and new marks. The writer publishes a base for its first record, and after that when 1024 deltas follow the last base or the deltas' stored bytes reach 1/4 of the base's (blockmap::BASE_AFTER_DELTAS, BASE_BYTES_DIVISOR, whichever comes first; stored bytes are the padded sizes of record_published). The rule is looser than the manifests' (77.7): a map base of a large folder is hundreds of MB of incompressible hashes and deltas are pure additions. In a base, the marks kept per place are the newest dead or undead mark of this writer and its lost mark, unless a pending mark replaces them; marks on places whose pack no storage holds any more leave the base, and so do entries of packs held nowhere. A record over 32 MiB is written in parts (77.5). A writer that finds a record under its next seq that no batch announced (a crash between the record and its batch) skips that seq and writes a base after it, because a delta would name a prev no reader can check.

Who writes. Every device that writes packs of the folder with the editor or owner role: own full devices, members of shared folders with the editor role, forwarders (they hold the folder key), and the collectors and repairers that write the new packs of rewrites and repairs. Viewers, replicas and holders of K3 alone write no maps (the acceptance rule refuses them, 77.5).

Writer. One push (or import, data move, repair, rewrite, forward run) writes its packs, then one map record listing their members to every hot metadata storage (put-if-absent; the first storage decides a seq race), then seals one batch with pack_stored for every (pack, storage) written and record_published for the map record (and the manifest record, 77.7), and pushes it (blockmap::MapWriter::publish, events). A crash before the batch leaves packs no claim names, which garbage collection deletes after 7 days when no map lists them (orphans, below).

Reader and the local table. A device that holds K10 of the folder keeps a table per folder, state/maps/<folder hex>.tbl (device-local state, not a wire format): the union of every accepted writer's newest base and the deltas after it, as fixed-width rows of 88 bytes sorted by object name, a second array of row numbers sorted by (chunk id, epoch), and the marks in a side table sorted by place (88 bytes each), with a footer (VBMT, version 1, the folder, counts) and a BLAKE3 over the file. Lookups are binary searches with positioned reads, so memory is O(1) in the number of blocks; disk is about 88 bytes per place. Every change writes a new file beside the old one (.tbl.tmp, flushed) and renames it over it, so a crash leaves the old table or the new one, and a table that fails its hash or its sizes is treated as empty and rebuilt from the bases. Building sorts with bounded memory (runs of 2^20 rows, merged from files). A pull (blockmap::pull) lists only streams whose announced newest seq is past the one applied, reads from a newer announced base when there is one (that writer's rows and marks are replaced), accepts records through record::accept, and requires the announced base to equal the body's; a delta applies only when it is the next seq, names the applied base and its prev equals the applied record's hash, else it and the writer's later records are skipped and reported. A mark on a pack the view gives to another folder is refused and counted (marks_refused).

Finding a block (fetch, restore, verification, P2P serving): the manifest gives the object name; the table gives its places (pack, offset, length); the ledger view gives the storages that hold each pack (claimed, not dropped, not retired); one ranged read; the object is checked against its name; it is opened with the chunk's epoch (blockmap::find_block, open_block). Places with a dead or lost mark are tried only after the others (LedgerView::block_places).

Copies of a block are the storages holding a live place of it: the pack held there and the place without a dead or lost mark (LedgerView::block_copies; the storage code of 77.9 also counts the writer's own dead flag like a dead mark). Policies, placement, staged moves, disk groups, drains and quotas count this way (77.9).

Dedup for a writer. Before writing a block the writer looks up its chunk id in its table (blockmap::needs_write). A place counts for storage S when its pack is held on S in the view and the place has no dead or lost mark this device holds (settled or not; an undead mark newer than every dead one revives it). If every target holds such a place, nothing is written; for the targets that lack one, the block goes into new packs for those storages only, with the same object. A block whose only places carry a dead mark is written again, never revived by reuse. Across epochs a chunk the folder already holds keeps its object: the oldest epoch with a live place anywhere wins, and within one epoch the object held on most targets.

Dead marks, settling and collection. Liveness is decided by references, never by marks alone. An owner or editor device that finds an object referenced by nothing publishes a dead mark for each of its places in its next map record. Referenced means: a current (not deleted) file in any accepted writer's newest manifest, an unexpired trash or history entry, an unexpired snapshot of the folder (gc3::References; trash3::Refs combines the three). The mark made in map record m of marker M is settled when every current writer of the folder (owners and editors, own devices and members, not revoked) has signed a batch whose seen names M at or after the batch that announced m (LedgerView::settled; members' folder-scoped batches count here and for pruning, never for the vault ledger's). A place is collectable when a dead mark of a current writer is on it and settled, no undead mark with a larger (Lamport time, device) stamp is on it, and nothing references the object (gc3::place_verdict). The race "a block deleted on one device while another skips writing it" is closed by the ordering: a writer that skipped a block did so before it pulled the mark, so its manifest naming the block is announced in a batch before the one in which it acknowledges the mark, and the collector sees that manifest before the place becomes collectable. A device that finds a reference to an object whose place is dead-marked publishes undead marks (gc3::mark_round). A hostile or mistaken mark delays nothing and deletes nothing that is referenced. Between several marks of one place, the newest by (Lamport time of the carrying record, marker device) decides, and a lost mark is sticky.

As built (garbage collection). The collector requires that it applied every reference record (manifest, trash, snapshot) its view shows announced by any writer of the folder, not only those announced up to the batches that settled the mark: the view keeps each writer's newest acknowledgement, not the batch that first carried it, and the stronger condition implies the design's (References::behind; a writer whose stream is forked counts as behind until the fork is resolved). Dead marks are likewise made only when no writer is behind. Only marks whose marker is a current writer count for collection (others are ignored and counted in marks_ignored), on top of the acceptance rule refusing the map records of viewers, K3-only devices and replicas outright. Undead marks are published by any writer that finds a reference, not only the marker. A pack whose known members do not follow one another from offset 0 holds a member the collector's table does not list and is neither dropped nor rewritten.

Who may mark. Owners and editors that hold K10 (gc3::Standing::may_mark), members of shared folders with the editor role included. Marks from viewers, replicas and K3-only devices cannot exist (those devices write no block-map record), marks of devices demoted or removed since are ignored, and marks naming a place in a pack of another folder are refused and counted.

Garbage collection (gc3::collect), run by the trash upkeep on own full devices with the write role that hold K10; members do not collect (Standing::may_collect: they may not hold the owner's storages). One run is one action: new packs first, then one map record for them, then one batch with pack_stored (new packs), record_published and pack_dropped, pushed; only then are old packs deleted (a failed commit deletes nothing):

  • a pack whose every member place is collectable is dropped on every storage that holds it; on a cold storage not before the price model's minimum storage duration, counted from the newest claim's batch time there (drops_later);
  • a hot pack (held only on hot storages) whose collectable members make up more than half of its member bytes (padding not counted) is rewritten: one GET, the id and length checked, every live member checked against its name, live members into new padded packs for the same storages, the new places in a map record;
  • cold and pool packs are never rewritten; their dead space goes when every member is collectable;
  • compaction: hot packs of a class below 64 MiB, grouped by the set of storages that hold them, whose live members together fill at least 64 MiB (and are more than one pack) are merged in the same way (this bounds the cost of small pushes).

Entries of a dropped pack leave their writer's next base; marks on places that are gone leave the marker's next base. A pack the view shows deliberately dropped from a storage but still there (a crash between the batch and the delete) is deleted at once.

Orphans. A pack on a storage that the view does not show held there, that the view does not show dropped, and that no map table lists is an orphan. Storages keep no write times the collector can read, so the 7-day rule counts from when the collector first saw it (gc3::OrphanState, kept by the caller, ORPHAN_SECS = 7 days); then it is deleted. As built: this stands in for the design's "older than 7 days"; fsck reports orphans with an age when its caller supplies modification times (77.10).

Verification and repair (gc3::verify, section 26 per pack). Verification reads a whole pack (one GET up to MAX_PACK) and compares its length with its class and its BLAKE3 with the pack id (PackCheck: Good, Missing, WrongLength, Mismatch); a good pack yields pack_verified. It needs no folder key, so K3-only devices and replicas verify too. A pack missing (or damaged) on a storage but held intact on another is copied whole from it, checked against its id, and claimed under the same id (copy_missing_pack; a replica claims with the zero folder and map seq 0). Repair (repair_pack) is for a writer: it checks every member the table lists against its name, takes a corrupt member from the same place on another storage that holds the pack, else from the caller's fetchers (another pack, a peer, the local file, the block cache), writes the good members into new packs on that storage (cold storages too: a damaged pack must not keep counting, so repair is the exception to "cold is never rewritten"), publishes a map record with the new places and lost marks, and seals one batch with pack_stored (new) and pack_dropped (damaged), then deletes the damaged pack. A member with no good copy anywhere keeps its lost mark and is reported (the file is damaged) until a device that holds the file writes it again. As built: a lost mark goes on a place only when no other storage holding the same pack gives a good member there, since a place is (pack id, offset) on every storage of the pack; a member fetched from another pack, a peer, the local file or the cache still leaves the lost mark, so reads prefer the new place. Repairs, like marks, need the writer role.

Pruning (gc3::prune_map). A writer deletes its map records below its newest base B on every hot metadata storage once every reader of the folder (every participant holding K10: owners, editors and viewers, own devices and members, not revoked) has acknowledged the batch that announced B; cold storages are not pruned, and a storage that does not hold B is not pruned. Readers that join later read B and its deltas. varsto status is meant to say which device a base or a collection waits for (GcPlan::waiting, map_readers_waiting); the commands are not part of this series.

Worked example (the design's, run as the test worked_example_a_pushes_deletes_b_marks_a_acks_b_collects). Device A pushes photo.jpg (3 MiB, three blocks) to hot storages H1, H2 and cold C: pack P (class 4 MiB) for {H1, H2}, pack Q (class 4 MiB) for {C}; map record A/17 lists both packs and six places; batch A/240 carries pack_stored(H1,P), pack_stored(H2,P), pack_stored(C,Q), record_published(block-map, F, 17) and record_published(manifest, F, 52). B pulls and reads a2 from P on H1. After A deletes the photo and the trash days pass, B's upkeep finds the blocks unreferenced and publishes B/9 with dead marks in batch B/77. A acknowledges B/77 in A/251; B's settle check passes (A and B are the only writers), B finds no reference, and seals pack_dropped(H1,P), pack_dropped(H2,P), pack_dropped(C,Q) and deletes them (Q after C's minimum duration). If device D had re-added the photo before pulling B/9, D's push skipped writing the blocks and announced D's manifest in D/30; D acknowledges B/77 only in D/31; B waits for D/31, reads D's manifest, finds the reference and publishes undead marks (worked_example_d_re_adds_the_photo_before_pulling_the_mark).

77.4 The pack-level ledger

Unchanged from section 6, 22 and 58, and reused as they are where the types are format independent (ledger3::store follows the format-2 store): per-device hash chains, Lamport clocks with reservations, order-independent application, the incremental mailbox (ledger/<device>/, a pull lists only what follows the head), batches waiting for a missing predecessor (<device>/pending/), fork detection, fencing on verified objects only, the scopes of section 58, acknowledgements (seen), the pruning rule (a checkpoint's batches go once every reader acknowledged it) and one batch per user action. What changes is the unit: the ledger claims packs, not blocks, and its objects are SignedRecords.

Batch body (postcard, then zstd; replaces JSON): Batch { device: [16], seq: u64, prev: [32], lamport: u64, created_utc: i64, seen: Vec<([16], u64)>, events: Vec<RawEvent> } with RawEvent { code: u16, payload: Vec<u8> }; each payload is the postcard encoding of the event's fields. prev is the body hash of batch seq - 1 of the device (zeros for seq 1); seen is the newest batch of other devices the writer held when it sealed this one (full devices: every device; members: the folder's devices only). The envelope is a SignedRecord (77.5) of kind batch at ledger/<device hex>/<seq 16>-0000.rec (a batch is always one part); its body_hash is the chain hash and its key_id is signed. MAX_BATCH_BODY is 16 MiB compressed, MAX_EVENTS 65 536 per batch, and a reader decompresses at most 64 MiB; an action that would exceed either seals further batches, each with the next Lamport time and its own seen (events::split_events; the one rule of "one batch per action" that bends). A reader skips a code it does not know (counted in events_unknown) and refuses a known code whose payload does not parse or breaks a limit (counted in events_refused); the rest of the batch counts.

Code Event Fields Who may make it
1 device_enrolled name (at most 128 bytes) any scope (the signer's own name)
2 folder_added folder full
3 pack_stored storage (name, 1 to 64 bytes), pack [32], class u8 (0 to 5), folder [16] (zeros from a replica), map_seq u64 (0 from a replica) full; member: its folder; replica: zero folder and map seq 0
4 pack_verified storage, pack full; member and viewer: packs of its folder; replica
5 pack_dropped storage, pack full; member: packs it stored
6 record_published kind u8 (manifest, block-map, trash or snapshot), scope [16], seq u64 (≥ 1), base u64 (1 to seq), parts u16 (1 to 1024), body_hash [32], size u64 full; member: kinds manifest, block-map and trash of its folder
7 storage_retired storage full
8 snapshot_taken backup, seq, taken_utc, expires_utc, files, bytes full (the source device)
9 snapshot_expired backup, device, seq full
10 backup_stopped backup full

Removed against section 6: chunk_stored, chunk_verified, chunk_dropped (replaced by the pack events), manifest_published (replaced by record_published, which also announces maps, trash records and snapshots) and chunk_on_device (below). snapshot_taken carries times and sizes only; the hash a restore checks is in the snapshot's record_published. The body_hash a multi-part record announces is BLAKE3 over the concatenated body_hash of its parts in order; a one-part record announces its part's hash (77.5).

chunk_on_device becomes a per-file flag. Its users decide per folder and already hold the folder key: transferrer targeting and emptying, the folder safety indicator ("another device holds a copy"), where, and the forwarding report. "Device D holds object O" now means: some entry of D's newest manifest with held names O (77.7, manifest3::HeldIndex). No ledger event; holders of K3 alone lose the per-device byte counts of where, which they could not attribute to files anyway.

Scopes (ledger3::EventScope, selected by the batch's key id, ledger@<e> full, replica, share-ledger:<folder>@<e> member): the table above and 77.11. Events outside the signer's scope are left out and counted in events_refused. A member's pack_stored must name its own folder, and its pack_stored, pack_verified and pack_dropped count only when the pack's folder (named by the newest claim of a full device, else by the newest member claim) is the member's folder; a pack_dropped also needs that the member stored the pack. Those depend on the rest of the view, so they are kept aside and decided once all batches are applied (LedgerView::finish), which keeps application order-independent. A viewer's batch counts pack_verified of its folder's packs and device_enrolled, nothing else.

View. ledger3::LedgerView (in memory; the cache ledger/view.rec is postcard, then zstd, then AEAD under a local key, view format 1 of format 3, ViewCache):

LedgerView { packs: HashMap<[u8;32], PackRecord>,
             streams: BTreeMap<(kind, scope, device), Stream>,   // announced records
             tables (interned devices, folders, storage names), devices, devices_at, folders, max_lamport,
             retired, batches, acks, folder_acks, forked, forked_streams, snapshots, backups_stopped,
             events_refused, events_unknown, marks_refused, ... }
PackRecord { class: u8, folder: u32, writer: u16, map_seq: u64, at: PackStamp,   // interned; from the newest claim
             places: SmallVec<[(storage u16, PackPlace)]> }
PackPlace  { claimed_by, verified_by, dropped_by: u64 device bitsets, stored_at, verified_at, dropped_at: Lamport,
             stored_utc, verified_utc }
Stream     { records: BTreeMap<seq, Announced { base, parts, body_hash, size, batch }>, floor }

Devices numbered 64 and above are kept in a side map (wide). Application is order-independent: claims and verifications are unions, times are maxima, a drop cancels the claims on that storage with a smaller Lamport time (a place counts while its newest claim is newer than its newest drop and than the storage's retirement), and the folder, writer, class and map seq of a pack come from the claim with the largest (Lamport time, device, batch seq, position) stamp among full devices' claims that name a folder. A stream keeps the newest base any announcement named and the records after it (floor is the largest base seen, a maximum, so arrival order does not matter); snapshot streams keep every record, since a differential names an older base. Two announcements of one seq with different hashes mark the stream forked. Interned numbers depend on arrival order, so two views are compared through canonical(). holders(pack), copies(pack), is_held, dropped_from, packs_on(storage), block_places, block_copies, announced, and the settling queries acked, settled, settle_waiting_for, vault_acked_by_all are the questions the rest asks.

Checkpoints keep their rules (written by the device itself, speak for their signer only through LedgerView::restricted_to, read only from full devices, refused when more than 65 536 beyond the newest batch held unless the batch they end at is beside them) with the pack-level view as body: Checkpoint { device, seq, head_hash, created_utc, view }, a SignedRecord of kind checkpoint at ledger/<device>/checkpoint-<seq 16>-<part 4>.rec (parts as in 77.5; checkpoint names still sort after every batch name), at most 1 GiB decompressed. Acknowledgements keep seen; a member's folder-scoped batches carry seen for the folder's devices only (LedgerStore::folder_seen), which count for settling marks and for pruning folder records, never for vault ledger pruning.

Estimates (the design's, not measured here): for 1 M files and 10 TB in four devices and three storages, the first upload is about 337 000 pack_stored events (about 27 MB) instead of about 12.9 M chunk_stored events (about 3.4 GB of JSON before zstd), the view about 187 000 pack records (about 40 MB in memory, about 26 MB stored) instead of at least 3 GB, and the block places about 730 MB on disk at the devices that hold the folder key. The ignored benchmarks ledger3_scale_benchmark (crates/varsto-core/tests/ledger3_scale.rs) and manifest3::tests::a_million_file_base measure these; their results are not part of this text.

As built. Batches and checkpoints are record::SignedRecords (ledger3::envelope is the ledger's door to record): they are sealed by record::RecordWriter and accepted by record::Acceptor, whose steps 1 to 3 (the name a batch was read under, the envelope, the signature, the writer) run even when the reader holds no key for the body (Acceptor::check_parts), so the signature and the body's associated data bind format 3 whatever the build's FORMAT_VERSION. A batch body is decompressed to at most 64 MiB and a checkpoint to at most 1 GiB (RecordBody::max_decoded). Folder roles of full devices (work package 12, design section 9): a full device's claim that names a folder (pack_stored with that folder) and its record_published of a folder's manifest, block map or trash record count only while the device is an owner or editor of that folder at the batch's Lamport time (ledger3::scope::FolderRoles, answered by the folder records' role history, FolderState::role_at); copies of whole packs (zero folder), verifications, drops and retirements count from every full device, as for a device that holds the vault key alone. A folder the folder records do not know is not judged. The caller puts what the roles depend on into the view cache's context, so a change of roles replays the view. Names are interned in 16 bits for devices and storages: a view takes at most 65 534 of each and counts events beyond that refused.

77.5 Signed records

Every object a device publishes, except packs, is a SignedRecord (record::SignedRecord): "VSR3" || postcard(envelope).

SignedRecord {
  format: u16 = 3, kind: u8, vault: [16], scope: [16] (zeros = vault-wide), device: [16],
  seq: u64, part: u16, parts: u16, key_id: String, body_hash: [32], sig_alg: u8 (1 = ed25519+ml-dsa-65),
  sig: bytes,   // 64 + 3309 bytes, over aad("record-signature", [kind, vault, scope, device, seq, part, parts, key_id, body_hash])
  body: bytes,  // nonce || AEAD ciphertext || tag
}
body AAD = aad(<kind name>, [vault, scope, device, seq u64, part u16, parts u16, key_id])
body_hash = BLAKE3(body)

kem: bodies are KEM ciphertext || nonce || ciphertext || tag (the AEAD key is the KEM secret, the AAD the generic one above), and none bodies are the framed plaintext without encryption. The byte fields are postcard byte strings (the same bytes as a Vec<u8>). The signature covers body_hash, so an envelope with an empty body proves that its signer wrote a record with that hash (head exchange, 77.8); verify refuses an empty body.

Padding. The plaintext of a part is len: u32 || data || random padding, where len is the length of the data (a slice of zstd(postcard(body))) and the padding is CSPRNG bytes chosen so that the length of body (nonce, KEM ciphertext, ciphertext and tag included) is a multiple of 64 KiB below 4 MiB and a multiple of 1 MiB from 4 MiB up (record::pad; a decoder refuses any other length: "its body length <n> is not a size class"). A reader takes len bytes after the length field and ignores the rest; a len past the end of the plaintext is junk. This applies to every kind, batches and checkpoints included.

Parts. A body larger than MAX_PART_BODY = 32 MiB is split into at most MAX_PARTS = 1024 parts, which are cut from the compressed bytes (zstd runs over the whole body first, the compressed stream is cut), each part sealed, hashed and signed on its own with part and parts inside the signature. A record is complete when all its parts are there; a reader fetches each part with a limit of MAX_PART_READ = 33 MiB, and decompresses at most MAX_DECODED_BODY = 4 GiB. The hash a batch announces is record_hash: the part's body_hash for one part, else BLAKE3 over the parts' hashes in order. Storage name: <stream prefix>/<seq 16 digits>-<part 4 digits>.rec.

Kinds and streams (record::Kind, StreamRef). "Announced" kinds count only once a batch of the same device announces them (record_published); the others are "newest seq of the stream wins" (put-if-absent at the seq; a writer starts after the highest it finds). The last column says whether the code in this series has a body type for the kind.

Code Kind Stream prefix key id Announced Body in code
1 manifest manifests/<folder>/<device>/ meta:<folder>@<e> yes manifest3
2 block-map maps/<folder>/<device>/ meta: yes blockmap
3 trash trash/<folder>/<device>/ meta: yes trash3
4 snapshot snapshots/<backup>/<device>/ meta: of the backup's folder key yes snapshot3
5 peer vault/peers/<device>/ registry@<e> no p2p::v3::peer
6 epoch (vault epoch) vault/epochs/ (seq = epoch; device = issuer, in the envelope only) epoch@<e> no membership3::epochs
7 share-epoch (folder epoch) vault/folder-epochs/<folder>/ (seq = epoch) meta:<folder>@<new epoch> no membership3::epochs
8 grant vault/grants/<folder or vault>/<epoch, 10 digits>/<recipient>/<issuer>/ kem:<recipient> no membership3::grants
9 request vault/requests/<folder>/<device>/ registry@<e> or none no membership3::requests
10 revocation vault/revocations/<device>/<issuer>/ (scope = the removed device) registry@0 no membership3::epochs
11 policy vault/policy/<device>/ registry@ no records3
12 placement vault/placement/<folder>/<device>/ registry@ no records3
13 checkpoint ledger/<device>/checkpoint- ledger@<e> (full devices) no ledger3
14 batch ledger/<device>/ ledger@<e>, share-ledger:<folder>@<e> or replica no ledger3
15 folder vault/folders/<folder>/<device>/ registry@ no membership3::folders
16 device vault/devices/<device>/ registry@ no membership3::devices
17 escrow vault/escrow/<folder>/<epoch, 10 digits>/<device>/ recovery no membership3::escrow
18 settings vault/settings/<device>/ registry@ no trash3::settings
19 storage-names vault/storage-names/<device>/ registry@ no records3
20, 21, 22 access, notes, thumbs access/, notes/, thumbs/ + <folder>/<device>/ meta: no records3
23 replica vault/replicas/<device>/ registry@ no none yet (77.16)
24 strongroom vault/strongroom/<folder>/<device>/ registry@ no none yet (77.16)
25, 26, 27 org-manifest, org-roster, org-log vault/org/manifest/, vault/org/roster/, vault/org/log/ + <device>/ registry@ no none yet (77.16)
28 mailbox vault/mailbox/<device>/ registry@ no none yet (77.16)

Bodies of kinds 11, 12, 19 to 22 (records3, work package 12). Each names its writer and seq (and, for folder kinds, the folder), which must be the envelope's. policy: the writer's policies by folder, each {policy or none (cleared by hand), updated_utc, lamport}; per folder the newest entry of any device wins by (updated_utc, Lamport time, device). placement: {folder, device, seq, lamport, updated_utc, storages, storage_ids, places}, newest of any device by the same order. storage-names: the writer's (local name, identity) pairs. access: (path, UTC seconds) pairs, the newest time per path over every device. notes: (path, {analysis (at most 64 KiB), tags (at most 64), content hash, by, analysed_utc}), the newest analysis per path. thumbs: (content hash, JPEG of at most 1 MiB) pairs; interpretation: a thumbs record carries the thumbnails made since the writer's previous one and a reader takes the union of a writer's records (one record per thumbnail would pad each to 64 KiB), the picture of the smallest (writer, seq) winning for one hash. Lists are sorted and unique; at most 2^20 items per record.

The vault grant (zero scope) is named vault/grants/vault/<epoch>/.... Kind::key_fits refuses a key id of the wrong class for the kind when an envelope is decoded and when a writer seals (for share-epoch the epoch in the key id must equal the record's seq; meta: keys of folder-scoped kinds must name the record's scope; batch with share-ledger: must name the scope folder; peer, policy, settings, storage-names and device have zero scope). Forward leases (section 70) stay plain JSON: they decide nothing a reader trusts.

Acceptance rule. One function, record::Acceptor::accept (open for steps 1 to 4 and finish for 5 and 6), for every kind:

  1. The envelope parses; format is 3; the kind is known; the key id is of the grammar and fits the kind; the signature algorithm is 1 and the signature has its length; part is below parts and parts at most 1024; the body is a size class of at most 32 MiB; vault is this vault; the name's prefix, scope (where the name has one), device (where it has one), seq, part and, for grants, recipient equal the envelope's; all parts of a record agree on every signed field.
  2. The signature verifies against the K6 public key of an accepted device record of the writer (for a device record, against the key in the body, whose BLAKE3 prefix must be the device id). A removed device's key is no longer asked for, except for folder-scoped folder, share-epoch, grant and escrow records, whose standing is decided on the body (77.6).
  3. The writer's role allows the kind in the scope (record::section9_allows, the matrix of 77.11) at the epoch the key id names.
  4. The body opens under the key the key id names (RecordKeys), with the AAD above, and decodes.
  5. For announced kinds, a batch of the same device that this device accepted carries record_published with the same part count and hash; and for a delta, the body's prev equals the announced hash of seq - 1 (seq 1 has none, and a delta at seq 1 is a fork).
  6. Kind-specific checks (RecordBody::check): the body names the envelope's scope, device and seq; manifest entries pass the checks of section 28 and the limits of 77.7; maps pass 77.3's limits; and so on.

A record failing 1 to 4 or 6 is junk: counted in records_refused by kind, never applied, reported once per name (RecordsRefused::note). A record that passes 1 to 4 but has no announcement yet waits (not counted; at most MAX_AHEAD = 64 per stream, more are not fetched and are listed again later); fewer parts than the record has are incomplete (not counted, read again later). A record whose announcement names another part count or hash, or a delta whose prev is not the announced hash of seq - 1, is refused and the writer is forked on that stream. Removed devices' records count only up to the last announcement in their accepted batches (the cut-off): the engine's announcement stops answering past it.

Refusal messages (record::Refused): record <kind> <seq> of <device hex> refused: <reason> with a reason from Junk ("its signature does not verify", "its writer is not a trusted device", "its writer may not write it", "the key it names is not held here", "its body does not open", "its key_id does not belong to its kind", "its body length is not a size class", "it belongs to another vault", and so on), record <kind> <seq> of <device hex> does not match what its batch announced for a fork, ... waits for the batch that announces it and ... is incomplete: <have> of <parts> parts. Writers refuse what readers would refuse: sealing checks the key id against the kind and scope, that the stream's device is the signer's, that a grant is sealed to the device its name gives, and that the body fits 1024 parts.

Reading streams (RecordStore): list_after(stream, after) lists a stream from a start-after name, highest_seq is where a writer continues, read_after returns accepted records in seq order, waiting ones (at most 64) and refusals, noted in the counter.

77.6 Folder membership, grants, requests, roles, removal and recovery

The records are those of membership3 (work package 8a); the commands, routes and pages are sections 76 and the CLI. Membership ties them to one device: it reads the records of every metadata storage, keeps what it accepted and writes new ones.

Devices. A device record (vault/devices/<device>/) carries the name, the K6 public key, the K8 public key and a stamp (Lamport time, device); the device id is the first 16 bytes of BLAKE3 of the K6 public key, so a record cannot be written for someone else's id, and the record is signed by the K6 it carries. Newest by (stamp, registry epoch) wins. Format 2 makes device ids at random; the switch to ids derived from K6 is work package 12.

Folder records (folder, scope = folder, key id registry@<e>): id, name, settings, participants: Vec<{device, role: owner|editor|viewer, stamp}>, denied: Vec<{device, stamp}>, never a key. The creator's first record (the one with creation) makes it the owner; the folder id is BLAKE3("varsto folder id 3" || creator || nonce)[..16] and the first record carries the nonce, so exactly one device can be the creator of an id (the design says "the creator's first record makes it the owner" without saying who the creator is). Later entries count only when their writer was an owner just before the entry's stamp (a replay in stamp order; entries from writers that were not owners are counted in entries_refused). Participants and denied entries merge per device by the largest (Lamport time, device) stamp, so two owners editing at once converge and removing a participant is a denied entry with a newer stamp. A demoted owner can still backdate entries below its demotion's stamp; Lamport stamps cannot tell that from a slow device.

Grants (grant): vault/grants/<folder>/<epoch 10>/<recipient>/<issuer>/<seq>-0000.rec, key id kem:<recipient>; body = the hybrid KEM ciphertext to the recipient's K8, then the AEAD (generic record AAD) of {folder, epoch, recipient, issuer, role, K9ₑ, K11, older: Vec<(epoch, K9)>}, where older holds the earlier epochs the recipient should read, ascending and below epoch. Accepted when the issuer is an owner of the folder at that epoch (folder records and folder epoch records). A device that holds a grant to itself holds the folder. As built: the epoch, recipient and issuer that the design puts in the AAD are in the body and checked against the storage name and the envelope, which the signature covers. A vault grant (zero scope, vault/grants/vault/...) carries {epoch, recipient, issuer, K3ₑ} for an epoch above 0.

Requests (request, vault/requests/<folder>/<device>/): {device, name, kem_pub, role_wanted} with role_wanted editor or viewer, under the registry key. Every owner device lists pending requests (a request counts as pending when the requester is a device of the vault whose device record carries the request's K8 key and which is neither a participant nor denied); approve writes a folder record that lists the device and a grant of the current epoch (and every older one held); one owner's approval suffices; deny adds a denied entry. Approval is manual: the background service only lists and announces (a test reads the service's own source and fails if a call that approves or grants appears, section 76). An approval shows the requester's device name and the six-word fingerprint of its K6 and K8 public keys (fingerprint::of_keys, membership3::fingerprint: the construction of section 24, BLAKE3 derive_key over length-prefixed parts, the top 66 bits as six BIP-39 English words, under the context varsto format-3 device fingerprint v1, over the two keys). Members of other vaults. Other people's devices ask out of band with a request code that carries their name, K6 and K8 public keys and fingerprint words; the owner answers with Membership::add_member: a folder record that lists the member as a participant (editor or viewer, never owner) together with its keys (MemberKeys: device, name, K6, K8, stamp; the id must be the BLAKE3 prefix of K6, and an entry counts only from an owner at its stamp), then a grant sealed to the member's K8. Every device of the vault learns the member's keys from the folder record (MemberRegistry), so Trust takes what the member writes by section 9's member rows (77.11), and the member reads its grant from the storage it was given. A participant that stays without any key here is listed as pending by start_folder_epoch.

Pairing (varsto pair offer, section 75): the joining device's hello carries its K6 and K8 public keys and name; the offering device shows name and fingerprint and asks; it issues grants for the folders the person ticked (Membership::grant_to_joiner, where the hello's keys stand in for a device record, which the joiner publishes after joining) before it reports success. Pairing is the only path that grants without a separate approval, and it is chosen by the person at the offering device. The vault key K3 arrives sealed to the joiner's K8 inside the SPAKE2-sealed bundle.

Roles. Owner: may grant, change roles, start folder epochs, write every folder kind. Editor: writes manifests, maps, trash records and its folder-scoped batches; marks blocks dead. Viewer: reads; its manifests, maps, trash records and marks are refused by every reader (it holds K9 and could write them, so the refusal is by acceptance rule, not by key). Role changes are folder records by an owner; a lower role does not take keys back.

Folder epochs and removal. Removing a participant starts a folder epoch: the owner makes a random K9ₑ₊₁ and writes vault/folder-epochs/<folder>/<e+1> (put-if-absent at the number; kind share-epoch, key id meta:<folder>@<e+1>, body {folder, epoch, issuer, participants that stay with their roles, removed: [{device, cutoff}]} with the removed device's newest ledger batch as the cut-off), denied entries for the removed devices, grants of the new epoch to every participant that stays, and an escrow when K1 is at hand (start_folder_epoch). One sequence 0, 1, 2, ... per folder serves removals of own devices and of members; epoch 0 has no record. Two owners writing a record under one number: both are recorded and neither is applied, nor anything above, until the user keeps one (FolderEpochs::resolve, varsto folder resolve-epoch), as section 58's "two epochs under one number" does per folder. Re-encrypting old data under the new key is a separate, budgeted job (varsto folder reencrypt, not part of this series).

Vault epochs. Removing an own full device from the vault (remove_device) writes a vault epoch record (kind epoch, vault/epochs/<e>, key id epoch@<e> = derive(K3ₑ, "epoch-record"); body {epoch, issuer, previous_epoch, previous_k3, members, revoked}, so the chain of records leads from any vault key down to K3₀), a revocation (vault/revocations/<device>/<issuer>/, scope = the removed device, key id registry@0 so the removed device reads it too; body {device, name, issuer, cutoff_seq, wipe, new_epoch}), vault grants of the new K3 to every device that stays, and a folder epoch for every folder the device held. A revocation counts only with the epoch record that backs it, applied in (new_epoch, issuer) order as in section 58 (a revocation by an issuer that was removed before it is skipped); two records under one vault epoch number are recorded in vault_forks. A vault key from before a removal does not open the newest records: such a device sees an old vault and gets no grant.

Recovery escrow. Every folder epoch is escrowed as vault/escrow/<folder>/<epoch>/<device>/<seq>-0000.rec, key id recovery, body {folder, epoch, K9ₑ, K11} under the escrow key derive(K2, "folder-escrow", vault, K3₀), signed by the writer (it counts when the writer is an owner of the folder). Binding K3₀ keeps "the recovery words alone give nothing" true even for someone who can list the storage: escrow names show folder ids, and K2 alone would otherwise open them. Every full device holds K3₀ (a newer vault key opens the older ones through the epoch records, walk_vault_chain). The recovery kit prints two word sets (escrow::kit_text): the vault words (the newest vault key K3ₑ, with a key check: device names, folder names and the storage ledger, no content) and the recovery words (K1, with a key check: with the vault words, every folder's content; alone they open nothing); varsto recovery kit --recovery-words prints both, --new-recovery-key makes a new K1, which gives nothing until folders are escrowed under it. Vault words plus recovery words rebuild every folder (Membership::recover_all_folders); the vault words alone give the registry and the pack-level ledger, no content; the recovery words alone give nothing. A vault epoch (removing a device) makes the kit's vault words stale, as today (join refuses them and the user prints a new kit); K1 does not change, so the escrows stay valid. Tests: vault_words_and_recovery_words_restore_every_folder, recovery_words_alone_give_nothing, a_folder_without_escrow_is_reported.

The user's decisions on writing the escrow (design section 6; the commands that make them are work package 12 unless named): varsto folder add asks for the recovery words and writes the folder's escrow at once; varsto unlock --with-recovery-key keeps a copy of the recovery words for the session, so that adding a folder and rotating a folder epoch need no prompt; until an epoch has an escrow, varsto status warns warning: folder <name> has no recovery copy: run varsto recovery escrow <name> (the design writes <folder> for the second name; the code prints the name twice) for every folder epoch this device holds without one (Membership::missing_escrows, also recovery_warnings in /api/status). As built: what exists is varsto recovery escrow [<folder>] [--with-recovery-key] [--recovery-file F] (section 76), which writes the copies missing_escrows lists with the recovery words from a file, VARSTO_RECOVERY_WORDS, a pipe or a hidden prompt, never the command line; Membership::create_folder and start_folder_epoch escrow at once when K1 is given. folder add and unlock --with-recovery-key do not yet ask or keep anything, and join --recovery-words is a stub that names what work package 12 connects.

Offline (local-first writes, the outbox, keys first). A device keeps a copy of the membership records: state/records3/ (the mirror: every record it read, and every record it wrote) is read together with the storages, so a record written here counts here at once. Writing (store::Writer): a record named by its device (every kind except vault and folder epochs; only that device writes the stream) is kept in the mirror first, which decides its seq (the next after the highest in the mirror, the outbox and every storage that answers); it is also put in the outbox state/outbox3/ and then put-if-absent on every storage that answers. The first storage that answers decides as before: when it already holds another record under the name, the local copy is taken back and the next seq is tried (a given seq fails). A storage that does not answer never fails the write; once every storage holds the record it leaves the outbox. A numbered record (vault/epochs/<e>, vault/folder-epochs/<folder>/<e>) is decided by the first storage that answers (no longer always the first storage of the list; with storages in a different order, or one storage away, two devices can still write one number on different storages, which is the existing "two epochs under one number" case of section 58), then kept in the mirror and in the outbox for the storages that did not answer; with no storage answering it is not written and the action fails, saying so. The outbox is sent by flush_outbox (put-if-absent per part; a storage that fails is skipped for the rest of that flush; a part a storage holds with other bytes is a conflict: logged, counted, and the record leaves the outbox) at the start of every membership refresh, so every sync and the service's retries send it; varsto status prints N changes waiting to upload and /api/status carries records_waiting and records_waiting_text. Stamps keep their rule: Lamport time from the engine's clock and the records read, and the device id; an entry written offline loses to a newer stamp written elsewhere meanwhile, as before. Reach (members3::Reach): adding a folder (its name checked against the folders known here and against the records as read), requests, approve, deny, roles, sharing with a member, writing recovery copies and the folder grants of a pairing read the storages when they answer and else this device's copy (StoragesOrLocal; without storages nothing is tried on them and every record waits); the pairing grants (f3_pair_grants), the recovery-copy check of status and /api/status (f3_missing_escrows) and the pairing dialog's folder list read this device's copy alone, with no network (Local; every membership refresh reads all requests and the recovery copies of the folders held into the mirror); starting a vault or folder epoch, resolving one and organization changes need the storages (Storages; organization changes fail at once saying so). Removing a device or members reads the ledger first when the storages answer and otherwise takes the cut-off from the batches held here; an organization roster or log that cannot be written after a removal is logged, the removal stands. Keys first: remove_devices and start_folder_epoch keep the new K3 or K9 (PendingKey: the key, and for a vault epoch the removed devices with their cut-offs and the wipe order) in state/pending-keys3.enc (encrypted under the device's root key like vault-keys.enc) before the epoch record is written; the key is dropped again only when the number turned out to be another device's (store::Taken) or once the epoch is complete. Right after the epoch record, the key is held (a vault key goes into the engine's keys even when a later step fails) and this device's own grant is written first. When a process stops part-way, the next open that reads the storages finishes the epoch (Membership::resume_pending): its own record under the number that opens with the kept key makes the key held and gets this device's grant, the missing revocations, the denied entries and the grants that are missing; a number held only by another device's record drops the key; a number that holds nothing keeps it (the record may be on a storage that does not answer now). A folder that cannot be re-keyed during a removal is reported as not rotated instead of failing the vault epoch. Accepting a share that fails after the new home was written takes the home back out again (reset_device, keeping the share request), so it can be accepted again without varsto reset. Tests: records_are_kept_here_first_and_wait_for_a_storage_that_is_down, without_any_storage_records_wait_and_a_flush_sends_them_once, a_numbered_record_is_decided_by_the_first_storage_that_answers, a_removal_that_stops_after_its_epoch_record_is_finished_with_the_key_kept_first, a_folder_epoch_that_stops_after_its_record_is_finished_from_the_kept_key, membership_changes_wait_on_the_device_while_the_bucket_is_away (tests/offline_membership.rs, against rclone serve s3).

77.7 Manifests, trash, history and snapshots as base + delta

All four are SignedRecords whose body is a base (base == seq, the whole record) or a delta against the base before it, in a stream per (folder or backup, device) that is written to every hot metadata storage and announced in the writer's batch. A reader reconstructs a writer's view as the newest announced base and the deltas after it in order, prev checked (WriterView, DeviceTrash). A pull lists only streams whose announced newest seq is past the one applied (section 25 with "base" in place of "manifest"); a stream announced with a newer base is read again from that base. A writer that cannot publish a seq (taken, or a half-written earlier attempt) moves to the next seq and writes a base there, so a reader never needs an unannounced prev. A delta that does not follow, names another base or another predecessor, or a record that differs from its announcement, forks the writer's stream: its view stays as last accepted until the fork is cleared.

Manifests (manifests/<folder>/<device>/, manifest3::ManifestBody):

ManifestBody { folder, device, seq, lamport, created_utc, base, prev,
               devices: Vec<[16]>,          // sorted, unique: interned ids of version vectors and modified_by
               files: Vec<WireEntry>,       // base: the device's whole view; delta: entries changed since seq-1
               removed: Vec<path bytes> }   // delta only: paths that left the view (normally none: deletions are entries with deleted = true)
WireEntry { path: bytes, version: Vec<(device index, u64)>, deleted, size, mtime, content_hash: Option<[32]>,
            chunks: Vec<Chunk3 { chunk: [32], object: [32], size: u64, epoch: u32 }>,
            modified_by: index, modified_clock, meta: Option<WireMeta>, chunking: u8, held: bool }

FileEntry keeps the format-2 fields of FileState (path, version vector, deleted, size, mtime, content hash, chunks, modified_by and clock, metadata of section 49, chunking) and gains held: this writer holds every block of this version (the file on disk, or every block in its block cache). Paths travel as bytes and must be UTF-8 and pass the synced-path checks (names::check_synced_path). Limits: 4 096 bytes per path, 4 194 304 entries plus removed paths per record whatever its number of parts, 2^20 chunks per entry, 65 536 devices in the table and in one version vector, a chunk of 1 byte to 16 MiB, the chunk sizes adding up to the file size, unique paths in a record, a base without removed. Base rule (manifest3::BaseRule): the record n places after a base is a base when n ≥ 64 and the stored bytes of the deltas since the base are at least 1/16 of the base's, or when n ≥ 1024. So a base is followed by at most 63 deltas under the size condition and at most 1023 otherwise (the design's test "base + 63 deltas, then a base"); bytes are the padded sizes of record_published. Reason for both conditions: at 1 M files a base is about 350 MB (paths compress, the 4.3 hashes per file do not); a count rule alone would rewrite it every 64 publishes, several GB a day per device on a busy folder, while small folders still get short chains. Worst case (design): small publishes never meet the size condition, so a base is rewritten once per 1024 publishes and a joining reader reads the base plus at most 1024 deltas under 22 MB; a mass metadata change meets the size condition at once. The merge rules of section 7 are unchanged (manifest3::merge): applying only the changed entries of a delta gives the same result as merging the full views (property tests). Pruning: a writer deletes the records below its newest base once every reader of the folder (every participant holding K10, members through their folder-scoped batches) has acknowledged the batch that announced the base; cold storages are not pruned and neither is a storage that does not hold the base (manifest3::prune_stream).

held replaces chunk_on_device (77.4): HeldIndex answers "which devices hold object O" from every writer's newest view, for transferrer targeting and emptying (77.9), the safety indicator, where (bytes and blocks per device) and the forwarding report. The references garbage collection starts from are the objects of the current (not deleted) files of every writer's newest view (77.3).

Trash and history (trash/<folder>/<device>/, trash3::TrashBody): {folder, device, seq, lamport, created_utc, base, prev, entries, removals, versions, forget} with Entry { id, path, size, mtime, content_hash, chunks, deleted_utc, deleted_by, clock, author }, Removal { id, utc, restored, deleted_utc, lamport }. entries are the deletions this device found, removals the entries (of any device) it restored or purged, versions the versions it replaced (the version history of section 50), forget the ids it no longer lists (a delta only; applied before the lists of the same record, and it removes the id from entries, removals and versions alike). The id of an entry or version is the first 16 bytes of BLAKE3 over a fixed label, the folder, the path, the deleting or replacing device and the Lamport clock, so a reader recomputes it, and an entry must be the deletion of its writer. A writer keeps an entry, a removal and a version listed for 7 days past its expiry so every device sees it go (KEEP_LISTED_SECS), then forgets it. Limits: 4 194 304 items per record, unique ids per list, a removal not from the future, the entry checks of section 43. The union-and-removal semantics of sections 43 and 50 are unchanged; of several removals of one entry the one with the largest (Lamport time, purge before restore, device) decides, and a removal carries no by (the record's device is the remover). Removals by members of a shared folder do not count on the owner's devices, and records of revoked devices are not used (trash3::Trust). <utc>-named records disappear. As built: the trash record uses the manifests' base rule (64 deltas and 1/16 of the base, forced at 1024), where the design's text for trash said "every 64 deltas or at 1/4"; pruning is the manifests'. The change history of section 57 is not a record: it is derived from manifests and kept in local files.

Settings (kind 18, vault/settings/<device>/, not announced): {device, seq, lamport, updated_utc, trash_days, history_days, trash_storage, storage_id, folder_trash_days, folder_history_days}; trash days 1 to 3650 (default 30), history days 0 to 3650 (default 90, 0 keeps no new versions), per-folder overrides sorted by id. The newest record of any accepted device wins, by (updated_utc, Lamport time, device). Members cannot read the registry key and keep the defaults.

Snapshots (snapshots/<backup>/<device>/, snapshot3::SnapshotBody): {backup, device, seq, lamport, taken_utc, expires_utc, base, devices, files, removed}, never changed once written. A snapshot is either a base (a full listing of live files) or a differential against a base (base = that base's seq): every entry that differs from the base and every path removed since. Differential, not incremental, so expiring any snapshot never breaks another: a base is kept (body retained, hidden from listings) while any unexpired snapshot names it, and goes with the last one. A new base is taken when 32 snapshots (the base included) name the current base, or when the differential's packed size (zstd of postcard, before padding) exceeds 1/4 of the base's packed size (SnapRule). Entries are the manifests' wire entries with held always false (a backup is held by no device) and no deleted entry; a snapshot has no prev (a reader checks that the base a differential names is a base the same device announced), and expires when the ledger says snapshot_expired or expires_utc of its signed body has passed (the owner owes the mark); the newest live snapshot (by taken_utc, seq, device) of a backup with no backup_stopped does not expire by its time. snapshot_taken carries times and sizes; record_published carries the hash a restore checks. Snapshot records are pruned only by expiry. A restore reads one snapshot and its base only.

77.8 Peers and transport

Sections 75 and 76 are the as-built text; the rules of the design's section 8 in short, with the differences:

  • Peer records (peer, vault/peers/<device>/, newest seq wins): the device's name, port, addresses (LAN, public, UDP public and local, mapped TCP and UDP, at most 32 each), cert_sha256 (the TLS pin of both transports), NAT type, relays, reachable, heads (the newest batch it holds of every full device, at most 256) and pushed (its own newest batch confirmed on each metadata storage, by storage identity from vault/storage-id.json, at most 64). A writer keeps two records. The servers of both transports admit only certificates named by an accepted peer record of a trusted full device, never their own, and never one that two devices claim.
  • No plaintext transport. TCP connections run TLS 1.3 with the same pinned self-signed certificates and client authentication as QUIC (ALPN varsto-p2p/3); a client that does not open with a TLS handshake gets an alert and no byte of the protocol. The handshake deadline is 5 s even while bytes arrive, and one address may hold at most 64 connections that have not finished it. Inside the session the requests are those of section 15. QUIC stays the path through NATs.
  • Request tokens are keyed with the TLS exporter of the connection (label EXPORTER-varsto-p2p-token, 32 bytes): X-Varsto-Auth: <device>:<responder>:<unix>:<nonce 32 hex>:<mac 64 hex>, mac = keyed_hash(exporter, aad("p2p-token", [device, responder, unix, nonce, path])). The responder requires that device is the device of the certificate of that very connection, responder is itself, |unix - now| ≤ 300 s and the nonce is unseen in that window (at most 65 536 kept). No vault secret is involved: a token cannot be made by anyone who merely holds K3, and cannot be replayed on another connection. As built: the design's nonce is 16 hex digits, the code's 32; the token is a MAC, not a per-request K6 signature (the handshake already proves the client against a pin from a signed record, and a download asks for thousands of blocks). A relay checks the asker's token for the full /p2p/via/<device>/<path> path and asks the registrant with a token of its own plus X-Varsto-For, which the registrant accepts only on its registration connection.
  • Signed beacons: VARSTO3 <tag> <device hex> <port> <seq> <sig hex>, sig the Ed25519 half of K6 (64 bytes, for size) over the tag, device, port and seq; a listener keeps the highest seq it accepted per device. A beacon only suggests an address: the pinned handshake checks the device.
  • Pairing hello carries the joiner's K6 and K8 public keys and name, bound into both key confirmations; the offering device shows the name and the six-word fingerprint (77.6), asks, and only then sends the bundle, with the vault key sealed to the joiner's K8. Discovery answers to rendezvous(code), 10 bits of derive("pair-rendezvous", digits) shown as a decimal number, instead of the code's digits (the design said a keyed hash as the record name).
  • Head exchange (design: a HEADS\n message; as built: /p2p/heads/<list> and /p2p/changed/<list> with the list as base64url postcard, ≤ 256 entries, ≤ 24 KiB of path): on every new connection between full devices and at most every few minutes on a kept one the responder answers with its own list and, for each device where it holds a newer batch, that batch's envelope without body (at most 64 envelopes and 512 KiB). An envelope verifies against the writer's K6 (the signature covers body_hash) and proves that the signer wrote the batch. The receiver records proofs in ledger/watch.json and fetches the batches it lacks from the proving peer (GET /p2p/ledger/<device>/<seq>, at most 64 per device and round), checked as if from a storage; it does not push them to storages (only their writers push).
  • Rollback warning. Storage S is expected to hold batch n of device D when D's accepted peer record lists S's identity in pushed with seq ≥ n, or this device pushed it there itself. After a pull, when S shows less than n and a proof of n older than the pull exists, the pair is suspect; after two such pulls in a row the warning is storage <S> may be withholding or rolled back: it shows ledger batches of <D> up to <shown>, but <source> proved <n>. Only full devices' heads within their cut-off count; a storage D never confirmed is not judged; an unreachable storage is not judged; the pair clears when S shows the batch or D's record stops listing S. Showing it in varsto status, varsto ledger status, the Help page and notifications, in English, Finnish and Swedish, is the engine's part (work package 12).
  • As built (the switch, part B). The format-2 transport is gone: no plain HTTP over TCP, no p2p-auth keyed tokens, no unsigned vault/peers/<device>.enc records, no VARSTO1 beacons, no format-2 pairing exchange and no signed head statements of section 74 (ledger/heads-seen.json). The TCP listener (p2p::Server::bind) takes the TLS side of the responder, the QUIC node starts only as quic::Node::start_v3, the peer table is built only from the directory (Peers::build_v3). The engine (engine/p2p3.rs) reads the directory over every hot metadata storage, newest seq of each trusted full device (an organization's platform policy applies as for every peer), and builds this device's record (peer_body: interface addresses ranked as section 68 ranks them, the configured public addresses, the certificate, heads and pushed); the service adds STUN, router and relay facts, publishes it when it changed or once an hour, and reads the directory again before each sync and after it when the records changed (the responder's directory and the QUIC node's admitted certificates follow, set_known); a handshake refused for a certificate the directory does not name makes the service read the records again, at most every 5 s, and the asking side rests only 3 s after such a refusal (instead of a minute), so a device that just published its record is admitted within seconds. Rests. A device that no route reached rests: when it answered within the last minute (a restart, a lost connection or handshake), 1 s, doubling per failure in a row up to a minute; when it answered earlier in this table's life, a minute; when it never answered, a minute doubling per failure in a row up to 15 minutes, so a device whose record stays in the vault long after it is gone costs an attempt now and then. A TCP address that answered within the minute before it failed rests 1 s instead of a minute. A failure while another request reached the device meanwhile does not count. While it rests a device is left out of the order; when no other peer had an object, Peers::get tries a device resting after a blip once more, one request at a time (the others wait for its outcome), at most every second doubling per failure, and up to its second failure in a row a request waits for that try rather than giving the block up. (One failed request used to rest the address and the device a minute, and every block asked for in that minute was reported unavailable without asking: a 10 000-file pull stopped part-way, 2026-11.) A rest ends at once on a newer record of the device (it started again and published), a signed LAN beacon from it (at most every 30 s), and an explicit sync (POST /api/sync, Engine::retry_peers_now: devices that answered before, or failed at most twice in a row). ask_each (head exchange, changed) asks up to 8 peers at once, live ones first: devices that are gone cost one timeout together, not one each in turn. A command-line run reaches its peers over TLS on TCP only (Engine::p2p_peers_tcp). The LAN beacon's tag is keyed_hash(derive3(K3₀, "p2p-tag"), vault id)[..12]. The snapshot a device serves carries its head list (its own head: the newest batch a storage confirmed) and its ledger directory, from which /p2p/heads, /p2p/changed and /p2p/ledger/ are answered; a request of a removed device is refused before any of them. Proofs are kept in ledger/proofs.json (the design's ledger/watch.json holds the pull's own freshness state). The engine exposes the catch-up (Engine::p2p_catch_up: proofs from every peer and from the writers' own peer records, batches fetched from the peer that proved them, checked by the acceptance rule and taken into the ledger without being pushed) and the judge (Engine::p2p_judge_rollback, with the pull's listing or its own per-device listing of each hot metadata storage, Engine::storage_views); the pull calls them. Pairing is only the exchange of this section: the joining device makes its K6 and K8 first (pair::v3::PairingKeys), shows their six words (varsto pair join, the pairing page), and joins with them (Engine::join_paired), so the grants the offering device wrote (varsto pair offer --folders A,B [--role] [--yes] asks "Do the six words match?" first; the page through /api/pair/answer) are sealed to its K8; POST /api/pair/start always opens such an offer.
  • Offline (peers without a storage). The directory is kept on the device, in peer-records.json under the device home: every accepted peer record as it was read (each part as its storage name and hex bytes). It is no source of trust: on load every record goes through the acceptance rule again against the membership held here (signer trusted now, registry key held, body checked), and records of devices removed or no longer trusted drop out. Opening the vault (Engine::open) and starting peer-to-peer (Engine::p2p_responder, the listener, the QUIC node and the beacons) use only this saved directory and ask no storage; a command-line run reads the storages' records at its first sync, the service before each sync. A read starts from the saved directory and merges every storage that answers, newest seq per device; a storage that fails or lists nothing changes no entry, and the file is written again only when a storage answered and something changed (Engine::peer_directory_read tells how many answered). While none answers, a refused handshake makes the service list the records again after 5 s, doubling up to 5 minutes. Publishing the record tries every storage; one that fails does not stop the others, and the publish counts as done only when all took it: otherwise it is tried again after 30 s, doubling up to 10 minutes. The storage identities in pushed are cached per storage location in memory (a failure for 5 minutes; a directory on this device is read every time). Several routes to a peer are raced with /p2p/info (each starting 300 ms after the one before it, in the order above) and the request goes over the first that answered; private IPv4 addresses on none of this device's subnets are not tried, unless a tunnel interface (VPN) or an unknown interface list means another private network may be routed. QUIC and TLS answers have a 30 s idle timeout per read instead of one 30 s deadline for the whole answer (and, on QUIC, a floor of 16 KiB/s on average once the length is known); a relay passes the registrant's answer on as it arrives. The handshake waits three times the last handshake time with that host, at least 1.5 s (3 s when punching), at most 6 s, and once more as long beyond the LAN. STUN server names are looked up on a helper thread for at most 3 s, answers are cached for 10 minutes (a stale one is used when a lookup fails), and nothing is looked up without a route out. Unlocking a service that started locked starts peer-to-peer at once. varsto p2p status without the service reads the records once for the list and the probe and asks at most two STUN servers while it probes.
  • Rendezvous (section 83). The rendezvous service is one more source of the directory and one more place a device publishes to: its peer record goes, sealed once more under derive3(K3₀, "rendezvous-blob"), into its slot under the vault tag after every publish (and every 6 h), and the vault tag's slots are read at service start and every 3 minutes. Their records go through the same acceptance rule and merge into the saved directory like a storage that answered (newest seq per device; the rendezvous copy carries the seq of the last storage publish, so neither source shadows the other). A device whose storages are all unreachable thus still learns where its peers are; with the rendezvous unreachable or off nothing here changes. Route order: LAN/direct TCP, QUIC with punches, a server-coordinated punch, a peer relay, the rendezvous relay.

77.9 Replicas, pools, transferrers, moves, drains and quotas on packs

storages3 decides from three inputs only: the ledger view (packs and their holders), the folder's map table (block to place) and the storages themselves. No function opens a vault, a folder key or an engine.

  • Copies (copies): a copy of a block is a storage holding a live place of it: the pack held there (claimed, not dropped, the storage not retired) and the place without a dead or lost mark; the writer's own dead flag counts like a dead mark. Policies (section 14), placement (section 23), the folder safety indicator, where and the forwarding report count this way, and need the map only to go from a file to its blocks.
  • Replicas (replica): a replica round copies packs whole, checks each against its id, claims it with pack_stored (zero folder, map seq 0) and records that it read it back with pack_verified; everything else on the source (maps, manifests, trash and other records, ledger batches) is copied as it is and never opened; a replica writes no map, no mark and no record of any kind.
  • Pools (pools): a pool keeps packs/<xx>/<pack id> files on removable disks; which packs it should keep is known from the ledger (each pack_stored names the pack and its class). A disk insert tidies away a pack the ledger dropped from the pool, after a grace period, when the pull read every hot metadata storage and the disk's own index does not list it; a pack the ledger has not seen is kept. It also removes packs of the wrong size and returns pack_dropped for packs the pool holds on no other disk; a disk check hashes every pack against its id (pack_verified for good packs, pack_dropped for bad or gone ones the pool holds nowhere else; bad packs are removed from the disk and the repair reads them from another storage); "next disk to dock" counts pack copies; a disk group rule counts the places that hold the pack.
  • Moves and staged moves (moves): a pack whose live members are all in scope is copied whole (no key, bytes checked against the pack id), claimed with a zero folder, read back, and only then dropped from the source; a pack that holds live members outside the scope is not copied: the members in scope go into new packs on the destination, the members outside into a new pack on the source (the remainder), and then the old pack goes. New places are returned as written packs for the mover's map record. A move never deletes a source pack before the map record is published and the batch with its drop is pushed (MoveRun::delete_dropped); a move that stops halfway is continued by planning it again. A pool destination whose disk has no room for a whole pack gets the members in halves, each in the smallest class it fits.
  • Drains and quotas (drain): draining or removing a storage works through the packs the ledger shows held on it; each block must keep, without this storage, the copies the folder's rules held before (capped at what was there), and is never left without a copy; missing copies are whole copies of the pack onto the folder's other storages, and then the pack is dropped; a pack whose needs cannot be met elsewhere is a refusal that says what is missing. A storage's use against its quota is the packs claimed on it and not dropped, counted by class, padding included (storage_usage: bytes and packs).
  • Transferrers (carriers): a carrier takes what no other device has yet (with destinations: what one of them still lacks) and is emptied when every destination holds it; "holds" is the held flag of the manifests (ObjectHolders, HeldIndex). A transferrer holds whole packs, so a pack is emptied from it when every live member is delivered.
  • A whole pack copied by anyone other than its writer is claimed with a zero folder and map seq 0 (as a replica's claims), so the claim that decides a pack's folder, writer and map record in the view stays the writer's.

77.10 fsck, ledger rebuild and scrub

fsck (fsck3::fsck, fix) is a function over what an engine holds: the ledger view, the opened storages, per folder the map table and the manifests, and optionally a probe that reads the announced records. It reports (Fsck3Report, JSON for varsto fsck --json): every pack the view claims, per claimed storage, present at exactly its class length (a ranged read of two bytes at class - 1, no download; missing_copies, wrong_length), with --verify its hash against the id through the per-pack verification of 77.3 (corrupt_copies, verify_errors); a class a storage may not hold (the 256 MiB class on a hot storage; reported with the wrong lengths); packs on a storage that nobody claims (orphans, with an age and gc_due after 7 days when the caller can supply modification times; without them an orphan is never due); per map the places that pass the end of their pack (outside_pack), lie in a pack the ledger never claimed or gives to another folder (unknown_pack), name another class than the ledger does (class_mismatch) or overlap (overlapping), and packs the view gives to the folder that its applied maps do not list (unmapped_packs); per folder the objects a current manifest references (blocks: referenced, live, only marked, missing) and the files damaged because a block has no live place on a storage that really holds the pack (damaged_files); announced map and manifest records that are gone from the metadata storages, incomplete, waiting or refused (records); forked devices and streams and the counters records_refused, events_refused, events_unknown, marks_refused; storages that could not be read or whose claims were not checked. As built: duplicate claims cannot exist in the pack-level view (claims are a union of devices); the equivalent corruption is two places that overlap or name different objects, reported as overlapping. fix makes the one repair the design allows without a folder key: a pack missing on one storage is copied whole from another storage that holds it intact (length and hash checked), the claim being in the ledger already, so nothing is announced; corrupt and short packs are handed to the repair callback (77.3). Section 38 for format 3 is rebuild3.

Ledger rebuild (rebuild3::rebuild, varsto ledger rebuild --json) is for a device whose local ledger/ directory is gone and which signed batches the storages may or may not hold; signing a number the storages hold already would fork the identity, so it signs nothing until the end: (1) pull every device's newest checkpoint and the batches after it from every metadata storage (this device's own through ingest_own_restored, which moves its head past a gap no storage can fill); a storage that holds a second history of this identity under one number marks it forked, and the rebuild refuses (two histories of this device exist (...); pair this computer again as a new device (varsto reset --yes, then varsto join)); (2) when another device said (signed seen) that it holds batches of this device that no storage returned, the next number is not free, and the rebuild asks the peers (fill_own, peer-to-peer) or refuses (other devices hold batches of this device up to <n>, the storages only up to <m>; signing now would reuse a number...); (3) reconstruct the events that were in lost batches and sign them in new batches: pack_stored for packs this device's own map records name and that are on a storage at their class length, pack_stored for packs no map of this device names and nobody claims after their hash was verified (no verification callback, no claim), record_published for its map and manifest records no accepted batch announces, folder_added for folders the engine holds that the ledger does not know, device_enrolled when nothing of this device was found; claims the ledger has already are not repeated, so a second run changes nothing; (4) push the new batches to the hot metadata storages. The batch is marked as a rebuild only in the local rebuild3.json: the ten events of 77.4 are binding, and a new wire event would be one more code older readers count as unknown. Its own records of other kinds (trash, snapshots) are not announced again by this build.

Scrub (scrub3, section 33 adapted): the unit is the pack. A target (a storage or a pool disk) is swept pack by pack: the items are the packs the view holds on a storage (or the pack files on a disk), their size is the class, and each is read whole (one GET) and hashed against its id. A pack needs no folder key to be checked, so K3-only devices and replicas scrub too. Schedule, budgets, cursor (now the last pack id of the pass) and report are the format-2 ones, so the state file and the status text need no change; reads go through parverify::run_ordered in the lanes of section 39, results consumed in key order, so the cursor never passes a pack that was not checked. A mismatch (missing, wrong length, hash differs) is handed to the repair queue of 77.3, not repaired here; scrub checks are not recorded in the ledger (a writer re-reading its own copy is not an independent verification). Budgets count whole classes: a 64 MiB pack costs 64 MiB of the budget however full it is.

77.11 Authorization matrix

What a writer may publish is checked twice: by the acceptance rule for records (77.5, step 3: record::section9_allows over the writer's class in the record's scope, with the role at the epoch the key id names) and by the scope of its batch for ledger events (77.4, EventScope). A record or event outside the writer's row is left out and counted.

Writer Record kinds it may write Ledger events that count Scope
full device, folder owner every kind every event (scope Full) its folders and the vault
full device, folder editor manifest, block-map, trash, access, notes, thumbs, batch every event that folder
full device, folder viewer access, batch every event that folder
full device without a grant for the folder (K3 only) request, device, peer, policy, placement, settings, storage-names, batch every event vault
full device, vault-wide records snapshot, peer, epoch, grant, revocation, policy, checkpoint, batch, device, settings, storage-names every event vault
member device (another person's), editor manifest, block-map, trash of that folder; folder-scoped batch device_enrolled; pack_stored, pack_verified, pack_dropped (its packs), record_published of those three kinds, for that folder that folder
member device, viewer folder-scoped batch device_enrolled; pack_verified of that folder's packs that folder
replica replica batch device_enrolled; pack_stored and pack_verified, zero folder (and map seq 0) none
storage, peer, anyone else nothing nothing: every object must verify none

A member never writes registry kinds, epochs, revocations, storage_retired, snapshots, policy, placement or settings. Only owners write folder records, folder epochs and grants of their folders; escrow records count from owners. Only full devices of the vault write vault epochs, revocations and checkpoints. Folder, folder-epoch and escrow records pass step 3 for any registered device and are judged on the body (the writer was an owner at the entry's stamp or at that epoch), and a removed device's folder-scoped records of those kinds still verify for what they said before the cut-off. As built: the scope of a batch comes from its key id, so a full device's batch (ledger@<e>) counts in full whatever its role in a folder; the design narrows the events of a viewer and of a K3-only device (for example to pack_stored of whole packs, pack_verified, pack_dropped, storage_retired and device_enrolled for a K3-only device, and pack_verified for a viewer), and the ledger does not: the roles restrict what records a full device may write (the column before), and the events of a device that holds the vault's ledger key are as trusted as the device. A K3-only device may write placement records here, where the design lists "placement (of folders it holds)". Work package 12 narrows the ledger as the design does for folder events: a full device's claims naming a folder and its announcements of the folder's manifests, maps and trash count only while it is an owner or editor there (77.4); its vault-level storage events (copies of whole packs with the zero folder, verifications, drops, retirements) count as for a K3-only device. membership3::Trust selects every row: a device of the vault's registry is a full device (owner, editor, viewer or without a grant in the folder), a device known only from a folder record's member entry is a member editor or viewer of that folder and untrusted everywhere else (77.6), and replicas have their replica key id.

77.12 What each party learns

  • The storage: the vault id; device ids and how often each writes (record names carry device and sequence, never time); folder ids and the number of writer streams per folder; pack size classes only (256 KiB, 1, 4, 16, 64, and on cold storages 256 MiB: from a 256 KiB pack only that its members total at most 256 KiB), how many packs and when they appear and go; record sizes in 64 KiB steps below 4 MiB and 1 MiB steps above, so manifests, maps and trash records show file and block counts and the size of changes only at that granularity; that a folder has grants to KEM keys of other devices. Not: file names, file sizes, file counts per pack, where a block starts or ends, chunk ids, object names of blocks (only pack ids), whether a known file is present. The same 10 MiB file pushed to two folders gives no pack whose size or id reveals it.
  • A holder of K3 only: everything the storage learns, plus device names, folder names, settings and participants, which storage holds which pack, bytes per folder, record announcements (kind, seq, size) and peer addresses. Never chunk ids, object names, block places or contents.
  • A member of a shared folder: everything of that folder (K10): file names, contents, maps, the folder's places in packs; nothing of other folders (their packs are listed on the storage, nothing more).
  • A replica: pack ids, sizes, its own claims; it copies packs whole and needs no folder key.
  • A peer (a full device of the vault): what any full device knows; an eavesdropper learns nothing over the wire (TLS 1.3).

77.13 Limits

  • The push path builds one pack per target set (77.2); imports, data moves, drains, repairs and forwarding still build one pack per storage, so their packs differ between the storages they write.
  • Members who are other people's devices are known from folder records (77.6); the engine's request-code exchange and a member's own engine (folder-scoped batches from another vault) come with the engine's switch to format 3; members' folder-scoped acknowledgements exist in the view.
  • Collection and map or manifest pruning wait for every writer's or reader's acknowledgement: a device that never syncs again blocks them in its folders until it is removed, as a silent full device blocks pruning today. GcPlan::waiting and map_readers_waiting name the device; varsto status text for it is the engine's (work package 12).
  • Folder records resolve concurrent owners by Lamport stamps; a demoted owner can backdate entries below its demotion's stamp (77.6).
  • Orphan age counts from when the collector first saw a pack, not from the storage's write time (77.3).
  • Repairs, like marks, need the writer role in the folder; a K3-only device can verify and copy whole packs but not rewrite.
  • A lost mark is sticky; a block with no good copy anywhere stays damaged until a device that holds the file writes it again.
  • Kinds 11, 12, 19, 20, 21 and 22 have body types in records3 (77.5); format 2's records for these remain what the engine uses until it switches to format 3.
  • Strongroom keys (K13) and the re-encryption job varsto folder reencrypt have no format-3 code in this series.
  • The design's estimates (77.4) are not measured in this text; the benchmarks exist and are ignored by default.
  • The test list of the design asks for fuzz targets; the series has parser mutation and random-input tests instead (77.14), and no cargo-fuzz targets.
  • The rollback warning's display and the format-mismatch refusal are the engine's (work package 12).

77.14 Tests

Run by CI (cargo test --workspace); names are the functions that exist. "Design test n" is the numbered list of section 12 of the design.

  1. Records (record::tests): key_ids_parse_and_format_one_spelling, every_kind_code_has_a_name_and_round_trips, a_record_of_every_kind_round_trips, a_grant_opens_only_for_its_recipient, bodies_land_on_size_classes_with_random_tails, large_records_split_into_parts_and_join_again, refusals (relabelled key id, moved record, swapped body, wrong signer, junk), announcements_decide_waiting_accepted_and_forked, record_store_reads_streams_and_drops_past_max_ahead, writers_refuse_what_readers_would_refuse, only_full_devices_write_snapshots, no_single_flipped_byte_verifies, random_bytes_never_panic_the_parser, byte_field_encoding_is_postcard_of_a_plain_vec; body parsers of the other modules are mutated or fed random bytes in blockmap::tests::body_parser_survives_random_input, manifest3::tests::the_body_parser_survives_mutations, trash3::tests::the_body_parsers_survive_mutations and applying_random_records_never_panics, snapshot3::tests::the_body_parser_survives_mutation, membership3::tests::body_parsers_survive_random_bytes.
  2. Writer classes: ledger3::tests::scope_refusals_per_role, member_claim_yields_to_a_full_devices_folder; gc3::tests::a_hostile_mark_from_a_viewer_k3_only_device_or_replica_deletes_nothing; storages3::tests::a_replica_never_writes_maps_marks_or_claims_a_folder; membership3::tests::grants_and_folder_records_from_non_owners_are_refused; trash3::tests::removals_of_members_do_not_count_and_revoked_devices_are_ignored. There is no single integration test that runs every writer class against every kind.
  3. Packs: packs::tests::size_classes_hold_the_smallest_fit, a_pack_is_padded_to_its_class_with_random_bytes, a_push_over_the_top_class_closes_the_pack_and_starts_another, padded_packs_are_read_back_member_by_member, a_fully_deleted_padded_pack_goes, a_pack_of_an_older_build_is_read_verified_and_collected; crates/varsto-core/tests/packs.rs (pack_sizes_are_size_classes_not_the_size_of_the_push, the_same_file_in_two_folders_gives_other_packs_and_no_block_objects, a_mostly_dead_pack_is_rewritten_and_every_device_still_reads); crates/varsto-core/tests/import_dir.rs (many_small_files_share_packs_of_size_classes).
  4. Known file: the_same_file_in_two_folders_gives_other_packs_and_no_block_objects (above).
  5. Ledger: ledger3::tests::view_is_pack_level, cached_view_equals_full_replay, view_application_is_order_independent, every_event_code_round_trips, unknown_code_is_skipped_and_counted, large_actions_seal_further_batches, drop_cancels_earlier_claims_and_not_later_ones, pack_metadata_follows_the_newest_claim, streams_keep_the_newest_base_and_its_deltas, copies_of_a_block_come_from_map_places, append_chain_and_ingest, fork_is_detected, gaps_wait_and_follow, checkpoint_cannot_speak_for_other_devices, checkpoint_far_ahead_is_refused, checkpoint_stands_in_for_its_batches, settle_needs_every_writer_in_any_order, rescan_rebuilds_heads; the ignored benchmark crates/varsto-core/tests/ledger3_scale.rs.
  6. Map (blockmap::tests): a_record_of_a_million_entries_round_trips, limits_are_checked_on_acceptance, too_many_entries_or_packs_are_refused, a_base_follows_1024_deltas_or_a_quarter_of_the_base, the_writer_resumes_from_the_view_and_skips_orphans, three_writers_in_any_arrival_order_give_the_same_rows, incremental_updates_and_a_rebuild_agree, a_crash_while_writing_the_table_leaves_a_usable_one, a_mark_outside_the_folders_packs_is_refused_and_counted, dedup_writes_a_block_only_where_it_is_missing, a_dead_marked_place_is_not_reused, a_place_is_collectable_only_when_settled_unreferenced_and_not_revived, a_block_is_found_and_read_through_the_map.
  7. The race (gc3::tests): worked_example_a_pushes_deletes_b_marks_a_acks_b_collects, worked_example_d_re_adds_the_photo_before_pulling_the_mark, no_referenced_block_is_ever_collected_in_random_schedules (random schedules of pulls, pushes and upkeeps), a_member_that_never_acknowledges_blocks_collection_and_is_named, standing_follows_roles, wp7_references_count_like_the_manifests_and_wait_for_unread_writers.
  8. Collection (gc3::tests): a_hot_pack_more_than_half_dead_is_rewritten_and_a_later_reader_finds_the_rest, a_cold_pack_is_never_rewritten, compaction_merges_small_hot_packs, a_failed_batch_deletes_nothing, an_orphan_pack_goes_after_seven_days_and_a_dropped_leftover_at_once, map_pruning_waits_for_every_reader.
  9. Repair (gc3::tests): verification_finds_a_flipped_byte_and_repair_takes_the_member_from_another_storage, a_member_with_no_good_copy_is_marked_lost_and_reported, a_corrupt_member_is_taken_from_the_local_file_when_no_storage_has_it, a_k3_only_device_verifies_and_copies_packs_without_keys; fsck3::tests::a_deleted_pack_is_reported_and_copied_back_from_the_other_storage, a_flipped_byte_is_found_by_verify_only.
  10. Membership (membership3::tests): a_device_with_the_vault_words_sees_names_and_no_content, approval_on_one_owner_device_suffices, grants_and_folder_records_from_non_owners_are_refused, a_folder_epoch_removes_a_member, two_folder_epochs_under_one_number_wait, removing_a_full_device_starts_a_vault_epoch_and_folder_epochs, fingerprint_is_stable_and_changes_with_either_key, folder_record_replay_converges_in_any_order, device_id_is_the_hash_of_k6; the commands and routes of section 76: crates/varsto-cli/tests/folder_approval_cli.rs (request_approve_members_deny_and_remove, deny_hides_the_request_and_resolve_epoch_needs_a_fork, escrow_writes_the_missing_copies_and_status_stops_warning), service.rs::the_service_never_approves_or_grants, desktop.rs::folder_membership_endpoints, pairing_asks_the_person_and_grants_only_ticked_folders.
  11. Recovery (membership3::tests): vault_words_and_recovery_words_restore_every_folder, recovery_words_alone_give_nothing, a_folder_without_escrow_is_reported.
  12. Manifests (manifest3::tests): the_base_rule, a_base_follows_63_deltas, base_and_deltas_equal_full_snapshots, a_delta_with_a_wrong_prev_forks_the_stream, a_record_that_differs_from_its_announcement_forks, a_writer_that_loses_a_seq_writes_a_base_next, a_pull_lists_only_streams_announced_past_what_was_applied, merging_views_is_commutative_idempotent_and_incremental, merge_properties, held_flags_give_the_holders_of_each_object, references_are_the_current_files_of_every_writer, pruning_waits_for_every_reader, the ignored a_million_file_base; trash3::tests::base_plus_delta_equals_the_full_state_over_random_sequences, a_reader_that_joins_at_any_point_converges, entries_expire_by_the_trash_days_of_the_vault_and_the_folder, history_versions_are_thinned_and_expire_by_the_history_days, restore_against_purge_is_decided_by_lamport_time, the_record_forgets_seven_days_past_the_expiry, settings_round_trip_and_the_newest_record_wins; storages3::tests::a_transferrer_takes_what_no_other_device_has_and_empties_when_delivered, transferrers_read_the_held_flags_of_the_manifests.
  13. Snapshots (snapshot3::tests): every_snapshot_reconstructs_from_its_base, a_restore_reads_one_snapshot_and_its_base_only, a_differential_without_its_base_waits, expiring_a_base_does_not_break_a_differential_until_that_expires, expiring_in_any_order_never_breaks_the_others, a_new_base_when_32_snapshots_name_the_base_or_the_differential_is_large.
  14. Peers (p2p::v3::tests, pair::v3::tests, fingerprint::tests): a_token_for_another_responder_connection_device_or_path_or_a_replay_is_refused, a_token_of_another_tls_connection_is_refused, a_plain_tcp_client_gets_a_tls_alert_and_no_protocol_bytes, tls_admits_only_certificates_named_by_an_accepted_peer_record, the_own_certificate_is_refused_both_ways, quic_v3_serves_devices_of_the_directory_with_connection_bound_tokens, a_relay_checks_the_askers_token_and_asks_with_its_own, unsigned_forged_foreign_or_replayed_beacons_are_ignored, head_exchange_proves_a_withheld_batch_and_the_peer_hands_it_over, forged_or_foreign_proofs_and_mismatched_batches_are_refused, rollback_warning_after_two_pulls_only_for_a_storage_the_writer_confirmed, the_hello_shows_name_and_fingerprint_and_the_vault_key_opens_only_with_k8, a_declined_device_gets_nothing_and_the_offer_closes, the_words_bind_both_keys.
  15. Storages, fsck, rebuild and scrub: storages3::tests (replica_copies_packs_and_claims_them_without_keys, moving_a_folder_to_another_storage_keeps_every_block_readable_through_the_map, a_move_that_keeps_the_source_or_meets_a_bad_pack_drops_nothing, a_drain_refuses_while_a_place_is_the_only_live_one_and_copies_packs_whole, quota_usage_counts_pack_classes_held, a_staged_move_across_two_disks_counts_a_group_rule_by_places, a_pool_disk_lists_packs_from_the_ledger_and_tidies_unknown_ones); fsck3::tests (a_clean_vault_is_clean, a_pack_lost_everywhere_damages_its_files_and_cannot_be_fixed, a_pack_of_the_wrong_length_is_reported, an_orphan_pack_is_reported_and_flagged_after_seven_days, overlapping_places_are_reported, a_record_that_is_gone_from_the_storages_is_reported); rebuild3::tests (a_lost_directory_is_rebuilt_from_the_batches_on_the_storages, claims_are_rebuilt_from_the_maps_and_the_pack_listing, a_cloned_identity_with_two_histories_is_refused, a_number_other_devices_hold_is_never_signed_again); scrub3::tests (a_clean_sweep_reads_every_pack_once_and_ends_the_pass, progress_is_kept_per_pack_across_runs, a_mismatch_is_handed_to_the_repair_callback).

Design test 15 (the lab: every existing scenario on format 3, and the new scenarios format3-scale, format3-gc-race, format3-withhold-rollback, format3-join-approve, format3-recovery, format2-refused) belongs to work package 12 and does not exist yet.

77.15 Migration and the switch

None: format 3 reads nothing older. vault/meta.json and vault.json say 3, and a device directory or storage of another format is refused (77.17, "Refusals"): varsto reset --yes removes the device's vault directory, not the user's folders, and varsto init makes K3₀, K1 (shown as the two-set recovery kit), the device's K6 and K8, the device record, and an escrow for every folder added. 0.0.1-alpha.15, which stays downloadable, is the reader of format 2. Supersedes in this document, for format 3: sections 3 and 4 (keys, AAD), 5 (layout), 6 (events, batch body), 7 (manifests as full views), 15 (token and plaintext HTTP), 21 (folder keys from vault epochs), 22 (checkpoint body), 24 (share tokens, share keys, SHARE_EPOCH_BASE), 25 (manifest pruning unit), 30 and 62 (pack index, tombstones, per-block claims), 43 and 50 (<utc> trash records), 58 (limits on unsigned key ids and manifests).

77.16 Record kinds and rules of the switch

Work package 12 (the switch to format 3) adds what the format-2 engine kept in objects of its own; the binding text is the design's section 5, "Kinds and rules of the switch". In short: the device record carries the device details (membership3::DeviceDetails: system, version, model, architecture, app version, platform, times; replaces vault/devinfo/); the folder record carries removed (FolderState::removed: the oldest accepted removal by an owner, final; replaces vault/removed/); kinds 23 replica (a full device enrols a replica's K6), 24 strongroom (K13 wraps per FIDO2 credential, an optional K2 escrow, the folder a conversion came from; written by an owner of the folder: membership3::Trust checks the role), 25 to 27 org-manifest, org-roster, org-log (today's signed bodies inside a record) and 28 mailbox (section 78's board; a K3-only device may write it) are in record::Kind with their streams and key ids; their bodies are written by the parts of the switch that use them. Forward and staging leases stay plain JSON. Rules: whole-pack copies are read from any storage the view shows holding the pack (cold storages only with a confirmed cold read); storage-names records map each writer's storage names to identities; data moves and drains keep the policy veto of section 59; quotas count the size classes of the packs claimed on a storage; a place counts as a copy only when its pack is held there and it carries no dead or lost mark, and the pack layer (packs::PlaceSource) writes and checks existence only through such places.

77.17 The switch, first part (as built)

FORMAT_VERSION is 3. What the engine does, where it differs from the format-2 sections:

  • Refusals. vault.json and vault/meta.json say 3; a device directory or storage of format 2 is refused with format_mismatch (format 2 or older: "Recreate the vault"; newer: "Update Varsto"), and adding a storage whose vault/meta.json names another format stops with storage <name> holds a vault of format <n>; use another bucket or directory, or delete it first.
  • Keys. The device id is BLAKE3(K6)[..16]; K8 is made at init and join and travels in the device record, which the device publishes once a storage exists. Vault keys are kept per epoch; join with the vault words walks the chain of vault epoch records down to K3₀ and refuses an out-of-date key and a key that opens no device record. Folder keys come only from grants to this device and, after join --recovery-words (Engine::recover_folders), from escrow; the local keyring keeps a copy of them (key_hex for epoch 0, epoch_keys, k11_hex), and vault::FolderKeys derives K10, K11, K12, K14 and the chunk nonce with the format-3 derivations over binary ids. A folder without a grant is known by name only: it cannot be attached ("ask for it with varsto folder request" or with Request access on the Files page, which is the only way on a phone: the status row says has_key: false and access is none, requested or approved, and access_words are the six words the owner compares).
  • Recovery words. init makes K1 and keeps it for its session; it prints the kit with both word sets. folder add writes the folder record (this device the owner), a random K9₀ granted to this device and, when the session holds K1, the escrow; the command line takes the words from --recovery-file, VARSTO_RECOVERY_WORDS, the copy the background service holds after varsto unlock --with-recovery-key (/api/unlock with recovery_words), or a hidden prompt where Enter leaves the copy for varsto recovery escrow; varsto status warns until every folder epoch has one.
  • Membership. The engine keeps a copy of what Membership read (devices, folder records and epochs, grants to this device, member devices, revocations), read again at every ledger pull from the hot metadata storages, and judges every record with that trust (membership3::Trust, plus the view's announcements for step 5) and those keys (KeyRing). Membership records are stamped after the engine's Lamport clock, so a role given now holds for the batches that follow. The device list and the local keyring follow the records; a folder removed by an owner is forgotten here.
  • Ledger. ledger3 at ledger/: one batch per action under ledger@<newest vault epoch> (events the rest of the engine records in the format-2 form are carried where format 3 has them: enrolment, folders, retirements, snapshots; per-block events are not part of format 3 and are left out), pushed to every hot metadata storage (a storage that holds a different batch this key signed under one of this device's numbers stops the device). A pull lists each known device's batches after its head, takes its newest checkpoint first, and checks them by the acceptance rule. The view is replayed under the keys held, the revocations' cut-offs, the scopes (full devices of the registry; members of shared folders by their role, viewers with Viewer) and the folder roles of full devices (FolderRegistry as FolderRoles), and kept between calls. The upkeep after a sync acknowledges other devices' checkpoints, writes a checkpoint of this device's batches every checkpoint_every batches, and deletes covered batches once every full device acknowledged the checkpoint.
  • Push. Blocks a target storage holds no live place of go into packs per target set; then one map delta, the manifest delta (with held: the version on disk or in the block cache is the one listed), the trash delta, and one batch. A viewer publishes nothing.
  • Pull. Map and manifest records the view announces past what was applied, from every hot metadata storage; the paths each writer changed are merged by the rules of section 7. Every writer's views are kept in state/manifests3/<folder>.json, the map tables in state/maps/.
  • Reads. The map tables are the place source of the pack layer (chunks/<xx>/<object> is an in-process name only). PlaceSource::is_live keeps places with a dead or lost mark, or flagged dead by their writer, out of writes and existence checks; reads try them last. No pack index, tombstone list or block object is written, and deleting a block by name is refused (blocks go through garbage collection).
  • Copies. status, the safety indicator, where, the trash and the version history count copies with storages3::block_copies and devices with the held flags of their manifests.
  • Trash and history. The device's trash entries, removals (with their Lamport time) and replaced versions are its trash stream (trash3); entry ids are computed over binary ids. As built: the vault's trash days, history days, days per folder and trash storage are the settings record (kind 18, vault/settings/<device>/, registry key; trash3::settings), written as a whole on every change and read as the newest record of every trusted device by (updated_utc, Lamport time, device); members of shared folders read none and keep the defaults. A folder at 0 trash days follows the vault and is not written.
  • fsck and repair. fsck is fsck3 over the hot storages (with --verify every claimed pack is read and hashed); its findings fill the format-2 counters and the repair queue. A repair copies a pack missing on a storage whole from another storage that holds it intact, and writes the good members of a damaged pack into a new pack there (corrupt members from the same place on another storage, the block cache or a file on this device), with lost marks where nothing has them, in one map record and one batch before the damaged pack is deleted (gc3::repair_pack).

Parts B and C ported or deleted every area that still spoke format 2 (77.18 to 77.21); what is left is in 77.22.

77.20 The switch: membership, sharing, removal, Strongroom and organizations (as built)

What the second part of the switch built for folder membership and the people around a vault (membership3, engine/members3.rs, engine/membership.rs, engine/share_ops.rs, engine/share_roles.rs, engine/strongroom_ops.rs), where it differs from the design or fills a gap in it:

  • Device removal. revoke_device writes the vault epoch record, the revocations and the vault grants (Membership::remove_devices, several devices in one epoch for an organization's user), then a folder epoch for every folder the device took part in. As built: a number under vault/epochs/ that no device of the vault signed is junk: a removal takes the number after the highest one listed, and a reader follows an epoch record that skips numbers only when no signed record is under the skipped ones (so a removed device's modified client cannot write past an epoch it never got); join refuses a vault key only when a signed newer epoch exists. The removed device accepts a revocation of itself without opening the epoch record that backs it (it gets no key of it) when a signed record of the issuer is under that number, and the issuer is not removed; with a wipe order it then wipes. Two signed records under one number stop adoption at that number and every signature of this device until the user keeps one (varsto device resolve-epoch, epoch-fork.json). A removed device's manifests, maps, trash records and snapshots count up to its cut-off (their announcements in its later batches do not count); its folder, grant and escrow records count through the cut-off its revocation carries for each of those streams (registry_cuts): the end of the run of sequence numbers from 1 that each held a signed record of it at removal, so a number it left empty below its highest one cannot be filled afterwards with a backdated record (a signed record above such a gap does not count either; honest streams have none); its other records do not count at all. A folder the remover could not re-key (it is no owner there, or holds no key of it) is re-keyed by the first owner device of that folder holding its current key that reads the membership, which every sync does (rekey_after_removals); every folder epoch also lists a removed device that still takes part as removed, with its revocation's cut-off, and denies it. What a removal cannot do: a key cannot be recalled. The removed device keeps every folder key it held and can read everything written under them: what was written before the removal, what other devices write before they read the new folder epoch, and, in a folder the remover could not re-key, everything written until an owner device of that folder that holds its key syncs (a folder whose owners were all removed stays under its key until a recovered owner takes it over and starts an epoch). Existing data is not re-encrypted (77.6), and storage credentials are not rotated. In an organization a device its policy locks out stays a member of the new epoch, gets no grant then, and gets one at the next read of the membership once the policy allows it again (grant_missing_vault_keys).
  • Folder removal. remove_folder writes the owner's folder record with removed; with --purge the folder's packs are dropped in one batch and deleted, then its manifests, maps, trash, access, notes, thumbnails, snapshots and Strongroom key wraps. Every device forgets the folder when it reads the record (files stay on disk).
  • Device details are the details of the device's own device record, written again when they change and at least every six hours; forge_device_details_for_tests shows that a record for another id is refused (the id is the BLAKE3 of the key it carries).
  • Other people's devices. The vsr1 request code carries the requester's K6 and K8 public keys and its name (vsr1.<K6 hex>.<K8 hex>[.<name>]; a link stores them in binary, which needs several QR codes); its six words are over the three. share_add (CLI share create --to, POST /api/share/create) checks the confirmed words, writes the folder record that lists the member with its keys and role, and a grant to its K8. As built: a member reads no registry, so every grant to a member device carries the folder's directory (membership3::Directory: the folder's name and creator and, for every participant, its K6 and K8, whether it is a device of the vault, its role history and, once removed, its ledger cut-off), under a stamp of its own; an owner writes the members new grants of the current epoch whenever the participants or their roles change, and the directory with the largest stamp counts. The member accepts (accept_share, CLI share accept --owner-words) by reading the grants to its key on the storage it was told, keeping only the one whose issuer has the six words the person confirmed (without words: the only one there); from then on it trusts that owner and the owners its accepted directories name (MemberView), and builds from the directory the same registries a device of the vault holds, so its records are judged by the same Trust. A member reads no revocation and no registry, so the registry cut-off cannot reach it: it applies a removal from the folder epoch record that made it. Once an applied epoch removed an owner whose grants it counted, it reads the folder again without that device's grants (trust starts from the owner it accepted and the owners the epoch records keep, and a directory of the removed device neither counts nor makes another device trusted), and a device an applied epoch removed starts no later epoch. Before an owner re-keys the folder, a member cannot tell that an owner device was removed from the vault. No token travels: the owner tells the storage and its six words.
  • Folder-scoped batches of owners. A member holds no vault key, so it cannot read the owners' vault batches. As built: a full device writes its events of a folder that has (or had) member devices into a folder-scoped batch under the folder's share-ledger key (envelope scope = the folder, read with the new EventScope::Owner: claims and announcements of that folder, verifications and drops of packs); the first time it sees a folder shared it announces there again the packs it wrote of that folder and its manifest, map and trash records, so a member that joins later finds them; and it keeps its batches on the storages from then on (members cannot read the checkpoints that would stand in for them). A device that holds the vault key alone sees no packs of a shared folder (design section 1 lets it see them).
  • Roles. Readers judge a record by the highest role its writer held while it took part (FolderRegistry::writer_role), and the ledger decides when it wrote: folder events of members and full devices count only while the writer was an owner or editor at the batch's Lamport time. So what an editor wrote before it became a viewer stays, and a viewer's later announcements are refused. A device removed by a later folder epoch keeps its role for the epochs before it. A member device removed from its folder (a folder epoch) counts up to its cut-off like a removed device.
  • Strongroom (kind 24). The record carries the wraps (method, credential, salt, wrap, label, time), the key commitment, updated_utc, converted_from, the manifests of each device the converted copy includes (covered) and rekey; escrow under K2 is not written yet. As built: the folder id is folder_id(creator, nonce) with nonce derived from K13 (strongrooms::creation_nonce), so the device holding the key names the id before anything is written; K13 is never granted (unlocking gives it for a while; the record keys of the folder come from it then). A conversion fetches every placeholder under the old key, writes the new folder's records (its participants copied), switches this device to it and pushes every file; the old folder's record then carries removed and its packs and records are deleted. Other devices take the new folder in the old one's place when they read its record (adopt_conversions).
  • Organizations. As built: the manifest, roster and log keep their own sealed and signed objects under org/ (with the claim of a sequence number by put-if-absent that lets two administrators converge); they are not yet wrapped in kinds 25 to 27. They are read with every read of the membership, and a device the roster does not list, or on a platform the policy refuses, writes nothing that counts (EventScope none for its batches). Joining an organization gives the vault key; folders still come with an owner's approval of the device's request.
  • Recovery. join --recovery-words (recover_folders) takes every escrowed folder key, which gives read access. As built: the recovering device becomes an owner of a recovered folder once every owner of it is removed from the vault: it writes a folder record naming itself owner, and readers take an entry by a non-owner that makes its own writer owner when every owner at that stamp is removed (FolderState::build_with). The usual order after losing every device: join with the vault words and the recovery words, remove the lost devices (varsto device remove), which also starts the folder epochs, then approve new devices.

77.18 Part B: backups, access, notes, thumbnails, change history and manifest pruning (as built)

Section 31 (backups), 13 (access), the file analyses, F-046 (thumbnails), 57 (change history) and 24 (manifest upkeep) in storage format 3. What differs from the format-2 text:

  • A backup is a folder. add_backup writes a folder record (this device the owner, a random K9₀ granted to it, the escrow when the session holds K1) whose settings carry backup, the JSON of its BackupInfo (source device, source path, retention, creation time); every device that reads the record lists it in backups() and not in folders(). The backup has a block map and packs like any folder, and no manifest, so no device holds its blocks (held has nothing to say) and peers never serve them. A transferrer is never written.
  • Taking a snapshot. The source device scans the directory, writes the blocks the hot and cold storages lack (never a transferrer) into packs per target set, publishes the map record and claims the packs in a batch, checks that every file of the snapshot has a live place of each of its blocks on a storage (a file for which that fails is left out and named in skipped), then seals a snapshot record: a base, or a differential against the current base (snapshot3::SnapshotWriter; the writer's base and counts are kept in state/backups/<backup>-writer.json, a restart that finds a higher seq on a storage starts with a new base). The record goes to every metadata storage that is not a transferrer, hot and cold, under snapshots/<backup>/<device>/, and is announced with record_published and snapshot_taken in the next batch.
  • Restore. The unexpired snapshots (and the bases they name) are read from the hot storages, from the cold ones only with the confirmation, through the acceptance rule: a copy that was altered, or is not what the ledger announced, is refused and the next storage tried; when no copy is accepted the restore says the snapshot was altered. The listing is rebuilt from the snapshot and its base alone. A device other than the source needs a grant of the backup's keys: it asks for the backup by name (folder request), the source approves with the six words, as for any folder; a device without the grant is told it holds no key.
  • Expiry. The source device expires a snapshot a day after its expiry time; any device does so once the backup is stopped, its source was removed from the vault, or two days have passed. snapshot_expired is sealed and pushed first. A record is deleted from the storages only when it is expired and no unexpired differential names it as its base (snapshot3::reader::deletable); a base that an unexpired differential needs stays, hidden from the listings. The blocks only expired snapshots used are not deleted by the expiry: the unexpired snapshots are references of the backup's folder for garbage collection (Engine::backup_gc_references3), which marks and collects them as for any folder. ExpireReport::snapshots_deleted counts records; objects_deleted stays 0. A stopped backup whose last snapshot has expired is removed as a folder record.
  • Access records. Kind 20, access/<folder>/<device>/, sealed under the folder's metadata key: the device's last-accessed times by path, replaced as a whole (the writer deletes its older records of the stream), written at most once an hour after a change, read in the same rhythm. Every device that may write the kind is read (viewers write them too, as the authorization matrix says); revoked devices are skipped.
  • Notes. Kind 21, notes/<folder>/<device>/: the analyses the device wrote (set, cleared or moved), each as a NoteWire; a cleared analysis is an entry with an empty text. Readers merge the newest record of every other device newest-wins per path by (analysed_utc, writer): the wire's analysed_utc of a clear or a move is the time it was made. A device's record lists only what that device wrote, so an analysis written by a removed device is not republished by the others (a deviation from format 2, where every device republished what it had merged).
  • Thumbnails. Kind 22, thumbs/<folder>/<device>/: the thumbnails one pass made are one record (JPEG bytes by content hash); a pass is bounded as before. Each device keeps the pictures it made or read in state/thumbs3/<folder>/, sealed under a key derived from its master key, so a folder kept encrypted here leaves nothing readable. thumbnail() reads the cache and, on a miss, the records past what was read (asking the storages at most every five seconds). A storage added later gets every record copied (replicate_records3).
  • Change history. Derived locally from the manifests as in section 57, not a record: a pull records the paths each writer's records changed (history_from_view), and a device starts its history from the views it holds (history_backfill).
  • Manifest pruning. After a sync a full device deletes its manifest records below its newest base once every reader of the folder (the participants of the folder at its epoch, not revoked) has acknowledged the batch that announced the base (manifest3::prune_floor, prune_stream; cold storages never). A pull reads only the records the ledger announced past what it applied, and an unchanged push asks no storage anything (format 3 has no full listings).
  • Deleted. The format-2 per-device <utc>-named access and notes objects and their keys, the per-thumbnail objects (thumbs/<folder>/<content hash>.enc), the format-2 manifest pull and manifest pruning, the backup snapshot object handling of engine::backups and its listing sweep. snapshot.rs and manifest_upkeep::parse_key went with the last part (77.22).

77.19 Part B: garbage collection, verification, scrub, repair, fsck, ledger rebuild and gaps (as built)

Sections 25 (repair), 26 and F-032 (automatic verification), 33 (scrub), 38 (ledger rebuild), 43 (the trash's blocks), 58 and 74 (gaps and heads) in storage format 3, over 77.3 and 77.10. What differs from the format-2 text and from the design:

  • Garbage collection runs in the trash upkeep (trash upkeep, trash purge, Engine::pack_upkeep; engine/pack_upkeep.rs) on own full devices with the writer role, for every attached folder and every backup: the folder's records are pulled, the references gathered (other writers' newest manifests, this device's folder state, which is newer than its last manifest when a pull applied changes no push published yet, and the unexpired trash and history entries; for a backup its unexpired snapshots), then one marking round (gc3::mark_round) and one collection run (gc3::collect) over the view the marks' batch left, then the orphan rule over every folder table held here (state/gc3.json keeps when an unclaimed pack was first seen). On a device that is the folder's only writer a deletion is collected in the same run. Events recorded before (a push's announcements, a trash record) are sealed first, so the map record of a round follows theirs. Pools and transferrers count as storages whose packs are never rewritten. TrashUpkeepReport::blocks_dropped counts the places collected, blocks_waiting the pack copies a cold storage's minimum duration keeps, and a note names the devices collection waits for.
  • Acknowledging marks. A mark settles only once every current writer has signed a batch whose seen names the marker's batch. A device that pulled another writer's dead marks and has not acknowledged them signs an empty batch at its next ledger upkeep (acks_due3), as it does for checkpoints, so collection does not wait for its next change. The garbage collection of the trash upkeep signs it too, right after it read the folder's records and before its own marking round (sign_due_acks3): marks a device found there are acknowledged even when its last sync had not seen them.
  • The trash storage takes the packs whose live members are only trash and history entries whole, and rebuilds packs that hold current blocks as well (storages3::moves: the trashed members into new packs on the trash storage, the others into a new pack where the old one was); the new places go into one map record and the copies and drops into one batch before the old packs are deleted.
  • Automatic verification reads whole packs that another device claimed on the storages this device reads without asking, due by the copy's last independent verification, and records pack_verified under the claimers' name of the storage; it needs no folder key (a device that joined with the vault words alone verifies). The budget counts packs (max_blocks) and class bytes. Missing and damaged packs go to the repair queue.
  • Scrub sweeps the packs the view holds on each storage read here (scrub3::scrub_packs), under this device's name for the storage; pool disks as before, a bad pack no other disk holds goes to the repair queue.
  • Repair works on the queue (with scan, after an fsck --verify that queues what it finds): a copy intact by now leaves the queue; a missing pack is copied whole from another storage that holds it intact; otherwise the pack's members come from the damaged copy, the same place on another storage, the block cache, another pack of the block on a hot storage, this device's file, a peer, or (with --from-cold) a cold storage, and gc3::repair_pack writes them into a new pack there. A missing pack nothing can rebuild is reported once per pack (a cold storage that holds another place of its blocks is named) and tried again a day later. Repaired copies are reported per block, losses per pack.
  • fsck: varsto fsck [--verify] [--fix] [--json] (--repair stays an alias of --fix) prints Fsck3Report::describe; --json carries the report under format3. With --verify the good packs are recorded with pack_verified and the task counts the blocks the maps place in each pack.
  • Ledger rebuild (varsto ledger rebuild) runs rebuild3: the claims of packs this device's maps name are signed again at once (in format 2 a second step with --from-storage was needed); --from-storage, and the service when no ledger is left anywhere, read and hash those packs first and claim packs nobody claims once their hash is their id (named_corrupt, unnamed_corrupt: not claimed, queued for repair). Own batches signed here that no storage holds while a storage holds another batch of this device under their numbers are set aside (ledger/discarded/) and their events signed again. Records below the newest base of a stream are superseded, not unannounced: they are not announced again. Nothing is signed while the local ledger needs a rebuild (the check is in the batch commit itself).
  • Gaps and heads. A pull first runs the head exchange with the peers (p2p_catch_up) and afterwards the rollback judge (p2p_judge_rollback); the gaps (LedgerHealth::behind) are computed from the view's acknowledgements, the peers' proofs (ledger/proofs.json) and the pending batches, and the rollback warnings join LedgerHealth::warnings (status, ledger status, the Help page, a notification when one appears). The health's own state is kept in ledger/health.json.
  • Map and manifest pruning delete this device's records below its newest base (gc3::prune_map, manifest3::prune_stream) once every reader acknowledged the batch that announced it.
  • Deleted. Tombstone lists and pack indexes (written and read; Storage::flush_deletions, collect_pack_garbage), the format-2 pack rewrite, the trash drop queue (state/trash/drops.json), the format-2 automatic verification, scrub and repair of single block objects (chunk_verified is no longer recorded by them), the format-2 fsck, ledger restore and claim rebuild, and the format-2 pull and push of the ledger. Event::ChunkVerified and snapshot.rs went with the last part (77.22).

77.21 The switch, storages (as built)

Policies, placement, quotas, data moves, staged moves, drains, storage removal, disk pools, replicas, transferrers, forwarding, the mailbox and imports work on the pack-level view (storages3) and the folders' block maps; the format-2 per-block claims, tombstone writes and pool bookkeeping of these parts are gone. Where it differs from 77.9 and the design:

  • Copies. Policies, placement, the drain and move plans, the disk group findings and the cleanup of imports count copies with storages3::block_facts / block_copies (a pool copy per disk that holds the pack, a disk that is away at its last check). A block taken away from a storage (a pack with a place of it dropped from there) is not written back by a push while another copy exists. fsck --verify records pack_verified for every pack it read back whole and hashed right; a download reads blocks and verifies no pack.
  • Storage names (kind 19). Every full device publishes its names and storage identities when they change and reads the others' at each pull; the view a device works with is localized (storages3::localize): places another device named differently are renamed to this device's name, and a storage of the same name that is not the same storage is kept apart (<name>@<device>). As built: the shared settings of storages (quota, drain, storage_settings) travel in the same record (StorageNamesBody::settings, as JSON per storage key, the newest updated_utc of a storage winning); the format-2 vault/storage-settings/ records are gone.
  • Policies and placements are policy (kind 11) and placement (kind 12) records; a device's policy record lists the policy of every folder it knows one of, so the newest entry of a folder wins whoever republished it.
  • Quotas count the size classes of the packs claimed on a storage. A writer reserves room by the packs its blocks fill (whole top-class packs and the smallest class of the rest), a whole-pack copy by its class.
  • Moves and staged moves. A move is planned with storages3::plan_move, then the folder's policy is checked for every block the plan takes off the old storage (capped at what the copies met before): a vetoed block stays (its pack is rebuilt with it in the remainder, or left alone). A pack is read from another storage that holds it, from the mailbox's outbox, or from the old storage when it may be read (cold: only with a confirmed cold read); when none may be read, the blocks are re-encrypted from the files on this device or taken from the block cache and written into new packs. Packs go in groups of up to 16 MiB of size classes, one batch each (sealed and pushed even inside an action that seals one batch at its end, before anything is deleted). A pool destination without room takes what fits (members in halves, each in the smallest class): the rest goes into the remainder on the old storage and waits. A dropped pack that cannot be deleted now stays until the next run of the move or garbage collection deletes it.
  • Drains and removal use storages3::drain_plan; a drain also copies a pack whose blocks keep their rules without the storage to the first target that lacks it (the number of copies is kept where a target exists), a removal copies only what the rules need. A drain's run limit counts packs. Removing a storage retires it after the copies; with delete_data everything but the (virtual) block names is deleted.
  • Pools. A disk insert tidies with storages3::tidy_disk_packs; a disk check and the insert's re-hash record pack_verified and pack_dropped (storages3::disk_check_events); a fill writes new packs of one folder each, listed in that folder's map record. fsck counts the packs whose disks are all away (objects_offline).
  • Replicas. Replica::init makes the replica's K6 and leaves an enrolment request (vault/replicas/<replica id>.enc: name and public K6, sealed under the replica key derived from K3₀) on both storages; a full device that reads it writes its replica record (kind 23). As built: the record lists every replica its writer enrolled (replica::ReplicaBody). Replica batches are SignedRecords under key id replica, counted in the replica scope.
  • Transferrers carry the ledger and the records too (they are metadata storages like any hot storage), take a block no other device holds (or one a destination lacks) by the held flags, are pruned after each pull of a folder (storages3::delivered_packs, drops pushed before the deletes), and are never repaired.
  • Forwarding reads the folder's map records before it plans, writes packs, reads each back whole, lists their places in its own map record and claims them.
  • The mailbox stages and delivers whole packs only: a storage task is a pack on a docked disk holding a current block whose rules are not kept, written whole to the target and claimed with a zero folder. As built: the list of what a device holds staged is its mailbox record (kind 28, mailbox::BoardBody); the staged packs are served to peers from the outbox (packs/<xx>/<id>).
  • Imports claim the packs they wrote in a map record at every checkpoint and publish the manifest as a format-3 record.

77.22 The switch, last part: what is left of format 2

The last part of the switch removed the format3 cargo feature (every module, command, route and the pairing question are unconditional; /api/state no longer says format3; CI runs one clippy and one test step), the engine code nothing called (the format-2 batch commit, manifest publishing, key directory, device-registry and ledger key helpers, the head exchange of section 74 over the format-2 view, trash record readers and the folder-record keys), Event::ChunkVerified (a download checks one block, not a pack, so it records nothing; pack_verified stays with fsck --verify, automatic verification, scrub and disk checks), crate::snapshot (the folder purge deletes the snapshot records with the folder's other records), ManifestPolicy::sweep_secs, the translations of the share-token pages, and the 3 suffix of engine functions whose plain name was free. The trash settings moved to the settings record (77.17).

What is left, and why:

  • The location view of crate::ledger (Engine::view, LedgerStore at state/f2-ledger, ledger::Event with chunk_stored, chunk_on_device, chunk_dropped, manifest_published): no batch of it is ever written or read from a storage, but the events this device records during an action (Engine::pending) are applied to it, and placement, where, protection, history and trash code still take this view as a parameter. Format 3 carries the events it has (enrolment, folders, retirements, snapshots) into its own batch and drops the per-block ones. Removing it means moving those readers to the pack-level view, not a deletion.
  • chunks/<xx>/<object> keys: the name of one block inside a pack, which packs::PackStore answers from the packs and the block maps; no block object is written under it.
  • Objects that are not records: import books (vault/imports/<folder>/<device>/<utc>.enc, sealed under the folder's K10), replica enrolment requests (vault/replicas/<replica>.enc), forward and staging leases, and the organization's manifest, roster and log under org/ (77.20); no record kind holds them yet.

77.23 Behaviours restored after the switch

The port of part B left three format-2 behaviours without callers, and the last part deleted them as dead code (77.22). They work on format 3 again:

  • A long upload reaches peers before it ends. A push on a device with peers (Engine::set_peers; the service sets them) whose file list changed publishes its manifest delta first (with held set: this device holds every new version), seals and pushes the batch that announces it, saves the folder state and builds the snapshot the peer-to-peer server answers from again (Engine::set_snapshot_sink, which the service hands over), then tells the peers (/p2p/changed). The other devices' pulls see the new files at once and fetch their blocks from this device peer to peer (the file's pieces, and blocks in packs of its local-directory storages) while the storages receive their copies; a device that cannot reach it finds the blocks on the storages later. While the upload runs, the packs the storages have taken so far go into a map delta of this device and their pack_stored claims into a batch, pushed at once, whenever at least EarlyPublish::bytes (64 MiB) more were handed to the uploaders or EarlyPublish::secs (30 s) passed since the last such record, and something new was stored; this goes on while the uploaders finish the last packs. The push's own map record at the end lists the rest. Without peers nothing changes: one manifest delta and one map delta after the upload, one batch. A failure of such an intermediate record is logged and the push goes on; the packs it took are claimed by nobody until the next push writes their blocks again (orphans go after 7 days, 77.3). Between the first record and the end, the folder's blocks have no storage copy yet: status and policies count them as such, as during any upload. Test: tests/upload_peers.rs (two engines on loopback, a storage that takes one 256 KiB pack per 250 ms: the second device has every new file, from the uploader, and sees the stored packs claimed before the push returns; afterwards a third device reads everything from the storage alone).
  • A folder created twice under one name. Two devices that create a folder under the same name while they cannot read each other's records get two folders with different ids. The creator's first folder record carries the setting created_utc (Unix seconds); FolderRegistry::dedupe_names, applied whenever the folder records are read, gives every live folder a shown name: in the order (created_utc, folder id), a folder keeps its name unless an earlier one took it (compared without case), else it is shown as " (2)", "(3)", ..., the first number free. Every device reads the same records and so shows the same names; the records keep the name their writers gave, removed folders take no name, and a Strongroom converted from a folder that is still there keeps the old folder's name beside it (converted_from). The local keyring, status, the interface, requests and the commands use the shown name; mounts are by folder id, so each device keeps its directory. A record without created_utc counts as created at 0. Tests: membership3::folders::tests, tests/folder_names.rs.
  • Quota room of writes that did not happen. A run takes quota room before it writes (QuotaGate::take per block, take_pack per whole pack, 77.21); give_back and give_back_pack return it when the write does not happen, so a later block of the same run is not refused for room nobody used: a push gives back the room of a block a storage failed or already held and of blocks it never handed over when it stopped; forwarding gives back the room of a block no source had, of an object refused by its checks, and of a block a target did not take (a failed write, a pack that did not read back intact); a data move gives back the room of packs it did not copy (no room after all, no place, damaged, unreadable, or groups left for the next run); a drain plan gives back what a pack took when another target refuses it. Tests: quotas::tests::a_write_that_did_not_happen_gives_its_room_back, tests/forwarding.rs::room_taken_for_a_block_that_is_not_written_goes_to_the_next_one.

77.24 Behaviours the lab scenarios corrected

Running the lab scenarios (scripts/test/lab) against rclone serve s3 found these; each has a regression test.

  • S3 reads of exactly the allowed size. A read capped at n bytes accepts a body of exactly n (a pack read with its class size by garbage collection); one byte more is refused. Test: tests/s3_reads.rs.
  • Range reads. A 206, or a 200 that carries Content-Range (rclone serve s3), holds the bytes from the header's start, possibly clipped at the object's end; a 200 without the header is the whole object; 416 is an empty range. A range read never comes back empty for bytes the object has. Test: tests/s3_reads.rs.
  • One writer of a device directory at a time. The background service and a command that opens the same device directory each hold parts of the state in memory (ledger heads, block map tables, the pack context). An operation that writes the local state (sync, pull, push, fsck, repair, scrub, trash upkeep, folder attach and detach, a backup snapshot, and the short operations that rewrite a folder's state state/<folder>.json or the configuration: fetch_file, free_file, writing and moving a file through the engine, set_folder_mode, set_selective, set_deletion_guard, confirm_deletions, discard_deletions, revert_local, override_remote) holds the exclusive file lock state/home.lock (waited for) and bumps the counter in state/home.gen when done; before, those short operations read and rewrote the folder's state without the lock, and whichever of them and a sync of the service saved last undid the other's changes (a fetched file's index entry, a confirmed deletion). Writing a file holds the lock to record its local name and to push it, not while it reads the content. Recording that a file was used (touch_access, the accessed field) takes the lock only when it is free and is left out otherwise, so opening a file never waits for a sync; an engine that finds the counter changed since its own last operation reads the ledger, membership, tables, pack context and configuration again before going on. Test: tests/one_home_two_processes.rs.
  • Attaching again after a detach. A pull applies every path of a writer's view whose sequence is past what the folder state applied (a state that starts clean after folder detach while the views read before stay), not only the paths its newly read records changed. Test: lab_regressions::attach_after_detach_gets_every_file_again.
  • A removed device's records for devices that come later. A device removed from the vault is judged with the highest role it held in the folder for the kinds that survive a removal (manifests, maps, trash, snapshots), so a device that joins after the removal and never applied the folder epoch it made still reads what the removed device wrote up to its cut-off (step 5 of the acceptance rule limits them to its announcements up to the cut-off). Test: format3_switch::recovering_after_the_lost_owner_was_removed_reads_its_records.
  • Repair of several packs in one run. Each damaged pack is repaired over the ledger view the previous repair left (its map record and batch), so an fsck --verify right after the repair finds every block placed. Tests: lab_regressions::fsck_right_after_repair_is_clean, a_lost_pack_is_rebuilt_from_a_conflict_copy.
  • The rollback judge reads each storage's own listing. The pull lists a device's batches from the head held here (a storage that has it lists it) and, when nothing from there is listed, the storage's whole listing of the device for its own newest batch or checkpoint; the head held here (from a peer or another storage) never stands in for what a storage shows. Test: peer_heads::a_storage_is_judged_by_its_own_listing_after_a_hand_over.
  • Acknowledgements in the trash upkeep (77.19, "Acknowledging marks"). Test: lab_regressions::gc_settles_when_the_other_writers_run_only_upkeep.

78. The mailbox for offline pool disks

Code: crates/varsto-core/src/mailbox.rs (outbox, task file, settings, published list), engine/mailbox.rs (runs), and the mailbox commands in crates/varsto-cli/src/upkeep.rs.

Why. A pool (section 19) is filled through one dock: disk A is docked, then put on the shelf, then disk B. A block that is only on A (or on A and too few places) and that disk B (another place of the same pool, or a disk of another pool), or another storage, should hold too, never gets there: when B is docked, A is not, and nothing else has the block. The device with the dock is the mailbox: while A is docked it reads what B needs into a durable outbox, and when B is docked (here, or on another device) the objects are written there.

Tasks. A task carries one ciphertext object, named by its hash, from a pool disk to a target (state/mailbox.json, per device: kind, the object's storage key, size, source pool, disk and label, target, the places or disks of the target that would take it, for blocks the folder, chunk and object, for moves the job, state, times). Three rules make tasks, each from what the disks docked now hold:

  • group: a pack on a pool with a disk group rule (section 23) that is held in fewer places than the rule asks, that the ledger still wants, and for which a disk of a missing place exists; the target is a disk of a missing place (add_copy_on_disk, read back as every pool write is). Nothing is recorded in the ledger: the pool index of the device and the disk's own index hold the copy (the ledger records one claim per pool).
  • storage: a block of a current file (from the folder state on this device) of a folder with a policy, whose copies do not keep the folder's copy rules (counted as the policy check counts them, the verification window left out, as forwarding does), and which another storage of this device should take by the folder's write targets (WriteTargets::wants: placement or the default fewest storages, drained storages and transferrers and cold storages left out) and does not hold yet. Written as packs, read back, recorded chunk_stored by this device, sealed and pushed (exactly as forwarding writes, section 70; the writer's read-back is not a verification).
  • move: a block that an open move job (section 59) from a pool still has to move, while the job waits (its target has no room or no docked disk). The mailbox only stages it: the job reads it from the outbox (move_source asks the outbox after the block cache and before the other storages), writes the target, reads it back, records chunk_stored and chunk_verified for the target and only then chunk_dropped for the source, seals and pushes the batch and deletes from the source (queued for a disk that is away, section 19). A source copy is never dropped before the target copy is written, read back and recorded, and never when the folder's copy rules need it (sections 23 and 59). A job whose blocks are only on source disks that are away no longer gives them up as "no readable copy": it waits (waiting.kind source, the disk's label, "attach disk «A» of pool P to continue the move"), and is ready again when that disk is docked.

A task is waiting for source (its disk is away, or the outbox had no room when it was docked) or held (the object is in the outbox). A task ends when its target holds the object (the pool rule is met, the ledger has a claim on the target storage, the job moved the block), when the rule that made it no longer asks (the block's copy rules are met in another way, the job finished or was cancelled, the pack is no longer wanted), and its staged object is deleted once no task needs it.

Keyless. Staging and writing need no folder key: objects are copied as stored and checked by hash only (name_matches: the BLAKE3 of the bytes must be the last part of the key, a block's object name or a pack's id). The planning reads the ledger, the pool indexes, the policies and the folder states, none of which needs the key, so a device carries blocks of a Strongroom while it is locked (move jobs need the folder to resolve, as before).

The outbox. <home>/outbox/chunks/<xx>/<object> and <home>/outbox/packs/<xx>/<pack id>: the object exactly as stored, refused unless it matches its name, written through a temporary file, fsynced and renamed (util::write_atomic), read back and checked again, and checked once more every time it is used (a staged object that does not match is deleted and counted rejected; its task waits for its source again). Leftover temporary files older than an hour are removed at the next run; objects no task holds are deleted. The outbox is never a storage: it holds no claims, and a staged object is never a copy for a policy.

Where staging goes. On this device's own disk. There is no fixed size limit: staging writes only while the device directory's disk keeps at least keep_free free after the write. config.json mailbox.keep_free is a list of limits in the form of section 53 (a share such as "15%" or an amount such as "50GB"), of which the largest counts; empty (the default) is ["15%", "50GB"]: 15 % of the volume or 50 GB, whichever is more. What a run stages is subtracted from the free space it measured at its start. An object that does not fit is left waiting (room_needed_bytes), smaller ones may still fit, and the report and the status say "N could not be staged: this device keeps X free (...); free space here or dock the target disk first" instead of failing. Staged objects are the first thing removed when the device needs space: whenever the disk is below keep_free, or a place on the same volume is short of space (section 53, freespace::short_places), objects are removed, the last staged first, until the rule holds again; their tasks wait for their source again. Neither the source copy nor any durable copy is ever removed for this.

One run (Engine::mailbox_run, MailboxOptions): pull the ledger; reconcile the task file with the outbox; give space back; read the other devices' lists; plan tasks from the docked disks; end the tasks that are done; stage (below); write to the targets docked now; take blocks other devices hold for this device's storages; delete what no task needs; publish this device's list; save the pool registries. One run at a time per device (state/mailbox.lock, taken over after ten minutes without progress). The service's budget is 4 GiB and 20 000 objects of staging a run; varsto mailbox run has none. A target that is docked together with the source gets the object directly, without staging (direct in the report).

Two dock hosts. Every device with something staged publishes its list, vault/mailbox/<device>/<utc, 20 digits>.enc on every storage that holds records (sealed with XChaCha20-Poly1305 under the device registry key, associated data mailbox-board, vault id and device id; JSON {device, updated_utc, held: [{kind, key, size, pool, source_label, target, target_disks, places, folder, chunk, object, staged_utc}]}), when it changes and daily while it holds anything; its older lists are deleted. Readers take the newest list per device and ignore lists older than 30 days and those of revoked devices. A device does not stage an object that another device's list holds (held_elsewhere), and shows those as "… (staged on )". While it stages, a device holds the lease vault/mailbox-leases/<slot>.json on those storages (the lease of forwarding, section 70, with the same slots, put-if-absent and lapse rules); a lease of another device means that device is staging now: this one stages nothing in this run (busy). The list is published before the lease is given back, so the second host sees what the first one holds.

Delivery on another device. The outbox is served to peers like the block cache (the peer snapshot's local_roots, section 15). A device that reads another device's list and has a storage that a listed storage task's block should go to, and can write it now (for a pool: a docked disk with room), fetches the block from the peers (Peers::get, checked against its name), writes, reads back and claims it as above (pulled_from_peers). The device that staged it sees the claim in the ledger at its next run and lets its copy go. Group tasks (whole packs, up to 64 MiB, and pool-index copies that the ledger does not record) and move tasks (jobs are per device) are delivered only by the device that staged them.

Policies: in transit. Staged objects count for no policy. The policy check reports, for a folder that is at risk or violated, the blocks a mailbox holds for their targets (here or on another device's list) as chunks_in_transit and bytes_in_transit with the reason "N blocks (X) in transit to disk «B» (staged on this device); staged copies do not count". The verification grace of automatic verification (package E) is not on this base; when it comes, in transit is the state it reads.

Status, interface and commands. Engine::mailbox_status (GET /api/mailbox, varsto mailbox, the service summary's mailbox and one-line mailbox_text) has the setting, the free and kept bytes, the objects and bytes held here, and groups of tasks by kind, source, target and state with a sentence each: "2.1 GiB from disk «A» waiting for disk «B» (staged on this device)", "1.0 GiB still to be read from disk «A» for disk «B»: keep it attached for about 3 min" (the time from the dock speed of section 34, disk_fetch.disk_mb_per_sec), "… waiting for disk «A» to be docked (to go to disk «B»)", and other devices' "… (staged on )". varsto status lists them under the move jobs. POST /api/mailbox {enabled, keep_free} (keep_free a list, one string, or "default"), POST /api/mailbox/run, varsto mailbox set [--on|--off] [--keep-free 15% --keep-free 50GB | --default-keep-free] and varsto mailbox run (through the running service, which knows the peers). Each pool card of the Storages page shows its lines, the first one also the setting with a checkbox and a Mailbox settings dialog, in English, Finnish and Swedish. The activity list (section 32) has a mailbox task with the steps stage ("Copying blocks from disk «A» to the mailbox") and deliver.

Next disk to dock. Engine::disk_suggestions (section 40) takes mailbox_waits: per pool and disks, the bytes staged for them (role target) and the bytes waiting to be read from them (role source, from tasks and from move jobs waiting for a source disk). A disk that is away gets 60 × (its staged bytes / all staged bytes waiting for a target) points (kind mailbox, "2.1 GiB staged from disk «A» waits for it: docking it writes them") and a source disk 45 × its share (kind mailbox_source, "1.0 GiB to copy from it to disk «B» (about 3 min of reading)"), each at least the suggestion threshold, so the disk that unblocks the most staged data comes first; a docked source disk is told how long to stay ("keep it attached for about 3 min: 1.0 GiB still to read for the mailbox", kind keep_attached). The answer carries the waits as mailbox.

The service. After every sync (after forwarding) and whenever a pool disk comes or goes (the 30-second disk check, before the move jobs, so that a move reads what was just staged), the service runs the mailbox when it is on and the vault is unlocked; between runs it only gives space back. A run that wrote anything raises a notification.

Not done (follow-ups). Staging only on the dock host's own disk. Choosing the cheapest place for staging (another device of the vault over peer-to-peer, always-on and same-LAN devices first, when this one has no room; then an online storage at the lowest price the price model knows, with the estimated cost shown before anything is uploaded to a paid storage, and the task waiting for a cheaper place when the policy allows) is not built; neither is delivering group tasks (packs) and move tasks on another device than the one that staged them. A staged object is not read back again after a crash beyond its check before use. The board reveals object names and folder ids only to devices that hold the registry key.

Tests: crates/varsto-core/tests/mailbox.rs (one pool with a two-place disk group rule, disks A and B and one dock: the packs only on A reach B through the outbox after A is undocked and B docked, the policy stays violated with the blocks in transit until then, B is the suggested disk; the free-space rule stages one pack of three, the status says to keep A attached, the staged copy is removed first when the device needs space and A keeps its copy, a rule of its own lets all three through; a run stopped after one object resumes in a new process, an interrupted write's leftover is removed, a staged object that rots is refused and its task waits for A, then goes directly from A to B; a damaged pack on A is not staged; a move job from pool to pool drops the copies on A only after the copies on B are written, read back and recorded, the deletes wait for A, the staged copies go afterwards; a move whose source disk is away waits for it instead of leaving blocks behind; two dock hosts: the second sees the first one's list and stages nothing, and nothing either while the first holds the lease; a block staged on one host for a pool disk that is docked on another host is taken over peer-to-peer, recorded there, and released by the first host), mailbox::tests (the default rule, the outbox refusing and dropping objects that do not match their name, the run lock), disksuggest::tests (the disk that unblocks the most staged data ranks first; keep attached), desktop::tests (/api/mailbox) and cli_smoke (varsto mailbox).

79. Working offline

Every Varsto function works as far as possible when the internet is bad or absent: only the LAN works, one S3 or rclone storage cannot be reached, or the link is slow and loses packets. Peers on the LAN, the local mirror of the membership records and the ledger batches sealed on the device keep the vault usable; storages that answer are used, and a storage that does not is left out without failing the whole operation. The subsections describe the parts; each names its tests. Two parts live with the format 3 text they change: peers without a storage (the saved peer directory, raced routes, slow-link timeouts) in 77.8, and local-first membership writes (the mirror, the outbox, keys before epoch records) in 77.6.

79.1 Storage health

Per run. The first network error of a storage marks it down for the rest of the operation (a sync with its upkeep, a push, a pull, a snapshot). A network error is a refused, reset or aborted connection, a timeout, a host name that does not resolve, an unreachable network, an HTTP 502, 503 or 504, or an rclone error that says so (dial tcp, i/o timeout, no such host, ...); is_network_error decides. A refused key, a damaged object, a full disk or a pool without its disk are not network errors and keep their own handling. A storage marked down is left out when the storages are opened, and a backend opened before answers every later call at once with StorageDown (itself a network error), so nothing waits for its timeout twice. The marks end with the operation.

Across runs. A storage that failed rests: state/storage-health.json keeps, per storage name, when its failures in a row began, the last failure and its error, the number of failures in a row, and when it is tried next (30 seconds after the first failure, doubling up to 10 minutes). A sync that starts while a storage rests leaves it out from the start. The first call to it that succeeds ends the rest. Engine::retry_storages_now ends every rest (a "Retry" button, or the network came back); Engine::storage_health lists the storages that are down or resting with the error, the next try and the objects waiting for them, and status carries it as storages_down. The file holds storage names and error texts only.

Per storage, per folder. Every loop over storages goes on with the others when one fails with a network error, and fails only when none answers:

  • the membership read (Membership::open_with through the local mirror tee): a storage that does not answer reads as empty; when no storage answers nothing is adopted, so the membership known here stays;
  • the ledger pull (pull_ledger3): the storage is skipped and reported to the rollback judge (section 74) as not reachable with its last known identity, so an outage is never taken for a rollback; the peers' head exchange still runs, also when the membership could not be read;
  • the push of this device's batches: a storage that does not answer keeps its pushed mark and gets the batches at a later push;
  • the folder records (block maps and manifests) and every other record stream read (each_store);
  • uploads: a storage that fails with a network error is treated like a pool without its disk, left out for the rest of the push (storages_unavailable), and the packs the others stored are published; the storages of one target set are written by one thread each, so a slow storage does not hold back the fast ones;
  • downloads: a block that one storage fails to give is asked of the next; the failure is the answer only when no storage had it;
  • record writes (write_record3, manifests, snapshots): the highest seq is the largest that any storage that answers shows, and never below a seq this device wrote while a storage was down (kept in the health file, because the storage that holds it may be the one not answering now); the first storage that answers decides whether the seq is free; the others take the parts where they can;
  • organization records: the claim is decided by the first hot storage that answers (a cold one only when no hot one is there), the others take the object best effort; reading the organization skips a storage that does not answer;
  • snapshot record expiry deletes on the storages that answer; the rest is deleted at a later upkeep.

A sync reports a folder that fails in that folder's PullReport.error and syncs the other folders; it fails only when every folder failed. Every report of a sync lists the storages that run could not reach (storages_down). Thumbnails are published best effort: a thumbnail record that cannot be written never stops the upload.

Healing. The parts of a record, snapshot or organization object written while a storage of its set was down are queued for that storage in the health file (at most 10 000 names per storage). After each sync, heal_partial_writes copies them there from a storage that holds them (hot storages first) once it answers. Reading the organization also copies objects that only some storages hold to the others. Packs and ledger batches need no queue: the next push writes what a storage lacks.

One ledger pull per round. Engine::sync_round runs a sync and its upkeep (and anything else a caller puts in it, such as the service's forwarding and move steps) as one round: every step that pulls the ledger once (pull_ledger_once) reuses the round's first pull instead of listing every storage again.

Tests: crates/varsto-core/tests/storage_health.rs (a dead storage does not fail the sync and a device that reaches only the other storage has everything; a resting storage is not tried by the next sync, retry_storages_now tries it and what it missed is copied there; the first storage down still publishes; a download asks the next storage; with every storage down the membership stays; a snapshot with its cold storage down, healed later; two syncs in one round list the ledger less than two rounds), engine::health::tests (network errors told apart, the rest schedule, marks per run and rests across engines, a marked storage answering at once), engine::fetch::tests (a failing storage passed over).

79.2 S3 and rclone transport

A dead or slow network must cost seconds, not minutes, and must be told apart from a refusal.

  • S3. Resolving has its own limit (5 s), connecting 10 s, the first byte of an answer 120 s; the whole call gets 60 s plus the time its bytes need at 256 kbit/s up or 512 kbit/s down (at most an hour), instead of one global limit. GET, HEAD, LIST, DELETE and PUT (content-addressed objects and put-if-absent, where a repeated conditional PUT that finds the object answers 412, read as "exists") and the start of a multipart upload are tried up to three times with a short backoff when the connection fails or the server answers 429, 500, 502, 503 or 504; a timeout or a name that does not resolve is repeated once. Objects over 8 MiB are written as multipart uploads in 8 MiB parts, each part tried again by itself; there is no one-request fallback after a failed multipart upload. The conditional-writes probe treats a network failure as "unknown": nothing is remembered, the write takes the HEAD-then-PUT path and the next write probes again.
  • rclone. Every call passes --contimeout 10s --timeout 60s --retries 1 --low-level-retries 2 and runs under a wall-clock limit (two minutes plus the time 256 kbit/s needs for the bytes, at most two hours); a child still running then is killed through its own process handle, never by name, and the call fails as a network error. Failures whose stderr says the host could not be reached (no such host, i/o timeout, connection refused or reset, no route) are network errors too.
  • Error kind. storage::NetworkUnavailable, made with storage::network_unavailable(what, detail) and recognised with storage::is_network_error(&anyhow::Error) (also true for a connection-kind std::io::Error in the chain), marks a failure of the network as opposed to a refusal, a missing object or a bad object. It is the one classifier: it also recognises the health layer's StorageDown, ureq timeouts and failed connections, and the messages listed in 79.1 (HTTP 502/503/504, dial tcp, ...); a short read (UnexpectedEof) is not a network error, because a damaged local file gives it too. The health layer (79.1) counts these, not refusals, towards "this storage is offline".
  • Joining. A typed host name resolves with a 5 s limit; the bundled storages are checked in parallel with 8 s in all.

79.3 The service and the local API while offline

The interface, the tray, the command line and MCP never wait behind network work.

No network I/O under the state lock. The service's state (desktop::State) is one lock. Work that may talk to a storage, a peer or the update site takes the engine and the service's own state out of it (a checkout): the sync round with its peer-record refresh, ledger guard and upkeep, the watch tick for new devices, publishing the peer record, the 30-second disk check with the mailbox and the moves, and every API route that works on the engine (/api/sync, /api/status, /api/files, /api/upload, downloads, the viewer, thumbnails, MCP calls). Meanwhile the shared state holds busy: what has the engine, since when, and the service's summary from when it started. The engine goes back when the work is done (also on an early return or a panic), and between the upkeep steps, so a request waiting for it gets its turn. Routes that set up or drop the engine (unlock, lock, init, join, reset, pairing) wait until no job has it out.

What answers at once. The host and token checks use values copied at start, never the lock. /api/service and /api/state answer from the state with the summary from before the job, with "busy": "<what>"; /api/state still says unlocked. Pause, lock, quit, restart, the interface language, the update settings and check, the pairing join status, the providers and the log settings run on threads of their own (not the API worker) and never wait for a job: a pause asked for meanwhile is applied when the job hands the engine back; a lock answers "pending": true, drops the pairing offer and the exported copies at once, and the keys go the moment the engine comes back. Reads of the cached routes (spec section 71) get the last answer while the engine is out; with nothing kept they get 503 {"busy": "<what>"} after 2 seconds instead of waiting; the page shows its "busy" line. Other requests wait for the engine up to 5 minutes, then get the same 503.

Liveness. GET /api/alive (with the token) is answered by the dispatching thread before any state is looked at: {"ok", "pid", "version", "busy"}. service::status asks /api/service within 5 seconds and, when that gives no answer, /api/alive within 3 seconds: a refused connection means not running, an answer from the same pid means running but busy. The command line, the tray and the MCP server therefore never open the vault beside a busy service or start a second one.

Jobs. POST /api/sync runs with the engine out of the state; with {"background": true} (and always for an MCP key) it only asks the service for a round and answers {"queued": true}. A sync asked for by hand (the API, varsto sync) first ends the rest of every storage (79.1). /api/upload receives the body with neither the lock nor the engine held: into the block cache for a folder kept encrypted here, else into a spool file under upload-spool/ in the device directory; only then is the engine taken to put the file in place, and a sync is asked for. GET /api/update/check runs curl with --connect-timeout 10 on a thread of its own and keeps its answer for an hour (a failure for 10 minutes); the daily automatic update and varsto update use the same connect timeout. POST /api/update starts the install on a thread of its own and answers at once; GET /api/update/status says state (checking, installing, done, failed), latest, updated and message, and the service restarts after an installed update as before.

MCP. The MCP server was removed and is not part of the program. The MCP server's calls to the service give up after 30 seconds; the service waits at most 25 seconds for the engine and answers busy, which the assistant hears as "Varsto is busy right now; try again in a minute". An MCP key's reads use the read cache (kept per key). GET /api/mcp/scope needs no engine.

After a failed sync. When a round fails (offline, a storage out of reach), the upkeep that works on this device's own disks or only adds still runs: the mailbox, the scheduled backup snapshots (not their expiry), restic, the move jobs and the disk suggestions. Ledger rebuilds, verification, the bit-rot check, repair, forwarding, drains, trash and backup expiry wait for a round that reached every storage: with a storage missing, its blocks would look lost. Forwarding, drains and moves each run as one sync round of the engine (79.1), so their ledger pulls are one. The watch tick backs off to a minute after a failed device check. A round that returns per-folder errors (PullReport.error, storages_down) sets the service's last_error to the folders not synced; /api/status carries storages_down, and the page shows "Storage X cannot be reached; it is tried again at HH:MM".

The mailbox. A run no longer needs a ledger pull first: the pull is best effort, a failure is a note in the report ("the storages could not be reached; worked from the ledger as last pulled"), and the docked disks are staged from and written to as before. A failed run records the docked disks, so the 30-second disk check does not run it again until a sync or a disk change.

Tests: desktop::tests (a job with the engine out: the summary, the state, /api/alive, pause, the language and the update settings answer within 1.5 s, a read with nothing kept is 503 busy, the pause applies afterwards; a lock asked for meanwhile takes the keys when the engine comes back and a restart asked for meanwhile is kept), readcache::tests (a miss while busy says busy after the wait; something kept is sent at once), service::tests (the upkeep after a failed sync; a refused connection versus a slow one), update::tests (--connect-timeout, the kept check answer and the kept failure, the background install with its status and the restart) and crates/varsto-core/tests/mailbox.rs (a hub that cannot be read does not stop the staging; not due again for the same disks).

79.4 Local actions

A local action finishes with what is on this device when a storage cannot be reached; the storages catch up on the next sync. import_run pulls its folder best effort and imports locally; its blocks go to the storages that answer, and a storage that cannot be reached is left out like a pool without its disk (an import needs at least one storage that answers). trash_list falls back to the cached trash and trash_list_checked returns a note that it may be stale. A thumbnail lookup that misses stamps its pull throttle also when the storages fail, and a failed pull is no error for the caller. write_file, create_file, move_file and commit_staged return after the local change; when the upload fails the PushReport has upload_pending (the reason) and the next sync or push uploads (a removed device, a forked ledger and a paused folder still fail). The restic child can be given a wall-clock limit with VARSTO_RESTIC_TIMEOUT_SECS (unset or 0: none); a run past it is killed and reported as an error. Tests: crates/varsto-core/tests/offline_local.rs, restic::tests.

81. Torrents through a local transmission daemon

Why. A torrent can be far larger than the disk of the computer that downloads it (a 2 TB archive on a laptop with 200 GB free). The data should go straight into a storage (an S3 bucket, later perhaps a disk pool through varsto move) with the local disk used only as a spool that never runs full, and with the certainty that every file of the torrent ends up stored. Varsto does not speak BitTorrent itself: a local transmission-daemon downloads, and Varsto decides which files it downloads when. Code: crates/varsto-core/src/transmission.rs (the RPC client, the metainfo and magnet parsing, and transmission::fake, an in-process daemon for tests), engine/torrent.rs (jobs, the planner and the step) and crates/varsto-cli/src/torrent.rs. Linux only; the command line refuses elsewhere. User guide: docs/torrents.md. Format 3 (section 77): the job uses the local-directory import (section 42) and its removal rule unchanged, and reads storage copies from the pack-level ledger view and the folder's block map. Nothing of a job is published: jobs are device state, and the vault sees an ordinary folder with an import book.

RPC. JSON over HTTP, POST to http://127.0.0.1:9091/transmission/rpc unless --rpc-url or VARSTO_TRANSMISSION_URL names another; HTTP Basic sign-in with --rpc-user/--rpc-password or VARSTO_TRANSMISSION_USER/_PASSWORD. A request without the current X-Transmission-Session-Id is answered 409 with the id to use; the client keeps it and sends the request again (also after a daemon restart). Methods: session-get (download-dir, incomplete-dir-enabled), torrent-add (metainfo as base64 or filename with a magnet link, download-dir, paused: true, files-unwanted with every index), torrent-get (ids: [<info hash>], fields id, hashString, name, totalSize, pieceSize, files, fileStats, status, percentDone, downloadDir, error, errorString), torrent-set (files-wanted with priority-normal, files-unwanted, downloadLimited/downloadLimit), torrent-start, torrent-stop, torrent-verify and torrent-remove (delete-local-data: false). Torrents are always named by their info hash, never by the daemon's numeric id. An empty files-unwanted list in torrent-set means every file; the client never sends an empty list by accident.

A job is state/torrents/<info hash>.json (written atomically), with the torrent file's copy <info hash>.torrent (or the magnet link in the job) and a lock file <info hash>.lock (flock): one step of a job runs at a time, whether the command line or the background service runs it. The job holds hash, name, folder, storages (the placement the job set, cheapest resolved), existing_folder, verify_existing, free_min (as given), download_dir (<download dir>/<info hash>), folder_parent, rpc_url, rpc_user and rpc_secret (the password is kept in the device's encrypted secret store, secrets.enc, under transmission:<info hash>), state (adding, metadata, downloading, checking, waiting_space, waiting_policy, paused, complete), text, user_paused, stopped_for_space, verify_pending, piece_size, files ({index, path, size, done, outcome}, outcome one of stored, present, identical, conflict), batch (indices in flight), batch_bytes, batches, bytes_stored (files the job stored), bytes_deduped (present and identical files), reserve_bytes, free_bytes, need_bytes, the last 20 errors ({utc, text}, a repeated one once), last_error, last_retry_utc and completed_utc. Missing fields read as their defaults. Nothing in it is the source of truth for what was stored: every step reads transmission's state, the folder's state and its import book again.

Adding (varsto import torrent <file.torrent|magnet:…> [--folder F] [--storage S… | --storage cheapest] [--free-min 15%] [--download-dir DIR] [--min-copies N | --keep-policy] [--verify-existing]). Torrents are an import source of varsto import (beside git-annex, rclone and local directories); the jobs are varsto import torrent-jobs …. The folder defaults to the torrent's name (import::folder_name_from; a magnet link's dn, else the info hash). The info hash is the SHA-1 of the bencoded info dictionary (or the magnet link's xt=urn:btih:, hex or base32); a file name with an empty, . or .. component or a component starting with .varsto refuses the torrent. Refused as well: a job for the torrent exists; transmission has the torrent already (it must be added by Varsto, with nothing wanted); the daemon keeps unfinished data in an incomplete-dir (another disk); an unknown storage name; cheapest together with storage names; --storage with an existing folder. Then the job's directory is made. An existing folder F (not removed, not a backup) takes the directory as a source: its import book, created with kind dir when the folder has none, gets the identity dir:<job directory> added and is saved and published (Engine::import_adopt_dir); a book of another kind (git-annex, rclone) refuses the job. An import of nothing (section 42, kind dir, identity dir:<job directory>) then creates the folder, attached selectively under the folder root, with its import book, or continues the existing one (attached selectively under the folder root when it is not attached here); that import refuses a download directory that is, holds or lies inside a Varsto folder or the device directory, and a new folder name that holds other data. --storage sets the new folder's placement (section 23). --storage cheapest is resolved once, here, by Engine::cheapest_storages(N) with N the --min-copies value (1 with --keep-policy): the configured storages that are neither transferrers nor cold nor drained, with a known price per GB-month (Engine::storage_price: the user's figures, else the built-in price data), the N cheapest, ties by name; refused when fewer than N have a price or when the priced storages use more than one currency (a literal storage named cheapest is a storage name). A folder created here gets the policy min_copies: N (default 1) unless --keep-policy: the default policy (section 14) asks for a copy on the user's own devices or disks verified by another device, which a folder kept only in a bucket never meets, and the removal rule below needs the policy to hold. Present files are marked (step 2 below), the job is saved (adding), then the torrent is added stopped with every file unwanted, all files are set unwanted once more (files-unwanted: []) and it is stopped. A magnet link's file list is not known yet: the torrent is started with a 50 kB/s download limit (metadata); when torrent-get lists files, the job stops it, sets every file unwanted (transmission wants all of them on arrival), lifts the limit and records the files.

A step (Engine::torrent_tick):

  1. torrent-get. A torrent the daemon lacks is added again as above (the error is recorded). An error (error 1 tracker warning, 2 tracker error, 3 local error) is recorded; a torrent stopped by a local error is started again once a minute, its batch kept: a file is retried, never skipped. While transmission checks data (status 1 or 2) the step ends.
  2. Done files. A file is done and stored when the folder's import book has a removal record for its path (section 42) and the folder's state has the path, not deleted, with the torrent's size. Newly done stored files set verify_pending. Then, unless verify_existing, a file that is not done becomes done and present when the folder's state holds its path, not deleted, with the torrent's size, and nothing (no file, no directory, no link) is at its path in the job's directory: it is never downloaded. The second condition keeps a file the job downloaded itself (and which may still wait for the policy) from being taken for one.
  3. Compare and import. Empty files are created in the job's directory when missing (transmission may not make them). The files transmission reports complete (bytesCompleted equal to the length: every piece was checked against the torrent's SHA-1 piece hashes) that are not done and are regular files on disk are taken one by one. When the folder's state holds the path (not deleted) and the book has no import of this file's id (dir:<size>:<mtime ns>:<path>) under the folder's content hash, the folder's version came from elsewhere: the downloaded file's keyed content hash (BLAKE3 keyed with the folder's hash key, as a scan computes it) is compared with the folder's. Equal: when the folder's version is safely stored (Engine::stored_problem, the removal rule below applied to the folder's file) the download is removed and the file is done and identical, otherwise it waits (its reason is the job's text); different: the file is done and a conflict, the folder is not changed and the download stays. Every other complete file is imported with Engine::import_run from a local-directory source restricted to exactly those paths (CompletedFiles, the files being written and .part files are never listed), selectively, with remove_source, and then Engine::import_cleanup(folder, apply): a file is removed only when its SHA-256 still matches what was imported, the folder holds it with that content, every block has a live place in a pack held by a storage that is not a transferrer (storages3::block_copies over the ledger view and the folder's block map), one copy was read back intact, and the folder's policy holds for its blocks. Files that do not qualify yet stay (their reason is the job's text) and are imported again as nothing new on the next step. Done files are recorded and the job is saved before anything is said to transmission. The command line pauses the background service during the import.
  4. Unwanted. Every done file transmission still wants is set unwanted; with verify_pending, torrent-verify makes transmission check its data again, which forgets the pieces of removed files (it would otherwise offer them to peers and fail to read them, and refuse to start a torrent whose data is all gone: "No data found"). The step ends there.
  5. Complete. When every file is done, the job checks again that every file but a conflict is in the folder with the torrent's size, that every stored one has a content hash the book imported under the SHA-256 its removal recorded, and that every block of each has a copy on a storage that is not a transferrer (as in step 3); then it stops the torrent, removes what transmission may have written into the places of done files other than conflicts (pieces reaching across two files are written whole) and the empty directories, the job's directory included when it is empty, and sets complete. Conflicts and anything else in the directory are not touched; the job's text names the conflicts.
  6. Paused by the user: the torrent is stopped and the step ends.
  7. Space. The free and total space of the download disk are measured (freespace::space_at). The reserve is the larger of --free-min (a share of the file system or an amount, default 15 %) and section 53's minimum: 5 %, or the limit of an attached folder or directory storage on the same file system (same device number) when larger.
  8. The batch in flight (files wanted, not yet complete): when the free space is below the reserve and data is left to download, the torrent is stopped (stopped_for_space, waiting_space, need_bytes = what is missing); a stopped batch goes on only when the free space covers the reserve plus what the batch still has to download. Otherwise the batch's files are wanted and the torrent runs.
  9. The next batch, when none is in flight: the candidates are the files that are neither done nor complete, in torrent order, each with its remaining bytes (length - bytesCompleted, so a file half downloaded before a restart needs only the rest). plan_batch takes them in order while the batch fits in free - reserve, where a batch costs its files' remaining bytes plus two pieces for every run of files that follow each other in the torrent's data (files without data between them; a piece reaching into a neighbouring file is written whole), and stops at the first file that does not fit, so files arrive in order and a large file is never passed over for smaller ones. An empty plan stops the torrent and waits (waiting_space, with what the first file needs). Otherwise the batch is saved, its files are set wanted (priority-normal) and the torrent is started. Files downloaded but waiting for the policy hold their space and are not downloaded again; when nothing else is left the job waits (waiting_policy). Conflicts hold their space until the user moves them.

Crashes and restarts. Each step derives what is done from the import book and the folder state, and what is downloaded from transmission. A crash after the import and before removal imports nothing again (the ids are in the book, and the comparison of step 3 recognises the job's own import) and removes on the next step; a crash after removal and before transmission was told sets the files unwanted and verifies on the next step; a crash while adding finds the torrent missing and adds it again. A step that fails records the error and leaves the job as its last saved state; import torrent-jobs run tries again after its interval.

Running. varsto import jobs run <job> [--interval 5] [--once] steps a job until it is complete; the background service steps every job that is neither complete nor paused once after each sync (an upkeep step after staged moves, skipping a job whose lock is held) and every 20 s in between while its state is free, on Linux, and notifies once when one waits for disk space and when one is complete. varsto import jobs status [job] (with the files that were present, identical or in conflict), list, pause, resume, remove [--keep-in-transmission] (the job's files and secret go; the folder and anything not stored stay; the torrent is removed from transmission without its data unless kept). varsto import jobs is one command for torrent and YouTube jobs (section 82): a torrent job is torrent:<info hash>, or its info hash or a prefix of 6 or more characters, its folder or its name when no YouTube job has that name too (else the command asks for the prefix). The Import page (section 42, Import page and the job list) adds torrents and shows, pauses, resumes and removes them. varsto status and varsto import status print a line per job that is not complete (import status <folder> only that folder's); import status and import verify describe a torrent folder as the dir import it is. The Help page (help.rs) has an attention line and a step "Make room for torrent job …" while a job waits for space, and an attention line and a tip for a week after one completed; English, Finnish and Swedish.

Seeding. transmission seeds what it has on disk: a file stored and removed is unwanted and forgotten by the re-check, so it is no longer offered. A torrent spooled this way is seeded only while each batch is on the disk.

Limits.

  • Linux only (the command line, the background service and the Import page).
  • "Present" is decided by path and size; --verify-existing downloads and compares instead. Content the folder holds under another path is downloaded again (its blocks are deduplicated when stored, so nothing is uploaded twice).
  • An existing folder's import book lists the job's last batch as the source's file list (section 42 keeps one list per book); import status of such a folder describes that batch.
  • A new folder has no recovery copy (section 77) until varsto recovery escrow, as with varsto import.
  • The reserve is measured between steps (every few seconds under import jobs run, every 20 s and after each sync in the service); a disk filled faster than that by something else can fall below the reserve before the torrent is stopped. Data transmission keeps in memory or preallocates beyond a file's length is not counted.
  • The two pieces per run are an estimate of what transmission writes outside the batch's files; with piece sizes much larger than the reserve leaves room for, a batch may not fit at all and the job waits.
  • After a re-check, pieces shared with removed files are forgotten and downloaded again with the next file that needs them (a little extra traffic).
  • A magnet link may download some data before its file list arrives and every file is set unwanted (at 50 kB/s for a few seconds). Magnet links need a v1 info hash; BitTorrent v2-only torrents are not supported.
  • The download directory must be a local path that the daemon and Varsto both use, and the daemon must run as the same user as Varsto (it writes files Varsto removes).
  • The folder is a normal folder afterwards: moving it to a disk pool is varsto move (section 59).

Tests: transmission::tests (metainfo and magnet parsing, the 409 handshake and a new session id after a restart, sign-in refused and accepted, add with every file unwanted, duplicates, start, download, remove, against the fake daemon), engine::torrent::tests (the planner: order, the reserve, pieces at run edges, resumption with what is left; with the fake daemon and a simulated small disk: added stopped with every file unwanted and the placement set; refusals of a download directory in the device directory or a folder and of a torrent the daemon has; a batch wanted, completed, imported, removed and unwanted with the data checked again; a crash after the import and one after the removal carried on by a new engine without importing or removing twice; free space falling below the reserve mid-batch stopping the torrent until there is room for the rest; no room for the first file; a local error reported and retried once a minute; a magnet link's file list; pause, resume and a torrent removed from the daemon added again; an existing folder: same path and size not downloaded, another size a conflict that leaves the folder's file as it was, --storage refused; --verify-existing: an identical file removed after the folder's copy is safe, a different one a conflict; a folder with a git-annex book refused; --storage cheapest by price, with the refusals for no price, mixed currencies, names mixed with cheapest and an unknown storage), crates/varsto-core/tests/torrent_spool.rs (a torrent three times the room above the reserve, with an empty file, in three batches into a folder on a directory storage: every file's content, the free space never below the reserve, the download directory empty, the format 3 completion check and import verify, removal of the job), crates/varsto-cli/tests/torrent_cli.rs (add, run to completion, list, status, varsto status, remove through the binary), and the lab scenario torrent-spool (scripts/test/lab/scenarios.py: a real transmission-daemon seeding a generated 2 GB torrent on one VM, another downloading it through a 512 MB tmpfs with a 20 % reserve into the lab's S3 bucket with --storage cheapest, polling df, then a second torrent over the same files plus new ones added to the same folder, whose present files are never downloaded).

82. YouTube channels through yt-dlp

Why. People archive channels by hand: list the channel with yt-dlp, then download one video at a time, slowly, and move the files somewhere safe. Varsto does the same with the user's own yt-dlp, stores every video in a folder (encrypted on the storages), keeps the download disk above a reserve, and never downloads a video the vault has. Only for content the user may keep a copy of (user guide: docs/youtube.md).

Addresses. crate::youtube::parse_source_url accepts youtube.com (with www., m., music.) and youtu.be: a channel (/@handle, /channel/<id>, /c/<name>, /user/<name>, with the tab videos (also for none and featured), shorts, streams (live) or playlists), a playlist (/playlist?list=<id>) or a video (watch?v=, youtu.be/, /shorts/, /live/, /embed/, /v/, or a bare 11-character id; a watch address with a list is the video). The canonical form (https://www.youtube.com/@handle/videos, .../playlist?list=<id>, .../watch?v=<id>) is the job's identity; a second job for the same canonical address is refused. A video id is 11 characters of A-Z a-z 0-9 - _.

A job. state/youtube/<job id>.json (16 random hex digits): the canonical address, kind and label, the folder, the storages, the reserve (free_min as given), the spool <download dir>/<job id>, the folder parent, the yt-dlp program (--ytdlp-path, else VARSTO_YTDLP, else yt-dlp on the PATH), the throttle, thumbnails and subtitle languages, the refresh interval in hours (0: list once; always 0 for a video), the state and a sentence about it, the last listing time and listing failures, the videos (id, title, url, status pending | downloaded | stored | already_stored | failed | gave_up, attempts, next_try_utc, last_error, size_estimate, probed_utc, paths, bytes, found_in), the yt-dlp run in flight (kind list | probe | download, video, PID, start), the reserve and free space at the last step, the bytes missing, the last 20 errors. <job id>.lock (flock) holds a job while one step changes it: the command line and the background service both drive jobs. Job states: listing, probing, downloading, waiting_space, waiting_policy (downloaded videos wait for the folder's policy and nothing else is to download), waiting_retry (only failed videos left), paused, up_to_date (everything stored; listed again after the refresh interval), complete (refresh 0).

Adding. Engine::youtube_add checks the address and the extra arguments, resolves --storage (names, or cheapest: the min_copies non-carrier storages with the lowest known storage_per_gb_month from Engine::storage_price, an error when none has a price), creates the spool, and runs an import of nothing from the spool (below) into the folder, attached selectively under the folder parent: that creates the folder and its book and refuses a spool inside the device directory or an attached folder, and a folder name that holds other data. A folder whose book is only a YouTube index (below) may be named: the job continues it. The folder gets the placement (storages) and, when it was created, the policy min_copies N (default 1; --keep-policy keeps the default policy).

yt-dlp runs. Three kinds, each with the job's --cookies-from-browser and extra arguments (-o, --output, -P, --paths, --exec, --batch-file, -a, --load-info-json, --yes-playlist, --no-continue, --force-overwrites and --config-locations are refused), the address after --, stdout and stderr to <spool>/.varsto-work/logs/<list | probe-<id> | download-<id>>.{out,err}:

  • listing: --flat-playlist --ignore-errors --no-warnings --print "%(id)s\t%(url)s\t%(title)s". Lines without a valid id take it from the address; duplicates keep the first. New ids are appended as pending; nothing is ever dropped from the list. A listing that exits non-zero with no video is a failure: retried with the backoff below, the videos listed before carry on;
  • probe: --skip-download --no-playlist --no-warnings --sleep-requests N [--format F] --print "%(filesize,filesize_approx)s": the expected size (NA: unknown, 0). A failing probe is a failure of the video. A probe is used for six hours;
  • download: --sleep-interval MIN --max-sleep-interval MAX --sleep-requests N [--limit-rate R] --concurrent-fragments N --ignore-errors --no-abort-on-error [--format F] ... --no-playlist --write-info-json --no-write-playlist-metafiles --no-progress --newline [--write-thumbnail] [--write-subs --sub-langs L] -o "<spool>/.varsto-work/%(id)s.%(ext)s". Defaults: 25-65 s, 2 s, 600K, 1 fragment. Success is a media file <id>.<ext> in the work directory (not .part, .ytdl, .temp, .tmp, .part-Frag* or .fNNN. streams before merging); its siblings <id>.info.json, thumbnails (jpg, jpeg, png, webp), subtitles (vtt, srt, ass, lrc, ttml, srv3) and other json/description files are kept too. They move to <channel>/<YYYY-MM-DD> <title> [<id>]<suffix> in the spool: channel from the info file's channel, uploader, channel_id or uploader_id (else the job's label), the date from upload_date (left out when unknown), the title from the info file (else the listing); /, \ and : become -, control characters spaces, runs of white space one space, leading dots go, the channel is cut at 100 bytes and the title at 150 (on character boundaries), an empty one becomes unknown channel / untitled.

The background service starts a run and leaves it; later steps poll it (this process's child by PID, else whether the PID lives). A run whose process this process did not start and that is gone is interrupted: a listing that printed nothing and a probe are made again (lines a listing printed count), a download is taken in when its media file is there and otherwise tried again without counting a failure. The command line waits for each run. While a download runs and the disk falls below the reserve, a run this process started is stopped by its PID (never by name); the part stays and yt-dlp continues it later (--continue is its default).

A step (Engine::youtube_tick, one action, saved after each part): (1) the run in flight: still running (stopped for space, see above), or ended and taken in; (2) the videos in the spool that are downloaded are imported with the import of section 42, the spool as a youtube source restricted to those paths, remove_source, selective; then the import's cleanup removes each file that is in the folder, has every block on a non-transferrer storage, was read back from one, meets the folder's policy, and whose SHA-256 is still what was imported, with the spool's current listing of those paths as the file list (not the book's tree, which another device may have replaced). A video whose files have all left the spool and are in the folder is stored; one whose files left the spool otherwise (removed by hand) is pending again; (3) paused: nothing more; (4) a listing when none succeeded yet, --retry-failed asked for one, or the refresh interval passed since the last one (and any backoff of a failed one); (5) the vault's YouTube index (below) is read and every pending or failed video in it becomes already_stored with where it is; (6) the next video, in list order, that is pending or failed with next_try_utc passed: when the free space of the spool's disk is below the reserve, waiting_space with the bytes missing; else a probe when there is no fresh one; else its download when estimate + estimate/20 - bytes already in the work directory for it fits above the reserve, else waiting_space naming the video; (7) with nothing to start: waiting_policy, waiting_retry, up_to_date or complete.

The reserve is the larger of the job's (--free-min, default 15 %) and Varsto's own minimum (section 53, 5 % by default) of every attached folder and directory storage on the same filesystem.

Failures. A failed probe or download records yt-dlp's reason (the last ERROR: line without the extractor and id prefix, else the last line, at most 300 characters), counts an attempt and waits 3600 * 4^(attempts-1) seconds, at most a week. The sixth failure makes the video gave_up. varsto import jobs resume and varsto import jobs run --retry-failed make failed and gave_up videos due again (with at most five attempts counted); --retry-failed lists again too.

The import book and the index. A YouTube job's folder has a book (section 42) of kind youtube, identity youtube:<canonical address> (two devices following one channel fill one folder), content ids youtube:<video id>:<suffix> (.mkv, .info.json, .en.vtt), the SHA-256 of what was read (for the cleanup). The book gains a field youtube: video id to the folder paths of that video, filled when a content id of that form is imported, merged by union. varsto import youtube-scan <folder> (attached here) records every file of the folder named ... [<id>] followed by . or the end with the folder's book, publishing it; a folder that has no book gets one with an empty kind that holds only this list (import status, verify and cleanup leave such books out; a source never matches them). varsto import youtube-scan <directory> (outside Varsto) records the ids with their paths in state/youtube/known.json, on this device only. Engine::youtube_index: the youtube lists of every live folder's book (after merging every device's records), the file names of every folder attached here, and known.json.

Commands and service. varsto import youtube <address> [--folder N] [--storage S|cheapest]... [--free-min 15%] [--download-dir DIR] [--rate R] [--sleep MIN-MAX] [--sleep-requests N] [--concurrent-fragments N] [--format F] [--cookies-from-browser B] [--extra-arg A]... [--thumbnails] [--subs LANGS] [--min-copies N | --keep-policy] [--refresh-hours N] [--ytdlp-path P] [--no-run] (then steps the job in the terminal until it waits, unless --no-run), import jobs list, import jobs run [JOB] [--retry-failed], import jobs status [JOB] [--videos], import jobs pause|resume|remove JOB (the job file goes, empty spool directories go, files in the spool stay), import youtube-scan <folder or directory>. import jobs is one command for YouTube and torrent jobs (section 81): a YouTube job is youtube:<id>, or its id or a prefix of 4 or more characters, its folder, label or address when no torrent job has that name too; run without a job works on every YouTube job until it waits and steps every torrent job once; --json gives the uniform rows of the job list for list and the job with job (its id in the list) and job_kind otherwise. The command line pauses the background service while it imports. The service steps every running job after each sync and every 20 s in between while its state is free (desktops only: not on Android or iOS), notifies once when a job starts waiting for space, and varsto status prints a line per job that is not complete.

Status and verify. A youtube book's file list (tree) is not replaced by each run's listing (the spool holds only the videos of the moment): each run adds its paths, nothing is counted gone at the source, and books of other devices add up (union) instead of the newest list winning. So varsto import status and varsto import verify <folder> (section 42) cover every video file a job imported.

Interface. The Import page (section 42, Import page and the job list) adds a job (with the toggle between one video and the whole channel or playlist, and the throttle under Advanced) and shows every job with its counts, the video in hand, the videos already stored and the failed ones with their reasons, with Pause, Resume, Try failed videos again and Remove.

Not done. Jobs run one after the other, one video at a time each. The index is consulted before each video, so two devices running the same channel at once may both download a video neither has stored yet.

Tests: crates/varsto-core/src/youtube.rs (addresses and ids, file names, throttle arguments, the flat listing, names in the folder, kept files, backoff and reasons), crates/varsto-core/src/engine/youtube.rs (task arguments, failures to given up, job states), crates/varsto-core/tests/youtube_jobs.rs (a fake yt-dlp serving a five-video channel: one private video failing with backoff without stopping the job, one already in another folder never probed or downloaded, a step that dies after a download and before the import (nothing downloaded again), a download that stops halfway and is continued, a later listing that brings only the new video, waiting for space before a video and for its size, the service mode leaving yt-dlp running and stopping it when the disk fills, scans of a directory and a folder, a scanned folder taking a job), crates/varsto-cli/tests/youtube_cli.rs (the commands through the binary). Lab: scenario youtube-spool in scripts/test/lab/scenarios.py.

83. The rendezvous service

Code: crates/varsto-core/src/rendezvous/ (proto.rs the wire formats, shared word for word with the server through #[path]; keys.rs the derivations and seals; client.rs HTTP, the control channel and the relay stream; mod.rs publish, fetch and pairing helpers), crates/varsto-core/src/p2p/rendezvous.rs (the runtime the service keeps: control connection, record writes, lookups, observes, the punch and relay routes), crates/varsto-core/src/pair.rs and pair/v3.rs (offers registered there, joining through it), crates/varsto-rendezvous (the server: registry.rs, control.rs, udp.rs, relay.rs, limits.rs, http.rs, selftest.rs, main.rs). Operator guide: docs/rendezvous.md. No stored format changes: the blobs are the format-3 peer records of section 75, sealed once more.

83.1 Why

Connecting devices across networks was nearly impossible. Pairing had no route beyond the LAN without a typed reachable address (section 68, "Not done"); the peer relay needed a publicly reachable device in the vault (sections 15 and 75: "there is no vendor relay"); a device learnt the others' addresses only from the storages, so with every storage unreachable a device that moved networks was lost; and STUN alone leaves two symmetric NATs, or a network that blocks UDP, without a path. The rendezvous is one small service where the devices of a vault meet: they leave their sealed peer records there, ask it to coordinate a simultaneous punch and, as the last route, splice their pinned TLS sessions through it. It is additive (section 79): LAN discovery, direct routes, punching on STUN addresses, peer relays and the storages work exactly as before without it; every call has a short timeout and runs in the background, and a failure is logged, never shown as an error that stops anything. Pairing still works LAN-only with no internet.

83.2 Shape

One process, everything in memory with TTLs (no database; after a restart clients write their slots again within minutes). HTTP and WebSocket on one TCP listener (behind a TLS proxy such as Caddy, on 127.0.0.1:<port>), one UDP socket on a public port. The default service is https://varsto.net/rv; anyone can run their own (varsto-rendezvous, a static musl binary in the daily build as varsto-daily-rendezvous-linux-x86_64). On a device: p2p.rendezvous in config.json, a base URL, https://varsto.net/rv when the key is missing, null when the user turned it off; varsto p2p rendezvous set <url> | --off | status. A base URL must be https://; plain http:// only to a loopback or private address (a server on the same LAN), or anywhere in a process started with VARSTO_RENDEZVOUS_PLAIN_HTTP=1 (only the lab sets it: its test internet has no TLS proxy). VARSTO_RENDEZVOUS (off or a base URL) overrides the setting for one process.

Routes. Every route answers with and without the /rv prefix, so the server works behind Caddy's handle_path /rv/* (which strips it) and handle /rv/* (which keeps it); a client appends the paths below to its base URL.

Route Method Body / answer
/info GET Info (JSON)
/health GET one text line of counters
/v1/put POST PutSlot → PutAnswer
/v1/delete POST DeleteSlot → {}
/v1/lookup POST Lookup → LookupAnswer
/v1/control GET, WebSocket the control channel, JSON text frames
/v1/relay/<token> GET, WebSocket one side of a relay session, binary frames

A refusal over HTTP is {"error": <code>, "message": <text>} with the status of its code: bad_request, bad_signature and version 400, too_large 413, stale and tag_full 409, not_owner 403, rate_limited 429, not_found and not_observed 404, unavailable 503. Every answer carries Cache-Control: no-store. Lookups are POSTs so that a tag never appears in a URL or a proxy's access log. Every message carries v: 1; a server answers another version with version.

83.3 Identifiers and derivations

Lengths in bytes. derive3(K, p) is the format-3 derivation (context e2ee-sync-format/3/<p>, section 77), aad3 its AEAD framing. K3₀ is the vault key of epoch 0 (Engine::root_key), which every full device keeps for good, so devices at different epochs agree.

  • Vault tag (16): keyed_hash(derive3(K3₀, "rendezvous-tag"), vault id as text)[..16]. The same on every device of the vault; not linkable to the vault id or to the LAN beacon tag (another purpose).
  • Device slot (16): keyed_hash(derive3(K3₀, "rendezvous-slot"), device id16)[..16].
  • Owner key of a device's slot: Ed25519 from the seed blake3::derive_key("e2ee-sync-format/3/rendezvous-owner", K6 secret bytes || tag). Only that device can make it; it is stable across restarts; it is not K6, so the server cannot link it to the device registry. A pairing offer uses a fresh random Ed25519 key.
  • Peer blob: XChaCha20-Poly1305(derive3(K3₀, "rendezvous-blob"), aad3("rendezvous-blob", [tag, slot]), postcard(parts)), random 24-byte nonce in front, where parts is the peer record exactly as peer::publish writes it to a storage ([(storage name, bytes)], normally one part). The outer seal hides the envelope's plain header (vault id, device id) and the storage name; the record inside is signed by K6 and sealed under the registry key, and is checked by the same acceptance rule as one read from a storage (section 77.8). At most 128 KiB: a format-3 record part is padded to at least 64 KiB of body plus its envelope (about 68 KiB for a peer record).
  • Pairing tag by code and its key: out = Argon2id(password = the nine digits, salt = "varsto-rv-pair/1", m = 19 MiB, t = 2, p = 1, 32 bytes); tag = out[..16], key = blake3::derive_key("e2ee-sync-format/3/rendezvous-pair-key", out).
  • Pairing tag by link token: the offer draws a random 16-byte token, carried in the pairing link and QR code as rv=<32 lowercase hex> (section 51); tag = blake3::derive_key("e2ee-sync-format/3/rendezvous-pair-token-tag", token)[..16], key = blake3::derive_key("e2ee-sync-format/3/rendezvous-pair-token-key", token || digits).
  • Pairing blob: XChaCha20-Poly1305(key, aad3("rendezvous-pair-offer", [tag]), JSON PairOffer), PairOffer = {v: 1, addrs: ["host:port", …] (at most 16, best first as section 68 ranks them), expires (Unix s), relay (the offering device holds a control connection with this slot claimed)}.

Why the code tag is slow. A pairing code has 10⁹ values. A fast hash of the digits (the lead's first sketch, hash("varsto-pair-3-rv", digits)) would let the server recover the code from the tag in seconds and then, holding the code, sit in the middle of a relayed SPAKE2 exchange. With Argon2id at the OWASP minimum (about 40 ms on a laptop and 150 ms on a phone, once per offer and once per join) trying every code costs on the order of 10⁷ CPU seconds per offer, inside the offer's ten minutes. The link-token path gives the server nothing about the code at all, and is tried first when the joiner scanned a link. Both stay behind SPAKE2's own protection (an active attacker gets one guess per attempt, three attempts per offer) and the six-word fingerprint confirmation on the offering device (section 75).

83.4 Registry: slots, ownership, expiry

The registry maps tag → (kind, slots) and slot → (owner key, blob, last ts, expiry). Kind peer (a vault's devices: at most 64 slots per tag, TTL at most 48 h) or pair (one slot, all zero; TTL at most 600 s). A tag's kind is fixed by its first slot.

  • Put (/v1/put): {v: 1, kind: "peer" | "pair", tag: 32 hex, slot: 32 hex, owner: 64 hex, ts: Unix s, ttl: s, blob: base64url without padding, sig: 128 hex}. sig is Ed25519 by owner over the fixed string "varsto-rv/1 put\0" | kind (1 byte: peer 1, pair 2) | tag (16) | slot (16) | owner (32) | ts (u64 LE) | ttl (u32 LE) | BLAKE3(blob) (32). Checked in this order: version; blob at most 128 KiB; 0 < ttl ≤ the kind's maximum; a pairing put names the zero slot; |ts − now| ≤ 300 s; the signature. Then: an absent or expired slot is created when the tag has room and is of the same kind (else tag_full); a live slot takes the write only from the same owner key (else not_owner) and with a ts above its last one (else stale: a write cannot be replayed even inside the window, and a client writes at most once a second per slot). Expiry is now + ttl. Answer {expires, created}. Global bounds (default 200 000 slots and 1 GiB of blobs): past them unavailable.
  • Delete (/v1/delete): {v, tag, slot, owner, ts, sig}, sig over "varsto-rv/1 delete\0" | tag | slot | owner | ts (u64 LE); the owner only, ts inside the window and not below the last write.
  • Lookup (/v1/lookup): {v, tag} → {kind, slots: [{slot, ts, expires, blob}]}, sorted by slot. An unknown tag answers an empty list, never "no such tag". Owner keys are not returned.

Write authorisation without membership. The server cannot know who belongs to a vault. A slot belongs to the key that first wrote it; a vault device's slot comes from its device id under K3₀ and its owner key from its own K6 secret, so a stranger can neither find a slot nor overwrite one, and one vault device cannot overwrite another's. The blob proves nothing either way: readers accept only records that pass the acceptance rule.

83.5 Observe over UDP

An observe is a STUN Binding Request (RFC 5389, 20-byte header) with, optionally, one attribute 0xC056 (comprehension-optional range) of 16 bytes: the control connection's UDP token. The answer is a Binding Success Response with XOR-MAPPED-ADDRESS = the datagram's source. A request over 64 bytes, a malformed one, any other STUN message and anything that is not STUN get no answer. A token of a live control connection records the source as that connection's observed address, with its time; an unknown token is answered like plain STUN and recorded nowhere. The server never sends a datagram nobody asked for; an answer is 32 bytes for IPv4 and 44 for IPv6.

Clients never assume a UDP port: the endpoints come from /info (udp: ["host:port", …]; the default is port 3334 (not 17893, the devices' own peer-to-peer port, so a server can run beside a device), and --public-udp-addr announces another). While its control connection is up a device sends an observe with its token from its QUIC socket every 25 s, through the STUN side channel of section 60 (the same transaction-id gate), so the answer refreshes the NAT mapping and the server's view of it, and replaces the dependency on public STUN servers for the address. The p2p.stun list stays as the fallback and for the NAT guess (two servers are still needed to tell cone from symmetric).

83.6 The control channel

GET /v1/control, a WebSocket of JSON text frames (at most 16 KiB each), tagged by t:

  • server → client, first: {"t": "challenge", "v": 1, "nonce": 64 hex, "time": Unix s};
  • client → server: {"t": "hello", "v": 1, "claims": [claim, …]} (at most 8), then any of {"t": "claim", "claims": […]}, {"t": "unclaim", "slots": [[tag, slot], …]}, {"t": "punch", "id": u32, "tag", "slot"}, {"t": "relay", "id", "tag", "slot"}, {"t": "ping", "id"};
  • a claim is {tag, slot, owner, sig}, sig by the slot's owner key over "varsto-rv/1 claim\0" | challenge (32) | tag | slot | owner. The server takes it when the signature verifies over this connection's challenge and the registry says owner owns that live slot, so a claim cannot be replayed on another connection;
  • server → client: {"t": "welcome", "udp_token": 32 hex, "claimed": [[tag, slot], …]} after hello, claim and unclaim; {"t": "punch_go", "id": u32 | null, "tag", "slot", "peer": "ip:port"}; {"t": "relay_ready", "id", "token"}; {"t": "relay_offer", "token", "tag", "slot"}; {"t": "pong", "id"}; {"t": "error", "id": u32 | null, "error": code, "message"}.

Nothing but hello may come first. Zero claims are allowed (a joining device). The newest connection that claimed a slot holds it; a closed connection's claims go with it. A connection that sends nothing for 90 s is closed (clients ping every 25 s). Messages the server cannot deliver because a connection does not read are dropped (64 queued at most), and a connection that has lost more than 16 of them is closed. The server sends a WebSocket ping every 30 s (proxies close silent connections; any answer or message resets the 90 s idle timer).

Who may reach whom. A punch or relay naming a pair tag is allowed from any connection: finding the tag took the code or the link. One naming a peer tag is allowed only from a connection that holds a claim under the same tag, that is, from a device of the same vault; otherwise not_owner. The target slot must be live and held by another connection, else not_found.

Punch (asker A, target slot B): A observes (83.5) and sends punch. The server needs a fresh (at most 120 s old) observed address for both connections, else not_observed. It sends A punch_go {id, tag, slot of B, peer: B's observed address} and B punch_go {id: null, tag, slot: B's own claimed slot, peer: A's observed address}. Both then do what section 15 does when punching: VARSTOPU datagrams to the peer address every quarter second for up to three seconds while A dials QUIC to it, pinned to the certificate of B's accepted peer record. Neither side trusts the server's address beyond trying it: the pinned handshake decides. The server hands out only addresses it observed itself, never ones a client supplied, so a punch cannot be aimed at a third party.

83.7 The relay

The last route, after LAN/direct TCP, QUIC with punches, a server-coordinated punch and a peer relay. A sends relay {tag, slot}; the server creates a session with two one-time random 16-byte tokens, answers A relay_ready {token_a} and tells B relay_offer {token_b, tag, slot}; both open GET /v1/relay/<token hex> (WebSocket) within 15 s, and the server splices the two streams (binary frames of at most 64 KiB). Inside runs the existing peer transport unchanged: A is the TLS 1.3 client pinning B's certificate and B the server admitting only certificates of its directory (section 75, p2p::v3::tls over a Read + Write stream instead of a TCP socket), so the server carries only TLS records, end-to-end encrypted, of devices it cannot identify. For pairing the joiner is A and the offerer B, and the SPAKE2 exchange of section 75 runs on the stream as on a TCP connection.

Limits: 4 MB/s per session and direction (--relay-rate, announced in /info), at most 4 sessions at once per tag and 1 000 in all, a token works once and expires after 15 s, and a session that moves nothing either way for 300 s ends (the pairing exchange waits up to five minutes for the person at the offering device). Two further caps keep the relay from becoming a file host: all sessions together move at most 32 MiB/s (--relay-total-rate, 0 for no cap; unused capacity is not saved up beyond a quarter second), and one tag moves at most 4 GiB per hour through the relay (--relay-tag-bytes; a session ends when its tag's window is spent, and a relay request of a spent tag is answered rate_limited until the next window). --no-relay or a rate of 0 turns the relay off (relay: false in /info, and relay requests answer unavailable).

83.8 Rate limits, sizes, /health and /info

Token buckets per client address (IPv6 counted by its /64) and per tag, per minute: puts 60 per address and 120 per tag, lookups 120 and 240, control connections 20 per address (at most 32 open per address and 50 000 in all), punch and relay requests 60 per address and 60 per tag, relay streams 60, observe datagrams 600, info and health 120. Bodies at most 192 KiB, blobs 128 KiB (a client reads a lookup answer of at most 64 slots of them; the server writes that answer out in small pieces and does not assemble it whole), control frames 16 KiB, relay frames 64 KiB, observe requests 64 bytes. A lookup bucket for an address holds only a few tokens at a time and refills to the per-minute rate, so one address cannot open a whole minute of lookups at once. Behind a proxy on the same host the client address is the last X-Forwarded-For entry (the one the proxy added), and only when the connection comes from loopback (--no-trust-proxy turns that off).

On SIGTERM or SIGINT the server stops accepting, tells every control and relay connection to close and exits when they have, or after --grace seconds (5). Every option is also read from the environment as VARSTO_RV_<NAME>. --self-test starts a private server on loopback and plays two devices against it (info, register and lookup with a refused overwrite, observe, control claims, a relayed stream, /health), exit status 0 when all pass. Logs go to stderr without timestamps; at info they are start, stop and one totals line every 10 minutes (the /health counters plus dropped, slow_closed, quota_stopped), never a tag or an address; at debug a connection may be logged with a salted per-process hash of its address.

/health answers one line, ok v=1 up=<s> tags=<n> slots=<n> pair=<n> control=<n> relays=<n> relay_bytes=<n> udp=<n> refused=<n> limited=<n>, with no per-tag detail.

/info answers {v: 1, server: "varsto-rendezvous <version>", udp: ["host:port", …], relay, limits: {max_blob, max_slots_per_tag, peer_ttl_max, pair_ttl_max, replay_window, relay_rate, relay_idle, relay_per_tag}, time}. A client fetches it first and keeps it for an hour, takes the UDP endpoints only from there, and says in its status when its clock is more than 300 s from time (its writes would be stale).

83.9 What the client does

  • Peer records. After each publish of its peer record (section 77.8), and at least every 6 h, the service writes the same record (sealed as in 83.3) to its slot with a TTL of 48 h. Seq rule: the device keeps the highest seq it gave its record anywhere and a hash of that record (own-peer-seq.json in its home); the rendezvous copy reuses that seq when the record did not change since (it is then the record the storages hold), and takes the next one when it did (no storage took the change yet); a storage publish starts above both the storage's highest record and that seq, so a record written later is never shadowed. The slot is written whether or not the storages answered: a device whose storages are all away still tells its peers where it is. Signed timestamps are in the server's time (our clock corrected by the offset seen in the control channel's challenge), so a device with a wrong clock still writes; the status still reports an offset beyond the replay window. At start and every 3 minutes it looks the vault tag up, opens every blob, hands the parts to the acceptance rule and merges the accepted records into the saved directory like a storage that answered (newest seq per device; a blob that does not open or a record that fails is skipped and counted). So a device whose storages are all unreachable still learns where its peers moved.
  • Control and observe. While unlocked, with peer-to-peer and the rendezvous on, the service keeps one control connection with its own slot claimed (and an open pairing offer's slot), reconnecting after 5 s and doubling to 5 minutes; it observes every 25 s from the QUIC socket (and at once on a new connection) and puts the observed address first in udp_public of its record; a new observed address makes the record go out again. A punch_go naming its own slot makes it punch towards the asker for three seconds; a relay_offer for its slot is taken and served by the TLS responder exactly as a TCP connection (only certificates of its directory are admitted). The process setting can be overridden with VARSTO_RENDEZVOUS (off, or a base URL): the command-line tests turn it off, the lab points it at its own server.
  • Route order towards a peer: LAN/direct TCP → QUIC to the record's addresses with punches → QUIC after a server-coordinated punch → a peer relay (relay_via) → the rendezvous relay. The two rendezvous routes are offered only while the control connection is up with the device's slot claimed (the punch also needs an observed address of at most 120 s and a QUIC node; the relay a server that offers one), so with the rendezvous off or down nothing is tried or waited for. A relayed TLS session is kept for 20 s for the next request; requests to one peer share at most two relayed sessions at once (the server allows four per vault) and the others wait their turn. varsto p2p status, GET /api/p2p and the Peers page show relayed via rendezvous, the observed address and the rendezvous state (URL; connecting, on, off or unreachable). GET /api/p2p carries it as one object, rendezvous: {url (the setting, null = off), default_url, enabled, state, observed, last_error, clock_skew, relayed_peers, slots_seen, relay_sessions}; POST /api/p2p takes rendezvous_on and rendezvous_url (empty or default: the default service).
  • Pairing. pair offer opens the LAN listener as before and, in the background, registers the offer under the link token (the link gains rv=) and the code tag with an ephemeral owner key, and holds a control connection with both claimed; a relayed session for them runs the offer's exchange as a LAN connection does (the same three attempts, the same approval). Deviation from the first design: a code tag that is taken (tag_full or not_owner) is skipped rather than drawing a new code, because the code is shown at once and registration runs in the background; the link token still finds the offer, and the typed code still works on the LAN. Such a clash needs two open offers with the same nine digits. The offer is withdrawn when it is taken, declined, cancelled or expires. pair join (and the interface's form, rv in POST /api/pair/join) with a code tries the typed address, the link's addresses, the LAN search (section 68), then looks the token or the code up, tries the offer's addresses, and last asks for a relay to the offer's slot with a control connection that claims nothing (a punch is of no use to the TCP pairing listener). A device that joins has no settings yet: it asks the service the link's rvu= names (an offer at a self-hosted server; rvu in POST /api/pair/join), else the default service or the one VARSTO_RENDEZVOUS names; VARSTO_RENDEZVOUS=off turns the lookup off even for a link that names a server. A typed code alone finds an offer at a self-hosted server only when the joiner's VARSTO_RENDEZVOUS names that server. A wrong code or a decline ends it at once, as on the LAN. The offering side shows "works across networks" while its offer is registered.

83.10 What the server sees

The server learns: tags (random-looking 16-byte values, one per vault and one or two per open pairing offer), slots (one per device), owner public keys that are not device keys, the sealed blobs with their sizes and timing, the IP addresses and ports of every request, observe and relay, which connections punched or relayed with which (so which addresses belong to one vault, and when they talk), and relayed byte counts. It never learns vault ids, device ids, device names, any key of the vault or of a device, the peer records' contents (addresses, certificates, heads), file names or content. It keeps nothing on disk and logs no tags or addresses (at debug level a connection may be logged as a salted per-process hash of its address). There are no accounts, no e-mail addresses and no tracking.

83.11 Honest limits

  • The operator sees which IP addresses form a vault and when they talk; a VPN hides that from it as from anyone. Tags do not rotate, so one vault's addresses can be followed over time.
  • A device removed from the vault still holds K3₀: it can compute the tag and slots and open the outer seal (not the records inside, which are under a newer registry key after a removal), and it can keep claiming its own slot. It cannot write another device's slot: owner keys come from each device's own K6 secret.
  • An operator who wants a pairing code from the code tag pays the Argon2 cost above; with enough hardware within ten minutes it could, and could then try to sit in the middle of a relayed pairing. The six-word fingerprint check on the offering device and SPAKE2's key confirmation are the protection then, as on a LAN.
  • A server that lies (drops writes, serves stale or foreign blobs, refuses relays, hands out wrong addresses) can only deny service: every record is checked and every connection pinned, and the other routes stay.
  • The device sockets are IPv4 (the QUIC socket); the server answers IPv6 observes.
  • Memory: the defaults bound the registry at about 1 GiB of blobs and each rate-limit class at 200 000 buckets. A flood of fresh source addresses fills only that class's map and is refused until the next prune of that class. The UDP observe port does not check the source, so its flood must not use up the maps that admit new TCP clients. A lookup answer is not buffered whole, and an address's lookup bucket never stores a whole minute of tokens.

83.12 Tests

rendezvous::proto::tests (puts, deletes and claims round trip through JSON and verify; forged, other-key, changed-TTL, old, future, oversize, wrong-version and wrong-slot puts refused; fixed signed-byte layouts; hex fields refuse wrong lengths and upper case; control messages round trip, oversize frames and too many claims refused; observe requests and answers for IPv4 and IPv6; junk datagrams get no answer; the health line; pairing offers bounded), rendezvous::keys::tests (one vault's devices agree on tag and slot, other vaults and keys differ; a peer blob opens only for its vault and slot and hides the names; owner keys per device and tag; pairing tags by code and by token agree, seal, and refuse the wrong code; token parsing), rendezvous::client::tests (base URLs with and without a prefix; plain http only to loopback or LAN), the server's unit tests (registry: the first writer owns, only newer writes, expiry frees a slot, tag bounds and kinds, memory caps, owner-only delete, forged puts, a lookup answer is written in bounded chunks; limits: buckets refill, IPv6 by /64, per tag, a full observe map does not block other classes, a lookup address cannot spend its minute at once; udp: answered with the source, tokens recorded only when known, junk dropped; control: claims need the owner's signature over this connection's challenge, hello first, a punch tells both sides, strangers cannot reach a peer slot but may reach a pairing offer, relays per tag capped; relay: tokens work once and expire, per-tag cap, two duplex streams spliced both ways, an idle session ends, the rate cap holds), crates/varsto-rendezvous/tests/http.rs (register, a stolen slot, a forged put, lookup with and without /rv, a pairing offer and its clash, delete, an oversize body, UDP observe and junk, /health, 429), tests/ops.rs (replay window both ways, a replayed put or delete, other keys refused, kinds kept; slots swept after their TTL with the registry bytes back to zero; per-tag and per-address buckets independent; server pings and a stop with an open connection closes it within the grace; a spent relay quota ends the session and refuses the next one while other vaults are unaffected; random bytes into the parsers, the HTTP routes, the UDP socket and a control connection, after which the server still answers), tests/load.rs (400 tags and 4 000 slots of 1 kB, 100 held control connections and 50 concurrent relay sessions moving 256 kB each way, the registry holding exactly the blobs, no leaked sessions, resident memory growth bounded at 300 MiB for client and server together; --ignored runs 10 000 slots and 1 000 control connections within 600 MiB), the relay unit tests for the global throttle and the tag quota, the http unit test that a connection that does not read is cut off, selftest::tests (the self-test passes), and tests/client_e2e.rs (the core client: two devices publish and fetch, another vault sees nothing, a stale rewrite, pairing offers by token and by code, a clashing code, withdrawal; control channels with claims, a claim made for another challenge refused, a coordinated punch with observed addresses, a stranger refused, a 300 kB relayed stream both ways, a used token refused, ping); on the client, crates/varsto-core/tests/rendezvous.rs with real engines and the server in-process (records written to the rendezvous only reach a device that asks no storage and merge into its saved directory, a record moved to another slot is not taken, the seq rule; a coordinated punch reaches a peer whose record has no address, over the address the server observed; a pull of every block through the relay, labelled relayed via rendezvous, and a device the directory does not name gets nothing through it; pairing through the relay by link token and by code, the LAN asked first, the offer withdrawn after; a wrong code finds nothing; with the rendezvous unreachable a pull from the storages, a pull from a LAN peer and LAN pairing work as before), pair::tests (the join order with a rendezvous: typed, link, LAN search, the offer's addresses, the relay; an offer without a control connection is not relayed), qr::tests (rv= round trip, malformed or repeated rv= refused) and p2p::tests (route order with both rendezvous routes).

84. A pull copies the blocks this device already has

A pull fetches from a peer or a storage only the blocks it cannot find on this device. At the first download or deletion of a pull (in a folder whose files are plain on this device; a folder kept encrypted here has its block cache, section 10), before either changes anything, the engine indexes the blocks of every file of the folder state whose local index entry has the recorded version's content hash and size (a pull with nothing to fetch builds no index): chunk id -> (file, offset, size), by the first 8 bytes of the id, at most 4 places per block, about 24 bytes per block in memory and nothing else. Each block of a file to download is then taken from, in order:

  1. the copy fetched ahead for small files (prefetch_small, which no longer fetches a block that is here);
  2. a file here that lists the block: the previous version of the same file (a changed file fetches only its changed blocks), another file of the folder (a renamed or moved file, a copy), a file this pull has already written, or the part of the file being written that is done (a block the file repeats);
  3. the staging area of a disk fetch plan (section 59);
  4. peers, then storages, in a window as before (section 15); a run fetched together ends at the next block that one of the above has.

A block read here is used only when its plaintext hashes (the folder's keyed hash, K11) to its chunk id; the index is never trusted. A source is opened only when it is a regular file (O_NOFOLLOW, O_NONBLOCK, the opened file the same as the one looked at) whose real directory is under the folder's directory (or under the folder's trash directory, below), so a link put in place of a file or a directory after the scan is not followed out of the folder. A source that cannot be read or whose block fails the check is dropped for the rest of the pull and the block is fetched instead. Nothing in the storage format or the ledger changes: a block copied here is written, counted as held and announced (chunk_on_device, the manifest's held) exactly as a downloaded one.

Deletions do not take sources away: a file that a pull deletes goes to the device's trash (<home>/trash/<folder>/<path>.<time>, section 7) and its blocks are read from there by the files written after it (the other half of a rename whose deletions are applied first). A file that a conflict moves to its conflict copy is read at its new name. A file replaced by a newer version is no source of its old blocks after the replacement. Chunk ids are keyed per folder, so blocks are found only within the folder being pulled.

Directories are not synced: when a deletion leaves the directories above the deleted file empty, they are removed up to the folder's directory, so a directory renamed on another device leaves no empty directory behind. A directory that still holds anything (an ignored file, a placeholder) stays.

PullReport.chunks_reused_local and bytes_reused_local count the blocks and bytes copied here; they are not in chunks_downloaded and bytes_downloaded, which count what came over the network (of that, chunks_from_peers and bytes_from_peers from peers). POST /api/sync returns them with the rest of the pull report.

Tests: engine::local_blocks::tests (a block read and checked, a changed file dropped, a file moved to the trash read there, a link at the file or in place of a directory not followed), crates/varsto-core/tests/pull_reuse.rs (a changed 400 kB file fetches only the blocks its push stored; a renamed directory fetches nothing with every block gone from the storage and leaves no empty directory, also with the deletions applied first, from the trash copies; duplicate files and a file that repeats itself fetch each distinct block once; a local copy changed without its size or time changing is not used and the file arrives right).