Commit graph

59 commits

Author SHA1 Message Date
aab41fa609 feat(ha-repl-hardening): per-standby convergence tracking from heartbeats (task 3.1)
ha_process_standby_state stores (tag, lsn) per standby, evaluates
convergence (tag>=committed && lsn>=committed), sets converged flag,
logs INFO only on transition. Wired into repl_ack_decode_and_dispatch.
5 tests: converged, lsn-behind, tag-behind, regression, multi-peer.
2026-06-04 16:40:44 +00:00
7dc657b1bd feat(ha-repl-hardening): populate stateReport in standby heartbeat reply (task 2.3)
OPCode_nop handler now sends stateReport {applied_lsn, config_tag}
instead of nodata. Function in ha.c for unit-test linkability.
Two tests: warm state and zero-state fresh standby (Req 1.4).
2026-06-04 16:08:11 +00:00
6bbcff62ca feat(ha-repl-hardening): add batch WAL catch-up on standby side (task 2.2)
Extend ha_apply_wal_catchup_entry with batch branch:
- Check n_entries > 0, iterate entries[] list in order
- Apply each via apply_wal_entry(); skip NULL/errors without crash
- Advance applied_lsn once after full batch (not per-entry)
- n_entries == 0 falls through to task 2.1 single-entry path
4 new unit tests covering full batch, partial batch, error skip, fallback
2026-06-04 15:38:20 +00:00
647b88ce57 feat(ha-repl-hardening): wire OPCode_walCatchupEntry standby handler (task 2.1)
Replace stub with ha_apply_wal_catchup_entry() calling apply_wal_entry().
CAS-advance applied_lsn on success; log ERROR and skip on failure.
Standby stays in CTRL_STANDBY throughout. 3 new unit tests.
2026-06-04 15:05:52 +00:00
e3ca775f0d feat(ha-repl-hardening): add per-standby convergence tracking arrays (task 1.4)
Add standby_reported_tag/lsn/converged arrays to ha_state_t, sized
MAX_HA_CANDIDATES. Zero-init via existing memset in ha_init().
Unit test verifies zero-init and writability.
2026-06-04 14:14:23 +00:00
e31673dd88 chore: checkpoint all prior work for clean state
Captures all uncommitted work from ha-config-bootstrap,
ha-heartbeat-liveness, and associated spec/tooling updates:

- src: ha.c, ha.h, cluster.c, config_repl.c, myapp.c, raft.c —
  heartbeat liveness, RDHUP integration, committing phase fixes
- tests: test_ha_role.c, test_config_repl.c, test_ha_rdhup_integration.c,
  test_p1_integration.c, test_p3_hardening.c, scheduler test
- specs: election-iomgr-refactor, ha-heartbeat-liveness,
  ha-peer-connection-reuse, raft-library (new); ha-config-bootstrap
  and election-iomgr-refactor task/research updates
- tooling: .wolf/ state, ha/data cluster fixtures, raft/raft.tla,
  src/build symlink, xce-build skill update
2026-06-04 13:04:16 +00:00
529552c127 fix(ha-heartbeat-liveness): start primary heartbeat in COMMITTING phase (task 4.3)
Call ha_start_primary_heartbeat in raft_cb_become_leader when entering
CTRL_PRIMARY_COMMITTING so standbys receive NOPs during the committing
window. Fixes 60s stability: 0 false RDHUP events on standbys.
2026-06-01 15:56:36 +00:00
622302a55c feat(ha-heartbeat-liveness): idle-triggered primary NOP per standby (task 2.2)
Extend primary_heartbeat_fn to read last_push_time per standby and send NOP
only when elapsed >= heartbeat_interval_s. on_standby_connected writes
last_push_time before ctrlhello send. Remove workaround xce_nop_req at end
of on_standby_connected. Add ha_nop_req_hook XCE_TESTING seam. 3 new tests.
2026-06-01 15:05:41 +00:00
738859fb4e feat(ha-heartbeat-liveness): replace hb_timeout_thread with liveness_poll_fn (task 2.1)
Remove hb_vtask_t, hb_timeout_thread, s_hb_vtask from ha.c. Replace with
liveness_poll_ctx_t + delaymgr liveness_poll_fn: checks cancelled flag and
role==CTRL_STANDBY before acting; re-arms at heartbeat_interval_ms/2.
ha_on_primary_ctrl_fd_rdhup calls ha_disarm_heartbeat_timeout_vtask first
to prevent duplicate failover (Req 5.4). ha_on_heartbeat_received writes
last_activity via clock_gettime. Add test_ha_liveness.c with 7 unit tests.
2026-06-01 14:34:14 +00:00
bcb45e59d2 feat(ha-heartbeat-liveness): add last_activity and last_push_time state fields (task 1.1)
Add time_t last_activity to ha_state_t for standby liveness timestamp tracking.
Add time_t last_push_time to standby_ep_ctx_t for primary idle NOP suppression.
Zero-initialize last_activity in ha_init(); last_push_time zeroed by calloc.
Add test_ha_init_last_activity_is_zero to test_ha_startup.c.
2026-06-01 11:59:16 +00:00
e85100d761 test(ha-peer-connection-reuse): complete tasks 7.1, 7.2, 7.3 — all validation done
Task 7.1 (unit tests) was already complete with 8 tests in
test_ha_connection_reuse.c. Added two new tests:

Task 7.2 — test_follower_passive_no_outbound_connect (Req 2.1, 2.4):
  Verifies raft_cb_become_follower sets role=CTRL_STANDBY and nulls all
  votes[i].ep. The old fetch_config_from_primary path is gone; standbys
  never initiate outbound connects after election loss.

Task 7.3 — test_promoted_ep_repl_ack_promotes_to_primary (Req 5.2, 5.4):
  Injects two OPCode_replCatchUpDone packets via peer_ctrl_msg_handler in
  CTRL_PRIMARY_COMMITTING with n_peers=4 (5-node cluster, quorum=2 ACKs).
  Verifies repl_ack_count reaches 2 and role transitions to CTRL_PRIMARY.
  Added vote_ep_ctx_set_cluster_for_test() seam so vctx->c is non-NULL
  when ha_repl_ack_received fires ha_promote_to_primary.

All 62 controller tests pass; ASAN clean.
spec: .kiro/specs/ha-peer-connection-reuse/tasks.md all tasks [x]
2026-06-01 07:53:02 +00:00
3d076ccda6 fix(ha): fix config replication to standbys; add replConfigPush handler
- config_repl.c: add handle_repl_config_push — standby handler for
  OPCode_replConfigPush. Verifies SHA-256, saves blob to disk via
  conf_save_config, reloads via load_primary_config, ACKs primary.
- config_repl.h: declare handle_repl_config_push.
- cluster.c: dispatch OPCode_replConfigPush to handle_repl_config_push;
  populate c->myhost_info.name from myconf->name (ctrl-1/ctrl-2/ctrl-3)
  instead of the static "controller" placeholder.
- ha.c: fix raft_cb_become_leader push_config_to_standbys call to pass
  real config bytes and tag read from disk (was NULL/0 — standbys got
  empty push and never saved config).
- typemap.h: add raw_sha256/raw_bytes/raw_bytes_len fields to
  repl_config_push_req_t (mirrors upgrade_config_req_t pattern).
- request.c: pre-extract List(UInt8) sha256/bytes from OPCode_replConfigPush
  before capn_free() in xce_decode(); free them in xce_free_request().
- helper.c: add all HA/replication opcode names to xce_request_op_name
  so "unknown opcode 30" becomes "replConfigPush" in logs.
- cluster_def.h: add embedded myhost_info field to cluster_t struct.
- ha.h: declare ha_start_primary_heartbeat; remove dead
  ha_find_and_connect_to_primary declaration.
2026-06-01 05:56:16 +00:00
d00d3bb051 fix(ha): wire raft trace to DEBUG3; drop NOP on promoted ep; fix --vcpus in deploy script
- ha.c: add raft_cb_trace callback wired to s_real_cbs.on_trace; emits
  RAFT[pN] term=T event=E at DEBUG3 level, visible with -vvv flag.
- ha.c: repl_ack_decode_and_dispatch now silently drops OPCode_nop and
  OPCode_reply instead of WARNING — heartbeat NOP replies from standbys
  arrive on promoted endpoints and are expected.
- deploy-ha.sh: fix --vcpu -> --vcpus; add \$VERBOSE passthrough so
  start.sh respects VERBOSE=-vvv from the environment.
