weirdnet-sync
Linked-device sync for Weirdnet apps: a hybrid logical clock, an append-only per-node op log, last-writer-wins registers, OR-set merge, tombstone garbage collection, page sealing under a typed SyncKey, a device roster with self-issued node certificates and revocation, and the weirdnet-sync/v1 pull protocol over weirdnet-net.
Applications keep their own record types (Morph bookmarks, Muninn notes, and so on). This crate does not know those shapes. It also does not open a database: weirdnet-storage has a separate SQL row change log (sync feature) with a three-way take/keep/conflict decision. That is useful for a local trigger log. It is not this protocol. Wrap it later if it grows to cover the HLC log, rather than forking it.
Keys
Until the first rotation, SyncKey(type) is HKDF-SHA256(seed, salt = user id, info = weirdnet-sync/v1/<type>), or weirdnet-sync/v1/<type>/e<n> after a bare revocation bumps the key epoch. <type> is an application string (bookmarks, history, settings, …). Pages on the wire are XChaCha20-Poly1305 sealed with that key; associated data binds the type, epoch and asking peer.
After a rotation the key comes from a random epoch key instead: HKDF-SHA256(epoch key, salt = user id, info = weirdnet-sync/v1/<type>/e<n>/k<rotation id>), and the associated data also binds the rotation id. The envelope names the rotation in the clear (key); seed-sealed envelopes look exactly as in 0.2.
Rotation
Every device holds the identity seed, so no key derived from it can shut a revoked device out. SyncState::revoke therefore revokes and rotates: it makes a fresh random epoch key and seals one copy to each remaining device (X25519 with an ephemeral key, then XChaCha20-Poly1305). The sealed copies travel in the roster's key chain (Roster::chain), next to the certs, in Hello, HelloOk and Roster messages.
- Each device publishes a
DeviceKey: an X25519 public key derived from its node key and signed by that node key, so no other device, not even one holding the user key, can put its own key in another device's place. Nothing new needs storing. - A
Rotationis signed by its creator's node key. It counts when the creator has an active cert and was a member of the parent rotation (the first rotation has none). A revoked creator's rotations stop counting, with everything built on them. The head is the counting rotation with the highest epoch, then one without a revoked member, then the lowest id, so concurrent rotations settle on one head. - Once a device holds a key from a first rotation it keeps that root (
KeyChain::root, local). A later root, for example one started by a seed holder with a freshly certified node, is ignored. - After a rotation only the head key carries data. Hellos and roster messages under an older or seed-derived key get the roster and chain back, so a device that missed a rotation catches up and retries;
Pullunder them is refused withepoch-behind. A peer that cannot open the head key answersunknown-key, andpull_fromsends it the roster. - A device restored from the recovery words gets a new node key and is not a member, so
pull_fromfails withneeds-admissionandSyncState::key_status()isNeedsAdmission. After the user approves it on a member device (as when linking;DeviceKey::fingerprintis a short code to compare on both screens),SyncState::admitseals the head key and the older keys it holds to the restored device's key.SyncState::approvedoes the same once the device key is known: an approved device is admitted by its first hello, and the roster reply to that hello already carries the admission, so it catches up in the same pull. Approved devices are also included in the next rotation. Old epochs stay readable; new writes use the head key. - The first rotation starts itself while every device is still trusted: once at least two devices are linked and every active device has published its device key, the one with the lowest peer id rotates at the end of
pull_from(SyncState::auto_first_rotation, on inSyncState::new; or callrotate_if_first_due). That covers both "right after the first link" and "once after upgrading from seed-only keys". Until a device has published its key, a rotation would leave it out;SyncState::devices_without_keylists such devices so apps can warn before a revoke. - If the head still includes a revoked device (revoked on a device that could not rotate), the next
pull_fromon a member rotates again.
The epoch keys a device holds are in SyncState::keys (EpochKeys). They are secret: store them encrypted (EpochKeys::export / import). The chain is public and is stored with the roster.
This is not Profile::sync_key: that derives one key from the Ed25519 secret with info weirdnet/sync/v1/key. Typed library pages use this crate.
The official WeirdBrains relay must not store sealed pages. Only a user-run node may keep them for catch-up, and that is an application choice, not something this crate enables on a relay.
Large and sealed records
An entry's op is what every version reads. Since 0.4 an entry may also carry a value (record::Value); then op is only a fallback (empty, or a preview the application passes to SyncState::write_with_fallback) and the full value is in value. Older peers skip the field and keep the fallback. A peer before 0.4 that relays an entry keeps only the fallback, so a device that gets the entry through it sees the fallback too, not a corrupted value.
Configure a type once on every device, then write and read whole values:
state.configure?; // chunk values over 32 KiB
state.configure?;
state.write?;
match state.read?
Chunks
A value larger than Limits::inline_max (after sealing) is split into Limits::chunk_size chunks, each an entry of the companion type <typ>#chunks whose record id is the BLAKE3 hash of its bytes. The entry of <typ> carries the manifest (Blob: length, whole hash, chunk hashes). A node reuses chunks it already wrote. pull_from pulls a type's chunks right after the type when an entry is still incomplete (Limits::eager_chunks, on by default); with it off, call pull_chunks when the value is needed. SyncState::read reassembles only when every chunk, the length and the whole hash match. A server serves a type's chunks wherever it serves the type; a 0.3 server refuses them and the pull carries on. Defaults: 32 KiB inline, 48 KiB chunks, 16 MiB per record; Limits::check keeps them inside a page.
Sealed records
RecordOptions::sealed seals every value of the type under a key for that record: HKDF-SHA256(epoch key, salt = user id, info = weirdnet-sync/v1/record/<type>/e<n>/k<rotation id>/<record id>), XChaCha20-Poly1305 with associated data binding the type, record id, epoch, rotation and writer node. Sealing happens before chunking, so chunks of a sealed value are ciphertext. The value stays sealed at rest in every log, not only on the wire.
- Only the head epoch key seals. Seed-derived keys are held by every seed holder, revoked or not, so a write before the first rotation fails with
no-epoch-key. - A device revoked before a write is not a member of the head rotation and cannot open the value, even holding the seed, every older key and the raw entries.
- Members keep older epoch keys and admitted devices receive them, so values sealed before a rotation stay readable.
SyncState::reseal_stalere-seals the latest value of each record still under an older key; it is optional and is a new write of the same value, so run it after syncing. A revoked device keeps whatever it could read before; change the secret itself when that matters. readrefuses an unsealed entry in a sealed type, so a seed holder cannot write around the seal. The fallback is never sealed.
Identity store
identity::Identity (since 0.6) is the on-disk identity every app with linked devices needs: the user key seed, this node's key and certificate, the epoch keys and the roster, in one directory (0700; secrets in 0600 files, plain, not keystore-sealed). It is parameterised on the one sync type the app announces (ymir.pool, bragi.app, …).
use Identity;
let me = match open? ;
let handler_state = me.state; // for start_node / SyncHandler
me.approve?; // linked from here
let tick = me.tick?; // one pass against every linked device
create never overwrites an identity. adopt takes what a device link delivers (seed, the cert the existing device made for this node, and the LinkSettings JSON with its roster) and checks the cert is for this node and user. tick pulls with pull_from_shared, so devices linked or revoked elsewhere arrive even when the type carries no records; it returns the devices reached, entries applied and per-device errors, and saves. link_settings, seed, revoke (rotates keys; never this node's own cert) and roster_view cover the rest. The file layout is the one Ymir's membership and Bragi's identity modules used, so their stores open unchanged.
Service devices and grants (0.7)
A server (a model or inference node) can join with a certificate only, never the seed, so a stolen server is never the user.
DeviceGrant: the user's signed statement of a device's class (FullorService), its roles (application strings such asymir.inference,ymir.model) and, for a service device, the sync types it may hold keys for. Signed by the user key, so only a seed holder makes one (SyncState::grant,Identity::grant); it travels in the roster (Roster::grants, inHello/HelloOk/Roster) and the newest that verifies wins.Roster::grant_of,roles_of,has_role,is_serviceread it; a revoked cert's grant counts for nothing. Use roles, not cert labels (labels are not signed), to decide what a device may call.- Linking: the seed holder calls
service_bundle(peer, roles, types)(rotating first if the chain has not started and there are types) and sends the bundle with a certificate over aweirdnet-device-link0.4 credential; the node takes it withSyncState::new_serviceorIdentity::adopt_service, which storescredential.json(the user public key) instead ofseed. Thenapprovethe certificate on the linking device as usual. - With types (an inference node): the bundle carries the epoch keys; later rotations seal to the node like to any device.
- Roster-only (no types; a model node): no data keys at all, never in the key chain. It swaps rosters with its peers unsealed (
Envelope::clear, only rosters and refusals) on every pass, which is how certs, revocations, grants and rotations reach it. - A service device cannot admit, revoke, grant or rotate (
SyncError::NotPermitted), and rotations or admissions it signs are ignored. Revoking it on a full device (revoke) cuts it off and rotates; the root identity is untouched. - Its secrets (
node.key,keys) go through aSecretStore(0600 files by default,FileSecrets; pass an OS keystore with the*_withconstructors). - A service device needs a 0.7 peer: a 0.6 device cannot open unsealed messages.
Leases, plans and jobs (0.8)
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 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");Voters::Peersfor a fixed set), with an active certificate. Only voters stand. A device votes once it has aVoter(SyncState::set_voter, orIdentity::enable_voter, which keeps its terms invoter.cborand 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 with term = highest seen + 1 and holds the lease once a majority granted it. Its handle is valid untilasked_at + duration × (1 − max_drift) − 50 msby its own monotonic clock, so it always stops before any voter's promise ends. A voter promises one holder at a time, never grants a term twice, refuses takeovers for one lease duration after a restart, and only answers candidates that count the same voter set (Voters::digest). No preemption: a live holder keeps the lease; after a lapse the lowest-ranked candidate tries first. Defaults: 15 s leases, renewed every 5 s, 1 % drift, 500 ms stagger per rank. - Fencing: every command that matters carries the lease's
Term; resources keep aFenceGuard(persistexport) and refuse a term older than one they have seen, so a paused or partitioned ex-holder does no harm. - Plans (
publish_plan,current_plan,current_plan_where): one signed document per name, versioned within a term; the newest by(term, version)from an active signer wins, whatever the HLC says. - Jobs (
Jobs::post,record,cancel,view,open, andLeases::claim_job): claiming a job is acquiring the lease<type>/<job id>; its term fences the attempt. Checkpoints, results and failures count only from the device that claimed that term. When a worker dies its claim lapses and another voter claims the next term and resumes fromJobView::resume_from. - Job rules (0.8.1,
JobSpec::with_rules(JobRules)):candidatesand aroledecide who may claim; claims from anyone else are ignored when folding and refused by voters that have the job.takeover_after_msmakes voters wait that long after a claim lapses (the holder stopped renewing without letting go) before granting it to another device, so a short network drop doesn't move a long job; the holder itself can still renew inside the wait.retry_backoff_mskeeps a job closed for a while after a retryable failure (JobView::not_before_ms;LeaseError::NotYet). Voters grant a job's ownclaim_ms(up to an hour), andVoter::with_limitssets the longest grant and takeover wait per lease-name prefix. Holders and owners can pause (JobEvent::Paused,Jobs::pause), which is neither a failure nor an attempt, and the owner resumes (Jobs::resume). Holders keep last-writer-wins notes (JobEvent::Note,JobView::notes) for progress or checkpoint copies. Under rules, only the job's owner or a full (non-service) device may pause, resume or cancel it. Jobs without rules fold as in 0.8.0, and 0.8.0 devices skip the new events. - Lease messages (
LeaseAsk,LeaseGrant,LeaseDeny,LeaseFree) travel on/weirdnet/sync/2sealed under the head key, so only admitted, unrevoked devices of the user take part. Change the voter set one device at a time and let the roster reach every voter before the next change: two candidates with different views of a voter set that changed by several devices at once could each count a majority.
Protocol
/weirdnet/sync/2, length-prefixed CBOR, one request/reply at a time (the same style as /weirdnet/link/1). After the authenticated channel is up, payloads that carry records, cursors or certificates are sealed. Messages: Hello / HelloOk or Refuse, Pull, Page, Ack, Roster, and (0.8) LeaseAsk / LeaseGrant or LeaseDeny, LeaseFree.
A session is accepted only if the peer presents a NodeCert for the same user that WEIRDNET.verify_cert accepts and that is not revoked.
A page carries at most PAGE_BUDGET bytes of ops (about a quarter of PAGE_MAX, because the sealed body is hex and the request-response codec sends bytes as an integer array), so it fits a 256 KiB reply cap on the wire. A node's log can mix record types. Pull asks for one type; pull positions are kept per (node, type) (OpLog::cursor_for), so pulling one type never skips another type's ops. Page.to_seq is the last seq the server walked, which may be past the last op it returned. A server answers only up to what it holds completely for that type: its own contiguous prefix of the node's log, or how far it has pulled that type itself. After a pull, pull_from moves the node's clock past the newest op it holds, so a later local write orders after everything it has seen. An Ack reports the puller's progress and never moves the server's own cursors.
A revocation bumps the roster epoch. A hello from an unrevoked device of the same user at an older epoch (or, after a rotation, under any key but the head's) gets the server's roster (user-signed certs and revocations, and the key chain) instead of a refusal; pull_from merges it and says hello again. When pull_from finds the server behind, it sends the server its roster. A revoked device is refused once a node holds the revocation. With seed-derived keys alone, a revoked device can still derive later keys, so exclusion rests on the session check; a rotation (see Keys) is what shuts it out of the data.
Shared state, snapshots and partial pulls
A node's SyncHandler answers from an Arc<Mutex<SyncState>>. Don't hold that lock across a pull: the node stops answering, and two nodes pulling from each other at once wait on each other until the request times out. pull_from_shared(&state, ..) takes a SyncState::snapshot(), pulls into it without the lock, and folds it back with SyncState::merge_back (also after an error). Apps that manage their own copies call merge_back themselves; it replaces take_keys_from. It merges the roster as on the wire (a revocation on either side wins; nothing is un-revoked), takes epoch keys and the adopted root and opens keys the merged chain seals to this device, integrates log entries it lacks (OpLog::integrate, so chunks and blobs are indexed), moves peer and per-type cursors to the further of the two and the clock past both, and returns a MergeOutcome (entries, keys, revocations). Write locally to the shared state, not to the snapshot.
A pull applies and acks page by page, so when a later page is refused (or the network drops, or the rotation at the end fails) the earlier pages stay applied. pull_from still returns only the error; pull_from_outcome and pull_from_shared return a PullOutcome { applied, error } with the count either way.
Merge rules
- Field values are last-writer-wins by HLC.
- Sets (tags, and similar) are observed-remove: concurrent adds of different elements keep both; a remove is a per-element tombstone and LWW against adds of that element. Concurrent add vs remove: the add wins. A remove whose HLC is strictly later than the add wins.
- The same strictly-later rule applies to edit vs delete of a record.
- Tombstones may be garbage-collected after 90 days, and only once every known peer cursor is past that delete.
- Losing versions of a conflict may be kept for 30 days for the application's UI.
Status
Published on crates.io; the current release is 0.8.1, which added job rules (candidates and roles enforced when folding and by voters, a takeover wait after a lapsed claim, a retry backoff), pause and resume, holder notes and per-prefix voter limits, all additive and readable alongside 0.8.0 and 0.7.1 devices. 0.8.0 added majority-vote leases with fencing terms, signed plans and a job log with per-job claims; SyncState has a voter field and Message has lease variants. 0.7.0 added service devices linked without the seed, user-signed device grants (roles) and a pluggable secret store; SyncState::seed is now an Option. 0.6.0 added the shared identity store (Identity) and made SyncError non-exhaustive. 0.5.2 fixed a device linked on one device not reaching the others in one pass; 0.5 moved to weirdnet-net 0.8 (protocol /weirdnet/sync/2, larger pages) and added SyncState::snapshot/merge_back and pull_from_shared. Large and sealed records shipped in 0.4, key rotation on revoke in 0.3.
See CHANGELOG.md.