← Back to Official Package Registry
Tier 6: Local-First, IoT, Web & Media • Local-First CRDTs & Presencev1.0.0 • 44 KB • Ed25519 Verified

crdt_sync@1.0.0

Hybrid Logical Clocks (HLC), PNCounter, LWW-Map, Observed-Remove Set, RGA collaborative text CRDT, state-vector sync, and room presence.

use [crdt_sync]
veko pkg add crdt_sync@1.0.0
Run in Browser PlaygroundDownload 1.0.0.vkpRaw demo.vk

crdt_sync

Pure-Veko local-first Conflict-Free Replicated Data Types (CRDTs), Hybrid Logical Clocks (HLC), Replicated Growable Array (RgaText) collaborative text sequences, binary delta sync framing, and ephemeral presence tracking (crdt_sync).

Overview

crdt_sync provides state-based and delta-capable CRDT primitives with deterministic semilattice convergence (merge(A, B) == merge(B, A), merge(A, merge(B, C)) == merge(merge(A, B), C), merge(A, A) == A):

  • Hybrid Logical Clock (HLC): Kulkarni-style causal timestamps packing a 48-bit physical millisecond wall clock, a 16-bit logical counter, and a deterministic node_id tie-breaker (new-hlc, hlc-now, hlc-receive, hlc-compare, hlc-pack, hlc-unpack).
  • Distributed Counters (GCounter, PNCounter): Grow-only and positive-negative counters using per-actor vector slots merged via pointwise maxima.
  • LWW-Element-Map (LwwMap): Key-value map where writes and tombstone deletions carry HlcTimestamp metadata and converge under a strict total order.
  • Observed-Remove Set (OrSet): Add-wins concurrent set tagging every addition with a unique (node_id, seq) dot so concurrent add + remove preserves the concurrent addition.
  • Collaborative UTF-8 Text (RgaText): Replicated Growable Array sequence CRDT operating on full Unicode codepoints (utf8), linearizing concurrent spans deterministically via pre-order traversal of the causal insertion tree without interleaving multi-character spans.
  • Sync & Ephemeral Presence (SyncFrame, PresenceRoom): CRC-32-authenticated VKCS binary sync frames carrying state-vector deltas alongside TTL-bounded room presence tracking.

Installation

powershell
veko pkg add crdt_sync@1.0.0

Import in .vk source files:

rebol
use [crdt = crdt_sync]

Architecture Notes

Hybrid Logical Clock Wire Format

hlc-pack encodes each HlcTimestamp into a compact big-endian binary envelope:

Byte OffsetFieldWidthDescription
0..6phys_ms48 bits BEPhysical Unix epoch milliseconds
6..8logical16 bits BEMonotonic logical tie-break counter
8..10node_lenuint16 BEByte length of node_id
10..endnode_idUTF-8 bytesDeterministic actor identifier

RgaText Causal Tree Linearization

Every inserted Unicode scalar value receives a unique RgaId { seq, node_id } (with seq = max_seq + 1) and references the origin_id immediately to its left (seq = 0 for document head). Merging two RgaText replicas computes the union of vertices (deleted = a.deleted or b.deleted) and linearizes the causal tree in pre-order with sibling nodes ordered by descending RgaId, guaranteeing identical UTF-8 output across all merge permutations.

Complete API Reference

Hybrid Logical Clock (HLC)

SymbolSignatureDescription
new-hlcfn [node_id str /initial-ms init_ms i64 = 0] HLCCreates a per-node HLC instance
hlc-nowfn [mut clock HLC /wall-ms wall_ms i64 = -1] HlcTimestampGenerates a monotonic local timestamp
hlc-receivefn [mut clock HLC, remote HlcTimestamp /wall-ms wall_ms i64 = -1] HlcTimestampAdvances clock past local wall time and remote
hlc-comparefn [a HlcTimestamp, b HlcTimestamp] i64Total order comparator (-1, 0, 1)
hlc-packfn [ts HlcTimestamp] bytesSerializes HlcTimestamp to binary wire bytes
hlc-unpackfn [raw bytes] HlcTimestampDeserializes HlcTimestamp from binary bytes

Counters, LwwMap, and OrSet