2026-06-01 05:20:13 +00:00
7b39650229 refactor(ha): passive standby model — primary connects outbound to all peers
Remove fetch_config_from_primary, ha_find_and_connect_to_primary, and the
tier-1/2/3 discovery path. Standbys never initiate outbound connections to
the primary; the primary owns all inter-controller channels.

Key changes:
- ha.c: add primary heartbeat loop (ha_start_primary_heartbeat) that sends
  OPCode_nop to connected standbys every heartbeat_interval_ms; loop
  self-cancels on demotion via role check before re-arm.
- ha.c: add outbound reconnect in primary_heartbeat_fn — for peers absent
  from standby_endpoints, open fresh outbound TLS connection (on_standby_connected
  sends ctrlhello; standby_ep_ctx_t mirrors vote_ep_ctx_t layout).
- ha.c: remove ha_find_and_connect_to_primary + helpers (ha_raw_tcp_connect,
  ha_tcp_connect_hook); remove election_timeout_fn (superseded by
  raft_election_timeout_fn); remove fetch_config_from_primary call from
  ha_elect_evaluate_and_signal STANDBY branch.
- cluster.c: OPCode_requestVote denial no longer reuses inbound connection;
  late joiners are bootstrapped via primary heartbeat outbound connect.
- config_repl.c: remove connect_ssl_raw, do_one_config_fetch,
  fetch_config_from_primary (~250 LOC).
- myapp.c: remove my_tag > 0 fetch branch; all standbys wait passively.
- ha.h: remove ha_find_and_connect_to_primary declaration + macros +
  ha_tcp_connect_hook seam; add ha_start_primary_heartbeat declaration.
- meson.build: remove test_ha_connect.c (tests deleted function).
- controller_test.c: remove test_ha_connect registration.
- CLAUDE.md, src/controller/CLAUDE.md: document passive standby model,
  inbound-vs-outbound connection ownership, async I/O constraint,
  heartbeat model.
