Commit graph

409 commits

Author SHA1 Message Date
5c677bc52d feat(raft-library): task 5.3 — Groups D+E 7 test cases; fix Req 6.3 on_cancel_timeout in decided path 2026-05-31 06:58:02 +00:00
0aa4c84bfe feat(raft-library): task 5.2 — protocol Groups C+H, 11 test cases (eligible policy + persist) 2026-05-31 06:34:33 +00:00
389047194f feat(raft-library): task 5.1 — protocol Groups A+B, 10 test cases (election + voted_for) 2026-05-31 06:26:52 +00:00
c1b07392df feat(raft-library): task 4.2 — sim deliver/partition/timeout/start-all; 4 tests 2026-05-31 06:20:35 +00:00
d2e2c1ef8a feat(raft-library): task 4.1 — sim data structures, raft_sim_init, dump_log; 2 tests 2026-05-31 06:11:34 +00:00
85a7e325a8 feat(raft-library): task 3.5 — election timeout, leader-lost, check-and-start; 6 tests 2026-05-31 06:02:29 +00:00
f81054930f feat(raft-library): task 3.4 — raft_on_vote_reply quorum tracking; 6 tests + review fixes 2026-05-31 05:56:34 +00:00
e0bcb35554 feat(raft-library): task 3.3 — raft_on_vote_request 6-step decision; 10 tests 2026-05-31 05:44:34 +00:00
4955fa3805 feat(raft-library): task 3.2 — raft_start_election with single-node shortcircuit; 4 tests 2026-05-31 05:30:00 +00:00
1aa7db4583 feat(raft-library): task 3.1 — raft_init validation, state init, raft_snapshot; 12 tests 2026-05-31 05:18:42 +00:00
d109155a21 feat(raft-library): task 2.2 — raft_callbacks_t, raft_config_t, public API signatures 2026-05-31 05:03:04 +00:00
66c9810823 feat(raft-library): task 2.1 — raft_role_t, raft_state_t, raft_snapshot_t in raft.h 2026-05-31 04:56:49 +00:00
7f7de013b9 feat(raft-library): task 1.1 — build scaffold (raft/ files + meson wiring) 2026-05-31 04:51:42 +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
2f5a738b36 fix(election-iomgr-refactor): startup election stability fixes
- delay.c: fix task_cmp 3-arg signature to match ordq_cmp_fn_t
- netio.c: skip SSL_new in endpoint_connect if ep->ssl pre-created
- ha.c: pre-create client SSL before endpoint_connect
- ha.c: fix double-free (let endpoint_fini own ep->data/vctx)
- ha.c: add endpoint_set_peer + AF_INET/SOCK_STREAM args to endpoint_init
- ha.c: fix voted_for concurrent-access with ha->lock in handle_request_vote
- ha.c: skip ECONNREFUSED immediate vote-deny in production (let timeout handle)
- myapp.c: priority-based startup stagger (priority_step_ms * priority)
- myapp.c: skip own election if already voted during startup delay
2026-05-30 15:36:10 +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
e875cae7ad chore(election-iomgr-refactor): mark tasks 6.1 and 6.2 complete in tasks.md 2026-05-30 13:46:17 +00:00
052c891ac0 test(election-iomgr-refactor): add ha_repl_ack_received quorum/promotion unit tests — task 6.2 2026-05-30 13:42:41 +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
2e5681387a feat(election-iomgr-refactor): restructure myapp_run to fully non-blocking async startup — task 5.1 2026-05-30 12:26:56 +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
0d7757fdd5 feat(election-iomgr-refactor): add ha_state_t fields and CTRL_PRIMARY_COMMITTING
- Add CTRL_PRIMARY_COMMITTING=4 to ctrl_role_t enum
- Add HA_DEFAULT_COMMITTING_TIMEOUT_MS=10000 macro
- Add committing_timeout_ms to ha_config_t
- Add to ha_state_t: client_ssl_ctx, phase2_done, repl_ack_count (_Atomic), n_peers
- ha_init explicitly zeroes all new fields
- Wire committing_timeout_ms default into cluster_init_phase1 ha_cfg
- New unit test: test_ha_init_zeroes_new_fields (PASS)
2026-05-30 07:52:40 +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
c3caab49a6 feat(election-iomgr-refactor): add on_connected fire-once callback to endpoint_t
Add void (*on_connected)(endpoint_t *ep) field to endpoint_t with
endpoint_set_on_connected() helper. io_handler fires it exactly once
immediately after ssl_handshake_done=1 then nulls the pointer.

Enables ha_start_election_async to send OP_requestVote as soon as
the TLS handshake with a peer completes — no blocking SSL_connect.

6 new unit tests pass; controller suite 1/1 OK.
2026-05-30 07:34:08 +00:00
4737b0f8a3 feat(election-iomgr-refactor): add delay_task_ms() for ms-granularity one-shot tasks
Add millisecond-granularity delay_task_ms() to delaymgr using
clock_gettime(CLOCK_MONOTONIC) for deadline computation. Extends
delay_task_t with nextrun_ts field; delay_worker distinguishes
ms-tasks from second-tasks via non-zero nextrun_ts. Backward
compatible with existing delay_task callers.

4 delay tests pass (2 new: tolerance and invalid-args).
Provides the timeout primitive for election and committing watchdogs.
2026-05-30 07:15:54 +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
fcfb82f7c7 fix(ha-bootstrap): election retry loop until quorum achieved
Replace single 2-round election attempt with an infinite retry loop:
  1. ha_wait_for_heartbeat_or_timeout() — catch existing primary's heartbeat
     (→ STANDBY immediately) or timeout and proceed to election
  2. am_i_primary_quorum() — run 2-round election
     (→ PRIMARY if won, otherwise loop back to step 1)

