Commit graph

270 commits

Author SHA1 Message Date
0a881804a0 test(ha-config-bootstrap): add failing dispatch gate tests (task 3.1)
RED-phase tests for ha_dispatch_gate() and FSM init state:
- CTRL_INIT + non-election ops -> XCE_ERR_NOT_READY
- CTRL_INIT/ELECTING + OP_requestVote/OP_probeConfigTag -> 0 (allowed)
- CTRL_STANDBY + primary-only ops -> XCE_ERR_STANDBY
- CTRL_PRIMARY + any op -> 0
- heartbeat_seen semaphore usable after ha_init()

ha_dispatch_gate, XCE_ERR_NOT_READY, XCE_ERR_STANDBY are all undefined
-> linker errors confirm RED phase
2026-05-28 04:42:30 +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
3ab2e6e4bf feat(ha-config-bootstrap): implement --vcpus CLI, wire validation, remove vcpus from config (task 2.2)
- Add --vcpus N argp option in main.c; store in myconf.vcpus
- Replace inline argp guard with validate_vcpus() call (returns -EINVAL for <=0)
- Add validate_startup_config() in startup_validation.c: returns 0; writes
  deprecation warning into caller-supplied warn_buf when vcpus key present
- Wire validate_startup_config() into myapp_run() after conffile resolved;
  emit WARN() if warn_buf non-empty (Req 4.4)
- Remove vcpus field from cluster_config_t (clusterconfig.h)
- Preserve capnp ordinal: vcpus @7 -> vcpusDeprecated @7: Void in controller.capnp
- vtaskmgr_init uses only myconf->vcpus with hardcoded default 8
- Add stub C types in typemap.h for capnp schema extensions from task 1.1
- 96 tests pass
2026-05-28 04:17:06 +00:00
bfa41eb135 test(ha-config-bootstrap): add failing startup validation tests (task 2.1)
RED-phase tests for 4 startup validation functions — all fail at link time
because the functions under test do not exist yet:
- validate_peer_count: even N>1 returns -EINVAL, odd N returns 0
- validate_cert_files: missing cert/key returns -ENOENT with full path
  in err_buf output param (asserted via strstr)
- validate_vcpus: vcpus<=0 returns -EINVAL, positive returns 0
- validate_startup_config: vcpus key in config returns 0 (not fatal)
  and writes deprecation text into warn_buf (asserted via strstr)
2026-05-28 03:31:30 +00:00
560d8fa1c8 feat(ha-config-bootstrap): add election types and new fields to ha.h (task 1.2)
- Add CTRL_INIT=2, CTRL_ELECTING=3 to ctrl_role_t
- Add ha_vote_entry_t per-peer vote tracking struct
- Add ha_elect_ctx_t with C99 flexible array votes[]
- Add 8 new ha_state_t fields: voted_for_term/name, primary_ctrl_fd,
  defer_config_fetch, elect_ctx (void * _Atomic), last_known_committed_lsn,
  heartbeat_seen (sem_t), last_known_committed_config_tag
- Declare ha_persist_term(), bootstrap_config_if_needed(), xce_probe_config_tag()
- Fix: use void * _Atomic (postfix) not _Atomic void * (prefix) for atomic
  pointer-to-void — C11 §6.7.2.4 prohibits _Atomic on incomplete type void
2026-05-28 03:15:29 +00:00
6adb7e806f feat(ha-config-bootstrap): add 6 new opcodes and HA message structs to controller.capnp 2026-05-28 03:02:40 +00:00
7a922cf184 docs(config-repl): update impl-status — Phase 1 wire protocol complete
- Mark Phase 1 as WIRE PROTOCOL COMPLETE (was: ACTIVE with stubs)
- Add commits 2ed7e34-5053c8d to component table
- Remove resolved limitations (do_one_config_fetch stub, push no-op)
- Update test count: 18 → 24 tests, total 84 passing
- Update Phase 2 table: handle_upgrade_config wired, push timeout enforced
- Update files changed to include request.c shims and new test additions
2026-05-22 09:20:29 +00:00
5053c8d42f feat(config-repl): wire handle_upgrade_config() via raw packet interception
Pre-decode opcode peek in myreq_handler() captures raw packet bytes for
OP_upgradeConfig before xce_decode() frees the capnp segment. Passes
raw bytes to xce_upgrade_config_req_extract_raw() to extract sha256 and
config blob, then delegates to do_upgrade_config_with_bytes().