SymbolSignatureDescription
new-gcounter / gcounter-inc / gcounter-value / gcounter-mergeGCounterGrow-only distributed counter
new-pncounterfn [] PNCounterCreates an empty positive-negative counter
pncounter-inc / pncounter-decfn [mut pn PNCounter, node_id str /by delta i64 = 1] i64Increments or decrements actor slot
pncounter-valuefn [pn PNCounter] i64Evaluates sum(pos) - sum(neg)
pncounter-mergefn [a PNCounter, b PNCounter] PNCounterPointwise-maximum semilattice merge
new-lww-mapfn [] LwwMapCreates an HLC-timestamped LWW map
lww-setfn [mut m LwwMap, key str, value any, ts HlcTimestamp] enumWrites key if ts dominates prior entry
lww-deletefn [mut m LwwMap, key str, ts HlcTimestamp] enumTombstones key at ts
lww-get / lww-has?fn [m LwwMap, key str] any / boolReads live key (returns err if absent/tombstoned)
lww-to-map / lww-mergefn [m LwwMap] map / fn [a LwwMap, b LwwMap] LwwMapMaterializes live keys / merges replicas
new-orsetfn [] OrSetCreates an add-wins Observed-Remove Set
orset-addfn [mut s OrSet, elem any, node_id str] strTags elem with a fresh (node_id, seq) dot
orset-removefn [mut s OrSet, elem any] i64Tombstones all observed dots for elem
orset-contains? / orset-elements / orset-mergeOrSetMembership query, sorted listing, and merge

RgaText, Sync Frames, and PresenceRoom

SymbolSignatureDescription
new-rgafn [node_id str] RgaTextCreates a collaborative text replica
rga-insert-strfn [mut doc RgaText, index i64, text str] enumInserts UTF-8 span at visible rune offset
rga-delete-rangefn [mut doc RgaText, start_index i64, count i64] i64Tombstones count visible runes from start_index
rga-to-str / rga-lenfn [doc RgaText] str / i64Materializes UTF-8 text or visible rune count
rga-mergefn [a RgaText, b RgaText] RgaTextOrder-independent sequence merge
rga-state-vector / rga-delta-since / rga-apply-deltaRgaTextCausal state-vector delta extraction and application
encode-sync-frame / decode-sync-frameSyncFrame <-> bytesCRC-32-verified VKCS binary sync frame codec
new-presence-room / join-presence / heartbeat-presence / expire-presence / active-presencePresenceRoomEphemeral peer lease & TTL expiration tracker

Idiomatic Veko Example

rebol
use [crdt = crdt_sync]

mut peer_a = crdt/new-rga 'alice'
_ = crdt/rga-insert-str mut peer_a 0 'Hello World'

mut peer_b = crdt/rga-merge (crdt/new-rga 'bob') peer_a

// Offline concurrent edits
_ = crdt/rga-insert-str mut peer_a 6 'Veko '
_ = crdt/rga-insert-str mut peer_b 11 '!'

ab = crdt/rga-merge peer_a peer_b
ba = crdt/rga-merge peer_b peer_a
println (crdt/rga-to-str ab) // 'Hello Veko World!'
println ((crdt/rga-to-str ab) == (crdt/rga-to-str ba)) // true
packages/crdt_sync/examples/demo.vkSelf-contained runnable example & assertion suite
Raw .vk
// packages/crdt_sync/examples/demo.vk
// Self-contained verification suite & runnable example for `crdt_sync`.

use [crdt = crdt_sync]

assert-true = fn [cond bool, label str] enum [
	if not cond [
		println (str/join ['[FAIL] ' label] '')
		os/exit 1
	]
	println (str/join ['[PASS] ' label] '')
	.ok
]

// --- 1. Hybrid Logical Clock (HLC) Monotonicity Under Clock Skew & Binary Pack/Unpack ---
mut clk_a = crdt/new-hlc 'node-a'
mut clk_b = crdt/new-hlc 'node-b'

t1 = crdt/hlc-now/wall-ms mut clk_a 1700000001000
t2 = crdt/hlc-now/wall-ms mut clk_a 1700000001000 // same ms -> logical increments
// Peer B has clock skewed 5 seconds in the future!
tb_skew = crdt/hlc-now/wall-ms mut clk_b 1700000006000
// Peer A receives B's skewed timestamp while A's wall clock is still at 1700000001050
t3 = crdt/hlc-receive/wall-ms mut clk_a tb_skew 1700000001050
t4 = crdt/hlc-now/wall-ms mut clk_a 1700000001060

