From 5ee8ff558fd01676b22eb3bc895aa5f3be7d7476 Mon Sep 17 00:00:00 2001 From: Kshiteesh R Bharadwaj <100955403+kshiteesh28@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:07:11 -0600 Subject: [PATCH 1/8] docs(supervisor): freeze the epoch artifact layout --- docs/SCRUM-WORK-LOG.md | 8 ++++ docs/contracts/epoch-artifact-layout-v1.md | 50 ++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 docs/contracts/epoch-artifact-layout-v1.md diff --git a/docs/SCRUM-WORK-LOG.md b/docs/SCRUM-WORK-LOG.md index 8fe797b..a445b78 100644 --- a/docs/SCRUM-WORK-LOG.md +++ b/docs/SCRUM-WORK-LOG.md @@ -509,3 +509,11 @@ Historical entries below are reconstructed from retained handoffs and GitHub evi - **Design and handoff:** LLD 8, JSON context, story and sprint sources now describe the actual diagnostic-only reader, exact caps, and initial-fatal versus later-incomplete ownership failure. All source links/JSON/story DAG checks pass. PRD 8 / SRD 5 / HLD 5 are unchanged. - **Integration:** PR20 is ready for feature integration after readback. Only documentation follows tested source. Full RG006 remains In progress and PR13 remains the final promotion to main. - **Next review finding (Senior/Master):** BootstrapStore creates epoch/intent.json while ManifestStore requires a separate new directory; current reader rejects all other siblings. Master selected a shared versioned manifest-store layout and format-specific validation for the next separate PR. Pending-identity controller targets, positive Docker exit evidence, durable recovery orchestration and successor authorization remain required. + +### LOG-059 — Epoch artifact-layout integration started (2026-11-24 UTC) + +- **Master:** PR20 merged as 9d90746 after real Linux verification; opened the separate artifact-layout branch from that feature head. Selected [layout v1](contracts/epoch-artifact-layout-v1.md): epoch intent plus optional private manifest-store directory. Missing/unknown/temporary artifacts remain uncertainty; a manifest phase never proves process cessation. +- **Senior developer:** Extending the read-only reader with independent manifest scanning, canonical cross-artifact candidate comparison, bounded nested validation and diagnostic manifest retention even when the intent is unavailable. Identified pending-bootstrap comparison as unavailable rather than an actual candidate mismatch. +- **Junior developer:** Implemented shared exact names and pure checked epoch parse/format helpers; grammar tests pass under strict NDEBUG. Prepared narrow BootstrapStore/ManifestStore name-reuse patches. Root review preserved existing validation precedence before formatting and publication. +- **Tester:** Independently preparing matching-phase, missing/corrupt/mismatched-artifact, nested type/link/mode/temp/mutation and shared-budget cases. Flagged pending-bootstrap classification before publication. +- **Scope:** This integration resolves artifact composition only. Controller targets for pending identities, real Docker exit evidence, recovery orchestration and verified successor authorization remain required. Source/tests and Linux acceptance for this increment are pending; no full RG006 acceptance is claimed. diff --git a/docs/contracts/epoch-artifact-layout-v1.md b/docs/contracts/epoch-artifact-layout-v1.md new file mode 100644 index 0000000..9e26231 --- /dev/null +++ b/docs/contracts/epoch-artifact-layout-v1.md @@ -0,0 +1,50 @@ +# Epoch artifact layout v1 + +**Status:** Selected implementation layout; integration in progress. Sources: PRD 8 / SRD 5, HLD 5 A-03 and LLD 8 §21. These choices preserve product behavior and release gates. + +## Directory contract + +```text +/ + owner.lock + runtime-anchor.json + epoch-<32 lowercase hexadecimal digits>/ + intent.json + manifest-store/ # optional until manifest creation + owner.lock # empty + manifest.json +``` + +Epoch IDs are nonzero. Shared `epoch_layout_v1` constants and checked parse/format helpers define these exact names. Helpers do not access the filesystem or confer ownership. Root ownership remains RuntimeOwner's responsibility. + +BootstrapStore creates the epoch directory and durable intent before process start. ManifestStore creates a separate, new `manifest-store` directory after the complete observed candidate is available. It does not initialize over an existing directory or adopt an existing ACTIVE epoch. Creation/phase persistence remain separate transitions; this layout does not make them one transaction. + +Witness/journal and recovery-operation artifacts are not yet recognized. Their paths and validators must be added before those modules are integrated. An unknown directory is never accepted merely because a future feature might use it. + +## Recovery interpretation + +The recovery reader independently examines the bootstrap intent and optional manifest store. A missing manifest directory is valid for a bootstrap-only structural scan and proves no activation state. If a manifest directory was observed, missing or changed contents are uncertainty. + +The manifest directory must be owned/private 0700. Its only accepted entries are an empty, owned regular single-link 0600 `owner.lock` and an owned regular single-link 0600 `manifest.json`. Known files are opened no-follow/nonblocking. `manifest.tmp`, `intent.tmp`, unknown entries, unsafe types, wrong modes, nonempty locks, missing files and detected mutations make the scan incomplete. Safely readable known artifacts remain diagnostic evidence. + +A manifest is decoded by the existing canonical schema/checksum codec within its 4 MiB limit. The reader never calls writable store reopening or acquires a serving capability. It retains a safely decoded immutable manifest even when the intent is missing, corrupt or inconsistent, where other budgets permit. + +A matching manifest requires the exact complete BootstrapInventory ReadyCandidate, including epoch, authority incarnation, policy digest, common clock provenance and every participant identity. Canonical ordering in both codecs is role, participant ID and slot. Missing/incomplete comparison data or a difference makes the scan incomplete. All manifest phases—Prepared, Active, Draining and Closed—are metadata only. CLOSED is not independent process-exit evidence. + +Historical clock/boot provenance is retained. Checksums are corruption checks, not authentication, rollback freshness or proof of prior fsync completion. No scan result permits adoption, stop, reset or successor activation. + +## Bounded evidence and consistency + +Root and epoch entry caps remain 4,096 and 16. The manifest-store entry cap is also 16. Epoch count remains 1,024; global/per-epoch issue caps remain 256/16, with explicit truncation and incomplete output. + +All attempted intent and manifest sizes consume the same 64 MiB input budget before allocation/read. Failed reads/decodes never refund it. Both retained bootstrap and manifest participant records consume the same 16,384-record budget, including matching duplicated representations, because both models occupy memory. + +Matching records in two artifacts within one epoch are expected representations, not cross-epoch collisions. Duplicate container/process identities across epoch directories remain conflicts. Inconsistent same-epoch candidate data is also incomplete; never select the latest artifact or silently replace one with the other. + +Validate directory, lock and manifest identities, owner UID/link count/mode/size/time metadata and bounded entry listings around reads. Validate epoch/root ownership again. This detects observed changes, not an atomic filesystem snapshot or hostile same-UID mutation. + +## Verification and remaining work + +Keep all bootstrap-only reader tests. Add independent matching-phase, incomplete/mismatched-candidate, missing/corrupt intent with readable manifest, file-type/mode/link, unknown/temp/missing entry, nested-limit, mutation and shared-budget cases. Pure grammar/name tests cover lowercase/nonzero canonical IDs and round trips. Require pinned real Linux/OpenSSL clean builds and sanitizers before integration acceptance. + +Real Docker/OS control, pending-identity stop targets, durable recovery orchestration, authenticated readiness/activation, witness integration and verified successor-epoch authorization remain separate requirements. This layout does not implement or prove them. From 9ca7f0c37733db6b85051545acd44f2ee1b1c495 Mon Sep 17 00:00:00 2001 From: Kshiteesh R Bharadwaj <100955403+kshiteesh28@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:42:37 -0600 Subject: [PATCH 2/8] refactor(supervisor): share canonical epoch artifact names --- CMakeLists.txt | 13 +++ src/supervisor/bootstrap_store.cpp | 23 ++-- src/supervisor/epoch_artifact_layout.h | 90 +++++++++++++++ src/supervisor/manifest_store.cpp | 7 +- .../supervisor/epoch_artifact_layout_test.cpp | 104 ++++++++++++++++++ 5 files changed, 220 insertions(+), 17 deletions(-) create mode 100644 src/supervisor/epoch_artifact_layout.h create mode 100644 tests/supervisor/epoch_artifact_layout_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 03bb5d2..a6233eb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -665,3 +665,16 @@ add_test(NAME rateguard.bootstrap_recovery_reader_independent COMMAND rateguard_bootstrap_recovery_reader_independent_tests) set_tests_properties(rateguard.bootstrap_recovery_reader rateguard.bootstrap_recovery_reader_independent PROPERTIES TIMEOUT 120) + +# Shared canonical epoch artifact grammar. +add_executable(rateguard_epoch_artifact_layout_tests + tests/supervisor/epoch_artifact_layout_test.cpp) +target_link_libraries(rateguard_epoch_artifact_layout_tests PRIVATE rateguard_epoch_gate) +target_compile_options(rateguard_epoch_artifact_layout_tests PRIVATE -Wall -Wextra -Werror -pedantic) +if(RATEGUARD_SANITIZE_BOOTSTRAP) + target_compile_options(rateguard_epoch_artifact_layout_tests PRIVATE -fsanitize=address,undefined -fno-omit-frame-pointer) + target_link_options(rateguard_epoch_artifact_layout_tests PRIVATE -fsanitize=address,undefined) +endif() +add_test(NAME rateguard.epoch_artifact_layout COMMAND rateguard_epoch_artifact_layout_tests) +set_tests_properties(rateguard.epoch_artifact_layout PROPERTIES TIMEOUT 30) + diff --git a/src/supervisor/bootstrap_store.cpp b/src/supervisor/bootstrap_store.cpp index b644603..4a6c8e2 100644 --- a/src/supervisor/bootstrap_store.cpp +++ b/src/supervisor/bootstrap_store.cpp @@ -1,6 +1,7 @@ #include "supervisor/bootstrap_store.h" #include "platform/file_io.h" +#include "supervisor/epoch_artifact_layout.h" #include #include @@ -16,24 +17,13 @@ using platform::file::Sync; using platform::file::UniqueFd; using platform::file::WriteAll; -constexpr char kIntentName[] = "intent.json"; -constexpr char kTempName[] = "intent.tmp"; +constexpr auto& kIntentName = epoch_layout_v1::kIntentFileName; +constexpr auto& kTempName = epoch_layout_v1::kIntentTemporaryFileName; bool Fail(IBootstrapStoreIo* io, BootstrapStoreIoPoint point) noexcept { return io != nullptr && io->FailAt(point); } -std::string Hex(const auto& bytes) { - constexpr char digits[] = "0123456789abcdef"; - std::string out; - out.reserve(bytes.size() * 2); - for (auto byte : bytes) { - out.push_back(digits[byte >> 4]); - out.push_back(digits[byte & 15]); - } - return out; -} - bool SameInode(const struct stat& a, const struct stat& b) noexcept { return a.st_dev == b.st_dev && a.st_ino == b.st_ino; } @@ -293,10 +283,15 @@ BootstrapStoreOpenResult BootstrapStore::CreateNew(InitialEpochClaim claim, cons const auto digest_result = BootstrapDigestV1(std::get(model)); if (const auto* error = std::get_if(&digest_result)) return failure(*error == BootstrapError::AllocationFailure ? BootstrapStoreError::AllocationFailure : BootstrapStoreError::InvalidPlan); + auto child_name_result = epoch_layout_v1::FormatEpochDirectoryName(plan.epoch_id); + if (const auto* error = std::get_if(&child_name_result)) + return failure(*error == epoch_layout_v1::LayoutError::AllocationFailure + ? BootstrapStoreError::AllocationFailure + : BootstrapStoreError::InvalidPlan); auto state = std::make_unique(std::move(claim)); state->test_io = test_io; - state->child_name = "epoch-" + Hex(plan.epoch_id); + state->child_name = std::get(std::move(child_name_result)); state->committed = std::make_shared(std::get(model)); state->digest = std::get>(digest_result); state->committed_bytes = bytes; diff --git a/src/supervisor/epoch_artifact_layout.h b/src/supervisor/epoch_artifact_layout.h new file mode 100644 index 0000000..d461d3a --- /dev/null +++ b/src/supervisor/epoch_artifact_layout.h @@ -0,0 +1,90 @@ +#pragma once + +// Pure v1 names and codecs for artifacts inside one supervisor runtime root: +// epoch-/intent.json, optionally epoch-/manifest-store/{owner.lock, +// manifest.json}. `intent.tmp` and `manifest.tmp` are transient artifacts and +// indicate an uncertain/incomplete recovery scan. No witness or journal names +// are recognized in v1. This header performs no filesystem access and grants +// no ownership/fencing authority. + +#include "supervisor/epoch_gate.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rateguard::supervisor::epoch_layout_v1 { + +inline constexpr char kEpochDirectoryPrefix[] = "epoch-"; +inline constexpr char kIntentFileName[] = "intent.json"; +inline constexpr char kIntentTemporaryFileName[] = "intent.tmp"; +inline constexpr char kManifestStoreDirectoryName[] = "manifest-store"; +inline constexpr char kManifestStoreLockFileName[] = "owner.lock"; +inline constexpr char kManifestFileName[] = "manifest.json"; +inline constexpr char kManifestTemporaryFileName[] = "manifest.tmp"; + +enum class LayoutError : std::uint8_t { + ZeroEpochId, + AllocationFailure, +}; + +[[nodiscard]] inline bool IsZeroEpochId(const EpochId& id) noexcept { + for (const auto byte : id) { + if (byte != 0) return false; + } + return true; +} + +[[nodiscard]] inline int HexNibble(char value) noexcept { + if (value >= '0' && value <= '9') return value - '0'; + if (value >= 'a' && value <= 'f') return value - 'a' + 10; + return -1; +} + +// Accepts exactly the shared BootstrapStore/BootstrapRecoveryReader grammar: +// `epoch-` followed by 32 lowercase hexadecimal digits, encoding nonzero ID. +[[nodiscard]] inline std::optional ParseEpochDirectoryName( + std::string_view name) noexcept { + constexpr std::size_t kPrefixLength = sizeof(kEpochDirectoryPrefix) - 1; + constexpr std::size_t kCanonicalLength = kPrefixLength + 32; + if (name.size() != kCanonicalLength || + name.substr(0, kPrefixLength) != kEpochDirectoryPrefix) { + return std::nullopt; + } + + EpochId epoch{}; + for (std::size_t i = 0; i < epoch.size(); ++i) { + const int high = HexNibble(name[kPrefixLength + (2 * i)]); + const int low = HexNibble(name[kPrefixLength + (2 * i) + 1]); + if (high < 0 || low < 0) return std::nullopt; + epoch[i] = static_cast((high << 4) | low); + } + if (IsZeroEpochId(epoch)) return std::nullopt; + return epoch; +} + +[[nodiscard]] inline std::variant FormatEpochDirectoryName( + const EpochId& epoch) noexcept { + if (IsZeroEpochId(epoch)) return LayoutError::ZeroEpochId; + constexpr char kHex[] = "0123456789abcdef"; + constexpr std::size_t kPrefixLength = sizeof(kEpochDirectoryPrefix) - 1; + constexpr std::size_t kCanonicalLength = kPrefixLength + 32; + try { + std::string name; + name.reserve(kCanonicalLength); + name.append(kEpochDirectoryPrefix, kPrefixLength); + for (const auto byte : epoch) { + name.push_back(kHex[(byte >> 4) & 0x0f]); + name.push_back(kHex[byte & 0x0f]); + } + return name; + } catch (...) { + return LayoutError::AllocationFailure; + } +} + +} // namespace rateguard::supervisor::epoch_layout_v1 diff --git a/src/supervisor/manifest_store.cpp b/src/supervisor/manifest_store.cpp index a6c55f9..97f726e 100644 --- a/src/supervisor/manifest_store.cpp +++ b/src/supervisor/manifest_store.cpp @@ -1,6 +1,7 @@ #include "supervisor/manifest_store.h" #include "supervisor/epoch_gate.h" +#include "supervisor/epoch_artifact_layout.h" #include "platform/file_io.h" #include @@ -15,9 +16,9 @@ namespace rateguard::supervisor { namespace { -constexpr char kLockName[] = "owner.lock"; -constexpr char kManifestName[] = "manifest.json"; -constexpr char kTempName[] = "manifest.tmp"; +constexpr auto& kLockName = epoch_layout_v1::kManifestStoreLockFileName; +constexpr auto& kManifestName = epoch_layout_v1::kManifestFileName; +constexpr auto& kTempName = epoch_layout_v1::kManifestTemporaryFileName; constexpr std::size_t kMaxDirectoryPathBytes = 4096; bool ValidPath(const std::string& path) noexcept; diff --git a/tests/supervisor/epoch_artifact_layout_test.cpp b/tests/supervisor/epoch_artifact_layout_test.cpp new file mode 100644 index 0000000..883a4d8 --- /dev/null +++ b/tests/supervisor/epoch_artifact_layout_test.cpp @@ -0,0 +1,104 @@ +#include "supervisor/epoch_artifact_layout.h" + +#include +#include +#include +#include +#include + +namespace layout = rateguard::supervisor::epoch_layout_v1; +using rateguard::supervisor::EpochId; + +namespace { + +int failures = 0; + +void Check(bool condition, std::string_view label) { + if (!condition) { + ++failures; + std::cerr << "FAIL: " << label << '\n'; + } +} + +void RoundTrip(const EpochId& id, std::string_view expected) { + const auto encoded = layout::FormatEpochDirectoryName(id); + const auto* name = std::get_if(&encoded); + Check(name != nullptr, "format accepted nonzero ID"); + if (name == nullptr) return; + Check(*name == expected, "format canonical expected spelling"); + const auto parsed = layout::ParseEpochDirectoryName(*name); + Check(parsed.has_value(), "parse formatted name"); + if (parsed) Check(*parsed == id, "round trip preserves all bytes"); +} + +void TestNames() { + constexpr std::array, 7> kNames{{ + {"epoch-", layout::kEpochDirectoryPrefix}, + {"intent.json", layout::kIntentFileName}, + {"intent.tmp", layout::kIntentTemporaryFileName}, + {"manifest-store", layout::kManifestStoreDirectoryName}, + {"owner.lock", layout::kManifestStoreLockFileName}, + {"manifest.json", layout::kManifestFileName}, + {"manifest.tmp", layout::kManifestTemporaryFileName}, + }}; + for (const auto& [expected, actual] : kNames) + Check(expected == actual, "shared v1 artifact name constant"); +} + +void TestRoundTrips() { + EpochId zero_first{}; + zero_first[15] = 1; + RoundTrip(zero_first, "epoch-00000000000000000000000000000001"); + + EpochId all_ff{}; + all_ff.fill(0xff); + RoundTrip(all_ff, "epoch-ffffffffffffffffffffffffffffffff"); + + EpochId alternating{}; + for (std::size_t i = 0; i < alternating.size(); ++i) + alternating[i] = i % 2 == 0 ? 0x0a : 0xb0; + RoundTrip(alternating, "epoch-0ab00ab00ab00ab00ab00ab00ab00ab0"); + + EpochId max_first{}; + max_first[0] = 0x80; + max_first[15] = 0x01; + RoundTrip(max_first, "epoch-80000000000000000000000000000001"); +} + +void TestRejectedNames() { + constexpr std::string_view kValid = "epoch-00000000000000000000000000000001"; + Check(layout::ParseEpochDirectoryName(kValid).has_value(), "canonical sample parses"); + Check(!layout::ParseEpochDirectoryName("epoch-00000000000000000000000000000000"), + "all-zero ID rejected"); + Check(!layout::ParseEpochDirectoryName("Epoch-00000000000000000000000000000001"), + "uppercase prefix rejected"); + Check(!layout::ParseEpochDirectoryName("epoch-0000000000000000000000000000000A"), + "uppercase hex rejected"); + Check(!layout::ParseEpochDirectoryName("epoch-0000000000000000000000000000000g"), + "non-hex character rejected"); + Check(!layout::ParseEpochDirectoryName("epoch-0000000000000000000000000000001"), + "short name rejected"); + Check(!layout::ParseEpochDirectoryName("epoch-000000000000000000000000000000001"), + "long name rejected"); + Check(!layout::ParseEpochDirectoryName("xepoch-00000000000000000000000000000001"), + "noncanonical prefix rejected"); + Check(!layout::ParseEpochDirectoryName("epoch_00000000000000000000000000000001"), + "alternate separator rejected"); + + const EpochId all_zero{}; + const auto formatted_zero = layout::FormatEpochDirectoryName(all_zero); + const auto* error = std::get_if(&formatted_zero); + Check(error != nullptr && *error == layout::LayoutError::ZeroEpochId, + "format rejects zero ID with typed error"); +} + +} // namespace + +int main() { + TestNames(); + TestRoundTrips(); + TestRejectedNames(); + if (failures != 0) return 1; + std::cout << "epoch artifact layout checks passed\n"; + return 0; +} From f546350f7aa16e78b3a8f148c494dab7b139ea66 Mon Sep 17 00:00:00 2001 From: Kshiteesh R Bharadwaj <100955403+kshiteesh28@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:42:41 -0600 Subject: [PATCH 3/8] feat(supervisor): reconcile optional manifest recovery evidence --- CMakeLists.txt | 2 + src/supervisor/bootstrap_recovery_reader.cpp | 370 ++++++++++++++++--- src/supervisor/bootstrap_recovery_reader.h | 35 ++ 3 files changed, 355 insertions(+), 52 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a6233eb..1f2911d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -678,3 +678,5 @@ endif() add_test(NAME rateguard.epoch_artifact_layout COMMAND rateguard_epoch_artifact_layout_tests) set_tests_properties(rateguard.epoch_artifact_layout PROPERTIES TIMEOUT 30) + +target_link_libraries(rateguard_bootstrap_recovery_reader PUBLIC rateguard_manifest_codec) diff --git a/src/supervisor/bootstrap_recovery_reader.cpp b/src/supervisor/bootstrap_recovery_reader.cpp index 1aeaae4..4ddaf46 100644 --- a/src/supervisor/bootstrap_recovery_reader.cpp +++ b/src/supervisor/bootstrap_recovery_reader.cpp @@ -1,4 +1,5 @@ #include "supervisor/bootstrap_recovery_reader.h" +#include "supervisor/epoch_artifact_layout.h" #include "platform/file_io.h" @@ -6,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -20,8 +22,7 @@ using platform::file::UniqueFd; constexpr char kLockName[] = "owner.lock"; constexpr char kAnchorName[] = "runtime-anchor.json"; -constexpr char kEpochPrefix[] = "epoch-"; -constexpr char kIntentName[] = "intent.json"; +using namespace epoch_layout_v1; bool Fail(IRecoveryReaderIo* io, RecoveryReaderIoPoint point) noexcept { return io != nullptr && io->FailAt(point); @@ -55,25 +56,6 @@ bool IsOwnedIntentFile(const struct stat& st) noexcept { st.st_nlink == 1 && st.st_size >= 0; } -int Nibble(char c) noexcept { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'a' && c <= 'f') return c - 'a' + 10; - return -1; -} - -bool ParseEpochName(std::string_view name, EpochId& epoch) noexcept { - constexpr std::size_t kNameLength = sizeof(kEpochPrefix) - 1 + 32; - if (name.size() != kNameLength || !name.starts_with(kEpochPrefix)) return false; - const auto hex = name.substr(sizeof(kEpochPrefix) - 1); - for (std::size_t i = 0; i < epoch.size(); ++i) { - const int hi = Nibble(hex[2 * i]); - const int lo = Nibble(hex[2 * i + 1]); - if (hi < 0 || lo < 0) return false; - epoch[i] = static_cast((hi << 4) | lo); - } - return std::any_of(epoch.begin(), epoch.end(), [](std::uint8_t byte) { return byte != 0; }); -} - struct Entry final { std::string name; struct stat st {}; @@ -139,7 +121,8 @@ void AddEpochIssue(ScanContext& ctx, std::size_t epoch_index, RecoveryIssueCode } Listing EnumerateDirectory(int directory_fd, ScanContext& ctx, - RecoveryReaderIoPoint fail_point) { + RecoveryReaderIoPoint fail_point, std::size_t cap, + RecoveryReaderIoPoint stat_point) { Listing listing; if (Fail(ctx.io, fail_point)) { listing.complete = false; @@ -156,8 +139,6 @@ Listing EnumerateDirectory(int directory_fd, ScanContext& ctx, listing.complete = false; return listing; } - const std::size_t cap = fail_point == RecoveryReaderIoPoint::EnumerateEpoch - ? kMaxRecoveryChildEntries : kMaxRecoveryRootEntries; listing.entries.reserve(cap); DIR* stream = ::fdopendir(scan.get()); if (stream == nullptr) { @@ -183,7 +164,7 @@ Listing EnumerateDirectory(int directory_fd, ScanContext& ctx, } Entry entry; entry.name.assign(name); - if (Fail(ctx.io, RecoveryReaderIoPoint::StatRootEntry) || + if (Fail(ctx.io, stat_point) || ::fstatat(directory_fd, entry.name.c_str(), &entry.st, AT_SYMLINK_NOFOLLOW) != 0) { entry.stat_ok = false; listing.complete = false; @@ -211,8 +192,8 @@ bool SameListing(const Listing& a, const Listing& b) noexcept { return true; } -void ProcessIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, - const Entry& root_entry) { +void ProcessBootstrapIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, + const Entry& root_entry) { auto& diagnostic = ctx.snapshot.epochs[epoch_index]; UniqueFd child(::openat(root_fd, diagnostic.directory_name.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); @@ -229,7 +210,8 @@ void ProcessIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, } diagnostic.directory_identity = Identity(child_fd_stat); - Listing child_before = EnumerateDirectory(child.get(), ctx, RecoveryReaderIoPoint::EnumerateEpoch); + Listing child_before = EnumerateDirectory(child.get(), ctx, RecoveryReaderIoPoint::EnumerateEpoch, + kMaxRecoveryChildEntries, RecoveryReaderIoPoint::StatRootEntry); if (!child_before.complete) AddEpochIssue(ctx, epoch_index, child_before.limit_reached ? RecoveryIssueCode::TooManyChildEntries : RecoveryIssueCode::EpochDirectoryChanged); @@ -239,13 +221,14 @@ void ProcessIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidIntentFile); continue; } - if (entry.name == kIntentName) found_intent = true; - else AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochHasUnexpectedEntry); + if (entry.name == kIntentFileName) found_intent = true; + else if (entry.name != kManifestStoreDirectoryName) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochHasUnexpectedEntry); } if (ctx.stop) return; if (!found_intent) { struct stat probe{}; - if (::fstatat(child.get(), kIntentName, &probe, AT_SYMLINK_NOFOLLOW) == 0) { + if (::fstatat(child.get(), kIntentFileName, &probe, AT_SYMLINK_NOFOLLOW) == 0) { found_intent = true; } else if (errno == ENOENT) { AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::MissingIntent); @@ -261,7 +244,7 @@ void ProcessIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, return; } struct stat path_before{}; - if (::fstatat(child.get(), kIntentName, &path_before, AT_SYMLINK_NOFOLLOW) != 0 || + if (::fstatat(child.get(), kIntentFileName, &path_before, AT_SYMLINK_NOFOLLOW) != 0 || !IsOwnedIntentFile(path_before)) { AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidIntentFile); return; @@ -283,7 +266,7 @@ void ProcessIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::IntentReadFailed); return; } - UniqueFd intent(::openat(child.get(), kIntentName, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + UniqueFd intent(::openat(child.get(), kIntentFileName, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); if (intent.get() < 0) { AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::IntentReadFailed); return; @@ -291,7 +274,7 @@ void ProcessIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, struct stat file_fd_before{}, path_opened{}; if (::fstat(intent.get(), &file_fd_before) != 0 || !IsOwnedIntentFile(file_fd_before) || !SameInode(path_before, file_fd_before) || - ::fstatat(child.get(), kIntentName, &path_opened, AT_SYMLINK_NOFOLLOW) != 0 || + ::fstatat(child.get(), kIntentFileName, &path_opened, AT_SYMLINK_NOFOLLOW) != 0 || !(Identity(path_opened) == Identity(file_fd_before))) { AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::IntentChanged); return; @@ -309,7 +292,7 @@ void ProcessIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, struct stat file_fd_after{}, path_after{}; if (Fail(ctx.io, RecoveryReaderIoPoint::RevalidateEntry) || ::fstat(intent.get(), &file_fd_after) != 0 || !IsOwnedIntentFile(file_fd_after) || - ::fstatat(child.get(), kIntentName, &path_after, AT_SYMLINK_NOFOLLOW) != 0 || + ::fstatat(child.get(), kIntentFileName, &path_after, AT_SYMLINK_NOFOLLOW) != 0 || !IsOwnedIntentFile(path_after) || !(Identity(file_fd_before) == Identity(file_fd_after)) || !(Identity(file_fd_after) == Identity(path_after))) { @@ -329,8 +312,8 @@ void ProcessIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::DomainMismatch); return; } - EpochId directory_epoch{}; - if (!ParseEpochName(diagnostic.directory_name, directory_epoch) || inventory.epoch_id() != directory_epoch) { + const auto parsed_directory_epoch = ParseEpochDirectoryName(diagnostic.directory_name); + if (!parsed_directory_epoch || inventory.epoch_id() != *parsed_directory_epoch) { AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochMismatch); return; } @@ -352,7 +335,8 @@ void ProcessIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, diagnostic.inventory = std::make_shared(std::move(inventory)); if (!child_before.limit_reached) { - Listing child_after = EnumerateDirectory(child.get(), ctx, RecoveryReaderIoPoint::EnumerateEpoch); + Listing child_after = EnumerateDirectory(child.get(), ctx, RecoveryReaderIoPoint::EnumerateEpoch, + kMaxRecoveryChildEntries, RecoveryReaderIoPoint::StatRootEntry); if (!SameListing(child_before, child_after)) AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochDirectoryChanged); } @@ -365,6 +349,264 @@ void ProcessIntent(ScanContext& ctx, int root_fd, std::size_t epoch_index, AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochDirectoryChanged); } +bool IsOwnedEmptyLock(const struct stat& st) noexcept { + return IsOwnedIntentFile(st) && st.st_size == 0; +} + +bool ChargeRead(ScanContext& ctx, std::size_t bytes, std::size_t epoch_index) { + if (bytes > kMaxRecoveryAggregateBytes - ctx.bytes_reserved) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::AggregateByteLimit); + ctx.stop = true; + return false; + } + // Charge the stat-reported extent before allocation/open/read and never + // refund it after any parse, open, or read failure. + ctx.bytes_reserved += bytes; + return true; +} + +void ProcessManifestStore(ScanContext& ctx, int root_fd, std::size_t epoch_index, + const Entry& root_entry, + const std::optional& expected_store, + bool baseline_stat_failed) { + auto& epoch = ctx.snapshot.epochs[epoch_index]; + UniqueFd epoch_fd(::openat(root_fd, epoch.directory_name.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + if (epoch_fd.get() < 0) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochDirectoryChanged); + return; + } + struct stat epoch_fd_stat{}, epoch_path_stat{}; + if (::fstat(epoch_fd.get(), &epoch_fd_stat) != 0 || + !IsOwnedPrivateDirectory(epoch_fd_stat) || + ::fstatat(root_fd, epoch.directory_name.c_str(), &epoch_path_stat, AT_SYMLINK_NOFOLLOW) != 0 || + !SameInode(root_entry.st, epoch_fd_stat) || !SameInode(epoch_fd_stat, epoch_path_stat)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::EpochDirectoryChanged); + return; + } + + struct stat store_initial{}; + if (::fstatat(epoch_fd.get(), kManifestStoreDirectoryName, &store_initial, AT_SYMLINK_NOFOLLOW) != 0) { + if (errno == ENOENT && !expected_store && !baseline_stat_failed) + return; // Bootstrap-only history is a valid diagnostic shape. + if (errno == ENOENT && expected_store) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreChanged); + else + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreDirectory); + return; + } + RecoveryEpochDiagnostic::ManifestDiagnostic diagnostic; + epoch.manifest_store = diagnostic; + auto& manifest_diag = *epoch.manifest_store; + if (baseline_stat_failed || !expected_store || !(Identity(store_initial) == *expected_store)) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreChanged); + if (!IsOwnedPrivateDirectory(store_initial)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreDirectory); + return; + } + UniqueFd store_fd; + if (Fail(ctx.io, RecoveryReaderIoPoint::OpenManifestStoreDirectory)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreDirectory); + return; + } + store_fd = UniqueFd(::openat(epoch_fd.get(), kManifestStoreDirectoryName, + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + struct stat store_fd_before{}, store_path_opened{}; + if (store_fd.get() < 0 || ::fstat(store_fd.get(), &store_fd_before) != 0 || + !IsOwnedPrivateDirectory(store_fd_before) || + !(Identity(store_initial) == Identity(store_fd_before)) || + ::fstatat(epoch_fd.get(), kManifestStoreDirectoryName, &store_path_opened, AT_SYMLINK_NOFOLLOW) != 0 || + !(Identity(store_fd_before) == Identity(store_path_opened))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreDirectory); + return; + } + manifest_diag.directory_identity = Identity(store_fd_before); + + Listing before = EnumerateDirectory(store_fd.get(), ctx, + RecoveryReaderIoPoint::EnumerateManifestStore, kMaxRecoveryManifestStoreEntries, + RecoveryReaderIoPoint::StatManifestStoreEntry); + if (!before.complete) + AddEpochIssue(ctx, epoch_index, before.limit_reached + ? RecoveryIssueCode::TooManyManifestStoreEntries + : RecoveryIssueCode::ManifestStoreChanged); + for (const auto& entry : before.entries) { + if (!entry.stat_ok) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreFile); + continue; + } + if (entry.name == kManifestStoreLockFileName || entry.name == kManifestFileName) continue; + else AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreHasUnexpectedEntry); + } + // Always probe the two allowlisted names, even when an unrelated temporary + // or unknown entry made the listing incomplete. This preserves known data. + const auto validate_lock = [&]() { + struct stat path_before{}; + if (::fstatat(store_fd.get(), kManifestStoreLockFileName, &path_before, AT_SYMLINK_NOFOLLOW) != 0) { + AddEpochIssue(ctx, epoch_index, errno == ENOENT + ? RecoveryIssueCode::MissingManifestStoreFile + : RecoveryIssueCode::InvalidManifestStoreFile); + return; + } + if (!IsOwnedEmptyLock(path_before)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreFile); + return; + } + if (Fail(ctx.io, RecoveryReaderIoPoint::OpenManifestLock)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreReadFailed); + return; + } + UniqueFd lock(::openat(store_fd.get(), kManifestStoreLockFileName, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + struct stat fd_stat{}, path_after{}; + if (lock.get() < 0 || ::fstat(lock.get(), &fd_stat) != 0 || !IsOwnedEmptyLock(fd_stat) || + !(Identity(path_before) == Identity(fd_stat)) || + Fail(ctx.io, RecoveryReaderIoPoint::RevalidateManifestLock) || + ::fstatat(store_fd.get(), kManifestStoreLockFileName, &path_after, AT_SYMLINK_NOFOLLOW) != 0 || + !(Identity(fd_stat) == Identity(path_after))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreFileChanged); + return; + } + manifest_diag.owner_lock_identity = Identity(fd_stat); + }; + validate_lock(); + + const auto read_manifest = [&]() { + struct stat path_before{}; + if (::fstatat(store_fd.get(), kManifestFileName, &path_before, AT_SYMLINK_NOFOLLOW) != 0) { + AddEpochIssue(ctx, epoch_index, errno == ENOENT + ? RecoveryIssueCode::MissingManifestStoreFile + : RecoveryIssueCode::InvalidManifestStoreFile); + return; + } + if (!IsOwnedIntentFile(path_before)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestStoreFile); + return; + } + const auto size = static_cast(path_before.st_size); + if (size > std::numeric_limits::max()) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreFileTooLarge); + return; + } + if (!ChargeRead(ctx, static_cast(size), epoch_index)) return; + if (size > kMaxManifestBytes) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreFileTooLarge); + return; + } + if (Fail(ctx.io, RecoveryReaderIoPoint::OpenManifestFile)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreReadFailed); + return; + } + UniqueFd file(::openat(store_fd.get(), kManifestFileName, + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + struct stat fd_before{}, path_opened{}; + if (file.get() < 0 || ::fstat(file.get(), &fd_before) != 0 || + !IsOwnedIntentFile(fd_before) || !(Identity(path_before) == Identity(fd_before)) || + ::fstatat(store_fd.get(), kManifestFileName, &path_opened, AT_SYMLINK_NOFOLLOW) != 0 || + !(Identity(fd_before) == Identity(path_opened))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreFileChanged); + return; + } + manifest_diag.manifest_identity = Identity(fd_before); + if (Fail(ctx.io, RecoveryReaderIoPoint::ReadManifestFile)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreReadFailed); + return; + } + std::string bytes; + if (!ReadAll(file.get(), bytes, static_cast(size))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreReadFailed); + return; + } + struct stat fd_after{}, path_after{}; + if (Fail(ctx.io, RecoveryReaderIoPoint::RevalidateManifestFile) || + ::fstat(file.get(), &fd_after) != 0 || !IsOwnedIntentFile(fd_after) || + ::fstatat(store_fd.get(), kManifestFileName, &path_after, AT_SYMLINK_NOFOLLOW) != 0 || + !IsOwnedIntentFile(path_after) || !(Identity(fd_before) == Identity(fd_after)) || + !(Identity(fd_after) == Identity(path_after))) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreFileChanged); + return; + } + manifest_diag.manifest_identity = Identity(fd_after); + const auto decoded = DecodeManifestV1(bytes); + if (const auto* codec_error = std::get_if(&decoded)) { + if (*codec_error == ManifestCodecError::DigestMismatch) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestCodecDigestMismatch); + else if (*codec_error == ManifestCodecError::DigestFailure) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::DigestFailure); + else + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::InvalidManifestEncoding); + return; + } + auto manifest = std::get(decoded); + if (ctx.participants_retained + manifest.candidate.participants.size() > + kMaxRecoveryAggregateParticipants) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::AggregateParticipantLimit); + ctx.stop = true; + return; + } + ctx.participants_retained += manifest.candidate.participants.size(); + const auto digest = ManifestDigestV1(manifest); + if (const auto* codec_error = std::get_if(&digest)) { + (void)codec_error; + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::DigestFailure); + return; + } + manifest_diag.canonical_digest = std::get>(digest); + manifest_diag.decoded_manifest = std::make_shared(std::move(manifest)); + const auto& inventory = epoch.inventory; + if (!inventory) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestBootstrapNotReady); + return; + } + const auto candidate = inventory->ReadyCandidate(); + if (std::holds_alternative(candidate)) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestBootstrapNotReady); + } else if (std::get(candidate) != manifest_diag.decoded_manifest->candidate) { + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestCandidateMismatch); + } + }; + read_manifest(); + + Listing after = EnumerateDirectory(store_fd.get(), ctx, + RecoveryReaderIoPoint::EnumerateManifestStore, kMaxRecoveryManifestStoreEntries, + RecoveryReaderIoPoint::StatManifestStoreEntry); + if (!SameListing(before, after)) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreChanged); + struct stat store_fd_after{}, store_path_after{}, epoch_fd_after{}, epoch_path_after{}; + if (Fail(ctx.io, RecoveryReaderIoPoint::RevalidateManifestStore) || + ::fstat(store_fd.get(), &store_fd_after) != 0 || + !IsOwnedPrivateDirectory(store_fd_after) || + !(Identity(store_fd_before) == Identity(store_fd_after)) || + ::fstatat(epoch_fd.get(), kManifestStoreDirectoryName, &store_path_after, AT_SYMLINK_NOFOLLOW) != 0 || + !IsOwnedPrivateDirectory(store_path_after) || + !(Identity(store_fd_after) == Identity(store_path_after)) || + ::fstat(epoch_fd.get(), &epoch_fd_after) != 0 || + ::fstatat(root_fd, epoch.directory_name.c_str(), &epoch_path_after, AT_SYMLINK_NOFOLLOW) != 0 || + !IsOwnedPrivateDirectory(epoch_fd_after) || + !(Identity(root_entry.st) == Identity(epoch_fd_after)) || + !(Identity(epoch_fd_after) == Identity(epoch_path_after))) + AddEpochIssue(ctx, epoch_index, RecoveryIssueCode::ManifestStoreChanged); +} + +void ProcessEpochArtifacts(ScanContext& ctx, int root_fd, std::size_t epoch_index, + const Entry& root_entry) { + std::optional expected_store; + bool baseline_stat_failed = false; + UniqueFd epoch_fd(::openat(root_fd, ctx.snapshot.epochs[epoch_index].directory_name.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); + if (epoch_fd.get() >= 0) { + struct stat path_stat{}; + if (::fstatat(epoch_fd.get(), kManifestStoreDirectoryName, &path_stat, AT_SYMLINK_NOFOLLOW) == 0) + expected_store = Identity(path_stat); + else if (errno != ENOENT) + baseline_stat_failed = true; + } else { + baseline_stat_failed = true; + } + ProcessBootstrapIntent(ctx, root_fd, epoch_index, root_entry); + if (!ctx.stop) + ProcessManifestStore(ctx, root_fd, epoch_index, root_entry, expected_store, baseline_stat_failed); +} + } // namespace BootstrapRecoveryReadResult BootstrapRecoveryReader::Read( @@ -394,7 +636,8 @@ BootstrapRecoveryReadResult BootstrapRecoveryReader::Read( snapshot->epochs.reserve(kMaxRecoveryEpochDirectories); snapshot->issues.reserve(kMaxRecoveryIssues); ScanContext ctx{*snapshot, test_io}; - Listing root_before = EnumerateDirectory(root.get(), ctx, RecoveryReaderIoPoint::EnumerateRootFirst); + Listing root_before = EnumerateDirectory(root.get(), ctx, RecoveryReaderIoPoint::EnumerateRootFirst, + kMaxRecoveryRootEntries, RecoveryReaderIoPoint::StatRootEntry); if (!root_before.complete) { AddRootIssue(ctx, root_before.limit_reached ? RecoveryIssueCode::TooManyRootEntries : RecoveryIssueCode::RootEnumerationFailed); @@ -405,13 +648,13 @@ BootstrapRecoveryReadResult BootstrapRecoveryReader::Read( if (ctx.stop) break; if (!entry.stat_ok) AddRootIssue(ctx, RecoveryIssueCode::RootEntryStatFailed); if (entry.name == kLockName || entry.name == kAnchorName) continue; - EpochId parsed_epoch{}; - if (!entry.name.starts_with(kEpochPrefix)) { + if (!entry.name.starts_with(kEpochDirectoryPrefix)) { AddRootIssue(ctx, RecoveryIssueCode::UnexpectedRootEntry); continue; } found_any_epoch_dir = true; - if (!ParseEpochName(entry.name, parsed_epoch)) { + const auto parsed = ParseEpochDirectoryName(entry.name); + if (!parsed) { AddRootIssue(ctx, RecoveryIssueCode::InvalidEpochDirectoryName); continue; } @@ -433,7 +676,7 @@ BootstrapRecoveryReadResult BootstrapRecoveryReader::Read( diagnostic.directory_identity = Identity(entry.st); snapshot->epochs.push_back(std::move(diagnostic)); const auto index = snapshot->epochs.size() - 1; - ProcessIntent(ctx, root.get(), index, entry); + ProcessEpochArtifacts(ctx, root.get(), index, entry); } if (root_before.limit_reached) ctx.stop = true; if (root_before.empty) { @@ -444,20 +687,42 @@ BootstrapRecoveryReadResult BootstrapRecoveryReader::Read( AddRootIssue(ctx, RecoveryIssueCode::NoValidIntents); } - // Report duplicated identities across epoch records; do not pick a latest record. + // Compare the union of bootstrap and manifest targets across epochs. + // Matching representations in one epoch intentionally repeat the same + // participants; only duplicates across epoch contexts are collisions. std::set> containers; std::set>> processes; for (std::size_t i = 0; i < snapshot->epochs.size() && !ctx.stop; ++i) { - const auto& inventory = snapshot->epochs[i].inventory; - if (!inventory) continue; - for (const auto& record : inventory->records()) { - if (!containers.insert(record.planned.container_id).second) { + std::set> epoch_containers; + std::set>> epoch_processes; + const auto add_target = [&](const std::string& container, std::uint64_t pid, + std::uint64_t start_ticks, + const std::array& boot) { + epoch_containers.insert(container); + if (pid != 0 && start_ticks != 0) epoch_processes.emplace(pid, start_ticks, boot); + }; + if (const auto& inventory = snapshot->epochs[i].inventory; inventory) { + for (const auto& record : inventory->records()) { + add_target(record.planned.container_id, record.identity_recorded ? record.pid : 0, + record.identity_recorded ? record.pid_start_ticks : 0, + record.clock_identity.boot_uuid); + } + } + if (const auto& manifest = snapshot->epochs[i].manifest_store; + manifest && manifest->decoded_manifest) { + for (const auto& participant : manifest->decoded_manifest->candidate.participants) { + add_target(participant.process.container_id, participant.process.pid, + participant.process.pid_start_ticks, participant.clock_identity.boot_uuid); + } + } + for (const auto& container : epoch_containers) { + if (!containers.insert(container).second) { AddEpochIssue(ctx, i, RecoveryIssueCode::IdentityCollisionAcrossEpochs); if (ctx.stop) break; } - if (!record.identity_recorded) continue; - const auto& boot = record.clock_identity.boot_uuid; - if (!processes.emplace(record.pid, record.pid_start_ticks, boot).second) { + } + for (const auto& process : epoch_processes) { + if (!processes.insert(process).second) { AddEpochIssue(ctx, i, RecoveryIssueCode::IdentityCollisionAcrossEpochs); if (ctx.stop) break; } @@ -465,7 +730,8 @@ BootstrapRecoveryReadResult BootstrapRecoveryReader::Read( } if (!ctx.stop) { - Listing root_after = EnumerateDirectory(root.get(), ctx, RecoveryReaderIoPoint::EnumerateRootSecond); + Listing root_after = EnumerateDirectory(root.get(), ctx, RecoveryReaderIoPoint::EnumerateRootSecond, + kMaxRecoveryRootEntries, RecoveryReaderIoPoint::StatRootEntry); struct stat root_after_stat{}; if (!SameListing(root_before, root_after) || ::fstat(root.get(), &root_after_stat) != 0 || !IsOwnedPrivateDirectory(root_after_stat) || diff --git a/src/supervisor/bootstrap_recovery_reader.h b/src/supervisor/bootstrap_recovery_reader.h index 40d42af..b454f4c 100644 --- a/src/supervisor/bootstrap_recovery_reader.h +++ b/src/supervisor/bootstrap_recovery_reader.h @@ -4,6 +4,7 @@ // recovery-mode RuntimeOwner. The result is never a serving or fencing token. #include "supervisor/bootstrap_inventory.h" +#include "supervisor/manifest_codec.h" #include "supervisor/runtime_owner.h" #include @@ -20,6 +21,7 @@ namespace rateguard::supervisor { inline constexpr std::size_t kMaxRecoveryEpochDirectories = 1024; inline constexpr std::size_t kMaxRecoveryRootEntries = 4096; inline constexpr std::size_t kMaxRecoveryChildEntries = 16; +inline constexpr std::size_t kMaxRecoveryManifestStoreEntries = 16; inline constexpr std::size_t kMaxRecoveryAggregateBytes = 64U * 1024U * 1024U; inline constexpr std::size_t kMaxRecoveryAggregateParticipants = 16'384; inline constexpr std::size_t kMaxRecoveryIssues = 256; @@ -69,6 +71,19 @@ enum class RecoveryIssueCode : std::uint8_t { RootChangedDuringScan, OwnerChangedDuringScan, ResourceLimit, + InvalidManifestStoreDirectory, + ManifestStoreChanged, + ManifestStoreHasUnexpectedEntry, + TooManyManifestStoreEntries, + MissingManifestStoreFile, + InvalidManifestStoreFile, + ManifestStoreReadFailed, + ManifestStoreFileChanged, + ManifestStoreFileTooLarge, + InvalidManifestEncoding, + ManifestCodecDigestMismatch, + ManifestCandidateMismatch, + ManifestBootstrapNotReady, }; struct RecoveryEpochDiagnostic final { @@ -78,6 +93,17 @@ struct RecoveryEpochDiagnostic final { std::optional intent_identity; std::shared_ptr inventory; std::optional> canonical_digest; + // Present only when the optional `manifest-store` child existed and was + // inspected. A decoded manifest is diagnostic data, never an activation, + // stop, reset, or successor-epoch authorization. + struct ManifestDiagnostic final { + RecoveryFileIdentity directory_identity{}; + std::optional owner_lock_identity; + std::optional manifest_identity; + std::shared_ptr decoded_manifest; + std::optional> canonical_digest; + }; + std::optional manifest_store; std::vector issues; bool issues_truncated{}; }; @@ -127,6 +153,15 @@ enum class RecoveryReaderIoPoint : std::uint8_t { ReadIntent, RevalidateEntry, ValidateOwnerAfter, + OpenManifestStoreDirectory, + EnumerateManifestStore, + StatManifestStoreEntry, + OpenManifestLock, + RevalidateManifestLock, + OpenManifestFile, + ReadManifestFile, + RevalidateManifestFile, + RevalidateManifestStore, }; class IRecoveryReaderIo { From 52e6d02148b2b2cdb70a9d0bb89293464562b63f Mon Sep 17 00:00:00 2001 From: Kshiteesh R Bharadwaj <100955403+kshiteesh28@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:42:45 -0600 Subject: [PATCH 4/8] test(supervisor): cover artifact phases and scan changes --- CMakeLists.txt | 2 + .../bootstrap_recovery_reader_test.cpp | 314 ++++++++++++++++++ 2 files changed, 316 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1f2911d..0fb7cab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -680,3 +680,5 @@ set_tests_properties(rateguard.epoch_artifact_layout PROPERTIES TIMEOUT 30) target_link_libraries(rateguard_bootstrap_recovery_reader PUBLIC rateguard_manifest_codec) + +target_link_libraries(rateguard_bootstrap_recovery_reader_tests PRIVATE rateguard_manifest_store) diff --git a/tests/supervisor/bootstrap_recovery_reader_test.cpp b/tests/supervisor/bootstrap_recovery_reader_test.cpp index f5f9676..fc4928b 100644 --- a/tests/supervisor/bootstrap_recovery_reader_test.cpp +++ b/tests/supervisor/bootstrap_recovery_reader_test.cpp @@ -1,5 +1,6 @@ #include "supervisor/bootstrap_recovery_reader.h" #include "supervisor/bootstrap_store.h" +#include "supervisor/manifest_store.h" #include #include @@ -106,6 +107,49 @@ void CreateHistory(const std::string& root, const BootstrapPlan& plan, bool reco owner.reset(); } +void CreateReadyHistoryWithManifest(const std::string& root, const BootstrapPlan& plan, + ManifestPhase phase = ManifestPhase::Prepared) { + auto owner_result = RuntimeOwner::CreateNew(root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + auto boot = BootstrapStore::CreateNew(std::move(std::get(claim_result)), plan); + CHECK(boot.ok() && boot.visibility == BootstrapVisibility::Durable); + for (std::size_t i = 0; i < plan.participants.size(); ++i) { + const auto before = boot.store->Snapshot(); + const auto digest = BootstrapDigestV1(*before); + CHECK((std::holds_alternative>(digest))); + const auto update = boot.store->RecordIdentity(before->revision(), + std::get>(digest), Observe(plan, i, 515 + i)); + CHECK(update.store_error == BootstrapStoreError::None); + CHECK(update.visibility == BootstrapVisibility::Durable); + } + const auto ready = boot.store->Snapshot()->ReadyCandidate(); + CHECK(std::holds_alternative(ready)); + const auto manifest_path = root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + OperationId operation{}; + operation.fill(0x90); + auto store_result = ManifestStore::CreateNew(manifest_path, + std::get(ready), operation); + CHECK(std::holds_alternative>(store_result)); + auto manifest = std::move(std::get>(store_result)); + const std::array next_phases{ + ManifestPhase::Active, ManifestPhase::Draining, ManifestPhase::Closed}; + for (const auto next : next_phases) { + if (static_cast(next) <= static_cast(phase)) { + const auto digest = manifest->digest(); + ++operation[0]; + const auto update = manifest->Transition(manifest->snapshot().generation, digest, + next, operation); + CHECK(update.visibility == ManifestVisibility::Durable && !update.error.has_value()); + } + } + manifest.reset(); + boot.store.reset(); + owner.reset(); +} + std::unique_ptr OpenRecoveryOwner(const TempRoot& temp, const BootstrapPlan& plan) { auto result = RuntimeOwner::OpenExisting(temp.root, plan.domain_id); CHECK(std::holds_alternative>(result)); @@ -144,6 +188,32 @@ struct MutateIntentAtReadback final : IRecoveryReaderIo { } }; +struct MutateManifestAtReadback final : IRecoveryReaderIo { + std::string path; + bool consumed{}; + explicit MutateManifestAtReadback(std::string p) : path(std::move(p)) {} + bool FailAt(RecoveryReaderIoPoint point) noexcept override { + if (consumed || point != RecoveryReaderIoPoint::RevalidateManifestFile) return false; + consumed = true; + return ::chmod(path.c_str(), 0640) != 0; + } +}; + +struct CreateManifestStoreAtIntentRevalidation final : IRecoveryReaderIo { + std::string source; + std::string destination; + bool consumed{}; + CreateManifestStoreAtIntentRevalidation(std::string from, std::string to) + : source(std::move(from)), destination(std::move(to)) {} + bool FailAt(RecoveryReaderIoPoint point) noexcept override { + if (consumed || point != RecoveryReaderIoPoint::RevalidateEntry) return false; + consumed = true; + std::error_code error; + std::filesystem::copy(source, destination, std::filesystem::copy_options::recursive, error); + return static_cast(error); + } +}; + void TestRecoveryScanRetainsPendingRosterAndCanRepeat() { TempRoot temp; const auto plan = MakePlan(); @@ -260,6 +330,193 @@ void TestPostReadModeChangeIsDetected() { CHECK(HasIssue(*snapshot, RecoveryIssueCode::IntentChanged)); } +void TestManifestPhasesAndCandidateBinding() { + for (const auto phase : {ManifestPhase::Prepared, ManifestPhase::Active, + ManifestPhase::Draining, ManifestPhase::Closed}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan, phase); + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(snapshot->scan_complete && snapshot->epochs.size() == 1); + CHECK(snapshot->epochs[0].inventory != nullptr); + CHECK(snapshot->epochs[0].manifest_store.has_value()); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest->phase == phase); + CHECK(snapshot->epochs[0].manifest_store->canonical_digest.has_value()); + } + + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto path = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store/manifest.json"; + auto owner = OpenRecoveryOwner(temp, plan); + const auto original = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(original)); + const auto original_snapshot = std::get>(original); + auto mismatched = *original_snapshot->epochs[0].manifest_store->decoded_manifest; + mismatched.candidate.policy_digest[0] ^= 0x5a; + const auto encoded = EncodeManifestV1(mismatched); + CHECK(std::holds_alternative(encoded)); + owner.reset(); + CHECK(::unlink(path.c_str()) == 0); + { std::ofstream output(path, std::ios::binary); output << std::get(encoded); } + CHECK(::chmod(path.c_str(), 0600) == 0); + owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestCandidateMismatch)); +} + +void TestManifestUnknownAndMissingFilesKeepBootstrapInventory() { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto directory = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto partial = directory + "/manifest.tmp"; + { std::ofstream output(partial); output << "partial"; } + CHECK(::chmod(partial.c_str(), 0600) == 0); + auto owner = OpenRecoveryOwner(temp, plan); + auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestStoreHasUnexpectedEntry)); + owner.reset(); + CHECK(::unlink(partial.c_str()) == 0); + CHECK(::unlink((directory + "/manifest.json").c_str()) == 0); + owner = OpenRecoveryOwner(temp, plan); + result = BootstrapRecoveryReader::Read(*owner); + snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::MissingManifestStoreFile)); +} + +void TestPendingBootstrapDoesNotClaimManifestMismatch() { + TempRoot pending; + TempRoot complete; + const auto plan = MakePlan(); + CreateHistory(pending.root, plan, true); + CreateReadyHistoryWithManifest(complete.root, plan); + const auto source = complete.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto destination = pending.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + std::filesystem::copy(source, destination, std::filesystem::copy_options::recursive); + CHECK(std::filesystem::exists(destination + "/manifest.json")); + auto owner = OpenRecoveryOwner(pending, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestBootstrapNotReady)); + CHECK(!HasIssue(*snapshot, RecoveryIssueCode::ManifestCandidateMismatch)); +} + +void TestManifestMetadataMutationsAndUnsafeObjectsFailClosed() { + { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto manifest = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store/manifest.json"; + auto owner = OpenRecoveryOwner(temp, plan); + MutateManifestAtReadback mutate(manifest); + const auto result = BootstrapRecoveryReader::Read(*owner, &mutate); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestStoreFileChanged)); + } + { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto directory = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto lock = directory + "/owner.lock"; + CHECK(::unlink(lock.c_str()) == 0); + const auto target = temp.parent + "/safe-empty-lock"; + { std::ofstream output(target); } + CHECK(::chmod(target.c_str(), 0600) == 0); + CHECK(::symlink(target.c_str(), lock.c_str()) == 0); + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::InvalidManifestStoreFile)); + } + { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto directory = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto manifest = directory + "/manifest.json"; + CHECK(::unlink(manifest.c_str()) == 0); + CHECK(::mkfifo(manifest.c_str(), 0600) == 0); + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::InvalidManifestStoreFile)); + } + { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto directory = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto manifest = directory + "/manifest.json"; + CHECK(::link(manifest.c_str(), (directory + "/extra-link").c_str()) == 0); + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestStoreHasUnexpectedEntry)); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::InvalidManifestStoreFile)); + } +} + +void TestManifestStoreEntryCapRetainsDecodedManifest() { + TempRoot temp; + const auto plan = MakePlan(); + CreateReadyHistoryWithManifest(temp.root, plan); + const auto directory = temp.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + for (std::size_t i = 0; i <= kMaxRecoveryManifestStoreEntries; ++i) { + const auto path = directory + "/extra-" + std::to_string(i); + { std::ofstream output(path); output << "x"; } + CHECK(::chmod(path.c_str(), 0600) == 0); + } + auto owner = OpenRecoveryOwner(temp, plan); + const auto result = BootstrapRecoveryReader::Read(*owner); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs[0].inventory != nullptr); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::TooManyManifestStoreEntries)); +} + +void TestManifestStoreCreatedDuringScanIsExplicitlyUncertain() { + TempRoot pending; + TempRoot complete; + const auto plan = MakePlan(); + CreateHistory(pending.root, plan); + CreateReadyHistoryWithManifest(complete.root, plan); + const auto source = complete.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + const auto destination = pending.root + "/" + EpochName(plan.epoch_id) + "/manifest-store"; + auto owner = OpenRecoveryOwner(pending, plan); + CreateManifestStoreAtIntentRevalidation create(source, destination); + const auto result = BootstrapRecoveryReader::Read(*owner, &create); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete && snapshot->epochs.size() == 1); + CHECK(snapshot->epochs[0].manifest_store->decoded_manifest != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::ManifestStoreChanged)); +} + void TestCrossEpochContainerCollisionIsReported() { TempRoot temp; const auto first = MakePlan(0x11); @@ -354,6 +611,56 @@ void WriteInventoryDirectory(const std::string& root, const BootstrapPlan& plan) CHECK(::chmod(intent.c_str(), 0600) == 0); } +void WriteRawBytes(const std::string& path, const std::string& bytes) { + std::ofstream out(path, std::ios::binary); + out.write(bytes.data(), static_cast(bytes.size())); + CHECK(out.good()); +} + +struct ManifestReadCounter final : IRecoveryReaderIo { + std::size_t intent_reads{}; + std::size_t manifest_reads{}; + bool FailAt(RecoveryReaderIoPoint point) noexcept override { + if (point == RecoveryReaderIoPoint::ReadIntent) ++intent_reads; + if (point == RecoveryReaderIoPoint::ReadManifestFile) ++manifest_reads; + return false; + } +}; + +void TestAggregateBudgetIncludesManifestAttemptedBytes() { + TempRoot temp; + const auto target = MakePlan(0xf0); + CreateOwnerOnly(temp.root, target.domain_id); + const std::string invalid(kMaxBootstrapBytes, 'x'); + for (std::uint8_t n = 0x10; n < 0x1f; ++n) { + const auto child = temp.root + "/" + EpochName(MakePlan(n).epoch_id); + CHECK(::mkdir(child.c_str(), 0700) == 0); + const auto path = child + "/intent.json"; + WriteRawBytes(path, invalid); + CHECK(::chmod(path.c_str(), 0600) == 0); + } + WriteInventoryDirectory(temp.root, target); + const auto manifest_directory = temp.root + "/" + EpochName(target.epoch_id) + "/manifest-store"; + CHECK(::mkdir(manifest_directory.c_str(), 0700) == 0); + const auto lock = manifest_directory + "/owner.lock"; + WriteRawBytes(lock, ""); + CHECK(::chmod(lock.c_str(), 0600) == 0); + const auto manifest = manifest_directory + "/manifest.json"; + const std::string oversized(kMaxManifestBytes + 1, 'x'); + WriteRawBytes(manifest, oversized); + CHECK(::chmod(manifest.c_str(), 0600) == 0); + + auto owner = OpenRecoveryOwner(temp, target); + ManifestReadCounter counter; + const auto result = BootstrapRecoveryReader::Read(*owner, &counter); + CHECK(std::holds_alternative>(result)); + const auto snapshot = std::get>(result); + CHECK(!snapshot->scan_complete); + CHECK(!snapshot->epochs.empty() && snapshot->epochs.back().inventory != nullptr); + CHECK(HasIssue(*snapshot, RecoveryIssueCode::AggregateByteLimit)); + CHECK(counter.manifest_reads == 0); // Budget is reserved before the over-cap read. +} + void TestAggregateParticipantLimitRetainsPriorInventories() { TempRoot temp; const auto first = MakeMaxParticipantPlan(0x11); @@ -430,6 +737,13 @@ int main() { TestEmptyAndMissingIntentRemainUnknown(); TestWrongModeAndInjectedReadFailure(); TestPostReadModeChangeIsDetected(); + TestManifestPhasesAndCandidateBinding(); + TestManifestUnknownAndMissingFilesKeepBootstrapInventory(); + TestPendingBootstrapDoesNotClaimManifestMismatch(); + TestManifestMetadataMutationsAndUnsafeObjectsFailClosed(); + TestManifestStoreEntryCapRetainsDecodedManifest(); + TestManifestStoreCreatedDuringScanIsExplicitlyUncertain(); + TestAggregateBudgetIncludesManifestAttemptedBytes(); TestCrossEpochContainerCollisionIsReported(); TestAggregateParticipantLimitRetainsPriorInventories(); TestAggregateByteLimitIsReservedBeforeRead(); From a911bea63131a9508f0baa758ed09d34b2922782 Mon Sep 17 00:00:00 2001 From: Kshiteesh R Bharadwaj <100955403+kshiteesh28@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:42:49 -0600 Subject: [PATCH 5/8] test(supervisor): independently check joint artifact limits --- .github/workflows/contract-build.yml | 125 ++- CMakeLists.txt | 16 +- ..._artifact_integration_independent_test.cpp | 709 ++++++++++++++++++ 3 files changed, 844 insertions(+), 6 deletions(-) create mode 100644 tests/supervisor/epoch_artifact_integration_independent_test.cpp diff --git a/.github/workflows/contract-build.yml b/.github/workflows/contract-build.yml index 0dfbfd0..c447275 100644 --- a/.github/workflows/contract-build.yml +++ b/.github/workflows/contract-build.yml @@ -86,9 +86,128 @@ jobs: ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 run: | - cmake -S . -B build-bootstrap-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_BOOTSTRAP=ON -DRATEGUARD_SANITIZE_RUNTIME=ON - cmake --build build-bootstrap-sanitized --parallel 2 --target rateguard_bootstrap_inventory_tests rateguard_bootstrap_inventory_independent_tests rateguard_bootstrap_store_tests rateguard_bootstrap_store_independent_tests rateguard_bootstrap_recovery_reader_tests rateguard_bootstrap_recovery_reader_independent_tests - ctest --test-dir build-bootstrap-sanitized --output-on-failure -R '^rateguard[.]bootstrap_(inventory|store|recovery_reader)(_independent)?$' + cmake -S . -B build-bootstrap-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_BOOTSTRAP=ON -DRATEGUARD_SANITIZE_RUNTIME=ON -DRATEGUARD_SANITIZE_MANIFEST=ON + cmake --build build-bootstrap-sanitized --parallel 2 --target rateguard_bootstrap_inventory_tests rateguard_bootstrap_inventory_independent_tests rateguard_bootstrap_store_tests rateguard_bootstrap_store_independent_tests rateguard_bootstrap_recovery_reader_tests rateguard_bootstrap_recovery_reader_independent_tests rateguard_epoch_artifact_layout_tests rateguard_epoch_artifact_integration_independent_tests + ctest --test-dir build-bootstrap-sanitized --output-on-failure -R '^rateguard[.](bootstrap_(inventory|store|recovery_reader)(_independent)?|epoch_artifact_(layout|integration_independent)) + + - name: Check durable manifest components under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-manifest-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_MANIFEST=ON + cmake --build build-manifest-sanitized --parallel 2 --target rateguard_manifest_codec_tests rateguard_manifest_store_tests rateguard_manifest_store_independent_tests + ctest --test-dir build-manifest-sanitized --output-on-failure -R '^rateguard[.]manifest_(codec|store|store_independent)$' + + - name: Check configured runtime ownership under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-runtime-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_RUNTIME=ON + cmake --build build-runtime-sanitized --parallel 2 --target rateguard_runtime_owner_tests rateguard_runtime_owner_independent_tests + ctest --test-dir build-runtime-sanitized --output-on-failure -R '^rateguard[.]runtime_owner(_independent)?$' + + - name: Check local supervisor lifecycle under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-supervisor-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_SUPERVISOR=ON + cmake --build build-supervisor-sanitized --parallel 2 --target rateguard_epoch_gate_tests rateguard_epoch_gate_independent_tests + ctest --test-dir build-supervisor-sanitized --output-on-failure -R '^rateguard[.]epoch_gate(_independent)?$' + + - name: Check clock and test fixtures under address/undefined sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-clock-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_CLOCK=ON + cmake --build build-clock-sanitized --parallel 2 --target rateguard_clock_tests rateguard_clock_independent_tests rateguard_clock_linux_smoke + ctest --test-dir build-clock-sanitized --output-on-failure -R '^rateguard[.]clock($|_independent$|_linux$)' + + - name: Check history components under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-history-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_HISTORY=ON + cmake --build build-history-sanitized --parallel 2 --target rateguard_history_inspect rateguard_event_recorder_tests rateguard_history_export_tests rateguard_history_validator_tests rateguard_history_reader_tests rateguard_aggregate_metrics_tests rateguard_history_file_publisher_tests rateguard_strict_reconciliation_tests + ctest --test-dir build-history-sanitized --output-on-failure -R '^rateguard[.](event_recorder|history_export|history_validator|history_reader|aggregate_metrics|history_file_publisher|strict_reconciliation|history_inspector)$' + + - name: Check security fixtures and trusted UTC under sanitizers + env: + ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + run: | + cmake -S . -B build-security-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_SECURITY=ON + cmake --build build-security-sanitized --parallel 2 --target rateguard_tls_compatibility_tests rateguard_trusted_wall_clock_tests rateguard_trusted_wall_clock_independent_tests rateguard_certificate_registry_tests rateguard_certificate_registry_profile_tests rateguard_certificate_registry_independent_tests rateguard_peer_authenticator_tests rateguard_authorization_tests rateguard_peer_authorization_rpc_tests rateguard_client_call_guard_tests rateguard_pinned_client_contract_tests rateguard_pinned_client_rpc_tests + ctest --test-dir build-security-sanitized --output-on-failure -R '^rateguard[.](mtls_compatibility|trusted_wall_clock|trusted_wall_clock_independent|certificate_registry|certificate_registry_profile|certificate_registry_independent|peer_authenticator|authorization|peer_authorization_rpc|client_call_guard|pinned_client_contract|pinned_client_rpc)$' + + - name: Observe pinned SDK TLS session qualification (production cache disabled) + run: | + python3 tools/tests/pinned_client_test_runner.py \ + --binary "$(realpath build/rateguard_pinned_client_rpc_tests)" \ + --fixture tests/fixtures/policy_v1.json \ + --qualify --output build/b3-session-qualification.json + + - name: Observe native trusted UTC source (not deployment acceptance) + run: | + python3 - <<'PY' + import json, pathlib, subprocess + result = subprocess.run(["build/trusted_wall_clock_probe"], text=True, capture_output=True, timeout=10) + data = json.loads(result.stdout) + if result.returncode not in (0, 2) or data.get("trusted") is not (result.returncode == 0): + raise SystemExit("native UTC probe returned an inconsistent result") + record = {"scope": "GitHub hosted Linux only; Docker/target deployment gate remains separate", + "exit_code": result.returncode, "observation": data} + pathlib.Path("build/native-trusted-time.json").write_text(json.dumps(record, indent=2) + "\n") + print(json.dumps(record)) + print("NATIVE_UTC_READY_OBSERVATION" if result.returncode == 0 else "NATIVE_UTC_NOT_READY_DEPLOYMENT_BLOCKED") + PY + + - name: Observe constrained Docker time capabilities (not service deployment) + run: | + python3 tools/probes/docker_time_preflight.py \ + --wall-probe "$(realpath build/trusted_wall_clock_probe)" \ + --clock-probe "$(realpath build/rateguard_clock_linux_smoke)" \ + --image ubuntu:24.04 > build/docker-time-preflight.json + cat build/docker-time-preflight.json | tee -a "$GITHUB_STEP_SUMMARY" + + - name: Capture observed build manifest + run: | + python3 tools/capture_build_manifest.py \ + --source-root . \ + --build-dir build \ + --codegen-tools build/codegen-tools.json \ + --output build/build-manifest.json \ + --build-result passed + cat build/build-manifest.json | tee -a "$GITHUB_STEP_SUMMARY" + + - name: Verify exact observed toolchain against the frozen lock + run: python3 tools/verify_build_manifest.py --lock build-lock.json --manifest build/build-manifest.json + + - name: Preserve the observed build manifest + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: rg001-build-manifest-${{ github.run_id }} + path: | + build/build-manifest.json + build/native-trusted-time.json + build/docker-time-preflight.json + build/b3-session-qualification.json + build/Testing/Temporary/LastTest.log + build-clean/Testing/Temporary/LastTest.log + build-bootstrap-sanitized/Testing/Temporary/LastTest.log + build-manifest-sanitized/Testing/Temporary/LastTest.log + build-runtime-sanitized/Testing/Temporary/LastTest.log + build-supervisor-sanitized/Testing/Temporary/LastTest.log + build-history-sanitized/Testing/Temporary/LastTest.log + build-clock-sanitized/Testing/Temporary/LastTest.log + build-security-sanitized/Testing/Temporary/LastTest.log + if-no-files-found: error + retention-days: 30 + - name: Check durable manifest components under sanitizers env: diff --git a/CMakeLists.txt b/CMakeLists.txt index 0fb7cab..b86f885 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -666,7 +666,10 @@ add_test(NAME rateguard.bootstrap_recovery_reader_independent set_tests_properties(rateguard.bootstrap_recovery_reader rateguard.bootstrap_recovery_reader_independent PROPERTIES TIMEOUT 120) -# Shared canonical epoch artifact grammar. + +# RG-006 layout grammar and optional manifest-store recovery diagnostics. +target_link_libraries(rateguard_bootstrap_recovery_reader PUBLIC rateguard_manifest_codec) + add_executable(rateguard_epoch_artifact_layout_tests tests/supervisor/epoch_artifact_layout_test.cpp) target_link_libraries(rateguard_epoch_artifact_layout_tests PRIVATE rateguard_epoch_gate) @@ -678,7 +681,14 @@ endif() add_test(NAME rateguard.epoch_artifact_layout COMMAND rateguard_epoch_artifact_layout_tests) set_tests_properties(rateguard.epoch_artifact_layout PROPERTIES TIMEOUT 30) - -target_link_libraries(rateguard_bootstrap_recovery_reader PUBLIC rateguard_manifest_codec) +add_executable(rateguard_epoch_artifact_integration_independent_tests + tests/supervisor/epoch_artifact_integration_independent_test.cpp) +target_link_libraries(rateguard_epoch_artifact_integration_independent_tests PRIVATE + rateguard_bootstrap_recovery_reader rateguard_bootstrap_store rateguard_manifest_store + nlohmann_json::nlohmann_json) +target_compile_options(rateguard_epoch_artifact_integration_independent_tests PRIVATE -Wall -Wextra -Werror -pedantic) +add_test(NAME rateguard.epoch_artifact_integration_independent + COMMAND rateguard_epoch_artifact_integration_independent_tests) +set_tests_properties(rateguard.epoch_artifact_integration_independent PROPERTIES TIMEOUT 120) target_link_libraries(rateguard_bootstrap_recovery_reader_tests PRIVATE rateguard_manifest_store) diff --git a/tests/supervisor/epoch_artifact_integration_independent_test.cpp b/tests/supervisor/epoch_artifact_integration_independent_test.cpp new file mode 100644 index 0000000..9ea57e9 --- /dev/null +++ b/tests/supervisor/epoch_artifact_integration_independent_test.cpp @@ -0,0 +1,709 @@ +#include "supervisor/bootstrap_recovery_reader.h" +#include "supervisor/bootstrap_store.h" +#include "supervisor/manifest_store.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace rateguard::supervisor; + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "CHECK failed at %s:%d: %s\n", __FILE__, __LINE__, #condition); \ + std::abort(); \ + } \ +} while (false) + +struct TempRoot { + std::string parent; + std::string root; + TempRoot() { + std::array pattern{}; + const std::string seed = "/tmp/rateguard-recovery-qa-XXXXXX"; + std::copy(seed.begin(), seed.end(), pattern.begin()); + char* made = ::mkdtemp(pattern.data()); + CHECK(made != nullptr); + parent = made; + root = parent + "/runtime"; + } + ~TempRoot() { std::error_code ignored; std::filesystem::remove_all(parent, ignored); } +}; + +BootstrapPlan MakePlan(std::uint8_t epoch_byte = 0x11) { + BootstrapPlan plan; + plan.domain_id.fill(0x10); + plan.epoch_id.fill(epoch_byte); + plan.authority_incarnation.fill(0x22); + plan.policy_digest.fill(0x33); + plan.expected_clock_identity = {}; + plan.expected_clock_identity.boot_uuid.fill(0x44); + plan.expected_clock_identity.namespace_device = 7; + plan.expected_clock_identity.namespace_inode = 9; + plan.expected_clock_identity.monotonic_offset_seconds = 0; + plan.expected_clock_identity.monotonic_offset_nanoseconds = 0; + plan.expected_clock_identity.boottime_offset_seconds = 0; + plan.expected_clock_identity.boottime_offset_nanoseconds = 0; + plan.expected_clock_identity.clock_id = 1; + const auto make = [](ParticipantRole role, std::uint32_t slot, std::string id, + std::uint8_t incarnation, char suffix) { + PlannedParticipant p; + p.role = role; p.slot_id = slot; p.participant_id = std::move(id); + p.incarnation.fill(incarnation); p.container_id = std::string(63, 'a') + suffix; + return p; + }; + plan.participants = { + make(ParticipantRole::Authority, 0, "authority", 0x22, '1'), + make(ParticipantRole::Replica, 77, "replica", 0x55, '2'), + make(ParticipantRole::Adapter, 0, "adapter", 0x66, '3'), + make(ParticipantRole::Witness, 0, "witness", 0x77, '4'), + }; + return plan; +} + +BootstrapPlan MakeLargePlan(std::uint8_t epoch_byte, std::size_t participant_count, + std::uint64_t container_base) { + BootstrapPlan plan = MakePlan(epoch_byte); + plan.participants.clear(); + constexpr char hex[] = "0123456789abcdef"; + auto add = [&](ParticipantRole role, std::uint32_t slot, std::string id, + std::uint8_t incarnation, std::size_t local_index) { + PlannedParticipant p; + p.role = role; + p.slot_id = slot; + p.participant_id = std::move(id); + p.incarnation.fill(incarnation); + p.container_id.assign(64, '0'); + const auto unique = container_base + local_index; + for (std::size_t n = 0; n < 16; ++n) { + const auto shift = static_cast((15 - n) * 4); + p.container_id[48 + n] = hex[(unique >> shift) & 0xfU]; + } + plan.participants.push_back(std::move(p)); + }; + add(ParticipantRole::Authority, 0, "authority", 0x22, 0); + for (std::uint32_t i = 0; i < 8; ++i) + add(ParticipantRole::Replica, i, "replica-" + std::to_string(i), 0x55, 1 + i); + const std::size_t adapter_count = participant_count - 10; + for (std::size_t i = 0; i < adapter_count; ++i) + add(ParticipantRole::Adapter, 0, "adapter-" + std::to_string(i), 0x66, 9 + i); + add(ParticipantRole::Witness, 0, "witness", 0x77, 9 + adapter_count); + CHECK(plan.participants.size() == participant_count); + return plan; +} + +std::string EpochDirectory(const std::string& root, const EpochId& epoch) { + constexpr char digits[] = "0123456789abcdef"; + std::string hex; + for (auto b : epoch) { hex.push_back(digits[b >> 4]); hex.push_back(digits[b & 15]); } + return root + "/epoch-" + hex; +} + +ObservedBootstrapIdentity Observe(const BootstrapPlan& plan, std::size_t index, std::uint64_t pid) { + return ObservedBootstrapIdentity{plan.participants[index], pid, pid + 1000, + plan.expected_clock_identity}; +} + +std::array Digest(const BootstrapInventory& inventory) { + const auto result = BootstrapDigestV1(inventory); + CHECK((std::holds_alternative>(result))); + return std::get>(result); +} + +OperationId Operation(std::uint8_t value) { + OperationId id{}; + id.fill(value); + return id; +} + +EpochCandidate CandidateFor(const BootstrapPlan& plan, std::uint64_t pid_base = 100) { + auto result = BootstrapInventory::Create(plan); + CHECK(std::holds_alternative(result)); + auto inventory = std::get(std::move(result)); + for (std::size_t i = 0; i < plan.participants.size(); ++i) + inventory = inventory.RecordIdentity(Observe(plan, i, pid_base + i)).next; + auto candidate = inventory.ReadyCandidate(); + CHECK(std::holds_alternative(candidate)); + return std::get(std::move(candidate)); +} + +void CreateLayoutWithInventoryAndManifest(const std::string& root, const BootstrapPlan& plan, + std::uint64_t pid_base, std::uint8_t operation_byte) { + auto created = BootstrapInventory::Create(plan); + CHECK(std::holds_alternative(created)); + auto inventory = std::get(std::move(created)); + for (std::size_t i = 0; i < plan.participants.size(); ++i) + inventory = inventory.RecordIdentity(Observe(plan, i, pid_base + i)).next; + auto ready = inventory.ReadyCandidate(); + CHECK(std::holds_alternative(ready)); + auto encoded = EncodeBootstrapInventoryV1(inventory); + CHECK(std::holds_alternative(encoded)); + const auto epoch_dir = EpochDirectory(root, plan.epoch_id); + CHECK(::mkdir(epoch_dir.c_str(), 0700) == 0); + const auto intent = epoch_dir + "/intent.json"; + { + std::ofstream out(intent, std::ios::binary); + const auto& bytes = std::get(encoded); + out.write(bytes.data(), static_cast(bytes.size())); + } + CHECK(::chmod(intent.c_str(), 0600) == 0); + const auto manifest_dir = epoch_dir + "/manifest-store"; + auto operation = Operation(operation_byte); + auto manifest = ManifestStore::CreateNew(manifest_dir, std::get(ready), operation); + CHECK(std::holds_alternative>(manifest)); +} + +std::unique_ptr CreateManifestAt(const std::string& root, + const BootstrapPlan& plan, + ManifestPhase phase = ManifestPhase::Prepared, + bool alter_policy = false, + bool alter_epoch = false, + bool alter_identity = false) { + auto candidate = CandidateFor(plan); + if (alter_policy) candidate.policy_digest[0] ^= 0xff; + if (alter_epoch) candidate.epoch_id[0] ^= 0x80; + if (alter_identity) candidate.participants.front().process.container_id.back() = 'f'; + const auto path = EpochDirectory(root, plan.epoch_id) + "/manifest-store"; + auto result = ManifestStore::CreateNew(path, candidate, Operation(0x81)); + CHECK(std::holds_alternative>(result)); + auto store = std::move(std::get>(result)); + std::uint8_t op = 0x82; + while (store->snapshot().phase != phase) { + const auto current = store->snapshot(); + ManifestPhase next{}; + switch (current.phase) { + case ManifestPhase::Prepared: next = ManifestPhase::Active; break; + case ManifestPhase::Active: next = ManifestPhase::Draining; break; + case ManifestPhase::Draining: next = ManifestPhase::Closed; break; + case ManifestPhase::Closed: CHECK(false); break; + } + const auto updated = store->Transition(current.generation, store->digest(), next, Operation(op++)); + CHECK(updated.visibility == ManifestVisibility::Durable); + CHECK(!updated.error.has_value()); + } + return store; +} + +// Populate one durable bootstrap inventory, then close all fresh-owner handles +// so the reader receives only an OpenExisting recovery-mode RuntimeOwner. +void CreateArtifacts(const std::string& root, const BootstrapPlan& plan, bool complete = false) { + auto owner_result = RuntimeOwner::CreateNew(root, plan.domain_id); + CHECK(std::holds_alternative>(owner_result)); + auto owner = std::move(std::get>(owner_result)); + auto claim_result = owner->ClaimInitialEpoch(plan.epoch_id); + CHECK(std::holds_alternative(claim_result)); + auto store_result = BootstrapStore::CreateNew(std::move(std::get(claim_result)), plan); + CHECK(store_result.ok()); + CHECK(store_result.visibility == BootstrapVisibility::Durable); + auto store = std::move(store_result.store); + if (complete) { + auto snapshot = store->Snapshot(); + for (std::size_t i = 0; i < plan.participants.size(); ++i) { + auto updated = store->RecordIdentity(snapshot->revision(), Digest(*snapshot), Observe(plan, i, 100 + i)); + CHECK(updated.store_error == BootstrapStoreError::None); + CHECK(updated.visibility == BootstrapVisibility::Durable); + snapshot = std::move(updated.snapshot); + } + } + store.reset(); + owner.reset(); +} + +std::unique_ptr OpenRecoveryOwner(const std::string& root, const BootstrapPlan& plan) { + auto opened = RuntimeOwner::OpenExisting(root, plan.domain_id); + CHECK(std::holds_alternative>(opened)); + auto owner = std::move(std::get>(opened)); + CHECK(owner->mode() == RuntimeOwnerMode::RecoveryRequired); + return owner; +} + +std::shared_ptr ReadRecovery(const RuntimeOwner& owner, + IRecoveryReaderIo* hooks = nullptr) { + auto result = BootstrapRecoveryReader::Read(owner, hooks); + CHECK(std::holds_alternative>(result)); + return std::get>(std::move(result)); +} + +bool HasIssue(const std::vector& issues, RecoveryIssueCode code) { + return std::any_of(issues.begin(), issues.end(), [code](const auto& issue) { return issue.code == code; }); +} +bool HasEpochIssue(const RecoveryEpochDiagnostic& epoch, RecoveryIssueCode code) { + return std::find(epoch.issues.begin(), epoch.issues.end(), code) != epoch.issues.end(); +} + +struct FailOne final : IRecoveryReaderIo { + RecoveryReaderIoPoint point; + bool consumed{}; + explicit FailOne(RecoveryReaderIoPoint p) : point(p) {} + bool FailAt(RecoveryReaderIoPoint candidate) noexcept override { + if (!consumed && candidate == point) { consumed = true; return true; } + return false; + } +}; + +struct ActionOnce final : IRecoveryReaderIo { + RecoveryReaderIoPoint point; + bool consumed{}; + std::function action; + ActionOnce(RecoveryReaderIoPoint p, std::function fn) + : point(p), action(std::move(fn)) {} + bool FailAt(RecoveryReaderIoPoint candidate) noexcept override { + if (!consumed && candidate == point) { + consumed = true; + action(); + } + return false; + } +}; + +void TestManifestStoreIsOptionalAndAllPhasesAreDiagnostic() { + { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(!snapshot->epochs.front().manifest_store.has_value()); + } + for (const auto phase : {ManifestPhase::Prepared, ManifestPhase::Active, + ManifestPhase::Draining, ManifestPhase::Closed}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan, phase); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + const auto& epoch = snapshot->epochs.front(); + CHECK(epoch.inventory != nullptr); + CHECK(epoch.manifest_store.has_value()); + CHECK(epoch.manifest_store->decoded_manifest != nullptr); + CHECK(epoch.manifest_store->canonical_digest.has_value()); + CHECK(epoch.manifest_store->decoded_manifest->phase == phase); + CHECK(epoch.manifest_store->decoded_manifest->candidate.epoch_id == plan.epoch_id); + CHECK(epoch.manifest_store->decoded_manifest->candidate.policy_digest == plan.policy_digest); + CHECK(!HasEpochIssue(epoch, RecoveryIssueCode::IdentityCollisionAcrossEpochs)); + // A readable manifest phase is historical data. It does not activate, + // adopt, close, or otherwise authorize the recovery-mode runtime. + (void)manifest_store; + } +} + +void TestValidManifestSurvivesPendingOrInvalidBootstrapIntent() { + for (const int kind : {0, 1, 2}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, kind != 0); + auto manifest_store = CreateManifestAt(temp.root, plan, ManifestPhase::Active); + const auto intent = EpochDirectory(temp.root, plan.epoch_id) + "/intent.json"; + if (kind == 1) { std::ofstream out(intent, std::ios::binary | std::ios::trunc); out << "invalid"; } + if (kind == 2) CHECK(::unlink(intent.c_str()) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete || kind == 0); + CHECK(snapshot->epochs.size() == 1); + const auto& epoch = snapshot->epochs.front(); + CHECK(epoch.manifest_store.has_value()); + CHECK(epoch.manifest_store->decoded_manifest != nullptr); + CHECK(epoch.manifest_store->decoded_manifest->phase == ManifestPhase::Active); + if (kind == 0) { + CHECK(epoch.inventory != nullptr); + CHECK(epoch.inventory->recorded_count() == 0); + CHECK(!HasEpochIssue(epoch, RecoveryIssueCode::ManifestCandidateMismatch)); + CHECK(HasEpochIssue(epoch, RecoveryIssueCode::ManifestBootstrapNotReady)); + } else { + CHECK(epoch.inventory == nullptr); + CHECK(HasEpochIssue(epoch, kind == 1 ? RecoveryIssueCode::InvalidEncoding + : RecoveryIssueCode::MissingIntent)); + } + (void)manifest_store; + } +} + +void TestManifestCandidateMismatchIsReportedButDecodedDataIsKept() { + for (const int field : {0, 1, 2}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan, ManifestPhase::Closed, + field == 0, field == 1, field == 2); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + const auto& epoch = snapshot->epochs.front(); + CHECK(epoch.inventory != nullptr); + CHECK(epoch.manifest_store.has_value()); + CHECK(epoch.manifest_store->decoded_manifest != nullptr); + CHECK(epoch.manifest_store->decoded_manifest->phase == ManifestPhase::Closed); + CHECK(HasEpochIssue(epoch, RecoveryIssueCode::ManifestCandidateMismatch)); + if (field == 0) + CHECK(epoch.manifest_store->decoded_manifest->candidate.policy_digest[0] != plan.policy_digest[0]); + if (field == 1) + CHECK(epoch.manifest_store->decoded_manifest->candidate.epoch_id != plan.epoch_id); + if (field == 2) + CHECK(epoch.manifest_store->decoded_manifest->candidate.participants.front().process.container_id != + plan.participants.front().container_id); + (void)manifest_store; + } +} + +void TestInvalidManifestArtifactsDoNotHideBootstrapInventory() { + for (const int mode : {0, 1, 2, 3, 4}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto dir = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store"; + if (mode == 0) CHECK(::unlink((dir + "/owner.lock").c_str()) == 0); + if (mode == 1) CHECK(::unlink((dir + "/manifest.json").c_str()) == 0); + if (mode == 2) { std::ofstream out(dir + "/manifest.tmp"); out << "pending"; } + if (mode == 3 || mode == 4) CHECK(::unlink((dir + "/manifest.json").c_str()) == 0); + if (mode == 3) CHECK(::symlink("/etc/passwd", (dir + "/manifest.json").c_str()) == 0); + if (mode == 4) CHECK(::mkfifo((dir + "/manifest.json").c_str(), 0600) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + const auto& epoch = snapshot->epochs.front(); + CHECK(epoch.inventory != nullptr); + CHECK(epoch.manifest_store.has_value()); + if (mode == 0 || mode == 2) { + CHECK(epoch.manifest_store->decoded_manifest != nullptr); + if (mode == 2) CHECK(HasEpochIssue(epoch, RecoveryIssueCode::ManifestStoreHasUnexpectedEntry)); + } else { + CHECK(!epoch.manifest_store->decoded_manifest); + } + if (mode == 0 || mode == 1) CHECK(HasEpochIssue(epoch, RecoveryIssueCode::MissingManifestStoreFile)); + if (mode == 3 || mode == 4) CHECK(HasEpochIssue(epoch, RecoveryIssueCode::InvalidManifestStoreFile)); + (void)manifest_store; + } +} + +void TestManifestHardlinkAndModeAreRejected() { + for (const bool use_hardlink : {false, true}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto dir = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store"; + const auto manifest = dir + "/manifest.json"; + if (use_hardlink) CHECK(::link(manifest.c_str(), (dir + "/extra-link").c_str()) == 0); + else CHECK(::chmod(manifest.c_str(), 0644) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(!snapshot->epochs.front().manifest_store->decoded_manifest); + CHECK(HasEpochIssue(snapshot->epochs.front(), use_hardlink + ? RecoveryIssueCode::ManifestStoreHasUnexpectedEntry + : RecoveryIssueCode::InvalidManifestStoreFile)); + (void)manifest_store; + } +} + +void TestNonemptyOwnerLockIsIncompleteButManifestIsRetained() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto lock = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store/owner.lock"; + { std::ofstream out(lock, std::ios::binary | std::ios::trunc); out << "unexpected"; } + CHECK(::chmod(lock.c_str(), 0600) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(snapshot->epochs.front().manifest_store->decoded_manifest != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::InvalidManifestStoreFile)); + (void)manifest_store; +} + +void TestNestedReadHooksFailClosedWithoutLosingBootstrapDiagnostic() { + const std::array points{ + RecoveryReaderIoPoint::OpenManifestStoreDirectory, + RecoveryReaderIoPoint::EnumerateManifestStore, + RecoveryReaderIoPoint::StatManifestStoreEntry, + RecoveryReaderIoPoint::OpenManifestLock, + RecoveryReaderIoPoint::RevalidateManifestLock, + RecoveryReaderIoPoint::OpenManifestFile, + RecoveryReaderIoPoint::ReadManifestFile, + RecoveryReaderIoPoint::RevalidateManifestFile, + RecoveryReaderIoPoint::RevalidateManifestStore, + }; + for (const auto point : points) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + auto owner = OpenRecoveryOwner(temp.root, plan); + FailOne hook(point); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs.front().inventory != nullptr); + (void)manifest_store; + } +} + +void TestNestedListingMutationRetainsDecodedManifestButMarksIncomplete() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto store_dir = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store"; + auto owner = OpenRecoveryOwner(temp.root, plan); + ActionOnce hook(RecoveryReaderIoPoint::EnumerateManifestStore, [&] { + std::ofstream out(store_dir + "/manifest.tmp"); + out << "new temp artifact"; + }); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(snapshot->epochs.front().manifest_store->decoded_manifest != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::ManifestStoreHasUnexpectedEntry) || + HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::ManifestStoreChanged)); + (void)manifest_store; +} + +void TestManifestReplacementDuringFileRevalidationIsNotKnown() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto path = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store/manifest.json"; + auto owner = OpenRecoveryOwner(temp.root, plan); + ActionOnce hook(RecoveryReaderIoPoint::RevalidateManifestFile, [&] { + const auto replacement = path + ".replacement"; + { std::ofstream out(replacement, std::ios::binary | std::ios::trunc); out << "replaced"; } + CHECK(::chmod(replacement.c_str(), 0600) == 0); + CHECK(::rename(replacement.c_str(), path.c_str()) == 0); + }); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(!snapshot->epochs.front().manifest_store->decoded_manifest); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::ManifestStoreFileChanged)); + (void)manifest_store; +} + +void TestReplacementAfterDecodeRetainsHistoricalManifestAsIncomplete() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto path = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store/manifest.json"; + auto owner = OpenRecoveryOwner(temp.root, plan); + ActionOnce hook(RecoveryReaderIoPoint::RevalidateManifestStore, [&] { + const auto replacement = path + ".replacement"; + { std::ofstream out(replacement, std::ios::binary | std::ios::trunc); out << "replaced"; } + CHECK(::chmod(replacement.c_str(), 0600) == 0); + CHECK(::rename(replacement.c_str(), path.c_str()) == 0); + }); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(snapshot->epochs.front().manifest_store->decoded_manifest != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::ManifestStoreChanged)); + (void)manifest_store; +} + +void TestManifestStoreAppearingDuringIntentReadIsReported() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto owner = OpenRecoveryOwner(temp.root, plan); + std::unique_ptr inserted_manifest; + ActionOnce hook(RecoveryReaderIoPoint::ReadIntent, [&] { + inserted_manifest = CreateManifestAt(temp.root, plan, ManifestPhase::Prepared); + }); + auto snapshot = ReadRecovery(*owner, &hook); + CHECK(hook.consumed); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(snapshot->epochs.front().manifest_store->decoded_manifest != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::ManifestStoreChanged)); + (void)inserted_manifest; +} + +void TestManifestStoreSymlinkAndFifoDirectoriesAreRejected() { + for (const bool fifo : {false, true}) { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + manifest_store.reset(); + const auto store_dir = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store"; + std::error_code remove_error; + std::filesystem::remove_all(store_dir, remove_error); + CHECK(!remove_error); + if (fifo) CHECK(::mkfifo(store_dir.c_str(), 0700) == 0); + else CHECK(::symlink("/tmp", store_dir.c_str()) == 0); + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.size() == 1); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::InvalidManifestStoreDirectory)); + } +} + +void TestNestedEntryCapStillReadsAllowlistedFiles() { + TempRoot temp; + const auto plan = MakePlan(); + CreateArtifacts(temp.root, plan, true); + auto manifest_store = CreateManifestAt(temp.root, plan); + const auto store_dir = EpochDirectory(temp.root, plan.epoch_id) + "/manifest-store"; + for (std::size_t i = 0; i < kMaxRecoveryManifestStoreEntries; ++i) { + std::ofstream out(store_dir + "/temporary-" + std::to_string(i)); + out << "x"; + } + auto owner = OpenRecoveryOwner(temp.root, plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(snapshot->epochs.front().manifest_store.has_value()); + CHECK(snapshot->epochs.front().manifest_store->decoded_manifest != nullptr); + CHECK(HasEpochIssue(snapshot->epochs.front(), RecoveryIssueCode::TooManyManifestStoreEntries)); + (void)manifest_store; +} + +void TestBootstrapAndManifestBytesShareAggregateReadBudget() { + TempRoot temp; + const auto first = MakePlan(0x01); + CreateArtifacts(temp.root, first, false); + const auto chunks = kMaxRecoveryAggregateBytes / kMaxManifestBytes; + for (std::size_t i = 0; i < chunks; ++i) { + auto plan = MakePlan(0x02); + plan.epoch_id.fill(0x02); + plan.epoch_id[15] = static_cast(i + 1); + constexpr char hex[] = "0123456789abcdef"; + for (std::size_t j = 0; j < plan.participants.size(); ++j) { + const auto value = 64 + i * plan.participants.size() + j; + plan.participants[j].container_id[plan.participants[j].container_id.size() - 2] = hex[value >> 4]; + plan.participants[j].container_id.back() = hex[value & 0x0f]; + } + auto model = BootstrapInventory::Create(plan); + CHECK(std::holds_alternative(model)); + auto encoded = EncodeBootstrapInventoryV1(std::get(model)); + CHECK(std::holds_alternative(encoded)); + const auto dir = EpochDirectory(temp.root, plan.epoch_id); + CHECK(::mkdir(dir.c_str(), 0700) == 0); + const auto intent = dir + "/intent.json"; + { + std::ofstream out(intent, std::ios::binary); + const auto& bytes = std::get(encoded); + out.write(bytes.data(), static_cast(bytes.size())); + } + CHECK(::chmod(intent.c_str(), 0600) == 0); + const auto store_dir = dir + "/manifest-store"; + CHECK(::mkdir(store_dir.c_str(), 0700) == 0); + const auto lock = store_dir + "/owner.lock"; + { std::ofstream out(lock, std::ios::binary); } + CHECK(::chmod(lock.c_str(), 0600) == 0); + const auto manifest = store_dir + "/manifest.json"; + { std::ofstream out(manifest, std::ios::binary); out.put('{'); } + CHECK(::chmod(manifest.c_str(), 0600) == 0); + std::filesystem::resize_file(manifest, kMaxManifestBytes); + } + auto owner = OpenRecoveryOwner(temp.root, first); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(!snapshot->epochs.empty()); + CHECK(snapshot->epochs.front().inventory != nullptr); + CHECK(HasIssue(snapshot->issues, RecoveryIssueCode::AggregateByteLimit)); + for (const auto& epoch : snapshot->epochs) { + if (epoch.inventory) CHECK(epoch.canonical_digest.has_value()); + if (epoch.manifest_store && epoch.manifest_store->decoded_manifest) + CHECK(epoch.manifest_store->canonical_digest.has_value()); + } +} + +void TestBootstrapAndManifestRecordsShareAggregateParticipantBudget() { + TempRoot temp; + const auto first_plan = MakeLargePlan(0x10, 256, 0x100000); + { + auto created = RuntimeOwner::CreateNew(temp.root, first_plan.domain_id); + CHECK(std::holds_alternative>(created)); + auto owner = std::move(std::get>(created)); + auto claim = owner->ClaimInitialEpoch(first_plan.epoch_id); + CHECK(std::holds_alternative(claim)); + } + + constexpr std::size_t paired_epochs = kMaxRecoveryAggregateParticipants / (2 * 256); + static_assert(paired_epochs == 32); + for (std::size_t i = 0; i < paired_epochs; ++i) { + const auto epoch_byte = static_cast(0x10 + i); + auto plan = MakeLargePlan(epoch_byte, 256, 0x100000 + i * 1000); + CreateLayoutWithInventoryAndManifest(temp.root, plan, + 10'000'000 + i * 1000, epoch_byte); + } + // A final valid bootstrap history adds participant records beyond the shared + // cap. Its inventory must not be presented as retained if the conservative + // count check stops before retention. + const auto overflow_plan = MakeLargePlan(0x40, 11, 0x200000); + CreateLayoutWithInventoryAndManifest(temp.root, overflow_plan, 20'000'000, 0x40); + + auto owner = OpenRecoveryOwner(temp.root, first_plan); + auto snapshot = ReadRecovery(*owner); + CHECK(!snapshot->scan_complete); + CHECK(HasIssue(snapshot->issues, RecoveryIssueCode::AggregateParticipantLimit)); + std::size_t retained_records = 0; + std::size_t retained_manifest_participants = 0; + for (const auto& epoch : snapshot->epochs) { + if (epoch.inventory) retained_records += epoch.inventory->records().size(); + if (epoch.manifest_store && epoch.manifest_store->decoded_manifest) + retained_manifest_participants += epoch.manifest_store->decoded_manifest->candidate.participants.size(); + } + CHECK(retained_records + retained_manifest_participants == kMaxRecoveryAggregateParticipants); + CHECK(snapshot->epochs.size() == paired_epochs + 1); + CHECK(snapshot->epochs.back().inventory == nullptr); + CHECK(snapshot->epochs.back().manifest_store == std::nullopt); +} + +} // namespace + +int main() { + TestManifestStoreIsOptionalAndAllPhasesAreDiagnostic(); + TestValidManifestSurvivesPendingOrInvalidBootstrapIntent(); + TestManifestCandidateMismatchIsReportedButDecodedDataIsKept(); + TestInvalidManifestArtifactsDoNotHideBootstrapInventory(); + TestManifestHardlinkAndModeAreRejected(); + TestNonemptyOwnerLockIsIncompleteButManifestIsRetained(); + TestNestedReadHooksFailClosedWithoutLosingBootstrapDiagnostic(); + TestNestedListingMutationRetainsDecodedManifestButMarksIncomplete(); + TestManifestReplacementDuringFileRevalidationIsNotKnown(); + TestReplacementAfterDecodeRetainsHistoricalManifestAsIncomplete(); + TestManifestStoreAppearingDuringIntentReadIsReported(); + TestManifestStoreSymlinkAndFifoDirectoriesAreRejected(); + TestNestedEntryCapStillReadsAllowlistedFiles(); + TestBootstrapAndManifestBytesShareAggregateReadBudget(); + TestBootstrapAndManifestRecordsShareAggregateParticipantBudget(); + return 0; +} From a3c4d7e7a95dc4b8c7570db671ebd1edb77fc82d Mon Sep 17 00:00:00 2001 From: Kshiteesh R Bharadwaj <100955403+kshiteesh28@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:02:23 -0600 Subject: [PATCH 6/8] ci: preserve the sanitizer selector shell quoting --- .github/workflows/contract-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/contract-build.yml b/.github/workflows/contract-build.yml index c447275..94b7853 100644 --- a/.github/workflows/contract-build.yml +++ b/.github/workflows/contract-build.yml @@ -88,7 +88,7 @@ jobs: run: | cmake -S . -B build-bootstrap-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_BOOTSTRAP=ON -DRATEGUARD_SANITIZE_RUNTIME=ON -DRATEGUARD_SANITIZE_MANIFEST=ON cmake --build build-bootstrap-sanitized --parallel 2 --target rateguard_bootstrap_inventory_tests rateguard_bootstrap_inventory_independent_tests rateguard_bootstrap_store_tests rateguard_bootstrap_store_independent_tests rateguard_bootstrap_recovery_reader_tests rateguard_bootstrap_recovery_reader_independent_tests rateguard_epoch_artifact_layout_tests rateguard_epoch_artifact_integration_independent_tests - ctest --test-dir build-bootstrap-sanitized --output-on-failure -R '^rateguard[.](bootstrap_(inventory|store|recovery_reader)(_independent)?|epoch_artifact_(layout|integration_independent)) + ctest --test-dir build-bootstrap-sanitized --output-on-failure -R '^rateguard[.](bootstrap_(inventory|store|recovery_reader)(_independent)?|epoch_artifact_(layout|integration_independent))$' - name: Check durable manifest components under sanitizers env: From 7fc9895e5f928ad1576d5b2119b79f4a717151e9 Mon Sep 17 00:00:00 2001 From: Kshiteesh R Bharadwaj <100955403+kshiteesh28@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:20:03 -0600 Subject: [PATCH 7/8] ci: restore single contract workflow and attempt-scoped artifact --- .github/workflows/contract-build.yml | 121 +-------------------------- 1 file changed, 1 insertion(+), 120 deletions(-) diff --git a/.github/workflows/contract-build.yml b/.github/workflows/contract-build.yml index 94b7853..aa3910c 100644 --- a/.github/workflows/contract-build.yml +++ b/.github/workflows/contract-build.yml @@ -190,126 +190,7 @@ jobs: - name: Preserve the observed build manifest uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: - name: rg001-build-manifest-${{ github.run_id }} - path: | - build/build-manifest.json - build/native-trusted-time.json - build/docker-time-preflight.json - build/b3-session-qualification.json - build/Testing/Temporary/LastTest.log - build-clean/Testing/Temporary/LastTest.log - build-bootstrap-sanitized/Testing/Temporary/LastTest.log - build-manifest-sanitized/Testing/Temporary/LastTest.log - build-runtime-sanitized/Testing/Temporary/LastTest.log - build-supervisor-sanitized/Testing/Temporary/LastTest.log - build-history-sanitized/Testing/Temporary/LastTest.log - build-clock-sanitized/Testing/Temporary/LastTest.log - build-security-sanitized/Testing/Temporary/LastTest.log - if-no-files-found: error - retention-days: 30 - - - - name: Check durable manifest components under sanitizers - env: - ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 - UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 - run: | - cmake -S . -B build-manifest-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_MANIFEST=ON - cmake --build build-manifest-sanitized --parallel 2 --target rateguard_manifest_codec_tests rateguard_manifest_store_tests rateguard_manifest_store_independent_tests - ctest --test-dir build-manifest-sanitized --output-on-failure -R '^rateguard[.]manifest_(codec|store|store_independent)$' - - - name: Check configured runtime ownership under sanitizers - env: - ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 - UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 - run: | - cmake -S . -B build-runtime-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_RUNTIME=ON - cmake --build build-runtime-sanitized --parallel 2 --target rateguard_runtime_owner_tests rateguard_runtime_owner_independent_tests - ctest --test-dir build-runtime-sanitized --output-on-failure -R '^rateguard[.]runtime_owner(_independent)?$' - - - name: Check local supervisor lifecycle under sanitizers - env: - ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 - UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 - run: | - cmake -S . -B build-supervisor-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_SUPERVISOR=ON - cmake --build build-supervisor-sanitized --parallel 2 --target rateguard_epoch_gate_tests rateguard_epoch_gate_independent_tests - ctest --test-dir build-supervisor-sanitized --output-on-failure -R '^rateguard[.]epoch_gate(_independent)?$' - - - name: Check clock and test fixtures under address/undefined sanitizers - env: - ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 - UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 - run: | - cmake -S . -B build-clock-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_CLOCK=ON - cmake --build build-clock-sanitized --parallel 2 --target rateguard_clock_tests rateguard_clock_independent_tests rateguard_clock_linux_smoke - ctest --test-dir build-clock-sanitized --output-on-failure -R '^rateguard[.]clock($|_independent$|_linux$)' - - - name: Check history components under sanitizers - env: - ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 - UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 - run: | - cmake -S . -B build-history-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_HISTORY=ON - cmake --build build-history-sanitized --parallel 2 --target rateguard_history_inspect rateguard_event_recorder_tests rateguard_history_export_tests rateguard_history_validator_tests rateguard_history_reader_tests rateguard_aggregate_metrics_tests rateguard_history_file_publisher_tests rateguard_strict_reconciliation_tests - ctest --test-dir build-history-sanitized --output-on-failure -R '^rateguard[.](event_recorder|history_export|history_validator|history_reader|aggregate_metrics|history_file_publisher|strict_reconciliation|history_inspector)$' - - - name: Check security fixtures and trusted UTC under sanitizers - env: - ASAN_OPTIONS: detect_leaks=1:strict_string_checks=1 - UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 - run: | - cmake -S . -B build-security-sanitized -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DRATEGUARD_FETCH_GRPC=OFF -DRATEGUARD_REQUIRE_PRODUCT_CONTRACTS=ON -DRATEGUARD_SANITIZE_SECURITY=ON - cmake --build build-security-sanitized --parallel 2 --target rateguard_tls_compatibility_tests rateguard_trusted_wall_clock_tests rateguard_trusted_wall_clock_independent_tests rateguard_certificate_registry_tests rateguard_certificate_registry_profile_tests rateguard_certificate_registry_independent_tests rateguard_peer_authenticator_tests rateguard_authorization_tests rateguard_peer_authorization_rpc_tests rateguard_client_call_guard_tests rateguard_pinned_client_contract_tests rateguard_pinned_client_rpc_tests - ctest --test-dir build-security-sanitized --output-on-failure -R '^rateguard[.](mtls_compatibility|trusted_wall_clock|trusted_wall_clock_independent|certificate_registry|certificate_registry_profile|certificate_registry_independent|peer_authenticator|authorization|peer_authorization_rpc|client_call_guard|pinned_client_contract|pinned_client_rpc)$' - - - name: Observe pinned SDK TLS session qualification (production cache disabled) - run: | - python3 tools/tests/pinned_client_test_runner.py \ - --binary "$(realpath build/rateguard_pinned_client_rpc_tests)" \ - --fixture tests/fixtures/policy_v1.json \ - --qualify --output build/b3-session-qualification.json - - - name: Observe native trusted UTC source (not deployment acceptance) - run: | - python3 - <<'PY' - import json, pathlib, subprocess - result = subprocess.run(["build/trusted_wall_clock_probe"], text=True, capture_output=True, timeout=10) - data = json.loads(result.stdout) - if result.returncode not in (0, 2) or data.get("trusted") is not (result.returncode == 0): - raise SystemExit("native UTC probe returned an inconsistent result") - record = {"scope": "GitHub hosted Linux only; Docker/target deployment gate remains separate", - "exit_code": result.returncode, "observation": data} - pathlib.Path("build/native-trusted-time.json").write_text(json.dumps(record, indent=2) + "\n") - print(json.dumps(record)) - print("NATIVE_UTC_READY_OBSERVATION" if result.returncode == 0 else "NATIVE_UTC_NOT_READY_DEPLOYMENT_BLOCKED") - PY - - - name: Observe constrained Docker time capabilities (not service deployment) - run: | - python3 tools/probes/docker_time_preflight.py \ - --wall-probe "$(realpath build/trusted_wall_clock_probe)" \ - --clock-probe "$(realpath build/rateguard_clock_linux_smoke)" \ - --image ubuntu:24.04 > build/docker-time-preflight.json - cat build/docker-time-preflight.json | tee -a "$GITHUB_STEP_SUMMARY" - - - name: Capture observed build manifest - run: | - python3 tools/capture_build_manifest.py \ - --source-root . \ - --build-dir build \ - --codegen-tools build/codegen-tools.json \ - --output build/build-manifest.json \ - --build-result passed - cat build/build-manifest.json | tee -a "$GITHUB_STEP_SUMMARY" - - - name: Verify exact observed toolchain against the frozen lock - run: python3 tools/verify_build_manifest.py --lock build-lock.json --manifest build/build-manifest.json - - - name: Preserve the observed build manifest - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 - with: - name: rg001-build-manifest-${{ github.run_id }} + name: rg001-build-manifest-${{ github.run_id }}-${{ github.run_attempt }} path: | build/build-manifest.json build/native-trusted-time.json From c8d2c88886539f8eaec294bc781a27a05ed17a98 Mon Sep 17 00:00:00 2001 From: Kshiteesh R Bharadwaj <100955403+kshiteesh28@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:35:49 -0600 Subject: [PATCH 8/8] docs: record verified artifact layout and per-agent review evidence --- README.md | 8 +-- docs/LLD.md | 66 +++++++++++++----- docs/SCRUM-WORK-LOG.md | 20 ++++++ docs/SPRINT-PLAN.md | 8 ++- docs/STORIES.md | 36 +++++----- docs/context-blocks.json | 80 +++++++++++++++------- docs/contracts/bootstrap-recovery-v1.md | 2 + docs/contracts/epoch-artifact-layout-v1.md | 2 +- docs/evidence/RG-006-E.md | 4 ++ docs/evidence/RG-006-F.md | 41 +++++++++++ 10 files changed, 199 insertions(+), 68 deletions(-) create mode 100644 docs/evidence/RG-006-F.md diff --git a/README.md b/README.md index c75606e..3991d4b 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,8 @@ Read in this order: 1. [PRD revision 8](docs/PRD.md) — product goals and release gates. 2. [SRD revision 5](docs/SRD.md) — normative behavior and test obligations. -3. [HLD revision 4](docs/HLD.md) — proposed process and deployment architecture. -4. [LLD revision 5](docs/LLD.md) — proposed interfaces, state transitions, classes, and implementation order. +3. [HLD revision 5](docs/HLD.md) — proposed process and deployment architecture. +4. [LLD revision 9](docs/LLD.md) — proposed interfaces, state transitions, classes, and implementation order. 5. [Implementation stories](docs/STORIES.md) and [JSON context blocks](docs/context-blocks.json) — planned work and acceptance evidence. 6. [Agile sprint plan](docs/SPRINT-PLAN.md) — minute-based effort estimates, sequence, roles, and acceptance gates. @@ -25,9 +25,9 @@ Live policy changes (PRD-013) and long-operation permits (PRD-014) are deferred. ## Status and implementation notes -RG-001 contracts/build ([PR #5](https://github.com/kshiteesh28/DistributedRateGuard/pull/5)) and RG-002 immutable policy/checked arithmetic ([PR #6](https://github.com/kshiteesh28/DistributedRateGuard/pull/6)) have passing component evidence and await review; neither is merged to main. RG-003 clock component ([PR #8](https://github.com/kshiteesh28/DistributedRateGuard/pull/8)) passed Linux/sanitizer checks; full service/checker integration remains pending. Read the [live per-agent scrum log](https://github.com/kshiteesh28/DistributedRateGuard/blob/docs/scrum-work-log/docs/SCRUM-WORK-LOG.md), [build instructions](docs/build.md), [RG-001 evidence](docs/evidence/RG-001.md), and [RG-002 evidence](docs/evidence/RG-002.md) for scope and observed results. Quota enforcement, release benchmarks, and model checking are not implemented or claimed. All product thresholds remain goals. +Component implementations are integrated on `feature/distributed-rateguard`: wire/build contracts, immutable policy and fixed-point arithmetic, clock provenance, security/client guards, bounded history and inspection, local lifecycle, durable manifests/intents, runtime ownership and recovery-artifact diagnostics. Read the [per-agent scrum log](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/SCRUM-WORK-LOG.md), [build instructions](docs/build.md) and [component evidence](docs/evidence/RG-006-F.md). The [final PR to main](https://github.com/kshiteesh28/DistributedRateGuard/pull/13) remains unmerged. Live quota/forwarding services, real process control and witness integration, release benchmarks and model checking remain pending. All product thresholds remain goals. -The source of truth is the current `main` branch. The local path hint in the context file currently contains documentation only and is not a verified Git checkout. Use the relevant review branch for implementation; dependent PRs may stack on a verified feature branch. The primary Ubuntu package lock is based on observed CI. Actual Docker target/image-digest evidence remains open; hosted component tests do not satisfy that deployment gate. Keep enforcement services fail-closed until shared-clock provenance, witness durability, process fencing, and identity fixtures pass. +PRD 8 and SRD 5 on `main` remain the product/behavior contracts; current HLD/LLD and implementation evidence are on `feature/distributed-rateguard` until final promotion. The local path hint in the context file currently contains documentation only and is not a verified Git checkout. Use the relevant review branch for implementation; dependent PRs may stack on a verified feature branch. The primary Ubuntu package lock is based on observed CI. Actual Docker target/image-digest evidence remains open; hosted component tests do not satisfy that deployment gate. Keep enforcement services fail-closed until shared-clock provenance, witness durability, process fencing, and identity fixtures pass. ## Research foundation diff --git a/docs/LLD.md b/docs/LLD.md index 612cc38..1702f8e 100644 --- a/docs/LLD.md +++ b/docs/LLD.md @@ -1,16 +1,18 @@ # DistributedRateGuard — Low-Level Design -**Revision:** 8 · **Date:** 2026-11-23 · **Status:** Proposed design; RG-006 reader component present, full recovery orchestration/controller pending -**Current source branch:** `feature/distributed-rateguard`; reader review on `feature/RG-006-bootstrap-recovery` +**Revision:** 9 · **Date:** 2026-11-24 UTC · **Status:** Proposed design; artifact-layout and manifest-reader components implemented; full recovery orchestration/controller pending, verification tracked separately +**Current source branch:** `feature/distributed-rateguard`; layout contract on `feature/RG-006-epoch-artifact-layout` **Binding sources:** [PRD revision 8](PRD.md), [SRD revision 5](SRD.md) **Architecture input:** [proposed HLD revision 5](HLD.md), delivered with this LLD. +**Revision input:** LLD revision 8 from `feature/distributed-rateguard` (blob `612cc386547f81cc83612fd548d276510f1e36d5`). +**Selected contract input:** `docs/contracts/epoch-artifact-layout-v1.md` from `feature/RG-006-epoch-artifact-layout` (blob `9e262317fd7ea029b48723805bf7b063d1bb78c5`). **Input blob identities before principal review (historical):** PRD `04456d95ed2474700198361db2314c50a73cb300`; SRD `dd82770809e1a56900336070404360c33b3b08a2`; HLD `fb835c70b4d53f1f4bf980dde1f0cd3065212cf3`. ## 1. Scope and implementation status This LLD serves implementers and reviewers of a tenant admission service. A delivers strict quota decisions, B delivers deterministic replay and evaluation, and C delivers fixed-Q credits and independent model/history validation. PRD-013 live policy changes and PRD-014 long-operation permits remain deferred. Multi-host operation, transparent failover, automatic credit reclamation, and continuous cross-epoch quota guarantees are excluded. -The implementation feature now contains component code for RuntimeOwner, InitialEpochClaim, BootstrapInventory, BootstrapStore, and BootstrapRecoveryReader; their boundaries are listed in §17.1 and §21. The Docker process controller, participant activation, complete supervisor lifecycle, and successor-epoch recovery remain integration work. PRD/SRD are binding; SRD §8 explicitly supersedes historical open decisions. The HLD's in-memory authority is a proposal conditional on integrity/fencing decisions. This LLD distinguishes component code from integration and does not claim CI acceptance, release acceptance, benchmark results, production deployment, or complete fencing. +The implementation feature contains component code for RuntimeOwner, InitialEpochClaim, BootstrapInventory, BootstrapStore, BootstrapRecoveryReader, and the pure epoch-artifact layout helper; their boundaries are listed in §17.1 and §21. The Docker process controller, participant activation, complete supervisor lifecycle, and successor-epoch recovery remain integration work. PRD/SRD are binding; SRD §8 explicitly supersedes historical open decisions. The HLD's in-memory authority is a proposal conditional on integrity/fencing decisions. This LLD distinguishes component code from integration and does not claim CI acceptance, release acceptance, benchmark results, production deployment, or complete fencing. ## 2. Modules and dependency graph @@ -29,7 +31,8 @@ Public means a process boundary; internal means a C++ library boundary. Rows lab | `src/supervisor/runtime_owner.h/.cpp` | Internal; POSIX filesystem and lock ownership | One configured runtime-root owner, anchor/lock identity, fresh/recovery mode, one-use initial claim; implemented component | | `src/supervisor/bootstrap_inventory.h/.cpp` | Internal immutable value model and canonical codec | Fixed planned roster, observed process identities, monotonic revision and recovery latch; implemented component | | `src/supervisor/bootstrap_store.h/.cpp` | Internal; RuntimeOwner claim, BootstrapInventory, POSIX durable file operations | Initial epoch intent creation, revision/digest CAS, last durable snapshot and candidate data handoff; implemented component | -| `src/supervisor/bootstrap_recovery_reader.h/.cpp` | Internal read-only diagnostic scan; recovery-mode RuntimeOwner and BootstrapInventory decoder | Bounded scan of recorded epoch intents, including pending process identities; returns diagnostic evidence only, not a serving/adoption/fencing capability; component code present, orchestration pending | +| `src/supervisor/epoch_artifact_layout.h` | Pure internal path/name utility; no filesystem access or state | Shared epoch artifact names and checked epoch-directory parse/format; no ownership or fencing capability | +| `src/supervisor/bootstrap_recovery_reader.h/.cpp` | Internal read-only diagnostic scan; recovery-mode RuntimeOwner, BootstrapInventory and ManifestCodec | Bounded scan contract covers recorded intents and optional manifest-store artifacts, including pending identities; bootstrap/optional-manifest reader component code is present; full orchestration pending | | `src/supervisor/epoch_gate.h` | Internal lifecycle gate and `IProcessController` interface | Fixed single-epoch candidate, commit leases, stop/inspect boundary and local phase; component-verified, not durable successor authorization | | `src/supervisor/manifest_store.h/.cpp` | Internal POSIX manifest store | Prepared/Active/Draining/Closed manifest snapshots and recovery-only existing open; component-verified, not launch or exit proof | | `adapter/` | Public sample API; admission client | Forwarding attempt state; FR-006 | @@ -474,7 +477,7 @@ Signatures are contract sketches; strong domain types and cancellation/deadline | InitialEpochClaim / src/supervisor/runtime_owner.h (implemented component) | Move-only one-use capability retaining the RuntimeOwner lock state | Supplies validated domain/epoch ownership and a duplicated root descriptor; proves neither process launch nor fencing | | BootstrapInventory / src/supervisor/bootstrap_inventory.h + bootstrap_inventory.cpp (implemented component) | Immutable planned roster, observations, canonical digest inputs, revision and recovery state | Create, RecordIdentity, RequireRecovery, ReadyCandidate; exact replay is idempotent, identity mismatch irreversibly requires recovery | | BootstrapStore / src/supervisor/bootstrap_store.h + bootstrap_store.cpp (implemented component) | InitialEpochClaim plus durable per-epoch intent file and last committed snapshot | CreateNew, RecordIdentity(revision,digest CAS), ReadyCandidate; distinguishes NotVisible, Durable and VisibleDurabilityUnknown; uncertainty blocks further writes | -| BootstrapRecoveryReader / src/supervisor/bootstrap_recovery_reader.h + bootstrap_recovery_reader.cpp (component code present) | Read-only bounded scan; recovery-mode RuntimeOwner and BootstrapInventory decoder | `Read(owner,test_io) → variant, RecoveryReaderFatal>`; returns diagnostic inventories/issues only, including planned participants without process identity; no claim, candidate, store, stop proof or fencing capability | +| BootstrapRecoveryReader / src/supervisor/bootstrap_recovery_reader.h + bootstrap_recovery_reader.cpp (component code present) | Read-only bounded scan; recovery-mode RuntimeOwner, bootstrap decoder, and manifest codec | `Read(owner,test_io) → variant, RecoveryReaderFatal>`; returns diagnostic inventories/manifests/issues, including pending process identities; no claim, candidate, store, stop proof or fencing capability | | TenantLedger / src/authority/tenant_ledger.h | Mutex, immutable identity, bucket, fixed grant-result array, version, reservation state | BeginReservation→Result; ReadSnapshot; no public balance setter | | TenantReservation / src/authority/tenant_reservation.h | Move-only reservation token, original version/snapshot, phase | ValidateSnapshot, CommitCandidate, CompleteAck, Fail; only this token can change the reserved tenant | | BucketMath / src/authority/bucket_math.h | Stateless production arithmetic | Refill, Decide, RetryDelay; checked 128-bit D3 arithmetic, never accesses clock or global state | @@ -493,7 +496,7 @@ Signatures are contract sketches; strong domain types and cancellation/deadline | AuthorityService / src/authority/authority_service.h | Internal gRPC facade; refs auth and AuthorityEngine | StrictCheck and AcquireCredit RPCs; only registered replica identity can call | | ForwardAttempt / adapter/forward_attempt.h | Attempt ID, deadline, atomic Pending/ForwardStarted/Expired/Failed | TryForwardTransition; exactly one CAS winner; does not retry backend automatically | | SampleAdapter / adapter/sample_adapter.h | Trusted fixture mapping and bounded active ForwardAttempt objects | Handle; derive authorized context, call admission, enforce receipt/epoch/deadline, never replay after crash | -| ManifestStore / src/supervisor/manifest_store.h/.cpp (component-verified) | Supervisor-owned directory/lock fd; immutable validated manifest snapshots | CreateNew, OpenExisting, snapshot, digest, Transition; existing opens are recovery-only; fsync/rename/directory-fsync uncertainty blocks writes; no anti-rollback claim from rename | +| ManifestStore / src/supervisor/manifest_store.h/.cpp (component-verified) | Caller-supplied directory/lock fd; immutable validated manifest snapshots | CreateNew, OpenExisting, snapshot, digest, Transition; existing opens are recovery-only; caller must compose the exact `/epoch-/manifest-store` path under validated global ownership; layout strings do not grant path authority; fsync/rename/directory-fsync uncertainty blocks writes; no anti-rollback claim from rename | | EpochSupervisor / src/supervisor/epoch_supervisor.h | Exclusive control thread, inventory/operation state, WitnessStateMachine, JournalWriter | StartEpoch, Drain, FenceAndClose, RecoverAfterCrash; never adopts old ACTIVE epoch | | EventRecorder / src/events/event_recorder.h | Fixed run-wide budget, producer sequences and reserved slots | Reserve→Result, Publish, SealIncomplete; no identifiers as metric labels | | HistoryExporter / src/events/history_exporter.h | Bounded streaming file writer | Export with count/hash/complete markers; cleanup follows D7; missing producer seal yields incomplete | @@ -528,18 +531,35 @@ classDiagram +issues +issues_truncated } + class RecoveryEpochDiagnostic { + +directory_name + +intent_identity + +canonical_digests + +issues + +issues_truncated + } class BootstrapInventory { +records() +recovery_required() } + class ManifestV1 { + +candidate + +phase + +generation + } BootstrapRecoveryReader ..> RuntimeOwner : validates mode and duplicates root - BootstrapRecoveryReader ..> BootstrapInventory : bounded decode only + BootstrapRecoveryReader ..> BootstrapInventory : bounded intent decode + BootstrapRecoveryReader ..> ManifestV1 : bounded manifest decode BootstrapRecoveryReader --> BootstrapRecoverySnapshot : diagnostic result - BootstrapRecoverySnapshot o-- BootstrapInventory : safely decoded epochs + BootstrapRecoverySnapshot o-- RecoveryEpochDiagnostic : per-epoch results + RecoveryEpochDiagnostic o-- BootstrapInventory : optional intent model + RecoveryEpochDiagnostic o-- ManifestV1 : optional manifest model BootstrapStore *-- InitialEpochClaim : consumes and retains lock capability BootstrapStore ..> BootstrapInventory : durable initial writes ``` +The shared `epoch_layout_v1` helper is a pure header utility, not a service or capability. It defines the literal names `epoch-`, `intent.json`, `intent.tmp`, `manifest-store`, `owner.lock`, `manifest.json`, and `manifest.tmp`, plus checked `ParseEpochDirectoryName` / `FormatEpochDirectoryName` functions. Parsing accepts only the exact `epoch-<32 lowercase hexadecimal digits>` form for a nonzero ID; formatting rejects a zero ID and reports allocation failure. BootstrapStore, BootstrapRecoveryReader, and ManifestStore reuse these names. The helper performs no filesystem checks and cannot grant path ownership. + ### 17.2 Construction, lifetime and threading ServiceRuntime owns instances in dependency order: validated policy/trust/clock → gate/recorder → ledger/witness/client → engines/services → servers. Stop reverses admission: reject new RPCs, mark DRAINING, wake CV waiters, cancel bounded transport waits, join workers, seal/export available histories, destroy services, then dependencies. A crash bypassing graceful shutdown triggers incomplete evidence and supervisor fencing. No detached task may retain raw pointers to destroyed services; pending operations hold owned request buffers and validated snapshot shared_ptrs. @@ -589,7 +609,7 @@ Class-level seam acceptance: substitute IClock, IAuthorityClient, IStateWitness ### 17.4 Per-process composition -The intended SupervisorRuntime composition is RuntimeOwner, BootstrapStore, BootstrapRecoveryReader, ManifestStore, EpochGate, DockerProcessController, EpochSupervisor, WitnessServer, WitnessStateMachine and JournalWriter. RuntimeOwner, InitialEpochClaim, BootstrapInventory, BootstrapStore and BootstrapRecoveryReader are the RG-006 components described in §21; EpochGate and ManifestStore are previously component-verified. `IProcessController` is currently an interface declared in `epoch_gate.h` with stop-request and inspection operations; no concrete Docker controller or durable process-launch/exit acknowledgment path is implemented. The component reader is implemented; full recovery orchestration/controller, participant activation and successor-epoch recovery remain pending. AuthorityRuntime owns TenantLedgers, AuthorityEngine/AuthorityService and LocalStateWitnessClient; it never shares a pointer to supervisor witness memory. ReplicaRuntime owns AdmissionService, CreditManager and GrpcAuthorityClient. AdapterRuntime owns SampleAdapter and its gRPC admission client. Evaluation tools own independent ReplayModel/HistoryChecker. ServiceRuntime is a per-process construction pattern, not one address space for all components. All cross-process transitions use the explicit authenticated ports. +The intended SupervisorRuntime composition is RuntimeOwner, BootstrapStore, BootstrapRecoveryReader, ManifestStore, EpochGate, DockerProcessController, EpochSupervisor, WitnessServer, WitnessStateMachine and JournalWriter. RuntimeOwner, InitialEpochClaim, BootstrapInventory, BootstrapStore and BootstrapRecoveryReader are the RG-006 components described in §21; EpochGate and ManifestStore are previously component-verified. `IProcessController` is currently an interface declared in `epoch_gate.h` with stop-request and inspection operations; no concrete Docker controller or durable process-launch/exit acknowledgment path is implemented. The bootstrap and optional-manifest reader components are implemented; full recovery orchestration/controller, participant activation and successor-epoch recovery remain pending. AuthorityRuntime owns TenantLedgers, AuthorityEngine/AuthorityService and LocalStateWitnessClient; it never shares a pointer to supervisor witness memory. ReplicaRuntime owns AdmissionService, CreditManager and GrpcAuthorityClient. AdapterRuntime owns SampleAdapter and its gRPC admission client. Evaluation tools own independent ReplayModel/HistoryChecker. ServiceRuntime is a per-process construction pattern, not one address space for all components. All cross-process transitions use the explicit authenticated ports. Witness Validate pre-reserves a bounded journal queue slot and maximum record byte budget before returning permission to prepare a transition; no automatic eviction/lease expiry can remove it while the authority may commit. It is released only on explicit precommit abort, committed acknowledgment, or fenced epoch shutdown. This prevents postcommit capacity rejection from becoming an unrecorded ordinary overload. Duplicate Validate with identical transaction identity returns its existing reservation. Only crashes/I/O/integrity failures can invalidate a postcommit reservation, and those follow DRAINING/uncertainty rules. @@ -648,7 +668,7 @@ sequenceDiagram Runtime ownership is global across epoch directories within the deployment's one trusted configured root. Different configured roots require deployment-level reconciliation before serving; changing that root while an old epoch may act cannot bypass fencing. A fresh ownership claim alone supplies no launch or durability proof. Bootstrap models supply no actual OS observation, authenticated control-channel or persistence guarantee. Those guarantees require the corresponding controller, durable store and participant integration tests. -## 21. RG-006 implementation boundary — revision 8 +## 21. RG-006 implementation boundary — revision 9 These components support PRD-007, PRD-024 and PRD-025 / FR-001, FR-007, FR-008 and FR-022. Component fixtures exercise ownership, intent and identity persistence; the end-to-end restart, state-integrity and fencing evidence in AT-08, AT-09 and AT-28 remains pending. @@ -666,15 +686,17 @@ A create operation that succeeds in the container runtime while persisting its r ### 21.1 BootstrapRecoveryReader v1 component contract -The reader contract is specified in [Bootstrap recovery reader v1](contracts/bootstrap-recovery-v1.md), based on PRD 8, SRD 5, HLD 5 A-03 and LLD 7 §21. The component reader is implemented; full recovery orchestration/controller remains pending. This LLD revision does not claim CI acceptance for the reader. +The [bootstrap-only base contract](contracts/bootstrap-recovery-v1.md) is extended by [Epoch artifact layout v1](contracts/epoch-artifact-layout-v1.md) for optional manifest-store validation. Sources are PRD 8, SRD 5 and HLD 5 A-03. The bootstrap and optional-manifest reader components are implemented; full recovery orchestration/controller remains pending. Verification evidence is tracked separately, and this document makes no end-to-end recovery or fencing claim. -**API and result semantics.** `BootstrapRecoveryReader::Read(const RuntimeOwner&, IRecoveryReaderIo*) noexcept` returns either `shared_ptr` or `RecoveryReaderFatal`. The owner must be in `RecoveryRequired` mode and pass initial validation; otherwise the call returns a fatal outcome. The reader duplicates its root descriptor and revalidates ownership after scanning; later failure returns incomplete diagnostic evidence. The snapshot carries the domain, `scan_complete`, per-epoch diagnostics, global issues, and `issues_truncated`. An epoch diagnostic may include its canonical directory name and identity, intent identity, a safely decoded immutable `BootstrapInventory`, canonical digest, epoch-local issues, and an `issues_truncated` flag. File identities record device, inode, owner UID, link count, mode, size, mtime, and ctime. Arbitrary raw filesystem names and file contents are excluded. +**API and result semantics.** `BootstrapRecoveryReader::Read(const RuntimeOwner&, IRecoveryReaderIo*) noexcept` returns either `shared_ptr` or `RecoveryReaderFatal`. The owner must be in `RecoveryRequired` mode and pass initial validation; otherwise the call returns a fatal outcome. The reader duplicates its root descriptor and revalidates ownership after scanning; later failure returns incomplete diagnostic evidence. The snapshot carries the domain, `scan_complete`, per-epoch diagnostics, global issues, and `issues_truncated`. An epoch diagnostic may include its canonical directory name and identity, intent identity, a safely decoded immutable `BootstrapInventory`, an optional safely decoded immutable `ManifestV1`, canonical digests, epoch-local issues, and an `issues_truncated` flag. File identities record device, inode, owner UID, link count, mode, size, mtime, and ctime. Arbitrary raw filesystem names and file contents are excluded. `scan_complete=true` means only that the bounded structural scan was stable and all examined artifacts were valid. It does not mean all planned participants have recorded process identities, that a previous write was durably synced, that an epoch was active, that any process exited, that rollback did not occur, or that reset/serve is safe. A structurally valid inventory may contain pending identities. Empty roots, missing or invalid intents, unknown entries, collisions, detected mutation, and every resource-limit/truncation condition make the scan incomplete. The result is diagnostic data only: it is not a `BootstrapStore`, `EpochCandidate`, `InitialEpochClaim`, stop/exit acknowledgment, fencing token, or successor authorization. -**Scan order and validation.** The reader validates recovery-mode ownership and duplicates the root descriptor; it enumerates all root entries rather than choosing a newest epoch. It recognizes only canonical `epoch-<32 lowercase hex>` directories with owner-only `0700` permissions. It inspects every child entry; `intent.json` must be an owner-only `0600` regular single-link file within the existing 4 MiB inventory codec cap. It opens entries with no-follow and nonblocking flags. It records symlinks, special files, hard links, malformed names, unexpected root/child entries (including temporary files), missing intents, invalid checksums/schema, domain or directory-epoch mismatch, and identity collisions across epochs as issues. Safely decoded sibling inventories remain in the result when another entry is invalid. It revalidates file/directory identities and entry listings around reads, repeats root enumeration, and validates ownership again. These checks detect observed changes; they are not an atomic filesystem snapshot or protection against a hostile same-UID writer. The scan never writes, repairs, removes, fsyncs, starts, stops, or adopts filesystem/process state. +**Scan order and validation.** The reader validates recovery-mode ownership and duplicates the root descriptor; it enumerates all root entries rather than choosing a newest epoch. It recognizes only canonical nonzero `epoch-<32 lowercase hex>` directories with owner-only `0700` permissions. An epoch directory contains `intent.json` and may contain `manifest-store`; absence of that directory is valid for a bootstrap-only structural scan and proves no activation state. The epoch child-entry cap includes both names. `intent.json` must be an owner-only `0600` regular single-link file within the existing 4 MiB inventory codec cap. If `manifest-store` exists, it must be owner-only `0700` and have no more than 16 entries; its only accepted entries are an empty, owner-owned regular single-link `0600` `owner.lock` and an owner-owned regular single-link `0600` `manifest.json`. The manifest has its own 4 MiB codec cap. It opens entries with no-follow and nonblocking flags. It records symlinks, special files, hard links, malformed names, unknown or temporary entries (`intent.tmp`, `manifest.tmp`), missing required files, invalid checksums/schema, domain or directory-epoch mismatch, and identity collisions across epochs as issues. Safely decoded sibling artifacts remain in the result when another artifact is invalid. A readable manifest remains in its epoch diagnostic even if the intent is missing, corrupt, or inconsistent, when remaining caps permit. It revalidates file/directory identities and entry listings around reads, repeats root enumeration, and validates ownership again. These checks detect observed changes; they are not an atomic filesystem snapshot or protection against a hostile same-UID writer. The scan never writes, repairs, removes, fsyncs, starts, stops, or adopts filesystem/process state. + +Every safely decoded inventory contributes each planned container ID as a diagnostic target, whether or not `identity_recorded` is true. PID and PID-start identity are included only when recorded. This preserves exact container targets for pending identities. If an intent is unreadable, malformed, missing, or absent, unknown targets may exist; the reader reports uncertainty and retains known targets from other valid artifacts rather than presenting a complete empty set. Historical boot/clock identity remains diagnostic evidence; decoding does not require it to match the current boot. -Every safely decoded inventory contributes each planned container ID as a diagnostic target, whether or not `identity_recorded` is true. PID and PID-start identity are included only when recorded. This preserves exact container targets for pending identities. If an intent is unreadable, malformed, missing, or absent, unknown targets may exist; the reader reports uncertainty and retains known targets from other valid intents rather than presenting a complete empty set. Historical boot/clock identity remains diagnostic evidence; decoding does not require it to match the current boot. +If both artifacts decode, candidate comparison occurs only when `BootstrapInventory::ReadyCandidate` succeeds. Compare exact epoch ID, authority incarnation, policy digest, shared clock identity, and every participant identity, using canonical ordering by role, participant ID, and slot. Incomplete comparison data or any mismatch makes the scan incomplete; do not select the newer artifact or repair one from the other. Same-epoch duplicate representations that match are expected and are not cross-epoch collisions. `Prepared`, `Active`, `Draining`, and `Closed` are recorded metadata only; no phase, including `Closed`, proves process cessation. Manifest and intent checksums detect corruption only; they do not authenticate a writer, prove rollback freshness, or prove that a prior directory fsync completed. **Finite reader limits.** The component uses these fixed caps. Exceeding a cap retains collected evidence where possible, reports a limit/truncation condition, and forces `scan_complete=false`. @@ -683,12 +705,22 @@ Every safely decoded inventory contributes each planned container ID as a diagno | Epoch directories | 1,024 | Stop enumerating more epoch directories and report a limit issue | | Root entries (excluding `.` and `..`) | 4,096 | Truncate the root listing and report a limit issue | | Entries per epoch directory | 16 | Truncate that child listing and report an epoch issue | -| Aggregate attempted intent bytes | 64 MiB | Budget file size before read/decode; failed attempts still consume budget | -| Retained participants across inventories | 16,384 | Preserve prior records, stop adding after the cap, report a limit issue | +| Entries in `manifest-store` | 16 | Truncate nested listing and report an epoch issue | +| Aggregate attempted intent and manifest bytes | 64 MiB | Shared budget before read/decode; failed attempts still consume budget | +| Retained bootstrap and manifest participant records | 16,384 | Shared record budget; count both matching representations, preserve prior records, report a limit issue | | Global issues | 256 | Stop retaining issues and set `issues_truncated` | | Issues per epoch | 16 | Stop retaining local issues and set epoch `issues_truncated` | -Each intent also obeys the existing 4 MiB inventory codec cap. These reader bounds do not amend product quota limits. Issue truncation, any resource cap, and allocation failure cannot become a clean scan. +Each intent and manifest also obey its 4 MiB codec cap. These reader bounds do not amend product quota limits. Issue truncation, any resource cap, and allocation failure cannot become a clean scan. Matching bootstrap/manifest records in the same epoch do not collide; duplicate container or process identities across epoch directories remain conflicts. **Recovery handoff and remaining gates.** `EpochSupervisor` may use decoded container IDs as inputs to a future stop/reconcile operation, but it must independently inspect and positively confirm exit for each exact process/container. The reader cannot report “all stopped.” Unknown targets, missing/untrusted artifacts, or incomplete evidence block successor activation until reconciliation or the contracts' controlled complete-VM shutdown evidence. Full recovery orchestration, the Docker process controller, stop/exit evidence, participant activation, and successor-epoch authorization remain pending. Independent tests and pinned Linux/sanitizer CI evidence for the reader are required before component acceptance; no end-to-end recovery or fencing result is claimed. +### 21.2 Epoch artifact layout v1 + +The selected names and structure are specified in [Epoch artifact layout v1](contracts/epoch-artifact-layout-v1.md). The pure `epoch_layout_v1` utility is shared by BootstrapStore, BootstrapRecoveryReader, and ManifestStore: one canonical parser/formatter for nonzero epoch IDs and one source for all artifact name constants. Format/parse helpers produce or validate strings only. They do not validate filesystem ownership, authorize file access, prove an epoch is active, or issue any capability. + +The per-epoch layout is `epoch-/intent.json`, optionally followed by `epoch-/manifest-store/{owner.lock,manifest.json}`. BootstrapStore persists the launch intent before process start. ManifestStore may create a new private manifest-store directory only after the complete observed candidate exists; it cannot initialize an existing directory or adopt an ACTIVE epoch. These are separate durable transitions, not one transaction. `manifest.tmp` is uncertain evidence. Until witness/journal and recovery-operation path validators are defined and integrated, their names/directories are not recognized or accepted; an unknown entry remains a scan issue. + +The generic ManifestStore factory receives a caller-supplied directory and does not itself bind that path to the validated runtime root and epoch directory. Supervisor integration must construct exactly `/epoch-/manifest-store` while holding and validating global RuntimeOwner ownership. Shared path constants are not path capabilities. This complete supervisor-to-manifest-store binding and the recovery controller remain unimplemented; layout conformance alone does not authorize serving, stopping, or successor creation. + + diff --git a/docs/SCRUM-WORK-LOG.md b/docs/SCRUM-WORK-LOG.md index a445b78..85d7aef 100644 --- a/docs/SCRUM-WORK-LOG.md +++ b/docs/SCRUM-WORK-LOG.md @@ -517,3 +517,23 @@ Historical entries below are reconstructed from retained handoffs and GitHub evi - **Junior developer:** Implemented shared exact names and pure checked epoch parse/format helpers; grammar tests pass under strict NDEBUG. Prepared narrow BootstrapStore/ManifestStore name-reuse patches. Root review preserved existing validation precedence before formatting and publication. - **Tester:** Independently preparing matching-phase, missing/corrupt/mismatched-artifact, nested type/link/mode/temp/mutation and shared-budget cases. Flagged pending-bootstrap classification before publication. - **Scope:** This integration resolves artifact composition only. Controller targets for pending identities, real Docker exit evidence, recovery orchestration and verified successor authorization remain required. Source/tests and Linux acceptance for this increment are pending; no full RG006 acceptance is claimed. + +### LOG-060 — Shared artifact composition, review and CI correction (2026-11-24 UTC) + +- **Master:** After continuation, re-read PR21/feature/main heads and resumed the unchanged draft. Elapsed interruption time is not treated as measured agent effort. Published shared grammar/store reuse, manifest reader, developer tests and independent tests/CI integration in four separate commits. +- **Junior developer:** Supplied pure canonical epoch parsing/formatting and exact names, strict NDEBUG grammar checks and narrow store reuse patches. Root review restored original error-validation precedence before formatting. +- **Senior developer:** Implemented independent optional-manifest scanning, bounded private nested files, complete-candidate comparison, shared byte/participant accounting and metadata/presence revalidation. No writable store reopen, process action or epoch capability is produced. +- **Tester:** Caught pending-bootstrap comparison being mislabeled as a mismatch and the developer phase-fixture predicate advancing beyond its target. Verified all phases, corrupt/missing/pending intent retention, unsafe files/locks, mutations/appearance, shared bytes and exactly 16,384 dual-representation records plus overflow. New independent, extended developer and legacy-reader suites passed strict Clang/ASan/UBSan with fake EVP; this is behavior smoke only. +- **Scrum Master:** Independently reviewed the artifact contract and class boundaries; requested explicit absent-to-present manifest-store detection, now implemented and covered by developer/independent race fixtures. No process-exit/reset proof is claimed. +- **Master CI error:** Run45328285923 passed 52 CTest groups twice, 17 Python tests and 12 matching generated files, but a JavaScript replacement interpreted the selector suffix and dropped the shell quote. Sanitizer binaries built but their tests did not run; overall failure is not acceptance. Commit a3c4d7e fixed the selector, but run45330502633 exposed a second effect of the original replacement: duplicated workflow steps caused a duplicate-artifact conflict after all suites passed. Master rebuilt from the verified feature baseline and validated YAML, 21 unique named steps and all18 shell blocks; commit7fc9895e also scopes artifact names by run attempt. Both failed runs are excluded from overall acceptance. Production C++ is unchanged; full run45332588272 is pending. +- **Documentation:** LLD 9 records the namespace helper, optional-manifest API/caps and generic-store binding boundary. Current README/source pointers and context/story metadata are being synchronized. PRD 8 / SRD 5 / HLD 5 remain unchanged. +- **Next technical decision:** Selected bounded Docker Engine HTTP over the fixed local Unix socket, avoiding CLI subprocess/environment containment. The next controller will inspect/stop exact pending or observed targets; stop ACK, observed exit and epoch authorization remain distinct. No implementation or Docker qualification is claimed for that next slice. + +### LOG-061 — Artifact-layout Linux acceptance and integration review (2026-11-24 UTC) + +- **Master:** Run [45332588272](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45332588272) passed tested source `7fc9895e5f928ad1576d5b2119b79f4a717151e9` as merge ref `a93680850e190bb7e4d6a3c11f3dc4bb46a8051f` against feature base `9d9074601859c67541cd73343249ea11e8e09a95`. Both clean builds passed all 52 CTest groups, all 17 Python tests and all 12 generated files reproduced. All 38 selected sanitizer groups passed with real OpenSSL. Artifact upload and exact toolchain verification succeeded; the earlier failed runs remain excluded from acceptance. +- **Tester:** Independent phase, mismatch, pending/corrupt intent, file safety, race and aggregate-budget checks are included in the verified Linux run. Component acceptance covers diagnostic artifact composition only. +- **Documentation:** LLD9, layout/reader contracts, README, stories, sprint checkpoint and JSON handoff now reflect implemented boundaries and remaining work. Re-read main PRD8/SRD5, checked 130 relative links and the 14-story dependency graph. Historical status entries retain their actual past revisions. +- **Review/integration:** PR21 is ready for merge into the feature after documentation readback and a documentation-only comparison. PR13 remains unmerged; main is unchanged. Full RG006 and all release-level numerical gates remain open. +- **Next increment — Master/Junior/Tester:** Fixed local Unix HTTP transport selected; independent review identified connect-backlog ambiguity, final deadline/cancellation gating, allocation-error classification and throwing-clock exception safety. Developer corrections and independent fixtures are being prepared; Linux transport compilation/execution are not yet accepted. Darwin fallback compilation is not Linux fixture evidence. +- **Coordination:** Master narrowed the Senior's next delivery to internal controller/probe headers and the Junior's delivery to the concrete reviewed transport fixes before further implementation. No measured active-agent effort is inferred from elapsed design/CI time. diff --git a/docs/SPRINT-PLAN.md b/docs/SPRINT-PLAN.md index 47ac923..cc3e607 100644 --- a/docs/SPRINT-PLAN.md +++ b/docs/SPRINT-PLAN.md @@ -1,8 +1,12 @@ # Agile Sprint Plan — DistributedRateGuard -**Date:** 2026-11-12 +**Date:** 2026-11-24 **Status:** RG-001 component verified; Sprint 0 deployment gate open. RG-002 component verified; RG-003-A and RG-004-A/B1/B2/B3 implementation inputs verified; full integration pending. Product Owner authorized development and testing on 2026-11-12. -**Source contracts:** PRD 8 / SRD 5 from `main`; HLD 5 / LLD 8 startup, class-boundary and diagnostic-recovery clarification and current implementation tracking on `feature/distributed-rateguard`. See [PRD](PRD.md), [SRD](SRD.md), [HLD](HLD.md), [LLD](LLD.md), [stories](STORIES.md), and [JSON context blocks](context-blocks.json). Final promotion to `main` remains PR #13. +**Source contracts:** PRD 8 / SRD 5 from `main`; HLD 5 / LLD 9 startup, artifact-layout and diagnostic-recovery clarification and current implementation tracking on `feature/distributed-rateguard`. See [PRD](PRD.md), [SRD](SRD.md), [HLD](HLD.md), [LLD](LLD.md), [stories](STORIES.md), and [JSON context blocks](context-blocks.json). Final promotion to `main` remains PR #13. + +## Current delivery checkpoint — 2026-11-24 + +PRs #5–12 and #14–20 are merged into the integration feature. PR #21 adds shared epoch-artifact grammar and optional-manifest diagnostics; [Linux verification](evidence/RG-006-F.md) passed; feature integration is recorded by PR #21. RG-006 is still In progress: real process control, authenticated activation, durable recovery/orphan reconciliation and successor authorization remain open. Full quota services, replay/evaluation and distributed-credit assurance are later dependent work. Historical progress entries below retain their original status. Only PR #13 promotes the feature to `main`, and remains unmerged. ## Team and control diff --git a/docs/STORIES.md b/docs/STORIES.md index 9a1deba..cbeb723 100644 --- a/docs/STORIES.md +++ b/docs/STORIES.md @@ -1,6 +1,6 @@ # Implementation stories -**Updated:** 2026-11-23 · **Status:** Foundation/security/history/lifecycle components are integrated on `feature/distributed-rateguard`; full runtime story acceptance remains pending. PR #13 is the final promotion to `main`. Earlier per-increment PR notes below record historical states. +**Updated:** 2026-11-24 · **Status:** Foundation/security/history/lifecycle components are integrated on `feature/distributed-rateguard`; full runtime story acceptance remains pending. PR #13 is the final promotion to `main`. Earlier per-increment PR notes below record historical states. Machine-readable handoff: [context blocks](context-blocks.json). Follow dependency IDs rather than numeric order. Release labels indicate the deliverable; independent oracle work precedes dependent correctness checks even when delivered with release B. @@ -16,7 +16,7 @@ Proposed files: `proto/rateguard/v1/admission.proto`, `proto/rateguard/v1/author Classes: AdmissionService, AuthorityService. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-005, PRD-021, FR-005, FR-020. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-005, PRD-021, FR-005, FR-020. Acceptance criteria: component PASS; see [RG-001 evidence](evidence/RG-001.md). Product/service integration remains assigned to later stories. @@ -36,7 +36,7 @@ Proposed files: `src/policy/policy_snapshot.h`, `src/policy/policy_loader.h`, `s Classes: PolicySnapshot, PolicyLoader, CanonicalPolicyCodec, BucketMath. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-001, PRD-002, PRD-003, FR-001, FR-002, FR-003. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-001, PRD-002, PRD-003, FR-001, FR-002, FR-003. Acceptance criteria: component PASS after corrected [run 43353832066](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43353832066) and independent Tester review. See [RG-002 evidence](evidence/RG-002.md) and [scrum log](SCRUM-WORK-LOG.md). Runtime quota/identity/clock integration remains separately gated. @@ -56,7 +56,7 @@ Proposed files: `src/platform/clock.h`, `src/platform/clock_linux.h`. Classes: IClock, LinuxMonotonicClock. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-002, PRD-024, FR-001, FR-017. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-002, PRD-024, FR-001, FR-017. Component evidence: [RG-003](https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/RG-003-clock-provenance/docs/evidence/RG-003.md), head `2d55c6e032ae75947f045ac76ffa383b2b1dd9d8`, run 43355987772, independent acceptance. Full story is not Done. @@ -85,7 +85,7 @@ Implemented component paths on review branches: `include/rateguard/security/{pee Classes: PeerAuthenticator, AuthorizationResolver, ClientCallGuard, PinnedPeerRpcClient. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-008, PRD-024, FR-003. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-008, PRD-024, FR-003. Compatibility input **RG-004-A** is independently accepted in [PR #9](https://github.com/kshiteesh28/DistributedRateGuard/pull/9), head `f5b3e975225c869e4a9638af57ab9f7c8a06e546`, [run 43980308204](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/43980308204). Exact URI/leaf pin verification, real TLS rejection controls, compiled bypass detection and trusted UTC primitive passed. Docker observations matched under restricted permissions; [the record](evidence/RG-004-A/docker-time-43980308204.json) is capability evidence only. This initial compatibility slice alone does not provide registry, authorization or connection-expiry guards; B1/B2/B3 supply the scoped inputs below. Manifest binding and epoch/service integration remain open. All full-story acceptance criteria below remain unverified. @@ -113,7 +113,7 @@ Component files include `src/events/` and `tools/history/`. See [RG-005 evidence Classes: EventRecorder, HistoryExporter. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-009, PRD-015, FR-009, FR-010. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-009, PRD-015, FR-009, FR-010. Component verification passed in Linux run 45126587562. Full acceptance remains pending service/supervisor wiring and the RG-011A provenance gate. @@ -125,9 +125,9 @@ Component verification passed in Linux run 45126587562. Full acceptance remains **Implement supervisor lifecycle and positive fencing** · Release A · In progress -Local [gate](evidence/RG-006-A.md), [manifest](evidence/RG-006-B.md) and [runtime ownership](evidence/RG-006-C.md) components are verified on the integration feature. [Bootstrap inventory/store](evidence/RG-006-D.md) verification and full runtime acceptance are tracked separately; the story remains In progress. +Local [gate](evidence/RG-006-A.md), [manifest](evidence/RG-006-B.md) and [runtime ownership](evidence/RG-006-C.md) components are verified on the integration feature. [Bootstrap inventory/store](evidence/RG-006-D.md), [recovery reader](evidence/RG-006-E.md) and [artifact composition](evidence/RG-006-F.md) components are verified; full runtime acceptance is tracked separately; the story remains In progress. -Implemented component paths: `src/supervisor/epoch_gate.h`, `manifest_codec.{h,cpp}`, `manifest_store.{h,cpp}`, `runtime_owner.{h,cpp}`, `bootstrap_inventory.{h,cpp}` and `bootstrap_store.{h,cpp}` (all under `src/supervisor/`). New classes: RuntimeOwner, InitialEpochClaim, BootstrapInventory and BootstrapStore; see LLD 8 §21. The diagnostic [recovery reader](evidence/RG-006-E.md) is a separate component; it preserves known pending-container identities and incomplete evidence without granting recovery authority. Concrete Docker control, authenticated activation and successor-epoch fencing remain pending. +Implemented component paths: `src/supervisor/epoch_gate.h`, `manifest_codec.{h,cpp}`, `manifest_store.{h,cpp}`, `runtime_owner.{h,cpp}`, `bootstrap_inventory.{h,cpp}` and `bootstrap_store.{h,cpp}` (all under `src/supervisor/`). New classes: RuntimeOwner, InitialEpochClaim, BootstrapInventory and BootstrapStore; see LLD 9 §21. The shared [artifact layout](contracts/epoch-artifact-layout-v1.md) and [manifest diagnostics](evidence/RG-006-F.md) extend the reader with a strictly validated optional manifest store. The diagnostic [recovery reader](evidence/RG-006-E.md) is a separate component; it preserves known pending-container identities and incomplete evidence without granting recovery authority. Concrete Docker control, authenticated activation and successor-epoch fencing remain pending. Dependencies: RG-002, RG-003-A, RG-005 and named verified RG-004-A/B1 inputs. B1 supplies typed certificate metadata only; RG-006 does not require full RG-004 completion. Full RG-004-AC02 later consumes RG-006 manifest/fencing evidence. This separates development inputs from final integration acceptance without waiving either gate. @@ -137,7 +137,7 @@ Remaining proposed integration files: `src/supervisor/process_controller.h`, `sr Classes: EpochGate, ManifestStore, IProcessController, EpochSupervisor, DockerProcessController. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-007, PRD-024, PRD-025, FR-001, FR-007, FR-008, FR-022. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-007, PRD-024, PRD-025, FR-001, FR-007, FR-008, FR-022. Acceptance criteria (not run): @@ -157,7 +157,7 @@ Proposed files: `src/authority/witness_port.h`, `src/supervisor/witness_state.h` Classes: IStateWitness, WitnessStateMachine, JournalWriter, LocalStateWitnessClient, WitnessServer. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-007, PRD-015, PRD-024, FR-008, FR-010. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-007, PRD-015, PRD-024, FR-008, FR-010. Acceptance criteria (not run): @@ -177,7 +177,7 @@ Proposed files: `tools/replay/reference_model.h`, `tools/replay/main.cpp`. Classes: ReplayModel. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-006, FR-011, FR-012. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-006, FR-011, FR-012. Acceptance criteria (not run): @@ -197,7 +197,7 @@ Proposed files: `src/authority/tenant_ledger.h`, `src/authority/tenant_reservati Classes: TenantLedger, TenantReservation, AuthorityEngine, AuthorityService, AdmissionService, GrpcAuthorityClient. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-001, PRD-002, PRD-003, PRD-005, FR-002, FR-005, FR-006. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-001, PRD-002, PRD-003, PRD-005, FR-002, FR-005, FR-006. Acceptance criteria (not run): @@ -217,7 +217,7 @@ Proposed files: `adapter/forward_attempt.h`, `adapter/sample_adapter.h`. Classes: ForwardAttempt, SampleAdapter. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-004, PRD-005, FR-004, FR-006. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-004, PRD-005, FR-004, FR-006. Acceptance criteria (not run): @@ -237,7 +237,7 @@ Proposed files: `src/credits/tenant_credits.h`, `src/credits/credit_manager.h`, Classes: ReplicaTenantCredits, CreditManager, IAuthorityClient. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-016, PRD-017, PRD-018, PRD-019, FR-014, FR-015, FR-016, FR-017, FR-018. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-016, PRD-017, PRD-018, PRD-019, FR-014, FR-015, FR-016, FR-017, FR-018. Acceptance criteria (not run): @@ -257,7 +257,7 @@ Proposed files: `tools/loadgen/trace_generator.h`, `tools/loadgen/runner.h`, `to Classes: TraceGenerator, BenchmarkRunner. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-010, PRD-011, PRD-012, PRD-020, PRD-022, PRD-026, FR-013, FR-019, FR-023, NFR-002, NFR-003, NFR-004, NFR-005, NFR-006, NFR-007, NFR-009. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-010, PRD-011, PRD-012, PRD-020, PRD-022, PRD-026, FR-013, FR-019, FR-023, NFR-002, NFR-003, NFR-004, NFR-005, NFR-006, NFR-007, NFR-009. Acceptance criteria (not run): @@ -277,7 +277,7 @@ Proposed files: `model/runner`, `model/RateGuard.tla`, `tools/history_checker/ch Classes: HistoryChecker, ModelHarness. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-018, PRD-021, PRD-023, FR-017, FR-020, FR-021. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-018, PRD-021, PRD-023, FR-017, FR-020, FR-021. Acceptance criteria (not run): @@ -297,7 +297,7 @@ Proposed files: `docs/releases/manifest.json`, `docs/releases/requirements-evide Classes: release artifacts and runner integration. -Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 6](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-010, PRD-011, PRD-012, PRD-021, PRD-023, FR-013, FR-020, FR-021, NFR-001, NFR-006. +Sources: [PRD 8](PRD.md), [SRD 5](SRD.md), [HLD 5](HLD.md), [LLD 9](LLD.md#17-class-design-and-construction-contracts). Requirements: PRD-010, PRD-011, PRD-012, PRD-021, PRD-023, FR-013, FR-020, FR-021, NFR-001, NFR-006. Acceptance criteria (not run): @@ -308,4 +308,4 @@ Acceptance criteria (not run): ## Readiness clarification — 2026-11-12 -The full replay command/report remains a Release B deliverable. Its independent strict decision oracle and golden fixtures are required earlier as test support for Release A; this does not move replay product scope into A. The performance p99 population and target-build lock are defined in PRD 8 / SRD 5 / LLD 8. No story is implemented or accepted by this clarification. +The full replay command/report remains a Release B deliverable. Its independent strict decision oracle and golden fixtures are required earlier as test support for Release A; this does not move replay product scope into A. The performance p99 population and target-build lock are defined in PRD 8 / SRD 5 / LLD 9. No story is implemented or accepted by this clarification. diff --git a/docs/context-blocks.json b/docs/context-blocks.json index c084d61..bebf776 100644 --- a/docs/context-blocks.json +++ b/docs/context-blocks.json @@ -21,11 +21,11 @@ "PRD": 8, "SRD": 5, "HLD": 5, - "LLD": 8 + "LLD": 9 }, "state": { - "documents": "reviewed_specifications_revision_8_5_5_8", - "implementation": "rg006_recovery_reader_verified_layout_controller_pending", + "documents": "reviewed_specifications_revision_8_5_5_9", + "implementation": "rg006_artifact_layout_component_verified_runtime_pending", "benchmarks": "not_run", "model_checking": "not_run", "note": "Foundation and security components are integrated on feature/distributed-rateguard. PR #13 is the pending promotion to main." @@ -217,7 +217,8 @@ "HLD 5 / LLD 6 clarify durable stopped-container intents, non-serving bootstrap and observed process-identity persistence before activation; PRD 8 / SRD 5 unchanged.", "Historical documentation-check entries retain the revisions actually checked at that time.", "LLD 7 records implemented ownership/bootstrap class boundaries; actual process control and successor-epoch authorization remain pending.", - "LLD 8 records recovery-reader API/caps and distinguishes fatal initial ownership failure from incomplete later diagnostics; read-only scan is not fencing." + "LLD 8 records recovery-reader API/caps and distinguishes fatal initial ownership failure from incomplete later diagnostics; read-only scan is not fencing.", + "LLD 9 and layout v1 define shared canonical paths, independent manifest retention, ReadyCandidate-only comparison, shared budgets and the generic-store path-binding integration boundary." ], "latest_rg006_runtime_ownership": { "status": "component_verified_merged_to_feature", @@ -242,17 +243,37 @@ "merge_commit": "cb98d7851fdac6f4eedab0d5f55a88a7fd98a798" }, "latest_rg006_bootstrap_recovery": { - "status": "component_verified_integration_pending", + "status": "component_verified_merged_to_feature", "pull_request": 20, "tested_head": "87c784b25d47dd97527709756fd63673671af470", "tested_merge_ref": "0784213de9ec24bf7e111224363f04a56909f4cb", "run": 45292546023, "evidence": "docs/evidence/RG-006-E.md", - "full_story_done": false + "full_story_done": false, + "pull_request_status": "merged_to_feature", + "merge_commit": "9d9074601859c67541cd73343249ea11e8e09a95" + }, + "latest_rg006_artifact_layout": { + "status": "component_verified", + "pull_request": 21, + "tested_head": "7fc9895e5f928ad1576d5b2119b79f4a717151e9", + "tested_merge_ref": "a93680850e190bb7e4d6a3c11f3dc4bb46a8051f", + "run": 45332588272, + "evidence": "docs/evidence/RG-006-F.md", + "scope": "Shared names and read-only optional manifest diagnostics; no Docker control, serving or successor capability", + "full_story_done": false, + "ctest_groups_per_clean_build": 52, + "clean_builds": 2, + "python_tests": 17, + "matching_generated_files": 12, + "sanitizer_groups": 38, + "artifact_id": 14893310876, + "artifact_sha256": "55e4f28c6a639bd8a09711b9842f3f40d8eca2cc7c144afe9f70721b951a188d", + "pull_request_status": "verified_ready_for_feature_integration" } }, "next_actions": [ - "Integrate the frozen epoch artifact layout and format-specific recovery validation, then implement pending/observed controller targets, durable recovery orchestration and verified successor claims. Existing roots and reader snapshots do not authorize serving or reset.", + "Implement a bounded local Docker Engine Unix HTTP transport and exact pending/observed inspect-stop controller; then integrate durable recovery operations, orphan inventory reconciliation and verified successor authorization. No current reader/layout result authorizes serving or reset.", "Then RG006 manifest/fencing and RG007 witness before strict runtime/adapter/Release A acceptance.", "Keep production session caching disabled; native SDK qualification is test-only.", "Maintain per-agent logs and leave main implementation merges to Product Owner control." @@ -262,7 +283,7 @@ "implementation": "Development/testing authorized; main merge remains under Product Owner review.", "planning_documentation_main": "Explicitly authorized by the user in this task.", "development_and_testing": "Authorized by Product Owner on 2026-11-12: begin the implementation.", - "main_implementation_merge": "Product Owner controls current implementation merge to main; all implementation PRs remain unmerged." + "main_implementation_merge": "Component PRs merge into feature/distributed-rateguard after verification. Final feature-to-main promotion is PR #13 and remains pending Product Owner review." }, "stories": [ { @@ -326,7 +347,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -433,7 +454,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -528,7 +549,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -726,7 +747,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -981,7 +1002,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -1104,6 +1125,10 @@ { "path": "src/supervisor/bootstrap_recovery_reader.cpp", "status": "implemented_component_verified" + }, + { + "path": "src/supervisor/epoch_artifact_layout.h", + "status": "implemented_component_verified" } ], "classes": [ @@ -1123,7 +1148,8 @@ "Use LLD sections 16 and 17 for exact sequencing and class ownership; evidence must be independent of production decision logic.", "LLD 7 §21 defines initial-claim ownership, durable visibility versus transition status and candidate-data handoff. BootstrapStore does not launch, activate, recover or fence participants.", "EpochSupervisor owns the future existing-intent recovery reader. RuntimeOwner existing acquisition does not load bootstrap state; missing or uncertain inventory blocks reset.", - "LLD 8 §21.1 defines diagnostic-only bounded recovery reading. Pending container IDs/historical provenance are retained; scan_complete never proves prior durability, cessation or safe reset." + "LLD 8 §21.1 defines diagnostic-only bounded recovery reading. Pending container IDs/historical provenance are retained; scan_complete never proves prior durability, cessation or safe reset.", + "epoch_layout_v1 is a pure namespace utility, not a service or capability. Optional nested manifest diagnostics use independent codecs and the same byte/participant budgets. CLOSED metadata is not process-exit evidence." ], "files_to_refer": [ { @@ -1143,7 +1169,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -1176,7 +1202,7 @@ "status": "not_run" } ], - "first_action": "Integrate the frozen epoch artifact layout and format-specific recovery validation, then implement pending/observed controller targets, durable recovery orchestration and verified successor claims. Existing roots and reader snapshots do not authorize serving or reset.", + "first_action": "Implement a bounded local Docker Engine Unix HTTP transport and exact pending/observed inspect-stop controller; then integrate durable recovery operations, orphan inventory reconciliation and verified successor authorization. No current reader/layout result authorizes serving or reset.", "input_dependency_contracts": [ { "contract": "RG-003-A", @@ -1204,7 +1230,9 @@ "manifest_evidence": "docs/evidence/RG-006-B.md", "runtime_ownership_evidence": "docs/evidence/RG-006-C.md", "bootstrap_evidence": "docs/evidence/RG-006-D.md", - "bootstrap_recovery_evidence": "docs/evidence/RG-006-E.md" + "bootstrap_recovery_evidence": "docs/evidence/RG-006-E.md", + "artifact_layout_contract": "docs/contracts/epoch-artifact-layout-v1.md", + "artifact_layout_evidence": "docs/evidence/RG-006-F.md" }, { "id": "RG-007", @@ -1279,7 +1307,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -1375,7 +1403,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -1491,7 +1519,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -1600,7 +1628,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -1702,7 +1730,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -1809,7 +1837,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -1908,7 +1936,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -2006,7 +2034,7 @@ }, { "path": "docs/LLD.md", - "revision": 8, + "revision": 9, "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/LLD.md" } ], @@ -2074,5 +2102,5 @@ "historical_actual_effort": "unknown_not_recorded", "url": "https://github.com/kshiteesh28/DistributedRateGuard/blob/feature/distributed-rateguard/docs/SCRUM-WORK-LOG.md" }, - "generated_at_utc": "2026-11-24T00:05:00Z" + "generated_at_utc": "2026-11-24T05:34:00Z" } diff --git a/docs/contracts/bootstrap-recovery-v1.md b/docs/contracts/bootstrap-recovery-v1.md index 839103f..7cfcabe 100644 --- a/docs/contracts/bootstrap-recovery-v1.md +++ b/docs/contracts/bootstrap-recovery-v1.md @@ -1,5 +1,7 @@ # Bootstrap recovery reader v1 +**Layout extension:** [Epoch artifact layout v1](epoch-artifact-layout-v1.md) adds strictly validated optional `manifest-store` artifacts to the bootstrap-only child allowlist below. Other bounds and diagnostic-only semantics remain in force. The extension does not authorize serving, stopping or reset. + **Status:** Proposed RG-006 component contract, 2026-11-23. Sources: PRD 8 / SRD 5, HLD 5 A-03, LLD 7 §21. This contract supplies the bounded read-only reader needed by the future EpochSupervisor recovery path. It does not complete that path. ## Boundary and result diff --git a/docs/contracts/epoch-artifact-layout-v1.md b/docs/contracts/epoch-artifact-layout-v1.md index 9e26231..de9d540 100644 --- a/docs/contracts/epoch-artifact-layout-v1.md +++ b/docs/contracts/epoch-artifact-layout-v1.md @@ -1,6 +1,6 @@ # Epoch artifact layout v1 -**Status:** Selected implementation layout; integration in progress. Sources: PRD 8 / SRD 5, HLD 5 A-03 and LLD 8 §21. These choices preserve product behavior and release gates. +**Status:** Selected component layout; implementation verification tracked in [RG-006-F evidence](../evidence/RG-006-F.md). Sources: PRD 8 / SRD 5, HLD 5 A-03 and LLD 9 §21. These choices preserve product behavior and release gates. ## Directory contract diff --git a/docs/evidence/RG-006-E.md b/docs/evidence/RG-006-E.md index 7caa6ad..070f53c 100644 --- a/docs/evidence/RG-006-E.md +++ b/docs/evidence/RG-006-E.md @@ -29,3 +29,7 @@ Linux [run 45292546023](https://github.com/kshiteesh28/DistributedRateGuard/acti ## Remaining integration The reader does not launch, inspect, stop or fence processes; restore a store; acknowledge activation; or issue any epoch capability. EpochSupervisor must still reconcile the full artifact/runtime inventory, use a real controller to positively confirm cessation, satisfy all policy/trust/clock/witness gates and obtain a verified successor authorization. Unknown or untrusted inventory blocks reset. Artifact layout/controller integration, authenticated participant activation, witness and full lifecycle acceptance remain open. + +## Later format extension + +[RG-006-F](RG-006-F.md) adds optional-manifest diagnostics under [artifact layout v1](../contracts/epoch-artifact-layout-v1.md). This evidence retains the original bootstrap-only source/run scope; neither version authorizes serving, stop or reset. diff --git a/docs/evidence/RG-006-F.md b/docs/evidence/RG-006-F.md new file mode 100644 index 0000000..efb38c1 --- /dev/null +++ b/docs/evidence/RG-006-F.md @@ -0,0 +1,41 @@ +# RG-006 artifact layout and manifest diagnostics evidence + +**Scope:** PR #21 / RG-006-F. Sources: PRD 8 / SRD 5, HLD 5, LLD 9 and [layout v1](../contracts/epoch-artifact-layout-v1.md). Full RG-006 remains In progress. + +## Implemented component + +The pure epoch_layout_v1 helper supplies exact canonical names and nonzero lowercase-hex epoch parse/format. BootstrapStore and ManifestStore reuse these definitions while preserving prior validation ordering, private new-only creation and publication semantics. + +The diagnostic reader recognizes an optional epoch/manifest-store directory containing an empty owner.lock and a canonical manifest.json. It validates ownership, permissions, single links, bounded file types/contents and before/after identity/entry metadata. Unknown, temporary, missing or changed artifacts make the scan incomplete while safely decoded known data remains available. + +Intent and manifest are scanned independently. A valid manifest remains diagnostic data when the intent is missing or corrupt. Candidate comparison occurs only after BootstrapInventory ReadyCandidate succeeds; unavailable comparison is ManifestBootstrapNotReady, while unequal complete candidates yield ManifestCandidateMismatch. Prepared/Active/Draining/Closed are retained phases, never exit or reset proof. + +Nested directory entries are capped at 16. Both representations share the existing 64 MiB attempted-byte budget and 16,384 retained-record budget. Matching participants in the two artifacts consume two memory records but are not cross-epoch identity collisions. Across-epoch container/process collisions remain incomplete. + +## Review and independent checks + +- Junior developer supplied shared names/grammar and store reuse patches. Master preserved original claim/domain/epoch/model validation priority before formatting. +- Senior developer added independent manifest scanning and typed diagnostics. Tester caught comparison of unavailable bootstrap data being reported as a mismatch, and a phase-fixture predicate that advanced past the target phase; both were corrected before publication. +- Scrum/Master review made baseline-absent to later-present manifest-directory changes explicit, independent of metadata timestamp granularity. Known data is retained, with an incomplete scan. +- Independent tests cover all phases, field mismatches, missing/corrupt/pending bootstrap, unsafe nested file types/modes/links, missing/nonempty lock, unknown/temp files, mutation/appearance races, nested-entry overflow and shared byte/record limits. The record-boundary fixture retains exactly 16,384 records across 32 paired epochs, then rejects the next over-budget inventory. +- Pure grammar, extended developer, new independent and legacy reader checks passed locally under strict NDEBUG Clang; applicable behavior suites passed ASan/UBSan with a deterministic EVP shim. Shim checks do not establish real cryptographic acceptance. + +## Linux verification + +Run 45328285923 passed all 52 CTest groups in both clean builds, 17 Python tests and 12 generated-file reproduction, but the sanitizer command failed because Master's JavaScript workflow replacement dropped its closing shell quote. The sanitizer binaries built; their tests were not executed. The overall failed run is excluded from acceptance. Master fixed only the selector line with literal mapping and checked its Bash syntax; C++ source did not change. + +Run 45330502633 then passed both 52-group clean suites, Python/reproduction checks and every selected sanitizer suite, but failed at a duplicate artifact upload. The same original replacement had also duplicated the workflow tail. This failed run is also excluded from overall acceptance. Master rebuilt the workflow from the verified feature baseline, preserved the two new targets and manifest sanitizer configuration, checked all 21 unique named steps and 18 Bash blocks, and scoped artifact names by run attempt. Commit 7fc9895e changes only the workflow; production C++ is unchanged. + +[Run 45332588272](https://github.com/kshiteesh28/DistributedRateGuard/actions/runs/45332588272) **passed** on source `7fc9895e5f928ad1576d5b2119b79f4a717151e9`, tested as merge ref `a93680850e190bb7e4d6a3c11f3dc4bb46a8051f` against feature base `9d9074601859c67541cd73343249ea11e8e09a95` with real Linux/OpenSSL: +- 52 CTest groups passed in each of two clean builds. +- 17 Python tests passed; all 12 generated files matched. +- Sanitizer selections passed: bootstrap/layout 8, manifest 3, runtime ownership 2, local lifecycle 2, clock 3, history 8 and security 12 groups. +- Frozen toolchain verification and artifact upload passed. Artifact `14893310876` (`rg001-build-manifest-45332588272-1`) has SHA-256 `55e4f28c6a639bd8a09711b9842f3f40d8eca2cc7c144afe9f70721b951a188d`. + +Only documentation follows this tested source. Hosted component checks and Docker clock observations do not satisfy the target deployment or complete fencing gates. + +## Remaining integration + +ManifestStore still receives a generic caller-supplied directory. Full EpochSupervisor composition must bind it to the validated runtime root/epoch/manifest-store while holding global ownership. Neither a path string, valid manifest nor scan_complete is an epoch capability. + +Docker/OS control, pending-identity stop targets, authenticated participant activation, durable recovery/orphan reconciliation, witness validators and verified successor authorization remain pending. Witness/recovery-operation names are not accepted until their own bounded validators are integrated. No release benchmark, quota safety, full fencing or production-readiness claim is made.