Removes Task 11 dependency. Phase 2 still gated by CONF_ENABLE_UPGRADE_CONFIG.
2026-05-21 13:51:52 +00:00
2aae45f046 feat(config-repl): wire do_one_config_fetch() — full SSL roundtrip
Replaces -ENOSYS stub with:
- connect_ssl_raw() helper (non-blocking connect + poll + SSL handshake,
  checks ha_is_primary() between iterations for early promotion exit)
- xce_replconfig_req_ssl() to send OP_replConfig request
- xce_replconfig_reply_ssl_decode() to receive and decode reply
- SHA-256 integrity verify (retry on mismatch with -EBADMSG)
- conf_save_config() atomic disk write to workdir/name/conf/
- load_primary_config() to reload cluster_config from newly saved file

Standby can now fetch ClusterConfig from primary on startup.
2026-05-21 13:38:21 +00:00
4ef2089fd4 fix(config-repl): wire handle_config_request() to send real bytes
Replace NULL sha256/bytes stub with xce_replconfig_reply_raw() call.
Primary now sends actual config blob and SHA-256 in OP_replConfig reply.
2026-05-21 13:16:38 +00:00
26393e919c feat(config-repl): add raw capnp shims for OP_replConfig wire protocol
xce_replconfig_reply_raw() - primary sends reply with real bytes via endpoint
xce_replconfig_req_ssl() - standby sends request over raw SSL socket
xce_replconfig_reply_ssl_decode() - standby decodes reply from raw SSL
xce_upgrade_config_req_extract() - documents architectural limitation; returns -ENOTSUP
xce_upgrade_config_req_extract_raw() - extract bytes from raw packet for OP_upgradeConfig

Same bypass pattern as existing xce_replconfigpush_req_raw(): build the
capnp message directly via capn_new_list8 + capn_setv8, sidestepping the
encode_Data_ptr path that routes raw bytes through xce_data_t (a
discriminated cluster-data union that cannot carry raw byte arrays).

Unblocks handle_config_request() and do_one_config_fetch() wiring.

Task A research finding: xce_upgrade_config_req_extract(xce_request_t*)
is unimplementable because xce_decode() calls capn_free() before any
handler runs, and decode_Data_ptr converts the wire-format List(UInt8)
into a zero-filled xce_data_t. Task D must capture the raw io_packet_t
bytes before xce_decode tears them down, then call the _raw variant.
2026-05-21 13:02:49 +00:00
f3babec5bc feat(config-repl): implement wait_all_with_timeout() for push fan-out
Replaces blocking pthread_join() per thread with a CLOCK_MONOTONIC
deadline + 5ms poll loop. CONF_PUSH_TIMEOUT_MS (500ms) now enforced.
Matches design §6.3 aggregate timeout guarantee.

- Add done field to push_ctx_t; push_thread sets it on exit
- Add static wait_all_with_timeout() before push_config_to_standbys()
- Wire push_config_to_standbys() to use wait_all_with_timeout()
- Add #include <stdatomic.h> to config_repl.c
- Guard push_ctx_t local typedef with #ifndef XCE_TESTING
- Expose push_ctx_t and wait_all_with_timeout_for_test() in header
  under XCE_TESTING for unit test access
- Add test_wait_all_with_timeout_slow_threads (timeout fires, acked=0)
- Add test_wait_all_with_timeout_fast_threads (all complete, acked=3)
- Update design doc §6.3 with actual implementation signature and
  5ms poll interval note
2026-05-21 08:30:43 +00:00
2ed7e34e25 fix(config-repl): conf_save_config() must use workdir/name not workdir
load_primary_config() reads from workdir/name/conf — conf_save_config()
was writing to workdir/conf. Latent bug: would have corrupted upgrade
restart cycle once Task 11 wired the upgrade path.

Update all conf_read_current_filename, conf_get_saved_tag, and
conf_check_stale calls in the test suite to use the corrected
effective_dir (workdir/name) path structure. Add new test
test_conf_save_config_path_consistency that explicitly verifies the
written path matches what load_primary_config() reads.
2026-05-21 08:09:02 +00:00
86fe35e671 add kiro skills 2026-05-21 03:41:57 +00:00
e5fde7b55f fix(persist): zero nresvals_to_sched after free_name_val_list
Crash: encode_NameValue_list called with count=21, s=NULL on worker
rejoin, causing SIGSEGV in persist_worker_hook_fun.