packed_t3 = crdt/hlc-pack t3
unpacked_t3 = crdt/hlc-unpack packed_t3

hlc_ok_1 = (crdt/hlc-compare t1 t2) < 0 and t2.logical == 1
hlc_ok_2 = (crdt/hlc-compare tb_skew t3) < 0 and t3.phys_ms == 1700000006000 and t3.logical == 1
hlc_ok_3 = (crdt/hlc-compare t3 t4) < 0 and t4.phys_ms == 1700000006000 and t4.logical == 2
hlc_ok_4 = (crdt/hlc-compare t3 unpacked_t3) == 0 and unpacked_t3.node_id == 'node-a'
_ = assert-true (hlc_ok_1 and hlc_ok_2 and hlc_ok_3 and hlc_ok_4) 'HLC causal monotonicity under 5s clock skew and 64-bit+node_id wire pack/unpack'

// --- 2. GCounter & PNCounter Commutativity, Associativity, and Idempotency ---
mut pna = crdt/new-pncounter
mut pnb = crdt/new-pncounter
mut pnc = crdt/new-pncounter

_ = crdt/pncounter-inc/by mut pna 'n1' 15
_ = crdt/pncounter-dec/by mut pna 'n1' 4
_ = crdt/pncounter-inc/by mut pnb 'n2' 20
_ = crdt/pncounter-dec/by mut pnb 'n2' 7
_ = crdt/pncounter-inc/by mut pnc 'n1' 10 // stale n1 count, should be dominated by 15
_ = crdt/pncounter-inc/by mut pnc 'n3' 6

pn_ab = crdt/pncounter-merge pna pnb
pn_ba = crdt/pncounter-merge pnb pna
pn_aa = crdt/pncounter-merge pna pna
pn_abc_1 = crdt/pncounter-merge (crdt/pncounter-merge pna pnb) pnc
pn_abc_2 = crdt/pncounter-merge pna (crdt/pncounter-merge pnb pnc)

// Expected net: n1 (+15, -4) + n2 (+20, -7) + n3 (+6, 0) = 11 + 13 + 6 = 30
pn_ok_1 = (crdt/pncounter-value pn_ab) == (crdt/pncounter-value pn_ba) and (crdt/pncounter-value pn_aa) == (crdt/pncounter-value pna)
pn_ok_2 = (crdt/pncounter-value pn_abc_1) == 30 and (crdt/pncounter-value pn_abc_2) == 30 and (json/encode pn_abc_1) == (json/encode pn_abc_2)
_ = assert-true (pn_ok_1 and pn_ok_2) 'PNCounter semilattice laws (commutative, associative, idempotent)'

// --- 3. LwwMap Tombstones & Semilattice Laws ---
mut ma = crdt/new-lww-map
mut mb = crdt/new-lww-map
mut mc = crdt/new-lww-map

ts_10 = crdt/HlcTimestamp { phys_ms = 1000, logical = 0, node_id = 'a' }
ts_20 = crdt/HlcTimestamp { phys_ms = 2000, logical = 0, node_id = 'b' }
ts_20_tie = crdt/HlcTimestamp { phys_ms = 2000, logical = 0, node_id = 'c' }
ts_30_del = crdt/HlcTimestamp { phys_ms = 3000, logical = 0, node_id = 'c' }

_ = crdt/lww-set mut ma 'title' 'Draft v1' ts_10
_ = crdt/lww-set mut ma 'temp' 'remove-me' ts_10
_ = crdt/lww-set mut mb 'title' 'Draft v2' ts_20
_ = crdt/lww-set mut mb 'owner' 'ada' ts_20
_ = crdt/lww-set mut mc 'title' 'Draft v2-c' ts_20_tie // node_id 'c' > 'b' tie-breaker
_ = crdt/lww-delete mut mc 'temp' ts_30_del

m_ab = crdt/lww-merge ma mb
m_ba = crdt/lww-merge mb ma
m_aa = crdt/lww-merge ma ma
m_abc_1 = crdt/lww-merge (crdt/lww-merge ma mb) mc
m_abc_2 = crdt/lww-merge ma (crdt/lww-merge mb mc)

