code wiki / _hdl_build / nx_ha_quorum.nx

nx_ha_quorum.nx source

↩ module page · 22 lines · 1118 B

1// nx_ha_quorum.nx -- CAP-HA-QUORUM: majority quorum + deterministic leader election for 3+ node clusters, 2// preventing SPLIT-BRAIN. A leader is elected ONLY if a MAJORITY of nodes are healthy (votes*2 > total), so a 3// partitioned minority never promotes itself -> no two primaries. The leader is the lowest-index healthy node 4// (deterministic, no election churn / no coin-flips). Pure integer, gateable offline. Composes with failover for a 5// 3+-node cluster. license_tier: ORIGINAL 6import "nx_syscalls.nx" 7 8// strict majority? 9func qm_has_quorum(votes: i64, total: i64) -> i64 { 10 if votes * 2 > total { return 1 } 11 return 0 12} 13// elected leader index, or -1 if NO quorum (minority partition must not lead -> split-brain prevented). 14// leader = the lowest-index healthy node (deterministic). healths[i] = 1 up, 0 down. 15func qm_leader(healths: *i64, n: i64) -> i64 { 16 var up: i64 = 0; var i: i64 = 0 17 while i < n { if healths[i] == 1 { up = up + 1 } i = i + 1 } 18 if qm_has_quorum(up, n) == 0 { return 0 - 1 } 19 i = 0 20 while i < n { if healths[i] == 1 { return i } i = i + 1 } 21 return 0 - 1 22}