MLambda.Data Developer Guide
How to define tables, store and query entities, replicate them, and change their schema, from Aleph. Every module
named here is in MLambda.Data/src; the samples are checked against the package.
Two levels
| Level | Modules | Use it for |
|---|---|---|
| ORM | Orm.Entity, Orm.Repository, Orm.Spec, Orm.Replicated |
Application code: a type maps to a table once |
| Engine | Engine.DataEngine, Engine.Query, Table.*, Distributed.Coordinator |
Tools, the API, anything that works with rows and tables directly |
Both answer every call with Either Fault _: failures are values to match, never exceptions.
Part 1 — Schema definition
Creating a table
A table is built step by step and checked once:
import Table.Schema
import Table.Builder
build (partitionKey ["user_id"] (column "name" TextType (column "user_id" UuidType (tableBuilder "users"))))
-- Right TableDef, or Left "what is wrong"
A build is refused when the table has no columns, a key or an index names a column it does not have, two columns or indexes share a name, or the replication factor is below 1.
Data types
Int32Type, Int64Type, Float64Type, TextType, BlobType, BooleanType, TimestampType, UuidType.
Values compare by their column’s type when the schema is known: an Int32, Int64 or Timestamp is a little-endian number; anything else compares byte by byte.
Columns
| Function | Column |
|---|---|
column name type |
Required: a write without it is refused |
nullableColumn name type |
Optional |
Partition key
partitionKey ["tenant", "user_id"]: the columns a row’s partition is hashed from. On a cluster the ring places a
partition on its replicas; rows of one partition live together.
Clustering key
clusteringKey ["created_at"]: the order of rows within a partition.
Indexes
| Function | Kind | Answers |
|---|---|---|
btreeIndex name columns |
B-tree | Equality, ranges (OpGt…OpLte) and prefixes |
hashIndex name columns |
Hash | Equality |
invertedIndex name columns |
Inverted | Words: rows holding every word of a query |
Every SSTable also carries a bloom block, so a read skips tables that cannot hold its key.
The query planner (Engine.Planner) answers one filter through an index that fits it (an equality by a hash lookup
or a B-tree point, a comparison by a range, a prefix by a prefix scan) and checks the other filters on the rows it
found; with no index that fits, it scans.
Replication
replicas 3 (placedBy SimpleStrategy (...))
The table’s replication factor and strategy (SimpleStrategy, NetworkTopologyStrategy).
Examples
-- Sensor readings: one partition per sensor, newest first by time.
sensors = build
(btreeIndex "ix_value" ["value"]
(clusteringKey ["at"]
(partitionKey ["sensor"]
(column "value" Float64Type
(column "at" TimestampType
(column "sensor" TextType (tableBuilder "readings")))))))
-- An event log searched by text.
events = build
(invertedIndex "ix_text" ["message"]
(partitionKey ["tenant", "id"]
(column "message" TextType
(column "id" UuidType
(column "tenant" TextType (tableBuilder "events"))))))
Part 2 — Entities
import Orm.Entity
trait Entity e where
mapping :: Mapping e -- mappedTo database builder
toColumns :: e -> Columns
fromColumns :: Columns -> Maybe e
keyOf :: e -> Bytes
data User = User { userId :: String, name :: String, email :: Maybe String, age :: Int }
instance Entity User where
mapping = mappedTo "app"
(btreeIndex "ix_age" ["age"]
(partitionKey ["id"]
(column "age" Int64Type
(nullableColumn "email" TextType
(column "name" TextType
(column "id" TextType (tableBuilder "users")))))))
toColumns u = Columns (withEmail u.email [fieldOf "id" u.userId, fieldOf "name" u.name, fieldOf "age" u.age])
fromColumns cs = case fieldValue "id" cs of
Nothing -> Nothing
Just i -> case fieldValue "name" cs of
Nothing -> Nothing
Just n -> case fieldValue "age" cs of
Nothing -> Nothing
Just a -> Just (User i n (fieldValue "email" cs) a)
keyOf u = B.bytesFromString u.userId
fieldOf name value and fieldValue name columns go through ColumnValue:
| Aleph type | Column bytes |
|---|---|
Int |
Int64, little-endian |
String |
UTF-8 |
Bool |
One byte |
A type of your own becomes a column with an instance ColumnValue.
A mapping that does not build is refused when the repository opens:
-- partitionKey ["missing"] on a table without that column
openRepository engine -- Left (Fault "MappingError" "the partition key names a column the table does not have: missing")
Part 3 — Repositories
import Orm.Repository
openRepository :: Entity e => Address DataEngine -> Either Fault (Repository e)
save :: Entity e => Repository e -> e -> Either Fault Int
find :: Entity e => Repository e -> Bytes -> Either Fault (Maybe e)
remove :: Repository e -> Bytes -> Either Fault Int
select :: Entity e => Repository e -> Selection -> Either Fault [e]
joinWith :: (Entity l, Entity r) => Repository l -> Repository r -> String -> [Filter] -> Either Fault [(l, r)]
Opening a repository defines its table (or finds it, unchanged). The repository’s type picks the entity, so give the
result a type: case (openRepository engine :: Either Fault (Repository User)) of ….
The engine
engineAt :: ActorSystem -> String -> Address DataEngine
engineAt system root = case Fs.makeDir root of
_ -> actorOf system (parameters [("root", root)])
One engine per data root: it routes each request to its table’s store (made on first use) and runs joins.
Writes and reads
save users (User "u-1" "Alice" (Just "[email protected]") 30) -- Right _
save users (User "u-1" "Alice Smith" (Just "[email protected]") 31) -- replaces the row: same key
find users (B.bytesFromString "u-1") -- Right (Just (User "u-1" "Alice Smith" ...))
remove users (B.bytesFromString "u-1") -- a tombstone; find answers Right Nothing
A write is logged and synced before it is acknowledged. Writes that arrive together share one sync (group commit).
Specifications
import Engine.Query
import Orm.Spec
data Spec = Where Filter | Both Spec Spec | OneOf Spec Spec | Negated Spec | Everything
data Filter = Filter String FilterOp Bytes -- OpEq | OpGt | OpGte | OpLt | OpLte | OpPrefix
selecting :: Spec -> Selection
orderedBy :: String -> Bool -> Selection -> Selection -- True: descending
withPage :: Int -> Int -> Selection -> Selection -- skip, at most (0: all)
With Carol 28, Dave 35, Eve 42 and Frank 19:
select users (selecting (Where (Filter "age" OpGt (toValue 30)))) -- Dave, Eve
select users (selecting (Both (Where (Filter "age" OpGt (toValue 20)))
(Negated (Where (Filter "name" OpPrefix (B.bytesFromString "D")))))) -- Carol, Eve
select users (withPage 1 2 (orderedBy "age" True (selecting Everything))) -- Dave, Carol
The filters joined by Both alone go to the engine (and through an index when one fits); the whole specification
is then checked on each row, so OneOf and Negated hold exactly.
Joins
joinWith orders users "user" [] -- each order with the user whose key is its "user" column
A hash join inside the engine: the right side bucketed by key, each left row matched by its column’s value. The filters narrow the left side.
Part 4 — Replication
On a cluster, Orm.Replicated stores entities on the replicas that own their keys, with the same Entity
instance:
import Orm.Replicated
openReplicated :: Entity e => Coordinator -> Address DataEngine -> Either Fault (Replicated e)
saveReplicated :: Entity e => Replicated e -> e -> Either Fault Int
findReplicated :: Entity e => Replicated e -> Bytes -> Either Fault (Maybe e)
removeReplicated :: Replicated e -> Bytes -> Either Fault Int
selectReplicated :: Entity e => Replicated e -> Selection -> Either Fault [e]
- The table is defined on every node when the repository opens.
- A save, a find and a remove reach a quorum of the key’s replicas, whichever node asks.
- A find answers the newest copy the quorum holds and writes it back to the replicas that were behind (read repair).
- A selection reads this node’s own engine. It sees every row while each key is copied to every node (three replicas, three nodes or fewer); beyond that, find rows by key.
Consistency levels
Distributed.Coordinator takes the level per request:
data Consistency = One | Quorum | All
writeAt :: Consistency -> Coordinator -> String -> String -> Bytes -> Columns -> Int -> Either Fault Int
readAt :: Consistency -> Coordinator -> String -> String -> Bytes -> Either Fault (Maybe Row)
deleteAt :: Consistency -> Coordinator -> String -> String -> Bytes -> Int -> Either Fault Int
| Level | Replicas that must answer |
|---|---|
One |
1 |
Quorum |
a majority (n/2 + 1) |
All |
every replica |
A request that cannot reach the level answers Left (Fault "ConsistencyNotMet" ...).
The ring
Distributed.Ring places keys: each node holds vnodes tokens on a consistent-hash ring (the service uses 256); a
key belongs to the first token at or after its hash, and its replicas are the next distinct nodes. With 256 tokens a
node the skew stays under 25%, and a fourth node joining a ring of three takes about a quarter of the keys.
Part 5 — Schema changes
Table.Evolution changes a table in place, keeping every row already written readable:
| Change | Allowed when |
|---|---|
AddColumn |
The column is nullable (old rows do not have it) and its name is free |
DropColumn |
The column is not part of a key or an index |
WidenColumn |
The new type holds every old value (Int32 → Int64, Int32/Int64 → Float64, Text → Blob) |
RenameColumn |
The new name is free (keys and indexes follow the rename) |
The schema registry (Table.Actors) takes AlterTable database table [change]; a change that does not fit is
refused with the reason, and each accepted change gives the registry a new version.
Constraints
Table.Constraints checks every write against the table’s rules: each column’s type, every required column present,
no column the table does not have. Add your own rule as a class with a Constraint instance (MaxBytes is one: a
column at most n bytes).
Part 6 — Storage, for operators
| Piece | Module | What it does |
|---|---|---|
| Write-ahead log | Storage.Wal |
Every write appended and synced before it is in the memtable; entries carry a CRC-32 |
| Memtable | Storage.Memtable |
Sorted writes in memory; flushed to an SSTable past its size (4 MiB by default) |
| SSTables | Storage.SSTable |
Immutable sorted files: data blocks, an index block, a bloom block, a footer |
| Compaction | Storage.Compaction |
Size-tiered: tables of a tier merged once it holds enough of them; the newest item per key wins |
| Snapshots | Storage.Snapshot |
A memtable saved whole with its log position, so recovery replays only what follows |
| Manifest | Storage.Manifest |
Which SSTables make up a table |
Recovery loads the manifest, the latest snapshot, and replays the log after it. A torn or corrupt log entry ends the replay at the last good one.
Part 7 — Failures
Management.Failures names the database’s failures (DiskFullException, an I/O failure; an fsync timeout, a
timeout …) and gives each a parent kind. Guardians are written as rules on those kinds and become MLambda.Actor
deciders, so storage restarts on I/O, compaction, snapshot and memory failures. Management.CompactionBreaker paces
compaction by the disk’s load: full speed when it is idle, throttled past half its I/O, paused at 80% I/O or a 5 ms
p99 write latency, and tried again a minute later.
The service
The database as its own process (MLambda.Data.Service) serves a REST API and five live channels on the same code.
See API Spec and Deployment.