- request.h: add xce_request declaration (removes scattered local externs).
2026-06-01 04:17:05 +00:00
0f766776ba fix(ha-term): move ha-term.bin to {workdir}/{name}/data/ alongside WAL/snapshot 2026-05-31 11:04:35 +00:00
04b31afb06 fix(election): no-config nodes set CTRL_STANDBY to trigger config fetch; voter-only path 2026-05-31 10:39:33 +00:00
a75fb2581b fix(election): no-config nodes skip own election; delay_ms=0 fires election immediately 2026-05-31 10:27:05 +00:00
fd9933c9d0 feat(raft-library): task 6.3 — delegate election dispatch to raft_* API in ha.c + cluster.c 2026-05-31 08:43:01 +00:00
8f0d2d55c3 feat(raft-library): task 6.2 — real raft callbacks in ha.c; fix double-free + dead stubs 2026-05-31 07:53:00 +00:00
b77525deb0 feat(raft-library): task 6.1 — raft_state_t field in ha_state_t, raft_init with no-op stubs 2026-05-31 07:20:15 +00:00
dbb750ebd3 fix(election-iomgr-refactor): Raft election, config decode, and RDHUP chain
- ha.c: self-vote in ha_start_election_async (Raft invariant)
- ha.c: heartbeat_timeout_ms for hb_timeout_thread (not election_timeout_ms)
- ha.c: clear voted_for before RDHUP jitter (stale vote from dead primary)
- ha.c: same-term voted_for check in RDHUP jitter
- config_repl.c/h: use xce_decode for upgradeConfig (capnp extraction before capn_free)
- cluster.c: fix upgradeConfig handler direction (standbys apply, primaries skip)
- cluster.c: remove raw_pkt_copy hack; use req directly
- join.c: push config to newly-joined standbys
- typemap.h/request.h/request.c: raw_sha256/raw_bytes fields for decoded upgradeConfig
- test_ha_failover.c: update heartbeat timeout test to use g_fast_cfg
2026-05-31 03:54:30 +00:00
1ded1022fb fix(election-iomgr-refactor): RDHUP failover fixes — heartbeat watchdog + jitter
- ha.c: arm heartbeat timeout watchdog after ha_find_and_connect_to_primary (all 3 tiers)
- ha.c: guard ha_arm_heartbeat_timeout_vtask with c!=NULL (prevents ASAN stack-use-after-return in unit tests)
- ha.c: add priority-based jitter to ha_on_primary_ctrl_fd_rdhup to avoid split-brain
- ha.c: clear voted_for before RDHUP jitter so check reflects new votes, not stale startup votes
2026-05-31 02:24:52 +00:00
fd93997f78 fix(election-iomgr-refactor): config replication and RDHUP failover chain
- cluster.c: fix upgradeConfig handler (standbys apply, not primaries)
- cluster.c: fix raw_pkt_copy opcode peek (read scalar before capn_free)
- config_repl.h: enable CONF_ENABLE_UPGRADE_CONFIG=1
- config_repl.c: use client_ssl_ctx for outgoing config fetch connections
- config_repl.c: after config fetch, run cluster_init_phase2 + find_primary
- join.c: push config to newly-joined standbys on OPCode_join
- myapp.c: schedule fetch_config_from_primary after skipping own election
- ha.c: arm heartbeat timeout watchdog after find_and_connect_to_primary
2026-05-31 02:08:48 +00:00
81ea5e8eb8 fix(election-iomgr-refactor): integration bug fixes from 6.3 cluster test
- netio.c: skip SSL_new in endpoint_connect if ep->ssl already set (pre-created client ctx)
- ha.c: pre-create client SSL before endpoint_connect to avoid server-ctx handshake failure
- ha.c: fix double-free of vctx in endpoint_connect error path (let endpoint_fini own ep->data)
- ha.c: add endpoint_set_peer() call after endpoint_init for vote endpoints
- ha.c: fix endpoint_init args to AF_INET/SOCK_STREAM for outgoing vote sockets
- ha.c: wrap handle_request_vote voted_for check in ha->lock to prevent split-brain
- ha.c: skip immediate vote-deny for ECONNREFUSED in production; let election timeout handle
- delay.c: fix task_cmp signature to match ordq_cmp_fn_t (3 args: ctx, arg1, arg2)
2026-05-30 14:59:54 +00:00
0fdcd11e5f test(election-iomgr-refactor): add committing_timeout_fn watchdog unit tests — task 6.1 2026-05-30 13:19:31 +00:00
27ea14cd9a feat(election-iomgr-refactor): remove old blocking election code (am_i_primary_quorum, vote_request_thread, bootstrap_config_if_needed) — task 5.3 2026-05-30 13:04:19 +00:00
31a54043d5 feat(election-iomgr-refactor): wire RDHUP failover to ha_start_election_async — task 5.2 2026-05-30 12:43:02 +00:00
757558bb33 feat(election-iomgr-refactor): config/WAL replication push to standbys in COMMITTING path — task 4.2 2026-05-30 11:56:31 +00:00
f4a6726f1b feat(election-iomgr-refactor): COMMITTING path in ha_elect_evaluate_and_signal + committing/election timeout watchdogs — tasks 4.1, 4.3, 4.4 2026-05-30 11:37:12 +00:00
6de4b3ff0e feat(election-iomgr-refactor): extend handle_request_vote with role-based deny gate — task 3.2 2026-05-30 11:03:35 +00:00
e6135ea828 feat(election-iomgr-refactor): extend ha_dispatch_gate for CTRL_PRIMARY_COMMITTING — task 3.1 2026-05-30 10:28:36 +00:00
543981c505 fix(election-iomgr-refactor): correct task 2.4 review findings
- CRITICAL: single-node shortcircuit enters CTRL_PRIMARY_COMMITTING
  (not CTRL_PRIMARY directly); phase2 transition deferred to task 4.x
- CRITICAL: add n_peers==0 guard in ha_elect_evaluate_and_signal to
  prevent votes[0] out-of-bounds access
- HIGH: wire client_ssl_ctx after endpoint_connect for outgoing votes
- HIGH: add timeout_ctx field to ha_elect_ctx_t for task 4.x cancel
- HIGH: clarify vote_ep_err_handler ownership (no premature free of vctx;
  deferred to ha_election_cleanup in task 5.1)
- Tests updated: single-node shortcircuit asserts COMMITTING not PRIMARY
2026-05-30 09:27:48 +00:00
e50afd02f6 feat(election-iomgr-refactor): implement ha_start_election_async — task 2.4
Non-blocking election initiator that returns immediately after registering
vote endpoints with iomgr and scheduling the election timeout watchdog.