mat = crdt/lww-to-map m_abc_1
lww_ok_1 = (json/encode (crdt/lww-to-map m_ab)) == (json/encode (crdt/lww-to-map m_ba)) and (json/encode (crdt/lww-to-map m_aa)) == (json/encode (crdt/lww-to-map ma))
lww_ok_2 = (json/encode mat) == (json/encode (crdt/lww-to-map m_abc_2)) and (crdt/lww-get m_abc_1 'title') == 'Draft v2-c'
lww_ok_3 = (not (crdt/lww-has? m_abc_1 'temp')) and (err? (crdt/lww-get/or m_abc_1 'temp' [e -> e]))
_ = assert-true (lww_ok_1 and lww_ok_2 and lww_ok_3) 'LwwMap HLC tombstones, node_id tie-breaking, and semilattice laws'

// --- 4. Observed-Remove Set (`OrSet`) Concurrent Add + Remove = Add-Wins ---
mut s_base = crdt/new-orset
_ = crdt/orset-add mut s_base 'editor' 'peer-1'
_ = crdt/orset-add mut s_base 'viewer' 'peer-1'

// Fork two replicas from s_base:
// - s_rem removes 'editor' (observing only peer-1:1)
// - s_add concurrently re-adds 'editor' on peer-2 (generating fresh dot peer-2:1) + adds 'auditor'
mut s_rem = crdt/orset-merge s_base (crdt/new-orset)
_ = crdt/orset-remove mut s_rem 'editor'

mut s_add = crdt/orset-merge s_base (crdt/new-orset)
_ = crdt/orset-add mut s_add 'editor' 'peer-2'
_ = crdt/orset-add mut s_add 'auditor' 'peer-2'

mut s_third = crdt/new-orset
_ = crdt/orset-add mut s_third 'billing' 'peer-3'

or_12 = crdt/orset-merge s_rem s_add
or_21 = crdt/orset-merge s_add s_rem
or_11 = crdt/orset-merge s_rem s_rem
or_123_a = crdt/orset-merge (crdt/orset-merge s_rem s_add) s_third
or_123_b = crdt/orset-merge s_rem (crdt/orset-merge s_add s_third)

or_ok_1 = (crdt/orset-contains? or_12 'editor') and (crdt/orset-elements or_12) == (crdt/orset-elements or_21) and (crdt/orset-elements or_11) == (crdt/orset-elements s_rem)
or_ok_2 = (crdt/orset-elements or_123_a) == ['auditor' 'billing' 'editor' 'viewer'] and (crdt/orset-elements or_123_a) == (crdt/orset-elements or_123_b)
_ = assert-true (or_ok_1 and or_ok_2) 'OrSet concurrent add + remove = add-wins and semilattice laws'

// --- 5. 3-Peer Offline `RgaText` Collaborative Editing Convergence ---
mut p1 = crdt/new-rga 'peer-1'
_ = crdt/rga-insert-str mut p1 0 'Hello World!'

// Peers 2 and 3 sync initial state 'Hello World!' and then all 3 go offline:
mut p2 = crdt/rga-merge (crdt/new-rga 'peer-2') p1
mut p3 = crdt/rga-merge (crdt/new-rga 'peer-3') p1

// Offline edits:
// - Peer 1 inserts 'Veko ' before 'World!' (index 6) and deletes '!' (now index 16)
_ = crdt/rga-insert-str mut p1 6 'Veko '
_ = crdt/rga-delete-range mut p1 16 1
// - Peer 2 concurrently inserts 'Local-First ' at index 6 (same anchor as Peer 1!)
_ = crdt/rga-insert-str mut p2 6 'Local-First '
// - Peer 3 concurrently appends ' [v1.0]' at the end (index 12) and replaces 'Hello' -> 'Hi'
_ = crdt/rga-insert-str mut p3 12 ' [v1.0]'
_ = crdt/rga-delete-range mut p3 1 4
_ = crdt/rga-insert-str mut p3 1 'i'

