Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[core] Add common blob reader api (#38298)

Pawel Raasz1ecab5a867c2
diff --git a/src/inference/dev_api/openvino/runtime/hsm_reader.hpp b/src/inference/dev_api/openvino/runtime/hsm_reader.hpp
new file mode 100644
index 00000000000..480b384f4d3
--- /dev/null
+++ b/src/inference/dev_api/openvino/runtime/hsm_reader.hpp
@@ -0,0 +1,341 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <istream>
+#include <optional>
+#include <variant>
+#include <vector>
+
+#include "openvino/runtime/hsm_format.hpp"
+#include "openvino/runtime/common.hpp"
+
+namespace ov::runtime::hsm {
+inline namespace v1 {
+
+/**
+ * @brief Copyable handle to one manifest entry's payload - the single way to read a #Section, whether the
+ * owning #Reader was opened over a stream or a buffer. Never owns or copies memory itself; #read() is
+ * the only copy point.
+ * @note Outlives the #Reader that produced it, as long as the stream/buffer passed to `open()` is still
+ * alive.
+ */
+class OPENVINO_RUNTIME_API Section {
+public:
+ /**
+ * @brief Inline-mode section - payload lives in @p entry itself, no external source needed.
+ */
+ explicit constexpr Section(const ManifestEntry& entry) noexcept : m_entry(entry) {}
+
+ /**
+ * @brief Pointer-mode section backed by an addressable buffer; @p payload is its own bytes only.
+ */
+ constexpr Section(const ManifestEntry& entry, ov::util::MemoryView payload) noexcept
+ : m_entry(entry),
+ m_source(payload) {}
+
+ /**
+ * @brief Pointer-mode section backed by a stream; @p payload_start is its first byte's stream position.
+ */
+ Section(const ManifestEntry& entry, std::istream& stream, std::streampos payload_start) noexcept
+ : m_entry(entry),
+ m_source(StreamSource{&stream, payload_start}) {}
+
+ constexpr DeviceId device() const noexcept {
+ return m_entry.device;
+ }
+ constexpr SectionTag tag() const noexcept {
+ return m_entry.tag;
+ }
+ constexpr size_t size() const noexcept {
+ return m_entry.tag.is_inline() ? m_entry.inline_bytes.size() : static_cast<size_t>(m_entry.size);
+ }
+
+ /**
+ * @brief Zero-copy view of the whole section.
+ * @return `std::nullopt` only for a pointer-mode section read from a stream-only #Reader - there's no
+ * addressable memory to view; use #read() instead. Slice the returned view yourself for a sub-range.
+ */
+ std::optional<ov::util::MemoryView> view() const noexcept;
+
+ /**
+ * @brief Reads `[offset, offset + length)` into caller-owned @p destination - the only copy this type
+ * ever makes. Always works, regardless of source; prefer #view() first to avoid the copy when possible.
+ * @param destination Must point to at least @p length writable bytes, kept alive by the caller - `void*`
+ * so any buffer type (`ov::Tensor::data()`, `vector<uint8_t>::data()`, ...) can be passed without a cast.
+ * @return false if `[offset, offset + length)` exceeds this section's size, or the underlying read failed.
+ */
+ bool read(size_t offset, size_t length, void* destination) const;
+
+ /**
+ * @overload Reads the whole section; @p destination must point to at least #size() writable bytes.
+ */
+ bool read(void* destination) const {
+ return read(0, size(), destination);
+ }
+
+ /**
+ * @brief Owned-copy convenience - explicit opt-in, since #Section itself never copies on its own.
+ * @return `std::nullopt` if the underlying #read() failed.
+ */
+ std::optional<std::vector<std::byte>> to_bytes() const {
+ std::vector<std::byte> bytes(size());
+ return read(bytes.data()) ? std::optional(std::move(bytes)) : std::nullopt;
+ }
+
+private:
+ using StreamSource = std::pair<std::istream*, std::streampos>;
+
+ ManifestEntry m_entry;
+ std::variant<std::monostate, ov::util::MemoryView, StreamSource> m_source;
+};
+
+/**
+ * @brief Common decoder contract: given a section, returns the decoded `T`, or `std::nullopt` if it doesn't
+ * parse. Written once, works unchanged whether #Section was opened over a stream or a buffer, and whether
+ * the decoder reads all of it (#Section::read()/#Section::view()) or only part, decided from what it already
+ * read - the reader itself never interprets content, so nothing here needs to change per source or per shape
+ * of read.
+ * @note Convention, not enforced: report malformed content via `std::nullopt`, never throw.
+ * @note Distinct from #ISectionReaderHandler: this is a stateless function for one already-known
+ * `(device, tag)` pair, invoked via #Reader::decode()/#Reader::decode_all(). #ISectionReaderHandler is for a
+ * set of stateful handlers dispatched across an entire manifest in one pass, without enumerating tags up front.
+ */
+template <typename T>
+using SectionDecoder = std::function<std::optional<T>(const Section&)>;
+
+/**
+ * @brief Adapts @p parse - the actual bytes-to-`T` logic, written once against a #ov::util::MemoryView -
+ * into a #SectionDecoder<T>. Runs @p parse directly over #Section::view() when one is available (no extra
+ * copy beyond what @p parse itself does), otherwise falls back to #Section::read() into an owned buffer and
+ * runs @p parse over that instead (exactly one copy) - so @p parse never needs to know or care which one
+ * happened.
+ */
+template <typename T>
+SectionDecoder<T> make_section_decoder(std::function<std::optional<T>(ov::util::MemoryView)> parse) {
+ return [parse = std::move(parse)](const Section& section) -> std::optional<T> {
+ if (const auto view = section.view()) {
+ return parse(*view);
+ } else {
+ const auto bytes = section.to_bytes();
+ return bytes ? parse(ov::util::MemoryView(bytes->data(), bytes->size())) : std::nullopt;
+ }
+ };
+}
+
+/**
+ * @brief Per-entry hook a #Reader offers to plugins/devices: given one manifest entry's section content, a
+ * concrete handler self-selects by checking `(entry.device, entry.tag)` and returns whether it recognized
+ * and handled it. Per the unknown-tag rule on #SectionTag, an entry no handler recognizes must be skipped,
+ * never fail import.
+ */
+class OPENVINO_RUNTIME_API ISectionReaderHandler {
+public:
+ virtual ~ISectionReaderHandler() = default;
+
+ /**
+ * @brief Attempts to interpret @p entry's section content.
+ * @note Not itself a dispatch loop - a caller tries this once per candidate entry against each handler
+ * it holds, in turn, until one returns true.
+ * @param entry Manifest entry being considered - not necessarily one this extension owns.
+ * @param section Bounds-checked view of the payload.
+ * @return true if `(entry.device, entry.tag)` was recognized and handled, false otherwise.
+ */
+ virtual bool handle_section(const ManifestEntry& entry, ov::util::MemoryView section) = 0;
+};
+
+/**
+ * @brief Common (device-agnostic) reader for a single HSM container, over any `std::istream&` or addressable
+ * buffer. Validates the container and drives extension dispatch so plugins can consume - or override - any
+ * section, without ever needing to interpret proprietary content itself.
+ * @note Deliberately stateless beyond the parsed manifest - every accessor resolves fresh by `(device, tag)`,
+ * so an #Reader is cheap to move. #entries() gives a no-payload-read overview; #section()/#sections() hand
+ * back #Section handles; #decode()/#decode_all() run a #SectionDecoder over them directly.
+ */
+class OPENVINO_RUNTIME_API Reader {
+public:
+ /**
+ * @brief Opens an HSM container from a given input stream.
+ * @param stream The input stream containing the HSM container data. Must remain valid for the lifetime
+ * of the returned Reader, and of any #Section obtained from it.
+ * @return A valid Reader if the container is successfully opened and validated; `std::nullopt` otherwise.
+ */
+ static std::optional<Reader> open(std::istream& stream);
+
+ /**
+ * @brief Opens an HSM container from a given in-memory buffer - enables zero-copy #Section::view().
+ * @param data Pointer to the buffer containing the HSM container data. Must remain valid for the lifetime
+ * of the returned Reader, and of any #Section obtained from it.
+ * @param size Size of the buffer in bytes.
+ * @return A valid Reader if the container is successfully opened and validated; `std::nullopt` otherwise.
+ */
+ static std::optional<Reader> open(const std::byte* data, size_t size);
+
+ /**
+ * @overload uint8_t variant of open(const std::byte*, size_t).
+ */
+ static std::optional<Reader> open(const uint8_t* data, size_t size);
+
+ Reader(const Reader&) = delete;
+ Reader& operator=(const Reader&) = delete;
+ Reader(Reader&&) = default;
+ Reader& operator=(Reader&&) = default;
+
+ /**
+ * @brief Returns a reference to the vector of all manifest entries in the container.
+ * @return A reference to the vector of all manifest entries in the container.
+ */
+ const std::vector<ManifestEntry>& entries() const noexcept {
+ return m_manifest;
+ }
+
+ /**
+ * @brief Number of manifest entries matching (@p device, @p tag) - no section payload is read.
+ *
+ * @param device The device ID to match.
+ * @param tag The tag to match.
+ * @return size_t The number of matching manifest entries.
+ */
+ template <typename Tag>
+ size_t count(DeviceId device, Tag tag) const noexcept {
+ return count_by_id(device, static_cast<uint32_t>(tag));
+ }
+
+ /**
+ * @overload Uses #any_device_id - shorthand for a Core-owned section.
+ */
+ template <typename Tag>
+ size_t count(Tag tag) const noexcept {
+ return count_by_id(any_device_id, static_cast<uint32_t>(tag));
+ }
+
+ /**
+ * @brief Finds the first manifest entry matching (@p device, @p tag) and returns a #Section handle for it.
+ *
+ * @param device The device ID to match.
+ * @param tag The tag to match.
+ * @return std::optional<Section> A handle to the matching section, or `std::nullopt` if not found.
+ */
+ template <typename Tag>
+ std::optional<Section> section(DeviceId device, Tag tag) const {
+ return section_by_id(device, static_cast<uint32_t>(tag));
+ }
+
+ /**
+ * @overload Uses #any_device_id - shorthand for Core sections; no new accessor needed as tags grow.
+ */
+ template <typename Tag>
+ std::optional<Section> section(Tag tag) const {
+ return section_by_id(any_device_id, static_cast<uint32_t>(tag));
+ }
+
+ /**
+ * @brief Finds all manifest entries matching (@p device, @p tag) and returns a #Section handle for each, in manifest order.
+ *
+ * @tparam Tag The type of the tag, typically an enum or `uint32_t`.
+ * @param device The device ID to match.
+ * @param tag The tag to match.
+ * @return std::vector<Section> A vector of handles to the matching sections, in manifest order.
+ */
+ template <typename Tag>
+ std::vector<Section> sections(DeviceId device, Tag tag) const {
+ return sections_by_id(device, static_cast<uint32_t>(tag));
+ }
+
+ /**
+ * @overload Uses #any_device_id - shorthand for a Core-owned section.
+ */
+ template <typename Tag>
+ std::vector<Section> sections(Tag tag) const {
+ return sections_by_id(any_device_id, static_cast<uint32_t>(tag));
+ }
+
+ /**
+ * @brief Runs @p decoder over the first manifest entry matching (@p device, @p tag).
+ * @note Returns std::nullopt if no matching entry is found, or if @p decoder itself returns std::nullopt.
+ * @param device The device ID to match.
+ * @param tag The tag to match.
+ * @param decoder The decoder to run over the matching section.
+ * @return A decoded value if the section is found and the decoder succeeds; otherwise, `std::nullopt`.
+ */
+ template <typename T, typename Tag>
+ std::optional<T> decode(DeviceId device, Tag tag, const SectionDecoder<T>& decoder) const {
+ const auto found = section(device, tag);
+ return found ? decoder(*found) : std::nullopt;
+ }
+
+ /**
+ * @overload Uses #any_device_id - shorthand for a Core-owned section.
+ */
+ template <typename T, typename Tag>
+ std::optional<T> decode(Tag tag, const SectionDecoder<T>& decoder) const {
+ return decode(any_device_id, tag, decoder);
+ }
+
+ /**
+ * @brief Runs @p decoder over every manifest entry matching (@p device, @p tag) - entries @p decoder
+ * itself rejects (returns std::nullopt for) are omitted, not treated as an error.
+ * @note If no matching entries are found, an empty vector is returned.
+ *
+ * @param device The device ID to match.
+ * @param tag The tag to match.
+ * @param decoder The decoder to run over the matching sections.
+ * @return A vector of decoded values for the matching sections that the decoder accepts.
+ */
+ template <typename T, typename Tag>
+ std::vector<T> decode_all(DeviceId device, Tag tag, const SectionDecoder<T>& decoder) const {
+ std::vector<T> result;
+ for (const auto& found : sections(device, tag)) {
+ if (auto value = decoder(found)) {
+ result.push_back(std::move(*value));
+ }
+ }
+ return result;
+ }
+
+ /**
+ * @overload Uses #any_device_id - shorthand for a Core-owned section.
+ */
+ template <typename T, typename Tag>
+ std::vector<T> decode_all(Tag tag, const SectionDecoder<T>& decoder) const {
+ return decode_all(any_device_id, tag, decoder);
+ }
+
+ /**
+ * @brief Dispatches every manifest entry - Core-owned sections included - to @p handlers, in order,
+ * stopping at the first one that recognizes it. An entry no handler recognizes is silently skipped.
+ *
+ * @param handlers The list of handlers to dispatch the manifest entries to.
+ * @return The number of entries actually handled by some handler.
+ */
+ size_t read_sections(const std::vector<ISectionReaderHandler*>& handlers) const;
+
+private:
+ Reader(std::optional<ov::util::MemoryView> buffer,
+ std::istream* stream,
+ std::streampos start,
+ std::vector<ManifestEntry> manifest) noexcept
+ : m_buffer(buffer),
+ m_stream(stream),
+ m_start(start),
+ m_manifest(std::move(manifest)) {}
+
+ Section make_section(const ManifestEntry& entry) const;
+
+ std::optional<Section> section_by_id(DeviceId device, uint32_t tag_id) const;
+ std::vector<Section> sections_by_id(DeviceId device, uint32_t tag_id) const;
+ size_t count_by_id(DeviceId device, uint32_t tag_id) const noexcept;
+
+ std::optional<ov::util::MemoryView> m_buffer; //!< set only by open(data,size)
+ std::istream* m_stream; //!< non-owning; set only by open(stream)
+ std::streampos m_start; //!< Start position of the container within #m_stream; else unused.
+ std::vector<ManifestEntry> m_manifest; //!< Parsed manifest entries.
+};
+
+} // namespace v1
+} // namespace ov::runtime::hsm
diff --git a/src/inference/sources.cmake b/src/inference/sources.cmake
index cecc244a12c..2d354fd4e96 100644
--- a/src/inference/sources.cmake
+++ b/src/inference/sources.cmake
@@ -21,6 +21,7 @@ set(OV_RUNTIME_SRCS
${CMAKE_CURRENT_LIST_DIR}/src/dev/device_id_parser.cpp
${CMAKE_CURRENT_LIST_DIR}/src/dev/exec_model_info.cpp
${CMAKE_CURRENT_LIST_DIR}/src/dev/hsm_format.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/src/dev/hsm_reader.cpp
${CMAKE_CURRENT_LIST_DIR}/src/dev/iasync_infer_request.cpp
${CMAKE_CURRENT_LIST_DIR}/src/dev/icompiled_model.cpp
${CMAKE_CURRENT_LIST_DIR}/src/dev/iplugin.cpp
diff --git a/src/inference/src/dev/hsm_reader.cpp b/src/inference/src/dev/hsm_reader.cpp
new file mode 100644
index 00000000000..45cdf81f330
--- /dev/null
+++ b/src/inference/src/dev/hsm_reader.cpp
@@ -0,0 +1,189 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/runtime/hsm_reader.hpp"
+
+#include <algorithm>
+#include <cstring>
+#include <limits>
+
+#include "openvino/util/variant_visitor.hpp"
+
+namespace ov::runtime::hsm {
+inline namespace v1 {
+
+std::optional<ov::util::MemoryView> Section::view() const noexcept {
+ if (m_entry.tag.is_inline()) {
+ return ov::util::MemoryView{reinterpret_cast<const std::byte*>(m_entry.inline_bytes.data()),
+ m_entry.inline_bytes.size()};
+ } else {
+ return std::visit(
+ ov::util::VariantVisitor{[](const auto&) -> std::optional<ov::util::MemoryView> {
+ return std::nullopt;
+ },
+ [](const ov::util::MemoryView& payload) -> std::optional<ov::util::MemoryView> {
+ return payload;
+ }},
+ m_source);
+ }
+}
+
+bool Section::read(size_t offset, size_t length, void* destination) const {
+ if (const auto total = size(); destination == nullptr || offset > total || length > total - offset) {
+ return false;
+ }
+
+ if (m_entry.tag.is_inline()) {
+ std::memcpy(destination, m_entry.inline_bytes.data() + offset, length);
+ return true;
+ } else {
+ return std::visit(ov::util::VariantVisitor{
+ [](const auto&) {
+ return false;
+ },
+ [&](const ov::util::MemoryView& payload) {
+ std::memcpy(destination, payload.data() + offset, length);
+ return true;
+ },
+ [&](const StreamSource& stream_source) {
+ auto& [stream, payload_start] = stream_source;
+ stream->seekg(payload_start + static_cast<std::streamoff>(offset));
+ return static_cast<bool>(stream->read(reinterpret_cast<char*>(destination),
+ static_cast<std::streamsize>(length)));
+ },
+ },
+ m_source);
+ }
+}
+
+namespace {
+bool entry_matches(const ManifestEntry& entry, DeviceId device, uint32_t tag_id) noexcept {
+ return entry.device == device && entry.tag.id() == tag_id;
+}
+
+// Resizes `manifest` per header.manifest_size and reads it in; a no-op read for an empty manifest.
+bool read_manifest(std::istream& stream,
+ std::streampos start,
+ const Header& header,
+ std::vector<ManifestEntry>& manifest) {
+ manifest.resize(static_cast<size_t>(header.manifest_size / sizeof(ManifestEntry)));
+ if (manifest.empty()) {
+ return true;
+ } else {
+ stream.seekg(start + static_cast<std::streamoff>(header.manifest_offset));
+ return static_cast<bool>(
+ stream.read(reinterpret_cast<char*>(manifest.data()), static_cast<std::streamsize>(header.manifest_size)));
+ }
+}
+
+bool has_container_size_bytes(std::istream& stream, std::streampos start, const Header& header) {
+ stream.seekg(start);
+ stream.ignore(static_cast<std::streamsize>(header.container_size));
+ return stream.gcount() == static_cast<std::streamsize>(header.container_size);
+}
+
+// 32-bit size_t can't represent every SizeType value - reject oversized sections before they're constructed.
+constexpr bool section_size_fits_size_t(const ManifestEntry& entry) noexcept {
+ if constexpr (sizeof(size_t) < sizeof(SizeType)) {
+ return !entry.tag.is_pointer() || entry.size <= static_cast<SizeType>(std::numeric_limits<size_t>::max());
+ } else {
+ return true;
+ }
+}
+} // namespace
+
+std::optional<Reader> Reader::open(std::istream& stream) {
+ const auto start = stream.tellg();
+ Header header{};
+ std::vector<ManifestEntry> manifest;
+
+ if (start == std::streampos(-1) || !stream.read(reinterpret_cast<char*>(&header), sizeof(header)) ||
+ !is_valid_header_fields(header) || !read_manifest(stream, start, header, manifest) ||
+ !has_container_size_bytes(stream, start, header) ||
+ !std::all_of(manifest.begin(), manifest.end(), [&header](const ManifestEntry& entry) {
+ return is_valid_section_bounds(entry, header) && section_size_fits_size_t(entry);
+ })) {
+ return std::nullopt;
+ } else {
+ return Reader{std::nullopt, &stream, start, std::move(manifest)};
+ }
+}
+
+std::optional<Reader> Reader::open(const std::byte* data, size_t size) {
+ const ContainerView view{data, size};
+ if (!view.validate()) {
+ return std::nullopt;
+ }
+ std::vector<ManifestEntry> manifest(view.manifest_count());
+ if (!manifest.empty()) {
+ std::memcpy(manifest.data(), &view.manifest(), manifest.size() * sizeof(ManifestEntry));
+ }
+ return Reader{ov::util::MemoryView{data, size}, nullptr, std::streampos(0), std::move(manifest)};
+}
+
+std::optional<Reader> Reader::open(const uint8_t* data, size_t size) {
+ return open(reinterpret_cast<const std::byte*>(data), size);
+}
+
+Section Reader::make_section(const ManifestEntry& entry) const {
+ if (entry.tag.is_inline()) {
+ return Section{entry};
+ } else {
+ return m_buffer ? Section{entry,
+ ov::util::MemoryView{m_buffer->data() + static_cast<size_t>(entry.offset),
+ static_cast<size_t>(entry.size)}}
+ : Section{entry, *m_stream, m_start + static_cast<std::streamoff>(entry.offset)};
+ }
+}
+
+std::optional<Section> Reader::section_by_id(DeviceId device, uint32_t tag_id) const {
+ const auto found = std::find_if(m_manifest.begin(), m_manifest.end(), [device, tag_id](const auto& entry) {
+ return entry_matches(entry, device, tag_id);
+ });
+ return found != m_manifest.end() ? std::optional<Section>(make_section(*found)) : std::nullopt;
+}
+
+std::vector<Section> Reader::sections_by_id(DeviceId device, uint32_t tag_id) const {
+ std::vector<Section> result;
+ for (const auto& entry : m_manifest) {
+ if (entry_matches(entry, device, tag_id)) {
+ result.push_back(make_section(entry));
+ }
+ }
+ return result;
+}
+
+size_t Reader::count_by_id(DeviceId device, uint32_t tag_id) const noexcept {
+ return static_cast<size_t>(std::count_if(m_manifest.begin(), m_manifest.end(), [device, tag_id](const auto& entry) {
+ return entry_matches(entry, device, tag_id);
+ }));
+}
+
+size_t Reader::read_sections(const std::vector<ISectionReaderHandler*>& handlers) const {
+ size_t handled = 0;
+ for (const auto& entry : m_manifest) {
+ const auto section = make_section(entry);
+ std::optional<std::vector<std::byte>> owned; // only materialized when a zero-copy view isn't possible
+ ov::util::MemoryView view;
+ if (const auto direct = section.view()) {
+ view = *direct;
+ } else {
+ owned = section.to_bytes();
+ if (!owned) {
+ continue;
+ }
+ view = {owned->data(), owned->size()};
+ }
+ for (const auto& handler : handlers) {
+ if (handler != nullptr && handler->handle_section(entry, view)) {
+ ++handled;
+ break;
+ }
+ }
+ }
+ return handled;
+}
+
+} // namespace v1
+} // namespace ov::runtime::hsm
diff --git a/src/inference/tests/unit/CMakeLists.txt b/src/inference/tests/unit/CMakeLists.txt
index 466706148c2..72301cd5867 100644
--- a/src/inference/tests/unit/CMakeLists.txt
+++ b/src/inference/tests/unit/CMakeLists.txt
@@ -27,6 +27,7 @@ ov_add_test_target(
${CMAKE_CURRENT_SOURCE_DIR}/executor_config_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/executor_manager_tests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/hsm_format.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/hsm_reader.cpp
${CMAKE_CURRENT_SOURCE_DIR}/infer_request_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/iplugin_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/make_default_multi_threaded_test.cpp
diff --git a/src/inference/tests/unit/hsm_reader.cpp b/src/inference/tests/unit/hsm_reader.cpp
new file mode 100644
index 00000000000..ec500eb0082
--- /dev/null
+++ b/src/inference/tests/unit/hsm_reader.cpp
@@ -0,0 +1,1088 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/runtime/hsm_reader.hpp"
+
+#include <gmock/gmock.h>
+
+#include <algorithm>
+#include <cstring>
+#include <limits>
+#include <optional>
+#include <sstream>
+#include <string>
+#include <vector>
+
+namespace ov::test {
+namespace hsm = ov::runtime::hsm;
+namespace {
+
+enum class FakePluginTag : uint32_t { shard = 0 };
+
+constexpr hsm::DeviceId fake_device_id = 7;
+
+struct EntrySpec {
+ hsm::ManifestEntry entry;
+ std::string payload;
+};
+
+hsm::ManifestEntry make_inline_entry(hsm::DeviceId device, hsm::SectionTag tag, const std::vector<uint8_t>& bytes) {
+ hsm::ManifestEntry entry{};
+ entry.device = device;
+ entry.tag = tag;
+ const auto n = std::min(bytes.size(), entry.inline_bytes.size());
+ std::copy(bytes.begin(), bytes.begin() + n, entry.inline_bytes.begin());
+ return entry;
+}
+
+hsm::ManifestEntry make_pointer_entry(hsm::DeviceId device, hsm::SectionTag tag) {
+ hsm::ManifestEntry entry{};
+ entry.device = device;
+ entry.tag = tag;
+ return entry; // offset/size are filled in by make_container() once payload placement is known.
+}
+
+// The one place that works around GCC 11's -Wstringop-overread false positive on vector::insert(it, begin, end)
+template <typename Container>
+void append(std::vector<uint8_t>& dst, const Container& src) {
+ if (!src.empty()) {
+ const auto offset = dst.size();
+ dst.resize(offset + src.size());
+ std::memcpy(dst.data() + offset, src.data(), src.size());
+ }
+}
+
+std::vector<uint8_t> make_container(std::vector<EntrySpec> specs, hsm::BlobMagic magic = hsm::BlobMagic::single) {
+ std::vector<uint8_t> payloads;
+ for (auto& spec : specs) {
+ if (spec.entry.tag.is_pointer()) {
+ spec.entry.offset = sizeof(hsm::Header) + payloads.size();
+ spec.entry.size = spec.payload.size();
+ append(payloads, spec.payload);
+ }
+ }
+
+ std::vector<uint8_t> manifest(specs.size() * sizeof(hsm::ManifestEntry));
+ for (size_t i = 0; i < specs.size(); ++i) {
+ std::memcpy(manifest.data() + i * sizeof(hsm::ManifestEntry), &specs[i].entry, sizeof(hsm::ManifestEntry));
+ }
+
+ hsm::Header header{};
+ header.magic = magic;
+ header.version_major = hsm::FormatVersion::major;
+ header.version_minor = hsm::FormatVersion::minor;
+ header.manifest_offset = sizeof(hsm::Header) + payloads.size();
+ header.manifest_size = manifest.size();
+ header.container_size = header.manifest_offset + header.manifest_size;
+
+ std::vector<uint8_t> buffer(sizeof(header));
+ std::memcpy(buffer.data(), &header, sizeof(header));
+ append(buffer, payloads);
+ append(buffer, manifest);
+ return buffer;
+}
+
+std::string to_string(const std::vector<std::byte>& section) {
+ return {reinterpret_cast<const char*>(section.data()), section.size()};
+}
+
+std::string to_string(const hsm::Section& section) {
+ const auto bytes = section.to_bytes();
+ return bytes ? to_string(*bytes) : std::string{};
+}
+
+std::vector<uint8_t> make_sample_reader_container() {
+ return make_container({
+ {make_inline_entry(hsm::any_device_id, hsm::model_id_tag, {0xAA, 0xBB, 0xCC, 0xDD}), {}},
+ {make_pointer_entry(hsm::any_device_id, hsm::model_tag), "compiled-model-bytes"},
+ {make_pointer_entry(fake_device_id, hsm::SectionTag::make_device_tag(/*local_id=*/1, /*is_inline=*/false)),
+ "device-specific-payload"},
+ });
+}
+
+// Minimal ISectionReaderHandler: recognizes one (device, tag id) pair, records what it was handed.
+class RecordingHandler : public hsm::ISectionReaderHandler {
+public:
+ RecordingHandler(hsm::DeviceId device, uint32_t tag_id) : m_device(device), m_tag_id(tag_id) {}
+
+ bool handle_section(const hsm::ManifestEntry& entry, ov::util::MemoryView section) override {
+ if (entry.device != m_device || entry.tag.id() != m_tag_id) {
+ return false;
+ }
+ last_payload = {reinterpret_cast<const char*>(section.data()), section.size()};
+ ++handled_count;
+ return true;
+ }
+
+ std::string last_payload;
+ size_t handled_count = 0;
+
+private:
+ hsm::DeviceId m_device;
+ uint32_t m_tag_id;
+};
+
+// Wraps `blob` in a seekable stream, preceded by `prefix_size` unrelated bytes (to exercise that the
+// container is read relative to the stream's position at open() time, not always from offset 0).
+std::stringstream make_stream(const std::vector<uint8_t>& blob, size_t prefix_size = 0) {
+ std::stringstream stream;
+ stream.write(std::string(prefix_size, '\0').data(), static_cast<std::streamsize>(prefix_size));
+ stream.write(reinterpret_cast<const char*>(blob.data()), static_cast<std::streamsize>(blob.size()));
+ stream.seekg(static_cast<std::streamoff>(prefix_size));
+ return stream;
+}
+
+class MockStreamBuf : public std::streambuf {
+public:
+ explicit MockStreamBuf(const std::vector<uint8_t>& data) : m_real(std::string(data.begin(), data.end())) {
+ ON_CALL(*this, xsgetn).WillByDefault([this](char_type* dst, std::streamsize n) {
+ return m_real.sgetn(dst, n);
+ });
+ ON_CALL(*this, seekoff)
+ .WillByDefault([this](off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) {
+ return m_real.pubseekoff(off, dir, which);
+ });
+ ON_CALL(*this, seekpos).WillByDefault([this](pos_type pos, std::ios_base::openmode which) {
+ return m_real.pubseekpos(pos, which);
+ });
+ ON_CALL(*this, underflow).WillByDefault([this]() {
+ return m_real.sgetc();
+ });
+ ON_CALL(*this, uflow).WillByDefault([this]() {
+ return m_real.sbumpc();
+ });
+ }
+
+ MOCK_METHOD(std::streamsize, xsgetn, (char_type * dst, std::streamsize n), (override));
+ MOCK_METHOD(pos_type,
+ seekoff,
+ (off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which),
+ (override));
+ MOCK_METHOD(pos_type, seekpos, (pos_type pos, std::ios_base::openmode which), (override));
+ MOCK_METHOD(int_type, underflow, (), (override));
+ MOCK_METHOD(int_type, uflow, (), (override));
+
+private:
+ std::stringbuf m_real;
+};
+
+} // namespace
+
+// --- Section: constructed directly, without a Reader - it's a publicly exposed type on its own ----------
+
+TEST(HsmSectionTest, inline_mode_reads_directly_from_the_entry_no_source_needed) {
+ const auto entry = make_inline_entry(fake_device_id, hsm::model_id_tag, {0xAA, 0xBB, 0xCC});
+ const hsm::Section section(entry);
+
+ EXPECT_EQ(section.device(), fake_device_id);
+ EXPECT_EQ(section.tag().id(), hsm::model_id);
+ EXPECT_EQ(section.size(), entry.inline_bytes.size());
+
+ std::vector<std::byte> destination(section.size());
+ ASSERT_TRUE(section.read(destination.data()));
+ EXPECT_EQ(destination[0], std::byte{0xAA});
+}
+
+TEST(HsmSectionTest, pointer_mode_reads_from_an_explicitly_supplied_buffer) {
+ const std::string payload = "standalone-section-bytes";
+ auto entry = make_pointer_entry(fake_device_id, hsm::model_tag);
+ entry.size = payload.size();
+ const ov::util::MemoryView view{reinterpret_cast<const std::byte*>(payload.data()), payload.size()};
+ const hsm::Section section(entry, view);
+
+ const auto direct = section.view();
+ ASSERT_TRUE(direct.has_value());
+ EXPECT_EQ(to_string(std::vector<std::byte>(direct->begin(), direct->end())), payload);
+}
+
+TEST(HsmSectionTest, read_rejects_a_null_destination) {
+ const auto entry = make_inline_entry(fake_device_id, hsm::model_id_tag, {0xAA});
+ const hsm::Section section(entry);
+ EXPECT_FALSE(section.read(0, section.size(), nullptr));
+}
+
+TEST(HsmSectionTest, pointer_mode_entry_built_with_the_inline_only_constructor_has_no_source) {
+ // Misuses the public API directly: the inline-only constructor never sets a payload source, so a
+ // pointer-mode entry built this way has nothing for view()/read() to fall back on (m_source stays
+ // std::monostate).
+ auto entry = make_pointer_entry(fake_device_id, hsm::model_tag);
+ entry.size = 4;
+ const hsm::Section section(entry);
+
+ EXPECT_FALSE(section.view().has_value());
+ std::vector<std::byte> destination(4);
+ EXPECT_FALSE(section.read(destination.data()));
+ EXPECT_FALSE(section.to_bytes().has_value());
+}
+
+// --- ISectionReaderHandler: constructed directly, without a Reader driving dispatch ---------------------
+
+TEST(ISectionReaderHandlerTest, recognizes_own_device_and_tag) {
+ hsm::ManifestEntry entry{};
+ entry.device = fake_device_id;
+ entry.tag = hsm::SectionTag::make(/*id=*/42, /*is_inline=*/false);
+
+ const std::byte payload[4] = {};
+ RecordingHandler handler(fake_device_id, /*tag_id=*/42);
+ EXPECT_TRUE(handler.handle_section(entry, ov::util::MemoryView{payload, 4}));
+ EXPECT_EQ(handler.last_payload.size(), 4u);
+ EXPECT_EQ(handler.handled_count, 1u);
+}
+
+TEST(ISectionReaderHandlerTest, skips_entry_it_does_not_own) {
+ hsm::ManifestEntry entry{};
+ entry.device = fake_device_id + 1; // different device
+ entry.tag = hsm::SectionTag::make(/*id=*/42, /*is_inline=*/false);
+
+ RecordingHandler handler(fake_device_id, /*tag_id=*/42);
+ EXPECT_FALSE(handler.handle_section(entry, ov::util::MemoryView{}));
+ EXPECT_EQ(handler.handled_count, 0u); // never called
+}
+
+TEST(HsmReaderTest, open_rejects_invalid_buffer) {
+ const std::vector<uint8_t> garbage(sizeof(hsm::Header), 0xFF);
+ EXPECT_FALSE(hsm::Reader::open(garbage.data(), garbage.size()).has_value());
+}
+
+TEST(HsmReaderTest, open_rejects_a_buffer_smaller_than_the_header_itself) {
+ const std::vector<uint8_t> too_small(sizeof(hsm::Header) - 1, 0xFF);
+ EXPECT_FALSE(hsm::Reader::open(too_small.data(), too_small.size()).has_value());
+}
+
+TEST(HsmReaderTest, open_accepts_valid_container) {
+ const auto blob = make_container({});
+ EXPECT_TRUE(hsm::Reader::open(blob.data(), blob.size()).has_value());
+}
+
+TEST(HsmReaderTest, open_accepts_shared_context_magic_and_reads_its_sections) {
+ const auto blob = make_container(
+ {
+ {make_inline_entry(hsm::any_device_id, hsm::model_id_tag, {0xAA}), {}},
+ {make_pointer_entry(fake_device_id, hsm::SectionTag::make_device_tag(/*local_id=*/1, /*is_inline=*/false)),
+ "shared-context-payload"},
+ },
+ hsm::BlobMagic::multi);
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto shard = reader->section(fake_device_id, hsm::SectionTag::make_device_tag(1, false).id());
+ ASSERT_TRUE(shard.has_value());
+ EXPECT_EQ(to_string(*shard), "shared-context-payload");
+}
+
+TEST(HsmReaderTest, model_id_section_reads_inline_payload) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto section = reader->section(hsm::model_id);
+ ASSERT_TRUE(section.has_value());
+ ASSERT_EQ(section->size(), 24u); // full inline capacity - see ManifestEntry::inline_bytes
+ const auto view = section->view();
+ ASSERT_TRUE(view.has_value()); // inline is always viewable, regardless of source
+ EXPECT_EQ(static_cast<uint8_t>(view->data()[0]), 0xAA);
+}
+
+TEST(HsmReaderTest, model_section_reads_pointer_payload) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto section = reader->section(hsm::model);
+ ASSERT_TRUE(section.has_value());
+ EXPECT_EQ(to_string(*section), "compiled-model-bytes");
+}
+
+TEST(HsmReaderTest, common_sections_absent_when_manifest_is_empty) {
+ const auto blob = make_container({});
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ EXPECT_FALSE(reader->section(hsm::model_id).has_value());
+ EXPECT_FALSE(reader->section(hsm::model).has_value());
+ EXPECT_FALSE(reader->section(hsm::runtime_requirements).has_value());
+}
+
+TEST(HsmReaderTest, runtime_requirements_section_reads_opaque_payload) {
+ const auto blob = make_container({
+ {make_pointer_entry(hsm::any_device_id, hsm::runtime_requirements_tag), "req-v1"},
+ });
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto section = reader->section(hsm::runtime_requirements);
+ ASSERT_TRUE(section.has_value());
+ EXPECT_EQ(to_string(*section), "req-v1"); // reader hands back raw bytes only, never interprets content
+}
+
+TEST(HsmReaderTest, move_constructed_reader_still_reads_sections) {
+ const auto blob = make_sample_reader_container();
+ auto original = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(original.has_value());
+
+ const hsm::Reader moved(std::move(*original));
+
+ // Zero-copy view must still resolve too - the buffer moved along, not aliased via a stale copy.
+ const auto section = moved.section(hsm::model);
+ ASSERT_TRUE(section.has_value());
+ const auto view = section->view();
+ ASSERT_TRUE(view.has_value());
+ EXPECT_EQ(std::string(reinterpret_cast<const char*>(view->data()), view->size()), "compiled-model-bytes");
+}
+
+TEST(HsmReaderTest, move_assignment_replaces_existing_reader) {
+ const auto blob_a = make_sample_reader_container();
+ auto reader_a = hsm::Reader::open(blob_a.data(), blob_a.size());
+ ASSERT_TRUE(reader_a.has_value());
+
+ const auto blob_b = make_container({
+ {make_inline_entry(hsm::any_device_id, hsm::model_id_tag, {0xBB}), {}},
+ });
+ auto reader_b = hsm::Reader::open(blob_b.data(), blob_b.size());
+ ASSERT_TRUE(reader_b.has_value());
+
+ *reader_a = std::move(*reader_b);
+
+ const auto section = reader_a->section(hsm::model_id);
+ ASSERT_TRUE(section.has_value());
+ const auto view = section->view();
+ ASSERT_TRUE(view.has_value());
+ EXPECT_EQ(static_cast<uint8_t>(view->data()[0]), 0xBB);
+}
+
+TEST(HsmReaderTest, section_returns_nullopt_for_unknown_device_or_tag) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ EXPECT_FALSE(reader->section(/*device=*/42, hsm::model_id).has_value());
+ EXPECT_FALSE(reader->section(hsm::any_device_id, /*tag_id=*/12345).has_value());
+}
+
+TEST(HsmReaderTest, section_accepts_any_enum_typed_tag_with_or_without_a_device) {
+ const auto blob = make_container({
+ {make_inline_entry(hsm::any_device_id, hsm::model_id_tag, {0xAA}), {}},
+ {make_pointer_entry(fake_device_id,
+ hsm::SectionTag::make(static_cast<uint32_t>(FakePluginTag::shard),
+ /*is_inline=*/false)),
+ "plugin-shard"},
+ });
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ // Tags, device-less (implies any_device_id) - no manual static_cast at the call site.
+ EXPECT_TRUE(reader->section(hsm::Tags::model_id).has_value());
+ // Tags, with an explicit device - same template, still no cast needed.
+ EXPECT_TRUE(reader->section(hsm::any_device_id, hsm::Tags::model_id).has_value());
+ // A completely unrelated enum type (mimicking a plugin's own tag enum) - same template handles it too.
+ const auto shard = reader->section(fake_device_id, FakePluginTag::shard);
+ ASSERT_TRUE(shard.has_value());
+ EXPECT_EQ(to_string(*shard), "plugin-shard");
+}
+
+TEST(HsmReaderTest, section_returns_only_the_first_of_several_matching_entries) {
+ const auto shard_tag = hsm::SectionTag::make_device_tag(/*local_id=*/2, /*is_inline=*/false);
+ const auto blob = make_container({
+ {make_pointer_entry(fake_device_id, shard_tag), "shard-0"},
+ {make_pointer_entry(fake_device_id, shard_tag), "shard-1"},
+ });
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto section = reader->section(fake_device_id, shard_tag.id());
+ ASSERT_TRUE(section.has_value());
+ EXPECT_EQ(to_string(*section), "shard-0");
+}
+
+TEST(HsmReaderTest, sections_returns_every_matching_entry_in_manifest_order) {
+ // Nothing in the format guarantees a (device, tag) pair is unique - e.g. multiple named/indexed shards.
+ const auto shard_tag = hsm::SectionTag::make_device_tag(/*local_id=*/2, /*is_inline=*/false);
+ const auto blob = make_container({
+ {make_pointer_entry(fake_device_id, shard_tag), "shard-0"},
+ {make_pointer_entry(fake_device_id, hsm::SectionTag::make_device_tag(3, false)), "unrelated"},
+ {make_pointer_entry(fake_device_id, shard_tag), "shard-1"},
+ });
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto sections = reader->sections(fake_device_id, shard_tag.id());
+ ASSERT_EQ(sections.size(), 2u);
+ EXPECT_EQ(to_string(sections[0]), "shard-0");
+ EXPECT_EQ(to_string(sections[1]), "shard-1");
+}
+
+TEST(HsmReaderTest, sections_returns_empty_vector_when_no_entry_matches) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ EXPECT_TRUE(reader->sections(/*device=*/42, hsm::model_id).empty());
+}
+
+TEST(HsmReaderTest, sections_any_device_id_overload_matches_the_explicit_any_device_id_form) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto sections = reader->sections(hsm::model);
+ ASSERT_EQ(sections.size(), 1u);
+ EXPECT_EQ(to_string(sections[0]), "compiled-model-bytes");
+ // fake_device_id-owned tag must not surface through the any_device_id-only overload.
+ EXPECT_TRUE(reader->sections(hsm::SectionTag::make_device_tag(/*local_id=*/1, /*is_inline=*/false).id()).empty());
+}
+
+TEST(HsmReaderTest, count_matches_sections_size_without_reading_any_payload) {
+ const auto shard_tag = hsm::SectionTag::make_device_tag(/*local_id=*/2, /*is_inline=*/false);
+ const auto blob = make_container({
+ {make_pointer_entry(fake_device_id, shard_tag), "shard-0"},
+ {make_pointer_entry(fake_device_id, hsm::SectionTag::make_device_tag(3, false)), "unrelated"},
+ {make_pointer_entry(fake_device_id, shard_tag), "shard-1"},
+ });
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ EXPECT_EQ(reader->count(fake_device_id, shard_tag.id()), 2u);
+ EXPECT_EQ(reader->count(/*device=*/42, hsm::model_id), 0u);
+}
+
+TEST(HsmReaderTest, count_any_device_id_overload_matches_the_explicit_any_device_id_form) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ // model is any_device_id-owned in make_sample_reader_container() - the any_device_id-only overload
+ // must find it too, not just count(any_device_id, tag).
+ EXPECT_EQ(reader->count(hsm::model), 1u);
+ // fake_device_id owns a different tag - the any_device_id-only overload must not see it.
+ EXPECT_EQ(reader->count(hsm::SectionTag::make_device_tag(/*local_id=*/1, /*is_inline=*/false).id()), 0u);
+}
+
+TEST(HsmReaderTest, entries_gives_a_manifest_overview_without_reading_any_payload) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ ASSERT_EQ(reader->entries().size(), 3u);
+ EXPECT_EQ(reader->entries()[0].tag.id(), hsm::model_id);
+ EXPECT_EQ(reader->entries()[1].tag.id(), hsm::model);
+ EXPECT_EQ(reader->entries()[2].device, fake_device_id);
+}
+
+TEST(HsmReaderTest, read_sections_dispatches_to_matching_handler_and_skips_the_rest) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ RecordingHandler matching(fake_device_id, /*tag_id=*/hsm::core_tag_id_range_end + 1);
+ RecordingHandler unrelated(/*device=*/9, /*tag_id=*/999);
+
+ const auto handled = reader->read_sections({&unrelated, &matching});
+ EXPECT_EQ(handled, 1u);
+ EXPECT_EQ(matching.handled_count, 1u);
+ EXPECT_EQ(matching.last_payload, "device-specific-payload");
+ EXPECT_EQ(unrelated.handled_count, 0u);
+}
+
+TEST(HsmReaderTest, read_sections_can_dispatch_core_owned_entries_when_a_handler_registers_for_them) {
+ // Customization point: Core sections are ordinary entries here, not special-cased - a plugin extension
+ // may register for (any_device_id, model_id) to override/extend how that common section is handled.
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ RecordingHandler model_id_override(hsm::any_device_id, hsm::model_id);
+ EXPECT_EQ(reader->read_sections({&model_id_override}), 1u);
+ EXPECT_EQ(model_id_override.handled_count, 1u);
+}
+
+TEST(HsmReaderTest, read_sections_returns_zero_for_empty_manifest) {
+ const auto blob = make_container({});
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+ EXPECT_EQ(reader->read_sections({}), 0u);
+}
+
+// --- Section::view(): zero-copy, only when opened over an addressable buffer (pointer-mode), always for
+// inline-mode entries regardless of source -----------------------------------------------------------
+
+TEST(HsmReaderTest, section_view_points_into_the_original_buffer) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto section = reader->section(hsm::model);
+ ASSERT_TRUE(section.has_value());
+ const auto view = section->view();
+ ASSERT_TRUE(view.has_value());
+ EXPECT_EQ(std::string(reinterpret_cast<const char*>(view->data()), view->size()), "compiled-model-bytes");
+
+ const auto* blob_begin = reinterpret_cast<const std::byte*>(blob.data());
+ const auto* blob_end = blob_begin + blob.size();
+ EXPECT_GE(view->data(), blob_begin);
+ EXPECT_LE(view->data() + view->size(), blob_end);
+}
+
+TEST(HsmReaderTest, section_view_available_even_for_inline_entries) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto section = reader->section(hsm::model_id);
+ ASSERT_TRUE(section.has_value());
+ const auto view = section->view();
+ ASSERT_TRUE(view.has_value());
+ ASSERT_EQ(view->size(), 24u);
+ EXPECT_EQ(static_cast<uint8_t>(view->data()[0]), 0xAA);
+}
+
+// --- Section::read(): section()/view() are whole-section only; this is for reading arbitrary ranges one
+// at a time, deciding what's next from what a previous call already returned --------------------------
+
+TEST(HsmReaderTest, section_read_reads_a_slice_of_a_pointer_mode_section) {
+ const std::string payload = "compiled-model-bytes";
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto section = reader->section(hsm::model);
+ ASSERT_TRUE(section.has_value());
+
+ std::vector<std::byte> destination(5);
+ ASSERT_TRUE(section->read(9, 5, destination.data()));
+ EXPECT_EQ(to_string(destination), payload.substr(9, 5));
+}
+
+TEST(HsmReaderTest, section_read_rejects_a_window_exceeding_the_section_size) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto section = reader->section(hsm::model);
+ ASSERT_TRUE(section.has_value());
+
+ std::vector<std::byte> destination(section->size());
+ EXPECT_FALSE(section->read(1, section->size(), destination.data()));
+ EXPECT_FALSE(section->read(section->size() + 1, 0, destination.data()));
+}
+
+TEST(HsmReaderTest, section_read_supports_several_calls_with_the_same_decoder) {
+ const std::string payload = "compiled-model-bytes";
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto section = reader->section(hsm::model);
+ ASSERT_TRUE(section.has_value());
+
+ struct Piece {
+ std::string bytes;
+ };
+ const hsm::SectionDecoder<Piece> decode_piece = [](const hsm::Section& s) -> std::optional<Piece> {
+ // Same decoder shape whether it's given the whole section (via view()/read()) or, as here, asked
+ // to decode only a range read into a caller-owned buffer.
+ std::vector<std::byte> bytes(s.size());
+ return s.read(bytes.data()) ? std::make_optional(Piece{to_string(bytes)}) : std::nullopt;
+ };
+
+ // Simulates deciding what to read next from what was already decoded - same decoder, two ranges.
+ std::vector<std::byte> head_bytes(9);
+ ASSERT_TRUE(section->read(0, 9, head_bytes.data()));
+ EXPECT_EQ(to_string(head_bytes), payload.substr(0, 9));
+
+ std::vector<std::byte> tail_bytes(5);
+ ASSERT_TRUE(section->read(9, 5, tail_bytes.data()));
+ EXPECT_EQ(to_string(tail_bytes), payload.substr(9, 5));
+
+ // The same decoder also still works when run through the reader, over the whole section, unchanged.
+ const auto whole = reader->decode(hsm::model, decode_piece);
+ ASSERT_TRUE(whole.has_value());
+ EXPECT_EQ(whole->bytes, payload);
+}
+
+TEST(HsmReaderTest, section_read_works_for_inline_entries) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto section = reader->section(hsm::model_id);
+ ASSERT_TRUE(section.has_value());
+
+ std::byte first_byte{};
+ ASSERT_TRUE(section->read(0, 1, &first_byte));
+ EXPECT_EQ(static_cast<uint8_t>(first_byte), 0xAA);
+}
+
+// --- decode()/decode_all(): the same SectionDecoder<T> works whether the reader is buffer- or
+// stream-backed - see HsmReaderStreamTest.decode_falls_back_to_read_when_no_view_is_available -----------
+
+TEST(HsmReaderTest, decode_uses_the_zero_copy_view_when_one_is_available) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const auto* blob_begin = reinterpret_cast<const std::byte*>(blob.data());
+ const auto* blob_end = blob_begin + blob.size();
+ // Exercises make_section_decoder()'s zero-copy path: parse receives the section's own view
+ // unchanged, still pointing inside the original buffer - not a copy routed through to_bytes().
+ const auto decode_as_view = hsm::make_section_decoder<ov::util::MemoryView>([](ov::util::MemoryView view) {
+ return std::make_optional(view);
+ });
+
+ const auto decoded = reader->decode(hsm::model, decode_as_view);
+ ASSERT_TRUE(decoded.has_value());
+ EXPECT_EQ(std::string(reinterpret_cast<const char*>(decoded->data()), decoded->size()), "compiled-model-bytes");
+ EXPECT_GE(decoded->data(), blob_begin);
+ EXPECT_LE(decoded->data() + decoded->size(), blob_end);
+}
+
+TEST(HsmReaderTest, decode_returns_nullopt_for_unknown_tag) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const hsm::SectionDecoder<int> decode_length = [](const hsm::Section& section) {
+ return std::make_optional(static_cast<int>(section.size()));
+ };
+ EXPECT_FALSE(reader->decode(/*device=*/42, hsm::model_id, decode_length).has_value());
+}
+
+TEST(HsmReaderTest, decode_with_an_explicit_device_finds_a_device_owned_section) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const hsm::SectionDecoder<std::string> decode_bytes = [](const hsm::Section& section) {
+ const auto view = section.view();
+ return view ? std::make_optional(std::string(reinterpret_cast<const char*>(view->data()), view->size()))
+ : std::nullopt;
+ };
+
+ const auto decoded = reader->decode(fake_device_id,
+ hsm::SectionTag::make_device_tag(/*local_id=*/1, /*is_inline=*/false).id(),
+ decode_bytes);
+ ASSERT_TRUE(decoded.has_value());
+ EXPECT_EQ(*decoded, "device-specific-payload");
+}
+
+TEST(HsmReaderTest, decode_all_returns_every_matching_entry_decoded_in_order) {
+ const auto shard_tag = hsm::SectionTag::make_device_tag(/*local_id=*/2, /*is_inline=*/false);
+ const auto blob = make_container({
+ {make_pointer_entry(fake_device_id, shard_tag), "shard-0"},
+ {make_pointer_entry(fake_device_id, shard_tag), "shard-1"},
+ });
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const hsm::SectionDecoder<std::string> decode_shard = [](const hsm::Section& section) {
+ const auto view = section.view();
+ return view ? std::make_optional(std::string(reinterpret_cast<const char*>(view->data()), view->size()))
+ : std::nullopt;
+ };
+
+ const auto shards = reader->decode_all(fake_device_id, shard_tag.id(), decode_shard);
+ ASSERT_EQ(shards.size(), 2u);
+ EXPECT_EQ(shards[0], "shard-0");
+ EXPECT_EQ(shards[1], "shard-1");
+}
+
+TEST(HsmReaderTest, decode_all_returns_an_empty_vector_when_nothing_matches) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const hsm::SectionDecoder<std::string> decode_bytes = [](const hsm::Section&) {
+ return std::make_optional(std::string{});
+ };
+
+ EXPECT_TRUE(reader->decode_all(/*device=*/42, hsm::model_id, decode_bytes).empty());
+}
+
+TEST(HsmReaderTest, decode_all_any_device_id_overload_matches_the_explicit_any_device_id_form) {
+ const auto blob = make_sample_reader_container();
+ const auto reader = hsm::Reader::open(blob.data(), blob.size());
+ ASSERT_TRUE(reader.has_value());
+
+ const hsm::SectionDecoder<std::string> decode_bytes = [](const hsm::Section& section) {
+ const auto view = section.view();
+ return view ? std::make_optional(std::string(reinterpret_cast<const char*>(view->data()), view->size()))
+ : std::nullopt;
+ };
+
+ const auto decoded = reader->decode_all(hsm::model, decode_bytes);
+ ASSERT_EQ(decoded.size(), 1u);
+ EXPECT_EQ(decoded[0], "compiled-model-bytes");
+}
+
+// --- Negative tests (Story 2 DoD: invalid header, invalid manifest, invalid offsets, unsupported
+// runtime requirements all reject at Reader::open(), before any section can be read) ------------------
+
+TEST(HsmReaderTest, rejects_invalid_header_magic) {
+ auto blob = make_container({});
+ blob[0] = 'X'; // corrupt magic
+ EXPECT_FALSE(hsm::Reader::open(blob.data(), blob.size()).has_value());
+}
+
+TEST(HsmReaderTest, rejects_invalid_manifest_offset) {
+ auto blob = make_sample_reader_container();
+ auto header = hsm::Header::view(blob.data());
+ header.manifest_offset = sizeof(hsm::Header) - 1; // would start inside the header itself
+ std::memcpy(blob.data(), &header, sizeof(header));
+
+ EXPECT_FALSE(hsm::Reader::open(blob.data(), blob.size()).has_value());
+}
+
+TEST(HsmReaderTest, rejects_invalid_section_offset) {
+ auto blob = make_sample_reader_container();
+ const auto header = hsm::Header::view(blob.data());
+
+ // Second manifest entry is the pointer-mode "model" tag; corrupt its offset out of bounds.
+ const auto model_entry_offset = header.manifest_offset + sizeof(hsm::ManifestEntry);
+ hsm::ManifestEntry entry{};
+ std::memcpy(&entry, blob.data() + model_entry_offset, sizeof(entry));
+ entry.offset = blob.size() + 1;
+ std::memcpy(blob.data() + model_entry_offset, &entry, sizeof(entry));
+
+ EXPECT_FALSE(hsm::Reader::open(blob.data(), blob.size()).has_value());
+}
+
+TEST(HsmReaderTest, rejects_container_with_out_of_bounds_runtime_requirements) {
+ auto blob = make_container({
+ {make_pointer_entry(hsm::any_device_id, hsm::runtime_requirements_tag), "req"},
+ });
+ auto header = hsm::Header::view(blob.data());
+ hsm::ManifestEntry entry{};
+ std::memcpy(&entry, blob.data() + header.manifest_offset, sizeof(entry));
+ entry.size = std::numeric_limits<hsm::SizeType>::max(); // unsupported: payload can't possibly fit
+ std::memcpy(blob.data() + header.manifest_offset, &entry, sizeof(entry));
+
+ EXPECT_FALSE(hsm::Reader::open(blob.data(), blob.size()).has_value());
+}
+
+TEST(HsmReaderTest, rejects_buffer_smaller_than_container_size) {
+ const auto blob = make_sample_reader_container();
+ // One byte short of what Header::container_size actually claims for this blob.
+ EXPECT_FALSE(hsm::Reader::open(blob.data(), blob.size() - 1).has_value());
+}
+
+TEST(HsmReaderTest, rejects_mismatched_major_version) {
+ auto blob = make_sample_reader_container();
+ auto header = hsm::Header::view(blob.data());
+ header.version_major = hsm::FormatVersion::major + 1;
+ std::memcpy(blob.data(), &header, sizeof(header));
+
+ EXPECT_FALSE(hsm::Reader::open(blob.data(), blob.size()).has_value());
+}
+
+TEST(HsmReaderTest, accepts_container_with_different_minor_version) {
+ // Only version_major is part of the compatibility contract - a minor-version bump must stay readable.
+ auto blob = make_sample_reader_container();
+ auto header = hsm::Header::view(blob.data());
+ header.version_minor = hsm::FormatVersion::minor + 1;
+ std::memcpy(blob.data(), &header, sizeof(header));
+
+ EXPECT_TRUE(hsm::Reader::open(blob.data(), blob.size()).has_value());
+}
+
+// --- Reader over a std::istream& source: same class, same output type, just a different open() -------
+
+TEST(HsmReaderStreamTest, open_rejects_invalid_stream) {
+ auto blob = make_container({});
+ blob[0] = 'X'; // corrupt magic
+ auto stream = make_stream(blob);
+ EXPECT_FALSE(hsm::Reader::open(stream).has_value());
+}
+
+TEST(HsmReaderStreamTest, open_rejects_a_stream_already_in_a_failed_state) {
+ std::stringstream stream;
+ stream.setstate(std::ios::failbit);
+ EXPECT_FALSE(hsm::Reader::open(stream).has_value());
+}
+
+TEST(HsmReaderStreamTest, open_accepts_valid_container_at_nonzero_stream_position) {
+ const auto blob = make_sample_reader_container();
+ auto stream = make_stream(blob, /*prefix_size=*/16);
+ const auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+}
+
+TEST(HsmReaderStreamTest, open_accepts_shared_context_magic_and_reads_its_sections) {
+ const auto blob = make_container(
+ {
+ {make_pointer_entry(fake_device_id, hsm::SectionTag::make_device_tag(/*local_id=*/1, /*is_inline=*/false)),
+ "shared-context-payload"},
+ },
+ hsm::BlobMagic::multi);
+ auto stream = make_stream(blob);
+ const auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+
+ const auto shard = reader->section(fake_device_id, hsm::SectionTag::make_device_tag(1, false).id());
+ ASSERT_TRUE(shard.has_value());
+ EXPECT_EQ(to_string(*shard), "shared-context-payload");
+}
+
+TEST(HsmReaderStreamTest, model_id_and_model_sections_read_correctly) {
+ const auto blob = make_sample_reader_container();
+ auto stream = make_stream(blob);
+ const auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+
+ const auto model_id = reader->section(hsm::model_id);
+ ASSERT_TRUE(model_id.has_value());
+ ASSERT_EQ(model_id->size(), 24u);
+ const auto model_id_view = model_id->view(); // inline - always viewable, even without a buffer
+ ASSERT_TRUE(model_id_view.has_value());
+ EXPECT_EQ(static_cast<uint8_t>(model_id_view->data()[0]), 0xAA);
+
+ const auto model = reader->section(hsm::model);
+ ASSERT_TRUE(model.has_value());
+ EXPECT_EQ(to_string(*model), "compiled-model-bytes");
+}
+
+TEST(HsmReaderStreamTest, section_read_reads_only_the_requested_slice_without_a_buffer) {
+ const std::string payload = "compiled-model-bytes";
+ const auto blob = make_sample_reader_container();
+ auto stream = make_stream(blob);
+ const auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+
+ // view() has no zero-copy option here (no addressable buffer) - read() is the only way to get part of
+ // a section without also reading (or allocating for) the rest.
+ const auto section = reader->section(hsm::model);
+ ASSERT_TRUE(section.has_value());
+ EXPECT_FALSE(section->view().has_value());
+
+ std::vector<std::byte> destination(5);
+ ASSERT_TRUE(section->read(9, 5, destination.data()));
+ EXPECT_EQ(to_string(destination), payload.substr(9, 5));
+}
+
+TEST(HsmReaderStreamTest, section_read_supports_repeated_calls_without_a_buffer) {
+ const std::string payload = "compiled-model-bytes";
+ const auto blob = make_sample_reader_container();
+ auto stream = make_stream(blob);
+ const auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+
+ const auto section = reader->section(hsm::model);
+ ASSERT_TRUE(section.has_value());
+
+ // Read the first 9 bytes, decide (at "runtime") what to read next, then read the rest - without ever
+ // materializing the whole section up front.
+ std::vector<std::byte> head(9);
+ ASSERT_TRUE(section->read(0, 9, head.data()));
+ EXPECT_EQ(to_string(head), payload.substr(0, 9));
+
+ std::vector<std::byte> rest(payload.size() - 9);
+ ASSERT_TRUE(section->read(9, rest.size(), rest.data()));
+ EXPECT_EQ(to_string(rest), payload.substr(9));
+}
+
+TEST(HsmReaderStreamTest, section_outlives_the_reader_it_came_from) {
+ const std::string payload = "compiled-model-bytes";
+ const auto blob = make_sample_reader_container();
+ auto stream = make_stream(blob);
+
+ std::optional<hsm::Section> section;
+ {
+ auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+ section = reader->section(hsm::model);
+ ASSERT_TRUE(section.has_value());
+ } // `reader` is destroyed here - `section` must not depend on it, only on `stream`.
+
+ std::vector<std::byte> destination(5);
+ ASSERT_TRUE(section->read(9, 5, destination.data()));
+ EXPECT_EQ(to_string(destination), payload.substr(9, 5));
+}
+
+TEST(HsmReaderStreamTest, decode_falls_back_to_read_when_no_view_is_available) {
+ const auto blob = make_sample_reader_container();
+ auto stream = make_stream(blob);
+ const auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+
+ struct ModelData {
+ std::string bytes;
+ };
+ // Exercises make_section_decoder()'s fallback path: no addressable buffer here, so it must
+ // resolve via Section::to_bytes() instead of view() - same parse callback either way.
+ const auto decode_model = hsm::make_section_decoder<ModelData>([](ov::util::MemoryView view) {
+ return std::make_optional(ModelData{std::string(reinterpret_cast<const char*>(view.data()), view.size())});
+ });
+
+ const auto decoded = reader->decode(hsm::model, decode_model);
+ ASSERT_TRUE(decoded.has_value());
+ EXPECT_EQ(decoded->bytes, "compiled-model-bytes");
+}
+
+TEST(HsmReaderStreamTest, move_constructed_reader_still_reads_sections) {
+ const auto blob = make_sample_reader_container();
+ auto stream = make_stream(blob);
+ auto original = hsm::Reader::open(stream);
+ ASSERT_TRUE(original.has_value());
+
+ const hsm::Reader moved(std::move(*original));
+
+ const auto section = moved.section(hsm::model);
+ ASSERT_TRUE(section.has_value());
+ EXPECT_EQ(to_string(*section), "compiled-model-bytes");
+}
+
+TEST(HsmReaderStreamTest, move_assignment_replaces_existing_reader) {
+ const auto blob_a = make_sample_reader_container();
+ auto stream_a = make_stream(blob_a);
+ auto reader_a = hsm::Reader::open(stream_a);
+ ASSERT_TRUE(reader_a.has_value());
+
+ const auto blob_b = make_container({
+ {make_inline_entry(hsm::any_device_id, hsm::model_id_tag, {0xBB}), {}},
+ });
+ auto stream_b = make_stream(blob_b);
+ auto reader_b = hsm::Reader::open(stream_b);
+ ASSERT_TRUE(reader_b.has_value());
+
+ *reader_a = std::move(*reader_b);
+
+ const auto section = reader_a->section(hsm::model_id);
+ ASSERT_TRUE(section.has_value());
+ const auto view = section->view();
+ ASSERT_TRUE(view.has_value());
+ EXPECT_EQ(static_cast<uint8_t>(view->data()[0]), 0xBB);
+}
+
+TEST(HsmReaderStreamTest, view_siblings_work_for_inline_but_not_pointer_mode_entries) {
+ const auto blob = make_sample_reader_container();
+ auto stream = make_stream(blob);
+ const auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+
+ const auto model_id = reader->section(hsm::model_id);
+ ASSERT_TRUE(model_id.has_value());
+ const auto model_id_view = model_id->view();
+ ASSERT_TRUE(model_id_view.has_value());
+ ASSERT_EQ(model_id_view->size(), 24u);
+ EXPECT_EQ(static_cast<uint8_t>(model_id_view->data()[0]), 0xAA);
+
+ const auto model = reader->section(hsm::model);
+ ASSERT_TRUE(model.has_value());
+ EXPECT_FALSE(model->view().has_value());
+}
+
+TEST(HsmReaderStreamTest, common_sections_absent_when_manifest_is_empty) {
+ const auto blob = make_container({});
+ auto stream = make_stream(blob);
+ const auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+
+ EXPECT_FALSE(reader->section(hsm::model_id).has_value());
+ EXPECT_FALSE(reader->section(hsm::model).has_value());
+ EXPECT_FALSE(reader->section(hsm::runtime_requirements).has_value());
+}
+
+TEST(HsmReaderStreamTest, sections_returns_every_matching_entry) {
+ const auto shard_tag = hsm::SectionTag::make_device_tag(/*local_id=*/2, /*is_inline=*/false);
+ const auto blob = make_container({
+ {make_pointer_entry(fake_device_id, shard_tag), "shard-0"},
+ {make_pointer_entry(fake_device_id, shard_tag), "shard-1"},
+ });
+ auto stream = make_stream(blob);
+ const auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+
+ const auto sections = reader->sections(fake_device_id, shard_tag.id());
+ ASSERT_EQ(sections.size(), 2u);
+ EXPECT_EQ(to_string(sections[0]), "shard-0");
+ EXPECT_EQ(to_string(sections[1]), "shard-1");
+}
+
+TEST(HsmReaderStreamTest, read_sections_dispatches_same_handler_type_as_memory_backed_reader) {
+ const auto blob = make_sample_reader_container();
+ auto stream = make_stream(blob);
+ const auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+
+ RecordingHandler extension(fake_device_id, /*tag_id=*/hsm::core_tag_id_range_end + 1);
+ EXPECT_EQ(reader->read_sections({&extension}), 1u);
+ EXPECT_EQ(extension.last_payload, "device-specific-payload");
+}
+
+TEST(HsmReaderStreamTest, read_sections_skips_an_entry_whose_bounds_validate_but_whose_read_fails) {
+ const auto blob = make_container({
+ {make_pointer_entry(fake_device_id, hsm::SectionTag::make_device_tag(1, false)), "unreadable-payload"},
+ });
+ ::testing::NiceMock<MockStreamBuf> buf(blob);
+ {
+ ::testing::InSequence seq;
+ EXPECT_CALL(buf, xsgetn).Times(2); // open()'s header + manifest reads
+ EXPECT_CALL(buf, xsgetn).WillOnce(::testing::Return(0)); // the one payload read this test targets
+ EXPECT_CALL(buf, xsgetn).Times(::testing::AnyNumber());
+ }
+ std::istream stream(&buf);
+ const auto reader = hsm::Reader::open(stream);
+ ASSERT_TRUE(reader.has_value());
+
+ RecordingHandler handler(fake_device_id,
+ hsm::SectionTag::make_device_tag(/*local_id=*/1, /*is_inline=*/false).id());
+ EXPECT_EQ(reader->read_sections({&handler}), 0u);
+ EXPECT_EQ(handler.handled_count, 0u);
+}
+
+TEST(HsmReaderStreamTest, rejects_invalid_manifest_offset) {
+ auto blob = make_sample_reader_container();
+ auto header = hsm::Header::view(blob.data());
+ header.manifest_offset = sizeof(hsm::Header) - 1; // would start inside the header itself
+ header.container_size = blob.size(); // ensure container_size is consistent with the actual blob size
+ std::memcpy(blob.data(), &header, sizeof(header));
+
+ auto stream = make_stream(blob);
+ EXPECT_FALSE(hsm::Reader::open(stream).has_value());
+}
+
+TEST(HsmReaderStreamTest, rejects_container_size_exceeding_available_stream_bytes) {
+ auto blob = make_sample_reader_container();
+ auto header = hsm::Header::view(blob.data());
+ header.container_size += 100; // claims more bytes than the stream actually holds
+ std::memcpy(blob.data(), &header, sizeof(header));
+
+ auto stream = make_stream(blob); // not padded to match the inflated container_size
+ EXPECT_FALSE(hsm::Reader::open(stream).has_value());
+}
+
+TEST(HsmReaderStreamTest, rejects_invalid_section_offset) {
+ auto blob = make_sample_reader_container();
+ const auto header = hsm::Header::view(blob.data());
+
+ // Second manifest entry is the pointer-mode "model" tag; corrupt its offset out of bounds.
+ const auto model_entry_offset = header.manifest_offset + sizeof(hsm::ManifestEntry);
+ hsm::ManifestEntry entry{};
+ std::memcpy(&entry, blob.data() + model_entry_offset, sizeof(entry));
+ entry.offset = blob.size() + 1;
+ std::memcpy(blob.data() + model_entry_offset, &entry, sizeof(entry));
+
+ auto stream = make_stream(blob);
+ EXPECT_FALSE(hsm::Reader::open(stream).has_value());
+}
+
+TEST(HsmReaderStreamTest, rejects_mismatched_major_version) {
+ auto blob = make_sample_reader_container();
+ auto header = hsm::Header::view(blob.data());
+ header.version_major = hsm::FormatVersion::major + 1;
+ std::memcpy(blob.data(), &header, sizeof(header));
+
+ auto stream = make_stream(blob);
+ EXPECT_FALSE(hsm::Reader::open(stream).has_value());
+}
+
+TEST(HsmReaderStreamTest, accepts_container_with_different_minor_version) {
+ auto blob = make_sample_reader_container();
+ auto header = hsm::Header::view(blob.data());
+ header.version_minor = hsm::FormatVersion::minor + 1;
+ std::memcpy(blob.data(), &header, sizeof(header));
+
+ auto stream = make_stream(blob);
+ EXPECT_TRUE(hsm::Reader::open(stream).has_value());
+}
+
+} // namespace ov::test