lattice/lww_map
A last-writer-wins map (LWW-Map) CRDT.
Each key maps to a value and a timestamp. On conflict, the entry with the higher timestamp wins. Removal is timestamp-based (tombstone): a remove at timestamp T beats any set at timestamp < T. Keys are strings; values are strings.
Example
import lattice/lww_map
let a = lww_map.new() |> lww_map.set("name", "Alice", 1)
let b = lww_map.new() |> lww_map.set("name", "Bob", 2)
let merged = lww_map.merge(a, b)
lww_map.get(merged, "name") // -> Ok("Bob")
Types
A Last-Writer-Wins Map (LWW-Map) CRDT.
Internally stores each key with an Option(String) value and an Int
timestamp. A None value represents a tombstone (removed key). On merge,
the entry with the higher timestamp wins for each key; on ties, the first
argument’s entry is kept as a consistent tiebreak.
pub type LWWMap {
LWWMap(
entries: dict.Dict(String, #(option.Option(String), Int)),
)
}
Constructors
-
LWWMap(entries: dict.Dict(String, #(option.Option(String), Int)))
Values
pub fn from_json(
json_string: String,
) -> Result(LWWMap, json.DecodeError)
Decode a LWWMap from a JSON string produced by to_json.
Returns Error if the string is not valid JSON or does not match the
expected format.
pub fn get(map: LWWMap, key: String) -> Result(String, Nil)
Get the value for a key.
Returns Ok(value) if the key exists and is not tombstoned.
Returns Error(Nil) if the key is missing or has been removed.
pub fn keys(map: LWWMap) -> List(String)
Return all active (non-tombstoned) keys in the map.
Order is not guaranteed.
pub fn merge(a: LWWMap, b: LWWMap) -> LWWMap
Merge two LWW-Maps by resolving each key using the highest timestamp.
Tombstones participate in merge: if a tombstone has a higher timestamp than the active entry for a key, the key remains removed after merging. On equal timestamps, the first argument’s entry wins (consistent tiebreak).
Merge is commutative, associative, and idempotent (a valid CRDT join).
pub fn remove(map: LWWMap, key: String, timestamp: Int) -> LWWMap
Remove a key at the given timestamp by inserting a tombstone.
If the key already has an entry with an equal or higher timestamp, the remove is rejected and the existing entry wins.
pub fn set(
map: LWWMap,
key: String,
value: String,
timestamp: Int,
) -> LWWMap
Set a key to a value at the given timestamp.
If the key already has an entry with an equal or higher timestamp, the existing entry is kept (LWW semantics: strictly greater timestamp wins).
pub fn to_json(map: LWWMap) -> json.Json
Encode a LWWMap as a self-describing JSON value.
Entries are encoded as a JSON array where each element has key, value
(nullable string for tombstones), and timestamp fields.
Format: {"type": "lww_map", "v": 1, "state": {"entries": [...]}}
The encoded value can be restored with from_json.