Root cause: free_name_val_list(xce_name_val_t***, int) accepted count by
value. It zeroed *vals (resvals_to_sched = NULL) but could not zero
nresvals_to_sched. Any caller that freed the scheduler resource snapshot
(opget.c workerlist, reply.c clusterconf, dataex.c, sched.c dispatch)
left nresvals_to_sched stale. When the worker later rejoined and the
WAL HOOK fired, the WAL encoder read count=21 with a NULL pointer.

Fix: change signature to free_name_val_list(xce_name_val_t***, int*)
so both fields are zeroed atomically. Update all 7 call sites.
2026-05-20 09:39:07 +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
93ed282ef7 feat(worker-join-refactor): implement apply_join_state, init_worker, rejoin_worker
Replace monolithic add_worker with three focused functions:
- apply_join_state (static under production, exported under XCE_TESTING):
  shared status/resource update called by both create and rejoin paths;
  clears XCE_WORKER_UNAVAIL, applies hconfig overrides, updates resources
- init_worker: first-time join path via makeWorker + apply_join_state
- rejoin_worker: reconnect path with explicit admin-bit preservation
  (XCE_WORKER_ADMIN_MASK = LOCKEDU|CLOSED|HIDDEN|CLOSED_BY_ADMIN)

Also makes find_matched_hostconfig non-static so join.c can call it
via the extern declaration already in worker.h.

Removes add_worker (no longer declared in worker.h, no callers).

All 7 tests in test_worker_join pass:
  apply_join_state (clears UNAVAIL, hosttype override, resource values),
  init_worker (creates entry, returns correct idx),
  rejoin_worker (updates attrs/ep, preserves admin bits).
2026-05-20 08:24:26 +00:00
1599d06bc4 feat: filter lost_and_found sentinel from pushes; reset unavail host attrs
- create_lost_and_found(): provide hostattrs_t so makeWorker succeeds
- collect_queues/collect_workers (dataex.c): skip lost_and_found sentinel
  so it is never pushed to apiserver or scheduler
- mark_worker_unavail(): reset hosttype/hostmodel to "unknown" and zero
  all numeric attrs, then update resvals and slots — prevents stale
  capacity from being visible while the host is down
- restore_worker(): apply the same attr reset on WAL recovery so
  restored-but-unavailable workers advertise no capacity until reconnect;
  also remove dead calloc() that was immediately overwritten by makeWorker
- Extract reset_hostattrs_unknown() helper to eliminate copy-paste
- Define XCE_LOST_AND_FOUND_NAME constant in config_repl.h; replace all
  six raw "lost_and_found" string literals across config_repl.c and dataex.c
2026-05-14 08:44:55 +00:00
2e2aaea78c feat: implement push_config_to_standbys() — parallel fan-out via xce_replconfigpush_req_raw() using capn_new_list8 for raw bytes 2026-05-14 03:58:02 +00:00
609314efa4 docs: update impl-status — create_lost_and_found done, API guard done, fix malformed row 2026-05-14 03:26:21 +00:00
bc921666de feat: reject job submissions to 'lost_and_found' reserved queue in preCheckJobRequest 2026-05-14 03:19:34 +00:00
91e66b8b07 feat: implement create_lost_and_found() — synthetic queue+host via makeQueue/makeWorker (gated for unit tests) 2026-05-14 03:13:14 +00:00
e4c1bfb17f docs: update design doc status; add config-replication-impl-status.md with full implementation summary 2026-05-14 03:01:38 +00:00
40c7a93951 docs: add future work items 6-8 and clarify design doc safety gate
- Future Work §6: validate_host() implementation plan (CN allowlist,
  admin-cn flag, reject/log unauthorised OP_upgradeConfig requests)
- Future Work §7: OP_replConfig access control hardening (peer
  validation, rate-limiting, minimum_role check)
- Future Work §8: lost_and_found reserved-name validation in admin
  config tool, with migration path for pre-existing clusters