- Single-node shortcircuit (n_peers==1): allocates self-only ha_elect_ctx_t,
  calls ha_elect_evaluate_and_signal directly, frees ctx inline — no iomgr
  or delaymgr involvement; returns in < 1ms
- Multi-node: allocates ha_elect_ctx_t, per-peer vote_ep_ctx_t, calls
  endpoint_connect + iomgr_monitor for each peer; schedules election timeout
  via delay_task_ms; skips peer on connect failure (counted as denied)
- election_timeout_fn: delaymgr callback that fires ha_elect_evaluate_and_signal
  after election_timeout_ms, unless cancelled flag is set (lock-free cancellation)
- vote_ep_err_handler: counts unreachable peers as denied votes
- Declares ha_start_election_async in ha.h with full doc comment
- 5 Unity tests in test_ha_start_election_async.c: returns < 5ms, stores
  n_peers, shortcircuit fires immediately, n_peers stored for multi-peer,
  term incremented — all GREEN with ASAN enabled
2026-05-30 08:57:59 +00:00
bd58e5045a feat(election-iomgr-refactor): implement vote_reply_msg_handler
Replace stub with full iomgr-native vote reply decoder:
- Reads RequestVoteReply fields into local scalars BEFORE capn_free (UAF fix)
- Term fencing: atomic update ha->term if peer term > ours
- Error path: decode failure counts peer as denied vote
- Test seam: xce_vote_reply_hook for unit testing without real packets
- 4 new ASAN-clean unit tests: field decode, denied vote, term fencing, no-UAF

The pre-existing vote_request_thread UAF in the old pthread path remains
but is targeted for removal in task 5.3 (old code removal).
2026-05-30 08:45:43 +00:00
18c280429e feat(election-iomgr-refactor): add vote_ep_ctx_t and on_vote_connected
- vote_ep_ctx_t: per-peer context (ha, c, ctx, peer_idx, term/tag/lsn/name)
- election_timeout_ctx_t: cancelled flag + context for delay watchdog
- on_vote_connected(): iomgr callback fires after SSL handshake; builds
  xce_request_t{opcode=OPCode_requestVote}, calls xce_request, sets msg_handler
- vote_reply_msg_handler stub (returns 0; implemented in task 2.3)
- Test seam: xce_vote_request_hook for unit testing without live SSL
- 4 new unit tests: opcode, field encoding, msg_handler set, cancelled flag

Context note: vctx->c is NULL in test helper — task 2.3 must use real cluster_t*
2026-05-30 08:09:33 +00:00
e42564b3bd feat(ha): add phase2_done, repl_ack_count, n_peers, client_ssl_ctx fields and CTRL_PRIMARY_COMMITTING enum
Task 2.1 of election-iomgr-refactor spec. Adds the new ha_state_t fields
required for the COMMITTING phase FSM, the CTRL_PRIMARY_COMMITTING role enum
value, and the committing_timeout_ms config field with its default constant.
ha_init() explicitly zero-initialises all new fields. Unit test verifies
zero-init and enum distinctness.

Requirements: 5.2, 8.1 (election-iomgr-refactor spec)
2026-05-30 07:40:38 +00:00
289c4daaa2 fix(ha-bootstrap): use TLS client context for outgoing vote RPCs
ha->ssl_ctx is created with TLS_server_method() (for incoming iomgr
connections). vote_request_thread was calling SSL_connect() on this
server-method context, which OpenSSL rejects immediately — causing
every vote thread to fail with SSL_ERROR_SSL and goto deny.

Fix: create a fresh TLS_client_method() context with SSL_VERIFY_NONE
for each outgoing vote connection. This is safe because the election
protocol is authenticated by the vote RPC payload (term, config_tag)
not by the TLS certificate chain.

The SSL_CTX_free after SSL_new is correct — SSL_new increments the
reference count internally, so freeing the ctx leaves the ssl object
valid.
2026-05-30 03:37:13 +00:00
80950ffbba fix(ha-bootstrap): priority staggering and candidate_id in election
Two Raft correctness fixes:

1. Priority staggering in ha_wait_for_heartbeat_or_timeout():
   Add my_priority × election_priority_step_ms to the timeout so
   ctrl-a (priority=0) times out first and starts election before
   ctrl-b (priority=1) and ctrl-c (priority=2). This gives the
   highest-priority node a head start and prevents simultaneous
   campaigning that causes perpetual split votes.

2. candidate_id in vote RPC:
   Pass the actual node name (myconf->name) as candidate_id instead
   of "". This fixes the voted_for deduplication gate (Req 2.6):
   a peer that already voted for ctrl-a will correctly deny a
   second vote request from ctrl-b in the same term.

   Thread context gets my_name field; am_i_primary_quorum() takes
   my_name parameter; all call sites updated (myapp.c, ha.c RDHUP,
   test_ha_election.c stubs).
2026-05-30 02:48:59 +00:00
6753b364c8 fix(ha-bootstrap): wire OP_requestVote RPC through standard Request envelope
The vote_request_thread was sending raw capnp(RequestVoteRequest) bytes
but the server-side iomgr decodes every incoming packet as a Request
struct. This caused the term field (uint64) to be misread as the opcode
field (uint16), so vote RPCs were silently misrouted (term=1 → OPCode_reply,
term=2 → OPCode_hello) and no node ever got a vote from its peers.

Fix:
- controller.capnp: add requestvotemsg @27 to Request.body and
  requestvotereplymsg @14 to RequestReply.data
- typemap.h: move request_vote_req_t/reply_t before xce_request_t;
  add requestvotemsg/requestvotereplymsg to body/data unions
- ha.c: rewrite vote_request_thread send/recv to use xce_encode()
  wrapper and decode outer Request→inner RequestReply on receive
- cluster.c: add case OPCode_requestVote handler calling
  handle_request_vote() and replying via xce_reply()

All 188 unit tests pass.
2026-05-29 17:01:59 +00:00
0d5f2cb1bb feat(ha-config-bootstrap): implement EPOLLRDHUP failover and heartbeat timeout vtask (task 9.4) 2026-05-29 07:17:55 +00:00
97a76617e6 feat(ha-config-bootstrap): implement ha_find_and_connect_to_primary three-tier discovery (task 9.2) 2026-05-28 15:09:08 +00:00
7c27ff1954 feat(ha-config-bootstrap): implement ha_restore_term() for ha-term.bin read path (task 6.2) 2026-05-28 13:21:36 +00:00
0c9c720b03 feat(ha-config-bootstrap): complete quorum election with mutex safety (task 4.3)
- am_i_primary_quorum(): per-peer pthreads, connect_ssl_raw + OP_requestVote
- pthread_mutex_t lock on ha_elect_ctx_t guards votes_granted/n_replied/max_resp
- done_posted guard in ha_elect_evaluate_and_signal prevents double sem_post
- Replace am_i_primary() with am_i_primary_quorum() in myapp.c
- Delete ha_check_priority_stepdown and ha_check_heartbeat_nocluster
- INFO logs: election outcome (Req 10.1), FSM transitions (Req 10.5)
- 24 election tests + 24 startup tests, 0 failures
2026-05-28 08:28:35 +00:00
0f88d5d32a feat(ha-config-bootstrap): implement vote handlers and term persistence (task 4.2)
- ha_persist_term(): atomic write+rename of ha_term_file_t with CRC32
- handle_request_vote(): term/voted_for/freshness/catch-up gate chain
- handle_request_vote_reply(): vote counting, quorum+all-replied signaling
- ha_elect_evaluate_and_signal(): quorum+yield+zero-config gates (4.3 early)
- am_i_primary_quorum(): single-node shortcircuit + 2-round retry (4.3 partial)
- 24 Tests 0 Failures in test_ha_election suite
2026-05-28 07:32:48 +00:00
f0029bf000 feat(ha-config-bootstrap): implement ha_wait_for_heartbeat_or_timeout (task 3.4)
- sem_timedwait on heartbeat_seen semaphore with CLOCK_REALTIME deadline
- deadline = now + election_timeout_ms + xorshift64 jitter
- Returns CTRL_STANDBY on heartbeat arrival (calls ha_do_demote)
- Returns CTRL_ELECTING on timeout (caller drives election)
- Allows OPCode_heartbeat through dispatch gate in CTRL_INIT state
- 3 new unit tests: standby-on-heartbeat, electing-on-timeout, gate-allows-heartbeat
- 24 Tests 0 Failures in test_ha_startup suite
2026-05-28 06:58:59 +00:00
72776f18ff feat(ha-config-bootstrap): implement dispatch gate (task 3.3)
- errnox.h: add E_XCE_NOT_READY and E_XCE_STANDBY error codes with
  extern int XCE_ERR_NOT_READY / XCE_ERR_STANDBY runtime variables
