OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[core] Add HSM Writer and Deferred Writer Implementation (#38567)
Pawel Raasz75e1da6f6ac3
diff --git a/src/inference/dev_api/openvino/runtime/hsm_deferred_writer.hpp b/src/inference/dev_api/openvino/runtime/hsm_deferred_writer.hppnew file mode 100644index 00000000000..ba36799a4ca--- /dev/null+++ b/src/inference/dev_api/openvino/runtime/hsm_deferred_writer.hpp@@ -0,0 +1,158 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <memory>+#include <optional>+#include <ostream>+#include <system_error>+#include <variant>+#include <vector>++#include "openvino/runtime/common.hpp"+#include "openvino/runtime/hsm_format.hpp"+#include "openvino/runtime/hsm_writer.hpp"++namespace ov::runtime::hsm {+inline namespace v1 {++/**+ * @brief Writer that accumulates sections as lightweight descriptors and writes them all at #finalize() -+ * #add_section() borrows @p payload (keep it alive until then); for a transient source, use an+ * #ISectionEncoder instead (see #add_section()'s encoder overload) - the writer itself never holds an+ * owned payload buffer.+ * @note When every section's size is known up front, the header is computed in one pure pass and written+ * first - no seeking back. Using the unsized overload of #add_section() (size only known after encoding)+ * forces the destination to be revisited once, after every real size is known - see #open(std::ostream&).+ */+class OPENVINO_RUNTIME_API DeferredWriter final : public IWriter {+public:+ /**+ * @brief Opens a DeferredWriter that writes into the given output stream.+ *+ * @param stream The output stream to write into. Must remain valid until #finalize() is called, and+ * be seekable - needed both to retry after a thrown exception and to revisit the destination when+ * the unsized overload of #add_section() is used.+ * @return A DeferredWriter instance if the stream is usable; std::nullopt otherwise.+ */+ static std::optional<DeferredWriter> open(std::ostream& stream);++ /**+ * @brief Opens a DeferredWriter that writes into the given preallocated buffer.+ *+ * @param dst The preallocated buffer to write into. Must remain valid until #finalize() is called.+ * @param size The size of the preallocated buffer in bytes.+ * @return A DeferredWriter instance if the buffer is usable; std::nullopt otherwise.+ */+ static std::optional<DeferredWriter> open(std::byte* dst, size_t size);++ /// @note Move-only: copying would silently duplicate owned/generated section payloads.+ DeferredWriter(const DeferredWriter&) = delete;+ DeferredWriter& operator=(const DeferredWriter&) = delete;+ DeferredWriter(DeferredWriter&&) noexcept = default;+ DeferredWriter& operator=(DeferredWriter&&) noexcept = default;++ bool add_section(DeviceId device,+ SectionTagReserved tag,+ ov::util::MemoryView payload,+ SectionAlignment align = {}) override;+ bool add_section(DeviceId device,+ SectionTagReserved tag,+ size_t size,+ SectionEncoderPtr encoder,+ SectionAlignment align = {}) override;+ bool add_section(DeviceId device,+ SectionTagReserved tag,+ SectionEncoderPtr encoder,+ SectionAlignment align = {}) override;++ /**+ * @brief See #IWriter::finalize().+ *+ * @return A repeated call after success, or after a normal (non-throwing) failure, just reports the+ * same outcome again. A repeated call after a thrown exception instead retries the whole attempt+ * from the container's start - each #ISectionEncoder may run again.+ */+ std::error_code finalize() override;++private:+ explicit DeferredWriter(std::ostream& stream) noexcept;+ DeferredWriter(std::byte* dst, size_t capacity) noexcept;++ // A section produced on demand at finalize() time - its size is known up front.+ struct PendingEncode {+ size_t size;+ SectionEncoderPtr encoder;+ };++ // One queued, not-yet-written section; `align` is already resolved to concrete powers of two. Field+ // order (largest-alignment-first) keeps padding to just the trailing (device, tag) pair. A bare+ // ISectionEncoder alternative means the unsized overload was used - size discovered only after it runs.+ struct PendingSection {+ SectionAlignment align;+ std::variant<ov::util::MemoryView, PendingEncode, SectionEncoderPtr> payload;+ DeviceId device;+ SectionTagReserved tag;++ PendingSection(SectionAlignment align, ov::util::MemoryView payload, DeviceId device, SectionTagReserved tag);+ PendingSection(SectionAlignment align, PendingEncode payload, DeviceId device, SectionTagReserved tag);+ PendingSection(SectionAlignment align, SectionEncoderPtr payload, DeviceId device, SectionTagReserved tag);+ };++ // Where bytes actually go - a stream (own running size tracked, since a stream has no addressable+ // pointer to fill directly) or a caller-owned fixed buffer (additionally tracks capacity and a+ // sticky failure flag once it runs out of room). A raw pointer, not a reference, so this stays+ // assignable when held in m_destination below.+ struct StreamDestination {+ std::ostream* stream = nullptr; // destination stream+ std::streampos start{}; // container's first byte, captured once at open()+ size_t size = 0; // bytes written so far (the write cursor)+ };+ struct BufferDestination {+ std::byte* dst = nullptr; // destination buffer+ size_t capacity = 0; // total usable bytes in dst+ size_t size = 0; // bytes written so far (the write cursor)+ bool good = true; // false once a write has failed (sticky)+ };++ static std::optional<size_t> reserve(BufferDestination& destination, size_t extra);++ void write(ov::util::MemoryView data);+ void write_zeros(size_t count);+ void patch(size_t offset, ov::util::MemoryView data);+ size_t written_size() const;+ bool destination_good() const;+ void reset_destination();+ void fail_destination();++ static void write_into(StreamDestination& destination, ov::util::MemoryView data);+ static void write_into(BufferDestination& destination, ov::util::MemoryView data);+ static void patch_into(StreamDestination& destination, size_t offset, ov::util::MemoryView data);+ static void patch_into(BufferDestination& destination, size_t offset, ov::util::MemoryView data);+ static bool is_good(const StreamDestination& destination);+ static bool is_good(const BufferDestination& destination);++ ManifestEntry write_section(DeviceId device,+ SectionTagReserved tag,+ SectionAlignment alignment,+ ov::util::MemoryView payload);+ ManifestEntry write_section(DeviceId device,+ SectionTagReserved tag,+ SectionAlignment alignment,+ const PendingEncode& payload);+ ManifestEntry write_section(DeviceId device,+ SectionTagReserved tag,+ SectionAlignment alignment,+ const SectionEncoderPtr& encoder);++ std::variant<StreamDestination, BufferDestination> m_destination;+ std::vector<PendingSection> m_sections;+ std::optional<std::error_code> m_result;+ bool m_has_unsized_section;+};++} // namespace v1+} // namespace ov::runtime::hsmdiff --git a/src/inference/dev_api/openvino/runtime/hsm_format.hpp b/src/inference/dev_api/openvino/runtime/hsm_format.hppindex 86551f02b16..98295f1adc3 100644--- a/src/inference/dev_api/openvino/runtime/hsm_format.hpp+++ b/src/inference/dev_api/openvino/runtime/hsm_format.hpp@@ -196,6 +196,28 @@ struct SectionTag {}};+/**+ * @brief #SectionTag plus its 4 reserved bytes (#ManifestEntry::tag_reserved). Implicitly convertible+ * from a bare #SectionTag (reserved bytes default to zero), so existing #IWriter::add_section() callers+ * are unaffected - only a caller whose `(device, tag)` pair redefines #ManifestEntry::tag_reserved's+ * meaning needs to construct one explicitly.+ * @note Never part of `(device, tag)` dispatch - see #SectionTag's unknown-tag rule; opaque sub-dispatch+ * data for the handler that already owns the pair, nothing more.+ */+struct SectionTagReserved {+ SectionTag tag;+ std::array<uint8_t, 4> bytes;++ constexpr SectionTagReserved(SectionTag tag, std::array<uint8_t, 4> bytes = {}) noexcept : tag(tag), bytes(bytes) {}++ constexpr bool is_inline() const noexcept {+ return tag.is_inline();+ }+ constexpr bool is_pointer() const noexcept {+ return tag.is_pointer();+ }+};+/*** @brief Core-owned HSM tag identifiers - explicit wire values so reordering is safe; never change or reuse a* value once shipped. #sentinel_count auto-tracks the count and must stay last.diff --git a/src/inference/dev_api/openvino/runtime/hsm_writer.hpp b/src/inference/dev_api/openvino/runtime/hsm_writer.hppnew file mode 100644index 00000000000..1aea4e597c4--- /dev/null+++ b/src/inference/dev_api/openvino/runtime/hsm_writer.hpp@@ -0,0 +1,198 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <cstdint>+#include <functional>+#include <memory>+#include <system_error>+#include <utility>+#include <vector>++#include "openvino/runtime/common.hpp"+#include "openvino/runtime/hsm_format.hpp"++namespace ov::runtime::hsm {+inline namespace v1 {++/**+ * @brief Callback handed to #ISectionEncoder::encode() for storing its content. Call it as many times as+ * convenient - each call goes straight to the final destination, so a caller already holding a contiguous+ * source can store it in one call, and a caller producing data incrementally never has to materialize+ * more than one chunk at a time; the writer itself never buffers a whole section on your behalf.+ */+using SectionSink = std::function<void(ov::util::MemoryView data)>;++/**+ * @brief Produces a section's content on demand: call @p sink as many times as convenient. Zero-copy+ * for a fixed-buffer destination (each call writes straight into it); for a stream destination, each call+ * writes straight to the stream too - never a whole-section staging buffer, regardless of size.+ * @note One interface covers both #IWriter::add_section() overloads that take it: given a known size,+ * the calls must sum to exactly that many bytes; without one, the writer measures however many bytes+ * they turn out to be - see that overload's docs for what that implies for the destination.+ */+class ISectionEncoder {+public:+ virtual ~ISectionEncoder() = default;++ /**+ * @brief Writes this section's content to @p sink.+ * @note Runs later, at #IWriter::finalize() time, not when passed to #IWriter::add_section() - any+ * state read here must outlive finalize().+ */+ virtual void encode(const SectionSink& sink) const = 0;+};++/**+ * @brief Owning handle to an #ISectionEncoder. Shared, not exclusive: a caller that already built and+ * holds a long-lived encoder can pass the same instance to multiple #IWriter::add_section() calls+ * (across one writer or several) instead of rebuilding a throwaway one each time.+ */+using SectionEncoderPtr = std::shared_ptr<ISectionEncoder>;++/**+ * @brief Pointer-mode start-offset and reserved-slot-size alignment for a section (ignored for inline-mode).+ * @p offset_align: `0` and `1` are equivalent (no alignment); anything else must be a power of two.+ * @p size_align: `0` (the default) inherits @p offset_align's value - the common case of padding the+ * offset and the slot size the same way; set it explicitly (`1` for no slot padding, or another power of+ * two) only when the slot size genuinely needs to differ from the offset alignment.+ * @note Always relative to the container's own first byte, never to the destination's absolute address -+ * getting that to line up with a real page boundary (e.g. for `mmap`) is the caller's responsibility:+ * place the container's first byte at a page-aligned position in the destination.+ */+struct SectionAlignment {+ size_t offset_align = 1;+ size_t size_align = 0; //!< 0 = inherit `offset_align`+};++/**+ * @brief Outcome of #IWriter::finalize(), reported via `std::error_code` - a default-constructed+ * (falsy) one means success; compare against #WriteErrc::write_failed for the one failure case.+ */+enum class WriteErrc {+ write_failed = 1, //!< The destination ran out of room (fixed buffer) or a write failed (stream).+};++/**+ * @brief ADL hook letting a #WriteErrc implicitly convert to/compare against `std::error_code` -+ * `ec.message()` gives the human-readable text.+ */+OPENVINO_RUNTIME_API std::error_code make_error_code(WriteErrc e) noexcept;++class ISectionWriterHandler;++/**+ * @brief Common (device- and destination-agnostic) writer interface for one HSM container.+ * @note #add_section() borrows @p payload (see the concrete class for how long it must stay alive); the+ * #ISectionEncoder overloads produce data on demand instead, for a payload with no existing view (e.g.+ * generated, or only transiently alive). @p device is always explicit - pass #any_device_id for a+ * Core-owned section.+ * @note Tag mode support is asymmetric: an inline @p tag (#SectionTag::is_inline()) is only accepted by+ * the #ov::util::MemoryView overload; both #ISectionEncoder overloads are pointer-mode only and reject+ * an inline @p tag.+ */+class OPENVINO_RUNTIME_API IWriter {+public:+ virtual ~IWriter() = default;++ /**+ * @brief Adds a section owned by @p device.+ *+ * @param device The device that owns the section.+ * @param tag The section tag.+ * @param payload The memory view containing the section's data.+ * @param align The alignment requirements for the section - accepted but ignored for an inline+ * @p tag, so the same value can be reused across inline and pointer-mode calls.+ * @return true if the section was added; false if the destination has run out of room or the write+ * failed.+ */+ virtual bool add_section(DeviceId device,+ SectionTagReserved tag,+ ov::util::MemoryView payload,+ SectionAlignment align = {}) = 0;++ /**+ * @brief Adds a section owned by @p device whose content is produced on demand by @p encoder, for a+ * payload that doesn't exist as a view yet (e.g. generated, or assembled piecemeal) - avoids an+ * intermediate allocation just to call the view overload.+ * @note Pointer-mode only; see the view overload for inline-mode.+ * @note @p encoder is invoked at most once per finalization attempt - see #finalize()'s note on how+ * a repeated call, or a call after an exception, is handled by the concrete implementation. It must+ * write exactly @p size bytes to `sink` (across one or more calls) - never buffer a copy of its own+ * first.+ *+ * @param device The device that owns the section.+ * @param tag The section tag.+ * @param size The size of the section's payload.+ * @param encoder The encoder that produces the section's content.+ * @param align The alignment requirements for the section.+ * @return true if the section was added; false if @p tag is inline, the destination has run out of+ * room, or the write failed.+ */+ virtual bool add_section(DeviceId device,+ SectionTagReserved tag,+ size_t size,+ SectionEncoderPtr encoder,+ SectionAlignment align = {}) = 0;++ /**+ * @brief Adds a section owned by @p device whose content is produced by @p encoder and whose size is+ * only known once @p encoder has finished writing it (e.g. serializing an object whose encoded length+ * depends on its runtime data).+ * @note @p encoder is invoked at most once per finalization attempt - see #finalize()'s note on how+ * a repeated call, or a call after an exception, is handled by the concrete implementation.+ * Pointer-mode only (same restriction as the sized overload for inline tags). Forces #finalize() to+ * revisit the destination once every real size is known, instead of computing the header up front -+ * a stream destination must be seekable if any section uses this overload.+ *+ * @param device The device that owns the section.+ * @param tag The section tag.+ * @param encoder The encoder that produces the section's content.+ * @param align The alignment requirements for the section.+ * @return true if the section was added; false if @p tag is inline, the destination has run out of+ * room, or the write failed.+ */+ virtual bool add_section(DeviceId device,+ SectionTagReserved tag,+ SectionEncoderPtr encoder,+ SectionAlignment align = {}) = 0;++ /**+ * @brief Writes the header, every section, and the manifest.+ * @note Call after the last add_section(). Behavior of a repeated call, and of a call after an+ * exception escapes a previous one, is defined by the concrete implementation.+ */+ virtual std::error_code finalize() = 0;++ /**+ * @brief Lets each of @p handlers contribute its own sections, in order, via #ISectionWriterHandler::+ * handle_section(). Symmetric to #Reader::read_sections() on the read side.+ * @param handlers The list of section writer handlers to invoke.+ */+ void add_sections(const std::vector<ISectionWriterHandler*>& handlers);+};++/**+ * @brief Writer-side plugin hook: a plugin contributes its own proprietary sections to a container.+ * Symmetric to #ISectionReaderHandler - #IWriter::add_sections() is the driver, taking a list of+ * handlers, exactly like #Reader::read_sections() does.+ */+class OPENVINO_RUNTIME_API ISectionWriterHandler {+public:+ virtual ~ISectionWriterHandler() = default;++ /**+ * @brief Reserves this handler's sections on @p writer, via any #IWriter::add_section() overload.+ * @note Called by #IWriter::add_sections(), not directly - see its docs.+ */+ virtual void handle_section(IWriter& writer) const = 0;+};++} // namespace v1+} // namespace ov::runtime::hsm++template <>+struct std::is_error_code_enum<ov::runtime::hsm::WriteErrc> : std::true_type {};diff --git a/src/inference/sources.cmake b/src/inference/sources.cmakeindex 2d354fd4e96..418db51f103 100644--- a/src/inference/sources.cmake+++ b/src/inference/sources.cmake@@ -21,7 +21,9 @@ 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_deferred_writer.cpp${CMAKE_CURRENT_LIST_DIR}/src/dev/hsm_reader.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/dev/hsm_writer.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.cppdiff --git a/src/inference/src/dev/hsm_deferred_writer.cpp b/src/inference/src/dev/hsm_deferred_writer.cppnew file mode 100644index 00000000000..e90d793e49f--- /dev/null+++ b/src/inference/src/dev/hsm_deferred_writer.cpp@@ -0,0 +1,447 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/runtime/hsm_deferred_writer.hpp"++#include <algorithm>+#include <array>+#include <limits>+#include <optional>+#include <utility>+#include <variant>++#include "openvino/core/except.hpp"+#include "openvino/util/memory.hpp"+#include "openvino/util/variant_visitor.hpp"++namespace ov::runtime::hsm {+inline namespace v1 {++namespace {++constexpr size_t k_inline_capacity = sizeof(ManifestEntry{}.inline_bytes);++size_t normalize_alignment(size_t alignment) {+ const size_t a = alignment == 0 ? 1 : alignment;+ const auto is_power_of_two = (a & (a - 1)) == 0;+ OPENVINO_ASSERT(is_power_of_two, "HSM section alignment must be a power of two");+ return a;+}++SectionAlignment resolve_alignment(SectionAlignment align) {+ const auto off_align = normalize_alignment(align.offset_align);+ const auto slot_align = align.size_align == 0 ? off_align : normalize_alignment(align.size_align);+ return {off_align, slot_align};+}++// Reserved byte range for one section - computed once so the size dry run and the actual write pass+// in DeferredWriter::finalize() can never disagree about where anything ends up.+struct SectionSlot {+ size_t start;+ size_t end;+};++constexpr std::optional<SectionSlot> reserve_slot(size_t cursor, size_t size, SectionAlignment align) {+ const auto start = ov::util::align_size_up_overflow(cursor, align.offset_align);+ const auto aligned_size = ov::util::align_size_up_overflow(size, align.size_align);+ if (!start || !aligned_size || *aligned_size > std::numeric_limits<size_t>::max() - *start) {+ return std::nullopt;+ } else {+ return SectionSlot{*start, *start + *aligned_size};+ }+}++constexpr Header make_header(size_t manifest_offset, size_t manifest_size, size_t container_size) {+ return {+ BlobMagic::single,+ FormatVersion::major,+ FormatVersion::minor,+ container_size,+ manifest_offset,+ manifest_size,+ };+}++} // namespace++std::optional<size_t> DeferredWriter::reserve(BufferDestination& destination, size_t extra) {+ OPENVINO_ASSERT(destination.size <= destination.capacity, "HSM writer: buffer size exceeds its capacity");+ if (!destination.good || extra > destination.capacity - destination.size) {+ destination.good = false;+ return std::nullopt;+ } else {+ return std::exchange(destination.size, destination.size + extra);+ }+}++DeferredWriter::PendingSection::PendingSection(SectionAlignment align,+ ov::util::MemoryView payload,+ DeviceId device,+ SectionTagReserved tag)+ : align{align},+ payload{payload},+ device{device},+ tag{tag} {}++DeferredWriter::PendingSection::PendingSection(SectionAlignment align,+ PendingEncode payload,+ DeviceId device,+ SectionTagReserved tag)+ : align{align},+ payload{std::move(payload)},+ device{device},+ tag{tag} {}++DeferredWriter::PendingSection::PendingSection(SectionAlignment align,+ SectionEncoderPtr payload,+ DeviceId device,+ SectionTagReserved tag)+ : align{align},+ payload{std::move(payload)},+ device{device},+ tag{tag} {}++void DeferredWriter::write_into(StreamDestination& destination, ov::util::MemoryView data) {+ destination.stream->write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));+ destination.size += data.size();+}++void DeferredWriter::write_into(BufferDestination& destination, ov::util::MemoryView data) {+ if (const auto at = reserve(destination, data.size())) {+ std::copy_n(data.data(), data.size(), destination.dst + *at);+ }+}++void DeferredWriter::write(ov::util::MemoryView data) {+ if (destination_good()) {+ std::visit(+ [&](auto& destination) {+ write_into(destination, data);+ },+ m_destination);+ }+}++void DeferredWriter::write_zeros(size_t count) {+ static constexpr std::array<std::byte, 256> zeros{};+ size_t remaining = count;+ while (remaining > 0 && destination_good()) {+ const size_t chunk = std::min(remaining, zeros.size());+ write({zeros.data(), chunk});+ remaining -= chunk;+ }+}++void DeferredWriter::patch_into(StreamDestination& destination, size_t offset, ov::util::MemoryView data) {+ const auto resume = destination.stream->tellp();+ const auto target = destination.start + static_cast<std::streamoff>(offset);+ destination.stream->seekp(target);+ destination.stream->write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));+ destination.stream->flush();+ if (destination.stream->tellp() != target + static_cast<std::streamoff>(data.size())) {+ destination.stream->setstate(std::ios::failbit);+ } else {+ destination.stream->seekp(resume);+ }+}++void DeferredWriter::patch_into(BufferDestination& destination, size_t offset, ov::util::MemoryView data) {+ OPENVINO_ASSERT(destination.good && offset + data.size() <= destination.size, "HSM writer: patch out of bounds");+ std::copy_n(data.data(), data.size(), destination.dst + offset);+}++void DeferredWriter::patch(size_t offset, ov::util::MemoryView data) {+ std::visit(+ [&](auto& destination) {+ patch_into(destination, offset, data);+ },+ m_destination);+}++size_t DeferredWriter::written_size() const {+ return std::visit(+ [](const auto& d) {+ return d.size;+ },+ m_destination);+}++bool DeferredWriter::is_good(const StreamDestination& destination) {+ return static_cast<bool>(*destination.stream);+}++bool DeferredWriter::is_good(const BufferDestination& destination) {+ return destination.good;+}++bool DeferredWriter::destination_good() const {+ return std::visit(+ [](const auto& destination) {+ return is_good(destination);+ },+ m_destination);+}++void DeferredWriter::reset_destination() {+ std::visit(ov::util::VariantVisitor{+ [](StreamDestination& destination) {+ destination.stream->seekp(destination.start);+ destination.size = 0;+ },+ [](BufferDestination& destination) {+ destination.size = 0;+ destination.good = true;+ },+ },+ m_destination);+}++void DeferredWriter::fail_destination() {+ std::visit(ov::util::VariantVisitor{+ [](StreamDestination& destination) {+ destination.stream->setstate(std::ios::failbit);+ },+ [](BufferDestination& destination) {+ destination.good = false;+ },+ },+ m_destination);+}++ManifestEntry DeferredWriter::write_section(DeviceId device,+ SectionTagReserved tag,+ SectionAlignment align,+ ov::util::MemoryView payload) {+ ManifestEntry entry{};+ entry.device = device;+ entry.tag = tag.tag;+ entry.tag_reserved = tag.bytes;+ if (tag.is_inline()) {+ std::copy_n(reinterpret_cast<const uint8_t*>(payload.data()), payload.size(), entry.inline_bytes.data());+ return entry;+ }+ const auto slot = reserve_slot(written_size(), payload.size(), align);+ if (slot) {+ write_zeros(slot->start - written_size()); // pad to the aligned start+ } else {+ fail_destination();+ }+ write(payload);+ if (destination_good()) {+ write_zeros(slot->end - written_size()); // pad the slot+ entry.offset = slot->start;+ entry.size = payload.size();+ }+ return entry;+}++ManifestEntry DeferredWriter::write_section(DeviceId device,+ SectionTagReserved tag,+ SectionAlignment align,+ const PendingEncode& payload) {+ ManifestEntry entry{};+ entry.device = device;+ entry.tag = tag.tag;+ entry.tag_reserved = tag.bytes;+ const auto slot = reserve_slot(written_size(), payload.size, align);+ if (slot) {+ write_zeros(slot->start - written_size());+ } else {+ fail_destination();+ }+ if (destination_good()) {+ size_t remaining = payload.size;+ const SectionSink sink = [this, &remaining](ov::util::MemoryView data) {+ OPENVINO_ASSERT(data.size() <= remaining, "HSM encoder wrote past its declared size");+ remaining -= data.size();+ write(data);+ };+ payload.encoder->encode(sink);+ // A destination that ran out of room mid-encode already failed for an unrelated reason - don't+ // also flag that as a broken encoder.+ OPENVINO_ASSERT(!destination_good() || remaining == 0, "HSM encoder must append exactly its declared size");+ }+ if (destination_good()) {+ write_zeros(slot->end - written_size());+ entry.offset = slot->start;+ entry.size = payload.size;+ }+ return entry;+}++ManifestEntry DeferredWriter::write_section(DeviceId device,+ SectionTagReserved tag,+ SectionAlignment align,+ const SectionEncoderPtr& encoder) {+ ManifestEntry entry{};+ entry.device = device;+ entry.tag = tag.tag;+ entry.tag_reserved = tag.bytes;+ const auto start = ov::util::align_size_up_overflow(written_size(), align.offset_align);+ if (start) {+ write_zeros(*start - written_size());+ } else {+ fail_destination();+ }+ if (destination_good()) {+ const SectionSink sink = [this](ov::util::MemoryView data) {+ write(data);+ };+ encoder->encode(sink);+ }+ const size_t real_size = destination_good() ? written_size() - *start : 0;+ if (destination_good()) {+ const auto aligned_end = ov::util::align_size_up_overflow(real_size, align.size_align);+ if (aligned_end) {+ write_zeros(*aligned_end - real_size);+ entry.offset = *start;+ entry.size = real_size;+ } else {+ fail_destination();+ }+ }+ return entry;+}++DeferredWriter::DeferredWriter(std::ostream& stream) noexcept+ : m_destination{StreamDestination{&stream, stream.tellp()}},+ m_sections{},+ m_result{},+ m_has_unsized_section{false} {}++DeferredWriter::DeferredWriter(std::byte* dst, size_t capacity) noexcept+ : m_destination{BufferDestination{dst, capacity}},+ m_sections{},+ m_result{},+ m_has_unsized_section{false} {}++std::optional<DeferredWriter> DeferredWriter::open(std::ostream& stream) {+ if (stream.tellp() == std::streampos(-1)) {+ return std::nullopt;+ } else {+ DeferredWriter writer{stream};+ return writer.destination_good() ? std::optional<DeferredWriter>{std::move(writer)} : std::nullopt;+ }+}++std::optional<DeferredWriter> DeferredWriter::open(std::byte* dst, size_t size) {+ if (dst == nullptr || size < sizeof(Header)) {+ return std::nullopt;+ } else {+ DeferredWriter writer{dst, size};+ return writer.destination_good() ? std::optional<DeferredWriter>{std::move(writer)} : std::nullopt;+ }+}++bool DeferredWriter::add_section(DeviceId device,+ SectionTagReserved tag,+ ov::util::MemoryView payload,+ SectionAlignment align) {+ if (tag.is_pointer()) {+ m_sections.emplace_back(resolve_alignment(align), payload, device, tag);+ return true;+ } else if (payload.size() <= k_inline_capacity) {+ m_sections.emplace_back(align, payload, device, tag);+ return true;+ } else {+ return false;+ }+}++bool DeferredWriter::add_section(DeviceId device,+ SectionTagReserved tag,+ size_t size,+ SectionEncoderPtr encoder,+ SectionAlignment align) {+ OPENVINO_DEBUG_ASSERT(!tag.is_inline(), "HSM fill-in-place sections must be pointer-mode");+ OPENVINO_DEBUG_ASSERT(encoder != nullptr, "HSM section encoder must not be null");+ if (tag.is_inline() || !encoder) {+ return false;+ } else {+ const auto resolved = resolve_alignment(align);+ m_sections.emplace_back(resolved, PendingEncode{size, std::move(encoder)}, device, tag);+ return true;+ }+}++bool DeferredWriter::add_section(DeviceId device,+ SectionTagReserved tag,+ SectionEncoderPtr encoder,+ SectionAlignment align) {+ OPENVINO_DEBUG_ASSERT(!tag.is_inline(), "HSM fill-in-place sections must be pointer-mode");+ OPENVINO_DEBUG_ASSERT(encoder != nullptr, "HSM section encoder must not be null");+ if (tag.is_inline() || !encoder) {+ return false;+ } else {+ const auto resolved = resolve_alignment(align);+ m_sections.emplace_back(resolved, std::move(encoder), device, tag);+ m_has_unsized_section = true;+ return true;+ }+}++std::error_code DeferredWriter::finalize() {+ if (!m_result.has_value()) {+ reset_destination();+ const auto section_count = m_sections.size();+ size_t manifest_offset = 0;+ if (m_has_unsized_section) {+ // At least one section's size is only known after encoding it, so the header can't be+ // computed up front - write a placeholder and patch it once every real size is known.+ write_zeros(sizeof(Header));+ } else {+ // std::get is safe here - m_has_unsized_section already rules out an ISectionEncoder payload.+ const auto payload_size = [](const PendingSection& section) -> size_t {+ if (const auto view = std::get_if<ov::util::MemoryView>(§ion.payload)) {+ return view->size();+ } else {+ return std::get<PendingEncode>(section.payload).size;+ }+ };++ auto body_size = sizeof(Header);+ for (const auto& section : m_sections) {+ if (!section.tag.is_inline()) {+ if (const auto slot = reserve_slot(body_size, payload_size(section), section.align)) {+ body_size = slot->end;+ } else {+ fail_destination();+ break;+ }+ }+ }++ if (destination_good()) {+ const auto manifest_size = section_count * sizeof(ManifestEntry);+ const auto header = make_header(body_size, manifest_size, body_size + manifest_size);+ write({reinterpret_cast<const std::byte*>(&header), sizeof(header)});+ manifest_offset = body_size;+ }+ }++ std::vector<ManifestEntry> entries(section_count);+ for (size_t i = 0; i < section_count && destination_good(); ++i) {+ const auto& section = m_sections[i];+ entries[i] = std::visit(+ [&](const auto& payload) -> ManifestEntry {+ return write_section(section.device, section.tag, section.align, payload);+ },+ section.payload);+ }++ if (m_has_unsized_section) {+ manifest_offset = written_size(); // now known: right before the manifest is written+ }+ write({reinterpret_cast<const std::byte*>(entries.data()), entries.size() * sizeof(ManifestEntry)});+ if (m_has_unsized_section && destination_good()) {+ const auto header = make_header(manifest_offset, entries.size() * sizeof(ManifestEntry), written_size());+ patch(0, {reinterpret_cast<const std::byte*>(&header), sizeof(header)});+ }+ m_result = destination_good() ? std::error_code{} : make_error_code(WriteErrc::write_failed);+ }+ return *m_result;+}++} // namespace v1+} // namespace ov::runtime::hsmdiff --git a/src/inference/src/dev/hsm_writer.cpp b/src/inference/src/dev/hsm_writer.cppnew file mode 100644index 00000000000..d6be57a1bce--- /dev/null+++ b/src/inference/src/dev/hsm_writer.cpp@@ -0,0 +1,44 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/runtime/hsm_writer.hpp"++namespace ov::runtime::hsm {+inline namespace v1 {++namespace {++class WriteErrorCategory final : public std::error_category {+public:+ const char* name() const noexcept override {+ return "ov::runtime::hsm::Write";+ }++ std::string message(int ev) const override {+ switch (static_cast<WriteErrc>(ev)) {+ case WriteErrc::write_failed:+ return "the destination ran out of room, or a write failed";+ default:+ return "unknown error";+ }+ }+};++} // namespace++std::error_code make_error_code(WriteErrc e) noexcept {+ static const WriteErrorCategory category;+ return {static_cast<int>(e), category};+}++void IWriter::add_sections(const std::vector<ISectionWriterHandler*>& handlers) {+ for (const auto* handler : handlers) {+ if (handler != nullptr) {+ handler->handle_section(*this);+ }+ }+}++} // namespace v1+} // namespace ov::runtime::hsmdiff --git a/src/inference/tests/unit/CMakeLists.txt b/src/inference/tests/unit/CMakeLists.txtindex ee1c19feac9..ba9b2f889b6 100644--- a/src/inference/tests/unit/CMakeLists.txt+++ b/src/inference/tests/unit/CMakeLists.txt@@ -26,8 +26,10 @@ ov_add_test_target(${CMAKE_CURRENT_SOURCE_DIR}/cpu_stream_info_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/executor_config_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/executor_manager_tests.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/hsm_deferred_writer.cpp${CMAKE_CURRENT_SOURCE_DIR}/hsm_format.cpp${CMAKE_CURRENT_SOURCE_DIR}/hsm_reader.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/hsm_writer.cpp${CMAKE_CURRENT_SOURCE_DIR}/infer_request_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/iplugin_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/isync_infer_request_test.cppdiff --git a/src/inference/tests/unit/hsm_deferred_writer.cpp b/src/inference/tests/unit/hsm_deferred_writer.cppnew file mode 100644index 00000000000..0ad01d4725c--- /dev/null+++ b/src/inference/tests/unit/hsm_deferred_writer.cpp@@ -0,0 +1,1146 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/runtime/hsm_deferred_writer.hpp"++#include <gtest/gtest.h>++#include <array>+#include <cstring>+#include <limits>+#include <optional>+#include <sstream>+#include <string>+#include <type_traits>+#include <vector>++#include "openvino/core/except.hpp"++// DeferredWriter-specific tests+namespace ov::test {+namespace hsm = ov::runtime::hsm;+namespace {++constexpr hsm::DeviceId fake_device_id = 7;+constexpr size_t k_buffer_capacity = 4096;++ov::util::MemoryView view_of(const std::string& s) {+ return {reinterpret_cast<const std::byte*>(s.data()), s.size()};+}++// Encodes an owned copy of a std::string - safe even if the source is destroyed before finalize().+class OwnedStringEncoder final : public hsm::ISectionEncoder {+public:+ explicit OwnedStringEncoder(std::string text) : m_text(std::move(text)) {}+ void encode(const hsm::SectionSink& sink) const override {+ sink({reinterpret_cast<const std::byte*>(m_text.data()), m_text.size()});+ }++private:+ std::string m_text;+};++// Encodes a live std::string by reference - the referenced string must outlive finalize().+class StringViewEncoder final : public hsm::ISectionEncoder {+public:+ explicit StringViewEncoder(const std::string& text) : m_text(text) {}+ void encode(const hsm::SectionSink& sink) const override {+ sink({reinterpret_cast<const std::byte*>(m_text.data()), m_text.size()});+ }++private:+ const std::string& m_text;+};++// Writes "chunk0-chunk1-chunk2-" across three separate sink() calls.+class ChunkedEncoder final : public hsm::ISectionEncoder {+public:+ void encode(const hsm::SectionSink& sink) const override {+ for (int i = 0; i < 3; ++i) {+ const std::string chunk = "chunk" + std::to_string(i) + "-";+ sink({reinterpret_cast<const std::byte*>(chunk.data()), chunk.size()});+ }+ }+};++// Does nothing - never calls sink() at all.+class NoOpEncoder final : public hsm::ISectionEncoder {+public:+ void encode(const hsm::SectionSink&) const override {}+};++// Sinks `count` zero bytes in one call.+class ZeroBytesEncoder final : public hsm::ISectionEncoder {+public:+ explicit ZeroBytesEncoder(size_t count) : m_bytes(count) {}+ void encode(const hsm::SectionSink& sink) const override {+ sink({m_bytes.data(), m_bytes.size()});+ }++private:+ std::vector<std::byte> m_bytes;+};++// Sinks a declared `size` larger than the single real byte behind `data` - the overflow/capacity check+// must reject this before any copy happens.+class OverflowEncoder final : public hsm::ISectionEncoder {+public:+ OverflowEncoder(const std::byte* data, size_t size) : m_data(data), m_size(size) {}+ void encode(const hsm::SectionSink& sink) const override {+ sink({m_data, m_size});+ }++private:+ const std::byte* m_data;+ size_t m_size;+};++// Always throws - simulates an encoder that blows up.+class ThrowingEncoder final : public hsm::ISectionEncoder {+public:+ void encode(const hsm::SectionSink&) const override {+ OPENVINO_THROW("encoder blew up");+ }+};++// Counts invocations; throws while `should_throw` is true, otherwise sinks a fixed 4-byte payload.+class RetryEncoder final : public hsm::ISectionEncoder {+public:+ RetryEncoder(int& call_count, bool& should_throw) : m_call_count(call_count), m_should_throw(should_throw) {}+ void encode(const hsm::SectionSink& sink) const override {+ ++m_call_count;+ if (m_should_throw) {+ OPENVINO_THROW("encoder blew up");+ }+ sink({reinterpret_cast<const std::byte*>("data"), 4});+ }++private:+ int& m_call_count;+ bool& m_should_throw;+};++// Sinks a single empty chunk.+class EmptyChunkEncoder final : public hsm::ISectionEncoder {+public:+ void encode(const hsm::SectionSink& sink) const override {+ sink(ov::util::MemoryView{});+ }+};++hsm::DeferredWriter open_writer(std::ostream& stream) {+ auto writer = hsm::DeferredWriter::open(stream);+ EXPECT_TRUE(writer.has_value());+ return std::move(writer).value();+}++hsm::DeferredWriter open_buffer_writer(std::byte* dst, size_t size) {+ auto writer = hsm::DeferredWriter::open(dst, size);+ EXPECT_TRUE(writer.has_value());+ return std::move(writer).value();+}++// Fails (writing only half the requested bytes) on a chosen xsputn() call, simulating a stream write+// that partially succeeds before std::ostream sets badbit - built on std::stringbuf so seeking still+// works, letting finalize()'s retry be observed.+class FlakyOnceStreamBuf : public std::stringbuf {+public:+ int fail_on_call = -1; // -1 = never fail+ int call_count = 0;++protected:+ std::streamsize xsputn(const char* s, std::streamsize n) override {+ if (++call_count == fail_on_call) {+ const auto partial = n / 2;+ std::stringbuf::xsputn(s, partial);+ return partial;+ }+ return std::stringbuf::xsputn(s, n);+ }+};++class AppendOnlyStreamBuf : public std::stringbuf {+protected:+ std::streamsize xsputn(const char* s, std::streamsize n) override {+ seekoff(0, std::ios::end, std::ios::out);+ return std::stringbuf::xsputn(s, n);+ }+};++struct ParsedContainer {+ hsm::Header header{};+ std::vector<hsm::ManifestEntry> entries;+ std::vector<std::byte> bytes;+};++std::optional<ParsedContainer> parse_container(std::vector<std::byte> raw) {+ if (raw.size() < sizeof(hsm::Header)) {+ return std::nullopt;+ }+ const auto& header = hsm::Header::view(reinterpret_cast<const uint8_t*>(raw.data()));+ if (!hsm::is_valid_header_fields(header)) {+ return std::nullopt;+ }+ const auto first_entry = reinterpret_cast<const hsm::ManifestEntry*>(raw.data() + header.manifest_offset);+ std::vector<hsm::ManifestEntry> entries(first_entry,+ first_entry + header.manifest_size / sizeof(hsm::ManifestEntry));+ return ParsedContainer{header, std::move(entries), std::move(raw)};+}++std::optional<ParsedContainer> parse_container(const std::string& stream_bytes) {+ const auto data = reinterpret_cast<const std::byte*>(stream_bytes.data());+ return parse_container(std::vector<std::byte>(data, data + stream_bytes.size()));+}++std::optional<ParsedContainer> parse_container(const std::byte* data, size_t size) {+ return parse_container(std::vector<std::byte>(data, data + size));+}++const hsm::ManifestEntry* find_entry(const ParsedContainer& container, hsm::DeviceId device, uint32_t tag_id) {+ for (const auto& entry : container.entries) {+ if (entry.device == device && entry.tag.id() == tag_id) {+ return &entry;+ }+ }+ return nullptr;+}++std::vector<const hsm::ManifestEntry*> find_entries(const ParsedContainer& container,+ hsm::DeviceId device,+ uint32_t tag_id) {+ std::vector<const hsm::ManifestEntry*> found;+ for (const auto& entry : container.entries) {+ if (entry.device == device && entry.tag.id() == tag_id) {+ found.push_back(&entry);+ }+ }+ return found;+}++std::string payload_string(const ParsedContainer& container, const hsm::ManifestEntry& entry) {+ if (entry.tag.is_inline()) {+ return {reinterpret_cast<const char*>(entry.inline_bytes.data()), entry.inline_bytes.size()};+ }+ return {reinterpret_cast<const char*>(container.bytes.data() + entry.offset), entry.size};+}++} // namespace++static_assert(std::is_move_constructible_v<hsm::DeferredWriter>);+static_assert(std::is_move_assignable_v<hsm::DeferredWriter>);+static_assert(!std::is_copy_constructible_v<hsm::DeferredWriter>);+static_assert(!std::is_copy_assignable_v<hsm::DeferredWriter>);++// --- open() factories ---++TEST(HsmDeferredWriterTest, open_stream_rejects_an_already_failed_stream) {+ std::stringstream stream;+ stream.setstate(std::ios::badbit);+ EXPECT_FALSE(hsm::DeferredWriter::open(stream).has_value());+}++TEST(HsmDeferredWriterTest, open_stream_rejects_a_non_seekable_stream) {+ struct NonSeekableStreamBuf : std::streambuf {}; // base class's seekoff/seekpos always fail+ NonSeekableStreamBuf buf;+ std::ostream stream(&buf);+ EXPECT_FALSE(hsm::DeferredWriter::open(stream).has_value());+}++TEST(HsmDeferredWriterTest, open_buffer_rejects_a_buffer_too_small_for_the_header) {+ std::vector<std::byte> too_small(sizeof(hsm::Header) - 1);+ EXPECT_FALSE(hsm::DeferredWriter::open(too_small.data(), too_small.size()).has_value());+}++TEST(HsmDeferredWriterTest, open_buffer_rejects_a_null_buffer) {+ EXPECT_FALSE(hsm::DeferredWriter::open(nullptr, 0).has_value());+}++// --- Writing into the two destination kinds ---++TEST(HsmDeferredWriterTest, writes_into_a_preallocated_buffer) {+ const std::string model = "model-bytes";++ std::vector<std::byte> buffer(k_buffer_capacity);+ auto writer = open_buffer_writer(buffer.data(), buffer.size());+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(model));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(buffer.data(), buffer.size());+ ASSERT_TRUE(container.has_value());+ const auto entry = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(entry, nullptr);+ EXPECT_EQ(payload_string(*container, *entry), "model-bytes");+}++TEST(HsmDeferredWriterTest, pads_an_alignment_gap_larger_than_the_internal_zero_fill_chunk) {+ // write_zeros() fills padding gaps via a small internal buffer reused in a loop - this forces a gap+ // bigger than that buffer, exercising more than one iteration of it.+ const std::string a = "a";+ const std::string b = "b";+ const auto b_tag = hsm::SectionTag::make_device_tag(5, false);++ std::vector<std::byte> buffer(k_buffer_capacity);+ auto writer = open_buffer_writer(buffer.data(), buffer.size());+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(a), {/*offset_align=*/1024});+ writer.add_section(fake_device_id, b_tag, view_of(b), {/*offset_align=*/1024});+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(buffer.data(), buffer.size());+ ASSERT_TRUE(container.has_value());+ const auto a_entry = find_entry(*container, hsm::any_device_id, hsm::model);+ const auto b_entry = find_entry(*container, fake_device_id, b_tag.id());+ ASSERT_NE(a_entry, nullptr);+ ASSERT_NE(b_entry, nullptr);+ EXPECT_EQ(b_entry->offset, a_entry->offset + 1024);+ EXPECT_EQ(payload_string(*container, *a_entry), "a");+ EXPECT_EQ(payload_string(*container, *b_entry), "b");+}++TEST(HsmDeferredWriterTest, sized_section_encoder_rejects_a_chunk_without_overflowing_the_capacity_check) {+ std::vector<std::byte> buffer(k_buffer_capacity);+ auto writer = open_buffer_writer(buffer.data(), buffer.size());+ const std::byte dummy{};+ static constexpr size_t huge = std::numeric_limits<size_t>::max() - 31;+ writer.add_section(hsm::any_device_id, hsm::model_tag, huge, std::make_shared<OverflowEncoder>(&dummy, huge));+ EXPECT_EQ(writer.finalize(), hsm::WriteErrc::write_failed);+}++TEST(HsmDeferredWriterTest, sized_section_encoder_fits_a_buffer_sized_to_the_exact_byte) {+ static constexpr size_t section_size = 4;+ constexpr size_t exact_capacity = sizeof(hsm::Header) + section_size + sizeof(hsm::ManifestEntry);+ std::vector<std::byte> buffer(exact_capacity);+ auto writer = open_buffer_writer(buffer.data(), buffer.size());+ writer.add_section(hsm::any_device_id,+ hsm::model_tag,+ section_size,+ std::make_shared<ZeroBytesEncoder>(section_size));+ EXPECT_EQ(writer.finalize(), std::error_code{});+}++TEST(HsmDeferredWriterTest, sized_section_encoder_rejects_a_buffer_one_byte_short_of_fitting) {+ static constexpr size_t section_size = 4;+ constexpr size_t exact_capacity = sizeof(hsm::Header) + section_size + sizeof(hsm::ManifestEntry);+ std::vector<std::byte> buffer(exact_capacity - 1);+ auto writer = open_buffer_writer(buffer.data(), buffer.size());+ writer.add_section(hsm::any_device_id,+ hsm::model_tag,+ section_size,+ std::make_shared<ZeroBytesEncoder>(section_size));+ EXPECT_EQ(writer.finalize(), hsm::WriteErrc::write_failed);+}++TEST(HsmDeferredWriterTest, finalize_reports_write_failed_for_an_undersized_buffer) {+ std::vector<std::byte> too_small(sizeof(hsm::Header)); // no room for even one section+ auto writer = open_buffer_writer(too_small.data(), too_small.size());+ const std::string model = "model";+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(model));+ EXPECT_EQ(writer.finalize(), hsm::WriteErrc::write_failed);+}++TEST(HsmDeferredWriterTest, finalize_s_returned_error_code_has_a_human_readable_message) {+ std::vector<std::byte> too_small(sizeof(hsm::Header));+ auto writer = open_buffer_writer(too_small.data(), too_small.size());+ const std::string model = "model";+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(model));++ const auto ec = writer.finalize();+ EXPECT_EQ(ec, hsm::WriteErrc::write_failed);+ EXPECT_FALSE(ec.message().empty());+}++TEST(HsmDeferredWriterTest, finalize_reports_write_failed_when_the_stream_is_already_bad) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ const std::string model = "model";+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(model));+ stream.setstate(std::ios::badbit); // fails every subsequent write+ EXPECT_EQ(writer.finalize(), hsm::WriteErrc::write_failed);+}++// --- add_section() validates its inputs ---++#ifndef NDEBUG+TEST(HsmDeferredWriterTest, sized_section_encoder_debug_asserts_on_an_inline_mode_tag) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ EXPECT_THROW(writer.add_section(hsm::any_device_id, hsm::model_id_tag, 4, std::make_shared<NoOpEncoder>()),+ ov::AssertFailure);+}++TEST(HsmDeferredWriterTest, unsized_section_encoder_debug_asserts_on_an_inline_mode_tag) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ EXPECT_THROW(writer.add_section(hsm::any_device_id, hsm::model_id_tag, std::make_shared<NoOpEncoder>()),+ ov::AssertFailure);+}++TEST(HsmDeferredWriterTest, sized_section_encoder_debug_asserts_on_a_null_encoder) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ EXPECT_THROW(writer.add_section(hsm::any_device_id, hsm::model_tag, 4, nullptr), ov::AssertFailure);+}++TEST(HsmDeferredWriterTest, unsized_section_encoder_debug_asserts_on_a_null_encoder) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ EXPECT_THROW(writer.add_section(hsm::any_device_id, hsm::model_tag, nullptr), ov::AssertFailure);+}+#else+TEST(HsmDeferredWriterTest, sized_section_encoder_rejects_an_inline_mode_tag) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ EXPECT_FALSE(writer.add_section(hsm::any_device_id, hsm::model_id_tag, 4, std::make_shared<NoOpEncoder>()));+}++TEST(HsmDeferredWriterTest, unsized_section_encoder_rejects_an_inline_mode_tag) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ EXPECT_FALSE(writer.add_section(hsm::any_device_id, hsm::model_id_tag, std::make_shared<NoOpEncoder>()));+}++TEST(HsmDeferredWriterTest, sized_section_encoder_rejects_a_null_encoder) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ EXPECT_FALSE(writer.add_section(hsm::any_device_id, hsm::model_tag, 4, nullptr));+}++TEST(HsmDeferredWriterTest, unsized_section_encoder_rejects_a_null_encoder) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ EXPECT_FALSE(writer.add_section(hsm::any_device_id, hsm::model_tag, nullptr));+}+#endif++// --- finalize() semantics ---++TEST(HsmDeferredWriterTest, finalize_is_idempotent) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ const std::string model = "model";+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(model));+ const auto first = writer.finalize();+ const auto written_once = stream.str();+ const auto second = writer.finalize();++ EXPECT_EQ(first, second);+ EXPECT_EQ(stream.str(), written_once); // no bytes written again+}++TEST(HsmDeferredWriterTest, finalize_propagates_an_exception_thrown_by_a_section_encoder) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id, hsm::model_tag, 4, std::make_shared<ThrowingEncoder>());+ EXPECT_THROW(writer.finalize(), ov::Exception);+}++TEST(HsmDeferredWriterTest, finalize_retries_the_encoder_after_a_thrown_attempt_and_can_then_succeed) {+ int call_count = 0;+ bool should_throw = true;+ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id, hsm::model_tag, 4, std::make_shared<RetryEncoder>(call_count, should_throw));+ EXPECT_THROW(writer.finalize(), ov::Exception);+ EXPECT_EQ(call_count, 1);++ should_throw = false; // the transient issue is gone by the next attempt+ EXPECT_EQ(writer.finalize(), std::error_code{});+ EXPECT_EQ(call_count, 2);+}++TEST(HsmDeferredWriterTest, finalize_retries_correctly_after_a_stream_write_throws_partway) {+ FlakyOnceStreamBuf buf;+ buf.fail_on_call = 2; // the header write succeeds; the payload write fails partway through+ std::ostream stream(&buf);+ stream.exceptions(std::ios::badbit);++ auto writer = open_writer(stream);+ const std::string model = "model-bytes";+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(model));+ EXPECT_THROW(writer.finalize(), std::ios_base::failure);++ stream.clear();+ buf.fail_on_call = -1; // the transient issue is gone by the next attempt+ EXPECT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(buf.str());+ ASSERT_TRUE(container.has_value());+ const auto entry = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(entry, nullptr);+ EXPECT_EQ(payload_string(*container, *entry), "model-bytes");+}++TEST(HsmDeferredWriterTest, finalize_retries_correctly_after_the_header_write_itself_throws_partway) {+ FlakyOnceStreamBuf buf;+ buf.fail_on_call = 1; // the header write itself fails partway through, before size is ever updated+ std::ostream stream(&buf);+ stream.exceptions(std::ios::badbit);++ auto writer = open_writer(stream);+ const std::string model = "model-bytes";+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(model));+ EXPECT_THROW(writer.finalize(), std::ios_base::failure);++ stream.clear();+ buf.fail_on_call = -1; // the transient issue is gone by the next attempt+ EXPECT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(buf.str());+ ASSERT_TRUE(container.has_value());+ const auto entry = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(entry, nullptr);+ EXPECT_EQ(payload_string(*container, *entry), "model-bytes");+}++TEST(HsmDeferredWriterTest, finalize_caches_a_normal_non_throwing_failure_instead_of_retrying) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ const std::string model = "model";+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(model));+ stream.setstate(std::ios::badbit);+ EXPECT_EQ(writer.finalize(), hsm::WriteErrc::write_failed);++ stream.clear();+ EXPECT_EQ(writer.finalize(), hsm::WriteErrc::write_failed); // cached, not re-derived+}++TEST(HsmDeferredWriterTest, finalize_rejects_a_sized_layout_whose_slot_computation_would_overflow) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ const std::string payload = "x";+ constexpr size_t huge_align = size_t{1} << 63; // aligned start and aligned size both become 1<<63+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(payload), {huge_align, huge_align});+ EXPECT_EQ(writer.finalize(), hsm::WriteErrc::write_failed);+ EXPECT_TRUE(stream.str().empty()); // rejected before writing anything, not after a wrapped-around size+}++TEST(HsmDeferredWriterTest, finalize_detects_a_misplaced_patch_on_an_append_only_stream) {+ AppendOnlyStreamBuf buf;+ std::ostream stream(&buf);+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id,+ hsm::model_tag,+ std::make_shared<OwnedStringEncoder>("discovered-at-write-time"));+ EXPECT_EQ(writer.finalize(), hsm::WriteErrc::write_failed);+}++TEST(HsmDeferredWriterTest, unsized_section_forces_the_header_to_be_patched_after_the_fact) {+ // With only sized content, the header is computed in one pass up front. An unsized section forces the+ // placeholder-then-patch fallback - verified here by confirming the final header is still correct.+ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id,+ hsm::model_tag,+ std::make_shared<OwnedStringEncoder>("discovered-at-write-time"));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ EXPECT_TRUE(hsm::is_valid_header_fields(container->header));+ const auto entry = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(entry, nullptr);+ EXPECT_EQ(payload_string(*container, *entry), "discovered-at-write-time");+}++TEST(HsmDeferredWriterTest, patches_the_unsized_section_header_relative_to_a_nonzero_stream_start) {+ std::stringstream stream;+ const std::string prefix = "PREFIX-BYTES";+ stream.write(prefix.data(), static_cast<std::streamsize>(prefix.size()));++ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id,+ hsm::model_tag,+ std::make_shared<OwnedStringEncoder>("discovered-at-write-time"));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto whole = stream.str();+ ASSERT_EQ(whole.compare(0, prefix.size(), prefix), 0); // prefix left untouched by the patch+ const auto container = parse_container(whole.substr(prefix.size()));+ ASSERT_TRUE(container.has_value());+ EXPECT_TRUE(hsm::is_valid_header_fields(container->header));+ const auto entry = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(entry, nullptr);+ EXPECT_EQ(payload_string(*container, *entry), "discovered-at-write-time");+}++TEST(HsmDeferredWriterTest, empty_inline_payload_is_written_without_undefined_behavior) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id, hsm::model_id_tag, ov::util::MemoryView{});+ EXPECT_EQ(writer.finalize(), std::error_code{});+}++TEST(HsmDeferredWriterTest, empty_pointer_mode_payload_is_written_without_undefined_behavior) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id, hsm::model_tag, ov::util::MemoryView{});+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ const auto entry = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(entry, nullptr);+ EXPECT_EQ(entry->size, 0u);+}++TEST(HsmDeferredWriterTest, empty_encoder_chunk_is_written_without_undefined_behavior) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id, hsm::model_tag, 0, std::make_shared<EmptyChunkEncoder>());+ EXPECT_EQ(writer.finalize(), std::error_code{});+}++// --- add_section() view overload ---++TEST(HsmDeferredWriterTest, empty_container_is_valid_and_has_no_sections) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ EXPECT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ EXPECT_TRUE(container->entries.empty());+ EXPECT_EQ(find_entry(*container, hsm::any_device_id, hsm::model), nullptr);+}++TEST(HsmDeferredWriterTest, round_trips_inline_and_pointer_sections) {+ const std::string id = "id";+ const std::string model = "compiled-model-bytes";++ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id, hsm::model_id_tag, view_of(id)); // inline-mode Core tag+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(model)); // pointer-mode Core tag+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());++ // Inline entries always carry the full 24-byte slot; the writer zero-fills past the payload.+ const auto read_id = find_entry(*container, hsm::any_device_id, hsm::model_id);+ ASSERT_NE(read_id, nullptr);+ EXPECT_TRUE(read_id->tag.is_inline());+ EXPECT_EQ(payload_string(*container, *read_id).substr(0, 2), "id");++ const auto read_model = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(read_model, nullptr);+ EXPECT_TRUE(read_model->tag.is_pointer());+ EXPECT_EQ(payload_string(*container, *read_model), "compiled-model-bytes");+}++TEST(HsmDeferredWriterTest, tag_reserved_bytes_round_trip_and_default_to_zero) {+ const std::string payload = "device-payload";+ const auto shard_tag = hsm::SectionTag::make_device_tag(/*local_id=*/1, /*is_inline=*/false);+ const std::array<uint8_t, 4> reserved{0x01, 0x02, 0x03, 0x04};++ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(fake_device_id, hsm::SectionTagReserved{shard_tag, reserved}, view_of(payload));+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(payload)); // bare SectionTag still compiles+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());++ const auto shard = find_entry(*container, fake_device_id, shard_tag.id());+ ASSERT_NE(shard, nullptr);+ EXPECT_EQ(shard->tag_reserved, reserved);++ const auto model = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(model, nullptr);+ EXPECT_EQ(model->tag_reserved, (std::array<uint8_t, 4>{}));+}++TEST(HsmDeferredWriterTest, device_specific_section_is_scoped_to_its_device) {+ const std::string payload = "device-payload";+ const auto shard_tag = hsm::SectionTag::make_device_tag(/*local_id=*/1, /*is_inline=*/false);++ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(fake_device_id, shard_tag, view_of(payload));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());++ EXPECT_EQ(find_entry(*container, hsm::any_device_id, shard_tag.id()), nullptr); // scoped to its device+ const auto shard = find_entry(*container, fake_device_id, shard_tag.id());+ ASSERT_NE(shard, nullptr);+ EXPECT_EQ(payload_string(*container, *shard), "device-payload");+}++TEST(HsmDeferredWriterTest, aligns_pointer_section_offset_and_pads_slot_to_aligned_size) {+ const std::string weights = "weights"; // 7 bytes; slot padded to a multiple of 64+ const std::string tail = "tail";+ const auto tail_tag = hsm::SectionTag::make_device_tag(9, false);++ std::vector<std::byte> buffer(k_buffer_capacity);+ auto writer = open_buffer_writer(buffer.data(), buffer.size());+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(weights), {/*offset_align=*/64});+ // offset_align 1: its offset reveals whether the previous slot's size was padded to 64.+ writer.add_section(fake_device_id, tail_tag, view_of(tail));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(buffer.data(), buffer.size());+ ASSERT_TRUE(container.has_value());++ const auto weights_entry = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(weights_entry, nullptr);+ EXPECT_EQ(weights_entry->offset % 64, 0u);+ EXPECT_EQ(payload_string(*container, *weights_entry), "weights");++ const auto tail_entry = find_entry(*container, fake_device_id, tail_tag.id());+ ASSERT_NE(tail_entry, nullptr);+ // Starts after the previous slot padded up to 64 bytes, not right after the 7 payload bytes.+ EXPECT_EQ(tail_entry->offset, weights_entry->offset + 64);+}++TEST(HsmDeferredWriterTest, zero_alignment_behaves_the_same_as_one) {+ const std::string a = "aa";+ const std::string b = "bbb";+ const auto b_tag = hsm::SectionTag::make_device_tag(4, false);++ std::stringstream zero_stream;+ auto zero_writer = open_writer(zero_stream);+ zero_writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(a), {/*offset_align=*/0});+ zero_writer.add_section(fake_device_id, b_tag, view_of(b), {/*offset_align=*/0});+ ASSERT_EQ(zero_writer.finalize(), std::error_code{});++ std::stringstream one_stream;+ auto one_writer = open_writer(one_stream);+ one_writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(a), {/*offset_align=*/1});+ one_writer.add_section(fake_device_id, b_tag, view_of(b), {/*offset_align=*/1});+ ASSERT_EQ(one_writer.finalize(), std::error_code{});++ EXPECT_EQ(zero_stream.str(), one_stream.str());+}++TEST(HsmDeferredWriterTest, size_align_pads_the_slot_independently_of_offset_align) {+ const std::string weights = "weights"; // 7 bytes+ const std::string tail = "tail";+ const auto tail_tag = hsm::SectionTag::make_device_tag(9, false);++ std::vector<std::byte> buffer(k_buffer_capacity);+ auto writer = open_buffer_writer(buffer.data(), buffer.size());+ // Offset aligned to 64, but the slot itself only needs to be padded to a multiple of 16.+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(weights), {/*offset_align=*/64, /*size_align=*/16});+ writer.add_section(fake_device_id, tail_tag, view_of(tail));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(buffer.data(), buffer.size());+ ASSERT_TRUE(container.has_value());++ const auto weights_entry = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(weights_entry, nullptr);+ EXPECT_EQ(weights_entry->offset % 64, 0u);++ const auto tail_entry = find_entry(*container, fake_device_id, tail_tag.id());+ ASSERT_NE(tail_entry, nullptr);+ // Slot padded to 16 (not 64, which the default single-value behavior would have produced).+ EXPECT_EQ(tail_entry->offset, weights_entry->offset + 16);+}++TEST(HsmDeferredWriterTest, preserves_multiple_sections_sharing_one_tag_in_order) {+ const std::string s0 = "shard-0";+ const std::string s1 = "shard-1";+ const auto shard_tag = hsm::SectionTag::make_device_tag(/*local_id=*/2, /*is_inline=*/false);++ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(fake_device_id, shard_tag, view_of(s0));+ writer.add_section(fake_device_id, shard_tag, view_of(s1));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ const auto shards = find_entries(*container, fake_device_id, shard_tag.id());+ ASSERT_EQ(shards.size(), 2u);+ EXPECT_EQ(payload_string(*container, *shards[0]), "shard-0");+ EXPECT_EQ(payload_string(*container, *shards[1]), "shard-1");+}++TEST(HsmDeferredWriterTest, rejects_inline_payload_exceeding_entry_capacity) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ const std::string too_big(25, 'x'); // inline capacity is 24 bytes+ EXPECT_FALSE(writer.add_section(hsm::any_device_id, hsm::model_id_tag, view_of(too_big)));+}++TEST(HsmDeferredWriterTest, rejects_non_power_of_two_alignment) {+ const std::string x = "x";+ std::stringstream stream;+ auto writer = open_writer(stream);+ EXPECT_THROW(writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(x), {/*offset_align=*/3}),+ ov::AssertFailure);+}++TEST(HsmDeferredWriterTest, inline_section_ignores_a_non_power_of_two_alignment) {+ const std::string id = "x";+ std::stringstream stream;+ auto writer = open_writer(stream);+ EXPECT_NO_THROW(writer.add_section(hsm::any_device_id, hsm::model_id_tag, view_of(id), {/*offset_align=*/3}));+ EXPECT_EQ(writer.finalize(), std::error_code{});+}++TEST(HsmDeferredWriterTest, zero_size_align_inherits_alignment) {+ const std::string weights = "weights"; // 7 bytes+ const std::string tail = "tail";+ const auto tail_tag = hsm::SectionTag::make_device_tag(9, false);++ std::stringstream inherited_stream;+ auto inherited = open_writer(inherited_stream);+ inherited.add_section(hsm::any_device_id, hsm::model_tag, view_of(weights), {/*offset_align=*/64}); // size_align=0+ inherited.add_section(fake_device_id, tail_tag, view_of(tail));+ ASSERT_EQ(inherited.finalize(), std::error_code{});++ std::stringstream explicit_stream;+ auto explicit_same = open_writer(explicit_stream);+ explicit_same.add_section(hsm::any_device_id,+ hsm::model_tag,+ view_of(weights),+ {/*offset_align=*/64, /*size_align=*/64});+ explicit_same.add_section(fake_device_id, tail_tag, view_of(tail));+ ASSERT_EQ(explicit_same.finalize(), std::error_code{});++ EXPECT_EQ(inherited_stream.str(), explicit_stream.str());+}++// --- add_section() ISectionEncoder overloads (sized and unsized) ---++TEST(HsmDeferredWriterTest, section_encoder_can_capture_a_copy_of_a_transient_payload) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ {+ const std::string transient = "transient-model";+ writer.add_section(hsm::any_device_id,+ hsm::model_tag,+ transient.size(),+ std::make_shared<OwnedStringEncoder>(transient));+ } // transient destroyed before finalize() - the encoder already captured its own copy+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ const auto model = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(model, nullptr);+ EXPECT_EQ(payload_string(*container, *model), "transient-model");+}++TEST(HsmDeferredWriterTest, fill_in_place_writes_generated_payload_into_the_destination) {+ const std::string content = "filled-bytes";++ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id,+ hsm::model_tag,+ content.size(),+ std::make_shared<StringViewEncoder>(content));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ const auto model = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(model, nullptr);+ EXPECT_EQ(payload_string(*container, *model), "filled-bytes");+}++TEST(HsmDeferredWriterTest, sized_section_encoder_can_split_its_output_into_several_chunks) {+ const std::string expected = "chunk0-chunk1-chunk2-";++ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id, hsm::model_tag, expected.size(), std::make_shared<ChunkedEncoder>());+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ const auto model = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(model, nullptr);+ EXPECT_EQ(payload_string(*container, *model), expected);+}++TEST(HsmDeferredWriterTest, sized_section_encoder_rejects_writing_past_its_declared_size_via_add_section) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id,+ hsm::model_tag,+ /*size=*/2,+ std::make_shared<OwnedStringEncoder>("too-long"));+ EXPECT_THROW(writer.finalize(), ov::AssertFailure);+}++TEST(HsmDeferredWriterTest, sized_section_encoder_rejects_writing_less_than_its_declared_size_via_add_section) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id,+ hsm::model_tag,+ /*size=*/10,+ std::make_shared<OwnedStringEncoder>("short"));+ EXPECT_THROW(writer.finalize(), ov::AssertFailure);+}++TEST(HsmDeferredWriterTest, unsized_section_encoder_discovers_size_after_writing) {+ // Simulates content whose length isn't known until it's actually produced (e.g. serializing a+ // variable-length object) - no size is passed to add_section() at all.+ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id, hsm::model_tag, std::make_shared<ChunkedEncoder>());+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ const auto model = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(model, nullptr);+ EXPECT_EQ(payload_string(*container, *model), "chunk0-chunk1-chunk2-");+}++TEST(HsmDeferredWriterTest, unsized_section_encoder_works_with_a_preallocated_buffer_too) {+ const std::string content = "discovered-at-write-time";++ std::vector<std::byte> buffer(k_buffer_capacity);+ auto writer = open_buffer_writer(buffer.data(), buffer.size());+ writer.add_section(hsm::any_device_id, hsm::model_tag, std::make_shared<StringViewEncoder>(content));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(buffer.data(), buffer.size());+ ASSERT_TRUE(container.has_value());+ const auto model = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(model, nullptr);+ EXPECT_EQ(payload_string(*container, *model), "discovered-at-write-time");+}++// --- add_sections() / ISectionWriterHandler content integration (dispatch logic itself is covered by+// mocks in hsm_writer.cpp - these confirm a real writer produces correct bytes end to end) ---++TEST(HsmDeferredWriterTest, add_sections_lets_a_handler_contribute_its_own_sections) {+ class PluginWriter : public hsm::ISectionWriterHandler {+ public:+ void handle_section(hsm::IWriter& writer) const override {+ writer.add_section(fake_device_id,+ hsm::SectionTag::make_device_tag(/*local_id=*/3, /*is_inline=*/false),+ view_of(m_payload));+ }++ private:+ std::string m_payload = "plugin-section";+ };++ std::stringstream stream;+ auto writer = open_writer(stream);+ PluginWriter plugin;+ writer.add_sections({&plugin});+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ const auto tag = hsm::SectionTag::make_device_tag(3, false);+ const auto section = find_entry(*container, fake_device_id, tag.id());+ ASSERT_NE(section, nullptr);+ EXPECT_EQ(payload_string(*container, *section), "plugin-section");+}++TEST(HsmDeferredWriterTest, section_encoder_avoids_materializing_a_view_for_a_transient_source_at_all) {+ // Builds the view into `value` only inside encode(), not ahead of time at add_section() time.+ class ValueEncoder final : public hsm::ISectionEncoder {+ public:+ explicit ValueEncoder(int value) : m_value(value) {}+ void encode(const hsm::SectionSink& sink) const override {+ sink({reinterpret_cast<const std::byte*>(&m_value), sizeof(m_value)});+ }++ private:+ int m_value;+ };++ class PluginWriter : public hsm::ISectionWriterHandler {+ public:+ void handle_section(hsm::IWriter& writer) const override {+ const int value = 42;+ writer.add_section(fake_device_id,+ hsm::SectionTag::make_device_tag(/*local_id=*/6, /*is_inline=*/false),+ sizeof(value),+ std::make_shared<ValueEncoder>(value));+ }+ };++ std::stringstream stream;+ auto writer = open_writer(stream);+ PluginWriter plugin;+ writer.add_sections({&plugin});+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ const auto tag = hsm::SectionTag::make_device_tag(6, false);+ const auto section = find_entry(*container, fake_device_id, tag.id());+ ASSERT_NE(section, nullptr);+ int decoded = 0;+ std::memcpy(&decoded, container->bytes.data() + section->offset, sizeof(decoded));+ EXPECT_EQ(decoded, 42);+}++TEST(HsmDeferredWriterTest, handler_based_add_section_reuses_one_handler_for_several_sections_sharing_a_tag) {+ class ShardHandler : public hsm::ISectionWriterHandler {+ public:+ explicit ShardHandler(std::vector<std::string> shards) : m_shards(std::move(shards)) {}++ void handle_section(hsm::IWriter& writer) const override {+ for (size_t i = 0; i < m_shards.size(); ++i) {+ writer.add_section(fake_device_id,+ hsm::SectionTag::make_device_tag(/*local_id=*/8, /*is_inline=*/false),+ m_shards[i].size(),+ std::make_shared<StringViewEncoder>(m_shards[i]));+ }+ }++ private:+ std::vector<std::string> m_shards;+ };++ std::stringstream stream;+ auto writer = open_writer(stream);+ ShardHandler handler({"shard-0", "shard-1"});+ writer.add_sections({&handler});+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ const auto tag = hsm::SectionTag::make_device_tag(8, false);+ const auto shards = find_entries(*container, fake_device_id, tag.id());+ ASSERT_EQ(shards.size(), 2u);+ EXPECT_EQ(payload_string(*container, *shards[0]), "shard-0");+ EXPECT_EQ(payload_string(*container, *shards[1]), "shard-1");+}++TEST(HsmDeferredWriterTest, handler_forwards_to_a_named_member_function_instead_of_inlining_logic_in_the_lambda) {+ struct CompiledOptions {+ uint32_t version;+ float scale;+ };++ class OptionsHandler : public hsm::ISectionWriterHandler {+ public:+ explicit OptionsHandler(CompiledOptions options) : m_options(options) {}++ void handle_section(hsm::IWriter& writer) const override {+ // ForwardingEncoder is only a one-line forwarder; write_options() below is an ordinary+ // member function - as long or recursive as needed, with full access to this handler's state.+ class ForwardingEncoder final : public hsm::ISectionEncoder {+ public:+ explicit ForwardingEncoder(const OptionsHandler& owner) : m_owner(owner) {}+ void encode(const hsm::SectionSink& sink) const override {+ m_owner.write_options(sink);+ }++ private:+ const OptionsHandler& m_owner;+ };++ writer.add_section(fake_device_id,+ hsm::SectionTag::make_device_tag(/*local_id=*/10, /*is_inline=*/false),+ sizeof(m_options),+ std::make_shared<ForwardingEncoder>(*this));+ }++ private:+ void write_options(const hsm::SectionSink& sink) const {+ sink({reinterpret_cast<const std::byte*>(&m_options), sizeof(m_options)});+ }++ CompiledOptions m_options;+ };++ std::stringstream stream;+ auto writer = open_writer(stream);+ OptionsHandler handler(CompiledOptions{7, 0.5f});+ writer.add_sections({&handler});+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ const auto tag = hsm::SectionTag::make_device_tag(10, false);+ const auto section = find_entry(*container, fake_device_id, tag.id());+ ASSERT_NE(section, nullptr);+ CompiledOptions decoded{};+ std::memcpy(&decoded, container->bytes.data() + section->offset, sizeof(decoded));+ EXPECT_EQ(decoded.version, 7u);+ EXPECT_FLOAT_EQ(decoded.scale, 0.5f);+}++TEST(HsmDeferredWriterTest, section_encoder_composes_from_several_sub_encoders) {+ // A section built from independent sub-encoders composed via a tiny local helper - no new API+ // needed beyond ISectionEncoder itself: each part is its own encoder, composition just calls each+ // in turn (e.g. for a section assembled from several sub-objects).+ class ComposedEncoder final : public hsm::ISectionEncoder {+ public:+ explicit ComposedEncoder(std::vector<hsm::SectionEncoderPtr> parts) : m_parts(std::move(parts)) {}+ void encode(const hsm::SectionSink& sink) const override {+ for (const auto& part : m_parts) {+ part->encode(sink);+ }+ }++ private:+ std::vector<hsm::SectionEncoderPtr> m_parts;+ };++ const std::string header = "head-";+ const std::string body = "body-";+ const std::string footer = "foot";+ auto encoder = std::make_shared<ComposedEncoder>(std::vector<hsm::SectionEncoderPtr>{+ std::make_shared<StringViewEncoder>(header),+ std::make_shared<StringViewEncoder>(body),+ std::make_shared<StringViewEncoder>(footer),+ });++ std::stringstream stream;+ auto writer = open_writer(stream);+ writer.add_section(hsm::any_device_id,+ hsm::model_tag,+ header.size() + body.size() + footer.size(),+ std::move(encoder));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ const auto model = find_entry(*container, hsm::any_device_id, hsm::model);+ ASSERT_NE(model, nullptr);+ EXPECT_EQ(payload_string(*container, *model), "head-body-foot");+}++// --- Wire-format compatibility: the writer's output must satisfy hsm_format.hpp's own contract ---++TEST(HsmDeferredWriterTest, written_header_satisfies_the_format_contract) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ const std::string model = "model";+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(model));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ hsm::Header header{};+ const auto bytes = stream.str();+ header = hsm::Header::view(reinterpret_cast<const uint8_t*>(bytes.data()));+ EXPECT_TRUE(hsm::is_recognized_header(header));+ EXPECT_TRUE(hsm::is_valid_header_fields(header));+ EXPECT_EQ(header.magic, hsm::BlobMagic::single);+ EXPECT_EQ(header.version_major, hsm::FormatVersion::major);+ EXPECT_EQ(header.version_minor, hsm::FormatVersion::minor);+}++TEST(HsmDeferredWriterTest, every_written_manifest_entry_has_valid_section_bounds) {+ std::stringstream stream;+ auto writer = open_writer(stream);+ const std::string id = "id";+ const std::string model = "model-bytes";+ writer.add_section(hsm::any_device_id, hsm::model_id_tag, view_of(id));+ writer.add_section(hsm::any_device_id, hsm::model_tag, view_of(model));+ ASSERT_EQ(writer.finalize(), std::error_code{});++ const auto container = parse_container(stream.str());+ ASSERT_TRUE(container.has_value());+ for (const auto& entry : container->entries) {+ EXPECT_TRUE(hsm::is_valid_section_bounds(entry, container->header));+ }+}++} // namespace ov::testdiff --git a/src/inference/tests/unit/hsm_writer.cpp b/src/inference/tests/unit/hsm_writer.cppnew file mode 100644index 00000000000..11c81435d01--- /dev/null+++ b/src/inference/tests/unit/hsm_writer.cpp@@ -0,0 +1,106 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/runtime/hsm_writer.hpp"++#include <gmock/gmock.h>+#include <gtest/gtest.h>++#include <string>+#include <vector>++// IWriter-interface-level tests only - no concrete IWriter implementation (e.g. DeferredWriter) is used+// here; a mock stands in wherever one is needed. Tests exercising a real implementation's behavior+// belong in that implementation's own test file (e.g. hsm_deferred_writer.cpp for DeferredWriter).+namespace ov::test {+namespace hsm = ov::runtime::hsm;++using testing::_, testing::A, testing::Ref, testing::Return;+namespace {++// Mocks IWriter's pure virtuals so add_sections() - the interface's one concrete member - can be tested+// without any concrete IWriter implementation.+class MockIWriter : public hsm::IWriter {+public:+ MOCK_METHOD(bool,+ add_section,+ (hsm::DeviceId, hsm::SectionTagReserved, ov::util::MemoryView, hsm::SectionAlignment),+ (override));+ MOCK_METHOD(bool,+ add_section,+ (hsm::DeviceId, hsm::SectionTagReserved, size_t, hsm::SectionEncoderPtr, hsm::SectionAlignment),+ (override));+ MOCK_METHOD(bool,+ add_section,+ (hsm::DeviceId, hsm::SectionTagReserved, hsm::SectionEncoderPtr, hsm::SectionAlignment),+ (override));+ MOCK_METHOD(std::error_code, finalize, (), (override));+};++class MockSectionWriterHandler : public hsm::ISectionWriterHandler {+public:+ MOCK_METHOD(void, handle_section, (hsm::IWriter&), (const, override));+};++} // namespace++// --- add_sections() - IWriter's one concrete (non-pure-virtual) member ---++TEST(HsmWriterTest, add_sections_dispatches_to_each_non_null_handler_once_in_order) {+ MockIWriter writer;+ MockSectionWriterHandler first;+ MockSectionWriterHandler second;++ {+ ::testing::InSequence in_order;+ EXPECT_CALL(first, handle_section(Ref(writer))).Times(1);+ EXPECT_CALL(second, handle_section(Ref(writer))).Times(1);+ }++ writer.add_sections({&first, &second});+}++TEST(HsmWriterTest, add_sections_skips_a_null_handler) {+ MockIWriter writer;+ MockSectionWriterHandler handler;+ EXPECT_CALL(handler, handle_section(Ref(writer))).Times(1);++ EXPECT_NO_THROW(writer.add_sections({nullptr, &handler, nullptr}));+}++// --- IWriter::add_section()'s 3 overloads, each reachable through a dispatched handler ---++TEST(HsmWriterTest, add_sections_lets_a_dispatched_handler_use_any_add_section_overload) {+ MockIWriter writer;+ MockSectionWriterHandler handler;+ const std::string payload = "data";+ const ov::util::MemoryView view{reinterpret_cast<const std::byte*>(payload.data()), payload.size()};++ EXPECT_CALL(handler, handle_section(Ref(writer))).WillOnce([&](auto& w) {+ w.add_section(hsm::any_device_id, hsm::model_tag, view); // view overload+ w.add_section(hsm::any_device_id, hsm::model_tag, size_t{4}, nullptr); // sized-encoder overload+ w.add_section(hsm::any_device_id, hsm::model_tag, nullptr); // unsized-encoder overload+ });+ EXPECT_CALL(writer, add_section(_, _, A<ov::util::MemoryView>(), _)).WillOnce(Return(true));+ EXPECT_CALL(writer, add_section(_, _, size_t{4}, _, _)).WillOnce(Return(true));+ EXPECT_CALL(writer, add_section(_, _, A<hsm::SectionEncoderPtr>(), _)).WillOnce(Return(true));++ writer.add_sections({&handler});+}++// --- WriteErrc / make_error_code ---++TEST(HsmWriterTest, write_errc_message_is_human_readable) {+ const auto ec = hsm::make_error_code(hsm::WriteErrc::write_failed);+ EXPECT_FALSE(ec.message().empty());+ EXPECT_EQ(ec, hsm::WriteErrc::write_failed);+}++TEST(HsmWriterTest, write_errc_category_reports_unknown_for_an_unrecognized_value) {+ const auto ec = hsm::make_error_code(static_cast<hsm::WriteErrc>(0));+ EXPECT_EQ(ec.message(), "unknown error");+ EXPECT_STREQ(ec.category().name(), "ov::runtime::hsm::Write");+}++} // namespace ov::test