- config-replication-design.md: expand CONF_ENABLE_UPGRADE_CONFIG
  safety gate section with gating prerequisites
2026-05-13 18:21:44 +00:00
5ef14a2717 feat: implement handle_upgrade_config() (gated), push_config_to_standbys(), create_lost_and_found() stub
- Add do_upgrade_config_with_bytes() helper with full validate/decode/
  re-encode/save/push/restart logic gated by CONF_ENABLE_UPGRADE_CONFIG
- Add push_config_to_standbys() stub: logs connected standbys and returns
  0; full parallel fan-out deferred to Task 11 (typemap byte shims needed)
- Add send_upgrade_error() private helper for consistent error replies
- Expand create_lost_and_found() stub with WARN log explaining Phase 2
  deferral; core config-replication feature works without it
- Declare push_config_to_standbys() in config_repl.h
2026-05-13 18:12:32 +00:00
a95476be4e feat: add schedule_checkpoint() with WAL record-count trigger and idempotency CAS guard 2026-05-13 17:56:46 +00:00
8f4db308da feat: implement handle_config_request(), fetch_config_from_primary(), handle_controller_join()
- handle_config_request(): primary-side handler sends up-to-date flag or
  version_tag; SHA-256 integrity check guards against in-place file changes;
  sha256/bytes fields left NULL pending Task 11 typemap shims
- fetch_config_from_primary(): standby fetch with exponential backoff retry
  (20 attempts, 500ms..5s); falls back to saved config via load_primary_config();
  do_one_config_fetch() stubbed (-ENOSYS) until Task 11 wires capnp over SSL
- handle_controller_join(): registers standby endpoint in ha.standby_endpoints
  via zarray_store() for OP_upgradeConfig fan-out; sends success reply
- Moved load_primary_config() from myconf.c to config_repl.c so the unit test
  binary (which links config_repl.c but not myconf.c) can resolve it
2026-05-13 17:46:56 +00:00
93b8616f11 fix: capture am_i_primary() result once; set ha->role before phase2; cluster_init wrapper cleanup on failure
- myapp.c: capture am_i_primary() into is_primary (avoids redundant
  second probe call); after load_primary_config() succeeds, record
  CTRL_PRIMARY role via atomic_store_explicit so cluster_init_phase2()
  sees the correct role (ha_init() defaults to CTRL_STANDBY)
- myapp.c: add #include "ha.h" for CTRL_PRIMARY, atomic_store_explicit,
  and memory_order_release
- cluster.c: cluster_init() wrapper now calls cluster_fini(c) before
  returning on create_ssl_context failure, hook failure, and
  cluster_init_phase2 failure — prevents SSL ctx and phase1 resource leak
2026-05-13 17:32:32 +00:00
6b06aa02d9 feat: split cluster_init() into phase1/phase2; update myapp_run() for two-phase startup with am_i_primary gating
- cluster_init_phase1(): hooks, HA init (priority from --peers), standby_endpoints zarray, cbuf
- cluster_init_phase2(): SSL ctx from ha.ssl_ctx, cluster_config guard, kvmgr sizing, iomgr, endpoint, persist, role promotion, create_lost_and_found, persist_recover
- cluster_init(): legacy wrapper calling both phases with inline SSL init for backward compat
- myapp_run(): phase1 → SSL init → am_i_primary → load_primary_config/fetch_config_from_primary → phase2 → start → run
- myreq_handler(): add OPCode_replConfig and OPCode_upgradeConfig dispatch
- handle_endpoint_error(): prune standby_endpoints on HostRole_controller disconnect
- cluster_run(): log restart_requested on exit
- config_repl.c: add create_lost_and_found, handle_config_request, handle_upgrade_config stubs
- config_repl.h: add declarations for new stubs; include netio.h + request.h
- cluster.h: declare cluster_init_phase1 and cluster_init_phase2
- myconf.c: fix FATAL → ERROR (FATAL macro undefined); add fetch_config_from_primary stub
2026-05-13 17:06:45 +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
8d86a1bcfe fix: get_default_conf bypass load_cluster_config to avoid dangling hook pointer (UAF) 2026-05-13 16:13:26 +00:00
6141264219 fix: free cluster_config on error paths in load_primary_config; fix get_default_conf wrapper leak 2026-05-13 16:11:58 +00:00
cd02cf40d2 feat: add load_primary_config(), myconf_fini(); remove static cf global from myconf.c
- load_primary_config(): resolves conf/current, reads raw bytes, computes
  SHA-256 tag, decodes Cap'n Proto via load_cluster_config_from_file(),
  checks reserved names, sets config_generation, checks staleness