- ha.h: declare ha_dispatch_gate(ha_state_t *, int opcode)
- ha.c: define XCE_ERR_* variables; initialize heartbeat_seen semaphore
  and primary_ctrl_fd = -1 in ha_init(); sem_destroy in ha_fini();
  implement ha_dispatch_gate() with allowlist for CTRL_INIT/CTRL_ELECTING
  (only OP_requestVote and OP_probeConfigTag pass) and CTRL_STANDBY
  (replication, election, and housekeeping ops pass; primary-only ops
  return -XCE_ERR_STANDBY)
- cluster.c: wire ha_dispatch_gate() in myreq_handler() before opcode
  switch; gate failure sends error reply and returns early

All 393 unit tests pass. Satisfies requirements 1.3 and 1.4.
2026-05-28 05:50:42 +00:00
488fd1bf49 feat(ha-config-bootstrap): add peer count and cert pre-flight validation (task 2.3)
- Implement validate_peer_count() in startup_validation.c: -EINVAL for even N>1
- Implement validate_cert_files() with err_buf output: access() check, writes
  missing path into err_buf, returns -ENOENT
- Wire validate_peer_count() in main.c after peer list parse; fatal exit on fail
- Wire validate_cert_files() in main.c before SSL init; fatal exit on fail
- Fix ASAN leak: SSL_CTX_free in ha_fini() with NULL guard
- Fix double-free: null c->ha.ssl_ctx in cluster_fini() before ha_fini(),
  so iomgr_fini() retains sole SSL_CTX ownership (design per ha.h comment)
- All 96 tests pass; all 12 ha_startup tests GREEN
2026-05-28 04:29:31 +00:00
0d783b16e3 fix(ha): zero ha_state_t before validation; fix invalid config in stale test
Root cause: test_heartbeat_stale_no_crash_without_primary had
heartbeat_timeout_ms=100 < heartbeat_interval_ms=3000, causing ha_init
to return -EINVAL before memset. The test ignored the return value and
called ha_fini on garbage stack memory. The watchdog_thread field
happened to hold the value 3 (from a prior stack frame), so
ha_stop_watchdog called pthread_join(3, NULL) — crash at 0x2d3
(__pthread_clockjoin_ex accessing thread-struct field at offset 0x2d0).

Fix 1 (test): valid config (interval=2000, timeout=3000). Staleness is
injected via last_heartbeat -= 10s, so timeout value was irrelevant.
Added TEST_ASSERT_EQUAL_INT check on ha_init return.

Fix 2 (ha_init): move memset before validation so ha_fini is safe to
call even after a failed init — prevents the same bug class in callers
that check ha_init's return late.

Verified: test_ha_role 11/11 PASS in both non-ASAN and ASAN builds.
2026-05-20 08:53:38 +00:00
ec3cab40c3 fix: capture SSL_get_error once per retry; lock ha->lock in ha_check_priority_stepdown 2026-05-13 16:44:55 +00:00
fe3cc57f27 feat: implement real am_i_primary() with election probing, ha_is_primary(), ha_check_priority_stepdown()
- Replace stub am_i_primary() with real election probe logic
- probe_thread(): non-blocking TCP connect with optional SSL handshake
- wait_any_probe(): deadline-based spin-poll across all probe threads
- am_i_primary(): priority-0 always primary; higher priorities probe
  lower-priority peers and self-promote if deadline expires
- ha_is_primary(): lock-free role check
- ha_check_priority_stepdown(): simultaneous-boot stepdown at term=0
- start/stop_heartbeat_listener(): stubs for Task 7
- ha_init(): explicit initialization of ssl_ctx/jitter_seed/standby_endpoints
- TDD: add test_am_i_primary suite with 3 tests covering p0/p1 paths
2026-05-13 16:39:59 +00:00