Clause
← All documentation

mnesia's files and protocol, as observed

What OTP 29's mnesia (4.27) writes to its directory and sends between nodes, observed by running scenarios on OTP nodes. Clause's mnesia is written from these observations and OTP's documentation, never from OTP's sources.

Directory files

Each file is a disk_log (halt log) of Erlang terms unless named a dets table. A log starts with {log_header, Kind, Version, MnesiaVersion, Node, Now}.

FileHeader kind and versionTerms after the header
FALLBACK.BUP, backupsbackup_log, "1.2"{schema, Tab, CreateList} items, the schema's first, then the records
schema.DATdets set, key position 2{schema, Tab, CreateList}: the schema's own list has a cookie but no majority or storage_properties
LATEST.LOG, PREVIOUS.LOGtrans_log, "4.3"#commit{} records, {decision, Tid, Outcome, Nodes, RamNodes} records and {master_nodes, Tab, Nodes} entries
DECISION_TAB.LOGdecision_tab, "1.0"one {decision_list, Decisions}: {trans_tid, serial, N} and {master_nodes, Tab, Nodes}, in OTP's ets order
Tab.DCDdcd_log, "1.0"a disc_copies table's records; a new table's file has no terms at all, not even a header
Tab.DCLdcl_log, "1.0"the table's log items since the DCD file
Tab.DATdets, the table's type, key position 2a disc_only_copies table's records

Schema transactions

On one node, a schema transaction logs {commit, Node, {decision, Tid, presume_abort, [Node], []}, [], Disc, DiscOnly, [], Ops} and then {decision, Tid, committed, [], []}. Cs below is the table's create list as in schema.DAT, with the new version.

Operation{op, ...} tuples
create_table/2{op, create_table, Cs}; a fragmented table's fragments, the last first, then the base table
delete_table/1, del_table_copy/2 of the last copy{op, delete_table, Cs} with the table's last definition
add_table_index/2, del_table_index/2{op, add_index, {Pos, ordered}, Cs}, {op, del_index, Pos, Cs}
transform_table/3,4{op, transform, Fun or ignore, Cs}
change_table_copy_type/3{op, change_table_copy_type, Node, From, To, Cs}
access mode, load order, majority{op, change_table_access_mode, Cs, Old, New}, change_table_load_order, change_table_majority alike
write_table_property/2, delete_table_property/2{op, write_property, Cs, Prop}, {op, delete_property, Cs, Key}
snmp_open_table/2, snmp_close_table/1{op, add_snmp, Ustruct, Cs}, {op, del_snmp, Cs}
dump_tables/1{op, dump_table, Size, Cs} per table
change_table_frag/2{op, change_table_frag, activate or deactivate or {add_frag, Nodes} or del_frag, BaseCs}, then create_table or delete_table of the fragment, then {op, rec, Storage, {{Frag, Key}, [Record], write}} and {op, rec, Storage, {{Frag, Key}, [{Frag, Key}], delete}} per moved record
restore/2{op, clear_table, Cs} or {op, restore_recreate, BackupCs} per table, the restored records as the commit's Disc and DiscOnly writes

Remote queries

What a node asks another node's mnesia through rpc:call/4, or through the other node's mnesia_rpc server, and what it answers. A node that is not running mnesia answers too, as long as the node itself runs.

QueryAnswer
mnesia_lib:is_running/0yes, no, starting or stopping
mnesia_lib:is_running_remote/0{IsRunning, node()}, IsRunning true only for yes; delete_schema/1 asks each node this
mnesia_lib:get_node_number/0{node(), Pid}, the answering process
mnesia_schema:remote_read_schema/0{ok, Source, CreateList}: ram while running, with the schema table's list; fallback or disc with the list in FALLBACK.BUP or schema.DAT, as written (no majority or storage_properties); default without a directory to use, with a new RAM schema on no nodes; {error, "No schema file exists"}. create_schema/1 asks each node this and refuses any other source than default
mnesia_schema:delete_schema2/0ok, the directory's mnesia files deleted, or {error, {"Mnesia still running", Node}}
mnesia_controller:get_remote_cstructs/0{cstructs, Cstructs, RunningNodes}: a #cstruct{} record per table, newest first, the schema last; without mnesia a {badmatch, {error, {node_not_running, Node}}} failure
mnesia_lib:db_get/2the records under the key in this node's replica; {aborted, {no_exists, {Tab, storage_type}}} or {aborted, {node_not_running, Node}} exits