- myconf_fini(): frees conffile and cluster_config (calls free_ClusterConfig)
- Remove static cf global from myconf.c; get_default_conf() now uses a
  local struct cluster_configuration* via load_cluster_config()
- Add load_primary_config_for_test() under XCE_TESTING in config_repl.c
  to test path resolution without triggering FATAL
- Add xce/cluster_def.h include to config_repl.c and test_config_repl.c
  so cluster_t is complete when XCE_TESTING is active
- TDD: test_load_primary_config_missing_returns_error passes (18/18)
2026-05-13 16:06:18 +00:00
ce62406f2c fix: validate --conf-keep-n >= 1 and --conf-stale-timeout >= 0 in argument parsing 2026-05-13 16:00:09 +00:00
e74fd2aac3 feat: main.c — null conffile (now heap-allocated), add --conf-keep-n/--conf-stale-timeout flags, peers validation 2026-05-13 15:57:02 +00:00
2f2bfa9a3c fix: conf_trim early-return on missing current pointer; check fsync/fseek return values 2026-05-13 15:53:40 +00:00
491c2550c2 feat: add config_repl Phase 1 — HEAD-file storage, SHA-256, trim, stale check, sanitise_cn
- config_repl.h/.c: atomic versioned file save, pointer file, trim, stale check
- test_config_repl.c: 17 Unity tests covering all Phase 1 storage functions
- typemap.h: add repl/heartbeat types + union members for xce_request_t/xce_reply_t
- clusterconfig.h: add config_generation field to cluster_config_t (capnp schema ref)
- meson.build: add config_repl.c and test_config_repl.c to build targets
- controller_test.c: register test_config_repl dispatch function
2026-05-13 15:45:28 +00:00
1c4a103a66 fix: resolve probe_ctx_t type tag, add DEFAULT_MAX_WAL_RECORDS macro, fix atomic type consistency, move ha_seed_jitter to ha.c, add API doc comments 2026-05-13 14:27:07 +00:00
8a9fce1be4 fix: ha_seed_jitter loop-until-full partial read; byteorder.h musl portability 2026-05-13 14:18:43 +00:00
2c375cf476 feat: add config replication fields to myconf_t, cluster_t, ha_state_t, persist_t; create byteorder.h 2026-05-13 14:15:30 +00:00
78adf3f843 fix: normalize capnp union arm naming to lowercase; fix UpgradeConfigRequest field order
- Rename replConfigRequestMsg/replConfigPushRequestMsg/upgradeConfigRequestMsg
  to replconfigrequestmsg/replconfigpushrequestmsg/upgradeconfigrequestmsg in
  Request.body union to match existing lowercase convention
- Rename replConfigReplyMsg/replConfigPushReplyMsg/upgradeConfigReplyMsg
  to replconfigreplymsg/replconfigpushreplymsg/upgradeconfigreplymsg in
  RequestReply.data union
- Swap UpgradeConfigRequest fields so sha256@0/bytes@1 matches sibling
  ReplConfigPushRequest pattern
- Move HeartbeatMsg out of the config replication section into its own
  '# ── HA heartbeat ──' section above the replication structs
2026-05-13 14:10:33 +00:00
683c092b77 feat: add replConfig/replConfigPush/upgradeConfig opcodes and message structs to capnp schema 2026-05-13 14:06:51 +00:00
6a47ef5c39 save document 2026-05-13 11:05:04 +00:00
e51687a354 Merge branch 'scheduler' into working 2026-05-13 11:02:43 +00:00
48f3a2d99e update .gitignore 2026-05-13 11:02:34 +00:00
5dbe404015 save kiro settings 2026-05-13 11:00:32 +00:00
033f34c07f add kiro-sdd documents 2026-05-13 10:58:51 +00:00
e847a32546 add user rshen 2026-05-13 10:51:32 +00:00
aae4c672b5 make unsatisfy_() just print unmeet resources 2026-05-13 10:48:38 +00:00