// Merge in 4 different permutations + idempotent self-merge!
c_123 = crdt/rga-merge (crdt/rga-merge p1 p2) p3
c_321 = crdt/rga-merge (crdt/rga-merge p3 p2) p1
c_231 = crdt/rga-merge p2 (crdt/rga-merge p3 p1)
c_132 = crdt/rga-merge p1 (crdt/rga-merge p3 p2)
c_idem = crdt/rga-merge c_123 c_123

txt_123 = crdt/rga-to-str c_123
rga_ok_1 = txt_123 == 'Hi Local-First Veko World [v1.0]' and txt_123 == (crdt/rga-to-str c_321) and txt_123 == (crdt/rga-to-str c_231)
rga_ok_2 = txt_123 == (crdt/rga-to-str c_132) and txt_123 == (crdt/rga-to-str c_idem)
_ = assert-true (rga_ok_1 and rga_ok_2) (str/join ['3-peer offline RgaText convergence across all merge permutations ("' txt_123 '")'] '')

// --- 6. State-Vector Sync Wire Frame & Ephemeral `PresenceRoom` Expiration ---
mut late_peer = crdt/rga-merge (crdt/new-rga 'peer-4') p1
sv_late = crdt/rga-state-vector late_peer
delta_ops = crdt/rga-delta-since c_123 sv_late
sync_wire = crdt/encode-sync-frame (crdt/SyncFrame {
	sender_id    = 'peer-1'
	hlc          = t4
	state_vector = (crdt/rga-state-vector c_123)
	rga_delta    = delta_ops
	payload      = { doc_id = 'doc-alpha' }
})
dec_frame = crdt/decode-sync-frame sync_wire
_ = crdt/rga-apply-delta mut late_peer dec_frame.rga_delta

mut room = crdt/new-presence-room/ttl 'doc-alpha' 5000
_ = crdt/join-presence mut room 'peer-1' { cursor = 14 } 10000
_ = crdt/join-presence mut room 'peer-2' { cursor = 3 } 10000
_ = crdt/join-presence mut room 'peer-3' { cursor = 25 } 10000
_ = crdt/heartbeat-presence/metadata mut room 'peer-1' 14000 { cursor = 18 }
evicted = crdt/expire-presence mut room 16000
survivors = crdt/active-presence room

sync_ok = (crdt/rga-to-str late_peer) == txt_123 and (map/get dec_frame.payload 'doc_id') == 'doc-alpha'
pres_ok = evicted == ['peer-2' 'peer-3'] and (len survivors) == 1 and survivors[0].peer_id == 'peer-1' and (map/get survivors[0].metadata 'cursor') == 18
_ = assert-true (sync_ok and pres_ok) 'State-vector VKCS sync frame delta convergence and PresenceRoom TTL expiration'

println 'crdt_sync: all verification checks passed'
Cryptographic Provenance

Ed25519 Signature & Merkle Integrity

Registry URL: https://veko-lang.org/pkg/crdt_sync/1.0.0.vkp
Archive SHA-256: 71f5fd84d682ef738d0dc7183cb6af26e699d7c84bd2153e5c89dfc4de73e58c
Merkle Root: ff7e9878cb96b7f3959237ec32dcab24585bb86f72bf7dc19c5befd156fcbe0e
Signer Trust Key: ed25519:27406074d8681da1d4e6420f5d887cac15c313334c249ac047ba9d4e2df72b70
Embedded VKP1 Manifest

manifest.json

{"name":"crdt_sync","version":"1.0.0","tier":6.0,"tier_label":"Tier 6: Local-First, IoT, Web & Media","category":"Local-First CRDTs & Presence","description":"Hybrid Logical Clocks (HLC), PNCounter, LWW-Map, Observed-Remove Set, RGA collaborative text CRDT, state-vector sync, and room presence.","modules":["crdt_sync"],"homepage":"https://veko-lang.org/packages/crdt_sync"}
Bundle Entry PathSizeLeaf SHA-256 Digest
README.md6 KB827aedc08ddb03614166ee903d6ab1b75e91b6ff246e6b81dc69716c55cd7fc8
examples/demo.vk8 KB0b76eba4e7ee2a4f348c2132834a78073d54c06667138ecdb95a7a9767ee917a
mod.vk28 KB4d52b74dbe71385093794aad95130f9e5657dcea1ffd2d01e7b162889d5cd488