Connecting

How two nodes' mnesia connect, observed with both nodes on a RAM schema. Neither node merges the other's schema here: {current, db_nodes} stays the node itself.

MessageFrom, toAnswer or effect
{negotiate_protocol, Nodes}a local caller of mnesia_monitor:negotiate_protocol/1, to mnesia_monitora process of the monitor's asks each node's monitor through rpc:multicall(Nodes, mnesia_monitor, call, [Msg]); the reply lists the nodes that accepted
{negotiate_protocol, Mon, Version, Protocols}the asking node's negotiator, to mnesia_monitor by gen_server:call{Node, {accept, MonPid, Version, Protocol}}, linking Mon; or {Node, {reject, MonPid, Version, Protocol}}. Version is mnesia's ("4.27"), Protocols [{8,6}, {8,5}, {8,4}, {8,3}]; a monitor accepts its own protocol when the asker lists it, {8,5} when the asker lists it first
{connect_nodes, Nodes}mnesia_recover:connect_nodes/1, to mnesia_recovernegotiates with the nodes not yet in recover_nodes, asks each mnesia_lib:is_running/0, adds those that run (yes or starting) to recover_nodes and replies {NewNodes, AlreadyConnected}
{decisions, Node, [{trans_tid, serial, N}]}the connecting node's mnesia_recover, to the new nodes' by gen_server:abcastthe receiver adds Node first in recover_nodes; a serial larger than its own makes its serial N + 1
{what_decision, Node, Decision}a node unsure of a transaction, to mnesia_recover by castthe serial of the decision's tid is taken as above; the reply is {decisions, Node, [D]} with this node's decision on the tid, or the asked one when it has none

Schema merge

How two running nodes with RAM schemas merge them, observed with mnesia:change_config(extra_db_nodes, [B]) on node a and with node b starting again with extra_db_nodes naming a. The merge is a schema transaction of a process the merging node starts: it locks the schema on every node and commits the merged definitions on both sides with OTP's asym_trans commit. In the tables, a is the merging node.

