diff --git a/conanfile.py b/conanfile.py index 5c0f1fed..f60c3153 100644 --- a/conanfile.py +++ b/conanfile.py @@ -10,7 +10,7 @@ class HomeBlocksConan(ConanFile): name = "homeblocks" - version = "6.0.19" + version = "6.0.20" homepage = "https://github.com/eBay/HomeBlocks" description = "Block Store built on HomeStore" diff --git a/src/lib/craft/craft_repl_dev.cpp b/src/lib/craft/craft_repl_dev.cpp index 09affc30..fe8ba0a6 100644 --- a/src/lib/craft/craft_repl_dev.cpp +++ b/src/lib/craft/craft_repl_dev.cpp @@ -372,6 +372,9 @@ class HomeStoreCraftJournalBackend : public CraftJournalBackend { co_return ok(); } + // The log store's tail: the highest seq_num written and not rolled back. + async_result< int64_t > tail_lsn() override { co_return static_cast< int64_t >(logstore_->tail_lsn()); } + private: shared< homestore::home_log_store > logstore_; uint64_t vol_ordinal_; @@ -385,13 +388,13 @@ unique< CraftJournalBackend > make_homestore_journal_backend(shared< homestore:: // Thin wrapper over homestore::cp_mgr(). One instance is shared by every volume's CraftReplDev. checkpoint_trigger_fn_t make_homestore_checkpoint_trigger_fn() { - return [](bool force) -> async_status { - if (co_await homestore::cp_mgr().trigger_cp_flush(force)) co_return ok(); + return [](bool force) -> async_result< bool > { + if (co_await homestore::cp_mgr().trigger_cp_flush(force)) co_return true; // cp_mgr().trigger_cp_flush() returns false, synchronously, when a flush is already in // progress (cp_mgr.cpp: m_in_flush_phase). That's expected and harmless when force=false // (this trigger's only current caller, fire_checkpoint_trigger, coalesces with any in-flight // flush on purpose). Only a force=true false return is a real failure worth surfacing. - if (!force) co_return ok(); + if (!force) co_return false; co_return std::unexpected(make_error_condition(volume_error::INTERNAL_ERROR)); }; } @@ -823,12 +826,74 @@ void CraftReplDev::fire_checkpoint_trigger(int64_t commit_lsn_snapshot) { // back-to-back flushes under high commit throughput (see checkpoint_trigger_fn_t's doc comment). // Detached (fire-and-forget): nothing here depends on the flush completing. A failure is logged, // not propagated, same posture as catch-up/fetch failures elsewhere in this class. - auto self = shared_from_this(); - detail::detach([self, commit_lsn_snapshot]() -> async_status { - if (auto cp = co_await self->checkpoint_trigger_(false); !cp) + // A captureless coroutine taking its state as parameters: the frame owns them. (A capturing lambda's closure is + // a temporary destroyed at the end of this statement, while the detached frame still refers to it.) + detail::detach([](shared< CraftReplDev > self, int64_t commit_lsn_snapshot) -> async_status { + auto cp = co_await self->checkpoint_trigger_(false); + if (!cp) { LOGE("checkpoint trigger failed at commit_lsn={}: {}", commit_lsn_snapshot, cp.error().message()); + co_return ok(); + } + // Coalesced into a flush that was already running: that flush may predate some of the slots applied up + // to commit_lsn_snapshot, so it proves nothing about them. The next trigger will. + if (!*cp) co_return ok(); + // S8: every slot <= commit_lsn_snapshot was applied to the index before this checkpoint started, so a + // restart may resume commit from here and the journal below it is no longer needed for local recovery. + { + std::lock_guard lk{self->state_mu_}; + if (commit_lsn_snapshot <= self->durable_.durable_commit_lsn) co_return ok(); + self->durable_.durable_commit_lsn = commit_lsn_snapshot; + auto& empties = self->durable_.empty_lsns; + empties.erase(empties.begin(), empties.upper_bound(commit_lsn_snapshot)); + } + if (auto r = co_await self->persist_state(); !r) { + LOGE("persisting durable commit_lsn={} failed: {}", commit_lsn_snapshot, r.error().message()); + co_return ok(); + } + // The frontier is durable: a restart never re-applies a slot <= it, so the blocks those slots replaced can go. + std::vector< homestore::blk_id > releasable; + { + std::lock_guard lk{self->state_mu_}; + auto& d = self->deferred_frees_; + auto const keep = std::stable_partition( + d.begin(), d.end(), [commit_lsn_snapshot](auto const& e) { return e.first > commit_lsn_snapshot; }); + for (auto it = keep; it != d.end(); ++it) + releasable.push_back(it->second); + d.erase(keep, d.end()); + } + co_await self->free_blocks(commit_lsn_snapshot, std::move(releasable)); co_return ok(); - }()); + }(shared_from_this(), commit_lsn_snapshot)); +} + +// ─── superseded blocks (S8) ────────────────────────────────────────────────── +// +// A block an index write replaces belongs to an OLDER slot. With restart recovery (a state store), freeing it at +// once is unsafe: until a checkpoint covering the replacing slot is durable, a restart re-applies the older slot +// from the journal and would point the index at a block that may already belong to someone else (review on #201). +// So the free waits until the durable commit frontier reaches the replacing slot (fire_checkpoint_trigger releases +// them). A crash before that leaks the waiting blocks (bounded by the window since the last durable checkpoint) -- +// never corruption. Without a state store there is no restart replay, so blocks are freed at once, as before. +async_status CraftReplDev::release_superseded(int64_t replacing_lsn, std::vector< homestore::blk_id > blocks) { + if (blocks.empty()) co_return ok(); + { + std::lock_guard lk{state_mu_}; + if (state_store_) { + for (auto const& b : blocks) + deferred_frees_.emplace_back(replacing_lsn, b); + co_return ok(); + } + } + co_await free_blocks(replacing_lsn, std::move(blocks)); + co_return ok(); +} + +async_status CraftReplDev::free_blocks(int64_t lsn, std::vector< homestore::blk_id > blocks) { + for (auto const& blk : blocks) { + if (auto fr = co_await journal_->free_data(homestore::multi_blk_id{blk}); !fr) + LOGE("free_data failed reclaiming blk={} lsn={}: {}", blk.to_string(), lsn, fr.error().message()); + } + co_return ok(); } // ─── commit() (internal; never a wire op) ──────────────────────────────────── @@ -841,13 +906,14 @@ void CraftReplDev::fire_checkpoint_trigger(int64_t commit_lsn_snapshot) { async_result< int64_t > CraftReplDev::commit_impl(int64_t upto_lsn, write_index_fn_t write_fn, delete_index_fn_t delete_fn) { - int64_t commit_lsn, last_append_lsn; + int64_t commit_lsn, last_append_lsn, replay_upto; { std::lock_guard lk{state_mu_}; if (commit_running_) co_return state_.commit_lsn; // another run is already advancing commit_running_ = true; commit_lsn = state_.commit_lsn; last_append_lsn = state_.last_append_lsn; + replay_upto = replay_upto_; } // Tracks the highest lsn successfully applied so far, updated per-iteration below WITHOUT // state_mu_. Written to the shared state_.commit_lsn exactly once, in @@ -885,6 +951,9 @@ async_result< int64_t > CraftReplDev::commit_impl(int64_t upto_lsn, write_index_ is_empty = empty_lsns_.contains(lsn); } if (is_missing) break; // stall at the first hole -- not an error + // A slot journalled before the last restart may be re-applied over an index that already holds a newer + // slot's block for the same LBA: never free what the re-apply replaces (see replay_upto_). + bool const replaying = lsn <= replay_upto; // Retires the overlay entry for each LBA in [start_lba, end_lba] whose recorded lsn equals // retiring_lsn -- shared by the data-apply path below and the is_empty path further down (a @@ -921,11 +990,8 @@ async_result< int64_t > CraftReplDev::commit_impl(int64_t upto_lsn, write_index_ if (auto r = delete_fn(start_lba, end_lba, freed); !r) co_return std::unexpected(r.error()); // Reclaim inline, same as write()'s own free_data call sites -- free errors are // logged but non-fatal (the block is merely leaked, not corrupted). - for (auto const& blk : freed) { - if (auto fr = co_await journal_->free_data(homestore::multi_blk_id{blk}); !fr) - LOGE("free_data failed reclaiming blk={} lsn={}: {}", blk.to_string(), lsn, - fr.error().message()); - } + if (replaying) freed.clear(); + co_await release_superseded(lsn, std::move(freed)); } else { // Decompose the slot's blkid into per-LBA single-block BlockInfo entries -- same shape // as write()'s own overlay-population decomposition and volume.cpp's non-CRAFT path. @@ -955,12 +1021,12 @@ async_result< int64_t > CraftReplDev::commit_impl(int64_t upto_lsn, write_index_ // old_blkid == new_blkid means this slot was already applied (crash-replay of an // idempotent commit before commit_lsn was durably persisted): the index already holds // this exact blkid, so freeing it here would free a block the index still references. + std::vector< homestore::blk_id > superseded; for (auto const& [_, info] : blocks_info) { - if (!info.old_blkid.is_valid() || info.old_blkid == info.new_blkid) continue; - if (auto fr = co_await journal_->free_data(homestore::multi_blk_id{info.old_blkid}); !fr) - LOGE("free_data failed reclaiming blk={} lsn={}: {}", info.old_blkid.to_string(), lsn, - fr.error().message()); + if (replaying || !info.old_blkid.is_valid() || info.old_blkid == info.new_blkid) continue; + superseded.push_back(info.old_blkid); } + co_await release_superseded(lsn, std::move(superseded)); } retire_overlay_range(start_lba, end_lba, lsn); @@ -993,6 +1059,9 @@ async_result< int64_t > CraftReplDev::commit_impl(int64_t upto_lsn, write_index_ } async_result< int64_t > CraftReplDev::commit(int64_t upto_lsn) { +#ifdef _PRERELEASE + if (test_write_fn_) co_return co_await commit_impl(upto_lsn, test_write_fn_, test_delete_fn_); +#endif if (!indx_tbl_) { // No index configured (write-path-only tests): nothing to apply, no-op safely. std::lock_guard lk{state_mu_}; @@ -1618,7 +1687,18 @@ async_status CraftReplDev::rebuild_overlay() { if (is_missing || is_empty) continue; auto slot_r = co_await journal_->read_slot(lsn); - if (!slot_r) co_return std::unexpected(slot_r.error()); + if (!slot_r) { + // Never journalled here (or rolled back): after a restart the range above the durable commit frontier + // is rebuilt from the journal, so a slot that is not in it is simply missing -- catch-up fills it. + // Any other read error is a real fault. + auto const e = slot_r.error(); + if (e == std::errc::result_out_of_range || e == std::errc::no_such_file_or_directory) { + std::lock_guard lk{state_mu_}; + missing_lsns_.insert(lsn); + continue; + } + co_return std::unexpected(e); + } auto& slot = *slot_r; lba_t const start_lba = static_cast< lba_t >(slot.lba_off_bytes) / lba_size_; @@ -1699,10 +1779,7 @@ void CraftReplDev::CraftRaftListener::on_commit(int64_t lsn, sisl::blob const& h return; } uint64_t const upto = reinterpret_cast< const LoginAbortedPayload* >(key.cbytes())->abort_upto; - owner_->enqueue_apply(lsn, [dev = owner_, upto]() -> async_status { - dev->apply_login_aborted(upto); - co_return ok(); - }); + owner_->enqueue_apply(lsn, [dev = owner_, upto]() -> async_status { return dev->apply_login_aborted(upto); }); break; } default: @@ -1754,11 +1831,25 @@ async_status CraftReplDev::drain_apply_queue() { } // A failed apply is logged by the apply itself and does not stop the queue: a RAFT entry is // committed, so later entries must still apply, in order. - if (auto r = co_await next.fn(); !r) { - LOGE("drain_apply_queue: apply of raft lsn={} failed: {}", next.raft_lsn, r.error().message()); - } - std::lock_guard lk{state_mu_}; - state_.last_applied_raft_idx = std::max(state_.last_applied_raft_idx, next.raft_lsn); + bool const applied = static_cast< bool >(co_await next.fn()); + if (!applied) LOGE("drain_apply_queue: apply of raft lsn={} failed", next.raft_lsn); + { + std::lock_guard lk{state_mu_}; + state_.last_applied_raft_idx = std::max(state_.last_applied_raft_idx, next.raft_lsn); + // The durable index stops advancing at the first entry that failed to apply (review on #201): a restart + // then re-applies from it -- e.g. an InternalLogin whose truncation failed gets another chance instead of + // being skipped for good. The entries after it are re-applied too; every apply is replay-safe. In this + // process the queue moves on: a committed entry cannot be un-committed, and the next login repairs. + if (!applied) apply_failed_ = true; + if (!apply_failed_) + durable_.last_applied_raft_idx = std::max(durable_.last_applied_raft_idx, next.raft_lsn); + } + // After the entry's own durable effects (each apply persists what it must, ahead of the change), so a + // restart re-applies an entry rather than skip one that never reached disk. A failure here only means the + // entry may be re-applied after a restart; every apply is replay-safe. + if (auto r = co_await persist_state(); !r) + LOGE("drain_apply_queue: persisting last applied raft lsn={} failed: {}", next.raft_lsn, + r.error().message()); } } @@ -1776,11 +1867,9 @@ async_status CraftReplDev::drain_apply_queue() { // correctness for that case currently rests entirely on HomeStore's calling convention (observed today: // fired at most once per instance per restart cycle), not on anything this class enforces itself. // -// Currently a no-op in practice: CraftPartitionState itself (state_) has no superblock-recovery path -// yet, so commit_lsn/last_append_lsn are still at their default -1/-1 when this fires, making -// rebuild_overlay()'s walk range empty and run_recovery() clear recovering_ almost immediately. This -// gate is still the correct wiring for once real superblock recovery populates state_ before this -// fires. +// With a state store wired (S8), run_recovery() first restores state_ from the durable image and the journal, +// then rebuilds the overlay over (commit_lsn, last_append_lsn]. Without one, state_ stays at its defaults and the +// walk is empty, as before S8. void CraftReplDev::CraftRaftListener::on_restart() { owner_->recovering_.store(true, std::memory_order_release); detail::detach(owner_->run_recovery()); @@ -1798,7 +1887,11 @@ void CraftReplDev::CraftRaftListener::on_restart() { // data is not. There is deliberately no self-healing path out of this state here -- an operator // decision (or a future re-sync-from-peer mechanism) is required. async_status CraftReplDev::run_recovery() { - auto r = co_await rebuild_overlay(); + // S8: state_ comes back from the durable image and the journal first; rebuild_overlay then walks the range + // that restore set up (and marks slots the journal does not hold as missing). A failure of either step faults + // the partition the same way: an image that cannot be loaded must never restart as an empty partition. + auto r = co_await restore_state(); + if (r) r = co_await rebuild_overlay(); if (!r) { LOGE("rebuild_overlay failed during restart recovery: {} -- partition permanently faulted, will " "not accept client I/O (see recovery_faulted_'s doc comment)", @@ -1807,9 +1900,183 @@ async_status CraftReplDev::run_recovery() { co_return r; } recovering_.store(false, std::memory_order_release); + // Resume a catch-up the restart interrupted. The runner itself re-derives what is still missing. + int64_t resume_to = -1; + { + std::lock_guard lk{state_mu_}; + if (durable_.catch_up_target > state_.commit_lsn) resume_to = durable_.catch_up_target; + } + if (resume_to >= 0) request_catch_up(resume_to); co_return r; } +// ─── durable state (S8 / SDSTOR-22745) ─────────────────────────────────────── + +namespace { +constexpr uint64_t k_durable_magic = 0x31425354'46415243ull; // "CRAFTSB1" little-endian +constexpr uint32_t k_durable_version = 1; +#pragma pack(push, 1) +struct DurableHeader { + uint64_t magic; + uint32_t version; + uint32_t n_empty; + uint64_t term; + uint64_t fence_term; + uint64_t client_token; + uint64_t aborted_upto; + int64_t last_applied_raft_idx; + int64_t durable_commit_lsn; + int64_t sync_watermark; + int64_t catch_up_target; +}; +#pragma pack(pop) +} // namespace + +std::vector< uint8_t > encode_durable_state(CraftDurableState const& s) { + DurableHeader h{k_durable_magic, + k_durable_version, + static_cast< uint32_t >(s.empty_lsns.size()), + s.term, + s.fence_term, + s.client_token, + s.aborted_upto, + s.last_applied_raft_idx, + s.durable_commit_lsn, + s.sync_watermark, + s.catch_up_target}; + std::vector< uint8_t > out(sizeof(h) + s.empty_lsns.size() * sizeof(int64_t)); + std::memcpy(out.data(), &h, sizeof(h)); + size_t off = sizeof(h); + for (int64_t lsn : s.empty_lsns) { + std::memcpy(out.data() + off, &lsn, sizeof(lsn)); + off += sizeof(lsn); + } + return out; +} + +std::optional< CraftDurableState > decode_durable_state(uint8_t const* buf, size_t len) { + if (buf == nullptr || len < sizeof(DurableHeader)) return std::nullopt; + DurableHeader h; + std::memcpy(&h, buf, sizeof(h)); + if (h.magic != k_durable_magic || h.version != k_durable_version) return std::nullopt; + if (len != sizeof(h) + static_cast< size_t >(h.n_empty) * sizeof(int64_t)) return std::nullopt; + CraftDurableState s{h.term, + h.fence_term, + h.client_token, + h.aborted_upto, + h.last_applied_raft_idx, + h.durable_commit_lsn, + h.sync_watermark, + h.catch_up_target, + {}}; + int64_t prev = s.durable_commit_lsn; + for (uint32_t i = 0; i < h.n_empty; ++i) { + int64_t lsn; + std::memcpy(&lsn, buf + sizeof(h) + i * sizeof(int64_t), sizeof(lsn)); + if (lsn <= prev) return std::nullopt; // must be strictly ascending and above the durable frontier + s.empty_lsns.insert(s.empty_lsns.end(), lsn); + prev = lsn; + } + return s; +} + +async_status CraftReplDev::persist_state() { + if (!state_store_) co_return ok(); + auto self = shared_from_this(); + uint64_t gen; + bool start = false; + { + std::lock_guard lk{state_mu_}; + gen = ++persist_req_gen_; + if (!persist_running_) { + persist_running_ = true; + start = true; + } + } + if (start) detail::detach(run_persist()); + auto done = [this, gen] { + std::lock_guard lk{state_mu_}; + return persist_done_gen_ >= gen; + }; + // notify_all wakes every waiter whenever ANY image lands; loop until one covering this ticket has. + while (!done()) + co_await persist_wait_.wait_until(done); + std::lock_guard lk{state_mu_}; + if (persist_ok_gen_ >= gen) co_return ok(); + co_return std::unexpected(std::make_error_condition(std::errc::io_error)); +} + +// The single writer behind persist_state(). Each round persists the newest image, which covers every ticket +// issued before it was taken; rounds repeat while new tickets arrive. +async_status CraftReplDev::run_persist() { + auto self = shared_from_this(); + for (;;) { + CraftDurableState image; + uint64_t gen; + { + std::lock_guard lk{state_mu_}; + if (persist_done_gen_ >= persist_req_gen_) { + persist_running_ = false; + co_return ok(); + } + image = durable_; + gen = persist_req_gen_; + } + auto r = co_await state_store_->persist(image); + { + std::lock_guard lk{state_mu_}; + persist_done_gen_ = gen; + if (r) { + persist_ok_gen_ = gen; + } else { + LOGE("persisting durable partition state failed: {}", r.error().message()); + } + } + persist_wait_.notify_all(); // never under state_mu_: woken waiters re-take it in their predicate + } +} + +async_status CraftReplDev::restore_state() { + if (!state_store_) co_return ok(); + auto loaded = state_store_->load(); + if (!loaded) { + LOGE("restore_state: durable partition state unreadable: {}", loaded.error().message()); + co_return std::unexpected(loaded.error()); + } + if (!*loaded) co_return ok(); // never persisted: a fresh partition + CraftDurableState const& d = **loaded; + + auto tail = co_await journal_->tail_lsn(); + if (!tail) { + LOGE("restore_state: journal tail unavailable: {}", tail.error().message()); + co_return std::unexpected(tail.error()); + } + { + std::lock_guard lk{state_mu_}; + durable_ = d; + state_.term = d.term; + state_.fence_term = d.fence_term; + state_.client_token = d.client_token; + state_.aborted_upto = d.aborted_upto; + state_.last_applied_raft_idx = d.last_applied_raft_idx; + state_.commit_lsn = d.durable_commit_lsn; + state_.last_append_lsn = std::max({*tail, d.sync_watermark, d.durable_commit_lsn}); + empty_lsns_ = std::unordered_set< int64_t >(d.empty_lsns.begin(), d.empty_lsns.end()); + missing_lsns_.clear(); // rebuild_overlay marks every slot above commit_lsn the journal does not hold + replay_upto_ = std::max(*tail, d.durable_commit_lsn); + last_checkpoint_lsn_ = d.durable_commit_lsn; + } + { + std::lock_guard lk{apply_mu_}; + last_enqueued_raft_idx_ = std::max(last_enqueued_raft_idx_, d.last_applied_raft_idx); + } + LOGI("restore_state: term={} fence_term={} commit_lsn={} journal tail={} sync_watermark={} empties={} " + "last_applied_raft_idx={}", + d.term, d.fence_term, d.durable_commit_lsn, *tail, d.sync_watermark, d.empty_lsns.size(), + d.last_applied_raft_idx); + co_return ok(); +} + // ─── Leader pre-resolution (S5 / SDSTOR-22907) ──────────────────────────────── // // candidates is the union of missing_lsns_ ∩ [0, upto] and (last_append_lsn, upto] minus empty_lsns_ @@ -1944,12 +2211,14 @@ async_result< std::vector< int64_t > > CraftReplDev::pre_resolve_slots(int64_t u LOGE("pre_resolve_slots: write_slot failed lsn={}: {} -- leaving as unresolved", slot->lsn, res.error().message()); if (blkid_allocated) { - detail::detach([self, blkid, lsn = slot->lsn]() -> async_status { - if (auto fr = co_await self->journal_->free_data(blkid); !fr) - LOGE("pre_resolve_slots: free_data failed after write_slot failure lsn={}: {}", lsn, - fr.error().message()); - co_return ok(); - }()); + // Captureless: the detached frame must own its state (see fire_checkpoint_trigger). + detail::detach( + [](shared< CraftReplDev > self, homestore::multi_blk_id blkid, int64_t lsn) -> async_status { + if (auto fr = co_await self->journal_->free_data(blkid); !fr) + LOGE("pre_resolve_slots: free_data failed after write_slot failure lsn={}: {}", lsn, + fr.error().message()); + co_return ok(); + }(self, blkid, slot->lsn)); } continue; } @@ -2002,6 +2271,10 @@ async_status CraftReplDev::apply_sync_rs_commit_lsn(int64_t rs_commit_lsn, uint6 // Exclusivity comes from RAFT's commit ordering plus the term fence every other IO already // checks (see apply_internal_login's header comment), not from an equality check here. + // A verdict at or below commit_lsn is for a slot already resolved and applied (after a restart: at or below + // the durable frontier, whose verdicts were dropped from the image). Re-freeing its journal record's blocks + // would free them twice (review on #201), so such verdicts are ignored. + std::erase_if(empty_slots, [this](int64_t lsn) { return lsn <= state_.commit_lsn; }); for (int64_t lsn : empty_slots) { bool const was_missing = missing_lsns_.erase(lsn) > 0; if (!was_missing && lsn <= state_.last_append_lsn && !empty_lsns_.contains(lsn)) { to_free.insert(lsn); } @@ -2014,6 +2287,21 @@ async_status CraftReplDev::apply_sync_rs_commit_lsn(int64_t rs_commit_lsn, uint6 if (!empty_lsns_.contains(lsn)) missing_lsns_.insert(lsn); } state_.last_append_lsn = std::max(state_.last_append_lsn, rs_commit_lsn); + + // S8 write-ahead: the verdicts (above the durable commit frontier), the watermark and the catch-up target + // must be durable BEFORE any block is freed below. Otherwise a restart re-applies this entry with no + // memory of the verdicts and frees the same blocks a second time. + for (int64_t lsn : empty_slots) + if (lsn > durable_.durable_commit_lsn) durable_.empty_lsns.insert(lsn); + durable_.sync_watermark = std::max(durable_.sync_watermark, rs_commit_lsn); + durable_.catch_up_target = std::max(durable_.catch_up_target, rs_commit_lsn); + } + + if (auto r = co_await persist_state(); !r) { + // Leak rather than risk a double free on replay: the blocks stay allocated under their (verdicted) slots. + LOGE("apply_sync_rs_commit_lsn: persisting verdicts failed: {} -- not freeing {} verdicted slot(s)", + r.error().message(), to_free.size()); + to_free.clear(); } if (!to_free.empty()) { @@ -2027,7 +2315,7 @@ async_status CraftReplDev::apply_sync_rs_commit_lsn(int64_t rs_commit_lsn, uint6 // Advance over everything already present, then hand the missing slots to catch-up. The catch-up runner runs // detached so a slow or unreachable peer never stalls the ordered apply queue (later entries). - advance_commit_after_sync(rs_commit_lsn); + co_await advance_commit_after_sync(rs_commit_lsn); request_catch_up(rs_commit_lsn); LOGT("apply_sync_rs_commit_lsn ok rs_commit_lsn={} client_token={}", rs_commit_lsn, client_token); co_return ok(); @@ -2087,12 +2375,12 @@ async_status CraftReplDev::run_catch_up() { } } if (ranges.empty() || peer_fetcher_ == nullptr) { - advance_commit_after_sync(target); + co_await advance_commit_after_sync(target); co_return ok(); } auto resolved = co_await catch_up_pass(std::move(ranges), term); - advance_commit_after_sync(target); + co_await advance_commit_after_sync(target); if (resolved && *resolved > 0) { failed_passes = 0; backoff = catch_up_min_backoff; @@ -2248,13 +2536,12 @@ async_result< bool > CraftReplDev::install_fetched_slot(JournalSlot& slot, uint6 if (!res) { LOGE("catch-up: write_slot failed lsn={}: {} -- leaving as missing", slot.lsn, res.error().message()); if (blkid_allocated) { - detail::detach([self, blkid, lsn = slot.lsn]() -> async_status { + // Captureless: the detached frame must own its state (see fire_checkpoint_trigger). + detail::detach([](shared< CraftReplDev > self, homestore::multi_blk_id blkid, int64_t lsn) -> async_status { if (auto fr = co_await self->journal_->free_data(blkid); !fr) - LOGE("catch-up: free_data failed after write_slot failure lsn={}: " - "{}", - lsn, fr.error().message()); + LOGE("catch-up: free_data failed after write_slot failure lsn={}: {}", lsn, fr.error().message()); co_return ok(); - }()); + }(self, blkid, slot.lsn)); } co_return false; } @@ -2268,18 +2555,42 @@ async_result< bool > CraftReplDev::install_fetched_slot(JournalSlot& slot, uint6 } if (voided_meanwhile) { LOGW("catch-up: lsn={} verdicted Empty during install -- reclaiming", slot.lsn); + // The verdict may still be on its way to disk (the Sync that installed it persists before ITS frees). Free + // only once it is durable: otherwise a crash replays that Sync with no memory of the verdict, finds this + // installed record, and frees the same blocks again (review on #201). If persisting fails, leak. + if (auto pr = co_await persist_state(); !pr) { + LOGE("catch-up: persisting verdict for lsn={} failed: {} -- not reclaiming", slot.lsn, + pr.error().message()); + co_return true; + } if (auto fr = co_await journal_->free_slot(slot.lsn); !fr) LOGE("catch-up: free_slot failed lsn={}: {} -- blocks may leak", slot.lsn, fr.error().message()); } co_return true; } -void CraftReplDev::advance_commit_after_sync(int64_t rs_commit_lsn) { +async_status CraftReplDev::advance_commit_after_sync(int64_t rs_commit_lsn) { // commit_lsn (CRAFT-Design) is the LOCAL CONTIGUOUS prefix, distinct from rs_commit_lsn (the // replica-set-wide watermark RAFT already agreed on): it must skip over Empty slots but never // advance past an unresolved Missing one, even if catch-up above left holes below rs_commit_lsn. // Mirrors craft_client's reference MemCraftReplica::apply_up_to. // + // With an index wired, the advance goes through commit(), which applies each slot to the index as it passes + // it (same rule: skip Empty, stop at Missing). Moving commit_lsn without that left the slots unapplied: + // commit() never revisits a slot below commit_lsn, and read() serves overlay entries only ABOVE commit_lsn, + // so a read of such an LBA returned the older index value (H9 in docs/craft/resync.md). It also made + // commit_lsn useless as a durable frontier for restart (S8). A commit() already running is left to finish; + // the next write/keep_alive/Sync carries the advance further, as for every other commit() caller. + bool has_index = indx_tbl_ != nullptr; +#ifdef _PRERELEASE + has_index = has_index || static_cast< bool >(test_write_fn_); +#endif + if (has_index) { + if (auto r = co_await commit(rs_commit_lsn); !r) + LOGE("advance_commit_after_sync: commit({}) failed: {}", rs_commit_lsn, r.error().message()); + co_return ok(); + } + // No index (the write-path-only unit tests): nothing to apply, advance the frontier alone. int64_t commit_lsn_snapshot; bool should_checkpoint; { @@ -2298,6 +2609,7 @@ void CraftReplDev::advance_commit_after_sync(int64_t rs_commit_lsn) { should_checkpoint = checkpoint_interval_crossed_locked(commit_lsn_snapshot); } if (should_checkpoint) fire_checkpoint_trigger(commit_lsn_snapshot); + co_return ok(); } // ─── InternalLogin apply (S5 / SDSTOR-22887; docs/craft/resync.md §4.6) ────── @@ -2325,6 +2637,7 @@ async_status CraftReplDev::apply_internal_login(uint64_t client_token, uint64_t // Local fence: from here on no new write of the old session is admitted, including on a replica that // missed the login poll (and so was never fenced by it). Lifted below by admitting the new term. state_.fence_term = std::max(state_.fence_term, term); + durable_.fence_term = std::max(durable_.fence_term, term); if (rs_commit_lsn && state_.last_append_lsn > *rs_commit_lsn) { if (state_.commit_lsn > *rs_commit_lsn) { // Cannot happen if the leader computed rs_commit_lsn as max(quorum.last_append): commit only @@ -2336,6 +2649,13 @@ async_status CraftReplDev::apply_internal_login(uint64_t client_token, uint64_t } } } + // The fence must survive a restart before the stale tail is touched: a replica that restarted unfenced + // would admit the old session's writes again (the in-memory fence above already rejects them now). + if (auto r = co_await persist_state(); !r) { + LOGE("apply_internal_login: persisting fence term={} failed: {} -- new session NOT admitted", term, + r.error().message()); + co_return r; + } if (do_truncate) { // Writes admitted before the fence may still be journalling a slot above the watermark; one finishing // after the rollback would recreate the stale tail. Wait for them (they cannot be acked: their @@ -2357,6 +2677,19 @@ async_status CraftReplDev::apply_internal_login(uint64_t client_token, uint64_t co_return r; } } + // Admission is made durable before it takes effect: once a new-term write is acked, a restart must not + // re-apply this InternalLogin (its truncation would destroy that write). With the term on disk the replay + // guard above turns the re-apply into a no-op. + { + std::lock_guard lk{state_mu_}; + durable_.term = std::max(durable_.term, term); + durable_.client_token = client_token; + } + if (auto r = co_await persist_state(); !r) { + LOGE("apply_internal_login: persisting session term={} failed: {} -- new session NOT admitted", term, + r.error().message()); + co_return r; + } { std::lock_guard lk{state_mu_}; state_.client_token = client_token; @@ -2372,11 +2705,31 @@ async_status CraftReplDev::apply_internal_login(uint64_t client_token, uint64_t // Lifts a fence left by a login that never committed its InternalLogin, so the current owner's session is // admitted again. A fence above abort_upto belongs to a newer login and is left alone. aborted_upto makes the // abort final: a late InternalLogin for an aborted term is ignored by apply_internal_login. -void CraftReplDev::apply_login_aborted(uint64_t abort_upto) { +// +// S8: aborted_upto is raised in memory at once (it only makes later InternalLogins no-ops: more restrictive). The +// fence is lowered only after the image is durable; if persisting fails the replica stays fenced (safe; the next +// login or LoginAborted repairs it). +async_status CraftReplDev::apply_login_aborted(uint64_t abort_upto) { + auto self = shared_from_this(); + bool lower_fence; + { + std::lock_guard lk{state_mu_}; + state_.aborted_upto = std::max(state_.aborted_upto, abort_upto); + durable_.aborted_upto = std::max(durable_.aborted_upto, abort_upto); + lower_fence = state_.fence_term > state_.term && state_.fence_term <= abort_upto; + if (durable_.fence_term > durable_.term && durable_.fence_term <= abort_upto) + durable_.fence_term = durable_.term; + } + if (auto r = co_await persist_state(); !r) { + LOGE("apply_login_aborted: persisting abort_upto={} failed: {} -- fence kept", abort_upto, r.error().message()); + co_return r; + } std::lock_guard lk{state_mu_}; - state_.aborted_upto = std::max(state_.aborted_upto, abort_upto); - if (state_.fence_term > state_.term && state_.fence_term <= abort_upto) { state_.fence_term = state_.term; } + // Re-check: a login poll or InternalLogin applied while persisting may have raised the fence above abort_upto. + if (lower_fence && state_.fence_term > state_.term && state_.fence_term <= abort_upto) + state_.fence_term = state_.term; LOGD("apply_login_aborted abort_upto={} fence_term={} term={}", abort_upto, state_.fence_term, state_.term); + co_return ok(); } } // namespace homeblocks diff --git a/src/lib/craft/craft_repl_dev.hpp b/src/lib/craft/craft_repl_dev.hpp index f45a2e9f..a0266bfc 100644 --- a/src/lib/craft/craft_repl_dev.hpp +++ b/src/lib/craft/craft_repl_dev.hpp @@ -67,7 +67,7 @@ struct CraftPartitionState { // the replica is fenced: it admits neither the old session nor the new one. uint64_t aborted_upto{0}; // every login term <= this was aborted (LoginAborted); its InternalLogin is a no-op int64_t last_applied_raft_idx{-1}; // highest RAFT log index applied -- replayed/duplicate entries at or below - // it are skipped. In-memory until S8 persists CraftPartitionState. + // it are skipped. Persisted (CraftDurableState) after each apply. int64_t all_committed_lsn{-1}; // client-computed set-wide min commit_lsn, piggybacked on keep_alive/write; // floors journal reclaim (S8: truncate below min(this, checkpointed apply // frontier)) -- S3 only captures it, the reclaim action itself is S8's job. @@ -152,6 +152,12 @@ class CraftJournalBackend { // blkid's byte length). Used by CraftReplDev::read() to fetch the bytes an index/overlay entry // only stores a block reference for. Mockable so read()'s tests stay light (no real HomeStore). virtual async_status read_data(homestore::multi_blk_id blkid, sisl::sg_list& dest) = 0; + // Highest lsn ever written and not rolled back (-1 for an empty journal). Restart recovery (S8) walks the + // slots between the durable commit frontier and this tail. Not every backend can answer: the default + // reports not_supported, which a recovery that needs it treats as a fault. + virtual async_result< int64_t > tail_lsn() { + co_return std::unexpected(std::make_error_condition(std::errc::operation_not_supported)); + } virtual ~CraftJournalBackend() = default; }; @@ -205,7 +211,12 @@ class CraftPeerFetcher { // (homestore::cp_mgr().trigger_cp_flush()). Injected into CraftReplDev so unit tests can exercise // the trigger without touching HomeStore. Production code passes make_homestore_checkpoint_trigger_fn()'s result. // Default (empty) leaves the trigger stubbed -- same posture as CraftPeerFetcher. -using checkpoint_trigger_fn_t = std::function< async_status(bool force) >; +// +// The result is true only when a checkpoint that started after the call has completed, i.e. everything applied to +// the index before the call is now durable. false means the request coalesced with a flush already in progress +// (force=false), which may not include the index state at the call. S8 records a durable commit frontier only on +// true (docs/craft/resync.md §4.11). +using checkpoint_trigger_fn_t = std::function< async_result< bool >(bool force) >; // Factory that wraps homestore::cp_mgr() (there is exactly one CPManager per HomeStore instance, // unlike make_homestore_journal_backend which is per-volume). Each CraftReplDev stores its own copy @@ -213,6 +224,49 @@ using checkpoint_trigger_fn_t = std::function< async_status(bool force) >; // factory's result alive themselves. Tests inject a plain callable directly. checkpoint_trigger_fn_t make_homestore_checkpoint_trigger_fn(); +// ─── Durable partition state (S8 / SDSTOR-22745) ───────────────────────────── +// +// The part of a partition's state that neither the journal nor the RAFT log gives back after a restart. Written +// AHEAD of the in-memory change it protects: CraftReplDev::durable_ is updated and persisted first, state_ second, +// so a crash between the two restarts at least as restrictive as before -- it never admits a term whose login was +// not made durable, and never forgets a fence it already answered under. +// +// Not here, and why: +// - last_append_lsn and the missing set come back from the journal itself: its tail, and a walk of the slots +// above durable_commit_lsn. last_append_lsn is raised to at least sync_watermark. +// - commit_lsn restarts at durable_commit_lsn, the frontier a completed checkpoint covers. Slots above it are +// re-applied to the index (CraftReplDev::replay_upto_ explains why that is safe). +struct CraftDurableState { + uint64_t term{0}; + uint64_t fence_term{0}; + uint64_t client_token{0}; + uint64_t aborted_upto{0}; + int64_t last_applied_raft_idx{-1}; // RAFT entries at or below are not re-applied after a restart + int64_t durable_commit_lsn{-1}; // commit frontier covered by a completed checkpoint + int64_t sync_watermark{-1}; // highest SyncRSCommitLSN rs applied; last_append_lsn >= this + int64_t catch_up_target{-1}; // catch-up resumes toward this after a restart + std::set< int64_t > empty_lsns; // Empty verdicts above durable_commit_lsn (below it they no longer matter) + + bool operator==(CraftDurableState const&) const = default; +}; + +// On-disk image of CraftDurableState: a fixed header, then the Empty verdicts as int64s. decode returns nullopt +// for anything malformed (bad magic or version, wrong length, verdicts not strictly ascending or at or below +// durable_commit_lsn). A superblock that fails to decode must fault the partition, never restart it empty. +std::vector< uint8_t > encode_durable_state(CraftDurableState const& s); +std::optional< CraftDurableState > decode_durable_state(uint8_t const* buf, size_t len); + +// Persistence seam for CraftDurableState, one per partition. Production keeps the encoded image in a HomeStore +// superblock (wired together with the CRAFT volume); tests inject an in-memory store. persist() returns only once +// the image is durable. CraftReplDev never issues two persist() calls at once. +class CraftStateStore { +public: + // The last persisted state; nullopt if nothing was ever persisted; an error if what is there is unusable. + virtual homestore::result< std::optional< CraftDurableState > > load() = 0; + virtual async_status persist(CraftDurableState const& s) = 0; + virtual ~CraftStateStore() = default; +}; + // ─── CraftReplDev ───────────────────────────────────────────────────────────── // // One instance per CRAFT-mode volume. Implements the full CRAFT data plane @@ -442,6 +496,16 @@ class CraftReplDev : public std::enable_shared_from_this< CraftReplDev > { // inject a mock. void set_checkpoint_trigger(checkpoint_trigger_fn_t fn) { checkpoint_trigger_ = std::move(fn); } + // Wires the durable partition state (S8). Must be called before the device serves anything or recovers: + // without a store nothing is persisted and a restart recovers nothing (the pre-S8 behaviour, still what the + // light unit tests use). + void set_state_store(unique< CraftStateStore > store) { state_store_ = std::move(store); } + // The image last handed to the store (or being handed to it). Test observability. + CraftDurableState durable_state() const { + std::lock_guard lk{state_mu_}; + return durable_; + } + // Overrides the commit_lsn delta between checkpoint triggers (default matches // sync_rs_commit_lsn_interval's own default of 128, tying checkpoint cadence to the periodic // SyncRSCommitLSN cadence). Production sets this from HB_DYNAMIC_CONFIG(sync_rs_commit_lsn_interval) @@ -472,6 +536,12 @@ class CraftReplDev : public std::enable_shared_from_this< CraftReplDev > { // logic (in-order apply, stall at a gap, Empty-slot skip, overlay retirement) against a fake // index instead of a real VolumeIndexTable. async_result< int64_t > commit_with(int64_t upto_lsn, write_index_fn_t write_fn, delete_index_fn_t delete_fn); + // Test seam: makes commit() itself (and so every caller of it, e.g. the Sync / catch-up advance) apply through + // these instead of a real index -- the light suite has no VolumeIndexTable. + void set_index_fns_for_test(write_index_fn_t write_fn, delete_index_fn_t delete_fn) { + test_write_fn_ = std::move(write_fn); + test_delete_fn_ = std::move(delete_fn); + } // Test seam for read(): runs the same read algorithm, but the index read operation is injected // rather than routed through indx_tbl_, so tests can exercise read()'s logic (index/overlay merge, @@ -617,13 +687,29 @@ class CraftReplDev : public std::enable_shared_from_this< CraftReplDev > { async_result< bool > install_fetched_slot(JournalSlot& slot, uint64_t term); // commit_lsn advance shared by both parts: skips Empty, stops at the first Missing slot <= rs_commit_lsn, // and fires the periodic checkpoint trigger. - void advance_commit_after_sync(int64_t rs_commit_lsn); + async_status advance_commit_after_sync(int64_t rs_commit_lsn); // InternalLogin: replay-guarded; raises a local fence (so a replica that missed the login poll stops // admitting the old session too), waits for already-admitted writes above rs_commit_lsn to finish, truncates // above rs_commit_lsn (v2 entries only; v1 carries none), then admits the new session term. async_status apply_internal_login(uint64_t client_token, uint64_t term, std::optional< int64_t > rs_commit_lsn); // LoginAborted: lift every fence at or below abort_upto; later InternalLogins for those terms are no-ops. - void apply_login_aborted(uint64_t abort_upto); + async_status apply_login_aborted(uint64_t abort_upto); + + // ── durable state (S8) ── + // Makes the current durable_ image durable. Callers update durable_ under state_mu_ first, then await this, + // then apply the change to state_ (write-ahead). Concurrent callers are coalesced onto one writer: each call + // returns once an image taken AFTER its own durable_ update has been persisted, and fails if that image's + // write failed. A no-op without a state store. + async_status persist_state(); + async_status run_persist(); + // Restart recovery, step 1 (before rebuild_overlay): load the durable image and rebuild state_ from it and the + // journal -- commit_lsn = durable_commit_lsn, last_append_lsn = max(journal tail, sync_watermark), the missing + // set from a walk of the journal above commit_lsn, Empty verdicts and control fields from the image. + async_status restore_state(); + // Frees blocks an index write superseded -- at once without a state store, otherwise once the durable commit + // frontier covers replacing_lsn (see the .cpp). + async_status release_superseded(int64_t replacing_lsn, std::vector< homestore::blk_id > blocks); + async_status free_blocks(int64_t lsn, std::vector< homestore::blk_id > blocks); // Shared admission check for write/read/keep_alive. Must be called with state_mu_ held. bool admits_term_locked(uint64_t term) const { return term == state_.term && state_.term >= state_.fence_term; } @@ -820,16 +906,36 @@ class CraftReplDev : public std::enable_shared_from_this< CraftReplDev > { iomgr::timer_token watchdog_token_; #ifdef _PRERELEASE std::atomic< int > watchdog_fire_count_{0}; // test-only; never present in production binaries + write_index_fn_t test_write_fn_; // set_index_fns_for_test + delete_index_fn_t test_delete_fn_; #endif checkpoint_trigger_fn_t checkpoint_trigger_{}; // empty until production wiring; unit tests inject a mock int64_t checkpoint_lsn_interval_{128}; // commit_lsn delta between checkpoint triggers; see // set_checkpoint_lsn_interval() - int64_t last_checkpoint_lsn_{-1}; // commit_lsn as of the last triggered checkpoint (guarded by state_mu_) - // FIXME(S8/SDSTOR-22745): defaults to -1 in lockstep with state_.commit_lsn - // When S8 wires recovering commit_lsn from the journal/superblock on restart, - // seed this to the recovered commit_lsn too (not -1), or the first post- - // restart apply_sync_rs_commit_lsn will unconditionally fire a checkpoint - // regardless of how recently one actually happened before the crash. + int64_t last_checkpoint_lsn_{-1}; // commit_lsn as of the last triggered checkpoint (guarded by state_mu_). + // restore_state() seeds it to the recovered commit_lsn. + + // ── durable state (S8) ── + unique< CraftStateStore > state_store_; // null: nothing persisted, nothing recovered + CraftDurableState durable_; // write-ahead image (guarded by state_mu_); see persist_state() + // persist_state() bookkeeping (guarded by state_mu_): every caller takes a ticket (persist_req_gen_); one writer + // (persist_running_) persists the latest image and records the highest ticket it covered (persist_done_gen_) + // and the highest one that was written successfully (persist_ok_gen_). + uint64_t persist_req_gen_{0}; + uint64_t persist_done_gen_{0}; + uint64_t persist_ok_gen_{0}; + bool persist_running_{false}; + bool apply_failed_{false}; // an apply failed in this process: durable_.last_applied_raft_idx stops advancing + detail::wait_list persist_wait_; // notified (never under state_mu_) whenever persist_done_gen_ moves + // Slots at or below this were journalled before the last restart and may already be in the durable index (a + // checkpoint can run between our triggers, so the index can be ahead of durable_commit_lsn). Re-applying such + // a slot must not free the block it replaces: that block may belong to a NEWER slot the index already holds, + // which the replay re-applies right after. Leaking those blocks is bounded by the replay window; freeing + // them would corrupt. Guarded by state_mu_; -1 = no replay window. + int64_t replay_upto_{-1}; + // Blocks superseded by an index write, waiting for the durable frontier to reach the replacing slot (first). + // Guarded by state_mu_. Lost on a crash (a bounded leak). + std::vector< std::pair< int64_t, homestore::blk_id > > deferred_frees_; }; } // namespace homeblocks diff --git a/src/lib/craft/tests/test_craft_commit.cpp b/src/lib/craft/tests/test_craft_commit.cpp index 91b7d5c8..ad892265 100644 --- a/src/lib/craft/tests/test_craft_commit.cpp +++ b/src/lib/craft/tests/test_craft_commit.cpp @@ -500,9 +500,9 @@ TEST_F(CraftCommitTest, WriteFnErrorAbortsCommit) { struct MockCraftCheckpointTrigger { int call_count{0}; - async_status operator()(bool) { + async_result< bool > operator()(bool) { ++call_count; - co_return ok(); + co_return true; } }; diff --git a/src/lib/craft/tests/test_craft_homestore_backend.cpp b/src/lib/craft/tests/test_craft_homestore_backend.cpp index b3732747..f3ada168 100644 --- a/src/lib/craft/tests/test_craft_homestore_backend.cpp +++ b/src/lib/craft/tests/test_craft_homestore_backend.cpp @@ -127,6 +127,28 @@ TEST_F(CraftHomeStoreBackendTest, TruncateToRollsBackRealLogStore) { EXPECT_EQ(logstore->tail_lsn(), 2); } +// S8 restart recovery reads the journal tail through the backend: it must follow writes and rollbacks. +TEST_F(CraftHomeStoreBackendTest, TailLsnFollowsWritesAndRollback) { + auto logstore = make_logstore(); + ASSERT_TRUE(logstore != nullptr); + auto backend = make_homestore_journal_backend(logstore, /* vol_ordinal = */ 0, k_page_size); + + for (int64_t lsn = 0; lsn <= 3; ++lsn) { + auto r = homeblocks::detail::sync_get(backend->write_slot(lsn, /* term = */ 1, /* lba = */ 0, /* len = */ 4096, + homestore::multi_blk_id{}, /* all_zeros = */ true, + std::vector< homestore::csum_t >{})); + ASSERT_TRUE(r.has_value()); + } + auto t = homeblocks::detail::sync_get(backend->tail_lsn()); + ASSERT_TRUE(t.has_value()); + EXPECT_EQ(*t, 3); + + ASSERT_TRUE(homeblocks::detail::sync_get(backend->truncate_to(1)).has_value()); + t = homeblocks::detail::sync_get(backend->tail_lsn()); + ASSERT_TRUE(t.has_value()); + EXPECT_EQ(*t, 1); +} + // read_slot must parse back exactly what write_slot wrote: header fields, the csum array, and the blkid. TEST_F(CraftHomeStoreBackendTest, ReadSlotReturnsCorrectData) { auto logstore = make_logstore(); @@ -401,6 +423,7 @@ TEST_F(CraftHomeStoreBackendTest, CheckpointTriggerHonorsForceFlag) { auto r = homeblocks::detail::sync_get(trigger(/* force = */ true)); ASSERT_TRUE(r.has_value()); + EXPECT_TRUE(*r); // a forced flush always runs, so it covers everything applied before the call } // cp_mgr()'s in-flight-flush gate (m_in_flush_phase) is a synchronous check-and-set at entry: the @@ -413,7 +436,7 @@ TEST_F(CraftHomeStoreBackendTest, CheckpointTriggerConcurrentForceFalseNeverFail auto trigger = make_homestore_checkpoint_trigger_fn(); constexpr int k_concurrent = 20; - std::vector< homestore::async_status > futs; // async_status is itself a sisl::async::task> + std::vector< homestore::async_result< bool > > futs; futs.reserve(k_concurrent); for (int i = 0; i < k_concurrent; ++i) { futs.push_back(trigger(/* force = */ false)); diff --git a/src/lib/craft/tests/test_craft_raft_entries.cpp b/src/lib/craft/tests/test_craft_raft_entries.cpp index 8414d7c2..2f73fb43 100644 --- a/src/lib/craft/tests/test_craft_raft_entries.cpp +++ b/src/lib/craft/tests/test_craft_raft_entries.cpp @@ -137,6 +137,43 @@ class MockCraftJournalBackend : public CraftJournalBackend { } bool has_slot(int64_t lsn) const { return slots.count(lsn) > 0; } + + bool fail_tail{false}; + async_result< int64_t > tail_lsn() override { + if (fail_tail) co_return std::unexpected(std::make_error_condition(std::errc::io_error)); + co_return slots.empty() ? -1 : slots.rbegin()->first; + } +}; + +// ── durable state store mock (S8) ───────────────────────────────────────────── +// +// Keeps the last persisted image and round-trips it through the real codec on load(), so restart tests also +// exercise encode/decode. fail_on_call fails one specific persist() call (1-based); fail_persist fails all. +class MockCraftStateStore : public CraftStateStore { +public: + std::optional< CraftDurableState > saved; + int persist_calls{0}; + bool fail_persist{false}; + int fail_on_call{0}; + bool fail_load{false}; + TestGate* gate{nullptr}; // when set, persist suspends until the gate opens + + result< std::optional< CraftDurableState > > load() override { + if (fail_load) return std::unexpected(std::make_error_condition(std::errc::io_error)); + if (!saved) return std::optional< CraftDurableState >{}; + auto bytes = encode_durable_state(*saved); + auto d = decode_durable_state(bytes.data(), bytes.size()); + if (!d) return std::unexpected(std::make_error_condition(std::errc::illegal_byte_sequence)); + return d; + } + async_status persist(CraftDurableState const& s) override { + int const call = ++persist_calls; + if (gate) co_await gate->wait(); + if (fail_persist || call == fail_on_call) + co_return std::unexpected(std::make_error_condition(std::errc::io_error)); + saved = s; + co_return ok(); + } }; // ── peer fetcher mock ───────────────────────────────────────────────────────── @@ -196,15 +233,16 @@ struct MockCraftCheckpointTrigger { int call_count{0}; bool last_force{false}; bool fail_next{false}; + bool flushed{true}; // false: the request coalesced with a flush already running - async_status operator()(bool force) { + async_result< bool > operator()(bool force) { ++call_count; last_force = force; if (fail_next) { fail_next = false; co_return std::unexpected(std::make_error_condition(std::errc::io_error)); } - co_return ok(); + co_return flushed; } }; @@ -273,6 +311,44 @@ class CraftRaftEntriesTest : public ::testing::Test { dev_->apply_sync_rs_commit_lsn(rs_commit_lsn, client_token, std::move(empty_slots))); } +public: + // S8 helpers: the private applies and persist_state() are reachable only through this (friended) fixture. + async_status abort_async(uint64_t upto) { return dev_->apply_login_aborted(upto); } + MockCraftStateStore* wire_store(CraftReplDev& dev) { + auto s = std::make_unique< MockCraftStateStore >(); + auto* raw = s.get(); + dev.set_state_store(std::move(s)); + return raw; + } + auto apply_login(uint64_t token, uint64_t term, std::optional< int64_t > rs) { + return homeblocks::detail::sync_get(dev_->apply_internal_login(token, term, rs)); + } + auto apply_abort(uint64_t upto) { return homeblocks::detail::sync_get(dev_->apply_login_aborted(upto)); } + async_status persist(CraftReplDev& dev) { return dev.persist_state(); } + + // Simulates a restart: a fresh device over a copy of this journal and of the persisted image, recovered + // through the production restart path. The fetcher, when given, is wired before recovery runs. + struct Restarted { + std::shared_ptr< CraftReplDev > dev; + MockCraftJournalBackend* journal; + MockCraftStateStore* store; + }; + Restarted restart(std::optional< CraftDurableState > image, std::map< int64_t, JournalSlot > slots, + MockCraftPeerFetcher* fetcher = nullptr, bool fail_tail = false, bool fail_load = false) { + auto j = std::make_unique< MockCraftJournalBackend >(); + auto* jraw = j.get(); + j->slots = std::move(slots); + j->fail_tail = fail_tail; + auto dev = CraftReplDev::create(volume_id_t{}, std::move(j), k_page_size, nullptr); + auto* store = wire_store(*dev); + store->saved = std::move(image); + store->fail_load = fail_load; + if (fetcher) dev->set_peer_fetcher(fetcher); + dev->trigger_on_restart(); // every mock completes inline, so recovery has finished on return + return Restarted{dev, jraw, store}; + } + +protected: MockCraftJournalBackend* journal_{nullptr}; MockCraftPeerFetcher fetcher_; MockCraftCheckpointTrigger trigger_; @@ -1465,6 +1541,573 @@ TEST_F(CraftRaftEntriesTest, CatchUpClampsAZeroSlotLimit) { EXPECT_EQ(dev_->missing_count(), 0u); } +// ══ S8: durable partition state and restart recovery (SDSTOR-22745) ══════════ + +JournalSlot page_slot(int64_t lsn) { + return JournalSlot{.lsn = lsn, + .all_zeros = true, + .lba_off_bytes = static_cast< lba_t >(lsn) * k_page_size, + .len_bytes = k_page_size}; +} + +std::map< int64_t, JournalSlot > zero_slots(std::initializer_list< int64_t > lsns) { + std::map< int64_t, JournalSlot > m; + for (int64_t l : lsns) + m[l] = page_slot(l); + return m; +} + +CraftDurableState sample_state() { + CraftDurableState s; + s.term = 3; + s.fence_term = 4; + s.client_token = 77; + s.aborted_upto = 2; + s.last_applied_raft_idx = 9; + s.durable_commit_lsn = 1; + s.sync_watermark = 6; + s.catch_up_target = 6; + s.empty_lsns = {4}; + return s; +} + +// ── codec ── + +TEST(CraftDurableStateCodec, RoundTrips) { + auto s = sample_state(); + s.empty_lsns = {2, 4, 9}; + auto bytes = encode_durable_state(s); + auto d = decode_durable_state(bytes.data(), bytes.size()); + ASSERT_TRUE(d.has_value()); + EXPECT_EQ(*d, s); + + CraftDurableState fresh; + bytes = encode_durable_state(fresh); + d = decode_durable_state(bytes.data(), bytes.size()); + ASSERT_TRUE(d.has_value()); + EXPECT_EQ(*d, fresh); +} + +TEST(CraftDurableStateCodec, RejectsMalformedImages) { + auto s = sample_state(); + s.empty_lsns = {4, 9}; + auto good = encode_durable_state(s); + + EXPECT_FALSE(decode_durable_state(nullptr, 0).has_value()); + EXPECT_FALSE(decode_durable_state(good.data(), 10).has_value()); // shorter than the header + EXPECT_FALSE(decode_durable_state(good.data(), good.size() - 1).has_value()); // empties cut short + auto longer = good; + longer.push_back(0); + EXPECT_FALSE(decode_durable_state(longer.data(), longer.size()).has_value()); // trailing bytes + + auto bad_magic = good; + bad_magic[0] ^= 0xff; + EXPECT_FALSE(decode_durable_state(bad_magic.data(), bad_magic.size()).has_value()); + auto bad_version = good; + bad_version[8] ^= 0xff; + EXPECT_FALSE(decode_durable_state(bad_version.data(), bad_version.size()).has_value()); + + // Verdicts must be strictly ascending and above durable_commit_lsn (1). + size_t const first_empty = good.size() - 2 * sizeof(int64_t); + auto unsorted = good; + int64_t const nine = 9, four = 4, one = 1; + std::memcpy(unsorted.data() + first_empty, &nine, sizeof(nine)); + std::memcpy(unsorted.data() + first_empty + sizeof(int64_t), &four, sizeof(four)); + EXPECT_FALSE(decode_durable_state(unsorted.data(), unsorted.size()).has_value()); + auto at_frontier = good; + std::memcpy(at_frontier.data() + first_empty, &one, sizeof(one)); + EXPECT_FALSE(decode_durable_state(at_frontier.data(), at_frontier.size()).has_value()); +} + +// ── write-ahead persistence ── + +// Without a store nothing is persisted and every apply behaves as before S8. +TEST_F(CraftRaftEntriesTest, NoStorePersistIsANoOp) { + auto r = homeblocks::detail::sync_get(persist(*dev_)); + EXPECT_TRUE(r.has_value()); + ASSERT_TRUE(apply_login(42, 5, std::nullopt).has_value()); + EXPECT_EQ(dev_->term(), 5u); +} + +// InternalLogin persists the fence, then the admitted term and token, and only then admits the session. +TEST_F(CraftRaftEntriesTest, InternalLoginPersistsFenceAndTermBeforeAdmitting) { + auto* store = wire_store(*dev_); + ASSERT_TRUE(apply_login(42, 5, std::nullopt).has_value()); + + EXPECT_EQ(dev_->term(), 5u); + ASSERT_TRUE(store->saved.has_value()); + EXPECT_EQ(store->saved->fence_term, 5u); + EXPECT_EQ(store->saved->term, 5u); + EXPECT_EQ(store->saved->client_token, 42u); + EXPECT_EQ(store->persist_calls, 2); // fence, then admission +} + +// If the fence cannot be made durable the login fails before truncating: the stale tail stays and the new +// session is not admitted (the in-memory fence keeps rejecting the old session meanwhile). +TEST_F(CraftRaftEntriesTest, InternalLoginFencePersistFailureStopsBeforeTruncation) { + auto* store = wire_store(*dev_); + store->fail_on_call = 1; + dev_->seed_lsns(/*last_append=*/8, {}); + + auto r = apply_login(42, 5, /*rs=*/6); + EXPECT_FALSE(r.has_value()); + EXPECT_FALSE(journal_->truncated_to.has_value()); + EXPECT_EQ(dev_->term(), 0u); + EXPECT_EQ(dev_->fence_term(), 5u); +} + +// If the admission cannot be made durable the session is not admitted, even though truncation already ran. +TEST_F(CraftRaftEntriesTest, InternalLoginTermPersistFailureDoesNotAdmit) { + auto* store = wire_store(*dev_); + store->fail_on_call = 2; + dev_->seed_lsns(/*last_append=*/8, {}); + + auto r = apply_login(42, 5, /*rs=*/6); + EXPECT_FALSE(r.has_value()); + EXPECT_EQ(journal_->truncated_to, 6); + EXPECT_EQ(dev_->term(), 0u); + EXPECT_EQ(dev_->fence_term(), 5u); +} + +// The fence is lowered only once the abort is durable: while the persist is in flight the replica stays fenced. +TEST_F(CraftRaftEntriesTest, LoginAbortedPersistsBeforeLoweringFence) { + auto* store = wire_store(*dev_); + ASSERT_TRUE(apply_login(42, 3, std::nullopt).has_value()); // session 3, durable + dev_->seed_fence_term(5); // a login poll for term 5 was answered (PR C raises this in production) + TestGate gate; + store->gate = &gate; + homeblocks::detail::detach(abort_async(5)); + EXPECT_EQ(dev_->fence_term(), 5u); // persisting: still fenced + EXPECT_EQ(dev_->durable_state().fence_term, 3u); + + store->gate = nullptr; + gate.open(); + EXPECT_EQ(dev_->fence_term(), 3u); + EXPECT_EQ(store->saved->fence_term, 3u); + EXPECT_EQ(store->saved->aborted_upto, 5u); +} + +// A LoginAborted whose image cannot be persisted keeps the fence: the replica stays safe (rejecting IO). +TEST_F(CraftRaftEntriesTest, LoginAbortedPersistFailureKeepsFence) { + auto* store = wire_store(*dev_); + dev_->seed_term(3); + dev_->seed_fence_term(5); + store->fail_persist = true; + + EXPECT_FALSE(apply_abort(5).has_value()); + EXPECT_EQ(dev_->fence_term(), 5u); + EXPECT_EQ(dev_->aborted_upto(), 5u); // raising aborted_upto only makes later logins no-ops: applied at once + + store->fail_persist = false; + ASSERT_TRUE(apply_abort(5).has_value()); + EXPECT_EQ(dev_->fence_term(), 3u); + EXPECT_EQ(store->saved->aborted_upto, 5u); +} + +// The Sync verdicts, watermark and catch-up target are durable before any verdicted block is freed. +TEST_F(CraftRaftEntriesTest, SyncPersistsVerdictsBeforeFreeing) { + auto* store = wire_store(*dev_); + journal_->slots = zero_slots({0, 1, 2, 3}); + journal_->slots[3].all_zeros = false; // real data under slot 3: a verdict must free it + dev_->seed_lsns(/*last_append=*/3, {}); + + ASSERT_TRUE(do_apply(/*rs_commit_lsn=*/5, /*client_token=*/0, /*empty_slots=*/{3}).has_value()); + EXPECT_EQ(journal_->free_slot_calls, 1); + ASSERT_TRUE(store->saved.has_value()); + EXPECT_EQ(store->saved->empty_lsns, (std::set< int64_t >{3})); + EXPECT_EQ(store->saved->sync_watermark, 5); + EXPECT_EQ(store->saved->catch_up_target, 5); +} + +// If the verdicts cannot be made durable, nothing is freed: a restart replaying this entry would otherwise free +// the same blocks twice. Leaking them is the safe side. +TEST_F(CraftRaftEntriesTest, SyncVerdictPersistFailureLeaksInsteadOfFreeing) { + auto* store = wire_store(*dev_); + store->fail_persist = true; + journal_->slots = zero_slots({0, 1, 2, 3}); + journal_->slots[3].all_zeros = false; + dev_->seed_lsns(/*last_append=*/3, {}); + + ASSERT_TRUE(do_apply(/*rs_commit_lsn=*/5, /*client_token=*/0, /*empty_slots=*/{3}).has_value()); + EXPECT_EQ(journal_->free_slot_calls, 0); + EXPECT_TRUE(dev_->is_empty_slot(3)); // the verdict itself still holds in memory +} + +// Every applied RAFT entry advances the persisted last-applied index. +TEST_F(CraftRaftEntriesTest, ApplyQueuePersistsLastAppliedRaftIdx) { + auto* store = wire_store(*dev_); + commit_entry(*dev_, 7, CraftEntryType::LoginAborted, make_login_aborted_key(1)); + ASSERT_TRUE(store->saved.has_value()); + EXPECT_EQ(store->saved->last_applied_raft_idx, 7); + EXPECT_EQ(store->saved->aborted_upto, 1u); + + store->fail_persist = true; // a failed persist only means the entry may be re-applied after a restart + commit_entry(*dev_, 8, CraftEntryType::LoginAborted, make_login_aborted_key(2)); + EXPECT_EQ(dev_->last_applied_raft_idx(), 8); + EXPECT_EQ(store->saved->last_applied_raft_idx, 7); +} + +// Concurrent persist_state() calls share one writer; each returns once an image covering it is durable. +TEST_F(CraftRaftEntriesTest, ConcurrentPersistsAreSerializedAndCoalesced) { + auto* store = wire_store(*dev_); + TestGate gate; + store->gate = &gate; + std::optional< status > first, second, third; + auto run = [](CraftRaftEntriesTest* t, CraftReplDev& dev, std::optional< status >& out) -> async_status { + // A captureless lambda: its coroutine frame owns the parameters, so detaching it is safe. + out = co_await t->persist(dev); + co_return ok(); + }; + homeblocks::detail::detach(run(this, *dev_, first)); // writer starts, held at the gate + homeblocks::detail::detach(run(this, *dev_, second)); // queued behind it + homeblocks::detail::detach(run(this, *dev_, third)); // coalesced with `second` + EXPECT_FALSE(first.has_value()); + EXPECT_EQ(store->persist_calls, 1); + + store->gate = nullptr; + gate.open(); + ASSERT_TRUE(first && second && third); + EXPECT_TRUE(first->has_value() && second->has_value() && third->has_value()); + EXPECT_EQ(store->persist_calls, 2); // one round for `first`, one for `second` and `third` together +} + +// A failed round fails exactly the callers it covered. +TEST_F(CraftRaftEntriesTest, PersistFailureIsReportedToItsCallers) { + auto* store = wire_store(*dev_); + store->fail_persist = true; + EXPECT_FALSE(homeblocks::detail::sync_get(persist(*dev_)).has_value()); + store->fail_persist = false; + EXPECT_TRUE(homeblocks::detail::sync_get(persist(*dev_)).has_value()); +} + +// ── durable commit frontier ── + +// A checkpoint that actually flushed makes commit_lsn the durable frontier and drops verdicts at or below it. +TEST_F(CraftRaftEntriesTest, FlushedCheckpointRecordsDurableCommit) { + auto* store = wire_store(*dev_); + dev_->set_checkpoint_trigger(std::ref(trigger_)); + dev_->set_checkpoint_lsn_interval(5); + dev_->seed_lsns(/*last_append=*/10, {}); + + ASSERT_TRUE(do_apply(/*rs_commit_lsn=*/10, /*client_token=*/0, /*empty_slots=*/{3}).has_value()); + EXPECT_EQ(trigger_.call_count, 1); + ASSERT_TRUE(store->saved.has_value()); + EXPECT_EQ(store->saved->durable_commit_lsn, 10); + EXPECT_TRUE(store->saved->empty_lsns.empty()); +} + +// A checkpoint request that coalesced into a flush already running proves nothing about the slots applied +// since that flush started: the durable frontier must not move. +TEST_F(CraftRaftEntriesTest, CoalescedCheckpointDoesNotRecordDurableCommit) { + auto* store = wire_store(*dev_); + dev_->set_checkpoint_trigger(std::ref(trigger_)); + dev_->set_checkpoint_lsn_interval(5); + trigger_.flushed = false; + dev_->seed_lsns(/*last_append=*/10, {}); + + ASSERT_TRUE(do_apply(/*rs_commit_lsn=*/10, /*client_token=*/0).has_value()); + EXPECT_EQ(trigger_.call_count, 1); + EXPECT_EQ(dev_->durable_state().durable_commit_lsn, -1); + EXPECT_EQ(store->saved->durable_commit_lsn, -1); +} + +// A frontier at or below the recorded one is ignored, and a persist failure is only logged. +TEST_F(CraftRaftEntriesTest, DurableCommitNeverRegressesAndSurvivesPersistFailure) { + auto* store = wire_store(*dev_); + dev_->set_checkpoint_trigger(std::ref(trigger_)); + dev_->set_checkpoint_lsn_interval(5); + dev_->seed_lsns(/*last_append=*/20, {}); + ASSERT_TRUE(do_apply(10, 0).has_value()); + EXPECT_EQ(store->saved->durable_commit_lsn, 10); + + store->fail_persist = true; + ASSERT_TRUE(do_apply(20, 0).has_value()); + EXPECT_EQ(dev_->durable_state().durable_commit_lsn, 20); // recorded; written again by the next persist + EXPECT_EQ(store->saved->durable_commit_lsn, 10); +} + +// ── restart recovery ── + +// A device that never persisted anything restarts empty and healthy. +TEST_F(CraftRaftEntriesTest, RestartWithNoImageStartsFresh) { + auto r = restart(std::nullopt, zero_slots({0, 1})); + EXPECT_FALSE(r.dev->is_recovery_faulted()); + EXPECT_FALSE(r.dev->is_recovering()); + EXPECT_EQ(r.dev->commit_lsn(), -1); + EXPECT_EQ(r.dev->last_append_lsn(), -1); +} + +// The control fields come back from the image; commit_lsn restarts at the durable frontier; last_append_lsn is +// the larger of the journal tail and the Sync watermark; every slot above the frontier the journal does not hold +// (and is not verdicted Empty) is missing. +TEST_F(CraftRaftEntriesTest, RestartRestoresControlStateAndJournalRange) { + auto r = restart(sample_state(), zero_slots({0, 1, 2, 3, 7})); + ASSERT_FALSE(r.dev->is_recovery_faulted()); + EXPECT_FALSE(r.dev->is_recovering()); + + EXPECT_EQ(r.dev->term(), 3u); + EXPECT_EQ(r.dev->fence_term(), 4u); + EXPECT_EQ(r.dev->client_token(), 77u); + EXPECT_EQ(r.dev->aborted_upto(), 2u); + EXPECT_EQ(r.dev->last_applied_raft_idx(), 9); + // commit_lsn restarted at the durable frontier (1); the resumed catch-up (no peer wired) then advanced it over + // the slots already present (2, 3) and the Empty one (4), stopping at the first missing slot. + EXPECT_EQ(r.dev->commit_lsn(), 4); + EXPECT_EQ(r.dev->last_append_lsn(), 7); + EXPECT_TRUE(r.dev->is_empty_slot(4)); + EXPECT_EQ(r.dev->missing_count(), 2u); + EXPECT_TRUE(r.dev->is_missing(5)); + EXPECT_TRUE(r.dev->is_missing(6)); + EXPECT_EQ(r.dev->overlay_lsn_for(7), 7); // slots above the frontier are readable again + EXPECT_EQ(r.dev->durable_state(), sample_state()); +} + +// The Sync watermark can be above the journal tail (the slots up to it were never received here). +TEST_F(CraftRaftEntriesTest, RestartRaisesLastAppendToSyncWatermark) { + auto r = restart(sample_state(), zero_slots({0, 1, 2})); + EXPECT_EQ(r.dev->last_append_lsn(), 6); + EXPECT_TRUE(r.dev->is_missing(3)); + EXPECT_TRUE(r.dev->is_missing(6)); + EXPECT_FALSE(r.dev->is_missing(4)); // Empty +} + +// RAFT entries at or below the persisted last-applied index are not applied again after a restart. +TEST_F(CraftRaftEntriesTest, RestartSkipsAlreadyAppliedRaftEntries) { + auto r = restart(sample_state(), zero_slots({0, 1})); + commit_entry(*r.dev, 9, CraftEntryType::LoginAborted, make_login_aborted_key(100)); + EXPECT_EQ(r.dev->aborted_upto(), 2u); + commit_entry(*r.dev, 10, CraftEntryType::LoginAborted, make_login_aborted_key(100)); + EXPECT_EQ(r.dev->aborted_upto(), 100u); +} + +// Even when the last-applied index did not reach disk, a re-applied InternalLogin whose term is already durable +// is a no-op: it must not truncate the new session's writes. +TEST_F(CraftRaftEntriesTest, RestartReappliedInternalLoginIsANoOp) { + auto img = sample_state(); + img.last_applied_raft_idx = 0; + auto r = restart(img, zero_slots({0, 1, 2, 3, 7})); + commit_entry(*r.dev, 5, CraftEntryType::InternalLogin, make_internal_login_v2_key(77, 3, /*rs=*/2)); + EXPECT_FALSE(r.journal->truncated_to.has_value()); + EXPECT_EQ(r.dev->last_append_lsn(), 7); +} + +// A catch-up the restart interrupted resumes toward the persisted target. +TEST_F(CraftRaftEntriesTest, RestartResumesCatchUp) { + fetcher_.range_script = {FetchRangeResult{.slots = {page_slot(5), page_slot(6)}, .next = -1}}; + auto r = restart(sample_state(), zero_slots({0, 1, 2, 3}), &fetcher_); + ASSERT_FALSE(fetcher_.range_requests.empty()); + EXPECT_EQ(fetcher_.range_requests.front(), (std::vector< LsnRange >{{5, 6}})); + EXPECT_EQ(r.dev->missing_count(), 0u); + EXPECT_EQ(r.dev->commit_lsn(), 6); +} + +// No catch-up is started when the persisted target is already covered. +TEST_F(CraftRaftEntriesTest, RestartDoesNotResumeFinishedCatchUp) { + auto img = sample_state(); + img.catch_up_target = 1; + restart(img, zero_slots({0, 1, 2, 3, 7}), &fetcher_); + EXPECT_TRUE(fetcher_.range_requests.empty()); +} + +// An image that cannot be read, or a journal whose tail cannot be read, faults the partition: restarting it +// empty would forget fences and verdicts. +TEST_F(CraftRaftEntriesTest, RestartFaultsOnUnreadableImage) { + auto r = restart(sample_state(), zero_slots({0}), nullptr, /*fail_tail=*/false, /*fail_load=*/true); + EXPECT_TRUE(r.dev->is_recovery_faulted()); +} + +TEST_F(CraftRaftEntriesTest, RestartFaultsOnUnreadableJournalTail) { + auto r = restart(sample_state(), zero_slots({0}), nullptr, /*fail_tail=*/true); + EXPECT_TRUE(r.dev->is_recovery_faulted()); +} + +// A backend that cannot report its tail (the interface default) cannot be recovered either. +TEST_F(CraftRaftEntriesTest, RestartFaultsWhenBackendHasNoTail) { + struct NoTailJournal : MockCraftJournalBackend { + async_result< int64_t > tail_lsn() override { return CraftJournalBackend::tail_lsn(); } + }; + auto dev = CraftReplDev::create(volume_id_t{}, std::make_unique< NoTailJournal >(), k_page_size, nullptr); + auto* store = wire_store(*dev); + store->saved = sample_state(); + dev->trigger_on_restart(); + EXPECT_TRUE(dev->is_recovery_faulted()); +} + +// A read error other than "not there" still faults the rebuild. +TEST_F(CraftRaftEntriesTest, RestartFaultsOnJournalReadError) { + struct BadReadJournal : MockCraftJournalBackend { + async_result< JournalSlot > read_slot(int64_t) override { + co_return std::unexpected(std::make_error_condition(std::errc::io_error)); + } + }; + auto j = std::make_unique< BadReadJournal >(); + j->slots = zero_slots({0, 1, 2, 3}); + auto dev = CraftReplDev::create(volume_id_t{}, std::move(j), k_page_size, nullptr); + wire_store(*dev)->saved = sample_state(); + dev->trigger_on_restart(); + EXPECT_TRUE(dev->is_recovery_faulted()); +} + +// Re-applying a slot journalled before the restart must not free the block it replaces in the index: the index +// may already hold a NEWER slot's block there (a checkpoint ran past the recorded durable frontier). Slots above +// the replay window free superseded blocks as usual. +TEST_F(CraftRaftEntriesTest, RestartReplayDoesNotFreeReplacedBlocks) { + auto img = sample_state(); + img.empty_lsns.clear(); + img.sync_watermark = -1; + img.catch_up_target = -1; + auto r = restart(img, zero_slots({0, 1, 2, 3})); + ASSERT_EQ(r.dev->last_append_lsn(), 3); + r.journal->slots[4] = page_slot(4); + r.dev->seed_lsns(/*last_append=*/4, {}); + + int deletes = 0; + auto delete_fn = [&deletes](lba_t, lba_t, std::vector< homestore::blk_id >& freed) -> status { + ++deletes; + freed.push_back(homestore::blk_id{7, 1, 0}); + return ok(); + }; + auto write_fn = [](lba_t, lba_t, std::unordered_map< lba_t, BlockInfo >&) -> status { return ok(); }; + auto c = homeblocks::detail::sync_get(r.dev->commit_with(4, write_fn, delete_fn)); + ASSERT_TRUE(c.has_value()); + EXPECT_EQ(*c, 4); + EXPECT_EQ(deletes, 3); // slots 2, 3 (replayed) and 4 + EXPECT_EQ(r.journal->free_data_calls, 0); // replayed: never freed; slot 4: deferred until a durable frontier +} + +// End to end: state persisted by one device restores another. +TEST_F(CraftRaftEntriesTest, PersistedStateRestoresAfterRestart) { + auto* store = wire_store(*dev_); + dev_->set_checkpoint_trigger(std::ref(trigger_)); + dev_->set_checkpoint_lsn_interval(2); + journal_->slots = zero_slots({0, 1, 2}); + dev_->seed_lsns(/*last_append=*/2, {}); + commit_entry(*dev_, 1, CraftEntryType::SyncRSCommitLSN, make_sync_rs_commit_lsn_key(2, 0, {})); + commit_entry(*dev_, 2, CraftEntryType::InternalLogin, make_internal_login_v2_key(42, 5, /*rs=*/2)); + commit_entry(*dev_, 3, CraftEntryType::SyncRSCommitLSN, make_sync_rs_commit_lsn_key(4, 0, {4})); + ASSERT_TRUE(store->saved.has_value()); + + auto r = restart(store->saved, journal_->slots); + ASSERT_FALSE(r.dev->is_recovery_faulted()); + EXPECT_EQ(r.dev->term(), 5u); + EXPECT_EQ(r.dev->client_token(), 42u); + EXPECT_EQ(r.dev->last_applied_raft_idx(), 3); + EXPECT_EQ(r.dev->commit_lsn(), 2); + EXPECT_EQ(r.dev->last_append_lsn(), 4); + EXPECT_TRUE(r.dev->is_missing(3)); + EXPECT_TRUE(r.dev->is_empty_slot(4)); +} + +// ── review on #201 (second round) ── + +// With a state store, a block an index write supersedes is freed only once a durable checkpoint covers the slot +// that replaced it: until then a restart could re-apply the older slot, which still needs its block. +TEST_F(CraftRaftEntriesTest, SupersededBlocksWaitForTheDurableFrontier) { + wire_store(*dev_); + journal_->slots = zero_slots({0, 1}); + dev_->seed_lsns(/*last_append=*/1, {}); + auto delete_fn = [](lba_t, lba_t, std::vector< homestore::blk_id >& freed) -> status { + freed.push_back(homestore::blk_id{7, 1, 0}); + return ok(); + }; + auto write_fn = [](lba_t, lba_t, std::unordered_map< lba_t, BlockInfo >&) -> status { return ok(); }; + + // A checkpoint that only coalesced proves nothing: the blocks keep waiting. + dev_->set_checkpoint_trigger(std::ref(trigger_)); + dev_->set_checkpoint_lsn_interval(1); + trigger_.flushed = false; + ASSERT_TRUE(homeblocks::detail::sync_get(dev_->commit_with(0, write_fn, delete_fn)).has_value()); + EXPECT_EQ(journal_->free_data_calls, 0); + + // A flushed checkpoint at commit 1 makes both replacing slots durable: both waiting blocks are freed. + trigger_.flushed = true; + ASSERT_TRUE(homeblocks::detail::sync_get(dev_->commit_with(1, write_fn, delete_fn)).has_value()); + EXPECT_EQ(dev_->durable_state().durable_commit_lsn, 1); + EXPECT_EQ(journal_->free_data_calls, 2); +} + +// Without a state store there is no restart replay, so superseded blocks are freed at once, as before S8. +TEST_F(CraftRaftEntriesTest, SupersededBlocksFreedAtOnceWithoutAStore) { + journal_->slots = zero_slots({0}); + dev_->seed_lsns(/*last_append=*/0, {}); + auto delete_fn = [](lba_t, lba_t, std::vector< homestore::blk_id >& freed) -> status { + freed.push_back(homestore::blk_id{7, 1, 0}); + return ok(); + }; + auto write_fn = [](lba_t, lba_t, std::unordered_map< lba_t, BlockInfo >&) -> status { return ok(); }; + ASSERT_TRUE(homeblocks::detail::sync_get(dev_->commit_with(0, write_fn, delete_fn)).has_value()); + EXPECT_EQ(journal_->free_data_calls, 1); +} + +// Once an entry fails to apply, the persisted applied index stops advancing: a restart re-applies from the failed +// entry (here an InternalLogin whose truncation failed) instead of skipping it for good. The queue itself goes on. +TEST_F(CraftRaftEntriesTest, FailedApplyFreezesThePersistedRaftIndex) { + auto* store = wire_store(*dev_); + commit_entry(*dev_, 1, CraftEntryType::LoginAborted, make_login_aborted_key(1)); + ASSERT_EQ(store->saved->last_applied_raft_idx, 1); + + dev_->seed_lsns(/*last_append=*/8, {}); + journal_->fail_truncate = true; + commit_entry(*dev_, 2, CraftEntryType::InternalLogin, make_internal_login_v2_key(42, 5, /*rs=*/6)); + EXPECT_EQ(dev_->term(), 0u); // not admitted + commit_entry(*dev_, 3, CraftEntryType::LoginAborted, make_login_aborted_key(2)); + EXPECT_EQ(dev_->aborted_upto(), 2u); // later entries still apply + EXPECT_EQ(dev_->last_applied_raft_idx(), 3); // in memory + EXPECT_EQ(store->saved->last_applied_raft_idx, 1) << "a restart re-applies from the failed InternalLogin"; + EXPECT_EQ(store->saved->aborted_upto, 2u); // what later entries made durable still is +} + +// A verdict for a slot at or below commit_lsn (after a restart: at or below the durable frontier, whose verdicts were +// dropped from the image) is ignored: freeing that slot's journal record again would be a double free. +TEST_F(CraftRaftEntriesTest, SyncIgnoresVerdictsAtOrBelowCommit) { + journal_->slots = zero_slots({0, 1, 2, 3, 4, 5}); + journal_->slots[3].all_zeros = false; + dev_->seed_lsns(/*last_append=*/5, {}); + dev_->seed_commit_lsn(4); + ASSERT_TRUE(do_apply(/*rs_commit_lsn=*/5, /*client_token=*/0, /*empty_slots=*/{3}).has_value()); + EXPECT_EQ(journal_->free_slot_calls, 0); + EXPECT_FALSE(dev_->is_empty_slot(3)); +} + +// Catch-up that finds its freshly installed slot verdicted Empty frees it only once the verdict is durable: if +// persisting fails, the blocks are leaked rather than risk a second free when a restart replays the Sync. +TEST_F(CraftRaftEntriesTest, CatchUpFreesAVoidedSlotOnlyOnceTheVerdictIsDurable) { + auto* store = wire_store(*dev_); + TestGate gate; + journal_->write_gates[3] = &gate; + dev_->set_peer_fetcher(&fetcher_); + dev_->seed_lsns(/*last_append=*/2, {}); + fetcher_.response = {JournalSlot{.lsn = 3, .all_zeros = true, .lba_off_bytes = 0, .len_bytes = 1}}; + + commit_entry(*dev_, 1, CraftEntryType::SyncRSCommitLSN, make_sync_rs_commit_lsn_key(3, 0, {})); + commit_entry(*dev_, 2, CraftEntryType::SyncRSCommitLSN, make_sync_rs_commit_lsn_key(3, 0, {3})); // voids 3 + ASSERT_TRUE(dev_->is_empty_slot(3)); + + store->fail_persist = true; + journal_->write_gates.clear(); + gate.open(); + EXPECT_EQ(journal_->free_slot_calls, 0) << "not freed: the verdict could not be made durable"; + EXPECT_TRUE(dev_->is_empty_slot(3)); + + store->fail_persist = false; +} + +// H9 (review on #201): the Sync advance applies every slot it passes to the index -- here a fake one through the +// commit() seam -- instead of only moving commit_lsn. Missing-slot catch-up advances through the same function. +TEST_F(CraftRaftEntriesTest, SyncAdvanceAppliesSlotsToTheIndex) { + journal_->slots = zero_slots({0, 1, 2}); + dev_->seed_lsns(/*last_append=*/2, {}); + std::vector< lba_t > applied; + dev_->set_index_fns_for_test([](lba_t, lba_t, std::unordered_map< lba_t, BlockInfo >&) -> status { return ok(); }, + [&applied](lba_t s, lba_t, std::vector< homestore::blk_id >&) -> status { + applied.push_back(s); + return ok(); + }); + ASSERT_TRUE(do_apply(/*rs_commit_lsn=*/2, /*client_token=*/0).has_value()); + EXPECT_EQ(dev_->commit_lsn(), 2); + EXPECT_EQ(applied, (std::vector< lba_t >{0, 1, 2})) << "every slot reached the index"; // zero_slot: lba 0..2 +} + } // namespace } // namespace homeblocks