What it brings
Keep one person's devices in step (bookmarks, history, settings, notes) peer to peer, with nothing readable by a relay or server, and with a revoked device locked out of everything written after the revocation. Apps keep their record types and their storage; the crate brings the clock, the log, the merge rules, the keys and the protocol over weirdnet-net.
What it is
Sync between one person’s devices over weirdnet-net: a hybrid logical clock, an append-only per-node op log, last-writer-wins registers, OR-set merge, tombstone garbage collection, pages sealed under a typed SyncKey, a device roster with self-issued node certificates and revocation, the /weirdnet/sync/2 pull protocol, and (0.4.0) records too big for one page, split into hash-checked chunks, and sealed records that a device revoked before a write cannot open.
Record types (bookmarks, history, settings, notes) and persistence stay in the application; OpLog is the in-memory log it snapshots.
How it works
The log and the merge rules
Each node appends ops to an OpLog stamped with a hybrid logical clock (Hlc: physical time, a
counter and the node id), so a later write orders after everything the node has seen even when its wall clock is behind. Ops
carry an app-defined type and record id; the bytes are the app's.
- Fields are last-writer-wins by HLC (
lww). - Sets are observed-remove (
OrSet): concurrent adds of different elements keep both; a concurrent add and remove of the same element keeps the add; a remove strictly later than the add wins. The same rule settles edit against delete. - Tombstones may be collected after 90 days, and only once every known peer cursor is past the delete; losing versions may
be kept 30 days for the app's UI.
folder_cyclecatches moves that would make a folder its own ancestor.
The protocol
/weirdnet/sync/2 (/1 before 0.5.0), length-prefixed CBOR, one request and reply at a time: Hello /
HelloOk or Refuse, Pull, Page, Ack, Roster, and (0.8.0) the lease messages. A session is
accepted only from a node with an unrevoked NodeCert for the same user. Pulls ask for one type, and positions are
kept per (node, type), so pulling one type never skips another. A server answers only up to what it holds completely, and
after a pull the puller's clock moves past the newest op it holds. Payloads with records, cursors or certificates are
sealed.
Keys and revocation
- Before any rotation,
SyncKey(type) = HKDF-SHA256(seed, salt = user id, info = weirdnet-sync/v1/<type>), and pages are XChaCha20-Poly1305 sealed with associated data binding the type, epoch and asking peer. - Rotation on revoke (0.3.0): every device holds the identity seed, so no seed-derived key can shut a device out.
SyncState::revoketherefore makes a fresh random epoch key and seals a copy to each remaining device'sDeviceKey(an X25519 key derived from its node key and signed by it). Rotations are signed by their creator and travel in the roster's key chain; concurrent rotations settle on one head. After a rotation only the head key carries data, and a device that missed it gets the roster back and catches up. - Re-admission: a device restored from the recovery words gets a new node key and reports
needs-admission(KeyStatus::NeedsAdmission) until a member device admits it (SyncState::admit, orapprovebefore its key is known; compareDeviceKey::fingerprinton both screens). - The first rotation starts by itself once two devices are linked and all have device keys
(
auto_first_rotation);devices_without_keylets an app warn before a revoke. 0.3.1 fixes two devices that both started the first rotation splitting into two chains, and revoking the device that made the first rotation no longer drops the whole chain. - Epoch keys (
EpochKeys) are secret: store them encrypted (export/import). The chain is public and stored with the roster.
Large and sealed records (0.4.0)
Ops carry small values inline. SyncState::write takes a record value of any size up to
Limits::record_max (default 16 MiB) and stores it as follows.
- Chunks: a value over
Limits::inline_max(default 32 KiB) is split intochunk_sizepieces (default 48 KiB). Each piece is addressed by its BLAKE3 hash and stored as an entry of the companion type<type>#chunks; the record itself carries only the list of hashes and the length. A type's chunks are pulled right after the type (Limits::eager_chunks, on by default) or on demand withpull_chunks, and are served wherever the type is.SyncState::readreassembles the value only when every chunk, the length and the whole hash match, and otherwise returnsRecordValue::Pendinglisting the missing chunks. - Sealed records: a type configured with
RecordOptions { sealed: true, .. }seals every value under its own key, derived from the head epoch key and bound (as associated data) to the type, record id, epoch, rotation and writer. A device revoked before a write cannot open it, even holding the seed and every older key; members keep older epoch keys, so values sealed before a rotation stay readable, andreseal_stalecan re-seal them under the head key. Nothing is sealed under seed-derived keys (the write fails withno-epoch-key), and an unsealed entry in a sealed type is refused. - Older peers:
write_with_fallbacklets an app give a small fallback op; a 0.3 peer ignores the new field and keeps the fallback, and a plain entry keeps the 0.3 wire shape. - Page budget: a page is now budgeted for what crosses the wire (
PAGE_BUDGET; in 0.4.0 about 60 KiB, a quarter of the 256 KiBPAGE_MAX), because the sealed body is hex and, with weirdnet-net 0.7, the request-response codec sent bytes as an integer array. Before, a full page could exceed the 256 KiB reply cap and stall the stream. 0.5.0 raises the budget to 112 KiB (see below). - Caller check:
Roster::check_callersays whether the transport-authenticated caller of an app call is an active linked device of this user. A presented certificate must match the peer and user, a revoked one is refused, and a certificate the roster does not hold never admits a caller.
0.4.0 depends on weirdnet-net 0.7, whose types are in its API, so apps move to net 0.7 with it.
Moving to 0.5.0
- weirdnet-net 0.8: 0.5.0 depends on weirdnet-net 0.8, whose types are in this crate's API, so apps move to net 0.8 with it. There are no other API changes from 0.4.
- Protocol
/weirdnet/sync/2(was/1): requests and replies carry byte fields as CBOR byte strings. A 0.4 node and a 0.5 node fail to negotiate rather than fail to decode, so 0.5.0 does not talk to 0.4 peers. Upgrade every device together. - Bigger pages:
PAGE_BUDGETis now(PAGE_MAX - 16 KiB) / 2 - 8 KiB, 114,688 bytes (112 KiB; was about 60 KiB). A page is hex-sealed (2x) inside one CBOR byte string (1x), no longer four times the plaintext. A full page is about 225 KiB on the wire, under the 256 KiBPAGE_MAX, andCHUNK_MAXgrows with it. - Stored data is unchanged: op logs, records, chunks, sealed values and key chains read exactly as in 0.4. Only the network protocol moved.
The WeirdBrains relay must not store sealed pages; only a user-run node may keep them for catch-up, as an app choice. weirdnet-storage's row change log is a separate, local mechanism.
Snapshots, merge-back and partial pulls (0.5.1)
A node's SyncHandler answers from the same Arc<Mutex<SyncState>> the app pulls into. Holding that
lock for a whole pull stops the node answering, and two nodes pulling from each other at once then wait on each other until the
request times out. pull_from_shared(&state, &node, peer, &addrs, typ) avoids that: it takes a
SyncState::snapshot(), pulls into it without the lock, and folds it back with SyncState::merge_back, also when
the pull failed part-way.
merge_back(&snapshot) is for apps that keep their own copies too (it replaces the deprecated
take_keys_from). It keeps everything the state learned or wrote meanwhile:
- the roster merges as on the wire: a revocation on either side wins, and an active copy in the snapshot never un-revokes a device; the epoch is the higher one and the key chain merges;
- epoch keys and the adopted root come across, then any key the merged chain seals to this device;
- log entries it lacks are integrated (
OpLog::integrate, so chunks and sealed values read back), peer and per-type cursors move to the further of the two, and the clock moves past both; - types, record options and the device stay the state's own. Write locally to the shared state, not to the snapshot.
It returns a MergeOutcome with the entries, keys and revocations it took.
A pull applies and acks page by page, so if a later page is refused, the network drops or the closing rotation fails, the
earlier pages stay applied and their cursors moved. pull_from keeps its signature and returns only the error;
pull_from_outcome and pull_from_shared return a PullOutcome { applied, error } (non-exhaustive)
with the count either way, so an app can show progress and retry from where it stopped.
Several types in one session (0.8.5)
pull_types(&mut state, &node, peer, &addrs, &["ymir.pool", "ymir.context"]) pulls several record
types from one peer in one session: one Hello (and at most one roster swap) for all of them, then each type's
Pull, Page and Ack. pull_types_shared does the same on a snapshot, as
pull_from_shared does for one type.
- Each type's requests are sealed under that type's own key, so a service device's scoped keys work as with
pull_from. Since 0.8.5 a server refuses aPullsealed under another type than the one it asks for (type-mismatch). - It returns a
PullTypesOutcomewith onePullOutcomeper type, in the order asked (get,applied,is_ok). A type the peer refuses fails alone and the others still pull:type-not-grantedoutside a service device's grant,type-offwhere the peer does not sync it. A service device does not ask for a type outside its own grant; that type comes backtype-not-grantedwithout a request. - Nothing changes on the wire: a server answers each request on its own, so a 0.7.1 or 0.8.0 to 0.8.4 peer serves a
pull_typessession too, with oneHello.
A device linked elsewhere (0.5.2)
Before 0.5.2 a node answering a pull listed only revoked certificates, so a device linked on another device (no revocation and no rotation, so no epoch change) reached the rest only by luck, and a pass could finish without error while the new device stayed unknown. Since 0.5.2 the answer lists every certificate, and a puller whose peer lacks one of its certificates sends it the roster. Old and new nodes still talk both ways: older nodes merge the extra certificates as before, and a 0.5.2 puller hands an older peer its roster on each pass (one small request).
The identity store (0.6.0)
Every app with linked devices keeps the same things: the user key seed, its own node key and certificate, the epoch keys and the
roster. Identity stores them in one directory (0700 on Unix; seed, node.key, keys
and roster.json in 0600 files, not sealed, so apps that keep secrets in the OS keystore hold SyncState
themselves for now). Each identity announces one sync type, such as ymir.pool or bragi.app.
Identity::open(dir, typ)loads it (Noneif there is none);create(dir, label, typ)makes a new user with this device as its first node and never overwrites one.adopt(dir, node_key, seed, cert, settings, typ)takes what a device link delivered: the seed, the certificate the existing device made for this node (checked against this node and user) and that device'sLinkSettingsJSON with its roster.link_settings()andseed()are the sending side;approve(cert)adds the new device.revoke(peer)revokes and rotates the keys, but never this node's own certificate.tick(&node, &addrs)runspull_from_sharedagainst every other active device and saves. It returns aTickwith the devices reached, entries applied and each failure, so devices linked or revoked elsewhere arrive even when the type has no records.state()is the shared state for the node'sSyncHandler, androster_view()a live roster for checks such as weirdnet-agent'sRosterAuth.
The file layout is the one Ymir's membership and Bragi's identity modules used, so their stores open
unchanged. 0.6.0 also makes SyncError non-exhaustive, with Io and Identity variants: add a
catch-all arm where you match it.
Service devices and grants (0.7.0)
A server (an inference or model node) can now be linked without the seed. The user signs a DeviceGrant for it:
a class (Full or Service), roles such as ymir.inference, and the sync types it may hold.
Grants live in the roster, sync like certificates and revocations, and are how apps decide what a device may do
(Roster::roles_of, has_role); people's roles stay in weirdnet-access.
- The existing device makes the bundle with
Identity::service_bundle(peer, roles, types)(it grants and, for a device with types, rotates first, so the bundle carries keys; since 0.8.3 only type-scoped ones), sends it over a weirdnet-device-link 0.4 credential, and the server callsIdentity::adopt_service. ItsSyncState::seedisNone. - A service device with types syncs them under the epoch key and is sealed into every later rotation, so revoking it cuts it off. One with no types (a model node) is roster-only: it holds no keys and follows certificates, revocations and grants over an unsealed roster exchange (only a roster or a refusal ever goes unsealed).
- It can't admit, revoke, grant or rotate (
SyncError::NotPermitted), and rotations or admissions it signs are ignored. SecretStorelets an app keep the identity's secrets in its own store (FileSecretsis the default).
Type-scoped keys for service devices (0.8.3)
A service device with sync types holds only the keys of the types in its grant, never an epoch key. A node granted
ymir.train syncs ymir.train, votes and claims jobs, and cannot open a ymir.context page or
sealed record, whatever it is sent.
- The link bundle carries, for each rotation, the key of each granted type and its chunk type, derived exactly as a full
device derives it, so envelopes look the same on the wire. A later rotation admits the device with the new rotation's
scoped keys instead of sealing the epoch key to it (
Roster::scoped_types,EpochKeys::get_scoped). - Leases come automatically: a service device with any sync type also gets the
weirdnet.lease(LEASE_TYPE) key. Granting onlyweirdnet.leasemakes a voter that holds no data keys. - Devices serve a service peer only its granted types: a
Hello,PullorAckfor another type, and a lease request from a roster-only device, gettype-not-granted(Roster::may_sync). Full devices are not limited. - A service device granted a sealed record type (
RecordOptions::sealed) reads and writes its records since 0.8.4 (below). One not granted the type opens neither its pages nor its records. - A service device given epoch keys by an older device replaces them with scoped keys when it loads them. Upgrade full devices to 0.8.3: an older one that rotates still seals the epoch key to service devices. A service device on 0.8.2 can't use the scoped keys and needs 0.8.3.
Sealed records on service devices (0.8.4)
A record of a sealed type can be sealed under a key from the type's own key under the rotation
(scoped_record_key), which a service device granted the type holds, instead of the epoch key. A node granted
ymir.pool and ymir.context reads and writes sealed ymir.context records; one granted
ymir.train still opens none of them.
- Which key seals (
SyncState::seals_scoped): a service device always uses the type-scoped key. A full device uses it while an active service device is granted the type (Roster::service_granted), and the epoch key otherwise, so 0.7.1 to 0.8.3 devices keep reading what it writes while no service device shares the type. - Readers try both keys, so nothing changes on the wire. Every full device that reads a type shared with a service device needs 0.8.4.
- Records written before the grant stay under the epoch key. Run
SyncState::reseal_staleon a full device after syncing: besides records under an older rotation, it re-seals those that use the other key than a write would now, so the service device can open them. After the last such service device is revoked, it moves them back. - A service device revoked before a rotation gets no key for it, so it cannot open records sealed under that rotation by either scheme.
Moving to 0.7.0
Breaking: SyncState::seed is an Option<Vec<u8>>; Roster has a
grants field, KeyStatus a RosterOnly variant, Envelope a clear flag
and SyncError a NotPermitted variant. Full devices on 0.6 and 0.7 keep syncing with each other (0.6
ignores grants), but a service device needs 0.7 peers.
Leases, plans and jobs (0.8.0)
The op log is eventually consistent, so it can't give mutual exclusion. For "one device decides" (a scheduler) and "one device works on this job", 0.8.0 adds a majority-vote lease with fencing terms, and two kinds of records ordered by term instead of clock.
- Voters are the devices the user granted a role (
Voters::Role("ymir.inference"), orVoters::Peersfor a fixed set) with an active certificate. A device votes once it has aVoter(SyncState::set_voter, orIdentity::enable_voter, which keeps its terms on disk and writes each new term before granting it). - Leases (
Leases::acquire,renew,release, or anElectorthat keeps one in the background): a candidate asks every voter at once and holds the lease once a majority granted it, and stops before any voter's promise ends. A voter never grants a term twice and refuses takeovers for one lease duration after a restart. A live holder keeps the lease. Defaults: 15 s leases, renewed every 5 s, 1 % clock drift. - Fencing: every command that matters carries the lease's
Term; resources keep aFenceGuardand refuse a term older than one they have seen, so a paused or partitioned ex-holder does no harm. - Plans (
publish_plan,current_plan): one signed document per name; the newest by(term, version)from an active signer wins, whatever the clock says. - Jobs (
Jobs,JobSpec,Leases::claim_job): claiming a job is acquiring its own lease, and that term fences the attempt. When a worker dies its claim lapses and another voter resumes from the last checkpoint. - Job rules (0.8.1,
JobSpec::with_rules,JobRules): the devices that may claim a job (a role, narrowed by a candidate list), how long voters wait after a claim lapsed before another device may take it over, and a backoff after a retryable failure. Claims from other devices are ignored when folding and refused by voters. Voters grant a job its own claim time (up to an hour,MAX_JOB_CLAIM; other names keep their limits, seeVoter::with_limits) and wait out their longest grant after a restart. Under rules, only the job's owner or a full device can pause, resume or cancel it. - Pausing and notes (0.8.1):
Jobs::pauseandresume; a pause never counts as an attempt (since 0.8.2 that holds for the owner's pause even when the holder's lease ran out before it recorded its own).JobEvent::Notelets the holder keep small values (progress, where copies of a checkpoint are) without a new checkpoint, newest per key. - Lease messages travel on
/weirdnet/sync/2, sealed under the head key, so only the user's admitted, unrevoked devices take part. Change the voter set one device at a time.
Moving to 0.8.0
Breaking: SyncState has a public voter field (struct literals add voter: None) and
Message has LeaseAsk, LeaseGrant, LeaseDeny and LeaseFree
variants (exhaustive matches need arms for them). Pulls between 0.7 and 0.8 devices are unchanged; every voting device needs
0.8.
0.8.1 needs no source changes, unless you match JobEvent or JobStatus exhaustively (new
Paused, Resumed and Note). Jobs posted without rules encode and fold as in 0.8.0. Give every
voter for a job role the 0.8.1 limits before posting jobs with long claim times.
Checking callers on a serving node
A node that serves something to the user's other devices (inference, files, app calls) has to decide who is calling. The
transport tells it the caller's peer id, authenticated by Noise; the roster tells it whether that peer is one of the user's
devices. Call Roster::check_caller(profile, &user_key, &peer, presented) for every incoming stream or call:
peeris the peer id the transport authenticated (for weirdnet-net,Stream::peer()), never a value from the request body.presentedis an optionalNodeCertthe caller sent. It must name that peer and this user and verify against the user key, or the answer isWrongUser; a revoked one isRevoked.- Only a certificate the roster itself holds admits a caller. A presented certificate alone is never enough, because anyone with
the user seed (a revoked device too) can mint one: a peer the roster does not know is
Unknown. Linkedadmits.CallerCheck::reason()gives a short refusal string to send back:unknown-device,revoked,wrong-userorneeds-admission(a device not yet in the key chain's head).
Check on each new stream rather than once per connection, with the roster as it is now, so a revocation takes effect for the
next call. weirdnet-agent's serve feature does exactly this for inference
(serve::RosterAuth).
Key types and modules
Hlc,NodeId: hybrid logical clocks withtickandreceive.OpLog,LogEntry: per-node sequences, per-(node, type) cursors, pages andintegrate.lww,OrSet,edit_vs_delete,can_gc_tombstone,folder_cycle: the merge rules.SyncState,SyncHandler,start_node,pull_from: the protocol over a weirdnet-net node.SyncState::snapshot,merge_back(MergeOutcome),pull_from_shared,pull_from_outcomeandPullOutcome: pull without holding the shared lock, and keep the count of pages applied when a pull stops early (0.5.1).Roster,DeviceKey,Rotation,KeyChain,EpochKeys,KeyStatus: certificates, revocation, key rotation and re-admission.sync_key,seal_page,open_page: typed keys and sealed pages.SyncState::configure,write,read,reseal_stale,pull_chunks;Limits,RecordOptions,RecordValue: large and sealed records (0.4.0).Roster::check_caller,CallerCheck: is the authenticated caller of an app call one of the user’s linked devices (0.4.0).Identity,LinkSettings,Tick(0.6.0): the on-disk identity store every app with linked devices needs (seed, node key and certificate, epoch keys, roster), parameterised on the app’s sync type, withcreate,adoptafter a device link,approve,revokeand atickthat syncs with every linked device.DeviceGrant,DeviceClass,Roster::roles_of,SyncState::new_service,LinkBundle,Identity::service_bundle/adopt_service,SecretStore(0.7.0): device roles and seedless service devices.Voters,Voter,Leases,Elector,Term,FenceGuard,Identity::enable_voter/disable_voter(0.8.0): majority-vote leases with fencing terms, for one device that decides.SyncState::publish_plan,current_plan;Jobs,JobSpec,Leases::claim_job(0.8.0): signed plans ordered by term, and a job log with per-job claims.JobRules,Jobs::pause/resume,JobEvent::Note,LeaseLimits,Voter::with_limits(0.8.1): who may claim a job, a takeover wait after a lapsed claim, a backoff after a failure, pausing without using an attempt, and holder notes.Roster::scoped_types,Roster::may_sync,EpochKeys::get_scoped,Envelope::seal_scoped/open_scoped,LEASE_TYPE(0.8.3): type-scoped keys for service devices, and their grants enforced on every request.SyncState::seals_scoped,Roster::service_granted,seal_record_scoped/open_record_scoped,scoped_record_key(0.8.4): sealed records a service device granted the type can read and write.pull_types,pull_types_shared,PullTypesOutcome(0.8.5): several record types from one peer in one session, one hello for all of them, each type under its own key.
Feature flags
None: everything is on by default.
Usage
In Cargo.toml:
[dependencies]
weirdnet-sync = "0.8.2"Then (built and run against the published crate when this page was made):
// The merge rules underneath linked-device sync: hybrid logical clocks, LWW and an OR-set.
use weirdnet_sync::{Hlc, Lww, NodeId, OrSet, lww};
fn main() {
let (laptop, phone) = (NodeId::new("laptop"), NodeId::new("phone"));
let t1 = Hlc::tick(None, 1_000, laptop.clone());
// The phone's clock is behind, but it has seen t1, so its next write still orders after it.
let t2 = Hlc::receive(None, &t1, 900, phone.clone());
assert!(t2.strictly_later_than(&t1));
assert_eq!(lww(&t1, &t2), Lww::TakeRemote);
let mut on_laptop = OrSet::new();
on_laptop.add("rust", t1.clone());
let mut on_phone = OrSet::new();
on_phone.add("p2p", t2.clone());
on_laptop.merge(&on_phone); // concurrent adds of different tags keep both
assert!(on_laptop.contains(&"rust") && on_laptop.contains(&"p2p"));
}
Where it fits
- Builds on weirdnet-net, weirdnet-keys.
- Used by Morph (bookmarks and linked devices).
- License: BSD-3-Clause.
/weirdnet/sync/2, and does not talk to 0.4 nodes: upgrade every device together. Stored data is unchanged. 0.5.1 is additive: SyncState snapshots and merge_back, pull_from_shared, and PullOutcome; take_keys_from is deprecated in favour of merge_back. 0.5.2 fixes a device linked on one device not reaching the others in one pass (wire-compatible). 0.6.0 adds Identity, extracted from Ymir’s membership and Bragi’s identity modules (same files on disk), and makes SyncError non-exhaustive with Io and Identity variants: breaking only for code that matches it exhaustively. 0.7.0 adds service devices linked without the seed and user-signed device grants (roles, class, sync types) in the roster; it is breaking (SyncState::seed is an Option, Roster, KeyStatus, Envelope and SyncError grow). Full 0.6 and 0.7 devices interoperate; a service device needs 0.7 peers. 0.8.0 adds majority-vote leases with fencing terms, signed plans and a job log with per-job claims; it is breaking (SyncState has a voter field and Message has lease variants). Pulls between 0.7 and 0.8 devices are unchanged; every voter needs 0.8. 0.8.1 is additive: job rules (candidates, a role, a takeover wait and a retry backoff, enforced when folding and by voters), pausing and resuming jobs, holder notes and per-prefix voter limits; jobs without rules behave as in 0.8.0, and 0.7.1 sealed records read and write unchanged. 0.8.2 makes an owner’s pause spare the claim in progress even when its holder’s lease ran out before the holder recorded its own pause. 0.8.3 is additive and wire-compatible: a service device with sync types holds type-scoped keys for its granted types only, never an epoch key, so a node granted ymir.train cannot open ymir.context; devices also refuse a service peer’s requests for types outside its grant. Upgrade full devices to 0.8.3 before relying on it. 0.8.4 is additive: a service device granted a sealed record type (such as ymir.context) reads and writes its records under a type-scoped record key; full devices use that key only while an active service device is granted the type, so older devices keep reading the rest. Every full device that reads a type shared with a service device needs 0.8.4. 0.8.5 is additive and wire-compatible: pull_types pulls several record types in one session (one hello for all of them, each type under its own key), also from 0.7.1 and 0.8.0 to 0.8.4 peers; servers refuse a Pull sealed under another type than the one it asks for. 0.8.6 fixes lease terms climbing while a standby retries: a candidate that got only some voters’ grants asks for the same term again instead of the next one, so a standby retrying while a holder lives no longer raises the term by one per try; voter rules and the wire are unchanged. Version 0.8.6 is on crates.io (docs.rs). See Moving to 0.7.0 and Moving to 0.8.0 in the guide.