MessageFrom, toAnswer or effect
{merging_schema, A}a, to mnesia_controller on a and on the nodes given, by castnothing observable
{connect_nodes, Nodes}a, to its own mnesia_recoveras when connecting; only nodes not yet running with a are merged, so a second call merges nothing
{Pid, {write, Tid, {schema, '______WHOLETABLE_____'}}}the transaction, to mnesia_locker of a, then of each running node and each node to merge{mnesia_locker, Node, granted}; an ended transaction sends {release_tid, Tid} to each locker when it aborts
mnesia_controller:get_remote_cstructs/0the transaction, to the first node to merge, by rpc{cstructs, Cstructs, RunningNodes} (remote queries)
{Pid, {ask_commit, asym_trans, Tid, #commit{}, DiscNodes, RamNodes}}the transaction, to each other node's mnesia_tma participant process of that node answers {mnesia_tm, Node, {vote_yes, Tid, Participant}}; the commit's decision is #decision{tid = Tid, outcome = presume_abort} with the same node lists, and its schema_ops are the merge's operations below
{Tid, pre_commit}the transaction, to each participant{mnesia_tm, Node, {acc_pre_commit, Tid, Participant, true}}
{Tid, committed}the transaction, to each participantthe participant applies the operations and answers {mnesia_tm, Node, {schema_commit, Tid, Participant}}
{Tid, simple_commit}a transaction that only locked, to that node's mnesia_tmthe node's locks of the transaction go
{im_running, A, Friends}a, after a merge, to the controllers of each side, naming the other side; after a transaction that merged nothing, to its own controller naming itselfthe controller casts {adopt_orphans, node(), Tabs} to each of Friends, Tabs being the tables it holds, without the schema
{adopt_orphans, Node, Tabs}a controller, to another node's or its own{log_mnesia_up, Node} to its mnesia_recover (which removes Node's mnesia_down record), then the {mnesia_up, Node} system event; Tabs are read and written on Node
{schema_is_merged, [], late_merge, []}a, after the merges, to the controllers of a and the connected nodes, by gen_server:multi_callignore
disc_load_intentsa node loading its tables at start, to each running node's controller, under the lock {'______GLOBAL_____', mnesia_late_disc_load}{ok, Node, Tabs}, the tables that node holds
{i_have_tab, Tab, Node}a node that loaded its replica, to the other controllersTab is read and written on Node

Remote reads and dirty writes

How a node reads and dirty-writes a table that only another node holds, observed after a merge of two RAM schemas. In the tables, a reads and writes, b holds the table.

Message or callFrom, toAnswer or effect
{apply, M, F, Args}a's caller, to b's mnesia_rpc by gen_server:call (remote queries)M:F(Args) on b's replica; a read that fails there answers {badrpc, {'EXIT', Reason}}
{Ref, {sync_dirty, {dirty, Pid}, #commit{}, Tab}}a's caller, to b's mnesia_tmb's mnesia_tm applies the commit, reports its table events with the activity id {dirty, Pid} and sends {mnesia_tm, b, {dirty_res, Result}} to Ref, an alias of the caller
{Pid, {async_dirty, {dirty, Pid}, #commit{}, Tab}}a's caller, to b's mnesia_tmb applies the commit and answers nothing

Remote locks

How a transaction locks a table that only another node holds, observed after a merge of two RAM schemas. In the tables, a's transaction locks a table that b holds. Requests go to each lock manager as raw messages {Pid, Request}, and it answers {mnesia_locker, Node, Reply} to Pid, the transaction's process. a's own lock manager answers a read of a record held on a {granted, lookup_in_client}, and the transaction reads the record itself.

Request to b's mnesia_lockerLockGrant
{read, Tid, {Tab, Key}}read lock of the record, on the node that where_to_read names{granted, Records}, the records read under the lock
{read, Tid, {Tab, '______WHOLETABLE_____'}}read lock of the table: lock/2, match_object, select, walks, folds, all_keys{granted, ok}; the reads follow through b's mnesia_rpc (remote reads)
{write, Tid, Oid}write lock of a record or table, on each node of where_to_wlockgranted
{read_write, Tid, {Tab, Key}}read/3 with write: write lock and read{granted, Records}
{ix_read, Tid, Tab, Value, Pos}index_read/3: read lock of the table and the index read{granted, Records, ['______WHOLETABLE_____']}
{read, Tid, {'______GLOBAL_____', Item}}, {write, ...}lock({global, Item, Nodes}, Kind), on each listed node{granted, ok}, granted
{sync_release_tid, Tid}a restarting transaction's locks{tid_released, Tid}
MessageFrom, toEffect
{not_granted, #cyclic{}}b's lock manager, to a younger transaction asking for a lock that an older one holds#cyclic{node = b, oid = Oid, op = Op, lock = Lock, lucky = HolderTid}; the transaction restarts with the same tid
{Tid, simple_commit}a's transaction at its commit, to b's mnesia_tm, when it only took locks on bb releases the transaction's locks and takes its serial as when connecting
{release_tid, Tid}a's aborting transaction, to each lock manager it usedthe locks go
{what_happened, unclear, Tid}a's mnesia_tm, when a transaction's process dies, to b's mnesia_recover by gen_server:call{ok, unclear} for a transaction b decided nothing about
{Tid, {do_abort, {mnesia_down, a}}}a's mnesia_tm, after that question, to b's mnesia_tmb releases the transaction's locks
{apply, mnesia_tm, fixtable, [Tab, true, Pid]}a's transaction before it walks the table or reads select/4 chunks, to b's mnesia_rpcb answers its node name; a's mnesia_tm sends [Tab, false, Pid] once the transaction ends

Two-phase commit

How transactions and schema changes commit on several nodes, observed after a merge of two RAM schemas. In the tables, a coordinates: a's transaction process sends each other node holding a written table one #commit{} and gathers the answers. Each commit's items are {{Tab, Key}, Value, Op} in the field of the table's storage on that node, as in the log.

MessageFrom, toAnswer or effect
{Pid, {ask_commit, Protocol, Tid, #commit{}, DiscNodes, RamNodes}}a's transaction, to each other node's mnesia_tmsee each protocol below; the node takes the transaction's serial as when connecting
{mnesia_tm, b, {vote_yes, Tid}}b's mnesia_tm, to a (sym_trans, sync_sym_trans)a sends {Tid, do_commit} to b's mnesia_tm and commits its own part; b applies its commit, reports its table events and completed activity with a's tid, and releases the transaction's locks
{mnesia_tm, b, {committed, Tid}}b's mnesia_tm, to a, after do_commit (sync_sym_trans)a waits for it before the transaction returns
{mnesia_tm, b, {vote_yes, Tid, Participant}}a process b's mnesia_tm starts, to a (asym_trans)a sends {Tid, pre_commit} to Participant
{mnesia_tm, b, {acc_pre_commit, Tid, Participant, SchemaOps}}the participant, to aSchemaOps is true when the commit has schema operations; a sends {Tid, committed} to the participant and commits its own part
{mnesia_tm, b, {schema_commit, Tid, Participant}}the participant, after applying schema operations, to aa waits for it before the schema change returns; a commit of records only is not confirmed
{mnesia_tm, b, {vote_no, Tid, {aborted, Reason}}}b, to athe transaction aborts with Reason and releases its locks on every node
{Tid, {do_abort, Reason}}a, to b's mnesia_tm or participantb drops the commit and releases the transaction's locks

Replicas and loading

How a node gets a replica's records from another node, observed after a merge of two RAM schemas. In the tables, b gets the replica and a holds the table. The receiver is the process that needs the records: the participant of b in add_table_copy/3 and move_table_copy/3 (before it votes), the coordinator itself when it gets the copy, or a loader process of b at start.

MessageFrom, toAnswer or effect
mnesia_lib:set({mnesia_loader, active_trans}, Tid)b's receiver of a new copy, to a, by rpcsets the variable on a; a sender of a table locked by the transaction locks it under that tid
{send_table, Tab, Receiver, Storage, Reason}b's receiver, to a's mnesia_controller by gen_server:casta's controller starts a sender; Reason is {add_table_copy, Tid} for a new copy and load at start
{Sender, {first, Size}}the sender, to the receiverSize is the table's size; the receiver makes its replica's table and answers {Receiver, more}
mnesia_controller:call({update_where_to_write, [add, Tab, b], Sender})the sender, to b by rpc, then to its own controllerthe table is written on b from then on (true)
{Sender, {more, Records}}, or {Sender, {more_z, zlib:compress(term_to_binary(Records))}} with send_compressed above 0the sender, to the process that answered moreall chunks follow at once, each of about max_transfer_size bytes of records, then {Sender, no_more}; the receiver acknowledges each with more, which the sender of a RAM replica does not wait for
{block_table, [Tab], Sender}, {add_active_replica, [Tab, b, Storage, AccessMode], Sender}the sender, to b's mnesia_controller by gen_server:call, the second also to its ownok, true: b's replica is active on both nodes
{Sender, {no_more, nobin}}the sender, to the receiverthe receiver answers {Pid, no_more}, Pid any process of its loader

Disc nodes

How nodes whose schemas are on disc are created, start, load their tables and log their commits, observed with two nodes a and b, each with its own directory.

Creating the schema

create_schema([A, B]) on a asks each node mnesia_schema:remote_read_schema/0 (remote queries), then a process of a installs the same fallback on every node:

MessageFrom, toAnswer or effect
global:set_lock({{mnesia_table_lock, schema}, Master}, Nodes)the master, on all the nodesheld until the end, then global:del_lock/2
spawn_link(Node, mnesia_bup, fallback_receiver, [Master, Args])the master, on each node, a includedthe receiver registers as mnesia_fallback; Args is OTP's #fallback_args{}: {fallback_args, Opaque, global, mnesia_backup, true, undefined, undefined, undefined, [], [], keep_tables}, Opaque a file name in the master's directory
{Master, {start, Header, SchemaItems}}the master, to each receiverthe receiver writes the master's backup header and {schema, schema, CreateList} items to a temporary file of its directory and answers {Receiver, ok}
{Master, swap}the master, to each receiverthe file becomes FALLBACK.BUP; {Receiver, ok}
{Master, stop}the master, to each receiverthe receiver exits with reason stopped; the master, linked and trapping exits, waits for each exit. A receiver that exits otherwise while the master waits fails the installation ({error, {"Cannot install fallback", {'EXIT', Pid, Reason}}})

Starting

Disc replicas over nodes

Logs on disc nodes

Schema changes with a disc node down

ChangeWith b down
create_table/2 with a copy on b{aborted, {not_active, Tab, b}}
create_table/2 of a RAM table on b onlycommits; b gets it at its next start (merge)
delete_table/1, add_table_index/2, del_table_index/2 of a table with a replica on b{aborted, {not_active, "All replicas on diskfull nodes are not active yet", Tab, [b]}}

Master nodes, majority and copies

Observed with two disc nodes a and b, as disc nodes.

Master nodes

Majority

A write lock on a table with majority aborts the transaction with {aborted, {no_majority, Tab}} unless more than half of the table's replicas are active: with two replicas, one node alone has no majority. Read locks and dirty writes are not checked; a read with a write lock (read(Tab, Key, write)) is. A schema transaction that locks such a table, as del_table_copy(schema, Node) locks each table of the node, aborts the same way.

Copies between disc nodes

Certainty

A coordinator casts {im_certain, Node, Decision} to the other disc nodes right after it sends committed, before its own part of the commit; a participant sends it before its schema_commit. A node that dumps its log while a decision is not yet certain keeps that decision in DECISION_TAB.LOG.

A coordinator logs its commit, then its committed decision naming the other disc nodes, then the decision again without each node whose im_certain came. A participant hears the coordinator's im_certain about when it logs its own decision, so it logs [A] then [], or [] twice.

Partitions and orphans

Observed with two disc nodes a and b, as disc nodes; the connection broke with erlang:disconnect_node/1 while both ran.

Partitions

Orphans

A replica that waits at start (see starting) is an orphan once another node comes up while no node will load it:

Commit protocol

A transaction commits with asym_trans when the tables it writes differ in where_to_commit, nodes and storage alike (disc_copies and ram_copies tables on the same nodes, for one), or have a majority; it then logs its commit under {decision, Tid, presume_abort, DiscNodes, RamNodes} even when this node commits alone (one node, or a partition), with its RAM writes beside the disc ones when it wrote on disc. Tables committing on the same nodes with the same storage use sym_trans.

Checkpoints over nodes

Observed with two disc nodes a and b. A checkpoint is OTP's #checkpoint_args{}, which nodes pass to each other: {checkpoint_args, Name, AllowRemote, RamOverridesDump, Nodes, Node, Now, Cookie, Min, Max, PendingTab, WaitForOld, IsActivated, IgnoreNew, Retainers, Iterators, Supervisor, Pid}, its retainers {retainer, Name, Tab, Store, Writers, ReallyRetain}. RamOverridesDump is the list of tables, [] without the option.

Activating

Nodes coming and going

Backups over nodes

A backup of a checkpoint runs where it is asked and needs the checkpoint there: elsewhere it fails with {error, {'EXIT', {error, {error, {no_exists, Name}}}}}. Each table is read where its retainer is written, here when this node writes it. Otherwise the backup spawns mnesia_log:tab_copier(Self, B, Tab) on a writer, with OTP's #backup_args{} ({backup_args, Name, Module, Opaque, Scope, PrevName, Tables, Cookie}), links it and receives:

The receiver writes each chunk to the backup with the table's name as the records' first element.

Fallbacks and restores over nodes

Observed with two disc nodes a and b. A fallback's arguments are OTP's #fallback_args{}: {fallback_args, Opaque, Scope, Module, UseDefaultDir, MnesiaDir, FallbackBup, FallbackTmp, SkipTables, KeepTables, DefaultOp}.

Events and fragments over nodes

Observed with two disc nodes a and b.