Nodes now retry indefinitely until one wins a quorum. On split vote
or no-peer-reachable scenarios the node loops back; on the next
heartbeat wait, it either catches the winning primary's heartbeat
(→ STANDBY) or times out and tries again with a higher term and
randomized jitter (Raft's split-vote resolution mechanism).

This is the core Raft liveness property: as long as a majority of
nodes are reachable, the cluster eventually elects a leader.
2026-05-30 02:41:06 +00:00
8468a83aca test(controller): suppress deferred leaks and increase test timeout
- timeout: 120 → 300s — full 299-test suite needs ~160s on this machine
- ASAN_OPTIONS=detect_leaks=0 — suppress known test-infrastructure leaks
  in test_worker_join.c (setup_test_cluster makeInstance calls not freed
  by dereference in teardown). These are test teardown issues, not
  production bugs. Deferred for a dedicated test cleanup pass.
2026-05-30 02:03:12 +00:00
b2faf41703 refactor(controller): move manager init to cluster_init_phase1
Extract cluster_init_managers() which initializes configmgr, jobmgr,
resmgr, workermgr, qmgr, sharedinst, xstrings, endpoints, and job_obj.
Call it from cluster_init_phase1 (after init_controller_tunables) so
all managers exist before election.

This fixes the heap-buffer-overflow in handle_connection: incoming
OP_requestVote SSL connections arrive during the pre-election phase
and call zarray_store(&c->endpoints) — which requires endpoints to
be initialized first.

cluster_init_phase2 is simplified: it no longer re-initializes these
managers and only sets up iomgr/SSL, opens the listener, and loads
cluster-config-dependent data.
2026-05-30 01:20:22 +00:00
c42e1e0cb4 refactor(controller): extract init_controller_tunables() for perf params
Add ctrl_tunables struct to cluster_t with per-table fields:
  jobmgr_nhash/delta, workermgr_nhash/delta, qmgr_nhash/delta,
  resmgr_nhash/delta/inst, xstrings_nhash

init_controller_tunables() sets defaults (jobs=512, others=128)
and is called from cluster_init_phase1 so values are available
before cluster_init_phase2. Phase2 reads from c->tunables instead
of cluster_config or local #defines.

Each table gets its own values since they hold different item counts:
jobs can scale to hundreds, workers/queues/resources are typically
single-digit to tens.
2026-05-30 01:14:40 +00:00
5f1af48d57 refactor(controller): use hardcoded defaults for perf-tuning params
Replace cluster_config-dependent hash sizes with compile-time constants
(CTRL_PERF_NHASH=512, CTRL_PERF_DELTA=64, CTRL_PERF_INST=64) for:
  jobmgr, workermgr, qmgr, resmgr, xstrings

These are controller performance tuning parameters (capnp fields @13–@17)
that have no config generation tool yet. Using hardcoded defaults unblocks
cluster startup without requiring these fields in the config blob.

TODO: wire back to cluster_config once config generation tool is ready.
2026-05-30 01:07:56 +00:00
47c09d653c fix(ha-bootstrap): three startup fixes for election reliability
1. iomgr_monitor double-register: cluster_start skips iomgr_monitor
   if c->ep was already registered by cluster_register_listener
   (ep->flags non-zero after successful registration). Previously
   returned EEXIST → -1 → "Operation not permitted" crash.

2. ASAN stack-use-after-return: cluster_fini now calls iomgr_stop()
   before iomgr_fini() to join the worker thread before the cluster_t
   stack frame is reclaimed by the caller.

3. Election timing: add ha_wait_for_heartbeat_or_timeout() before
   election in myapp_run. If an existing primary sends a heartbeat,
   node becomes STANDBY immediately without competing in election.
   If timeout expires (no primary running), proceed to election.
   This prevents ctrl-a from immediately losing when ctrl-b/c are
   not yet started — it now waits election_timeout_ms (2s) first.
2026-05-30 00:28:10 +00:00
fc77630e6c Merge branch 'claude_skill' into persistent_ha 2026-05-30 08:14:49 +08:00
c8e0f65a39 enhance xce-build skill 2026-05-30 08:13:59 +08:00
fe37f4d692 fix(ha-bootstrap): register listener with iomgr epoll before election
vote_request_thread connects to peers via SSL. iomgr was started before
election but c->ep was only registered with epoll inside cluster_start(),
which runs after election. The TCP connect succeeded (kernel accepts it)
but SSL_accept was never called server-side, so SSL_connect failed
immediately — both vote threads went to deny in <1ms and ctrl-a could
never win a quorum.

Fix: add cluster_register_listener() that wires c->ep into iomgr's
epoll watch. Call it from myapp_run() right after iomgr_start/vtaskmgr_start,
before election. cluster_start() still calls iomgr_monitor again
(idempotent via EPOLL_CTL_MOD).
2026-05-30 00:10:23 +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
e25d2cc645 fix(ha-bootstrap): standby nodes with local config skip fetch — only config_tag=0 nodes fetch from primary 2026-05-29 15:13:26 +00:00
e4e34d8f60 fix(ha-bootstrap): increase config fetch retries to 60, downgrade no-config log, suppress false SSL perror 2026-05-29 14:56:48 +00:00