From 3aeb1a47155ef6d8cf0f2c714d1ec172fe729d1f Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Thu, 19 Nov 2026 12:19:55 -0600 Subject: [PATCH 01/19] Synchronize PAL lifecycle generations Publish complete PAL generations atomically so concurrent initialization and shutdown cannot race provider ownership or close a newer logging stream. Release providers outside the state lock and roll back failed initialization. Files: lib/pal/PAL.cpp, lib/pal/PAL.hpp, tests/functests/BasicFuncTests.cpp, tests/no-exceptions/no-exceptions-smoke.cpp, tests/unittests/PalTests.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f7e2f450-c2c4-43c5-9fb1-05fa4f7d8e9e --- lib/pal/PAL.cpp | 271 ++++++--- lib/pal/PAL.hpp | 8 +- tests/functests/BasicFuncTests.cpp | 14 +- tests/no-exceptions/no-exceptions-smoke.cpp | 18 + tests/unittests/PalTests.cpp | 597 +++++++++++++++++++- 5 files changed, 798 insertions(+), 110 deletions(-) diff --git a/lib/pal/PAL.cpp b/lib/pal/PAL.cpp index 94a71b4a0..8356e3648 100644 --- a/lib/pal/PAL.cpp +++ b/lib/pal/PAL.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -137,32 +138,23 @@ namespace PAL_NS_BEGIN { #define DBG_BUFFER_LEN 2048 -#ifndef _WIN32 -#define DEBUG_LOG_NULL "/dev/null" -#else -#define DEBUG_LOG_NULL "NUL" -#endif - - bool isLoggingInited = false; - #ifdef HAVE_MAT_LOGGING std::recursive_mutex debugLogMutex; std::string debugLogPath; std::unique_ptr debugLogStream; + bool isLoggingInited = false; + uint64_t debugLogEpoch = 0; - bool log_init(bool isTraceEnabled, const std::string& traceFolderPath) + bool log_init(bool isTraceEnabled, const std::string& traceFolderPath, uint64_t& epoch) { + std::lock_guard lock(debugLogMutex); + epoch = 0; if (!isTraceEnabled) { + isLoggingInited = false; return false; } - bool result = true; - if (debugLogStream != nullptr) - { - return result; - } - // Check if the path exists #if defined(_WIN32) || defined(_WIN64) DWORD fileAttr = GetFileAttributesA(traceFolderPath.c_str()); @@ -175,29 +167,46 @@ namespace PAL_NS_BEGIN { if (!pathExists || containsParentDirectory) { + isLoggingInited = false; return false; } - debugLogMutex.lock(); - debugLogPath = traceFolderPath; - if (debugLogPath.back() != '/' && debugLogPath.back() != '\\') + std::string requestedPath = traceFolderPath; + if (requestedPath.back() != '/' && requestedPath.back() != '\\') { - debugLogPath += "/"; + requestedPath += "/"; } - debugLogPath += "mat-debug-"; - debugLogPath += std::to_string(MAT::GetCurrentProcessId()); - debugLogPath += ".log"; + requestedPath += "mat-debug-"; + requestedPath += std::to_string(MAT::GetCurrentProcessId()); + requestedPath += ".log"; - debugLogStream = std::unique_ptr(new std::fstream()); - debugLogStream->open(debugLogPath, std::fstream::out); - if (!debugLogStream->is_open()) + if (!debugLogStream || debugLogPath != requestedPath) { - // If file cannot be created, log to /dev/null - debugLogStream->open(DEBUG_LOG_NULL); - result = false; + isLoggingInited = false; + debugLogStream.reset(); + debugLogPath = std::move(requestedPath); + auto stream = std::unique_ptr(new std::fstream()); + stream->open(debugLogPath, std::fstream::out); + if (!stream->is_open()) + { + return false; + } + debugLogStream = std::move(stream); } - debugLogMutex.unlock(); - return result; + + if (++debugLogEpoch == 0) + { + ++debugLogEpoch; + } + epoch = debugLogEpoch; + isLoggingInited = true; + return true; + } + + bool log_init(bool isTraceEnabled, const std::string& traceFolderPath) + { + uint64_t epoch; + return log_init(isTraceEnabled, traceFolderPath, epoch); } const std::unique_ptr& getDebugLogStream() noexcept @@ -212,21 +221,28 @@ namespace PAL_NS_BEGIN { void log_done() { - debugLogMutex.lock(); - if (debugLogStream) + std::lock_guard lock(debugLogMutex); + debugLogStream.reset(); + isLoggingInited = false; + } + + void log_done(uint64_t epoch) + { + std::lock_guard lock(debugLogMutex); + if (epoch != 0 && epoch == debugLogEpoch) { - debugLogStream = nullptr; + debugLogStream.reset(); isLoggingInited = false; } - debugLogMutex.unlock(); } #else - bool log_init(bool /*isTraceEnabled*/, const std::string& /*traceFolderPath*/) + bool log_init(bool /*isTraceEnabled*/, const std::string& /*traceFolderPath*/, uint64_t& epoch) { + epoch = 0; return false; } - void log_done() + void log_done(uint64_t /*epoch*/) { } #endif @@ -362,6 +378,7 @@ namespace PAL_NS_BEGIN { std::shared_ptr PlatformAbstractionLayer::getDefaultTaskDispatcher() { + std::lock_guard lock(m_stateLock); if (!m_taskDispatcher) { // Default implementation of task dispatcher is a single-threaded worker thread task queue @@ -567,43 +584,53 @@ namespace PAL_NS_BEGIN { void PlatformAbstractionLayer::registerSemanticContext(ISemanticContext* context) { - if (m_DeviceInformation != nullptr) + std::shared_ptr deviceInformation; + std::shared_ptr systemInformation; + std::shared_ptr networkInformation; + { + std::lock_guard lock(m_stateLock); + deviceInformation = m_DeviceInformation; + systemInformation = m_SystemInformation; + networkInformation = m_NetworkInformation; + } + + if (deviceInformation != nullptr) { - const auto& deviceId = m_DeviceInformation->GetDeviceId(); + const auto& deviceId = deviceInformation->GetDeviceId(); #ifdef MATSDK_DISABLE_DEVICE_ID if (!deviceId.empty()) #endif context->SetDeviceId(deviceId); - context->SetDeviceModel(m_DeviceInformation->GetModel()); - context->SetDeviceMake(m_DeviceInformation->GetManufacturer()); + context->SetDeviceModel(deviceInformation->GetModel()); + context->SetDeviceMake(deviceInformation->GetManufacturer()); } - if (m_SystemInformation != nullptr) + if (systemInformation != nullptr) { // Get SystemInfo common fields - context->SetOsVersion(m_SystemInformation->GetOsMajorVersion()); - context->SetOsName(m_SystemInformation->GetOsName()); - context->SetOsBuild(m_SystemInformation->GetOsFullVersion()); - context->SetDeviceClass(m_SystemInformation->GetDeviceClass()); + context->SetOsVersion(systemInformation->GetOsMajorVersion()); + context->SetOsName(systemInformation->GetOsName()); + context->SetOsBuild(systemInformation->GetOsFullVersion()); + context->SetDeviceClass(systemInformation->GetDeviceClass()); // AppInfo fields - context->SetAppId(m_SystemInformation->GetAppId()); - context->SetAppVersion(m_SystemInformation->GetAppVersion()); - context->SetAppLanguage(m_SystemInformation->GetAppLanguage()); + context->SetAppId(systemInformation->GetAppId()); + context->SetAppVersion(systemInformation->GetAppVersion()); + context->SetAppLanguage(systemInformation->GetAppLanguage()); // UserInfo fields. - context->SetUserLanguage(m_SystemInformation->GetUserLanguage()); - context->SetUserTimeZone(m_SystemInformation->GetUserTimeZone()); - //context->SetUserAdvertisingId(m_SystemInformation->GetUserAdvertisingId()); + context->SetUserLanguage(systemInformation->GetUserLanguage()); + context->SetUserTimeZone(systemInformation->GetUserTimeZone()); + //context->SetUserAdvertisingId(systemInformation->GetUserAdvertisingId()); - context->SetCommercialId(m_SystemInformation->GetCommercialId()); + context->SetCommercialId(systemInformation->GetCommercialId()); } - if (m_NetworkInformation != nullptr) + if (networkInformation != nullptr) { // Get NetworkInfo common fields - context->SetNetworkProvider(m_NetworkInformation->GetNetworkProvider()); - context->SetNetworkCost(m_NetworkInformation->GetNetworkCost()); - context->SetNetworkType(m_NetworkInformation->GetNetworkType()); + context->SetNetworkProvider(networkInformation->GetNetworkProvider()); + context->SetNetworkCost(networkInformation->GetNetworkCost()); + context->SetNetworkType(networkInformation->GetNetworkType()); } } @@ -637,53 +664,129 @@ namespace PAL_NS_BEGIN { void PlatformAbstractionLayer::initialize(IRuntimeConfig& configuration) { - if (m_palStarted.fetch_add(1) == 0) { + std::unique_lock lock(m_stateLock); + m_stateChanged.wait(lock, [this] { return !m_initializing; }); + if (m_palStarted > 0) + { + const size_t count = ++m_palStarted; + lock.unlock(); + LOG_INFO("Already initialized: %zu", count); + (void)count; + return; + } + m_initializing = true; + } + + // Platform provider factories can invoke callbacks that access PAL. + uint64_t logEpoch = 0; + std::shared_ptr systemInformation; + std::shared_ptr deviceInformation; + std::shared_ptr networkInformation; +#if HAVE_EXCEPTIONS + try + { +#endif std::string traceFolderPath = MAT::GetTempDirectory(); if (configuration.HasConfig(CFG_STR_TRACE_FOLDER_PATH)) { traceFolderPath = static_cast(configuration[CFG_STR_TRACE_FOLDER_PATH]); } - detail::isLoggingInited = detail::log_init(configuration[CFG_BOOL_ENABLE_TRACE], traceFolderPath); + detail::log_init(configuration[CFG_BOOL_ENABLE_TRACE], traceFolderPath, logEpoch); LOG_TRACE("Initializing..."); - m_SystemInformation = SystemInformationImpl::Create(configuration); - m_DeviceInformation = DeviceInformationImpl::Create(configuration); - m_NetworkInformation = NetworkInformationImpl::Create(configuration); - LOG_INFO("Initialized"); + systemInformation = SystemInformationImpl::Create(configuration); + deviceInformation = DeviceInformationImpl::Create(configuration); + networkInformation = NetworkInformationImpl::Create(configuration); +#if HAVE_EXCEPTIONS } - else + catch (...) + { + networkInformation.reset(); + deviceInformation.reset(); + systemInformation.reset(); + detail::log_done(logEpoch); + { + std::lock_guard lock(m_stateLock); + m_initializing = false; + } + m_stateChanged.notify_all(); + throw; + } +#endif + { - LOG_INFO("Already initialized: %d", m_palStarted.load()); + std::lock_guard lock(m_stateLock); + m_SystemInformation = std::move(systemInformation); + m_DeviceInformation = std::move(deviceInformation); + m_NetworkInformation = std::move(networkInformation); + m_logEpoch = logEpoch; + m_palStarted = 1; + m_initializing = false; } + m_stateChanged.notify_all(); + LOG_INFO("Initialized"); + } + + std::shared_ptr PlatformAbstractionLayer::GetNetworkInformation() const noexcept + { + std::lock_guard lock(m_stateLock); + return m_NetworkInformation; + } + + std::shared_ptr PlatformAbstractionLayer::GetDeviceInformation() const noexcept + { + std::lock_guard lock(m_stateLock); + return m_DeviceInformation; } - std::shared_ptr PlatformAbstractionLayer::GetNetworkInformation() const noexcept { return m_NetworkInformation; } - std::shared_ptr PlatformAbstractionLayer::GetDeviceInformation() const noexcept { return m_DeviceInformation; } - std::shared_ptr PlatformAbstractionLayer::GetSystemInformation() const noexcept { return m_SystemInformation; } + std::shared_ptr PlatformAbstractionLayer::GetSystemInformation() const noexcept + { + std::lock_guard lock(m_stateLock); + return m_SystemInformation; + } void PlatformAbstractionLayer::shutdown() { - if (m_palStarted == 0) + std::shared_ptr taskDispatcher; + std::shared_ptr systemInformation; + std::shared_ptr deviceInformation; + std::shared_ptr networkInformation; + uint64_t logEpoch = 0; { - LOG_ERROR("PAL is already shutdown!"); - return; - } + std::unique_lock lock(m_stateLock); + m_stateChanged.wait(lock, [this] { return !m_initializing; }); + if (m_palStarted == 0) + { + lock.unlock(); + LOG_ERROR("PAL is already shutdown!"); + return; + } + if (--m_palStarted > 0) + { + const size_t count = m_palStarted; + lock.unlock(); + LOG_INFO("Shutting down: %zu", count); + (void)count; + return; + } - if (m_palStarted.fetch_sub(1) == 1) - { - LOG_TRACE("Shutting down..."); - if (m_taskDispatcher) { m_taskDispatcher = nullptr; } - if (m_SystemInformation) { m_SystemInformation = nullptr; } - if (m_DeviceInformation) { m_DeviceInformation = nullptr; } - if (m_NetworkInformation) { m_NetworkInformation = nullptr; } - LOG_INFO("Shut down"); - detail::log_done(); - } - else - { - LOG_INFO("Shutting down: %d", m_palStarted.load()); + taskDispatcher = std::move(m_taskDispatcher); + systemInformation = std::move(m_SystemInformation); + deviceInformation = std::move(m_DeviceInformation); + networkInformation = std::move(m_NetworkInformation); + logEpoch = m_logEpoch; + m_logEpoch = 0; } + + LOG_TRACE("Shutting down..."); + // Releasing the last dispatcher reference can join a worker that re-enters PAL. + taskDispatcher.reset(); + systemInformation.reset(); + deviceInformation.reset(); + networkInformation.reset(); + LOG_INFO("Shut down"); + detail::log_done(logEpoch); } #ifndef HAVE_MAT_UTC diff --git a/lib/pal/PAL.hpp b/lib/pal/PAL.hpp index f79cdd080..209d1ad6c 100644 --- a/lib/pal/PAL.hpp +++ b/lib/pal/PAL.hpp @@ -111,7 +111,11 @@ namespace PAL_NS_BEGIN MATSDK_LOG_DECL_COMPONENT_CLASS(); private: - volatile std::atomic m_palStarted { 0 }; + mutable std::mutex m_stateLock; + std::condition_variable m_stateChanged; + bool m_initializing = false; + size_t m_palStarted = 0; + uint64_t m_logEpoch = 0; std::shared_ptr m_taskDispatcher; std::shared_ptr m_SystemInformation; std::shared_ptr m_NetworkInformation; @@ -243,9 +247,11 @@ namespace PAL_NS_BEGIN namespace detail { bool log_init(bool isTraceEnabled, const std::string& traceFolderPath); + bool log_init(bool isTraceEnabled, const std::string& traceFolderPath, uint64_t& epoch); const std::unique_ptr& getDebugLogStream() noexcept; const std::string& getDebugLogPath() noexcept; void log_done(); + void log_done(uint64_t epoch); } #endif diff --git a/tests/functests/BasicFuncTests.cpp b/tests/functests/BasicFuncTests.cpp index 7f231b07b..a66d03c28 100644 --- a/tests/functests/BasicFuncTests.cpp +++ b/tests/functests/BasicFuncTests.cpp @@ -44,27 +44,31 @@ namespace PAL_NS_BEGIN static long GetPalRefCount() { - return PAL::GetPAL().m_palStarted.load(); + auto& pal = PAL::GetPAL(); + std::lock_guard lock(pal.m_stateLock); + return static_cast(pal.m_palStarted); }; static std::shared_ptr GetTaskDispatcher() { - return PAL::GetPAL().m_taskDispatcher; + auto& pal = PAL::GetPAL(); + std::lock_guard lock(pal.m_stateLock); + return pal.m_taskDispatcher; }; static std::shared_ptr GetSystemInformation() { - return PAL::GetPAL().m_SystemInformation; + return PAL::GetPAL().GetSystemInformation(); } static std::shared_ptr GetNetworkInformation() { - return PAL::GetPAL().m_NetworkInformation; + return PAL::GetPAL().GetNetworkInformation(); } static std::shared_ptr GetDeviceInformation() { - return PAL::GetPAL().m_DeviceInformation; + return PAL::GetPAL().GetDeviceInformation(); } }; } diff --git a/tests/no-exceptions/no-exceptions-smoke.cpp b/tests/no-exceptions/no-exceptions-smoke.cpp index d85307af3..e7d7a3fc0 100644 --- a/tests/no-exceptions/no-exceptions-smoke.cpp +++ b/tests/no-exceptions/no-exceptions-smoke.cpp @@ -5,7 +5,9 @@ #include "LogConfiguration.hpp" #include "CorrelationVector.hpp" #include "TransmitProfiles.hpp" +#include "config/RuntimeConfig_Default.hpp" #include "http/HttpResponseDecoder.hpp" +#include "pal/PAL.hpp" #include "utils/ZlibUtils.hpp" #include @@ -91,6 +93,22 @@ namespace int main() { + ILogConfiguration logConfiguration; + RuntimeConfig_Default runtimeConfiguration(logConfiguration); + PAL::PlatformAbstractionLayer pal; + pal.initialize(runtimeConfiguration); + pal.initialize(runtimeConfiguration); + check(pal.GetSystemInformation() && pal.GetDeviceInformation() && pal.GetNetworkInformation(), + "PAL initialization must publish all providers"); +#ifdef MATSDK_DISABLE_DEVICE_ID + check(pal.GetDeviceInformation()->GetDeviceId().empty(), "native device ID must remain disabled"); +#endif + pal.shutdown(); + check(pal.GetSystemInformation() != nullptr, "PAL must retain providers until its final shutdown"); + pal.shutdown(); + check(!pal.GetSystemInformation() && !pal.GetDeviceInformation() && !pal.GetNetworkInformation(), + "PAL final shutdown must release its providers"); + const char* invalidConfigurations[] = {nullptr, "", "[", "not-json", "null", "1", "\"text\"", "[]", "[{}]"}; for (const char* input : invalidConfigurations) { diff --git a/tests/unittests/PalTests.cpp b/tests/unittests/PalTests.cpp index 9d4ba3891..ca0ec9add 100644 --- a/tests/unittests/PalTests.cpp +++ b/tests/unittests/PalTests.cpp @@ -4,12 +4,16 @@ // #include "common/Common.hpp" +#include "config/RuntimeConfig_Default.hpp" +#include "pal/PAL.hpp" #include "pal/PseudoRandomGenerator.hpp" #include "pal/TaskDispatcher.hpp" #include "pal/WorkerThread.hpp" +#include "NullObjects.hpp" #include "Version.hpp" #include +#include #include #include #include @@ -22,13 +26,12 @@ #include #include #include +#include +#include #ifdef HAVE_MAT_LOGGING -#include "pal/PAL.hpp" #include #include -#include -#include #include #if defined(_WIN32) || defined(_WIN64) #include @@ -40,6 +43,35 @@ using namespace PAL::detail; using namespace testing; +namespace PAL_NS_BEGIN { +#ifdef HAVE_MAT_LOGGING + namespace detail + { + extern std::recursive_mutex debugLogMutex; + extern std::string debugLogPath; + extern std::unique_ptr debugLogStream; + extern bool isLoggingInited; + extern uint64_t debugLogEpoch; + } +#endif + + class PALTest + { + public: + static bool HasDispatcher(const PlatformAbstractionLayer& pal) + { + std::lock_guard lock(pal.m_stateLock); + return static_cast(pal.m_taskDispatcher); + } + + static bool IsInitializing(const PlatformAbstractionLayer& pal) + { + std::lock_guard lock(pal.m_stateLock); + return pal.m_initializing; + } + }; +} PAL_NS_END + #if defined(_WIN32) || defined(_WIN64) namespace PAL_NS_BEGIN { std::string formatWindowsOsFullVersion( @@ -51,7 +83,384 @@ namespace PAL_NS_BEGIN { } PAL_NS_END #endif -class PalTests : public Test {}; +namespace +{ +#ifdef HAVE_MAT_LOGGING + class ScopedLogState + { + public: + ScopedLogState() + { + std::lock_guard lock(PAL::detail::debugLogMutex); + m_path = std::move(PAL::detail::debugLogPath); + m_stream = std::move(PAL::detail::debugLogStream); + m_enabled = PAL::detail::isLoggingInited; + m_epoch = PAL::detail::debugLogEpoch; + PAL::detail::isLoggingInited = false; + } + + ~ScopedLogState() + { + std::lock_guard lock(PAL::detail::debugLogMutex); + PAL::detail::debugLogStream = std::move(m_stream); + PAL::detail::debugLogPath = std::move(m_path); + PAL::detail::debugLogEpoch = m_epoch; + PAL::detail::isLoggingInited = m_enabled; + } + + private: + std::string m_path; + std::unique_ptr m_stream; + uint64_t m_epoch = 0; + bool m_enabled = false; + }; +#endif + + class BlockingRuntimeConfig : public MAT::RuntimeConfig_Default + { + public: + BlockingRuntimeConfig( + MAT::ILogConfiguration& configuration, + std::promise& entered, + std::shared_future release) + : RuntimeConfig_Default(configuration), m_entered(entered), m_release(std::move(release)) + { + } + + bool HasConfig(const char* key) override + { + if (!m_blocked.exchange(true)) + { + m_entered.set_value(); + m_release.wait(); + } + return RuntimeConfig_Default::HasConfig(key); + } + + private: + std::promise& m_entered; + std::shared_future m_release; + std::atomic m_blocked { false }; + }; + +#if HAVE_EXCEPTIONS + class ThrowOnceRuntimeConfig : public MAT::RuntimeConfig_Default + { + public: + explicit ThrowOnceRuntimeConfig(MAT::ILogConfiguration& configuration) + : RuntimeConfig_Default(configuration) + { + } + + MAT::Variant& operator[](const char* key) override + { + if (m_throw && std::string(key) == CFG_BOOL_ENABLE_NET_DETECT) + { + m_throw = false; + throw std::runtime_error("PAL initialization failed"); + } + return RuntimeConfig_Default::operator[](key); + } + + private: + bool m_throw = true; + }; +#endif + + class ReinitializePalTask + { + public: + ReinitializePalTask( + PAL::PlatformAbstractionLayer& pal, + MAT::IRuntimeConfig& configuration, + std::shared_future release, + std::atomic& shouldInitialize, + std::promise& started, + std::promise& finished, + std::shared_ptr& replacement) + : m_pal(pal), + m_configuration(configuration), + m_release(std::move(release)), + m_shouldInitialize(shouldInitialize), + m_started(started), + m_finished(finished), + m_replacement(replacement) + { + } + + void Run() + { + m_started.set_value(); + m_release.wait(); + if (m_shouldInitialize.load()) + { + m_pal.initialize(m_configuration); + m_replacement = m_pal.getDefaultTaskDispatcher(); + m_pal.shutdown(); + } + m_finished.set_value(); + } + + private: + PAL::PlatformAbstractionLayer& m_pal; + MAT::IRuntimeConfig& m_configuration; + std::shared_future m_release; + std::atomic& m_shouldInitialize; + std::promise& m_started; + std::promise& m_finished; + std::shared_ptr& m_replacement; + }; + + class SignalTask + { + public: + explicit SignalTask(std::promise& signal) : m_signal(signal) {} + void Run() { m_signal.set_value(); } + + private: + std::promise& m_signal; + }; + + class BlockingTask + { + public: + BlockingTask(std::promise& started, std::shared_future release) + : m_started(started), m_release(std::move(release)) + { + } + + void Run() + { + m_started.set_value(); + m_release.wait(); + } + + private: + std::promise& m_started; + std::shared_future m_release; + }; + + class BlockingSemanticContext : public MAT::NullContext + { + public: + BlockingSemanticContext(std::promise& entered, std::shared_future release) + : m_entered(entered), m_release(std::move(release)) + { + } + + void SetDeviceId(const std::string& value) override + { + deviceId = value; + sawDeviceId = true; + } + + void SetDeviceModel(const std::string& value) override + { + m_entered.set_value(); + m_release.wait(); + deviceModel = value; + sawDeviceModel = true; + } + + void SetOsName(const std::string& value) override + { + osName = value; + sawOsName = true; + } + + void SetNetworkProvider(const std::string&) override + { + sawNetworkProvider = true; + } + + std::string deviceId; + std::string deviceModel; + std::string osName; + bool sawDeviceId = false; + bool sawDeviceModel = false; + bool sawOsName = false; + bool sawNetworkProvider = false; + + private: + std::promise& m_entered; + std::shared_future m_release; + }; +} + +class PalTests : public Test +{ +#ifdef HAVE_MAT_LOGGING + ScopedLogState m_logState; +#endif +}; + +TEST_F(PalTests, ConcurrentInitializationPublishesCompleteState) +{ + MAT::ILogConfiguration logConfiguration; + logConfiguration[CFG_BOOL_ENABLE_TRACE] = false; + std::promise firstEntered; + std::promise releaseFirst; + auto firstEnteredFuture = firstEntered.get_future(); + BlockingRuntimeConfig configuration(logConfiguration, firstEntered, releaseFirst.get_future().share()); + PAL::PlatformAbstractionLayer pal; + + struct Observation + { + std::shared_ptr system; + std::shared_ptr device; + std::shared_ptr network; + std::shared_ptr dispatcher; + }; + std::array observations; + auto initialize = [&](size_t index) { + pal.initialize(configuration); + observations[index].system = pal.GetSystemInformation(); + observations[index].device = pal.GetDeviceInformation(); + observations[index].network = pal.GetNetworkInformation(); + observations[index].dispatcher = pal.getDefaultTaskDispatcher(); + }; + + std::thread first([&] { initialize(0); }); + if (firstEnteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + releaseFirst.set_value(); + first.join(); + pal.shutdown(); + FAIL() << "The first initializer did not enter the configuration"; + } + + std::promise secondStarted; + std::promise secondFinished; + auto secondStartedFuture = secondStarted.get_future(); + auto secondFinishedFuture = secondFinished.get_future(); + std::thread second([&] { + secondStarted.set_value(); + initialize(1); + secondFinished.set_value(); + }); + secondStartedFuture.wait(); + + auto getter = std::async(std::launch::async, [&] { return pal.GetSystemInformation(); }); + const auto getterStatus = getter.wait_for(std::chrono::seconds(2)); + const auto secondStatus = secondFinishedFuture.wait_for(std::chrono::milliseconds(250)); + releaseFirst.set_value(); + first.join(); + second.join(); + + EXPECT_EQ(getterStatus, std::future_status::ready); + EXPECT_EQ(getter.get(), nullptr); + EXPECT_EQ(secondStatus, std::future_status::timeout); + EXPECT_THAT(observations[0].system, NotNull()); + EXPECT_THAT(observations[0].device, NotNull()); + EXPECT_THAT(observations[0].network, NotNull()); + EXPECT_THAT(observations[0].dispatcher, NotNull()); + EXPECT_EQ(observations[0].system, observations[1].system); + EXPECT_EQ(observations[0].device, observations[1].device); + EXPECT_EQ(observations[0].network, observations[1].network); + EXPECT_EQ(observations[0].dispatcher, observations[1].dispatcher); + + std::promise releaseShutdown; + auto shutdownGate = releaseShutdown.get_future().share(); + std::thread shutdown1([&] { shutdownGate.wait(); pal.shutdown(); }); + std::thread shutdown2([&] { shutdownGate.wait(); pal.shutdown(); }); + releaseShutdown.set_value(); + shutdown1.join(); + shutdown2.join(); + EXPECT_EQ(pal.GetSystemInformation(), nullptr); + EXPECT_EQ(pal.GetDeviceInformation(), nullptr); + EXPECT_EQ(pal.GetNetworkInformation(), nullptr); + EXPECT_FALSE(PAL::PALTest::HasDispatcher(pal)); +} + +#if HAVE_EXCEPTIONS +TEST_F(PalTests, FailedInitializationCanBeRetried) +{ + MAT::ILogConfiguration logConfiguration; + logConfiguration[CFG_BOOL_ENABLE_TRACE] = false; + ThrowOnceRuntimeConfig configuration(logConfiguration); + PAL::PlatformAbstractionLayer pal; + + EXPECT_THROW(pal.initialize(configuration), std::runtime_error); + ASSERT_FALSE(PAL::PALTest::IsInitializing(pal)); + EXPECT_FALSE(pal.GetSystemInformation()); + EXPECT_FALSE(pal.GetDeviceInformation()); + EXPECT_FALSE(pal.GetNetworkInformation()); + pal.initialize(configuration); + EXPECT_THAT(pal.GetSystemInformation(), NotNull()); + pal.shutdown(); +} +#endif + +TEST_F(PalTests, RetainedDispatcherSurvivesFinalShutdown) +{ + MAT::ILogConfiguration logConfiguration; + logConfiguration[CFG_BOOL_ENABLE_TRACE] = false; + MAT::RuntimeConfig_Default configuration(logConfiguration); + PAL::PlatformAbstractionLayer pal; + pal.initialize(configuration); + auto dispatcher = pal.getDefaultTaskDispatcher(); + pal.shutdown(); + + std::promise ran; + auto ranFuture = ran.get_future(); + SignalTask task(ran); + PAL::dispatchTask(dispatcher.get(), &task, &SignalTask::Run); + EXPECT_EQ(ranFuture.wait_for(std::chrono::seconds(5)), std::future_status::ready); + dispatcher.reset(); +} + +TEST_F(PalTests, WorkerCanReinitializeWhileFinalShutdownReleasesDispatcher) +{ + MAT::ILogConfiguration logConfiguration; + logConfiguration[CFG_BOOL_ENABLE_TRACE] = false; + MAT::RuntimeConfig_Default configuration(logConfiguration); + PAL::PlatformAbstractionLayer pal; + pal.initialize(configuration); + auto dispatcher = pal.getDefaultTaskDispatcher(); + + std::promise workerStarted; + std::promise releaseWorker; + std::promise workerFinished; + auto startedFuture = workerStarted.get_future(); + auto finishedFuture = workerFinished.get_future(); + std::atomic shouldInitialize { false }; + std::shared_ptr replacement; + ReinitializePalTask task( + pal, configuration, releaseWorker.get_future().share(), shouldInitialize, + workerStarted, workerFinished, replacement); + PAL::dispatchTask(dispatcher.get(), &task, &ReinitializePalTask::Run); + if (startedFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + releaseWorker.set_value(); + dispatcher.reset(); + pal.shutdown(); + FAIL() << "The worker did not start"; + } + dispatcher.reset(); + + std::thread shutdown([&] { pal.shutdown(); }); + std::promise dispatcherRetired; + auto retiredFuture = dispatcherRetired.get_future(); + std::thread observer([&] { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (PAL::PALTest::HasDispatcher(pal) && std::chrono::steady_clock::now() < deadline) + { + std::this_thread::yield(); + } + dispatcherRetired.set_value(!PAL::PALTest::HasDispatcher(pal)); + }); + const bool retired = + retiredFuture.wait_for(std::chrono::seconds(5)) == std::future_status::ready && retiredFuture.get(); + shouldInitialize.store(retired); + releaseWorker.set_value(); + observer.join(); + const auto finished = finishedFuture.wait_for(std::chrono::seconds(5)); + shutdown.join(); + + EXPECT_TRUE(retired); + EXPECT_EQ(finished, std::future_status::ready); + EXPECT_THAT(replacement, NotNull()); +} TEST_F(PalTests, UuidGeneration) { @@ -189,24 +598,50 @@ TEST_F(PalTests, MonotonicTime) TEST_F(PalTests, SemanticContextPopulation) { - /* MockISemanticContext context; - - - EXPECT_CALL(context, SetAppId(Not(IsEmpty()))).WillOnce(DoDefault()); - EXPECT_CALL(context, SetAppVersion(_)).WillOnce(DoDefault()); - EXPECT_CALL(context, SetAppLanguage(_)).WillOnce(DoDefault()); - - EXPECT_CALL(context, SetUserLanguage(_)).WillOnce(DoDefault()); - EXPECT_CALL(context, SetUserTimeZone(Not(IsEmpty()))).WillOnce(DoDefault()); - //EXPECT_CALL(context, SetUserAdvertisingId(_)).WillOnce(DoDefault()); - - - PAL::registerSemanticContext(&context); + MAT::ILogConfiguration logConfiguration; + logConfiguration[CFG_BOOL_ENABLE_TRACE] = false; + MAT::RuntimeConfig_Default configuration(logConfiguration); + PAL::PlatformAbstractionLayer pal; + pal.initialize(configuration); + + ASSERT_TRUE(pal.GetDeviceInformation()); + ASSERT_TRUE(pal.GetSystemInformation()); + ASSERT_TRUE(pal.GetNetworkInformation()); + const auto expectedDeviceId = pal.GetDeviceInformation()->GetDeviceId(); + const auto expectedDeviceModel = pal.GetDeviceInformation()->GetModel(); + const auto expectedOsName = pal.GetSystemInformation()->GetOsName(); + + std::promise entered; + std::promise release; + auto enteredFuture = entered.get_future(); + BlockingSemanticContext context(entered, release.get_future().share()); + std::thread populate([&] { pal.registerSemanticContext(&context); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + populate.join(); + pal.shutdown(); + FAIL() << "Semantic-context population did not reach the device callback"; + } - PAL::sleep(500); + auto shutdown = std::async(std::launch::async, [&] { pal.shutdown(); }); + const auto shutdownStatus = shutdown.wait_for(std::chrono::seconds(2)); + release.set_value(); + populate.join(); + shutdown.get(); - PAL::unregisterSemanticContext(&context); - */ + EXPECT_EQ(shutdownStatus, std::future_status::ready); +#ifdef MATSDK_DISABLE_DEVICE_ID + EXPECT_EQ(context.sawDeviceId, !expectedDeviceId.empty()); +#else + EXPECT_TRUE(context.sawDeviceId); +#endif + EXPECT_EQ(context.deviceId, expectedDeviceId); + EXPECT_TRUE(context.sawDeviceModel); + EXPECT_EQ(context.deviceModel, expectedDeviceModel); + EXPECT_TRUE(context.sawOsName); + EXPECT_EQ(context.osName, expectedOsName); + EXPECT_TRUE(context.sawNetworkProvider); } TEST_F(PalTests, SdkVersion) @@ -840,6 +1275,7 @@ TEST_F(PalTests, WorkerThreadSelfJoinSurvivesConcurrentFinalRelease) class LogInitTest : public Test { protected: + ScopedLogState m_logState; std::string validPath = "valid/path/"; void SetUp() override @@ -937,4 +1373,125 @@ TEST_F(LogInitTest, LogInitPathWithoutTrailingBackslash) EXPECT_TRUE(PAL::detail::getDebugLogStream()->is_open()); } +TEST_F(LogInitTest, OlderEpochCannotCloseCurrentLog) +{ + uint64_t oldEpoch = 0; + uint64_t currentEpoch = 0; + ASSERT_TRUE(log_init(true, validPath, oldEpoch)); + ASSERT_TRUE(log_init(true, validPath, currentEpoch)); + EXPECT_NE(oldEpoch, currentEpoch); + + log_done(oldEpoch); + ASSERT_TRUE(getDebugLogStream()); + EXPECT_TRUE(getDebugLogStream()->is_open()); + log_done(currentEpoch); + EXPECT_FALSE(getDebugLogStream()); +} + +TEST_F(LogInitTest, PalGenerationSurvivesOlderShutdown) +{ + MAT::ILogConfiguration firstLogConfiguration; + firstLogConfiguration[CFG_BOOL_ENABLE_TRACE] = true; + firstLogConfiguration[CFG_STR_TRACE_FOLDER_PATH] = validPath; + MAT::RuntimeConfig_Default firstConfiguration(firstLogConfiguration); + PAL::PlatformAbstractionLayer pal; + pal.initialize(firstConfiguration); + ASSERT_TRUE(getDebugLogStream()); + const std::string oldPath = getDebugLogPath(); + + auto dispatcher = pal.getDefaultTaskDispatcher(); + std::promise started; + std::promise release; + auto startedFuture = started.get_future(); + BlockingTask task(started, release.get_future().share()); + PAL::dispatchTask(dispatcher.get(), &task, &BlockingTask::Run); + if (startedFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + dispatcher.reset(); + pal.shutdown(); + FAIL() << "The worker did not start"; + } + dispatcher.reset(); + + std::thread shutdown([&] { pal.shutdown(); }); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (PAL::PALTest::HasDispatcher(pal) && std::chrono::steady_clock::now() < deadline) + { + std::this_thread::yield(); + } + if (PAL::PALTest::HasDispatcher(pal)) + { + release.set_value(); + shutdown.join(); + FAIL() << "The old dispatcher was not retired"; + } + + const auto separator = validPath.find_last_of("/\\", validPath.size() - 2); + const std::string otherDirectory = validPath.substr(0, separator + 1); + MAT::ILogConfiguration secondLogConfiguration; + secondLogConfiguration[CFG_BOOL_ENABLE_TRACE] = true; + secondLogConfiguration[CFG_STR_TRACE_FOLDER_PATH] = otherDirectory; + MAT::RuntimeConfig_Default secondConfiguration(secondLogConfiguration); + pal.initialize(secondConfiguration); + const std::string newPath = getDebugLogPath(); + release.set_value(); + shutdown.join(); + + EXPECT_NE(newPath, oldPath); + ASSERT_TRUE(getDebugLogStream()); + EXPECT_TRUE(getDebugLogStream()->is_open()); + EXPECT_EQ(getDebugLogPath(), newPath); + pal.shutdown(); + std::remove(oldPath.c_str()); +} + +TEST_F(LogInitTest, NewEpochUsesItsConfiguredPath) +{ + uint64_t oldEpoch = 0; + uint64_t currentEpoch = 0; + ASSERT_TRUE(log_init(true, validPath, oldEpoch)); + const std::string oldPath = getDebugLogPath(); + const auto separator = validPath.find_last_of("/\\", validPath.size() - 2); + ASSERT_NE(separator, std::string::npos); + const std::string otherDirectory = validPath.substr(0, separator + 1); + + const bool opened = log_init(true, otherDirectory, currentEpoch); + EXPECT_TRUE(opened); + if (opened) + { + EXPECT_NE(getDebugLogPath(), oldPath); + log_done(oldEpoch); + EXPECT_TRUE(getDebugLogStream()); + } + std::remove(oldPath.c_str()); +} + +TEST_F(LogInitTest, FailedOpenIsNotReusedAsSuccessfulLogging) +{ + uint64_t epoch = 0; + ASSERT_TRUE(log_init(true, validPath, epoch)); + const std::string blockedPath = getDebugLogPath(); + log_done(epoch); + ASSERT_EQ(std::remove(blockedPath.c_str()), 0); +#if defined(_WIN32) || defined(_WIN64) + ASSERT_TRUE(CreateDirectoryA(blockedPath.c_str(), nullptr)); +#else + ASSERT_EQ(mkdir(blockedPath.c_str(), 0777), 0); +#endif + + uint64_t firstEpoch = 0; + uint64_t secondEpoch = 0; + EXPECT_FALSE(log_init(true, validPath, firstEpoch)); + EXPECT_FALSE(log_init(true, validPath, secondEpoch)); + EXPECT_EQ(firstEpoch, 0u); + EXPECT_EQ(secondEpoch, 0u); + log_done(); +#if defined(_WIN32) || defined(_WIN64) + EXPECT_TRUE(RemoveDirectoryA(blockedPath.c_str())); +#else + EXPECT_EQ(rmdir(blockedPath.c_str()), 0); +#endif +} + #endif From a9c133f0cf6823557f2760a9ed9de8ec8e994e1f Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Thu, 19 Nov 2026 13:18:05 -0600 Subject: [PATCH 02/19] Prevent undersized bundled zlib allocations Reject allocation-size overflow and preserve full-width multiplication so the bundled allocator cannot silently allocate less than requested. Exercise the boundary in native CTest and 32-bit Windows CI. Files: zlib/zutil.c, tests/zlib-allocation-test.c, tests/unittests/CMakeLists.txt, .github/workflows/test-win-latest.yml Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e5009227-6b49-4803-8153-63d8d94037e3 --- .github/workflows/test-win-latest.yml | 14 +++++ tests/unittests/CMakeLists.txt | 5 ++ tests/zlib-allocation-test.c | 84 +++++++++++++++++++++++++++ zlib/zutil.c | 15 ++++- 4 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 tests/zlib-allocation-test.c diff --git a/.github/workflows/test-win-latest.yml b/.github/workflows/test-win-latest.yml index c6f19f8aa..298bb4672 100644 --- a/.github/workflows/test-win-latest.yml +++ b/.github/workflows/test-win-latest.yml @@ -56,6 +56,20 @@ jobs: with: vs-version: '[17,)' + - name: Test bundled zlib allocation bounds (Win32) + if: matrix.arch == 'Win32' && matrix.build == 'Release' && matrix.transport == 'WinHTTP' + shell: cmd + run: | + set "VSPATH=" + for /f "usebackq tokens=*" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "VSPATH=%%i" + if not defined VSPATH exit /b 1 + set "PATH=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer;%PATH%" + call "%VSPATH%\VC\Auxiliary\Build\vcvars32.bat" >nul + if errorlevel 1 exit /b 1 + cl /nologo /W4 /WX /TC /DZLIB_TEST_REQUIRE_32_BIT tests\zlib-allocation-test.c /Fo"%RUNNER_TEMP%\zlib-allocation-test.obj" /Fe"%RUNNER_TEMP%\zlib-allocation-test.exe" + if errorlevel 1 exit /b 1 + "%RUNNER_TEMP%\zlib-allocation-test.exe" + - name: Test ${{ matrix.transport }} ${{ matrix.arch }} ${{ matrix.build }} shell: cmd run: build-tests.cmd ${{ matrix.arch }} ${{ matrix.build }} "" ${{ matrix.transport }} diff --git a/tests/unittests/CMakeLists.txt b/tests/unittests/CMakeLists.txt index ff682427b..7b81dde24 100644 --- a/tests/unittests/CMakeLists.txt +++ b/tests/unittests/CMakeLists.txt @@ -159,3 +159,8 @@ endif() add_test(NAME UnitTests COMMAND UnitTests "--gtest_output=xml:${PROJECT_BINARY_DIR}/test-reports/UnitTests.xml") set_tests_properties(UnitTests PROPERTIES WORKING_DIRECTORY "${PROJECT_BINARY_DIR}") + +if(NOT MATSDK_PLATFORM_IOS) + add_executable(zlib-allocation-test ../zlib-allocation-test.c) + add_test(NAME zlib-allocation-test COMMAND zlib-allocation-test) +endif() diff --git a/tests/zlib-allocation-test.c b/tests/zlib-allocation-test.c new file mode 100644 index 000000000..f6772427a --- /dev/null +++ b/tests/zlib-allocation-test.c @@ -0,0 +1,84 @@ +#include +#include +#include +#include + +static size_t allocated_size; +static unsigned allocation_calls; +static int allocation_succeeds = 1; +static char allocation; + +static void *test_malloc(size_t size) { + allocated_size = size; + allocation_calls++; + return allocation_succeeds ? &allocation : NULL; +} + +static void *test_calloc(size_t items, size_t size) { + allocation_calls++; + if (size != 0 && items > (size_t)-1 / size) + return NULL; + allocated_size = items * size; + return allocation_succeeds ? &allocation : NULL; +} + +static void test_free(void *ptr) { + (void)ptr; +} + +#define malloc test_malloc +#define calloc test_calloc +#define free test_free +#include "../zlib/zutil.c" +#undef malloc +#undef calloc +#undef free + +#define CHECK(condition) do { \ + if (!(condition)) { \ + fprintf(stderr, "Allocation check failed at line %d\n", __LINE__); \ + return 1; \ + } \ +} while (0) + +int main(void) { + voidpf result; + +#ifdef ZLIB_TEST_REQUIRE_32_BIT + CHECK(sizeof(size_t) == 4 && sizeof(uInt) == 4); +#endif + + allocation_calls = 0; + result = zcalloc(NULL, 3, 7); + CHECK(result == &allocation && allocation_calls == 1 && allocated_size == 21); + + result = zcalloc(NULL, 0, 7); + CHECK(result == &allocation && allocated_size == 0); + result = zcalloc(NULL, 7, 0); + CHECK(result == &allocation && allocated_size == 0); + + allocation_succeeds = 0; + result = zcalloc(NULL, 3, 7); + CHECK(result == NULL); + allocation_succeeds = 1; + + if (sizeof(size_t) > sizeof(unsigned)) { + result = zcalloc(NULL, UINT_MAX, 2); + CHECK(result == &allocation && allocated_size == (size_t)UINT_MAX * 2); + if (UINT_MAX <= (size_t)-1 / UINT_MAX) { + result = zcalloc(NULL, UINT_MAX, UINT_MAX); + CHECK(result == &allocation && + allocated_size == (size_t)UINT_MAX * UINT_MAX); + } + } else { + result = zcalloc(NULL, UINT_MAX, 1); + CHECK(result == &allocation && allocated_size == (size_t)UINT_MAX); + allocation_calls = 0; + result = zcalloc(NULL, UINT_MAX, 2); + CHECK(result == NULL); + if (sizeof(uInt) > 2) + CHECK(allocation_calls == 0); + } + + return 0; +} diff --git a/zlib/zutil.c b/zlib/zutil.c index 6c01021df..78513e27f 100644 --- a/zlib/zutil.c +++ b/zlib/zutil.c @@ -302,8 +302,19 @@ extern void free(voidpf ptr); voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { (void)opaque; - return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : - (voidpf)calloc(items, size); + if (sizeof(uInt) > 2) { + /* Modified for the SDK: reject sizes that malloc cannot represent. */ +#ifdef STDC + if (size != 0 && items > (size_t)-1 / size) + return Z_NULL; + return (voidpf)malloc((size_t)items * size); +#else + if (size != 0 && items > (uInt)-1 / size) + return Z_NULL; + return (voidpf)malloc(items * size); +#endif + } + return (voidpf)calloc(items, size); } void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { From 84141b42773199887cbc686961e456b227facee9 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Thu, 19 Nov 2026 13:51:08 -0600 Subject: [PATCH 03/19] Keep allocation regression warning-clean on older MSVC Express the same allocation checks without constant if conditions so the Windows 2022 compiler can enforce warnings as errors. Files: zlib/zutil.c, tests/zlib-allocation-test.c Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e5009227-6b49-4803-8153-63d8d94037e3 --- tests/zlib-allocation-test.c | 11 +++++++---- zlib/zutil.c | 19 ++++++++----------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/tests/zlib-allocation-test.c b/tests/zlib-allocation-test.c index f6772427a..88b6b520b 100644 --- a/tests/zlib-allocation-test.c +++ b/tests/zlib-allocation-test.c @@ -43,9 +43,12 @@ static void test_free(void *ptr) { int main(void) { voidpf result; + size_t size_t_width = sizeof(size_t); + size_t uint_width = sizeof(uInt); + size_t max_size = (size_t)-1; #ifdef ZLIB_TEST_REQUIRE_32_BIT - CHECK(sizeof(size_t) == 4 && sizeof(uInt) == 4); + CHECK(size_t_width == 4 && uint_width == 4); #endif allocation_calls = 0; @@ -62,10 +65,10 @@ int main(void) { CHECK(result == NULL); allocation_succeeds = 1; - if (sizeof(size_t) > sizeof(unsigned)) { + if (size_t_width > sizeof(unsigned)) { result = zcalloc(NULL, UINT_MAX, 2); CHECK(result == &allocation && allocated_size == (size_t)UINT_MAX * 2); - if (UINT_MAX <= (size_t)-1 / UINT_MAX) { + if (UINT_MAX <= max_size / UINT_MAX) { result = zcalloc(NULL, UINT_MAX, UINT_MAX); CHECK(result == &allocation && allocated_size == (size_t)UINT_MAX * UINT_MAX); @@ -76,7 +79,7 @@ int main(void) { allocation_calls = 0; result = zcalloc(NULL, UINT_MAX, 2); CHECK(result == NULL); - if (sizeof(uInt) > 2) + if (uint_width > 2) CHECK(allocation_calls == 0); } diff --git a/zlib/zutil.c b/zlib/zutil.c index 78513e27f..6a43b038b 100644 --- a/zlib/zutil.c +++ b/zlib/zutil.c @@ -301,20 +301,17 @@ extern void free(voidpf ptr); #endif voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { - (void)opaque; - if (sizeof(uInt) > 2) { - /* Modified for the SDK: reject sizes that malloc cannot represent. */ #ifdef STDC - if (size != 0 && items > (size_t)-1 / size) - return Z_NULL; - return (voidpf)malloc((size_t)items * size); + typedef size_t alloc_size_t; #else - if (size != 0 && items > (uInt)-1 / size) - return Z_NULL; - return (voidpf)malloc(items * size); + typedef uInt alloc_size_t; #endif - } - return (voidpf)calloc(items, size); + (void)opaque; + /* Modified for the SDK: reject sizes that malloc cannot represent. */ + if (size != 0 && sizeof(uInt) > 2 && items > (alloc_size_t)-1 / size) + return Z_NULL; + return sizeof(uInt) > 2 ? (voidpf)malloc((alloc_size_t)items * size) : + (voidpf)calloc(items, size); } void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) { From 6d46e26a8ca9d3780b93d9bb97317ce2ae3296d7 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Thu, 19 Nov 2026 14:05:09 -0600 Subject: [PATCH 04/19] Prevent offline flush from outliving storage Drain generation-scoped flushes before storage shutdown and retain batches when providers mutate their input, preventing stranded teardown and lost retries. Files: lib\offline\OfflineStorageHandler.cpp, lib\offline\OfflineStorageHandler.hpp, lib\pal\WorkerThread.cpp, tests\unittests\CMakeLists.txt, tests\unittests\OfflineStorageTests.cpp, tests\unittests\PalTests.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f7e2f450-c2c4-43c5-9fb1-05fa4f7d8e9e --- lib/offline/OfflineStorageHandler.cpp | 372 +++++++++-- lib/offline/OfflineStorageHandler.hpp | 17 +- lib/pal/WorkerThread.cpp | 18 +- tests/unittests/CMakeLists.txt | 3 + tests/unittests/OfflineStorageTests.cpp | 780 +++++++++++++++++++++++- tests/unittests/PalTests.cpp | 46 ++ 6 files changed, 1151 insertions(+), 85 deletions(-) diff --git a/lib/offline/OfflineStorageHandler.cpp b/lib/offline/OfflineStorageHandler.cpp index 60f67fb64..ec6f5de84 100644 --- a/lib/offline/OfflineStorageHandler.cpp +++ b/lib/offline/OfflineStorageHandler.cpp @@ -12,6 +12,7 @@ #include "ILogManager.hpp" #include "utils/Utils.hpp" #include +#include #include #include #include @@ -32,6 +33,152 @@ namespace MAT_NS_BEGIN { MATSDK_LOG_INST_COMPONENT_CLASS(OfflineStorageHandler, "EventsSDK.StorageHandler", "Events telemetry client - OfflineStorageHandler class") + // Queued tasks retain this state even after the handler has stopped. + class OfflineStorageHandler::FlushState + { + public: + enum class Phase { Accepting, Draining, Closing, Retryable, Stopped }; + enum class ShutdownStage { Flush, MemoryShutdown, DiskShutdown, Complete }; + + struct PendingTask + { + // Keep the task alive while cancellation looks up its identity. + std::recursive_mutex mutex; + Task* task = nullptr; + }; + + explicit FlushState(OfflineStorageHandler* handler) : owner(handler) {} + + std::mutex mutex; + std::condition_variable cv; + Phase phase = Phase::Accepting; + ShutdownStage shutdownStage = ShutdownStage::Flush; + OfflineStorageHandler* owner; + size_t active = 0; + std::shared_ptr pending; + }; + + class OfflineStorageHandler::OperationGuard + { + public: + explicit OperationGuard(std::shared_ptr state, bool allowDraining = false) : + m_state(std::move(state)) + { + std::lock_guard lock(m_state->mutex); + if (m_state->phase == FlushState::Phase::Accepting || + (allowDraining && m_state->phase == FlushState::Phase::Draining)) + { + m_owner = m_state->owner; + ++m_state->active; + } + } + + OperationGuard(std::shared_ptr state, + std::shared_ptr const& pending) : + m_state(std::move(state)) + { + std::lock_guard lock(m_state->mutex); + if (m_state->pending != pending) + { + return; + } + m_state->pending.reset(); + if (m_state->phase == FlushState::Phase::Accepting) + { + m_owner = m_state->owner; + ++m_state->active; + } + } + + ~OperationGuard() noexcept + { + if (m_owner) + { + { + std::lock_guard lock(m_state->mutex); + --m_state->active; + } + m_state->cv.notify_all(); + } + } + + explicit operator bool() const noexcept { return m_owner != nullptr; } + OfflineStorageHandler* Owner() const noexcept { return m_owner; } + + OperationGuard(OperationGuard const&) = delete; + OperationGuard& operator=(OperationGuard const&) = delete; + + private: + std::shared_ptr m_state; + OfflineStorageHandler* m_owner = nullptr; + }; + + class OfflineStorageHandler::ScheduledFlushTask final : public Task + { + public: + ScheduledFlushTask(std::shared_ptr state, + std::shared_ptr pending) : + m_state(std::move(state)), + m_pending(std::move(pending)) + { + Type = Task::Call; + TargetTime = 0; + TypeName = "OfflineStorageFlushTask"; + std::lock_guard lock(m_pending->mutex); + m_pending->task = this; + } + + ~ScheduledFlushTask() noexcept override + { + { + std::lock_guard lock(m_pending->mutex); + m_pending->task = nullptr; + } + std::lock_guard lock(m_state->mutex); + if (m_state->pending == m_pending) + { + m_state->pending.reset(); + } + } + + void operator()() override + { + OperationGuard operation(m_state, m_pending); + if (operation) + { + operation.Owner()->Flush(); + } + } + + private: + std::shared_ptr m_state; + std::shared_ptr m_pending; + }; + + class OfflineStorageHandler::TeardownGuard + { + public: + explicit TeardownGuard(std::shared_ptr state) : m_state(std::move(state)) {} + + ~TeardownGuard() noexcept + { + { + std::lock_guard lock(m_state->mutex); + m_state->phase = m_completed ? FlushState::Phase::Stopped : FlushState::Phase::Retryable; + } + m_state->cv.notify_all(); + } + + void Complete() noexcept { m_completed = true; } + + TeardownGuard(TeardownGuard const&) = delete; + TeardownGuard& operator=(TeardownGuard const&) = delete; + + private: + std::shared_ptr m_state; + bool m_completed = false; + }; + OfflineStorageHandler::OfflineStorageHandler(ILogManager& logManager, IRuntimeConfig& runtimeConfig, ITaskDispatcher& taskDispatcher) : OfflineStorageHandler(logManager, runtimeConfig, taskDispatcher, OfflineStorageFactory::GetDefaultProvider()) { @@ -45,7 +192,7 @@ namespace MAT_NS_BEGIN { m_storageProvider(std::move(storageProvider)), m_killSwitchManager(), m_clockSkewManager(), - m_flushPending(false), + m_flushState(std::make_shared(this)), m_offlineStorageMemory(nullptr), m_offlineStorageDisk(nullptr), m_readFromMemory(false), @@ -136,33 +283,70 @@ namespace MAT_NS_BEGIN { /* slower */ m_killSwitchManager.isTokenBlocked(record.tenantToken)); } - void OfflineStorageHandler::WaitForFlush() + bool OfflineStorageHandler::BeginTeardown() { + auto state = m_flushState; + std::shared_ptr pending; { - LOCKGUARD(m_flushLock); - if (!m_flushPending) - return; + std::unique_lock lock(state->mutex); + state->cv.wait(lock, [&state] { + return state->phase != FlushState::Phase::Draining && + state->phase != FlushState::Phase::Closing; + }); + if (state->phase == FlushState::Phase::Stopped) + { + return false; + } + if (state->phase == FlushState::Phase::Retryable) + { + state->phase = FlushState::Phase::Closing; + return true; + } + // Drain admitted operations before closing storage or invalidating queued work. + m_shutdownStarted = true; + state->phase = FlushState::Phase::Draining; + state->cv.wait(lock, [&state] { return state->active == 0; }); + state->phase = FlushState::Phase::Closing; + state->owner = nullptr; + pending = std::move(state->pending); + } + + if (pending) + { + MATSDK_TRY + { + std::lock_guard lock(pending->mutex); + if (pending->task) + { + m_taskDispatcher.Cancel(pending->task); + } + } + MATSDK_CATCH(...) + { + std::fputs("Failed to cancel pending offline flush\n", stderr); + } } - LOG_INFO("Waiting for pending Flush (%p) to complete...", - static_cast(m_flushHandle.GetTask())); - m_flushComplete.wait(); + return true; } OfflineStorageHandler::~OfflineStorageHandler() { - WaitForFlush(); - if (nullptr != m_offlineStorageMemory) + if (BeginTeardown()) { + TeardownGuard teardown(m_flushState); m_offlineStorageMemory.reset(); - } - if (nullptr != m_offlineStorageDisk) - { m_offlineStorageDisk.reset(); + teardown.Complete(); } } void OfflineStorageHandler::Initialize(IOfflineStorageObserver& observer) { + Shutdown(); + m_offlineStorageMemory.reset(); + m_offlineStorageDisk.reset(); + m_flushState = std::make_shared(this); + m_shutdownStarted = false; m_observer = &observer; m_cacheMemorySizeLimitInBytes = m_config[CFG_INT_RAM_QUEUE_SIZE]; @@ -181,25 +365,48 @@ namespace MAT_NS_BEGIN { m_offlineStorageMemory->Initialize(*this); } - m_shutdownStarted = false; LOG_TRACE("Initializing offline storage handler"); } void OfflineStorageHandler::Shutdown() { LOG_TRACE("Shutting down offline storage handler"); - m_shutdownStarted = true; - WaitForFlush(); - if (nullptr != m_offlineStorageMemory) + if (!BeginTeardown()) { - m_offlineStorageMemory->ReleaseAllRecords(); - Flush(); - m_offlineStorageMemory->Shutdown(); + return; } - if (nullptr != m_offlineStorageDisk) + auto state = m_flushState; + TeardownGuard teardown(state); + // A failed teardown retries only the stage that did not complete. + if (state->shutdownStage == FlushState::ShutdownStage::Flush) { - m_offlineStorageDisk->Shutdown(); + if (nullptr != m_offlineStorageMemory) + { + m_offlineStorageMemory->ReleaseAllRecords(); + { + ActivityGuard activity(m_logManager, true); + FlushImpl(); + } + } + state->shutdownStage = FlushState::ShutdownStage::MemoryShutdown; } + if (state->shutdownStage == FlushState::ShutdownStage::MemoryShutdown) + { + if (nullptr != m_offlineStorageMemory) + { + m_offlineStorageMemory->Shutdown(); + } + state->shutdownStage = FlushState::ShutdownStage::DiskShutdown; + } + if (state->shutdownStage == FlushState::ShutdownStage::DiskShutdown) + { + if (nullptr != m_offlineStorageDisk) + { + m_offlineStorageDisk->Shutdown(); + } + state->shutdownStage = FlushState::ShutdownStage::Complete; + } + teardown.Complete(); } /// @@ -243,33 +450,30 @@ namespace MAT_NS_BEGIN { void OfflineStorageHandler::Flush() { - // Shutdown has already paused normal logging, but its synchronous final - // flush must still persist the in-memory records before storage closes. - ActivityGuard activityGuard(m_logManager, m_shutdownStarted); + OperationGuard operation(m_flushState); + if (!operation) + { + return; + } + ActivityGuard activityGuard(m_logManager); if (!activityGuard.IsActive()) { - // The LogManager is shutting down, so the flush cannot run. Still - // signal completion and clear the pending flag so a concurrent - // WaitForFlush() (e.g. during teardown) does not block forever - // waiting for m_flushComplete. - LOCKGUARD(m_flushLock); - m_flushHandle.Cancel(); - m_flushComplete.post(); - m_flushPending = false; return; } + FlushImpl(); + } + + void OfflineStorageHandler::FlushImpl() + { std::vector recordsToRecover; std::vector memoryOnlyRecords; + size_t savedRecords = 0; + bool notifySaved = false; MATSDK_TRY { // Flush could be executed from context of worker thread, as well as from TPM and // after HTTP callback. Make sure it is atomic / thread-safe. LOCKGUARD(m_flushLock); - // If item isn't scheduled yet, it gets canceled, so that we don't do two flushes. - // If we are running that item right now (our thread), then nothing happens other - // than the handle reporting nullptr once that task finishes. - m_flushHandle.Cancel(); - size_t dbSizeBeforeFlush = (m_offlineStorageMemory != nullptr) ? m_offlineStorageMemory->GetSize() : 0; if ((m_offlineStorageMemory) && (dbSizeBeforeFlush > 0) && (m_offlineStorageDisk)) { @@ -316,9 +520,14 @@ namespace MAT_NS_BEGIN { }), recordsToRecover.end()); - const size_t batchSaved = recordsToRecover.empty() - ? 0 - : m_offlineStorageDisk->StoreRecords(recordsToRecover); + size_t batchSaved = 0; + if (!recordsToRecover.empty()) + { + // Storage can consume its input, so retain the original batch for retry. + auto recordsForStorage = recordsToRecover; + batchSaved = m_offlineStorageDisk->StoreRecords(recordsForStorage); + } + totalSaved += std::min(batchSaved, recordsToRecover.size()); if (batchSaved != recordsToRecover.size()) { LOG_WARN("Flush: disk store failed for the batch of %zu records; returning it to the queue for retry", @@ -328,7 +537,6 @@ namespace MAT_NS_BEGIN { break; } - totalSaved += batchSaved; recordsToRecover.clear(); } ReturnRecordsToMemory(memoryOnlyRecords); @@ -353,7 +561,8 @@ namespace MAT_NS_BEGIN { // obviously because the disk is slower than ram. LOG_WARN("Data is arriving too fast!"); } - OnStorageRecordsSaved(totalSaved); + savedRecords = totalSaved; + notifySaved = true; } // Checkpoint DB @@ -363,8 +572,6 @@ namespace MAT_NS_BEGIN { } m_isStorageFullNotificationSend = false; - m_flushComplete.post(); - m_flushPending = false; } MATSDK_CATCH(...) { @@ -385,16 +592,65 @@ namespace MAT_NS_BEGIN { { std::fputs("Failed to recover records after flush failure\n", stderr); } - LOCKGUARD(m_flushLock); - m_flushComplete.post(); - m_flushPending = false; + if (notifySaved) + { + MATSDK_TRY + { + OnStorageRecordsSaved(savedRecords); + } + MATSDK_CATCH(...) + { + std::fputs("Failed to report saved records after flush failure\n", stderr); + } + } std::rethrow_exception(failure); +#endif + } + if (notifySaved) + { + OnStorageRecordsSaved(savedRecords); + } + } + + void OfflineStorageHandler::QueueScheduledFlush() + { + auto state = m_flushState; + std::shared_ptr pending; + { + std::lock_guard lock(state->mutex); + if (state->phase != FlushState::Phase::Accepting || state->pending) + { + return; + } + pending = std::make_shared(); + state->pending = pending; + } + + MATSDK_TRY + { + std::unique_ptr task(new ScheduledFlushTask(state, pending)); + m_taskDispatcher.Queue(task.release()); + } + MATSDK_CATCH(...) + { +#if HAVE_EXCEPTIONS + std::lock_guard lock(state->mutex); + if (state->pending == pending) + { + state->pending.reset(); + } + throw; #endif } } bool OfflineStorageHandler::StoreRecord(StorageRecord const& record) { + OperationGuard operation(m_flushState, true); + if (!operation) + { + return false; + } // Don't discard on shutdown because the kill-switch may be temporary. // Attempt to upload after restart. if ((!m_shutdownStarted) && isKilled(record)) @@ -436,25 +692,7 @@ namespace MAT_NS_BEGIN { // Perform periodic flush to disk if (memDbSize > cacheMemorySizeLimitInBytes) { - if (m_flushLock.try_lock()) - { - if (!m_flushPending) - { - m_flushPending = true; - m_flushComplete.Reset(); - m_flushHandle = PAL::scheduleTask(&m_taskDispatcher, 0, this, &OfflineStorageHandler::Flush); - if (m_flushHandle.GetTask() == nullptr) - { - // The dispatcher may drop a task synchronously during - // shutdown. Do not leave WaitForFlush blocked forever. - m_flushPending = false; - m_flushComplete.post(); - } - LOG_INFO("Requested Flush (%p)", - static_cast(m_flushHandle.GetTask())); - } - m_flushLock.unlock(); - } + QueueScheduledFlush(); } } else diff --git a/lib/offline/OfflineStorageHandler.hpp b/lib/offline/OfflineStorageHandler.hpp index 0eae7510b..3c69640be 100644 --- a/lib/offline/OfflineStorageHandler.hpp +++ b/lib/offline/OfflineStorageHandler.hpp @@ -14,9 +14,10 @@ #include "ILogManager.hpp" #include "pal/TaskDispatcher.hpp" -#include #include #include +#include +#include #include #include "KillSwitchManager.hpp" @@ -82,9 +83,11 @@ namespace MAT_NS_BEGIN { bool isKilled(StorageRecord const& record); std::mutex m_flushLock; - bool m_flushPending; - PAL::DeferredCallbackHandle m_flushHandle; - PAL::Event m_flushComplete; + class FlushState; + class OperationGuard; + class ScheduledFlushTask; + class TeardownGuard; + std::shared_ptr m_flushState; std::shared_ptr m_offlineStorageMemory; std::shared_ptr m_offlineStorageDisk; @@ -92,7 +95,7 @@ namespace MAT_NS_BEGIN { std::atomic m_readFromMemory; std::atomic m_lastReadCount; - bool m_shutdownStarted; + std::atomic m_shutdownStarted; unsigned m_memoryDbSize; unsigned m_memoryDbSizeNotificationLimit; unsigned m_queryDbSize; @@ -103,7 +106,9 @@ namespace MAT_NS_BEGIN { MATSDK_LOG_DECL_COMPONENT_CLASS(); private: - void WaitForFlush(); + bool BeginTeardown(); + void QueueScheduledFlush(); + void FlushImpl(); bool IsBatchedStorageFlushEnabled(); void ReportInvalidDiskRecord(StorageRecord const& record); size_t StoreRecordsIndividually(std::vector& records); diff --git a/lib/pal/WorkerThread.cpp b/lib/pal/WorkerThread.cpp index 03878f298..46da4f62f 100644 --- a/lib/pal/WorkerThread.cpp +++ b/lib/pal/WorkerThread.cpp @@ -295,19 +295,15 @@ namespace PAL_NS_BEGIN { queuedItem = *it; m_timerQueue.erase(it); } - lock.unlock(); - delete queuedItem; -#if 0 - for (;;) { - { - LOCKGUARD(m_lock); - if (item->Type == MAT::Task::Done) { - return; - } + else { + auto immediate = std::find(m_queue.begin(), m_queue.end(), item); + if (immediate != m_queue.end()) { + queuedItem = *immediate; + m_queue.erase(immediate); } - Sleep(10); } -#endif + lock.unlock(); + delete queuedItem; return true; } diff --git a/tests/unittests/CMakeLists.txt b/tests/unittests/CMakeLists.txt index ff682427b..e2204546c 100644 --- a/tests/unittests/CMakeLists.txt +++ b/tests/unittests/CMakeLists.txt @@ -68,6 +68,9 @@ set(MATSDK_UNIT_TEST_DEFINITIONS) if(NOT MSVC) set_source_files_properties(${SRCS} PROPERTIES COMPILE_FLAGS -Wno-deprecated-declarations) +else() + # The storage regression tests exceed the default COFF section limit. + set_source_files_properties(OfflineStorageTests.cpp PROPERTIES COMPILE_OPTIONS /bigobj) endif() # Enable Azure Monitor unit tests when the module is present. diff --git a/tests/unittests/OfflineStorageTests.cpp b/tests/unittests/OfflineStorageTests.cpp index 9f3f5fc35..50012ee50 100644 --- a/tests/unittests/OfflineStorageTests.cpp +++ b/tests/unittests/OfflineStorageTests.cpp @@ -8,13 +8,20 @@ #include "offline/IOfflineStorageProvider.hpp" #include "offline/StorageObserver.hpp" #include "offline/MemoryStorage.hpp" +#include "pal/TaskDispatcher_CAPI.hpp" #include "NullObjects.hpp" #include +#include +#include #include +#include +#include #include +#include #include #include +#include #include #include @@ -186,6 +193,28 @@ namespace ILogConfiguration& GetLogConfiguration() override { return config; } }; + class CountingLogManager : public ConfigurableLogManager + { + public: + bool StartActivity() override + { + ++activityCount; + ++activeActivities; + return true; + } + + void EndActivity() override { --activeActivities; } + + std::atomic activityCount{0}; + std::atomic activeActivities{0}; + }; + + class PausedLogManager : public ConfigurableLogManager + { + public: + bool StartActivity() override { return false; } + }; + // Remove a SQLite db file along with its WAL-mode companion files // (-wal/-shm/-journal), which would otherwise accumulate in the temp dir. void RemoveDbFiles(const std::string& path) @@ -226,6 +255,89 @@ namespace } std::vector m_tasks; }; + + class ManualTaskDispatcher : public ITaskDispatcher + { + public: + enum class Behavior { Hold, Inline, Drop, ThrowOnce }; + + void Join() override + { + Take(); + } + + void Queue(Task* task) override + { + std::unique_ptr owned(task); + EXPECT_EQ(static_cast(task->Type), static_cast(Task::Call)); + const unsigned call = ++queueCalls; + if (beforeQueue) + { + beforeQueue(); + } + if (behavior == Behavior::Inline) + { + (*owned)(); + return; + } + if (behavior == Behavior::Drop) + { + return; + } +#if HAVE_EXCEPTIONS + if (behavior == Behavior::ThrowOnce && call == 1) + { + throw std::runtime_error("queue failed"); + } +#else + UNREFERENCED_PARAMETER(call); +#endif + std::lock_guard lock(m_mutex); + EXPECT_EQ(m_task, nullptr); + m_task = std::move(owned); + } + + bool Cancel(Task* task, uint64_t = 0) override + { + std::unique_ptr cancelled; + { + std::lock_guard lock(m_mutex); + if (m_task.get() != task) + { + return false; + } + cancelled = std::move(m_task); + } + return true; + } + + std::unique_ptr Take() + { + std::lock_guard lock(m_mutex); + return std::move(m_task); + } + + Behavior behavior = Behavior::Hold; + std::atomic queueCalls{0}; + std::function beforeQueue; + + private: + std::mutex m_mutex; + std::unique_ptr m_task; + }; + + void EVTSDK_LIBABI_CDECL QueueInlineCapiTask(evt_task_t* task, task_callback_fn_t callback) + { + EXPECT_EQ(task->delayMs, 0u); + callback(task->id); + } + + bool EVTSDK_LIBABI_CDECL CancelCapiTask(const char*) + { + return true; + } + + void EVTSDK_LIBABI_CDECL JoinCapiTasks() {} } namespace MAT_NS_BEGIN { @@ -391,6 +503,667 @@ TEST_P(OfflineStorageRetrievalExceptionTests, PartialRetrievalReleasesRecordsToT INSTANTIATE_TEST_SUITE_P(MemoryAndDisk, OfflineStorageRetrievalExceptionTests, Combine(Bool(), Bool())); #endif +class OfflineStorageLifecycleTests : public Test +{ +protected: + void SetUp() override + { + config[CFG_INT_RAM_QUEUE_SIZE] = 1; + config[CFG_BOOL_ENABLE_BATCHED_STORAGE_FLUSH] = true; + memory = std::make_shared(logManager, config); + disk = std::make_shared>(); + auto provider = std::make_shared(memory, disk); + handler.reset(new OfflineStorageHandler(logManager, config, dispatcher, provider)); + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + } + + StorageRecord Record(const char* id) + { + return StorageRecord(id, "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'x'}); + } + + bool StoreTwo() + { + return handler->StoreRecord(Record("first")) && handler->StoreRecord(Record("second")); + } + + void ExpectSaved(size_t count) + { + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([count](std::vector& records) + { + EXPECT_EQ(records.size(), count); + return records.size(); + })); + EXPECT_CALL(observer, OnStorageRecordsSaved(count)); + } + + CountingLogManager logManager; + NiceMock config; + ManualTaskDispatcher dispatcher; + StrictMock observer; + std::shared_ptr memory; + std::shared_ptr> disk; + std::unique_ptr handler; +}; + +TEST_F(OfflineStorageLifecycleTests, ShutdownCancelsQueuedFlushAndPersistsRecords) +{ + ASSERT_TRUE(StoreTwo()); + ExpectSaved(2); + EXPECT_CALL(*disk, Shutdown()); + + std::promise finished; + auto done = finished.get_future(); + std::thread shutdown([&] { + handler->Shutdown(); + finished.set_value(); + }); + const auto status = done.wait_for(std::chrono::seconds(5)); + if (status != std::future_status::ready) + { + auto task = dispatcher.Take(); + if (task) + { + (*task)(); + } + } + shutdown.join(); + EXPECT_EQ(status, std::future_status::ready); + EXPECT_EQ(dispatcher.Take(), nullptr); + EXPECT_FALSE(handler->StoreRecord(Record("after-shutdown"))); + const unsigned activitiesAfterShutdown = logManager.activityCount.load(); + handler->Flush(); + EXPECT_EQ(logManager.activityCount.load(), activitiesAfterShutdown); +} + +TEST_F(OfflineStorageLifecycleTests, ShutdownWaitsForDirectFlushObserver) +{ + ASSERT_TRUE(StoreTwo()); + auto task = dispatcher.Take(); + ASSERT_NE(task, nullptr); + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + std::atomic shutdownCalls{0}; + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)) + .WillOnce(Invoke([&](size_t) { + entered.set_value(); + releaseFuture.wait(); + })); + EXPECT_CALL(*disk, Shutdown()).WillOnce(Invoke([&] { ++shutdownCalls; })); + + std::thread flush([&] { handler->Flush(); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + flush.join(); + FAIL() << "Direct flush did not notify its observer"; + } + std::promise started; + auto startedFuture = started.get_future(); + std::promise finished; + auto done = finished.get_future(); + std::thread shutdown([&] { + started.set_value(); + handler->Shutdown(); + finished.set_value(); + }); + startedFuture.wait(); + EXPECT_EQ(done.wait_for(std::chrono::milliseconds(200)), std::future_status::timeout); + EXPECT_EQ(shutdownCalls.load(), 0u); + release.set_value(); + flush.join(); + shutdown.join(); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::ready); + const unsigned activitiesAfterShutdown = logManager.activityCount.load(); + (*task)(); + EXPECT_EQ(logManager.activityCount.load(), activitiesAfterShutdown); +} + +TEST_F(OfflineStorageLifecycleTests, ConcurrentShutdownRunsStorageShutdownOnce) +{ + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + EXPECT_CALL(*disk, Shutdown()).WillOnce(Invoke([&] { + entered.set_value(); + releaseFuture.wait(); + })); + + std::thread first([&] { handler->Shutdown(); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + first.join(); + FAIL() << "First shutdown did not reach storage"; + } + std::promise started; + auto startedFuture = started.get_future(); + std::promise finished; + auto done = finished.get_future(); + std::thread second([&] { + started.set_value(); + handler->Shutdown(); + finished.set_value(); + }); + startedFuture.wait(); + EXPECT_EQ(done.wait_for(std::chrono::milliseconds(200)), std::future_status::timeout); + release.set_value(); + first.join(); + second.join(); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::ready); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, ShutdownWaitsForRunningFlush) +{ + ASSERT_TRUE(StoreTwo()); + auto task = dispatcher.Take(); + ASSERT_NE(task, nullptr); + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + std::atomic batchCalls{0}; + std::atomic directlyStored{0}; + EXPECT_CALL(*disk, StoreRecords(_)) + .WillRepeatedly(Invoke([&](std::vector& records) { + if (++batchCalls == 1) + { + entered.set_value(); + releaseFuture.wait(); + } + return records.size(); + })); + EXPECT_CALL(*disk, StoreRecord(_)) + .WillRepeatedly(Invoke([&](StorageRecord const&) { + ++directlyStored; + return true; + })); + EXPECT_CALL(observer, OnStorageRecordsSaved(_)).Times(AtLeast(1)); + EXPECT_CALL(*disk, Shutdown()); + + std::thread worker([task = std::move(task)] { (*task)(); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + worker.join(); + FAIL() << "Scheduled flush did not enter storage"; + } + std::promise started; + auto startedFuture = started.get_future(); + std::promise finished; + auto done = finished.get_future(); + std::thread shutdown([&] { + started.set_value(); + handler->Shutdown(); + finished.set_value(); + }); + startedFuture.wait(); + for (unsigned i = 0; i < 500 && directlyStored.load() == 0; ++i) + { + auto id = "probe-" + std::to_string(i); + handler->StoreRecord(Record(id.c_str())); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + EXPECT_EQ(directlyStored.load(), 1u); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::timeout); + release.set_value(); + worker.join(); + shutdown.join(); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::ready); +} + +TEST_F(OfflineStorageLifecycleTests, StoresDuringDrainReachDiskBeforeShutdown) +{ + ASSERT_TRUE(handler->StoreRecord(Record("first"))); + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + dispatcher.beforeQueue = [&] { + entered.set_value(); + releaseFuture.wait(); + }; + std::atomic directlyStored{0}; + size_t batched = 0; + EXPECT_CALL(*disk, StoreRecord(_)) + .WillRepeatedly(Invoke([&](StorageRecord const&) { + ++directlyStored; + return true; + })); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([&](std::vector& records) { + batched = records.size(); + return records.size(); + })); + EXPECT_CALL(observer, OnStorageRecordsSaved(_)); + EXPECT_CALL(*disk, Shutdown()); + + std::thread producer([&] { EXPECT_TRUE(handler->StoreRecord(Record("second"))); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + producer.join(); + FAIL() << "Store did not reach task submission"; + } + std::promise started; + auto startedFuture = started.get_future(); + std::promise finished; + auto done = finished.get_future(); + std::thread shutdown([&] { + started.set_value(); + handler->Shutdown(); + finished.set_value(); + }); + startedFuture.wait(); + size_t accepted = 2; + for (unsigned i = 0; i < 500 && directlyStored.load() == 0; ++i) + { + auto id = "during-drain-" + std::to_string(i); + if (handler->StoreRecord(Record(id.c_str()))) + { + ++accepted; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + EXPECT_EQ(directlyStored.load(), 1u); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::timeout); + release.set_value(); + producer.join(); + shutdown.join(); + EXPECT_EQ(batched + directlyStored.load(), accepted); + EXPECT_EQ(dispatcher.Take(), nullptr); +} + +TEST_F(OfflineStorageLifecycleTests, DroppedTaskAllowsAnotherFlushToBeScheduled) +{ + dispatcher.behavior = ManualTaskDispatcher::Behavior::Drop; + ASSERT_TRUE(StoreTwo()); + ASSERT_TRUE(handler->StoreRecord(Record("third"))); + EXPECT_EQ(dispatcher.queueCalls.load(), 2u); + ExpectSaved(3); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, InlineDispatcherRunsFlushWithoutDeadlock) +{ + dispatcher.behavior = ManualTaskDispatcher::Behavior::Inline; + ExpectSaved(2); + ASSERT_TRUE(StoreTwo()); + EXPECT_EQ(dispatcher.queueCalls.load(), 1u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +#if HAVE_EXCEPTIONS +TEST_F(OfflineStorageLifecycleTests, FailedQueueDoesNotBlockLaterScheduling) +{ + dispatcher.behavior = ManualTaskDispatcher::Behavior::ThrowOnce; + ASSERT_TRUE(handler->StoreRecord(Record("first"))); + EXPECT_THROW(handler->StoreRecord(Record("second")), std::runtime_error); + ASSERT_TRUE(handler->StoreRecord(Record("third"))); + EXPECT_EQ(dispatcher.queueCalls.load(), 2u); + ExpectSaved(3); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, FailedDirectFlushReleasesActivityAndCanBeRetried) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& records) -> size_t { + records.clear(); + throw std::runtime_error("disk write failed"); + })) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + EXPECT_THROW(handler->Flush(), std::runtime_error); + EXPECT_EQ(logManager.activeActivities.load(), 0); + EXPECT_EQ(memory->GetRecordCount(), 2u); + handler->Flush(); + EXPECT_EQ(logManager.activeActivities.load(), 0); + EXPECT_EQ(memory->GetRecordCount(), 0u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, ConcurrentShutdownRetriesFailedAttempt) +{ + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + EXPECT_CALL(*disk, Shutdown()) + .WillOnce(Invoke([&] { + entered.set_value(); + releaseFuture.wait(); + throw std::runtime_error("shutdown failed"); + })) + .WillOnce(Return()); + + std::thread first([&] { EXPECT_THROW(handler->Shutdown(), std::runtime_error); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + first.join(); + FAIL() << "First shutdown did not reach storage"; + } + std::promise started; + auto startedFuture = started.get_future(); + std::promise finished; + auto done = finished.get_future(); + std::thread second([&] { + started.set_value(); + EXPECT_NO_THROW(handler->Shutdown()); + finished.set_value(); + }); + startedFuture.wait(); + EXPECT_EQ(done.wait_for(std::chrono::milliseconds(200)), std::future_status::timeout); + release.set_value(); + first.join(); + second.join(); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::ready); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, FailedShutdownFlushCanBeRetried) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Throw(std::runtime_error("disk write failed"))) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + EXPECT_CALL(*disk, Shutdown()); + EXPECT_THROW(handler->Shutdown(), std::runtime_error); + EXPECT_EQ(memory->GetRecordCount(), 2u); + handler->Shutdown(); + EXPECT_EQ(memory->GetRecordCount(), 0u); +} + +TEST_F(OfflineStorageLifecycleTests, ReinitializeRetriesFailedShutdownBeforeReplacingStorage) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Throw(std::runtime_error("disk write failed"))) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + EXPECT_CALL(*disk, Shutdown()).Times(2); + EXPECT_THROW(handler->Shutdown(), std::runtime_error); + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + EXPECT_EQ(memory->GetRecordCount(), 0u); + handler->Shutdown(); +} + +TEST(OfflineStorageHandlerFlushTests, RetryingDiskShutdownDoesNotRepeatMemoryShutdown) +{ + ConfigurableLogManager logManager; + NiceMock config; + ManualTaskDispatcher dispatcher; + StrictMock observer; + config[CFG_INT_RAM_QUEUE_SIZE] = 1024 * 1024; + config[CFG_BOOL_ENABLE_BATCHED_STORAGE_FLUSH] = true; + auto memory = std::make_shared>(); + auto disk = std::make_shared>(); + auto provider = std::make_shared(memory, disk); + OfflineStorageHandler handler(logManager, config, dispatcher, provider); + EXPECT_CALL(*disk, Initialize(Ref(handler))); + EXPECT_CALL(*memory, Initialize(Ref(handler))); + handler.Initialize(observer); + EXPECT_CALL(*memory, GetSize()).WillOnce(Return(0)); + EXPECT_CALL(*memory, Shutdown()).Times(1); + EXPECT_CALL(*disk, Shutdown()) + .WillOnce(Throw(std::runtime_error("shutdown failed"))) + .WillOnce(Return()); + EXPECT_THROW(handler.Shutdown(), std::runtime_error); + handler.Shutdown(); +} +#endif + +TEST_F(OfflineStorageLifecycleTests, PartialBatchMutationRetainsRecordsForRetry) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& records) -> size_t { + records.clear(); + return 1; + })) + .WillOnce(Invoke([](std::vector& records) { + EXPECT_EQ(records.size(), 2u); + return records.size(); + })); + EXPECT_CALL(observer, OnStorageRecordsSaved(1)); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + handler->Flush(); + EXPECT_EQ(memory->GetRecordCount(), 2u); + handler->Flush(); + EXPECT_EQ(memory->GetRecordCount(), 0u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, SavedObserverCanWaitForAnotherFlush) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + std::promise finished; + auto done = finished.get_future(); + std::thread nested; + EXPECT_CALL(observer, OnStorageRecordsSaved(2)) + .WillOnce(Invoke([&](size_t) { + nested = std::thread([&] { + handler->Flush(); + finished.set_value(); + }); + EXPECT_EQ(done.wait_for(std::chrono::seconds(5)), std::future_status::ready); + })); + handler->Flush(); + if (nested.joinable()) + { + nested.join(); + } + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, ReinitializeWithoutMemoryCacheStoresDirectlyToDisk) +{ + config[CFG_INT_RAM_QUEUE_SIZE] = 0; + EXPECT_CALL(*disk, Shutdown()); + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + + EXPECT_CALL(*disk, StoreRecord(_)).WillOnce(Return(true)); + EXPECT_TRUE(handler->StoreRecord(Record("direct"))); + EXPECT_EQ(memory->GetRecordCount(), 0u); + + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, OldDequeuedTaskStaysInertAfterReinitialize) +{ + ASSERT_TRUE(StoreTwo()); + auto oldTask = dispatcher.Take(); + ASSERT_NE(oldTask, nullptr); + ExpectSaved(2); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); + + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + ASSERT_TRUE(StoreTwo()); + const unsigned activitiesBeforeTask = logManager.activityCount.load(); + (*oldTask)(); + oldTask.reset(); + EXPECT_EQ(logManager.activityCount.load(), activitiesBeforeTask); + auto currentTask = dispatcher.Take(); + ASSERT_NE(currentTask, nullptr); + ExpectSaved(2); + (*currentTask)(); + EXPECT_GT(logManager.activityCount.load(), activitiesBeforeTask); + EXPECT_EQ(memory->GetRecordCount(), 0u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, ReinitializeWhileAcceptingClosesOldGeneration) +{ + ASSERT_TRUE(StoreTwo()); + auto oldTask = dispatcher.Take(); + ASSERT_NE(oldTask, nullptr); + ExpectSaved(2); + EXPECT_CALL(*disk, Shutdown()); + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + + ASSERT_TRUE(StoreTwo()); + const unsigned activitiesBeforeTask = logManager.activityCount.load(); + (*oldTask)(); + oldTask.reset(); + EXPECT_EQ(logManager.activityCount.load(), activitiesBeforeTask); + auto currentTask = dispatcher.Take(); + ASSERT_NE(currentTask, nullptr); + ExpectSaved(2); + (*currentTask)(); + EXPECT_EQ(memory->GetRecordCount(), 0u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, OldCompletionDoesNotClearNewerQueuedFlush) +{ + ASSERT_TRUE(StoreTwo()); + auto oldTask = dispatcher.Take(); + ASSERT_NE(oldTask, nullptr); + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([&](std::vector& records) { + entered.set_value(); + releaseFuture.wait(); + return records.size(); + })) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)).Times(2); + std::thread worker([task = std::move(oldTask)] { (*task)(); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + worker.join(); + FAIL() << "Scheduled flush did not enter storage"; + } + EXPECT_TRUE(handler->StoreRecord(Record("third"))); + EXPECT_TRUE(handler->StoreRecord(Record("fourth"))); + release.set_value(); + worker.join(); + auto newTask = dispatcher.Take(); + ASSERT_NE(newTask, nullptr); + (*newTask)(); + EXPECT_EQ(memory->GetRecordCount(), 0u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST(OfflineStorageHandlerFlushTests, ShutdownFlushesWhenActivitiesArePaused) +{ + PausedLogManager logManager; + NiceMock config; + ManualTaskDispatcher dispatcher; + StrictMock observer; + config[CFG_INT_RAM_QUEUE_SIZE] = 1024 * 1024; + config[CFG_BOOL_ENABLE_BATCHED_STORAGE_FLUSH] = true; + auto memory = std::make_shared(logManager, config); + auto disk = std::make_shared>(); + auto provider = std::make_shared(memory, disk); + OfflineStorageHandler handler(logManager, config, dispatcher, provider); + EXPECT_CALL(*disk, Initialize(Ref(handler))); + handler.Initialize(observer); + StorageRecord record("event", "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'x'}); + ASSERT_TRUE(handler.StoreRecord(record)); + handler.Flush(); + EXPECT_CALL(*disk, StoreRecords(_)).WillOnce(Return(1)); + EXPECT_CALL(observer, OnStorageRecordsSaved(1)); + EXPECT_CALL(*disk, Shutdown()); + handler.Shutdown(); +} + +TEST(OfflineStorageHandlerFlushTests, CapiDispatcherReceivesImmediateFlush) +{ + ConfigurableLogManager logManager; + NiceMock config; + PAL::TaskDispatcher_CAPI dispatcher(&QueueInlineCapiTask, &CancelCapiTask, &JoinCapiTasks); + StrictMock observer; + config[CFG_INT_RAM_QUEUE_SIZE] = 1; + config[CFG_BOOL_ENABLE_BATCHED_STORAGE_FLUSH] = true; + auto memory = std::make_shared(logManager, config); + auto disk = std::make_shared>(); + auto provider = std::make_shared(memory, disk); + OfflineStorageHandler handler(logManager, config, dispatcher, provider); + EXPECT_CALL(*disk, Initialize(Ref(handler))); + handler.Initialize(observer); + EXPECT_CALL(*disk, StoreRecords(_)).WillOnce(Return(2)); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + StorageRecord first("first", "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'x'}); + StorageRecord second("second", "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'y'}); + ASSERT_TRUE(handler.StoreRecord(first)); + ASSERT_TRUE(handler.StoreRecord(second)); + EXPECT_CALL(*disk, Shutdown()); + handler.Shutdown(); +} + +TEST(OfflineStorageHandlerFlushTests, DequeuedFlushCannotRunAfterShutdown) +{ + CountingLogManager logManager; + NiceMock config; + ManualTaskDispatcher dispatcher; + StrictMock observer; + config[CFG_INT_RAM_QUEUE_SIZE] = 1; + config[CFG_BOOL_ENABLE_BATCHED_STORAGE_FLUSH] = true; + auto memory = std::make_shared(logManager, config); + auto disk = std::make_shared>(); + auto provider = std::make_shared(memory, disk); + OfflineStorageHandler handler(logManager, config, dispatcher, provider); + EXPECT_CALL(*disk, Initialize(Ref(handler))); + handler.Initialize(observer); + + StorageRecord first("first", "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'x'}); + StorageRecord second("second", "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'y'}); + ASSERT_TRUE(handler.StoreRecord(first)); + ASSERT_TRUE(handler.StoreRecord(second)); + auto task = dispatcher.Take(); + ASSERT_NE(task, nullptr); + + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + handler.Flush(); + + EXPECT_CALL(*disk, Shutdown()); + handler.Shutdown(); + const unsigned activitiesBeforeTask = logManager.activityCount.load(); + (*task)(); + EXPECT_EQ(logManager.activityCount.load(), activitiesBeforeTask); +} + TEST(OfflineStorageHandlerFlushTests, FailedMemoryRequeueIsReportedAndDropped) { NullLogManager logManager; @@ -512,7 +1285,12 @@ TEST(OfflineStorageHandlerFlushTests, BatchedFlushKeepsMemoryOnlyRecordsOffDisk) EXPECT_CALL(*memory, StoreRecord(Field(&StorageRecord::id, "memory-only"))) .WillOnce(Return(true)); EXPECT_CALL(*disk, StoreRecord(_)).Times(0); - EXPECT_CALL(*disk, StoreRecords(_)).WillOnce(Return(1)); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& batch) -> size_t { + EXPECT_THAT(batch, ElementsAre(Field(&StorageRecord::id, "persisted"))); + batch.clear(); + return 1; + })); EXPECT_CALL(observer, OnStorageRecordsSaved(1)); handler.Flush(); diff --git a/tests/unittests/PalTests.cpp b/tests/unittests/PalTests.cpp index 9d4ba3891..cf37c8c56 100644 --- a/tests/unittests/PalTests.cpp +++ b/tests/unittests/PalTests.cpp @@ -592,6 +592,25 @@ namespace bool m_successorRan = false; }; + class TrackedImmediateTask final : public MAT::Task + { + public: + TrackedImmediateTask(std::atomic& ran, std::atomic& destroyed) : + m_ran(ran), m_destroyed(destroyed) + { + Type = MAT::Task::Call; + TargetTime = 0; + TypeName = "TrackedImmediateTask"; + } + + ~TrackedImmediateTask() noexcept override { m_destroyed.store(true); } + void operator()() override { m_ran.store(true); } + + private: + std::atomic& m_ran; + std::atomic& m_destroyed; + }; + class SelfDisposeHelper { public: @@ -682,6 +701,33 @@ TEST_F(PalTests, ScheduleTaskAfterWorkerThreadJoinReturnsNoOpHandle) EXPECT_TRUE(handle.Cancel()); } +TEST_F(PalTests, CancelRemovesQueuedImmediateTask) +{ + auto dispatcher = PAL::WorkerThreadFactory::Create(); + BlockingCancellationTarget blocker; + auto running = PAL::scheduleTask( + dispatcher.get(), 0, &blocker, &BlockingCancellationTarget::Block); + (void)running; + if (!blocker.WaitUntilEntered()) + { + blocker.Release(); + dispatcher->Join(); + FAIL() << "Worker did not start the blocking task"; + } + + std::atomic ran{false}; + std::atomic destroyed{false}; + auto task = std::make_unique(ran, destroyed); + auto* identity = task.get(); + dispatcher->Queue(task.release()); + EXPECT_TRUE(dispatcher->Cancel(identity)); + EXPECT_TRUE(destroyed.load()); + blocker.Release(); + dispatcher->Join(); + EXPECT_FALSE(ran.load()); + EXPECT_TRUE(destroyed.load()); +} + TEST_F(PalTests, ScheduleTaskHandleClearsAfterWorkerThreadCallbackCompletes) { auto dispatcher = PAL::WorkerThreadFactory::Create(); From 8a5e822935356bb06152a70161baf6d11ee7aee2 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Thu, 19 Nov 2026 14:43:22 -0600 Subject: [PATCH 05/19] Count early uploads without weakening the manager stress test File: tests/functests/MultipleLogManagersTests.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e5009227-6b49-4803-8153-63d8d94037e3 --- tests/functests/MultipleLogManagersTests.cpp | 100 ++++++++++++++++--- 1 file changed, 86 insertions(+), 14 deletions(-) diff --git a/tests/functests/MultipleLogManagersTests.cpp b/tests/functests/MultipleLogManagersTests.cpp index 420377442..024618621 100644 --- a/tests/functests/MultipleLogManagersTests.cpp +++ b/tests/functests/MultipleLogManagersTests.cpp @@ -13,6 +13,7 @@ #include "api/LogManagerFactory.hpp" #include "api/LogManagerImpl.hpp" +#include "utils/ZlibUtils.hpp" #include "CsProtocol_types.hpp" #include "bond/All.hpp" @@ -49,6 +50,8 @@ using namespace MAT; // iOS xctest gtest wrapper, so the exclusion must be at compile time.) #if !defined(TARGET_OS_IPHONE) || !TARGET_OS_IPHONE +constexpr static char final_event_name[] = "multi_manager_final_event"; + class RequestHandler : public HttpServer::Callback { public: @@ -58,6 +61,25 @@ class RequestHandler : public HttpServer::Callback { std::string expected_url = "/" + std::to_string(m_id) + "/"; EXPECT_EQ(request.uri, expected_url); + std::string body = request.content; + auto encoding = request.headers.find("Content-Encoding"); + if (encoding != request.headers.end()) + { + std::vector compressed(body.begin(), body.end()); + std::vector inflated; + if (ZlibUtils::InflateVector(compressed, inflated, encoding->second == "gzip")) + { + body.assign(inflated.begin(), inflated.end()); + } + else + { + body.clear(); + } + } + if (body.find(final_event_name) != std::string::npos) + { + m_receivedFinalEvent = true; + } m_count++; return 200; } @@ -66,8 +88,13 @@ class RequestHandler : public HttpServer::Callback return m_count; } + bool HasFinalEvent() const noexcept { + return m_receivedFinalEvent; + } + private: std::atomic m_count {}; + std::atomic m_receivedFinalEvent {}; int m_id ; }; @@ -147,18 +174,26 @@ class MultipleLogManagersTests : public ::testing::Test } } - void waitForRequestsSingleLogManager(unsigned timeout, unsigned expectedCount = 1) + bool waitForRequestsAndFinalEvent(unsigned timeout, size_t expectedCount) { - auto sz = callback1.GetRequestCount(); auto start = PAL::getUtcSystemTimeMs(); - while (callback1.GetRequestCount() - sz < expectedCount) + while (callback1.GetRequestCount() < expectedCount || !callback1.HasFinalEvent()) { if (PAL::getUtcSystemTimeMs() - start >= timeout) { - GTEST_FATAL_FAILURE_("Didn't receive request within given timeout"); + return false; } PAL::sleep(100); } + return true; + } + + template + bool startAndWaitForRequests(unsigned timeout, Action action) + { + auto expectedCount = callback1.GetRequestCount() + 2; + action(); + return waitForRequestsAndFinalEvent(timeout, expectedCount); } /* CsProtocol::ClientToCollectorRequest decodeRequest(HttpServer::Request const& request) @@ -212,6 +247,42 @@ TEST_F(MultipleLogManagersTests, ThreeInstancesCoexist) constexpr static unsigned max_iterations = 2000; +TEST_F(MultipleLogManagersTests, WaitIncludesRequestsReceivedBeforeWaiting) +{ + HttpServer::Request request {}; + HttpServer::Response response {}; + request.uri = "/1/"; + EXPECT_TRUE(startAndWaitForRequests(0, [&] { + request.content = final_event_name; + callback1.onHttpRequest(request, response); + request.content.clear(); + callback1.onHttpRequest(request, response); + })); +} + +TEST_F(MultipleLogManagersTests, WaitIgnoresRequestsBeforeStarting) +{ + HttpServer::Request request {}; + HttpServer::Response response {}; + request.uri = "/1/"; + callback1.onHttpRequest(request, response); + EXPECT_FALSE(startAndWaitForRequests(0, [&] { + request.content = final_event_name; + callback1.onHttpRequest(request, response); + })); +} + +TEST_F(MultipleLogManagersTests, WaitRequiresFinalEvent) +{ + HttpServer::Request request {}; + HttpServer::Response response {}; + request.uri = "/1/"; + EXPECT_FALSE(startAndWaitForRequests(0, [&] { + callback1.onHttpRequest(request, response); + callback1.onHttpRequest(request, response); + })); +} + TEST_F(MultipleLogManagersTests, MultiProcessesLogManager) { CAPTURE_PERF_STATS("start"); @@ -222,16 +293,17 @@ TEST_F(MultipleLogManagersTests, MultiProcessesLogManager) CAPTURE_PERF_STATS("LogManager created"); ILogger* logger = lm->GetLogger("aaa"); CAPTURE_PERF_STATS("Logger created"); - size_t numIterations = max_iterations; - while (numIterations--) - { - EventProperties props = CreateSampleEvent("event_name", EventPriority_Normal); - logger->LogEvent(props); - } - CAPTURE_PERF_STATS("Events Sent"); - lm->GetLogController()->UploadNow(); - CAPTURE_PERF_STATS("Events Uploaded"); - waitForRequestsSingleLogManager(20000, 2); + ASSERT_TRUE(startAndWaitForRequests(20000, [&] { + size_t numIterations = max_iterations; + while (numIterations--) + { + EventProperties props = CreateSampleEvent(numIterations == 0 ? final_event_name : "event_name", EventPriority_Normal); + logger->LogEvent(props); + } + CAPTURE_PERF_STATS("Events Sent"); + lm->GetLogController()->UploadNow(); + CAPTURE_PERF_STATS("Events Uploaded"); + })) << "Didn't receive two requests and the final event within the given timeout"; lm.reset(); CAPTURE_PERF_STATS("Log Manager deleted"); } From 0564675933eb20d1fb99ecd5c31de0d536e656fb Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Thu, 19 Nov 2026 17:15:37 -0600 Subject: [PATCH 06/19] Fail closed on decoder allocation and prefix bounds Reject unrepresentable compression bounds and handle allocation failure without exceptions. Decode size prefixes without alignment assumptions and reject truncated prefixes. Files changed: - lib/decoder/PayloadDecoder.cpp - tests/unittests/PayloadDecoderTests.cpp - tests/no-exceptions/no-exceptions-smoke.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e5009227-6b49-4803-8153-63d8d94037e3 --- lib/decoder/PayloadDecoder.cpp | 92 +++++--- tests/no-exceptions/no-exceptions-smoke.cpp | 52 ++++- tests/unittests/PayloadDecoderTests.cpp | 225 ++++++++++++++++++++ 3 files changed, 334 insertions(+), 35 deletions(-) diff --git a/lib/decoder/PayloadDecoder.cpp b/lib/decoder/PayloadDecoder.cpp index 25a0231ce..2c67dade0 100644 --- a/lib/decoder/PayloadDecoder.cpp +++ b/lib/decoder/PayloadDecoder.cpp @@ -33,6 +33,8 @@ MAT_NS_END #else #include #include +#include +#include #include #include #include @@ -391,7 +393,9 @@ namespace clienttelemetry { /// /// /// - bool Compress(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool prependSize) + // Successful custom allocations must be compatible with delete[]. + bool Compress(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool prependSize, + char* (*allocate)(size_t)) { if ((!source) || (!sourceLen)) { @@ -401,38 +405,48 @@ namespace clienttelemetry { *dest = NULL; destLen = 0; - // Compressing variables - uLong compSize = compressBound((uLong)sourceLen); + const auto inputSize = static_cast(sourceLen); + if (inputSize > static_cast(std::numeric_limits::max()) || + (prependSize && inputSize > static_cast(std::numeric_limits::max()))) + { + return false; + } - // Allocate memory for the new compressed buffer - size_t reserved = ((unsigned)prependSize * sizeof(uint32_t)); - char* compBody = new char[std::max(compSize, ((uLong)sourceLen)) + reserved]; - if (compBody != NULL) + uLong compSize = compressBound(static_cast(sourceLen)); + const size_t reserved = prependSize ? sizeof(uint32_t) : 0; + const size_t maxAllocation = static_cast(std::numeric_limits::max()); + if (compSize == std::numeric_limits::max() || compSize < sourceLen || + sourceLen > maxAllocation - reserved || compSize > maxAllocation - reserved) { - if (prependSize) - { - // Remember source uncompressed size if requested - uint32_t *s = (uint32_t*)(compBody); - (*s) = (uint32_t)sourceLen; // truncate this to 32-bit, we do not support 3+ TB blobs - } - // Deflate - int res = compress2((Bytef *)(compBody + reserved), &compSize, (Bytef *)source, (uLong)sourceLen, Z_BEST_SPEED); - if (res != Z_OK) - { - TEST_LOG_ERROR("Compression failed, error=%u", res); - delete[] compBody; - compBody = NULL; - return false; - } - else - { - *dest = compBody; - destLen = compSize + reserved; - return true; - } + return false; } - // OOM - return false; + + char* compBody = allocate(std::max(static_cast(compSize), sourceLen) + reserved); + if (compBody == nullptr) + { + return false; + } + if (prependSize) + { + const uint32_t originalSize = static_cast(sourceLen); + std::memcpy(compBody, &originalSize, sizeof(originalSize)); + } + int res = compress2((Bytef *)(compBody + reserved), &compSize, (Bytef *)source, (uLong)sourceLen, Z_BEST_SPEED); + if (res != Z_OK) + { + TEST_LOG_ERROR("Compression failed, error=%u", res); + delete[] compBody; + return false; + } + *dest = compBody; + destLen = compSize + reserved; + return true; + } + + bool Compress(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool prependSize) + { + return Compress(source, sourceLen, dest, destLen, prependSize, + [](size_t size) { return new (std::nothrow) char[size]; }); } /// @@ -460,13 +474,23 @@ namespace clienttelemetry { // Get uncompressed size at zero offset. if (sizeAtZeroIndex) { - uint32_t s32 = *((uint32_t*)(source)); - uint64_t s64 = (sourceLen >= sizeof(uint64_t)) ? *((uint64_t*)(source)) : 0; + if (sourceLen < sizeof(uint32_t)) + { + destLen = 0; + return false; + } + uint32_t s32 = 0; + std::memcpy(&s32, source, sizeof(s32)); // If we are reading 64-bit generated legacy DB, step 32-bit forward to // skip zero-padding in most-significant DWORD on Intel architecture - if ((s64 - s32) == 0) + if (sourceLen >= sizeof(uint64_t)) { - reserved += sizeof(uint32_t); + uint64_t s64 = 0; + std::memcpy(&s64, source, sizeof(s64)); + if (s64 == s32) + { + reserved += sizeof(uint32_t); + } } destLen = s32; } diff --git a/tests/no-exceptions/no-exceptions-smoke.cpp b/tests/no-exceptions/no-exceptions-smoke.cpp index d85307af3..79773285f 100644 --- a/tests/no-exceptions/no-exceptions-smoke.cpp +++ b/tests/no-exceptions/no-exceptions-smoke.cpp @@ -8,9 +8,11 @@ #include "http/HttpResponseDecoder.hpp" #include "utils/ZlibUtils.hpp" +#include #include #include #include +#include #if HAVE_EXCEPTIONS #error This regression executable must be compiled without C++ exceptions. @@ -19,9 +21,25 @@ #error This regression executable requires JSON and zlib support. #endif +namespace +{ + std::atomic failNextNothrowArrayAllocation {false}; +} + +void* operator new[](std::size_t size, const std::nothrow_t&) noexcept +{ + if (failNextNothrowArrayAllocation.exchange(false)) + { + return nullptr; + } + return ::operator new[](size); +} + namespace clienttelemetry { namespace data { namespace v3 { + bool Compress(const char*, size_t, char**, size_t&, bool); + bool Compress(const char*, size_t, char**, size_t&, bool, char* (*)(size_t)); bool Expand(const char*, size_t, char**, size_t&, bool); bool Expand(const char*, size_t, char**, size_t&, bool, char* (*)(size_t)); } @@ -151,6 +169,14 @@ int main() "oversized expansion must fail"); check(output == nullptr && outputSize == 0, "failed expansion must clear outputs"); char previousOutput = 0; + for (size_t length = 1; length < sizeof(uint32_t); ++length) + { + output = &previousOutput; + outputSize = 32; + check(!clienttelemetry::data::v3::Expand(invalidCompressed, length, &output, outputSize, true), + "short size prefix must fail"); + check(output == nullptr && outputSize == 0, "short size prefix must clear outputs"); + } output = &previousOutput; outputSize = 32; static size_t requestedSize = 0; @@ -161,6 +187,30 @@ int main() }), "representable allocation failure must return false"); check(requestedSize == 32, "failure injection must reach the allocator"); check(output == nullptr && outputSize == 0, "allocation failure must clear an existing output and its length"); - std::puts("Passed no-exceptions configuration, response, profile, numeric-limit, and expansion smoke checks."); + output = &previousOutput; + outputSize = 32; + requestedSize = 0; + check(!clienttelemetry::data::v3::Compress(invalidCompressed, sizeof(invalidCompressed), &output, outputSize, false, + [](size_t size) -> char* { + requestedSize = size; + return nullptr; + }), "compression allocation failure must return false"); + check(requestedSize > sizeof(invalidCompressed), "compression failure injection must reach the allocator"); + check(output == nullptr && outputSize == 0, "failed compression must clear output and its length"); + output = &previousOutput; + outputSize = 32; + failNextNothrowArrayAllocation = true; + const bool compressed = clienttelemetry::data::v3::Compress( + invalidCompressed, sizeof(invalidCompressed), &output, outputSize, false); + check(!failNextNothrowArrayAllocation, "default compression must use the nothrow array allocator"); + check(!compressed && output == nullptr && outputSize == 0, + "default compression must report allocation failure without exceptions"); + output = &previousOutput; + outputSize = 32; + check(!clienttelemetry::data::v3::Compress(invalidCompressed, std::numeric_limits::max(), + &output, outputSize, true), + "unrepresentable compression size must fail"); + check(output == nullptr && outputSize == 0, "oversized compression must clear output and its length"); + std::puts("Passed no-exceptions configuration, response, profile, numeric-limit, and compression smoke checks."); return EXIT_SUCCESS; } diff --git a/tests/unittests/PayloadDecoderTests.cpp b/tests/unittests/PayloadDecoderTests.cpp index 6a3d8f6a2..5be428b5f 100644 --- a/tests/unittests/PayloadDecoderTests.cpp +++ b/tests/unittests/PayloadDecoderTests.cpp @@ -5,16 +5,23 @@ #include "common/Common.hpp" #include "PayloadDecoder.hpp" #include "utils/ZlibUtils.hpp" +#include +#include #include +#include #if defined(HAVE_MAT_ZLIB) && defined(HAVE_MAT_JSONHPP) #include "bond/All.hpp" #include "bond/generated/CsProtocol_writers.hpp" #include +#include namespace clienttelemetry { namespace data { namespace v3 { + bool Compress(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool prependSize); + bool Compress(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool prependSize, + char* (*allocate)(size_t)); bool Expand(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool sizeAtZeroIndex); bool Expand(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool sizeAtZeroIndex, char* (*allocate)(size_t)); @@ -147,6 +154,224 @@ TEST(PayloadDecoderTests, DecodeRecord_ValidUtf8_IsPreserved) } #if defined(HAVE_MAT_ZLIB) && defined(HAVE_MAT_JSONHPP) +TEST(PayloadDecoderTests, Compress_InvalidInputLeavesOutputUnchanged) +{ + const char source[] = "sample"; + char previousOutput = 0; + char* output = &previousOutput; + size_t outputSize = 32; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(nullptr, sizeof(source), &output, outputSize, false)); + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, 0, &output, outputSize, false)); + EXPECT_EQ(output, &previousOutput); + EXPECT_EQ(outputSize, 32u); +} + +TEST(PayloadDecoderTests, Compress_AllocationFailureClearsExistingOutput) +{ + const char source[] = "sample"; + for (bool prependSize : {false, true}) + { + char previousOutput = 0; + char* output = &previousOutput; + size_t outputSize = 32; + static size_t requestedSize = 0; + requestedSize = 0; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, sizeof(source), &output, outputSize, prependSize, + [](size_t size) -> char* { + requestedSize = size; + return nullptr; + })); + EXPECT_GT(requestedSize, sizeof(source)); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + } +} + +TEST(PayloadDecoderTests, Compress_RejectsUnrepresentableSizeBeforeAllocation) +{ + const char source[] = "sample"; + for (bool prependSize : {false, true}) + { + char previousOutput = 0; + char* output = &previousOutput; + size_t outputSize = 32; + static bool allocated = false; + allocated = false; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, std::numeric_limits::max(), + &output, outputSize, prependSize, [](size_t) -> char* { + allocated = true; + return nullptr; + })); + EXPECT_FALSE(allocated); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + } +} + +TEST(PayloadDecoderTests, Compress_RejectsSaturatedZlibBound) +{ + const auto maxZlibSize = static_cast(std::numeric_limits::max()); + if (maxZlibSize <= std::numeric_limits::max()) + { + const char source[] = "sample"; + char* output = nullptr; + size_t outputSize = 0; + static bool allocated = false; + allocated = false; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, static_cast(maxZlibSize), + &output, outputSize, false, [](size_t) -> char* { + allocated = true; + return nullptr; + })); + EXPECT_FALSE(allocated); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + } +} + +TEST(PayloadDecoderTests, Compress_RejectsUnrepresentableAllocationBound) +{ + const auto maxAllocation = static_cast(std::numeric_limits::max()); + if (maxAllocation <= static_cast(std::numeric_limits::max())) + { + const char source[] = "sample"; + char* output = nullptr; + size_t outputSize = 0; + static bool allocated = false; + allocated = false; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, static_cast(maxAllocation), + &output, outputSize, false, [](size_t) -> char* { + allocated = true; + return nullptr; + })); + EXPECT_FALSE(allocated); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + } +} + +TEST(PayloadDecoderTests, Compress_RejectsSizeThatCannotFitPrefix) +{ + const auto oversized = static_cast(std::numeric_limits::max()) + 1; + if (oversized <= std::numeric_limits::max()) + { + const char source[] = "sample"; + char* output = nullptr; + size_t outputSize = 0; + static bool allocated = false; + allocated = false; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, static_cast(oversized), + &output, outputSize, true, [](size_t) -> char* { + allocated = true; + return nullptr; + })); + EXPECT_FALSE(allocated); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + + if (oversized <= static_cast(std::numeric_limits::max()) && + oversized < static_cast(std::numeric_limits::max())) + { + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, static_cast(oversized), + &output, outputSize, false, [](size_t) -> char* { + allocated = true; + return nullptr; + })); + EXPECT_TRUE(allocated); + } + } +} + +TEST(PayloadDecoderTests, Compress_PreservesZlibOutputWithAndWithoutSizePrefix) +{ + const char source[] = "sample compression payload"; + std::vector expected(compressBound(sizeof(source))); + uLongf expectedSize = static_cast(expected.size()); + ASSERT_EQ(compress2(expected.data(), &expectedSize, reinterpret_cast(source), + sizeof(source), Z_BEST_SPEED), Z_OK); + + for (bool prependSize : {false, true}) + { + char* output = nullptr; + size_t outputSize = 0; + ASSERT_TRUE(clienttelemetry::data::v3::Compress(source, sizeof(source), &output, outputSize, prependSize)); + std::unique_ptr owned(output); + const size_t reserved = prependSize ? sizeof(uint32_t) : 0; + ASSERT_EQ(outputSize, expectedSize + reserved); + EXPECT_EQ(std::memcmp(output + reserved, expected.data(), expectedSize), 0); + if (prependSize) + { + uint32_t originalSize = 0; + std::memcpy(&originalSize, output, sizeof(originalSize)); + EXPECT_EQ(originalSize, sizeof(source)); + + std::vector unaligned(outputSize + 1); + std::memcpy(unaligned.data() + 1, output, outputSize); + char* expanded = nullptr; + size_t expandedSize = 0; + ASSERT_TRUE(clienttelemetry::data::v3::Expand( + unaligned.data() + 1, outputSize, &expanded, expandedSize, true)); + std::unique_ptr expandedOwner(expanded); + ASSERT_EQ(expandedSize, sizeof(source)); + EXPECT_EQ(std::memcmp(expanded, source, sizeof(source)), 0); + + const uint16_t endianMarker = 1; + if (*reinterpret_cast(&endianMarker) == 1) + { + std::vector legacy(outputSize + sizeof(uint32_t) + 1, 0); + std::memcpy(legacy.data() + 1, output, sizeof(uint32_t)); + std::memcpy(legacy.data() + 1 + sizeof(uint64_t), output + sizeof(uint32_t), + outputSize - sizeof(uint32_t)); + expanded = nullptr; + expandedSize = 0; + ASSERT_TRUE(clienttelemetry::data::v3::Expand(legacy.data() + 1, + outputSize + sizeof(uint32_t), &expanded, expandedSize, true)); + std::unique_ptr legacyOwner(expanded); + ASSERT_EQ(expandedSize, sizeof(source)); + EXPECT_EQ(std::memcmp(expanded, source, sizeof(source)), 0); + } + } + char restored[sizeof(source)] {}; + uLongf restoredSize = sizeof(restored); + ASSERT_EQ(uncompress(reinterpret_cast(restored), &restoredSize, + reinterpret_cast(output + reserved), + static_cast(outputSize - reserved)), Z_OK); + ASSERT_EQ(restoredSize, sizeof(source)); + EXPECT_EQ(std::memcmp(restored, source, sizeof(source)), 0); + } +} + +TEST(PayloadDecoderTests, Expand_RejectsShortOrIncompleteSizePrefixes) +{ + char previousOutput = 0; + char* output = &previousOutput; + size_t outputSize = 32; + const char source = 0; + EXPECT_FALSE(clienttelemetry::data::v3::Expand(&source, 0, &output, outputSize, true)); + EXPECT_EQ(output, &previousOutput); + EXPECT_EQ(outputSize, 32u); + + for (size_t length = 1; length <= sizeof(uint64_t); ++length) + { + std::vector prefix(length, 0); + output = &previousOutput; + outputSize = 32; + EXPECT_FALSE(clienttelemetry::data::v3::Expand(prefix.data(), prefix.size(), &output, outputSize, true)); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + + if (length >= sizeof(uint32_t)) + { + const uint32_t declaredSize = 1; + std::memcpy(prefix.data(), &declaredSize, sizeof(declaredSize)); + output = &previousOutput; + outputSize = 32; + EXPECT_FALSE(clienttelemetry::data::v3::Expand(prefix.data(), prefix.size(), &output, outputSize, true)); + EXPECT_EQ(output, nullptr); + } + } +} + TEST(PayloadDecoderTests, Expand_UnrepresentableSizeClearsOutput) { const char source[] = "invalid"; From f5cc37e222fd62b0d2daaf4eb9e215810ef34ffa Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sun, 8 Nov 2026 16:17:44 -0600 Subject: [PATCH 07/19] Keep late telemetry workers safe in embedded SDK copies Retain the SDK version and auth-token lock through exit-owner teardown. Honor Apple system SQLite/zlib even with vcpkg, and let independent embedded copies select a private Objective-C HTTP delegate name without changing the default. Files: CMakeLists.txt; cmake/MatsdkOptions.cmake; docs/embedding-with-cmake.md; lib/CMakeLists.txt; lib/api/AuthTokensController.cpp; lib/pal/PAL.cpp; tests/apple/embedding-options-tests.cmake; tests/apple/embedding-options/CMakeLists.txt; tests/embedding/CMakeLists.txt; tests/embedding/lifetime-tests.cmake; tests/embedding/lifetime-tests.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 5484aed9-9464-4bc8-9ca7-fd67954034ff (cherry picked from commit 66faca8d506351f0559e65e475897109d631afce) --- CMakeLists.txt | 4 +- cmake/MatsdkOptions.cmake | 5 + docs/embedding-with-cmake.md | 16 +++- lib/CMakeLists.txt | 5 + lib/api/AuthTokensController.cpp | 8 +- lib/pal/PAL.cpp | 8 +- tests/apple/embedding-options-tests.cmake | 43 +++++++++ tests/apple/embedding-options/CMakeLists.txt | 70 ++++++++++++++ tests/embedding/CMakeLists.txt | 7 ++ tests/embedding/lifetime-tests.cmake | 52 +++++++++++ tests/embedding/lifetime-tests.cpp | 98 ++++++++++++++++++++ 11 files changed, 309 insertions(+), 7 deletions(-) create mode 100644 tests/apple/embedding-options-tests.cmake create mode 100644 tests/apple/embedding-options/CMakeLists.txt create mode 100644 tests/embedding/lifetime-tests.cmake create mode 100644 tests/embedding/lifetime-tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f56eb8f7f..105ceb21b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -228,7 +228,7 @@ if(TARGET SQLite::SQLite3 AND NOT TARGET SQLite3::SQLite3) matsdk_add_interface_dependency(SQLite3::SQLite3 SQLite::SQLite3) endif() if(MATSDK_SQLITE_PROVIDER_RESOLVED STREQUAL "SYSTEM" AND NOT TARGET SQLite3::SQLite3) - if(APPLE AND NOT MATSDK_USING_VCPKG) + if(APPLE) matsdk_add_apple_system_library(SQLite3::SQLite3 sqlite3) set(MATSDK_SQLITE_DEPENDENCY_KIND APPLE_SYSTEM) else() @@ -253,7 +253,7 @@ if(MATSDK_SQLITE_PROVIDER_RESOLVED STREQUAL "SYSTEM" AND NOT TARGET SQLite3::SQL endif() if(MATSDK_ZLIB_PROVIDER_RESOLVED STREQUAL "SYSTEM" AND NOT TARGET ZLIB::ZLIB) - if(APPLE AND NOT MATSDK_USING_VCPKG) + if(APPLE) matsdk_add_apple_system_library(ZLIB::ZLIB z) set(MATSDK_ZLIB_DEPENDENCY_KIND APPLE_SYSTEM) else() diff --git a/cmake/MatsdkOptions.cmake b/cmake/MatsdkOptions.cmake index ac8a38c7e..41fd4812b 100644 --- a/cmake/MatsdkOptions.cmake +++ b/cmake/MatsdkOptions.cmake @@ -51,6 +51,11 @@ option(MATSDK_BUILD_AZMON "Build Azure Monitor / Application Insights support" ON) option(MATSDK_BUILD_APPLE_HTTP "Build the Apple-native HTTP client" "${APPLE}") +set(MATSDK_APPLE_HTTP_DELEGATE_CLASS "MATStreamingSessionDelegate" CACHE STRING + "Private Objective-C class name for the Apple HTTP session delegate") +if(NOT MATSDK_APPLE_HTTP_DELEGATE_CLASS MATCHES "^[A-Za-z_][A-Za-z0-9_]*$") + message(FATAL_ERROR "MATSDK_APPLE_HTTP_DELEGATE_CLASS must be a C identifier.") +endif() option(MATSDK_USE_WININET "Use WinInet instead of WinHTTP as the Win32 desktop HTTP client" OFF) option(MATSDK_DISABLE_LOGGING diff --git a/docs/embedding-with-cmake.md b/docs/embedding-with-cmake.md index 692d91579..7bcd58f0a 100644 --- a/docs/embedding-with-cmake.md +++ b/docs/embedding-with-cmake.md @@ -61,7 +61,8 @@ Recommended packaged-library policy: | Android | `MINIMAL`, or `NONE` with Room | `VENDORED` | Java/JNI by default | Apple's SQLite and zlib entries are system libraries: consumers link them but -do not ship private copies. A Linux host such as Foundry Local that already +do not ship private copies, including when a vcpkg toolchain is active. Existing +caller-provided canonical targets still take precedence. A Linux host such as Foundry Local that already standardizes on libcurl/OpenSSL should provide `CURL::libcurl` and select `MATSDK_CURL_PROVIDER=SYSTEM`; other self-contained Linux consumers can use the SDK's pinned curl/mbedTLS build. @@ -71,6 +72,19 @@ consumer must set `skipSqliteInitAndShutdown` to `"true"` and leave SQLite's process-wide lifetime to the host. This is the required configuration for coexisting Apple libraries that all link the system `libsqlite3`. +When independently embedded SDK copies coexist in an Apple process, choose a +different private HTTP delegate class name for each copy before adding the SDK: + +```cmake +set(MATSDK_APPLE_HTTP_DELEGATE_CLASS MyProductMATStreamingSessionDelegate + CACHE STRING "" FORCE) +``` + +The default remains `MATStreamingSessionDelegate`. Objective-C class names are +process-global even when C++ symbols are hidden. This setting affects only the +Apple HTTP implementation and does not propagate to consumers or rename public +Objective-C wrapper classes. + ## Non-vcpkg dependency selection When the CPP11 PAL uses the curl HTTP transport outside vcpkg, the SDK normally diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index d44de8ab6..43eb05d07 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -376,6 +376,11 @@ else() message(STATUS "Building static SDK library") add_library(mat STATIC ${SRCS}) endif() +if(APPLE AND MATSDK_BUILD_APPLE_HTTP) + # Objective-C class names are process-global, even with hidden symbol visibility. + target_compile_definitions(mat PRIVATE + "MATStreamingSessionDelegate=${MATSDK_APPLE_HTTP_DELEGATE_CLASS}") +endif() target_link_libraries(mat PRIVATE $ $) diff --git a/lib/api/AuthTokensController.cpp b/lib/api/AuthTokensController.cpp index 4a7778aaa..93c0ba806 100644 --- a/lib/api/AuthTokensController.cpp +++ b/lib/api/AuthTokensController.cpp @@ -6,6 +6,7 @@ #include "AuthTokensController.hpp" #include "ILogManager.hpp" #include "utils/Utils.hpp" +#include namespace MAT_NS_BEGIN { @@ -24,8 +25,11 @@ namespace MAT_NS_BEGIN { std::mutex& AuthTokensController::GetMutex() { - static std::mutex mutex; - return mutex; + // Like GetPAL(), this lock must survive late upload workers. + using AuthMutex = std::mutex; + alignas(AuthMutex) static unsigned char storage[sizeof(AuthMutex)]; + static AuthMutex* mutex = ::new (storage) AuthMutex; + return *mutex; } status_t AuthTokensController::SetTicketToken(TicketType type, char const* tokenValue) diff --git a/lib/pal/PAL.cpp b/lib/pal/PAL.cpp index 8356e3648..860e40806 100644 --- a/lib/pal/PAL.cpp +++ b/lib/pal/PAL.cpp @@ -658,8 +658,12 @@ namespace PAL_NS_BEGIN { const std::string& PlatformAbstractionLayer::getSdkVersion() const { - static const std::string sdkVersion(EVTSDK_VERSION_PREFIX "-" OS_NAME "-C++-" ECS_SUPP "-" BUILD_VERSION_STR); - return sdkVersion; + // Like GetPAL(), this immutable value must survive late upload workers. + using SdkVersion = std::string; + alignas(SdkVersion) static unsigned char storage[sizeof(SdkVersion)]; + static const SdkVersion* sdkVersion = ::new (storage) + SdkVersion(EVTSDK_VERSION_PREFIX "-" OS_NAME "-C++-" ECS_SUPP "-" BUILD_VERSION_STR); + return *sdkVersion; } void PlatformAbstractionLayer::initialize(IRuntimeConfig& configuration) diff --git a/tests/apple/embedding-options-tests.cmake b/tests/apple/embedding-options-tests.cmake new file mode 100644 index 000000000..01a203e49 --- /dev/null +++ b/tests/apple/embedding-options-tests.cmake @@ -0,0 +1,43 @@ +cmake_minimum_required(VERSION 3.19) +get_filename_component(sdk_root "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) +if(NOT DEFINED OUTPUT_DIR) + set(OUTPUT_DIR "${sdk_root}/out/apple-embedding-options") +endif() +set(generator_args) +if(TEST_GENERATOR) + list(APPEND generator_args -G "${TEST_GENERATOR}") +endif() +if(TEST_GENERATOR_PLATFORM) + list(APPEND generator_args -A "${TEST_GENERATOR_PLATFORM}") +endif() + +function(check_options apple vcpkg provided http class) + # Keep MSBuild's nested compiler-probe paths below its legacy path limit. + string(SHA1 name "${apple}-${vcpkg}-${provided}-${http}-${class}") + string(SUBSTRING "${name}" 0 6 name) + execute_process(COMMAND "${CMAKE_COMMAND}" ${generator_args} + -S "${CMAKE_CURRENT_LIST_DIR}/embedding-options" -B "${OUTPUT_DIR}/${name}" + "-DSDK_ROOT=${sdk_root}" "-DTEST_APPLE=${apple}" "-DTEST_VCPKG=${vcpkg}" + "-DTEST_PROVIDED=${provided}" "-DTEST_HTTP=${http}" + "-DMATSDK_APPLE_HTTP_DELEGATE_CLASS=${class}" + RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) + if(class STREQUAL "invalid-class") + if(result EQUAL 0 OR NOT error MATCHES "must be a C identifier") + message(FATAL_ERROR "Invalid delegate name was not rejected:\n${output}\n${error}") + endif() + elseif(NOT result EQUAL 0) + message(FATAL_ERROR "${apple}/${vcpkg}/${provided}/${http}/${class} failed:\n${output}\n${error}") + endif() +endfunction() + +foreach(apple ON OFF) + foreach(vcpkg ON OFF) + foreach(provided ON OFF) + check_options("${apple}" "${vcpkg}" "${provided}" ON MATStreamingSessionDelegate) + check_options("${apple}" "${vcpkg}" "${provided}" ON ProductMATStreamingSessionDelegate) + endforeach() + endforeach() +endforeach() +check_options(ON ON OFF OFF ProductMATStreamingSessionDelegate) +check_options(ON ON OFF ON invalid-class) +message(STATUS "18 Apple dependency/delegate configurations passed") diff --git a/tests/apple/embedding-options/CMakeLists.txt b/tests/apple/embedding-options/CMakeLists.txt new file mode 100644 index 000000000..0188837f4 --- /dev/null +++ b/tests/apple/embedding-options/CMakeLists.txt @@ -0,0 +1,70 @@ +cmake_minimum_required(VERSION 3.19) +project(apple_embedding_options LANGUAGES C CXX) + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/platform.cmake" "set(APPLE ${TEST_APPLE})\n") +set(CMAKE_PROJECT_INCLUDE "${CMAKE_CURRENT_BINARY_DIR}/platform.cmake") +set(APPLE "${TEST_APPLE}") +if(TEST_VCPKG) + set(VCPKG_TARGET_TRIPLET test-triplet) +endif() +set(MATSDK_BUILD_HEADERS OFF CACHE BOOL "" FORCE) +set(MATSDK_BUILD_LIBRARY OFF CACHE BOOL "" FORCE) +set(MATSDK_BUILD_TEST_TOOL OFF CACHE BOOL "" FORCE) +set(MATSDK_BUILD_UNIT_TESTS OFF CACHE BOOL "" FORCE) +set(MATSDK_BUILD_FUNC_TESTS OFF CACHE BOOL "" FORCE) +set(MATSDK_BUILD_PACKAGE OFF CACHE BOOL "" FORCE) +set(MATSDK_BUILD_APPLE_HTTP "${TEST_HTTP}" CACHE BOOL "" FORCE) +set(MATSDK_SQLITE_PROVIDER SYSTEM CACHE STRING "" FORCE) +set(MATSDK_ZLIB_PROVIDER SYSTEM CACHE STRING "" FORCE) +add_library(CURL::libcurl INTERFACE IMPORTED) +add_library(nlohmann_json::nlohmann_json INTERFACE IMPORTED) +if(TEST_PROVIDED OR NOT TEST_APPLE) + add_library(SQLite3::SQLite3 INTERFACE IMPORTED) + add_library(ZLIB::ZLIB INTERFACE IMPORTED) + set_property(TARGET SQLite3::SQLite3 PROPERTY INTERFACE_LINK_LIBRARIES caller-sqlite) + set_property(TARGET ZLIB::ZLIB PROPERTY INTERFACE_LINK_LIBRARIES caller-zlib) +endif() +foreach(package SQLite3 unofficial-sqlite3 ZLIB nlohmann_json) + set(CMAKE_DISABLE_FIND_PACKAGE_${package} ON) +endforeach() +add_subdirectory("${SDK_ROOT}" sdk) +foreach(pair "SQLite3::SQLite3|sqlite3|caller-sqlite" "ZLIB::ZLIB|z|caller-zlib") + string(REPLACE "|" ";" pair "${pair}") + list(GET pair 0 target) + list(GET pair 1 expected) + if(TEST_PROVIDED OR NOT TEST_APPLE) + list(GET pair 2 expected) + endif() + get_target_property(links "${target}" INTERFACE_LINK_LIBRARIES) + if(NOT links STREQUAL expected) + message(FATAL_ERROR "${target} links ${links}, expected ${expected}") + endif() +endforeach() + +# Evaluate the production target guard without requiring an Apple compiler or SDK. +file(READ "${SDK_ROOT}/lib/CMakeLists.txt" library) +string(FIND "${library}" "if(APPLE AND MATSDK_BUILD_APPLE_HTTP)" start) +if(start EQUAL -1) + message(FATAL_ERROR "Update Apple delegate target instrumentation") +endif() +string(SUBSTRING "${library}" ${start} -1 definition) +string(FIND "${definition}" "\nendif()" end) +math(EXPR end "${end} + 8") +string(SUBSTRING "${definition}" 0 ${end} definition) +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/delegate.cpp" "") +add_library(mat STATIC "${CMAKE_CURRENT_BINARY_DIR}/delegate.cpp") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/delegate.cmake" "${definition}") +include("${CMAKE_CURRENT_BINARY_DIR}/delegate.cmake") +get_target_property(private mat COMPILE_DEFINITIONS) +get_target_property(public mat INTERFACE_COMPILE_DEFINITIONS) +set(expected "MATStreamingSessionDelegate=${MATSDK_APPLE_HTTP_DELEGATE_CLASS}") +if(TEST_APPLE AND TEST_HTTP) + if(NOT expected IN_LIST private) + message(FATAL_ERROR "Missing private Apple delegate definition: ${private}") + endif() +elseif(expected IN_LIST private) + message(FATAL_ERROR "Delegate definition leaked into a non-Apple HTTP build") +endif() +if(expected IN_LIST public) + message(FATAL_ERROR "Delegate definition propagated to consumers") +endif() diff --git a/tests/embedding/CMakeLists.txt b/tests/embedding/CMakeLists.txt index fb7a01ffa..9b1a4cc8f 100644 --- a/tests/embedding/CMakeLists.txt +++ b/tests/embedding/CMakeLists.txt @@ -114,3 +114,10 @@ endif() enable_testing() add_test(NAME embedding_test COMMAND embedding_test) +include("${CMAKE_CURRENT_LIST_DIR}/lifetime-tests.cmake") +add_test(NAME apple_embedding_options + COMMAND "${CMAKE_COMMAND}" + "-DOUTPUT_DIR=${CMAKE_CURRENT_BINARY_DIR}/apple-options" + "-DTEST_GENERATOR=${CMAKE_GENERATOR}" + "-DTEST_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}" + -P "${CMAKE_CURRENT_LIST_DIR}/../apple/embedding-options-tests.cmake") diff --git a/tests/embedding/lifetime-tests.cmake b/tests/embedding/lifetime-tests.cmake new file mode 100644 index 000000000..9db97aac4 --- /dev/null +++ b/tests/embedding/lifetime-tests.cmake @@ -0,0 +1,52 @@ +# Static embedding lets the instrumented production objects replace their archive counterparts. +if(BUILD_SHARED_LIBS) + return() +endif() + +set(lifetime_dir "${CMAKE_CURRENT_BINARY_DIR}/lifetime-sdk") +file(MAKE_DIRECTORY "${lifetime_dir}") +foreach(source pal/PAL.cpp api/AuthTokensController.cpp) + set(source_path "${sdk_source}/lib/${source}") + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${source_path}") + file(READ "${source_path}" instrumented) + if(source STREQUAL "pal/PAL.cpp") + string(REPLACE "static const std::string sdkVersion(" "static const LifetimeString sdkVersion(" + instrumented "${instrumented}") + string(REPLACE "using SdkVersion = std::string;" "using SdkVersion = LifetimeString;" + instrumented "${instrumented}") + set(hook "LifetimeVersionDestroyed") + set(type String) + set(base string) + else() + string(REPLACE "static std::mutex mutex;" "static LifetimeMutex mutex;" + instrumented "${instrumented}") + string(REPLACE "using AuthMutex = std::mutex;" "using AuthMutex = LifetimeMutex;" + instrumented "${instrumented}") + set(hook "LifetimeMutexDestroyed") + set(type Mutex) + set(base mutex) + endif() + if(NOT instrumented MATCHES "(static const LifetimeString sdkVersion|using SdkVersion = LifetimeString|static LifetimeMutex mutex|using AuthMutex = LifetimeMutex)") + message(FATAL_ERROR "Update lifetime instrumentation for ${source}") + endif() + string(PREPEND instrumented + "#include \n#include \n" + "extern \"C\" void ${hook}();\n" + "struct Lifetime${type} : std::${base} {\n" + " using std::${base}::${base};\n" + " ~Lifetime${type}() { ${hook}(); }\n" + "};\n") + get_filename_component(name "${source}" NAME) + file(WRITE "${lifetime_dir}/${name}" "${instrumented}") +endforeach() + +add_executable(sdk_lifetime_tests "${CMAKE_CURRENT_LIST_DIR}/lifetime-tests.cpp" + "${lifetime_dir}/PAL.cpp" "${lifetime_dir}/AuthTokensController.cpp") +target_link_libraries(sdk_lifetime_tests PRIVATE MSTelemetry::mat matsdk_internal_config matsdk_build_options) +target_include_directories(sdk_lifetime_tests PRIVATE "$" + "${sdk_source}/lib/api") +add_dependencies(embedding_test sdk_lifetime_tests) +foreach(mode version mutex both) + add_test(NAME sdk_lifetime_${mode} COMMAND sdk_lifetime_tests "${mode}") + set_tests_properties(sdk_lifetime_${mode} PROPERTIES TIMEOUT 30) +endforeach() diff --git a/tests/embedding/lifetime-tests.cpp b/tests/embedding/lifetime-tests.cpp new file mode 100644 index 000000000..90df11436 --- /dev/null +++ b/tests/embedding/lifetime-tests.cpp @@ -0,0 +1,98 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +#include "api/AuthTokensController.hpp" +#include "pal/PAL.hpp" + +#include +#include +#include +#include +#include +#include + +namespace +{ + std::atomic versionDestroyed{false}; + std::atomic mutexDestroyed{false}; + bool checkVersion = false; + bool checkMutex = false; + const std::string* versionAddress = nullptr; + std::mutex* mutexAddress = nullptr; + + void Fail(const char* message) + { + std::fprintf(stderr, "%s\n", message); +#ifdef _WIN32 + // The exit owner holds the CRT exit lock while waiting for this worker. + ::TerminateProcess(::GetCurrentProcess(), 1); +#endif + std::_Exit(1); + } + + void ReadState() + { + if (checkVersion) + { + if (versionDestroyed.load()) + { + Fail("SDK version was destroyed before its exit owner"); + } + const auto& version = PAL::GetPAL().getSdkVersion(); + if (version.empty() || (versionAddress && versionAddress != &version)) + { + Fail("SDK version did not retain its value and identity"); + } + versionAddress = &version; + } + if (checkMutex) + { + if (mutexDestroyed.load()) + { + Fail("Auth mutex was destroyed before its exit owner"); + } + auto& mutex = MAT::AuthTokensController::GetMutex(); + if (mutexAddress && mutexAddress != &mutex) + { + Fail("Auth mutex did not retain its identity"); + } + std::lock_guard lock(mutex); + mutexAddress = &mutex; + } + } + + void ExitOwner() + { + // Model an owner registered before its first upload initializes SDK state. + std::thread lateWorker(ReadState); + lateWorker.join(); + } +} + +extern "C" void LifetimeVersionDestroyed() +{ + versionDestroyed.store(true); +} + +extern "C" void LifetimeMutexDestroyed() +{ + mutexDestroyed.store(true); +} + +int main(int argc, char** argv) +{ + if (argc != 2) + { + return 2; + } + checkVersion = std::strcmp(argv[1], "version") == 0 || std::strcmp(argv[1], "both") == 0; + checkMutex = std::strcmp(argv[1], "mutex") == 0 || std::strcmp(argv[1], "both") == 0; + if ((!checkVersion && !checkMutex) || std::atexit(ExitOwner) != 0) + { + return 2; + } + ReadState(); + ReadState(); + return 0; +} From b4ec224c39fae0cab18278970be87d9d9030175c Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Mon, 9 Nov 2026 00:40:52 -0600 Subject: [PATCH 08/19] Avoid SDK version buffer leaks when embedded libraries unload The placement-new string avoided exit-time destruction but abandoned its heap buffer on unload: two real reload cycles leak 56 bytes under LSan. Return the compile-time literal through the internal const-char accessor instead, preserving late-worker safety without allocation or destruction. Keep the auth mutex and existing Apple embedding fixes unchanged. Files: - lib/pal/PAL.cpp, lib/pal/PAL.hpp: allocation-free internal version accessor. - tests/embedding/lifetime-tests.cpp: string-view value/address expectations. - tests/embedding/lifetime-tests.cmake: entry instrumentation and real DSO test. - tests/embedding/version-reload-fixture.cpp: embed the production SDK archive. - tests/embedding/version-reload-test.cpp: verify two actual unload cycles. - tests/embedding/CMakeLists.txt: opt-in Linux ASan/LSan coverage. - .github/workflows/test-embedding.yml: enforce sanitizer coverage in CI. Validation: Windows VS2026 and Linux GCC13 ASan/LSan embedding suites each pass all six tests. The old placement-new buffer leaks exactly 56 bytes; original destructible statics fail all three lifetime tests on both OSes. Formatting, existing misspell workflow and git diff --check pass. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 5484aed9-9464-4bc8-9ca7-fd67954034ff (cherry picked from commit e630e2c9d11176499856393ffac9179520c80da6) --- .github/workflows/test-embedding.yml | 18 ++++ lib/pal/PAL.cpp | 10 +-- lib/pal/PAL.hpp | 4 +- tests/embedding/CMakeLists.txt | 19 +++++ tests/embedding/lifetime-tests.cmake | 35 +++++++- tests/embedding/lifetime-tests.cpp | 30 ++++++- tests/embedding/version-reload-fixture.cpp | 18 ++++ tests/embedding/version-reload-test.cpp | 96 ++++++++++++++++++++++ 8 files changed, 216 insertions(+), 14 deletions(-) create mode 100644 tests/embedding/version-reload-fixture.cpp create mode 100644 tests/embedding/version-reload-test.cpp diff --git a/.github/workflows/test-embedding.yml b/.github/workflows/test-embedding.yml index 2a0795866..9df6f47a5 100644 --- a/.github/workflows/test-embedding.yml +++ b/.github/workflows/test-embedding.yml @@ -94,6 +94,24 @@ jobs: cmake --build build-provided-consumer --parallel 4 ctest --test-dir build-provided-consumer --output-on-failure + linux-lifetime-sanitizers: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - name: Install system dependencies + run: sudo apt-get update && sudo apt-get install -y libcurl4-openssl-dev libsqlite3-dev ninja-build zlib1g-dev + - name: Configure ASan and LSan embedding regressions + run: > + cmake -G Ninja -S tests/embedding -B build-lifetimes + -DCMAKE_BUILD_TYPE=RelWithDebInfo + -DMATSDK_EMBEDDING_ADDRESS_SANITIZER=ON + -DMATSDK_SQLITE_PROVIDER=SYSTEM + -DMATSDK_ZLIB_PROVIDER=SYSTEM + - name: Build and run + run: | + cmake --build build-lifetimes --target embedding_test --parallel 4 + ctest --test-dir build-lifetimes --output-on-failure + windows: runs-on: windows-2022 steps: diff --git a/lib/pal/PAL.cpp b/lib/pal/PAL.cpp index 860e40806..e81827a13 100644 --- a/lib/pal/PAL.cpp +++ b/lib/pal/PAL.cpp @@ -656,14 +656,10 @@ namespace PAL_NS_BEGIN { #define OS_NAME "Unknown" #endif - const std::string& PlatformAbstractionLayer::getSdkVersion() const + const char* PlatformAbstractionLayer::getSdkVersion() const { - // Like GetPAL(), this immutable value must survive late upload workers. - using SdkVersion = std::string; - alignas(SdkVersion) static unsigned char storage[sizeof(SdkVersion)]; - static const SdkVersion* sdkVersion = ::new (storage) - SdkVersion(EVTSDK_VERSION_PREFIX "-" OS_NAME "-C++-" ECS_SUPP "-" BUILD_VERSION_STR); - return *sdkVersion; + // A literal survives late workers without leaking a string buffer on library unload. + return EVTSDK_VERSION_PREFIX "-" OS_NAME "-C++-" ECS_SUPP "-" BUILD_VERSION_STR; } void PlatformAbstractionLayer::initialize(IRuntimeConfig& configuration) diff --git a/lib/pal/PAL.hpp b/lib/pal/PAL.hpp index 209d1ad6c..eca9edf32 100644 --- a/lib/pal/PAL.hpp +++ b/lib/pal/PAL.hpp @@ -78,7 +78,7 @@ namespace PAL_NS_BEGIN public: void sleep(unsigned delayMs) const noexcept; - const std::string& getSdkVersion() const; + const char* getSdkVersion() const; std::string generateUuidString() const; @@ -140,7 +140,7 @@ namespace PAL_NS_BEGIN /** * Return SDK version in format "----". */ - inline const std::string& getSdkVersion() + inline const char* getSdkVersion() { return GetPAL().getSdkVersion(); } diff --git a/tests/embedding/CMakeLists.txt b/tests/embedding/CMakeLists.txt index 9b1a4cc8f..792283f2f 100644 --- a/tests/embedding/CMakeLists.txt +++ b/tests/embedding/CMakeLists.txt @@ -5,7 +5,22 @@ set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) +option(MATSDK_EMBEDDING_ADDRESS_SANITIZER + "Run embedding regressions with AddressSanitizer and leak detection" OFF) +if(MATSDK_EMBEDDING_ADDRESS_SANITIZER) + if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux" OR + NOT CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + message(FATAL_ERROR "Embedding ASan/LSan coverage requires Linux with GCC or Clang") + endif() + add_compile_options(-fsanitize=address -fno-omit-frame-pointer) + add_link_options(-fsanitize=address) +endif() + set(BUILD_SHARED_LIBS OFF CACHE BOOL "") +if(MATSDK_EMBEDDING_ADDRESS_SANITIZER AND BUILD_SHARED_LIBS) + message(FATAL_ERROR "Embedding ASan/LSan coverage requires static SDK embedding") +endif() + set(MATSDK_BUILD_HEADERS ON CACHE BOOL "" FORCE) set(MATSDK_BUILD_LIBRARY ON CACHE BOOL "" FORCE) set(MATSDK_BUILD_TEST_TOOL OFF CACHE BOOL "" FORCE) @@ -115,6 +130,10 @@ endif() enable_testing() add_test(NAME embedding_test COMMAND embedding_test) include("${CMAKE_CURRENT_LIST_DIR}/lifetime-tests.cmake") +if(MATSDK_EMBEDDING_ADDRESS_SANITIZER) + set_tests_properties(sdk_version_reload PROPERTIES + ENVIRONMENT "ASAN_OPTIONS=detect_leaks=1;LSAN_OPTIONS=exitcode=23") +endif() add_test(NAME apple_embedding_options COMMAND "${CMAKE_COMMAND}" "-DOUTPUT_DIR=${CMAKE_CURRENT_BINARY_DIR}/apple-options" diff --git a/tests/embedding/lifetime-tests.cmake b/tests/embedding/lifetime-tests.cmake index 9db97aac4..8de708589 100644 --- a/tests/embedding/lifetime-tests.cmake +++ b/tests/embedding/lifetime-tests.cmake @@ -14,6 +14,14 @@ foreach(source pal/PAL.cpp api/AuthTokensController.cpp) instrumented "${instrumented}") string(REPLACE "using SdkVersion = std::string;" "using SdkVersion = LifetimeString;" instrumented "${instrumented}") + # Hook entry, not a local variable: the allocation-free implementation has none. + string(REGEX REPLACE "(PlatformAbstractionLayer::getSdkVersion\\(\\) const[ \r\n]*\\{)" + "\\1\n LifetimeVersionAccessed();" instrumented "${instrumented}") + if(NOT instrumented MATCHES "LifetimeVersionAccessed\\(\\);") + message(FATAL_ERROR "Update version accessor lifetime instrumentation") + endif() + string(PREPEND instrumented + "extern \"C\" void LifetimeVersionAccessed();\n") set(hook "LifetimeVersionDestroyed") set(type String) set(base string) @@ -26,7 +34,7 @@ foreach(source pal/PAL.cpp api/AuthTokensController.cpp) set(type Mutex) set(base mutex) endif() - if(NOT instrumented MATCHES "(static const LifetimeString sdkVersion|using SdkVersion = LifetimeString|static LifetimeMutex mutex|using AuthMutex = LifetimeMutex)") + if(NOT instrumented MATCHES "(LifetimeVersionAccessed\\(\\);|static LifetimeMutex mutex|using AuthMutex = LifetimeMutex)") message(FATAL_ERROR "Update lifetime instrumentation for ${source}") endif() string(PREPEND instrumented @@ -43,6 +51,7 @@ endforeach() add_executable(sdk_lifetime_tests "${CMAKE_CURRENT_LIST_DIR}/lifetime-tests.cpp" "${lifetime_dir}/PAL.cpp" "${lifetime_dir}/AuthTokensController.cpp") target_link_libraries(sdk_lifetime_tests PRIVATE MSTelemetry::mat matsdk_internal_config matsdk_build_options) +target_compile_features(sdk_lifetime_tests PRIVATE cxx_std_17) target_include_directories(sdk_lifetime_tests PRIVATE "$" "${sdk_source}/lib/api") add_dependencies(embedding_test sdk_lifetime_tests) @@ -50,3 +59,27 @@ foreach(mode version mutex both) add_test(NAME sdk_lifetime_${mode} COMMAND sdk_lifetime_tests "${mode}") set_tests_properties(sdk_lifetime_${mode} PROPERTIES TIMEOUT 30) endforeach() + +# Embed the actual archive, not the instrumented copies, to catch unload-time leaks. +add_library(sdk_version_reload_fixture SHARED version-reload-fixture.cpp) +target_link_libraries(sdk_version_reload_fixture PRIVATE MSTelemetry::mat + matsdk_internal_config matsdk_build_options) +target_compile_features(sdk_version_reload_fixture PRIVATE cxx_std_17) +target_include_directories(sdk_version_reload_fixture PRIVATE + "$") +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + # GNU-unique symbols pin DSOs; symbol interposition can bind to another SDK copy. + target_compile_options(mat PRIVATE $<$:-fno-gnu-unique>) + target_link_options(sdk_version_reload_fixture PRIVATE + "-Wl,--exclude-libs,ALL" "-Wl,-Bsymbolic") +endif() + +add_executable(sdk_version_reload_test version-reload-test.cpp) +target_link_libraries(sdk_version_reload_test PRIVATE ${CMAKE_DL_LIBS} + matsdk_internal_config matsdk_build_options) +target_include_directories(sdk_version_reload_test PRIVATE + "$") +add_dependencies(embedding_test sdk_version_reload_fixture sdk_version_reload_test) +add_test(NAME sdk_version_reload + COMMAND sdk_version_reload_test "$") +set_tests_properties(sdk_version_reload PROPERTIES TIMEOUT 30) diff --git a/tests/embedding/lifetime-tests.cpp b/tests/embedding/lifetime-tests.cpp index 90df11436..be59e18c8 100644 --- a/tests/embedding/lifetime-tests.cpp +++ b/tests/embedding/lifetime-tests.cpp @@ -2,6 +2,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // +#include "Version.hpp" #include "api/AuthTokensController.hpp" #include "pal/PAL.hpp" @@ -10,6 +11,7 @@ #include #include #include +#include #include namespace @@ -18,7 +20,7 @@ namespace std::atomic mutexDestroyed{false}; bool checkVersion = false; bool checkMutex = false; - const std::string* versionAddress = nullptr; + const char* versionAddress = nullptr; std::mutex* mutexAddress = nullptr; void Fail(const char* message) @@ -39,24 +41,34 @@ namespace { Fail("SDK version was destroyed before its exit owner"); } - const auto& version = PAL::GetPAL().getSdkVersion(); - if (version.empty() || (versionAddress && versionAddress != &version)) + + const std::string_view version = PAL::GetPAL().getSdkVersion(); + const std::string_view prefix = EVTSDK_VERSION_PREFIX "-"; + const std::string_view suffix = "-C++-" ECS_SUPP "-" BUILD_VERSION_STR; + if (version.substr(0, prefix.size()) != prefix || + version.size() < suffix.size() || + version.substr(version.size() - suffix.size()) != suffix || + (versionAddress && versionAddress != version.data())) { Fail("SDK version did not retain its value and identity"); } - versionAddress = &version; + + versionAddress = version.data(); } + if (checkMutex) { if (mutexDestroyed.load()) { Fail("Auth mutex was destroyed before its exit owner"); } + auto& mutex = MAT::AuthTokensController::GetMutex(); if (mutexAddress && mutexAddress != &mutex) { Fail("Auth mutex did not retain its identity"); } + std::lock_guard lock(mutex); mutexAddress = &mutex; } @@ -75,6 +87,14 @@ extern "C" void LifetimeVersionDestroyed() versionDestroyed.store(true); } +extern "C" void LifetimeVersionAccessed() +{ + if (versionDestroyed.load()) + { + Fail("SDK version accessed after destruction"); + } +} + extern "C" void LifetimeMutexDestroyed() { mutexDestroyed.store(true); @@ -86,12 +106,14 @@ int main(int argc, char** argv) { return 2; } + checkVersion = std::strcmp(argv[1], "version") == 0 || std::strcmp(argv[1], "both") == 0; checkMutex = std::strcmp(argv[1], "mutex") == 0 || std::strcmp(argv[1], "both") == 0; if ((!checkVersion && !checkMutex) || std::atexit(ExitOwner) != 0) { return 2; } + ReadState(); ReadState(); return 0; diff --git a/tests/embedding/version-reload-fixture.cpp b/tests/embedding/version-reload-fixture.cpp new file mode 100644 index 000000000..8f63cd91c --- /dev/null +++ b/tests/embedding/version-reload-fixture.cpp @@ -0,0 +1,18 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +#include "pal/PAL.hpp" + +#include + +#ifdef _WIN32 +#define EXPORTED __declspec(dllexport) +#else +#define EXPORTED __attribute__((visibility("default"))) +#endif + +extern "C" EXPORTED const char* GetSdkVersionForReload() +{ + return std::string_view(PAL::getSdkVersion()).data(); +} diff --git a/tests/embedding/version-reload-test.cpp b/tests/embedding/version-reload-test.cpp new file mode 100644 index 000000000..d07fc5785 --- /dev/null +++ b/tests/embedding/version-reload-test.cpp @@ -0,0 +1,96 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +#include "Version.hpp" +#include "mat/config.h" + +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace +{ + bool CheckVersion(const char* version) + { + const char prefix[] = EVTSDK_VERSION_PREFIX "-"; +#ifdef HAVE_MAT_EXP + const char suffix[] = "-C++-ECS-" BUILD_VERSION_STR; +#else + const char suffix[] = "-C++-No-" BUILD_VERSION_STR; +#endif + if (!version) + { + return false; + } + + const auto size = std::strlen(version); + return size >= sizeof(suffix) - 1 && + std::strncmp(version, prefix, sizeof(prefix) - 1) == 0 && + std::strcmp(version + size - (sizeof(suffix) - 1), suffix) == 0; + } + + bool Reload(const char* path) + { +#ifdef _WIN32 + const auto library = ::LoadLibraryA(path); + const auto version = library + ? reinterpret_cast(::GetProcAddress(library, "GetSdkVersionForReload")) + : nullptr; +#else + auto* library = dlopen(path, RTLD_NOW | RTLD_LOCAL); + const auto version = library + ? reinterpret_cast(dlsym(library, "GetSdkVersionForReload")) + : nullptr; +#endif + if (!library) + { + std::fprintf(stderr, "Unable to load SDK fixture: %s\n", path); + return false; + } + + // Do not keep a pointer into an unloaded DSO or heap buffer on the stack. + const bool valid = version && CheckVersion(version()) && CheckVersion(version()); +#ifdef _WIN32 + const bool unloaded = ::FreeLibrary(library) && !::GetModuleHandleA(path); +#else + const bool closed = dlclose(library) == 0; + auto* remaining = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + const bool unloaded = closed && !remaining; + if (remaining) + { + dlclose(remaining); + } +#endif + if (!valid || !unloaded) + { + std::fprintf(stderr, "SDK version validation or actual library unload failed\n"); + } + + return valid && unloaded; + } +} + +int main(int argc, char** argv) +{ + if (argc != 2) + { + return 2; + } + + for (int cycle = 0; cycle != 2; ++cycle) + { + if (!Reload(argv[1])) + { + return 1; + } + } + + std::puts("PASS two SDK version unload/reload cycles"); + return 0; +} From d5e25fa4f9757f6290b047f570254e523af26f46 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Mon, 9 Nov 2026 11:54:49 -0600 Subject: [PATCH 09/19] Keep batched telemetry storage within its configured limit Repeat 25% trims while the database remains oversized, stopping if resizing fails or makes no progress. Large flushes can otherwise leave the database above its limit and fail the iOS functional test. Files changed: lib/offline/OfflineStorage_SQLite.cpp; tests/unittests/OfflineStorageTests_SQLite.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2b4dcf34-18a6-4f77-9013-1db2fe20cc40 (cherry picked from commit 5f424de2d8d29c4a4d901284e863dd38d2032fc6) --- lib/offline/OfflineStorage_SQLite.cpp | 9 +++++-- .../unittests/OfflineStorageTests_SQLite.cpp | 25 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/lib/offline/OfflineStorage_SQLite.cpp b/lib/offline/OfflineStorage_SQLite.cpp index 631fd6dd5..a921a3e0e 100644 --- a/lib/offline/OfflineStorage_SQLite.cpp +++ b/lib/offline/OfflineStorage_SQLite.cpp @@ -255,9 +255,14 @@ namespace MAT_NS_BEGIN { { LOCKGUARD(m_resizeLock); //Serialize resize operations m_resizing = true; - if (m_DbSizeEstimate > m_DbSizeLimit) + // A batch can exceed the limit by more than one 25% trim. + while (m_DbSizeEstimate > m_DbSizeLimit) { - ResizeDb(); + const size_t previousSize = GetSize(); + if (!ResizeDb() || m_DbSizeEstimate >= previousSize) + { + break; + } } m_resizing = false; } diff --git a/tests/unittests/OfflineStorageTests_SQLite.cpp b/tests/unittests/OfflineStorageTests_SQLite.cpp index 79f631c83..33a28080f 100644 --- a/tests/unittests/OfflineStorageTests_SQLite.cpp +++ b/tests/unittests/OfflineStorageTests_SQLite.cpp @@ -1135,6 +1135,31 @@ TEST_F(OfflineStorageTests_SQLite, ResizeDbCompactsThePhysicalDatabase) EXPECT_LE(offlineStorage->GetSize(), maximumSize); } +TEST_F(OfflineStorageTests_SQLite, BatchStorageLimitRequiresMultipleTrims) +{ + constexpr size_t maximumSize = 5 * 1024 * 1024; + EXPECT_CALL(configMock, GetOfflineStorageMaximumSizeBytes()) + .WillRepeatedly(Return(maximumSize)); + configMock[CFG_BOOL_ENABLE_DB_DROP_IF_FULL] = true; + initializeStorage(false); + + std::vector records; + for (int i = 0; i < 15; ++i) + { + records.push_back({ + "record-" + std::to_string(i), + "token", + EventLatency_Normal, + EventPersistence_Normal, + i + 1, + StorageBlob(512 * 1024) }); + } + + ASSERT_THAT(offlineStorage->StoreRecords(records), records.size()); + EXPECT_LE(offlineStorage->GetSize(), maximumSize); + EXPECT_GT(offlineStorage->GetRecordCount(EventLatency_Unspecified), size_t { 0 }); +} + TEST_F(OfflineStorageTests_SQLite, StorageLimitIncludesLargePageOverhead) { sqlite3* db = nullptr; From 5540a51c1ee85f1cfe35be63c44ac326e718375e Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Mon, 9 Nov 2026 14:06:18 -0600 Subject: [PATCH 10/19] Trim minizip packaging forks to keep the vendor delta focused Restore upstream's cached BZip2 capability contract and pkg-config defaults instead of carrying SDK-unrelated dependency naming and configuration policy. Keep demonstrated gzip/ZIP runtime fixes, archive regressions, SDK shims, and the focused minizip include-directory, version, and large-file checks. Remove tests tied to the reverted packaging policies; preserve the original package consumers and shared/static archive tests. Files changed: - zlib/contrib/minizip/CMakeLists.txt - zlib/contrib/minizip/minizip.pc.txt - zlib/contrib/minizip/minizipConfig.cmake.in - zlib/contrib/minizip/test/CMakeLists.txt - zlib/contrib/minizip/test/find_package_test.cmake.in - zlib/contrib/minizip/test/pkg-config-test.cmake.in (removed) Validation: Windows minizip 11/11 and SDK embedding 6/6; Linux minizip 11/11 with BZip2 OFF and 11/11 ON, ASan/LSan embedding 6/6; existing misspell workflow and git diff --check. No remaining tests skipped. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 976e8fb6-5cab-4bb8-955e-9eeb6f8d44d9 (cherry picked from commit 6fb4a2e059ea1a17398d941ac54f2510b5015bf9) --- zlib/contrib/minizip/CMakeLists.txt | 110 ++---------------- zlib/contrib/minizip/minizip.pc.txt | 11 +- zlib/contrib/minizip/minizipConfig.cmake.in | 6 +- zlib/contrib/minizip/test/CMakeLists.txt | 29 ----- .../minizip/test/find_package_test.cmake.in | 22 ---- .../minizip/test/pkg-config-test.cmake.in | 31 ----- 6 files changed, 19 insertions(+), 190 deletions(-) delete mode 100644 zlib/contrib/minizip/test/pkg-config-test.cmake.in diff --git a/zlib/contrib/minizip/CMakeLists.txt b/zlib/contrib/minizip/CMakeLists.txt index 02deda8d4..795328bbb 100644 --- a/zlib/contrib/minizip/CMakeLists.txt +++ b/zlib/contrib/minizip/CMakeLists.txt @@ -39,7 +39,6 @@ include(CheckSymbolExists) include(CheckIncludeFile) include(CMakePackageConfigHelpers) include(CheckTypeSize) -include(CMakePushCheckState) include(GNUInstallDirs) if(NOT CPACK_INCLUDED) @@ -65,8 +64,7 @@ endif(MINIZIP_ENABLE_BZIP2) # # Check for fopen64 # -cmake_push_check_state() -list(APPEND CMAKE_REQUIRED_DEFINITIONS -D_LARGEFILE64_SOURCE=1) +set(CMAKE_REQUIRED_DEFINITIONS -D_LARGEFILE64_SOURCE=1) check_symbol_exists(fopen64 stdio.h HAVE_FOPEN64) # @@ -83,7 +81,7 @@ check_include_file(unistd.h HAVE_UNISTD_H) # Check to see if we have large file support # check_type_size(off64_t OFF64_T) -cmake_pop_check_state() +unset(CMAKE_REQUIRED_DEFINITIONS) # clear variable # # Check visibility attribute is supported @@ -146,6 +144,9 @@ set(MINIUNZIP_HDRS unzip.h zip.h) +set(LIBMINIZIP_PC ${minizip_BINARY_DIR}/minizip.pc) +configure_file(${minizip_SOURCE_DIR}/minizip.pc.txt ${LIBMINIZIP_PC} @ONLY) + if(WIN32 OR CYGWIN) set(minizip_static_suffix "s") set(CMAKE_DEBUG_POSTFIX "d") @@ -160,7 +161,6 @@ if(MINIZIP_BUILD_SHARED) target_include_directories(${ZLIB_CONTRIB_PREFIX}libminizip PUBLIC $ - $ $) target_compile_definitions(${ZLIB_CONTRIB_PREFIX}libminizip PRIVATE @@ -240,7 +240,6 @@ if(MINIZIP_BUILD_STATIC) target_include_directories(${ZLIB_CONTRIB_PREFIX}libminizipstatic PUBLIC $ - $ $) target_compile_definitions(${ZLIB_CONTRIB_PREFIX}libminizipstatic PRIVATE @@ -310,95 +309,6 @@ if(MINIZIP_BUILD_STATIC) PRIVATE MINIZIP::minizipstatic) endif(MINIZIP_BUILD_STATIC) -if(MINIZIP_BUILD_SHARED OR MINIZIP_BUILD_STATIC) - if(MINIZIP_BUILD_SHARED) - set(MINIZIP_PC_TARGET MINIZIP::minizip) - set(MINIZIP_PC_ZLIB_TARGET ZLIB::ZLIB) - else() - set(MINIZIP_PC_TARGET MINIZIP::minizipstatic) - set(MINIZIP_PC_ZLIB_TARGET ZLIB::ZLIBSTATIC) - endif() - function(minizip_pc_library_name target output) - get_target_property(_minizip_imported ${target} IMPORTED) - if(NOT _minizip_imported) - set(${output} "$" PARENT_SCOPE) - return() - endif() - # Imported targets do not expose their filename through the base-name expression. - set(_minizip_library "") - set(_minizip_configs NOCONFIG ${CMAKE_CONFIGURATION_TYPES} ${CMAKE_BUILD_TYPE}) - list(REMOVE_DUPLICATES _minizip_configs) - get_target_property(_minizip_imported_configs - ${target} IMPORTED_CONFIGURATIONS) - foreach(_minizip_config IN LISTS _minizip_configs) - string(TOUPPER "${_minizip_config}" _minizip_upper) - get_target_property(_minizip_file ${target} - LOCATION_${_minizip_upper}) - get_target_property(_minizip_mapped ${target} - MAP_IMPORTED_CONFIG_${_minizip_upper}) - if(NOT _minizip_mapped) - set(_minizip_mapped "") - endif() - foreach(_minizip_import IN ITEMS ${_minizip_mapped} - ${_minizip_upper} NOCONFIG ${_minizip_imported_configs}) - string(TOUPPER "${_minizip_import}" _minizip_import) - get_target_property(_minizip_implib ${target} - IMPORTED_IMPLIB_${_minizip_import}) - if(_minizip_implib) - set(_minizip_file "${_minizip_implib}") - break() - endif() - endforeach() - if(NOT _minizip_implib) - get_target_property(_minizip_implib ${target} IMPORTED_IMPLIB) - if(_minizip_implib) - set(_minizip_file "${_minizip_implib}") - endif() - endif() - get_filename_component(_minizip_name "${_minizip_file}" NAME_WE) - if(CMAKE_STATIC_LIBRARY_PREFIX) - string(REGEX REPLACE "^${CMAKE_STATIC_LIBRARY_PREFIX}" "" - _minizip_name "${_minizip_name}") - endif() - if(_minizip_config STREQUAL "NOCONFIG") - set(_minizip_config "") - endif() - string(APPEND _minizip_library - "$<$:${_minizip_name}>") - endforeach() - set(${output} "${_minizip_library}" PARENT_SCOPE) - endfunction() - minizip_pc_library_name(${MINIZIP_PC_TARGET} MINIZIP_PC_LIBRARY) - minizip_pc_library_name(${MINIZIP_PC_ZLIB_TARGET} MINIZIP_PC_ZLIB_LIBRARY) - set(MINIZIP_PC_LIBS_PRIVATE "") - set(MINIZIP_PC_CFLAGS "") - get_target_property(_minizip_zlib_imported ${MINIZIP_PC_ZLIB_TARGET} IMPORTED) - if(_minizip_zlib_imported) - string(APPEND MINIZIP_PC_LIBS_PRIVATE - "-L\"$\" ") - set(MINIZIP_PC_CFLAGS - "-I\"$,\" -I\">\"") - endif() - string(APPEND MINIZIP_PC_LIBS_PRIVATE "-l${MINIZIP_PC_ZLIB_LIBRARY}") - if(MINIZIP_ENABLE_BZIP2) - minizip_pc_library_name(BZip2::BZip2 MINIZIP_PC_BZIP2_LIBRARY) - string(APPEND MINIZIP_PC_LIBS_PRIVATE - " -L\"$\" -l${MINIZIP_PC_BZIP2_LIBRARY}") - endif(MINIZIP_ENABLE_BZIP2) - foreach(dir IN ITEMS LIBDIR INCLUDEDIR) - if(IS_ABSOLUTE "${CMAKE_INSTALL_${dir}}") - set(MINIZIP_PC_${dir} "${CMAKE_INSTALL_${dir}}") - else() - set(MINIZIP_PC_${dir} "\${exec_prefix}/${CMAKE_INSTALL_${dir}}") - endif() - endforeach() - set(LIBMINIZIP_PC ${minizip_BINARY_DIR}/$/minizip.pc) - configure_file(${minizip_SOURCE_DIR}/minizip.pc.txt - ${minizip_BINARY_DIR}/minizip.pc.in @ONLY) - file(GENERATE OUTPUT ${LIBMINIZIP_PC} - INPUT ${minizip_BINARY_DIR}/minizip.pc.in) -endif() - if(MINIZIP_INSTALL) if(MINIZIP_BUILD_SHARED) install( @@ -462,12 +372,10 @@ if(MINIZIP_INSTALL) install(FILES ${minizip_BINARY_DIR}/minizipConfig.cmake ${minizip_BINARY_DIR}/minizipConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/minizip) - if(MINIZIP_BUILD_SHARED OR MINIZIP_BUILD_STATIC) - install( - FILES ${LIBMINIZIP_PC} - COMPONENT Development - DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") - endif() + install( + FILES ${LIBMINIZIP_PC} + COMPONENT Development + DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") endif(MINIZIP_INSTALL) if(MINIZIP_BUILD_TESTING) diff --git a/zlib/contrib/minizip/minizip.pc.txt b/zlib/contrib/minizip/minizip.pc.txt index d075af1dc..060ab091c 100644 --- a/zlib/contrib/minizip/minizip.pc.txt +++ b/zlib/contrib/minizip/minizip.pc.txt @@ -1,14 +1,13 @@ prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=@CMAKE_INSTALL_PREFIX@ -libdir=@MINIZIP_PC_LIBDIR@ -sharedlibdir=@MINIZIP_PC_LIBDIR@ -includedir=@MINIZIP_PC_INCLUDEDIR@ +libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@ +sharedlibdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@ +includedir=${exec_prefix}/@CMAKE_INSTALL_INCLUDEDIR@ Name: minizip Description: minizip compression library Version: @minizip_VERSION@ Requires: -Libs: -L${libdir} -L${sharedlibdir} -l@MINIZIP_PC_LIBRARY@ -Libs.private: @MINIZIP_PC_LIBS_PRIVATE@ -Cflags: -I${includedir} -I${includedir}/minizip @MINIZIP_PC_CFLAGS@ +Libs: -L${libdir} -L${sharedlibdir} -lz -lminizip +Cflags: -I${includedir} diff --git a/zlib/contrib/minizip/minizipConfig.cmake.in b/zlib/contrib/minizip/minizipConfig.cmake.in index 474f2da30..71bed1d67 100644 --- a/zlib/contrib/minizip/minizipConfig.cmake.in +++ b/zlib/contrib/minizip/minizipConfig.cmake.in @@ -1,7 +1,11 @@ set(_MINIZIP_supported_components "shared" "static") include(CMakeFindDependencyMacro) -set(minizip_HAS_BZIP2 "@MINIZIP_ENABLE_BZIP2@") +set(minizip_HAS_BZIP2 + "@MINIZIP_ENABLE_BZIP2@" + CACHE + BOOL + "Indicates if minizip was compiled with bzip2 support") if(minizip_HAS_BZIP2) find_dependency(BZip2) diff --git a/zlib/contrib/minizip/test/CMakeLists.txt b/zlib/contrib/minizip/test/CMakeLists.txt index 578c4bd17..4801dfe05 100644 --- a/zlib/contrib/minizip/test/CMakeLists.txt +++ b/zlib/contrib/minizip/test/CMakeLists.txt @@ -106,35 +106,6 @@ set_tests_properties(minizip_find_package_build PROPERTIES FIXTURES_REQUIRED mzfp_config) -if(NOT MSVC) - find_package(PkgConfig QUIET) - if(PKG_CONFIG_FOUND) - configure_file( - ${CMAKE_CURRENT_SOURCE_DIR}/pkg-config-test.cmake.in - ${WORK_DIR}/minizip_pkg_config_test/CMakeLists.txt @ONLY) - add_test(NAME minizip_pkg_config_configure - COMMAND ${CMAKE_COMMAND} ${PLATFORM} - -B${WORK_DIR}/minizip_pkg_config_test_build - -DCMAKE_BUILD_TYPE=$ - -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} - -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS} - "-DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES}" - "-DCMAKE_OSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET}" - -DCMAKE_INSTALL_PREFIX=${WORK_DIR}/test_install - $<$:--fresh> - -G "${CMAKE_GENERATOR}" - -S${WORK_DIR}/minizip_pkg_config_test) - add_test(NAME minizip_pkg_config_build - COMMAND ${CMAKE_COMMAND} --build . --config $ - WORKING_DIRECTORY ${WORK_DIR}/minizip_pkg_config_test_build) - set_tests_properties(minizip_pkg_config_configure PROPERTIES - FIXTURES_REQUIRED ${inst_setup} - FIXTURES_SETUP mzpc_config) - set_tests_properties(minizip_pkg_config_build PROPERTIES - FIXTURES_REQUIRED mzpc_config) - endif(PKG_CONFIG_FOUND) -endif(NOT MSVC) - # # find_package_no_components_test # diff --git a/zlib/contrib/minizip/test/find_package_test.cmake.in b/zlib/contrib/minizip/test/find_package_test.cmake.in index fbf5fd28a..5da6afa1b 100644 --- a/zlib/contrib/minizip/test/find_package_test.cmake.in +++ b/zlib/contrib/minizip/test/find_package_test.cmake.in @@ -8,27 +8,11 @@ project( option(MINIZIP_BUILD_SHARED "" @MINIZIP_BUILD_SHARED@) option(MINIZIP_BUILD_STATIC "" @MINIZIP_BUILD_STATIC@) -# Simulate a consumer cache left by a package with the opposite feature setting. -if(@MINIZIP_ENABLE_BZIP2@) - set(minizip_HAS_BZIP2 OFF CACHE BOOL "" FORCE) -else() - set(minizip_HAS_BZIP2 ON CACHE BOOL "" FORCE) - set(CMAKE_DISABLE_FIND_PACKAGE_BZip2 TRUE) -endif() - set(MINIZIP_SRCS @minizip_SOURCE_DIR@/ioapi.c $<$:@minizip_SOURCE_DIR@/iowin32.c> @minizip_SOURCE_DIR@/minizip.c @minizip_SOURCE_DIR@/zip.c) -file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/installed_headers.c - "#include \n" - "#include \n" - "int main(void) {\n" - " unzFile file = unzOpen(\"missing.zip\");\n" - " return file ? unzClose(file) : 0;\n" - "}\n") - if(MINIZIP_BUILD_SHARED) find_package(minizip ${minizip_VERSION} CONFIG @@ -36,9 +20,6 @@ if(MINIZIP_BUILD_SHARED) REQUIRED) add_executable(test_example ${MINIZIP_SRCS}) target_link_libraries(test_example MINIZIP::minizip) - add_executable(test_installed_headers - ${CMAKE_CURRENT_BINARY_DIR}/installed_headers.c) - target_link_libraries(test_installed_headers MINIZIP::minizip) endif(MINIZIP_BUILD_SHARED) if(MINIZIP_BUILD_STATIC) @@ -48,7 +29,4 @@ if(MINIZIP_BUILD_STATIC) REQUIRED) add_executable(test_example_static ${MINIZIP_SRCS}) target_link_libraries(test_example_static MINIZIP::minizipstatic) - add_executable(test_installed_headers_static - ${CMAKE_CURRENT_BINARY_DIR}/installed_headers.c) - target_link_libraries(test_installed_headers_static MINIZIP::minizipstatic) endif(MINIZIP_BUILD_STATIC) diff --git a/zlib/contrib/minizip/test/pkg-config-test.cmake.in b/zlib/contrib/minizip/test/pkg-config-test.cmake.in deleted file mode 100644 index 0d23afa5d..000000000 --- a/zlib/contrib/minizip/test/pkg-config-test.cmake.in +++ /dev/null @@ -1,31 +0,0 @@ -cmake_minimum_required(VERSION 3.15...3.31) -project(minizip_pkg_config LANGUAGES C) - -set(prefix "@WORK_DIR@/test_install") -if(IS_ABSOLUTE "@CMAKE_INSTALL_LIBDIR@") - set(package "@CMAKE_INSTALL_LIBDIR@/pkgconfig/minizip.pc") -else() - set(package "${prefix}/@CMAKE_INSTALL_LIBDIR@/pkgconfig/minizip.pc") -endif() - -foreach(kind IN ITEMS cflags libs) - execute_process( - COMMAND "@PKG_CONFIG_EXECUTABLE@" --static --${kind} - "--define-variable=prefix=${prefix}" - "--define-variable=exec_prefix=${prefix}" "${package}" - RESULT_VARIABLE result OUTPUT_VARIABLE flags ERROR_VARIABLE error) - if(NOT result EQUAL 0) - message(FATAL_ERROR "pkg-config --${kind} failed: ${error}") - endif() - separate_arguments(pc_${kind} UNIX_COMMAND "${flags}") -endforeach() - -file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/consumer.c - "#include \n" - "int main(void) {\n" - " unzFile file = unzOpen(\"missing.zip\");\n" - " return file ? unzClose(file) : 0;\n" - "}\n") -add_executable(pkg_config_consumer ${CMAKE_CURRENT_BINARY_DIR}/consumer.c) -target_compile_options(pkg_config_consumer PRIVATE ${pc_cflags}) -target_link_libraries(pkg_config_consumer PRIVATE ${pc_libs}) From 264e632f1b7c1273c1443456771cad602456af3d Mon Sep 17 00:00:00 2001 From: bmehta001 Date: Sat, 5 Dec 2026 07:56:53 -0600 Subject: [PATCH 11/19] Fix CI --- lib/include/public/ICdsFactory.hpp | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/include/public/ICdsFactory.hpp b/lib/include/public/ICdsFactory.hpp index 312c3b210..f5906969e 100644 --- a/lib/include/public/ICdsFactory.hpp +++ b/lib/include/public/ICdsFactory.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include From 1f6916d16cf4a95b536c90c1630355664b07b054 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 08:00:04 -0600 Subject: [PATCH 12/19] Make CI child-role claims exclusive Use shell noclobber in tests/build-runner-tests.py so the mock processes cannot both take the same role when the external mkdir reports success twice. Resolve temporary paths before comparing the shell working directory. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 54c795bf-a207-409f-a052-7a84f6ac3854 --- tests/build-runner-tests.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/build-runner-tests.py b/tests/build-runner-tests.py index 8360c1142..43aadc28a 100644 --- a/tests/build-runner-tests.py +++ b/tests/build-runner-tests.py @@ -15,7 +15,7 @@ class BuildRunnerTests(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory() self.addCleanup(self.temporary.cleanup) - self.root = Path(self.temporary.name) + self.root = Path(self.temporary.name).resolve() self.calls = self.root / "calls.txt" shutil.copyfile(REPO_ROOT / "build-tests.sh", self.root / "build-tests.sh") self.write_script( @@ -33,7 +33,8 @@ def setUp(self): self.write_script( "out/tests/functests/FuncTests", 'printf "concurrent %s\\n" "$*" >> "$CALLS"\n' - 'if mkdir "$CASE_ROOT/first-child" 2>/dev/null; then\n' + # Use shell noclobber to claim one role without an external mkdir. + 'if (set -C; : > "$CASE_ROOT/first-child") 2>/dev/null; then\n' ' sleep 0.05\n' ' echo first-finished >> "$CALLS"\n' ' exit "${FIRST_RESULT:-0}"\n' @@ -65,7 +66,7 @@ def run_runner(self, *arguments, **variables): environment.update(variables) result = subprocess.run( ["sh", str(self.root / "build-tests.sh"), *arguments], - cwd=self.temporary.name, + cwd=self.root, env=environment, capture_output=True, text=True, From 3d186ec2b74d9004a0e9161a4c5d7d8195fad106 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 09:20:48 -0600 Subject: [PATCH 13/19] Call the precise system clock directly on Windows 10 The SDK now targets the Windows 10 API floor, so GetSystemTimePreciseAsFileTime is always available. The runtime kernel32 lookup and GetSystemTimeAsFileTime fallback only preserved Windows 7 compatibility, which no longer applies. Files changed: - lib/pal/PAL.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: cd197032-9b52-4cdc-9a3b-d23c8ec90596 --- lib/pal/PAL.cpp | 39 ++------------------------------------- 1 file changed, 2 insertions(+), 37 deletions(-) diff --git a/lib/pal/PAL.cpp b/lib/pal/PAL.cpp index e81827a13..22c2f6be5 100644 --- a/lib/pal/PAL.cpp +++ b/lib/pal/PAL.cpp @@ -51,7 +51,6 @@ #pragma comment(lib, "Ole32.Lib") /* CoCreateGuid */ #include #include -#include "utils/WindowsUtils.hpp" #endif #if defined(ANDROID) && defined(HAVE_MAT_LOGGING) @@ -62,40 +61,6 @@ namespace PAL_NS_BEGIN { -#if defined(_WIN32) || defined(_WIN64) - namespace - { - using GetSystemTimeAsFileTimeProc = VOID (WINAPI*)(LPFILETIME); - - GetSystemTimeAsFileTimeProc getPreciseSystemTimeAsFileTime() noexcept - { - static std::once_flag once; - static GetSystemTimeAsFileTimeProc proc = nullptr; - std::call_once(once, [] { - HMODULE kernel32 = ::GetModuleHandleW(L"kernel32.dll"); - if (kernel32 != nullptr) - { - proc = MAT::GetWindowsProcAddress( - kernel32, "GetSystemTimePreciseAsFileTime"); - } - }); - return proc; - } - - void getSystemTimeAsFileTime(FILETIME& fileTime) noexcept - { - if (auto preciseProc = getPreciseSystemTimeAsFileTime()) - { - preciseProc(&fileTime); - } - else - { - ::GetSystemTimeAsFileTime(&fileTime); - } - } - } -#endif - PlatformAbstractionLayer& GetPAL() noexcept { // Deliberately never destroyed. PAL::shutdown() (called from @@ -468,7 +433,7 @@ namespace PAL_NS_BEGIN { { #ifdef _WIN32 FILETIME fileTime; - getSystemTimeAsFileTime(fileTime); + ::GetSystemTimePreciseAsFileTime(&fileTime); ULARGE_INTEGER now; now.LowPart = fileTime.dwLowDateTime; now.HighPart = fileTime.dwHighDateTime; @@ -487,7 +452,7 @@ namespace PAL_NS_BEGIN { { #ifdef _WIN32 FILETIME tocks; - getSystemTimeAsFileTime(tocks); + ::GetSystemTimePreciseAsFileTime(&tocks); ULONGLONG ticks = (ULONGLONG(tocks.dwHighDateTime) << 32) | tocks.dwLowDateTime; // number of days from beginning to 1601 multiplied by ticks per day return ticks + 0x701ce1722770000ULL; From 3eda82da70699edbe222c68df67490161a712602 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 10:12:24 -0600 Subject: [PATCH 14/19] Address storage, Windows, Apple, and minizip review findings Keep a failed final storage flush retryable on zero, short batch, or per-record writes. Preserve the generation and owner until shutdown can complete, and surface failure across C and JNI without leaking C++ exceptions. Cover retry and invalid paths in the unit and functional tests. lib/offline/OfflineStorageHandler.{cpp,hpp}; lib/api/LogManagerImpl.{cpp,hpp}; lib/api/{LogManagerFactory.cpp,capi.cpp}; lib/include/public/LogManagerBase.hpp; lib/jni/LogManager_jni.cpp; tests/unittests/{LogManagerImplTests,OfflineStorageTests}.cpp; tests/functests/APITest.cpp. Keep trimming when committed deletes make progress without shrinking the SQLite file yet. Cover the packed-small-records case at the batch limit. lib/offline/OfflineStorage_SQLite.{cpp,hpp}; tests/unittests/OfflineStorageTests_SQLite.cpp. Apply /bigobj to OfflineStorageTests.cpp in the native Windows CI project without replacing inherited options. Apply the configured delegate name whenever the Apple HTTP source is selected, including HTTP-off mobile builds. Extend the configure matrix to guard this case. tests/unittests/UnitTests.vcxproj; lib/CMakeLists.txt; tests/apple/{embedding-options-tests.cmake,embedding-options/CMakeLists.txt}. Restore standalone minizip packaging to the PR base rather than maintain an SDK-unneeded change to absolute paths, static dependency order, include flags, and package-derived BZip2 state. Keep the vendor sources that Windows and the zlib clean target still use. zlib/contrib/minizip/{CMakeLists.txt,minizip.pc.txt,minizipConfig.cmake.in}; zlib/contrib/minizip/test/{CMakeLists.txt,find_package_test.cmake.in,pkg-config-test.cmake.in}. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2dc9129f-15f0-482c-a1ea-d48d05909daf --- lib/CMakeLists.txt | 2 +- lib/api/LogManagerFactory.cpp | 12 ++ lib/api/LogManagerImpl.cpp | 25 +++- lib/api/LogManagerImpl.hpp | 7 +- lib/api/capi.cpp | 20 +++- lib/include/public/LogManagerBase.hpp | 5 +- lib/jni/LogManager_jni.cpp | 30 ++++- lib/offline/OfflineStorageHandler.cpp | 47 ++++++-- lib/offline/OfflineStorageHandler.hpp | 7 +- lib/offline/OfflineStorage_SQLite.cpp | 21 +++- lib/offline/OfflineStorage_SQLite.hpp | 1 + tests/apple/embedding-options-tests.cmake | 19 +-- tests/apple/embedding-options/CMakeLists.txt | 8 +- tests/functests/APITest.cpp | 25 ++-- tests/unittests/LogManagerImplTests.cpp | 45 +++++++ tests/unittests/OfflineStorageTests.cpp | 35 ++++++ .../unittests/OfflineStorageTests_SQLite.cpp | 38 ++++++ tests/unittests/UnitTests.vcxproj | 4 +- zlib/contrib/minizip/CMakeLists.txt | 110 ++++++++++++++++-- zlib/contrib/minizip/minizip.pc.txt | 11 +- zlib/contrib/minizip/minizipConfig.cmake.in | 6 +- zlib/contrib/minizip/test/CMakeLists.txt | 29 +++++ .../minizip/test/find_package_test.cmake.in | 22 ++++ .../minizip/test/pkg-config-test.cmake.in | 31 +++++ 24 files changed, 496 insertions(+), 64 deletions(-) create mode 100644 zlib/contrib/minizip/test/pkg-config-test.cmake.in diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 43eb05d07..61a5ff272 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -376,7 +376,7 @@ else() message(STATUS "Building static SDK library") add_library(mat STATIC ${SRCS}) endif() -if(APPLE AND MATSDK_BUILD_APPLE_HTTP) +if(APPLE AND PAL_IMPLEMENTATION STREQUAL "CPP11" AND (MATSDK_BUILD_APPLE_HTTP OR MATSDK_PLATFORM_IOS)) # Objective-C class names are process-global, even with hidden symbol visibility. target_compile_definitions(mat PRIVATE "MATStreamingSessionDelegate=${MATSDK_APPLE_HTTP_DELEGATE_CLASS}") diff --git a/lib/api/LogManagerFactory.cpp b/lib/api/LogManagerFactory.cpp index f6e68a5c3..8da0779ee 100644 --- a/lib/api/LogManagerFactory.cpp +++ b/lib/api/LogManagerFactory.cpp @@ -177,6 +177,10 @@ namespace MAT_NS_BEGIN const std::string& host = kv.first; if (kv.second.names.count(name)) { + if (static_cast(kv.second.instance)->HasPendingStorageShutdown()) + { + return false; + } kv.second.names.erase(name); if (kv.second.names.empty()) { @@ -197,6 +201,10 @@ namespace MAT_NS_BEGIN if (exclusive.count(name)) { auto val = exclusive[name]; + if (static_cast(val.instance)->HasPendingStorageShutdown()) + { + return false; + } // destroy LM Destroy(val.instance); exclusive.erase(name); @@ -208,6 +216,10 @@ namespace MAT_NS_BEGIN if ((shared.find(host) != std::end(shared)) && (shared[host].names.count(name))) { + if (static_cast(shared[host].instance)->HasPendingStorageShutdown()) + { + return false; + } shared[host].names.erase(name); if (shared[host].names.empty()) { diff --git a/lib/api/LogManagerImpl.cpp b/lib/api/LogManagerImpl.cpp index dd943fd6c..9d223dfa5 100644 --- a/lib/api/LogManagerImpl.cpp +++ b/lib/api/LogManagerImpl.cpp @@ -449,7 +449,30 @@ namespace MAT_NS_BEGIN if (m_isSystemStarted && m_system) { - m_system->stop(); + MATSDK_TRY + { + if (m_storageShutdownPending) + { + // The telemetry system already drained and stopped its upload pipeline. + m_offlineStorage->Shutdown(); + } + else + { + m_system->stop(); + } + } +#if HAVE_EXCEPTIONS + MATSDK_CATCH(...) + { + m_storageShutdownPending = m_offlineStorage && m_offlineStorage->IsShutdownPending(); + throw; + } +#endif + m_storageShutdownPending = m_offlineStorage && m_offlineStorage->IsShutdownPending(); + if (m_storageShutdownPending) + { + return; + } LOG_TRACE("Telemetry system stopped"); } m_system = nullptr; diff --git a/lib/api/LogManagerImpl.hpp b/lib/api/LogManagerImpl.hpp index 75e062868..a4060ef70 100644 --- a/lib/api/LogManagerImpl.hpp +++ b/lib/api/LogManagerImpl.hpp @@ -32,6 +32,7 @@ #include "IDataInspector.hpp" #include "offline/LogSessionDataProvider.hpp" +#include #include #include #include @@ -131,6 +132,8 @@ namespace MAT_NS_BEGIN using LoggerMap = std::map>; + class OfflineStorageHandler; + class DeadLoggers { public: @@ -155,6 +158,7 @@ namespace MAT_NS_BEGIN virtual void Configure() final; virtual void FlushAndTeardown() final; + bool HasPendingStorageShutdown() const noexcept { return m_storageShutdownPending; } virtual status_t Flush() final; virtual status_t UploadNow() final; @@ -332,9 +336,10 @@ namespace MAT_NS_BEGIN AuthTokensController m_authTokensController; - std::unique_ptr m_offlineStorage; + std::unique_ptr m_offlineStorage; std::unique_ptr m_logSessionDataProvider; bool m_isSystemStarted{}; + std::atomic m_storageShutdownPending{false}; std::unique_ptr m_system; bool m_alive; diff --git a/lib/api/capi.cpp b/lib/api/capi.cpp index 92bef825e..dc8882fcd 100644 --- a/lib/api/capi.cpp +++ b/lib/api/capi.cpp @@ -8,6 +8,7 @@ #if !defined (ANDROID) || defined(ENABLE_CAPI_HTTP_CLIENT) #include "http/HttpClient_CAPI.hpp" #endif +#include "LogManagerImpl.hpp" #include "LogManagerProvider.hpp" #include "mat.h" #include "pal/TaskDispatcher_CAPI.hpp" @@ -316,6 +317,11 @@ static evt_status_t mat_close(evt_context_t *ctx) { VERIFY_CLIENT_HANDLE(client, ctx); const auto result = static_cast(LogManagerProvider::Release(client->logmanager->GetLogConfiguration())); + if (result != STATUS_SUCCESS) + { + ctx->result = result; + return result; + } if (client->http != nullptr) { @@ -359,9 +365,17 @@ static evt_status_t mat_upload(evt_context_t *ctx) static evt_status_t mat_flushAndTeardown(evt_context_t *ctx) { VERIFY_CLIENT_HANDLE(client, ctx); - client->logmanager->FlushAndTeardown(); - ctx->result = STATUS_SUCCESS; - return STATUS_SUCCESS; + auto manager = static_cast(client->logmanager); + MATSDK_TRY + { + manager->FlushAndTeardown(); + ctx->result = manager->HasPendingStorageShutdown() ? STATUS_EFAIL : STATUS_SUCCESS; + } + MATSDK_CATCH(...) + { + ctx->result = STATUS_EFAIL; + } + return ctx->result; } static evt_status_t mat_flush(evt_context_t *ctx) diff --git a/lib/include/public/LogManagerBase.hpp b/lib/include/public/LogManagerBase.hpp index b9ffdefca..c461a5db9 100644 --- a/lib/include/public/LogManagerBase.hpp +++ b/lib/include/public/LogManagerBase.hpp @@ -291,7 +291,10 @@ namespace MAT_NS_BEGIN } ILogConfiguration& currentConfig = GetLogConfiguration(); auto result = LogManagerProvider::Release(currentConfig); - instance = nullptr; + if (result == STATUS_SUCCESS) + { + instance = nullptr; + } return result; } // already gone diff --git a/lib/jni/LogManager_jni.cpp b/lib/jni/LogManager_jni.cpp index cab9d7535..b46f3aaa9 100644 --- a/lib/jni/LogManager_jni.cpp +++ b/lib/jni/LogManager_jni.cpp @@ -30,6 +30,7 @@ #include "JavaDataViewerProxy.hpp" #include "JniConvertors.hpp" #include "LogManagerBase.hpp" +#include "api/LogManagerImpl.hpp" #include "WrapperLogManager.hpp" #ifdef HAVE_MAT_LOGGING #include "android/log.h" @@ -71,7 +72,14 @@ extern "C" JNIEnv* /* env */, jclass /* LogManager.class */) { - return static_cast(WrapperLogManager::FlushAndTeardown()); + MATSDK_TRY + { + return static_cast(WrapperLogManager::FlushAndTeardown()); + } + MATSDK_CATCH(...) + { + return static_cast(STATUS_EFAIL); + } } JNIEXPORT jint JNICALL @@ -1167,7 +1175,25 @@ Java_com_microsoft_applications_events_LogManagerProvider_00024LogManagerImpl_na { return; } - logManager->FlushAndTeardown(); + bool stopped = false; + MATSDK_TRY + { + logManager->FlushAndTeardown(); + stopped = !static_cast(logManager)->HasPendingStorageShutdown(); + } + MATSDK_CATCH(...) + { + stopped = false; + } + if (!stopped) + { + if (auto errorClass = env->FindClass("java/lang/IllegalStateException")) + { + env->ThrowNew(errorClass, "Telemetry shutdown did not complete"); + env->DeleteLocalRef(errorClass); + } + return; + } // FlushAndTeardown is terminal: LogManagerImpl sets m_alive to false and GetLogger() returns // nullptr from then on, and nothing sets it back, so no further viewer callback can occur. diff --git a/lib/offline/OfflineStorageHandler.cpp b/lib/offline/OfflineStorageHandler.cpp index ec6f5de84..7c18fc593 100644 --- a/lib/offline/OfflineStorageHandler.cpp +++ b/lib/offline/OfflineStorageHandler.cpp @@ -342,7 +342,11 @@ namespace MAT_NS_BEGIN { void OfflineStorageHandler::Initialize(IOfflineStorageObserver& observer) { - Shutdown(); + if (!TryShutdown()) + { + ReportIncompleteShutdown(); + return; + } m_offlineStorageMemory.reset(); m_offlineStorageDisk.reset(); m_flushState = std::make_shared(this); @@ -369,11 +373,34 @@ namespace MAT_NS_BEGIN { } void OfflineStorageHandler::Shutdown() + { + if (!TryShutdown()) + { + ReportIncompleteShutdown(); + } + } + + void OfflineStorageHandler::ReportIncompleteShutdown() + { + LOG_ERROR("Offline storage shutdown deferred: could not persist all queued records"); +#if HAVE_EXCEPTIONS + throw std::runtime_error("Could not persist all queued records during offline storage shutdown"); +#endif + } + + bool OfflineStorageHandler::IsShutdownPending() const + { + auto state = m_flushState; + std::lock_guard lock(state->mutex); + return state->phase == FlushState::Phase::Retryable; + } + + bool OfflineStorageHandler::TryShutdown() { LOG_TRACE("Shutting down offline storage handler"); if (!BeginTeardown()) { - return; + return true; } auto state = m_flushState; TeardownGuard teardown(state); @@ -383,9 +410,10 @@ namespace MAT_NS_BEGIN { if (nullptr != m_offlineStorageMemory) { m_offlineStorageMemory->ReleaseAllRecords(); + ActivityGuard activity(m_logManager, true); + if (!FlushImpl()) { - ActivityGuard activity(m_logManager, true); - FlushImpl(); + return false; } } state->shutdownStage = FlushState::ShutdownStage::MemoryShutdown; @@ -407,6 +435,7 @@ namespace MAT_NS_BEGIN { state->shutdownStage = FlushState::ShutdownStage::Complete; } teardown.Complete(); + return true; } /// @@ -462,12 +491,13 @@ namespace MAT_NS_BEGIN { FlushImpl(); } - void OfflineStorageHandler::FlushImpl() + bool OfflineStorageHandler::FlushImpl() { std::vector recordsToRecover; std::vector memoryOnlyRecords; size_t savedRecords = 0; bool notifySaved = false; + bool complete = true; MATSDK_TRY { // Flush could be executed from context of worker thread, as well as from TPM and @@ -530,6 +560,7 @@ namespace MAT_NS_BEGIN { totalSaved += std::min(batchSaved, recordsToRecover.size()); if (batchSaved != recordsToRecover.size()) { + complete = false; LOG_WARN("Flush: disk store failed for the batch of %zu records; returning it to the queue for retry", recordsToRecover.size()); ReturnRecordsToMemory(recordsToRecover); @@ -547,7 +578,7 @@ namespace MAT_NS_BEGIN { // Preserve the legacy per-record path and its unlimited drain. recordsToRecover = m_offlineStorageMemory->GetRecords( false, EventLatency_Unspecified); - totalSaved = StoreRecordsIndividually(recordsToRecover); + totalSaved = StoreRecordsIndividually(recordsToRecover, complete); } // Persistence and retry handling are complete; a later exception @@ -610,6 +641,7 @@ namespace MAT_NS_BEGIN { { OnStorageRecordsSaved(savedRecords); } + return complete; } void OfflineStorageHandler::QueueScheduledFlush() @@ -729,7 +761,7 @@ namespace MAT_NS_BEGIN { OnStorageFailed("Invalid parameters"); } - size_t OfflineStorageHandler::StoreRecordsIndividually(std::vector& records) + size_t OfflineStorageHandler::StoreRecordsIndividually(std::vector& records, bool& complete) { size_t totalSaved = 0; std::vector recordsToRetry; @@ -759,6 +791,7 @@ namespace MAT_NS_BEGIN { continue; } + complete = false; for (size_t retryIndex = nextRecord; retryIndex < records.size(); ++retryIndex) { auto const& retryRecord = records[retryIndex]; diff --git a/lib/offline/OfflineStorageHandler.hpp b/lib/offline/OfflineStorageHandler.hpp index 3c69640be..c016c0093 100644 --- a/lib/offline/OfflineStorageHandler.hpp +++ b/lib/offline/OfflineStorageHandler.hpp @@ -34,6 +34,7 @@ namespace MAT_NS_BEGIN { virtual ~OfflineStorageHandler() override; virtual void Initialize(IOfflineStorageObserver& observer) override; virtual void Shutdown() override; + bool IsShutdownPending() const; virtual void Flush() override; virtual bool StoreRecord(StorageRecord const& record) override; virtual size_t StoreRecords(std::vector & records) override; @@ -107,11 +108,13 @@ namespace MAT_NS_BEGIN { private: bool BeginTeardown(); + bool TryShutdown(); + void ReportIncompleteShutdown(); void QueueScheduledFlush(); - void FlushImpl(); + bool FlushImpl(); bool IsBatchedStorageFlushEnabled(); void ReportInvalidDiskRecord(StorageRecord const& record); - size_t StoreRecordsIndividually(std::vector& records); + size_t StoreRecordsIndividually(std::vector& records, bool& complete); size_t ReturnRecordsToMemory(std::vector const& records); }; diff --git a/lib/offline/OfflineStorage_SQLite.cpp b/lib/offline/OfflineStorage_SQLite.cpp index a921a3e0e..c6e3e02f9 100644 --- a/lib/offline/OfflineStorage_SQLite.cpp +++ b/lib/offline/OfflineStorage_SQLite.cpp @@ -256,10 +256,10 @@ namespace MAT_NS_BEGIN { LOCKGUARD(m_resizeLock); //Serialize resize operations m_resizing = true; // A batch can exceed the limit by more than one 25% trim. + bool madeProgress = false; while (m_DbSizeEstimate > m_DbSizeLimit) { - const size_t previousSize = GetSize(); - if (!ResizeDb() || m_DbSizeEstimate >= previousSize) + if (!ResizeDb(madeProgress) || !madeProgress) { break; } @@ -1168,6 +1168,12 @@ namespace MAT_NS_BEGIN { } bool OfflineStorage_SQLite::ResizeDb() + { + bool madeProgress = false; + return ResizeDb(madeProgress); + } + + bool OfflineStorage_SQLite::ResizeDb(bool& madeProgress) { LOCKGUARD(m_lock); if (!m_db) { @@ -1177,8 +1183,9 @@ namespace MAT_NS_BEGIN { size_t eventsDropped = 0; bool compactDatabase = false; - m_DbSizeEstimate = GetSize(); - if (m_DbSizeEstimate <= m_DbSizeLimit) + const size_t previousSize = GetSize(); + m_DbSizeEstimate = previousSize; + if (previousSize <= m_DbSizeLimit) return false; { @@ -1191,7 +1198,7 @@ namespace MAT_NS_BEGIN { } #endif auto count = GetRecordCountUnsafe(EventLatency::EventLatency_Unspecified); - if (m_DbSizeEstimate > 2 * m_DbSizeLimit) + if (previousSize > 2 * m_DbSizeLimit) { LOG_TRACE("DB is too big, deleting..."); if (!SqliteStatement(*m_db, "DELETE FROM " TABLE_NAME_EVENTS).execute()) @@ -1241,7 +1248,9 @@ namespace MAT_NS_BEGIN { return false; } - m_DbSizeEstimate = GetSize(); + const size_t newSize = GetSize(); + m_DbSizeEstimate = newSize; + madeProgress = eventsDropped != 0 || (newSize != 0 && newSize < previousSize); DebugEvent evt(DebugEventType::EVT_DROPPED); evt.param1 = eventsDropped; evt.param2 = static_cast(DROPPED_REASON_OFFLINE_STORAGE_OVERFLOW); diff --git a/lib/offline/OfflineStorage_SQLite.hpp b/lib/offline/OfflineStorage_SQLite.hpp index 2053a0246..aa3d4ffaa 100644 --- a/lib/offline/OfflineStorage_SQLite.hpp +++ b/lib/offline/OfflineStorage_SQLite.hpp @@ -122,6 +122,7 @@ namespace MAT_NS_BEGIN { MATSDK_LOG_DECL_COMPONENT_CLASS(); private: + bool ResizeDb(bool& madeProgress); size_t GetRecordCountUnsafe(EventLatency latency) const; // Validate a record's required fields; reports OnStorageFailed on rejection. diff --git a/tests/apple/embedding-options-tests.cmake b/tests/apple/embedding-options-tests.cmake index 01a203e49..51d7365a5 100644 --- a/tests/apple/embedding-options-tests.cmake +++ b/tests/apple/embedding-options-tests.cmake @@ -11,14 +11,14 @@ if(TEST_GENERATOR_PLATFORM) list(APPEND generator_args -A "${TEST_GENERATOR_PLATFORM}") endif() -function(check_options apple vcpkg provided http class) +function(check_options apple vcpkg provided http mobile class) # Keep MSBuild's nested compiler-probe paths below its legacy path limit. - string(SHA1 name "${apple}-${vcpkg}-${provided}-${http}-${class}") + string(SHA1 name "${apple}-${vcpkg}-${provided}-${http}-${mobile}-${class}") string(SUBSTRING "${name}" 0 6 name) execute_process(COMMAND "${CMAKE_COMMAND}" ${generator_args} -S "${CMAKE_CURRENT_LIST_DIR}/embedding-options" -B "${OUTPUT_DIR}/${name}" "-DSDK_ROOT=${sdk_root}" "-DTEST_APPLE=${apple}" "-DTEST_VCPKG=${vcpkg}" - "-DTEST_PROVIDED=${provided}" "-DTEST_HTTP=${http}" + "-DTEST_PROVIDED=${provided}" "-DTEST_HTTP=${http}" "-DTEST_MOBILE=${mobile}" "-DMATSDK_APPLE_HTTP_DELEGATE_CLASS=${class}" RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) if(class STREQUAL "invalid-class") @@ -26,18 +26,19 @@ function(check_options apple vcpkg provided http class) message(FATAL_ERROR "Invalid delegate name was not rejected:\n${output}\n${error}") endif() elseif(NOT result EQUAL 0) - message(FATAL_ERROR "${apple}/${vcpkg}/${provided}/${http}/${class} failed:\n${output}\n${error}") + message(FATAL_ERROR "${apple}/${vcpkg}/${provided}/${http}/${mobile}/${class} failed:\n${output}\n${error}") endif() endfunction() foreach(apple ON OFF) foreach(vcpkg ON OFF) foreach(provided ON OFF) - check_options("${apple}" "${vcpkg}" "${provided}" ON MATStreamingSessionDelegate) - check_options("${apple}" "${vcpkg}" "${provided}" ON ProductMATStreamingSessionDelegate) + check_options("${apple}" "${vcpkg}" "${provided}" ON OFF MATStreamingSessionDelegate) + check_options("${apple}" "${vcpkg}" "${provided}" ON OFF ProductMATStreamingSessionDelegate) endforeach() endforeach() endforeach() -check_options(ON ON OFF OFF ProductMATStreamingSessionDelegate) -check_options(ON ON OFF ON invalid-class) -message(STATUS "18 Apple dependency/delegate configurations passed") +check_options(ON ON OFF OFF OFF ProductMATStreamingSessionDelegate) +check_options(ON ON OFF OFF ON ProductMATStreamingSessionDelegate) +check_options(ON ON OFF ON OFF invalid-class) +message(STATUS "19 Apple dependency/delegate configurations passed") diff --git a/tests/apple/embedding-options/CMakeLists.txt b/tests/apple/embedding-options/CMakeLists.txt index 0188837f4..b7491361a 100644 --- a/tests/apple/embedding-options/CMakeLists.txt +++ b/tests/apple/embedding-options/CMakeLists.txt @@ -13,6 +13,8 @@ set(MATSDK_BUILD_TEST_TOOL OFF CACHE BOOL "" FORCE) set(MATSDK_BUILD_UNIT_TESTS OFF CACHE BOOL "" FORCE) set(MATSDK_BUILD_FUNC_TESTS OFF CACHE BOOL "" FORCE) set(MATSDK_BUILD_PACKAGE OFF CACHE BOOL "" FORCE) +set(DEFAULT_PAL_IMPLEMENTATION CPP11) +set(BUILD_IOS "${TEST_MOBILE}" CACHE BOOL "" FORCE) set(MATSDK_BUILD_APPLE_HTTP "${TEST_HTTP}" CACHE BOOL "" FORCE) set(MATSDK_SQLITE_PROVIDER SYSTEM CACHE STRING "" FORCE) set(MATSDK_ZLIB_PROVIDER SYSTEM CACHE STRING "" FORCE) @@ -43,7 +45,7 @@ endforeach() # Evaluate the production target guard without requiring an Apple compiler or SDK. file(READ "${SDK_ROOT}/lib/CMakeLists.txt" library) -string(FIND "${library}" "if(APPLE AND MATSDK_BUILD_APPLE_HTTP)" start) +string(FIND "${library}" "if(APPLE AND PAL_IMPLEMENTATION STREQUAL \"CPP11\" AND (MATSDK_BUILD_APPLE_HTTP OR MATSDK_PLATFORM_IOS))" start) if(start EQUAL -1) message(FATAL_ERROR "Update Apple delegate target instrumentation") endif() @@ -54,11 +56,13 @@ string(SUBSTRING "${definition}" 0 ${end} definition) file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/delegate.cpp" "") add_library(mat STATIC "${CMAKE_CURRENT_BINARY_DIR}/delegate.cpp") file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/delegate.cmake" "${definition}") +set(PAL_IMPLEMENTATION "${DEFAULT_PAL_IMPLEMENTATION}") +set(MATSDK_PLATFORM_IOS "${TEST_MOBILE}") include("${CMAKE_CURRENT_BINARY_DIR}/delegate.cmake") get_target_property(private mat COMPILE_DEFINITIONS) get_target_property(public mat INTERFACE_COMPILE_DEFINITIONS) set(expected "MATStreamingSessionDelegate=${MATSDK_APPLE_HTTP_DELEGATE_CLASS}") -if(TEST_APPLE AND TEST_HTTP) +if(TEST_APPLE AND (TEST_HTTP OR TEST_MOBILE)) if(NOT expected IN_LIST private) message(FATAL_ERROR "Missing private Apple delegate definition: ${private}") endif() diff --git a/tests/functests/APITest.cpp b/tests/functests/APITest.cpp index 1500ec30e..6128fae1d 100644 --- a/tests/functests/APITest.cpp +++ b/tests/functests/APITest.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -1254,18 +1255,17 @@ TEST(APITest, LogManager_BadStoragePath_Test) auto& config = LogManager::GetLogConfiguration(); config[CFG_INT_TRACE_LEVEL_MASK] = 0xFFFFFFFF; // API calls + Global mask for general messages - less SQL config[CFG_INT_TRACE_LEVEL_MIN] = ACTTraceLevel_Trace; - config[CFG_INT_MAX_TEARDOWN_TIME] = 16; + config[CFG_INT_MAX_TEARDOWN_TIME] = 0; + const std::string missingDirectory = GetTempDirectory() + "invalid-storage-" + PAL::generateUuidString(); std::vector paths = { #ifdef _WIN32 - "T:\\invalid\\file\\path", // This fails - no offline storage - u8"C:\\неправильный\\каталог\\utf-8", // This fails - no offline storage - u8"C:\\Проверка-проверка 1 2 3\\файл.db" // This should pass if dir exists + missingDirectory + "\\file.db", + missingDirectory + u8"\\каталог\\файл.db" #else - "/invalid/file/path", - u8"/неправильный/каталог/utf-8", // This fails - no offline storage - u8"/Проверка-проверка 1 2 3/файл.db" // This should pass if dir exists + missingDirectory + "/file.db", + missingDirectory + u8"/каталог/файл.db" #endif }; @@ -1274,13 +1274,20 @@ TEST(APITest, LogManager_BadStoragePath_Test) debugListener.storageFailed = false; config[CFG_STR_CACHE_FILE_PATH] = path.c_str(); ILogger *result = LogManager::Initialize(TEST_TOKEN, config); + ASSERT_NE(result, nullptr); LogManager::AddEventListener(DebugEventType::EVT_STORAGE_FAILED, debugListener); - EXPECT_EQ(true, (result != NULL)); + LogManager::PauseTransmission(); result->LogEvent("test"); LogManager::Flush(); - LogManager::FlushAndTeardown(); +#if HAVE_EXCEPTIONS + EXPECT_THROW(LogManager::FlushAndTeardown(), std::runtime_error); +#else + EXPECT_EQ(LogManager::FlushAndTeardown(), STATUS_EFAIL); +#endif LogManager::RemoveEventListener(DebugEventType::EVT_STORAGE_FAILED, debugListener); EXPECT_EQ(true, debugListener.storageFailed); + EXPECT_EQ(LogManager::DeleteData(), STATUS_SUCCESS); + ASSERT_EQ(LogManager::FlushAndTeardown(), STATUS_SUCCESS); } } diff --git a/tests/unittests/LogManagerImplTests.cpp b/tests/unittests/LogManagerImplTests.cpp index 289bcc5a1..856983448 100644 --- a/tests/unittests/LogManagerImplTests.cpp +++ b/tests/unittests/LogManagerImplTests.cpp @@ -4,6 +4,8 @@ // #include "api/LogManagerImpl.hpp" #include "common/Common.hpp" +#include "common/MockIOfflineStorage.hpp" +#include "LogManagerProvider.hpp" #include using namespace testing; @@ -82,6 +84,49 @@ TEST(LogManagerImplTests, DeadLoggersAreDead) logger->LogEvent("DeadLoggerEvent"); } +#ifdef HAVE_MAT_STORAGE +TEST(LogManagerImplTests, FailedPerRecordShutdownCanBeRetriedBeforeRelease) +{ + ILogConfiguration configuration; + configuration[CFG_STR_FACTORY_NAME] = "storage-shutdown-retry"; + configuration[CFG_INT_MAX_TEARDOWN_TIME] = 0; + configuration[CFG_INT_RAM_QUEUE_SIZE] = 1024 * 1024; + configuration.AddModule(CFG_MODULE_HTTP_CLIENT, std::make_shared()); + auto disk = std::make_shared>(); + configuration.AddModule(CFG_MODULE_OFFLINE_STORAGE, disk); + + status_t status; + auto manager = LogManagerProvider::CreateLogManager(configuration, status); + ASSERT_EQ(status, STATUS_SUCCESS); + ASSERT_NE(manager, nullptr); + ASSERT_EQ(manager->PauseTransmission(), STATUS_SUCCESS); + auto logger = manager->GetLogger("test-tenant"); + ASSERT_NE(logger, nullptr); + logger->LogEvent("StorageShutdownRetry"); + + std::string failedRecord; + EXPECT_CALL(*disk, StoreRecord(_)).WillOnce(Invoke([&](StorageRecord const& record) { + failedRecord = record.id; + return false; + })); + EXPECT_CALL(*disk, Shutdown()).Times(0); +#if HAVE_EXCEPTIONS + EXPECT_THROW(manager->FlushAndTeardown(), std::runtime_error); +#else + manager->FlushAndTeardown(); +#endif + ASSERT_EQ(LogManagerProvider::Release(configuration), STATUS_EFAIL); + ASSERT_FALSE(failedRecord.empty()); + ASSERT_TRUE(Mock::VerifyAndClearExpectations(disk.get())); + + EXPECT_CALL(*disk, StoreRecord(Field(&StorageRecord::id, failedRecord))) + .WillOnce(Return(true)); + EXPECT_CALL(*disk, Shutdown()); + manager->FlushAndTeardown(); + EXPECT_EQ(LogManagerProvider::Release(configuration), STATUS_SUCCESS); +} +#endif + TEST(LogManagerImplTests, NotPausedInitially) { ILogConfiguration configuration; diff --git a/tests/unittests/OfflineStorageTests.cpp b/tests/unittests/OfflineStorageTests.cpp index 50012ee50..38b1d27c2 100644 --- a/tests/unittests/OfflineStorageTests.cpp +++ b/tests/unittests/OfflineStorageTests.cpp @@ -952,6 +952,36 @@ TEST_F(OfflineStorageLifecycleTests, PartialBatchMutationRetainsRecordsForRetry) handler->Shutdown(); } +TEST_F(OfflineStorageLifecycleTests, ShortShutdownWritesRetainStorageUntilReinitializeCanFlush) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Return(0)) + .WillOnce(Return(1)); + EXPECT_CALL(observer, OnStorageRecordsSaved(0)); + EXPECT_CALL(observer, OnStorageRecordsSaved(1)); + +#if HAVE_EXCEPTIONS + EXPECT_THROW(handler->Shutdown(), std::runtime_error); +#else + handler->Shutdown(); +#endif + EXPECT_EQ(memory->GetRecordCount(), 2u); +#if HAVE_EXCEPTIONS + EXPECT_THROW(handler->Initialize(observer), std::runtime_error); +#else + handler->Initialize(observer); +#endif + EXPECT_EQ(memory->GetRecordCount(), 2u); + + ExpectSaved(2); + EXPECT_CALL(*disk, Shutdown()).Times(2); + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + EXPECT_EQ(memory->GetRecordCount(), 0u); + handler->Shutdown(); +} + TEST_F(OfflineStorageLifecycleTests, SavedObserverCanWaitForAnotherFlush) { ASSERT_TRUE(StoreTwo()); @@ -1632,7 +1662,12 @@ TEST(OfflineStorageHandlerFlushTests, FailedDiskStoreDuringFlushReturnsRecordsTo // returned to the in-memory queue rather than silently dropped. EXPECT_EQ(handler.GetRecordCount(), kCount); +#if HAVE_EXCEPTIONS + EXPECT_THROW(handler.Shutdown(), std::runtime_error); +#else handler.Shutdown(); +#endif + EXPECT_EQ(handler.GetRecordCount(), kCount); } TEST(OfflineStorageHandlerFlushTests, EventLatencyOffIsDroppedWithoutReportingStoreFailure) diff --git a/tests/unittests/OfflineStorageTests_SQLite.cpp b/tests/unittests/OfflineStorageTests_SQLite.cpp index 33a28080f..38cf8082d 100644 --- a/tests/unittests/OfflineStorageTests_SQLite.cpp +++ b/tests/unittests/OfflineStorageTests_SQLite.cpp @@ -1160,6 +1160,44 @@ TEST_F(OfflineStorageTests_SQLite, BatchStorageLimitRequiresMultipleTrims) EXPECT_GT(offlineStorage->GetRecordCount(EventLatency_Unspecified), size_t { 0 }); } +TEST_F(OfflineStorageTests_SQLite, BatchStorageLimitKeepsTrimmingWhenOnlyRecordCountDrops) +{ + sqlite3* db = nullptr; + ASSERT_EQ(sqlite3_open(storageFilename.c_str(), &db), SQLITE_OK); + const int result = sqlite3_exec(db, "PRAGMA page_size=65536; PRAGMA auto_vacuum=FULL; VACUUM;", nullptr, nullptr, nullptr); + const int closeResult = sqlite3_close(db); + ASSERT_EQ(result, SQLITE_OK); + ASSERT_EQ(closeResult, SQLITE_OK); + + constexpr size_t maximumSize = 512 * 1024; + EXPECT_CALL(configMock, GetOfflineStorageMaximumSizeBytes()).WillRepeatedly(Return(maximumSize)); + configMock[CFG_BOOL_ENABLE_DB_DROP_IF_FULL] = false; + initializeStorage(false); + + std::vector records; + for (int i = 0; i < 40; ++i) + { + records.emplace_back("small-" + std::to_string(i), "token", EventLatency_Normal, + EventPersistence_Normal, i + 1, StorageBlob(1)); + } + records.emplace_back("large", "token", EventLatency_Normal, + EventPersistence_Normal, 41, StorageBlob(4 * 65536)); + ASSERT_EQ(offlineStorage->StoreRecords(records), records.size()); + + const size_t oversized = offlineStorage->GetSize(); + ASSERT_GT(oversized, maximumSize); + ASSERT_LE(oversized, 2 * maximumSize); + ASSERT_TRUE(offlineStorage->ResizeDb()); + ASSERT_LT(offlineStorage->GetRecordCount(EventLatency_Unspecified), records.size()); + ASSERT_EQ(offlineStorage->GetSize(), oversized); + + configMock[CFG_BOOL_ENABLE_DB_DROP_IF_FULL] = true; + std::vector next{{"next", "token", EventLatency_Normal, + EventPersistence_Normal, 42, StorageBlob(1)}}; + ASSERT_EQ(offlineStorage->StoreRecords(next), 1u); + EXPECT_LE(offlineStorage->GetSize(), maximumSize); +} + TEST_F(OfflineStorageTests_SQLite, StorageLimitIncludesLargePageOverhead) { sqlite3* db = nullptr; diff --git a/tests/unittests/UnitTests.vcxproj b/tests/unittests/UnitTests.vcxproj index ce61469ff..298c18d9a 100644 --- a/tests/unittests/UnitTests.vcxproj +++ b/tests/unittests/UnitTests.vcxproj @@ -464,7 +464,9 @@ - + + /bigobj %(AdditionalOptions) + diff --git a/zlib/contrib/minizip/CMakeLists.txt b/zlib/contrib/minizip/CMakeLists.txt index 795328bbb..02deda8d4 100644 --- a/zlib/contrib/minizip/CMakeLists.txt +++ b/zlib/contrib/minizip/CMakeLists.txt @@ -39,6 +39,7 @@ include(CheckSymbolExists) include(CheckIncludeFile) include(CMakePackageConfigHelpers) include(CheckTypeSize) +include(CMakePushCheckState) include(GNUInstallDirs) if(NOT CPACK_INCLUDED) @@ -64,7 +65,8 @@ endif(MINIZIP_ENABLE_BZIP2) # # Check for fopen64 # -set(CMAKE_REQUIRED_DEFINITIONS -D_LARGEFILE64_SOURCE=1) +cmake_push_check_state() +list(APPEND CMAKE_REQUIRED_DEFINITIONS -D_LARGEFILE64_SOURCE=1) check_symbol_exists(fopen64 stdio.h HAVE_FOPEN64) # @@ -81,7 +83,7 @@ check_include_file(unistd.h HAVE_UNISTD_H) # Check to see if we have large file support # check_type_size(off64_t OFF64_T) -unset(CMAKE_REQUIRED_DEFINITIONS) # clear variable +cmake_pop_check_state() # # Check visibility attribute is supported @@ -144,9 +146,6 @@ set(MINIUNZIP_HDRS unzip.h zip.h) -set(LIBMINIZIP_PC ${minizip_BINARY_DIR}/minizip.pc) -configure_file(${minizip_SOURCE_DIR}/minizip.pc.txt ${LIBMINIZIP_PC} @ONLY) - if(WIN32 OR CYGWIN) set(minizip_static_suffix "s") set(CMAKE_DEBUG_POSTFIX "d") @@ -161,6 +160,7 @@ if(MINIZIP_BUILD_SHARED) target_include_directories(${ZLIB_CONTRIB_PREFIX}libminizip PUBLIC $ + $ $) target_compile_definitions(${ZLIB_CONTRIB_PREFIX}libminizip PRIVATE @@ -240,6 +240,7 @@ if(MINIZIP_BUILD_STATIC) target_include_directories(${ZLIB_CONTRIB_PREFIX}libminizipstatic PUBLIC $ + $ $) target_compile_definitions(${ZLIB_CONTRIB_PREFIX}libminizipstatic PRIVATE @@ -309,6 +310,95 @@ if(MINIZIP_BUILD_STATIC) PRIVATE MINIZIP::minizipstatic) endif(MINIZIP_BUILD_STATIC) +if(MINIZIP_BUILD_SHARED OR MINIZIP_BUILD_STATIC) + if(MINIZIP_BUILD_SHARED) + set(MINIZIP_PC_TARGET MINIZIP::minizip) + set(MINIZIP_PC_ZLIB_TARGET ZLIB::ZLIB) + else() + set(MINIZIP_PC_TARGET MINIZIP::minizipstatic) + set(MINIZIP_PC_ZLIB_TARGET ZLIB::ZLIBSTATIC) + endif() + function(minizip_pc_library_name target output) + get_target_property(_minizip_imported ${target} IMPORTED) + if(NOT _minizip_imported) + set(${output} "$" PARENT_SCOPE) + return() + endif() + # Imported targets do not expose their filename through the base-name expression. + set(_minizip_library "") + set(_minizip_configs NOCONFIG ${CMAKE_CONFIGURATION_TYPES} ${CMAKE_BUILD_TYPE}) + list(REMOVE_DUPLICATES _minizip_configs) + get_target_property(_minizip_imported_configs + ${target} IMPORTED_CONFIGURATIONS) + foreach(_minizip_config IN LISTS _minizip_configs) + string(TOUPPER "${_minizip_config}" _minizip_upper) + get_target_property(_minizip_file ${target} + LOCATION_${_minizip_upper}) + get_target_property(_minizip_mapped ${target} + MAP_IMPORTED_CONFIG_${_minizip_upper}) + if(NOT _minizip_mapped) + set(_minizip_mapped "") + endif() + foreach(_minizip_import IN ITEMS ${_minizip_mapped} + ${_minizip_upper} NOCONFIG ${_minizip_imported_configs}) + string(TOUPPER "${_minizip_import}" _minizip_import) + get_target_property(_minizip_implib ${target} + IMPORTED_IMPLIB_${_minizip_import}) + if(_minizip_implib) + set(_minizip_file "${_minizip_implib}") + break() + endif() + endforeach() + if(NOT _minizip_implib) + get_target_property(_minizip_implib ${target} IMPORTED_IMPLIB) + if(_minizip_implib) + set(_minizip_file "${_minizip_implib}") + endif() + endif() + get_filename_component(_minizip_name "${_minizip_file}" NAME_WE) + if(CMAKE_STATIC_LIBRARY_PREFIX) + string(REGEX REPLACE "^${CMAKE_STATIC_LIBRARY_PREFIX}" "" + _minizip_name "${_minizip_name}") + endif() + if(_minizip_config STREQUAL "NOCONFIG") + set(_minizip_config "") + endif() + string(APPEND _minizip_library + "$<$:${_minizip_name}>") + endforeach() + set(${output} "${_minizip_library}" PARENT_SCOPE) + endfunction() + minizip_pc_library_name(${MINIZIP_PC_TARGET} MINIZIP_PC_LIBRARY) + minizip_pc_library_name(${MINIZIP_PC_ZLIB_TARGET} MINIZIP_PC_ZLIB_LIBRARY) + set(MINIZIP_PC_LIBS_PRIVATE "") + set(MINIZIP_PC_CFLAGS "") + get_target_property(_minizip_zlib_imported ${MINIZIP_PC_ZLIB_TARGET} IMPORTED) + if(_minizip_zlib_imported) + string(APPEND MINIZIP_PC_LIBS_PRIVATE + "-L\"$\" ") + set(MINIZIP_PC_CFLAGS + "-I\"$,\" -I\">\"") + endif() + string(APPEND MINIZIP_PC_LIBS_PRIVATE "-l${MINIZIP_PC_ZLIB_LIBRARY}") + if(MINIZIP_ENABLE_BZIP2) + minizip_pc_library_name(BZip2::BZip2 MINIZIP_PC_BZIP2_LIBRARY) + string(APPEND MINIZIP_PC_LIBS_PRIVATE + " -L\"$\" -l${MINIZIP_PC_BZIP2_LIBRARY}") + endif(MINIZIP_ENABLE_BZIP2) + foreach(dir IN ITEMS LIBDIR INCLUDEDIR) + if(IS_ABSOLUTE "${CMAKE_INSTALL_${dir}}") + set(MINIZIP_PC_${dir} "${CMAKE_INSTALL_${dir}}") + else() + set(MINIZIP_PC_${dir} "\${exec_prefix}/${CMAKE_INSTALL_${dir}}") + endif() + endforeach() + set(LIBMINIZIP_PC ${minizip_BINARY_DIR}/$/minizip.pc) + configure_file(${minizip_SOURCE_DIR}/minizip.pc.txt + ${minizip_BINARY_DIR}/minizip.pc.in @ONLY) + file(GENERATE OUTPUT ${LIBMINIZIP_PC} + INPUT ${minizip_BINARY_DIR}/minizip.pc.in) +endif() + if(MINIZIP_INSTALL) if(MINIZIP_BUILD_SHARED) install( @@ -372,10 +462,12 @@ if(MINIZIP_INSTALL) install(FILES ${minizip_BINARY_DIR}/minizipConfig.cmake ${minizip_BINARY_DIR}/minizipConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/minizip) - install( - FILES ${LIBMINIZIP_PC} - COMPONENT Development - DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") + if(MINIZIP_BUILD_SHARED OR MINIZIP_BUILD_STATIC) + install( + FILES ${LIBMINIZIP_PC} + COMPONENT Development + DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") + endif() endif(MINIZIP_INSTALL) if(MINIZIP_BUILD_TESTING) diff --git a/zlib/contrib/minizip/minizip.pc.txt b/zlib/contrib/minizip/minizip.pc.txt index 060ab091c..d075af1dc 100644 --- a/zlib/contrib/minizip/minizip.pc.txt +++ b/zlib/contrib/minizip/minizip.pc.txt @@ -1,13 +1,14 @@ prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=@CMAKE_INSTALL_PREFIX@ -libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@ -sharedlibdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${exec_prefix}/@CMAKE_INSTALL_INCLUDEDIR@ +libdir=@MINIZIP_PC_LIBDIR@ +sharedlibdir=@MINIZIP_PC_LIBDIR@ +includedir=@MINIZIP_PC_INCLUDEDIR@ Name: minizip Description: minizip compression library Version: @minizip_VERSION@ Requires: -Libs: -L${libdir} -L${sharedlibdir} -lz -lminizip -Cflags: -I${includedir} +Libs: -L${libdir} -L${sharedlibdir} -l@MINIZIP_PC_LIBRARY@ +Libs.private: @MINIZIP_PC_LIBS_PRIVATE@ +Cflags: -I${includedir} -I${includedir}/minizip @MINIZIP_PC_CFLAGS@ diff --git a/zlib/contrib/minizip/minizipConfig.cmake.in b/zlib/contrib/minizip/minizipConfig.cmake.in index 71bed1d67..474f2da30 100644 --- a/zlib/contrib/minizip/minizipConfig.cmake.in +++ b/zlib/contrib/minizip/minizipConfig.cmake.in @@ -1,11 +1,7 @@ set(_MINIZIP_supported_components "shared" "static") include(CMakeFindDependencyMacro) -set(minizip_HAS_BZIP2 - "@MINIZIP_ENABLE_BZIP2@" - CACHE - BOOL - "Indicates if minizip was compiled with bzip2 support") +set(minizip_HAS_BZIP2 "@MINIZIP_ENABLE_BZIP2@") if(minizip_HAS_BZIP2) find_dependency(BZip2) diff --git a/zlib/contrib/minizip/test/CMakeLists.txt b/zlib/contrib/minizip/test/CMakeLists.txt index 4801dfe05..578c4bd17 100644 --- a/zlib/contrib/minizip/test/CMakeLists.txt +++ b/zlib/contrib/minizip/test/CMakeLists.txt @@ -106,6 +106,35 @@ set_tests_properties(minizip_find_package_build PROPERTIES FIXTURES_REQUIRED mzfp_config) +if(NOT MSVC) + find_package(PkgConfig QUIET) + if(PKG_CONFIG_FOUND) + configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/pkg-config-test.cmake.in + ${WORK_DIR}/minizip_pkg_config_test/CMakeLists.txt @ONLY) + add_test(NAME minizip_pkg_config_configure + COMMAND ${CMAKE_COMMAND} ${PLATFORM} + -B${WORK_DIR}/minizip_pkg_config_test_build + -DCMAKE_BUILD_TYPE=$ + -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} + -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS} + "-DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES}" + "-DCMAKE_OSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET}" + -DCMAKE_INSTALL_PREFIX=${WORK_DIR}/test_install + $<$:--fresh> + -G "${CMAKE_GENERATOR}" + -S${WORK_DIR}/minizip_pkg_config_test) + add_test(NAME minizip_pkg_config_build + COMMAND ${CMAKE_COMMAND} --build . --config $ + WORKING_DIRECTORY ${WORK_DIR}/minizip_pkg_config_test_build) + set_tests_properties(minizip_pkg_config_configure PROPERTIES + FIXTURES_REQUIRED ${inst_setup} + FIXTURES_SETUP mzpc_config) + set_tests_properties(minizip_pkg_config_build PROPERTIES + FIXTURES_REQUIRED mzpc_config) + endif(PKG_CONFIG_FOUND) +endif(NOT MSVC) + # # find_package_no_components_test # diff --git a/zlib/contrib/minizip/test/find_package_test.cmake.in b/zlib/contrib/minizip/test/find_package_test.cmake.in index 5da6afa1b..fbf5fd28a 100644 --- a/zlib/contrib/minizip/test/find_package_test.cmake.in +++ b/zlib/contrib/minizip/test/find_package_test.cmake.in @@ -8,11 +8,27 @@ project( option(MINIZIP_BUILD_SHARED "" @MINIZIP_BUILD_SHARED@) option(MINIZIP_BUILD_STATIC "" @MINIZIP_BUILD_STATIC@) +# Simulate a consumer cache left by a package with the opposite feature setting. +if(@MINIZIP_ENABLE_BZIP2@) + set(minizip_HAS_BZIP2 OFF CACHE BOOL "" FORCE) +else() + set(minizip_HAS_BZIP2 ON CACHE BOOL "" FORCE) + set(CMAKE_DISABLE_FIND_PACKAGE_BZip2 TRUE) +endif() + set(MINIZIP_SRCS @minizip_SOURCE_DIR@/ioapi.c $<$:@minizip_SOURCE_DIR@/iowin32.c> @minizip_SOURCE_DIR@/minizip.c @minizip_SOURCE_DIR@/zip.c) +file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/installed_headers.c + "#include \n" + "#include \n" + "int main(void) {\n" + " unzFile file = unzOpen(\"missing.zip\");\n" + " return file ? unzClose(file) : 0;\n" + "}\n") + if(MINIZIP_BUILD_SHARED) find_package(minizip ${minizip_VERSION} CONFIG @@ -20,6 +36,9 @@ if(MINIZIP_BUILD_SHARED) REQUIRED) add_executable(test_example ${MINIZIP_SRCS}) target_link_libraries(test_example MINIZIP::minizip) + add_executable(test_installed_headers + ${CMAKE_CURRENT_BINARY_DIR}/installed_headers.c) + target_link_libraries(test_installed_headers MINIZIP::minizip) endif(MINIZIP_BUILD_SHARED) if(MINIZIP_BUILD_STATIC) @@ -29,4 +48,7 @@ if(MINIZIP_BUILD_STATIC) REQUIRED) add_executable(test_example_static ${MINIZIP_SRCS}) target_link_libraries(test_example_static MINIZIP::minizipstatic) + add_executable(test_installed_headers_static + ${CMAKE_CURRENT_BINARY_DIR}/installed_headers.c) + target_link_libraries(test_installed_headers_static MINIZIP::minizipstatic) endif(MINIZIP_BUILD_STATIC) diff --git a/zlib/contrib/minizip/test/pkg-config-test.cmake.in b/zlib/contrib/minizip/test/pkg-config-test.cmake.in new file mode 100644 index 000000000..0d23afa5d --- /dev/null +++ b/zlib/contrib/minizip/test/pkg-config-test.cmake.in @@ -0,0 +1,31 @@ +cmake_minimum_required(VERSION 3.15...3.31) +project(minizip_pkg_config LANGUAGES C) + +set(prefix "@WORK_DIR@/test_install") +if(IS_ABSOLUTE "@CMAKE_INSTALL_LIBDIR@") + set(package "@CMAKE_INSTALL_LIBDIR@/pkgconfig/minizip.pc") +else() + set(package "${prefix}/@CMAKE_INSTALL_LIBDIR@/pkgconfig/minizip.pc") +endif() + +foreach(kind IN ITEMS cflags libs) + execute_process( + COMMAND "@PKG_CONFIG_EXECUTABLE@" --static --${kind} + "--define-variable=prefix=${prefix}" + "--define-variable=exec_prefix=${prefix}" "${package}" + RESULT_VARIABLE result OUTPUT_VARIABLE flags ERROR_VARIABLE error) + if(NOT result EQUAL 0) + message(FATAL_ERROR "pkg-config --${kind} failed: ${error}") + endif() + separate_arguments(pc_${kind} UNIX_COMMAND "${flags}") +endforeach() + +file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/consumer.c + "#include \n" + "int main(void) {\n" + " unzFile file = unzOpen(\"missing.zip\");\n" + " return file ? unzClose(file) : 0;\n" + "}\n") +add_executable(pkg_config_consumer ${CMAKE_CURRENT_BINARY_DIR}/consumer.c) +target_compile_options(pkg_config_consumer PRIVATE ${pc_cflags}) +target_link_libraries(pkg_config_consumer PRIVATE ${pc_libs}) From 0a4cc2e7610a7930c4d3b6f9f79e50bd81d43d8b Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 10:47:53 -0600 Subject: [PATCH 15/19] Preserve the final LogManager lease until teardown succeeds A last owner can release without explicitly flushing. Complete teardown before removing either the lease or the registered manager. Keep the manager retryable when a provider refuses a write and report failure if pipeline shutdown throws before storage is reached. Reserve teardown before callbacks and avoid holding the factory lock while they run. Reject reentrant final release or acquisition of the reserved manager. A nonfinal shared release still only drops its lease. Use the shutdown result at C and JNI boundaries and roll back an open that cannot acquire a manager. Verify exclusive, host-specific shared, and name-only shared release, including retry of the exact failed record. Files: lib/api/LogManagerFactory.{cpp,hpp} lib/api/LogManagerImpl.{cpp,hpp} lib/api/capi.cpp lib/include/public/LogManagerBase.hpp lib/jni/LogManager_jni.cpp tests/unittests/LogManagerImplTests.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2dc9129f-15f0-482c-a1ea-d48d05909daf --- lib/api/LogManagerFactory.cpp | 158 ++++++++++++++---------- lib/api/LogManagerFactory.hpp | 11 ++ lib/api/LogManagerImpl.cpp | 40 +++++- lib/api/LogManagerImpl.hpp | 14 ++- lib/api/capi.cpp | 8 +- lib/include/public/LogManagerBase.hpp | 4 + lib/jni/LogManager_jni.cpp | 3 +- tests/unittests/LogManagerImplTests.cpp | 73 ++++++++++- 8 files changed, 236 insertions(+), 75 deletions(-) diff --git a/lib/api/LogManagerFactory.cpp b/lib/api/LogManagerFactory.cpp index 8da0779ee..793b795a3 100644 --- a/lib/api/LogManagerFactory.cpp +++ b/lib/api/LogManagerFactory.cpp @@ -20,9 +20,7 @@ namespace MAT_NS_BEGIN { - // This mutex has to be recursive because we allow both - // Destroy and destrutor to lock it. destructor could be - // called directly, and Destroy calls destructor. + // Leasing may create and register a new manager under the same lock. std::recursive_mutex ILogManagerInternal::managers_lock; std::set ILogManagerInternal::managers; @@ -46,20 +44,50 @@ namespace MAT_NS_BEGIN /// status_t LogManagerFactory::Destroy(ILogManager* instance) { - if (instance == nullptr) + RegistryLock lock(ILogManagerInternal::managers_lock); + return tryDestroy(instance, lock, nullptr, {}) ? STATUS_SUCCESS : STATUS_EFAIL; + } + + bool LogManagerFactory::tryDestroy(ILogManager* instance, RegistryLock& lock, + Registry* registry, std::string key) + { + if (!ILogManagerInternal::managers.count(instance)) { - return STATUS_EFAIL; + return false; } - LOCKGUARD(ILogManagerInternal::managers_lock); - auto it = ILogManagerInternal::managers.find(instance); - if (it != std::end(ILogManagerInternal::managers)) + auto manager = static_cast(instance); + if (!manager->BeginTeardown()) + { + return false; + } + + // Keep the lease reserved, but allow callbacks to enter the factory. + lock.unlock(); + bool complete = false; + MATSDK_TRY { - ILogManagerInternal::managers.erase(it); - delete instance; - return STATUS_SUCCESS; + complete = manager->CompleteTeardown(); } - return STATUS_EFAIL; + MATSDK_CATCH(...) + { + complete = false; + } + lock.lock(); + if (!complete) + { + manager->m_teardownInProgress = false; + return false; + } + + if (registry) + { + registry->erase(key); + } + ILogManagerInternal::managers.erase(instance); + lock.unlock(); + delete instance; + return true; } // Move guests from ROOT to the new host home @@ -115,17 +143,26 @@ namespace MAT_NS_BEGIN std::string name; std::string host; parseConfig(c, name, host); + RegistryLock lock(ILogManagerInternal::managers_lock); + const auto canLease = [](const Pool& pool) { + return !static_cast(pool.instance)->m_teardownInProgress; + }; // Exclusive mode if (host.empty()) { // Exclusive hosts are being kept in their own sandbox: high chairs near the bar. - if (!exclusive.count(name)) + auto pool = exclusive.find(name); + if (pool == exclusive.end()) { - exclusive[name] = {{name}, Create(c)}; + pool = exclusive.emplace(name, Pool{{name}, Create(c)}).first; + } + else if (!canLease(pool->second)) + { + return nullptr; } c[CFG_BOOL_HOST_MODE] = true; - return exclusive[name].instance; + return pool->second.instance; } // Shared mode @@ -133,9 +170,14 @@ namespace MAT_NS_BEGIN { // There are some items already. This guest doesn't care // where to go, so it goes to the first host's pool. - shared[shared.begin()->first].names.insert(name); + auto& pool = shared.begin()->second; + if (!canLease(pool)) + { + return nullptr; + } + pool.names.insert(name); c[CFG_BOOL_HOST_MODE] = false; - return shared[shared.begin()->first].instance; + return pool.instance; } if (!shared.count(host)) @@ -145,6 +187,10 @@ namespace MAT_NS_BEGIN // irrespective of whether it's a host or guest if (shared.count(ANYHOST)) { + if (!canLease(shared.find(ANYHOST)->second)) + { + return nullptr; + } rehome(name, host); } else @@ -152,9 +198,12 @@ namespace MAT_NS_BEGIN shared[host] = {{name}, Create(c)}; } } - else if (!shared[host].names.count(name)) + else { - // Host already exists, so simply add the new item to it + if (!canLease(shared[host])) + { + return nullptr; + } shared[host].names.insert(name); } @@ -172,23 +221,17 @@ namespace MAT_NS_BEGIN bool LogManagerFactory::release(const std::string& name) { - for (auto& kv : shared) + RegistryLock lock(ILogManagerInternal::managers_lock); + return releaseShared(name, lock); + } + + bool LogManagerFactory::releaseShared(const std::string& name, RegistryLock& lock) + { + for (auto pool = shared.begin(); pool != shared.end(); ++pool) { - const std::string& host = kv.first; - if (kv.second.names.count(name)) + if (pool->second.names.count(name)) { - if (static_cast(kv.second.instance)->HasPendingStorageShutdown()) - { - return false; - } - kv.second.names.erase(name); - if (kv.second.names.empty()) - { - // Last owner is gone, destroy - Destroy(shared[host].instance); - shared.erase(host); - } - return true; + return releaseFrom(shared, pool, name, lock); } } return false; @@ -196,43 +239,30 @@ namespace MAT_NS_BEGIN bool LogManagerFactory::release(const std::string& name, const std::string& host) { + RegistryLock lock(ILogManagerInternal::managers_lock); if (host.empty()) { - if (exclusive.count(name)) - { - auto val = exclusive[name]; - if (static_cast(val.instance)->HasPendingStorageShutdown()) - { - return false; - } - // destroy LM - Destroy(val.instance); - exclusive.erase(name); - return true; - } - return false; + auto pool = exclusive.find(name); + return pool != exclusive.end() && releaseFrom(exclusive, pool, name, lock); } - if ((shared.find(host) != std::end(shared)) && - (shared[host].names.count(name))) + auto pool = shared.find(host); + if (pool != shared.end() && pool->second.names.count(name)) { - if (static_cast(shared[host].instance)->HasPendingStorageShutdown()) - { - return false; - } - shared[host].names.erase(name); - if (shared[host].names.empty()) - { - // Last owner is gone, destroy LM - Destroy(shared[host].instance); - shared.erase(host); - } - return true; + return releaseFrom(shared, pool, name, lock); } - // repeat the same action as above, but this time - // searching for rehomed guests in all hosts - return release(name); + return releaseShared(name, lock); + } + + bool LogManagerFactory::releaseFrom(Registry& registry, Registry::iterator pool, + const std::string& name, RegistryLock& lock) + { + if (pool->second.names.size() == 1) + { + return tryDestroy(pool->second.instance, lock, ®istry, pool->first); + } + return pool->second.names.erase(name) != 0; } void LogManagerFactory::dump() diff --git a/lib/api/LogManagerFactory.hpp b/lib/api/LogManagerFactory.hpp index 63adfb646..b8690ee96 100644 --- a/lib/api/LogManagerFactory.hpp +++ b/lib/api/LogManagerFactory.hpp @@ -12,6 +12,7 @@ #include "NullObjects.hpp" #include +#include #include #include #include @@ -43,6 +44,16 @@ namespace MAT_NS_BEGIN { /// Registry exclusive; + using RegistryLock = std::unique_lock; + + static bool tryDestroy(ILogManager* instance, RegistryLock& lock, + Registry* registry, std::string key); + + bool releaseFrom(Registry& registry, Registry::iterator pool, + const std::string& name, RegistryLock& lock); + + bool releaseShared(const std::string& name, RegistryLock& lock); + protected: LogManagerFactory(); diff --git a/lib/api/LogManagerImpl.cpp b/lib/api/LogManagerImpl.cpp index 9d223dfa5..b3e3931af 100644 --- a/lib/api/LogManagerImpl.cpp +++ b/lib/api/LogManagerImpl.cpp @@ -381,7 +381,7 @@ namespace MAT_NS_BEGIN { MATSDK_TRY { - FlushAndTeardown(); + FlushAndTeardownWithStatus(); } #if HAVE_EXCEPTIONS MATSDK_CATCH(const std::exception& e) @@ -412,6 +412,30 @@ namespace MAT_NS_BEGIN } void LogManagerImpl::FlushAndTeardown() + { + if (!FlushAndTeardownWithStatus()) + { +#if HAVE_EXCEPTIONS + throw std::runtime_error("Log manager teardown did not complete"); +#endif + } + } + + bool LogManagerImpl::FlushAndTeardownWithStatus() + { + if (!BeginTeardown()) + { + return false; + } + struct ResetOnExit + { + std::atomic& pending; + ~ResetOnExit() { pending = false; } + } reset{m_teardownInProgress}; + return CompleteTeardown(); + } + + bool LogManagerImpl::CompleteTeardown() { PauseActivity(); WaitPause(); @@ -449,6 +473,12 @@ namespace MAT_NS_BEGIN if (m_isSystemStarted && m_system) { +#if HAVE_EXCEPTIONS + if (m_systemStopFailure) + { + std::rethrow_exception(m_systemStopFailure); + } +#endif MATSDK_TRY { if (m_storageShutdownPending) @@ -465,13 +495,18 @@ namespace MAT_NS_BEGIN MATSDK_CATCH(...) { m_storageShutdownPending = m_offlineStorage && m_offlineStorage->IsShutdownPending(); + if (!m_storageShutdownPending) + { + // The system's one-shot stop failed before storage became retryable. + m_systemStopFailure = std::current_exception(); + } throw; } #endif m_storageShutdownPending = m_offlineStorage && m_offlineStorage->IsShutdownPending(); if (m_storageShutdownPending) { - return; + return false; } LOG_TRACE("Telemetry system stopped"); } @@ -494,6 +529,7 @@ namespace MAT_NS_BEGIN LOG_INFO("Shutdown complete in %lld ms", shutTime); } m_alive = false; + return true; } status_t LogManagerImpl::Flush() diff --git a/lib/api/LogManagerImpl.hpp b/lib/api/LogManagerImpl.hpp index a4060ef70..403568744 100644 --- a/lib/api/LogManagerImpl.hpp +++ b/lib/api/LogManagerImpl.hpp @@ -34,6 +34,7 @@ #include #include +#include #include #include @@ -158,7 +159,7 @@ namespace MAT_NS_BEGIN virtual void Configure() final; virtual void FlushAndTeardown() final; - bool HasPendingStorageShutdown() const noexcept { return m_storageShutdownPending; } + bool FlushAndTeardownWithStatus(); virtual status_t Flush() final; virtual status_t UploadNow() final; @@ -339,7 +340,10 @@ namespace MAT_NS_BEGIN std::unique_ptr m_offlineStorage; std::unique_ptr m_logSessionDataProvider; bool m_isSystemStarted{}; - std::atomic m_storageShutdownPending{false}; + bool m_storageShutdownPending{}; +#if HAVE_EXCEPTIONS + std::exception_ptr m_systemStopFailure; +#endif std::unique_ptr m_system; bool m_alive; @@ -363,6 +367,12 @@ namespace MAT_NS_BEGIN Paused }; PauseState m_pause_state = PauseState::Active; + + private: + friend class LogManagerFactory; + bool BeginTeardown() noexcept { return !m_teardownInProgress.exchange(true); } + bool CompleteTeardown(); + std::atomic m_teardownInProgress{false}; }; } diff --git a/lib/api/capi.cpp b/lib/api/capi.cpp index dc8882fcd..6ea064680 100644 --- a/lib/api/capi.cpp +++ b/lib/api/capi.cpp @@ -196,7 +196,10 @@ static evt_status_t mat_open_core( // Verify that the instance pointer is valid if (clients[code].logmanager == nullptr) { - status = static_cast(EFAULT); + remove_client(code); + ctx->result = static_cast(EFAULT); + ctx->handle = 0; + return EFAULT; } ctx->result = static_cast(status); ctx->handle = code; @@ -368,8 +371,7 @@ static evt_status_t mat_flushAndTeardown(evt_context_t *ctx) auto manager = static_cast(client->logmanager); MATSDK_TRY { - manager->FlushAndTeardown(); - ctx->result = manager->HasPendingStorageShutdown() ? STATUS_EFAIL : STATUS_SUCCESS; + ctx->result = manager->FlushAndTeardownWithStatus() ? STATUS_SUCCESS : STATUS_EFAIL; } MATSDK_CATCH(...) { diff --git a/lib/include/public/LogManagerBase.hpp b/lib/include/public/LogManagerBase.hpp index c461a5db9..6fbdbf198 100644 --- a/lib/include/public/LogManagerBase.hpp +++ b/lib/include/public/LogManagerBase.hpp @@ -252,6 +252,10 @@ namespace MAT_NS_BEGIN status_t status = STATUS_SUCCESS; instance = LogManagerProvider::CreateLogManager(currentConfig, status); + if (!instance) + { + return nullptr; + } instance->AttachEventSource(GetDebugEventSource()); return instance->GetLogger(currentConfig[CFG_STR_PRIMARY_TOKEN]); } diff --git a/lib/jni/LogManager_jni.cpp b/lib/jni/LogManager_jni.cpp index b46f3aaa9..245ec0e5f 100644 --- a/lib/jni/LogManager_jni.cpp +++ b/lib/jni/LogManager_jni.cpp @@ -1178,8 +1178,7 @@ Java_com_microsoft_applications_events_LogManagerProvider_00024LogManagerImpl_na bool stopped = false; MATSDK_TRY { - logManager->FlushAndTeardown(); - stopped = !static_cast(logManager)->HasPendingStorageShutdown(); + stopped = static_cast(logManager)->FlushAndTeardownWithStatus(); } MATSDK_CATCH(...) { diff --git a/tests/unittests/LogManagerImplTests.cpp b/tests/unittests/LogManagerImplTests.cpp index 856983448..9adc472e3 100644 --- a/tests/unittests/LogManagerImplTests.cpp +++ b/tests/unittests/LogManagerImplTests.cpp @@ -7,6 +7,7 @@ #include "common/MockIOfflineStorage.hpp" #include "LogManagerProvider.hpp" #include +#include using namespace testing; using namespace MAT; @@ -115,16 +116,84 @@ TEST(LogManagerImplTests, FailedPerRecordShutdownCanBeRetriedBeforeRelease) #else manager->FlushAndTeardown(); #endif - ASSERT_EQ(LogManagerProvider::Release(configuration), STATUS_EFAIL); ASSERT_FALSE(failedRecord.empty()); ASSERT_TRUE(Mock::VerifyAndClearExpectations(disk.get())); EXPECT_CALL(*disk, StoreRecord(Field(&StorageRecord::id, failedRecord))) .WillOnce(Return(true)); EXPECT_CALL(*disk, Shutdown()); - manager->FlushAndTeardown(); EXPECT_EQ(LogManagerProvider::Release(configuration), STATUS_SUCCESS); } + +enum class ReleaseRoute { Exclusive, SharedByConfig, SharedByName }; + +class LogManagerFinalReleaseTests : public TestWithParam +{ +}; + +TEST_P(LogManagerFinalReleaseTests, FailedFinalFlushPreservesLeaseAndRetriesTheRecord) +{ + const auto route = GetParam(); + const bool shared = route != ReleaseRoute::Exclusive; + const std::string name = "final-release-" + std::to_string(static_cast(route)); + ILogConfiguration configuration; + configuration[CFG_STR_FACTORY_NAME] = name.c_str(); + if (shared) + { + configuration[CFG_MAP_FACTORY_CONFIG][CFG_STR_FACTORY_HOST] = name.c_str(); + } + configuration[CFG_INT_MAX_TEARDOWN_TIME] = 0; + configuration[CFG_INT_RAM_QUEUE_SIZE] = 1024 * 1024; + configuration.AddModule(CFG_MODULE_HTTP_CLIENT, std::make_shared()); + auto disk = std::make_shared>(); + configuration.AddModule(CFG_MODULE_OFFLINE_STORAGE, disk); + + status_t status; + auto manager = LogManagerProvider::CreateLogManager(configuration, status); + ASSERT_EQ(status, STATUS_SUCCESS); + ASSERT_NE(manager, nullptr); + ASSERT_EQ(manager->PauseTransmission(), STATUS_SUCCESS); + auto logger = manager->GetLogger("test-tenant"); + ASSERT_NE(logger, nullptr); + logger->LogEvent("FinalReleaseRetry"); + + ILogConfiguration guest; + guest[CFG_STR_FACTORY_NAME] = "final-release-guest"; + guest[CFG_MAP_FACTORY_CONFIG][CFG_STR_FACTORY_HOST] = name.c_str(); + EXPECT_CALL(*disk, Shutdown()).Times(0); + if (shared) + { + EXPECT_CALL(*disk, StoreRecord(_)).Times(0); + ASSERT_EQ(LogManagerProvider::CreateLogManager(guest, status), manager); + ASSERT_EQ(LogManagerProvider::Release(guest), STATUS_SUCCESS); + ASSERT_TRUE(Mock::VerifyAndClearExpectations(disk.get())); + EXPECT_CALL(*disk, Shutdown()).Times(0); + } + + const auto release = [&] { + return route == ReleaseRoute::SharedByName ? LogManagerProvider::Release(name.c_str()) + : LogManagerProvider::Release(configuration); + }; + std::string failedRecord; + EXPECT_CALL(*disk, StoreRecord(_)).WillOnce(Invoke([&](const StorageRecord& record) { + failedRecord = record.id; + EXPECT_EQ(release(), STATUS_EFAIL); + EXPECT_EQ(LogManagerProvider::CreateLogManager(shared ? guest : configuration, status), nullptr); + EXPECT_EQ(status, STATUS_EFAIL); + return false; + })); + ASSERT_EQ(release(), STATUS_EFAIL); + ASSERT_FALSE(failedRecord.empty()); + ASSERT_TRUE(Mock::VerifyAndClearExpectations(disk.get())); + + EXPECT_CALL(*disk, StoreRecord(Field(&StorageRecord::id, failedRecord))).WillOnce(Return(true)); + EXPECT_CALL(*disk, Shutdown()); + EXPECT_EQ(release(), STATUS_SUCCESS); + EXPECT_EQ(release(), STATUS_EFAIL); +} + +INSTANTIATE_TEST_SUITE_P(FactoryRoutes, LogManagerFinalReleaseTests, + Values(ReleaseRoute::Exclusive, ReleaseRoute::SharedByConfig, ReleaseRoute::SharedByName)); #endif TEST(LogManagerImplTests, NotPausedInitially) From 66f68c6ce0b3d50418c500bce40bae9a509100ac Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 11:16:44 -0600 Subject: [PATCH 16/19] Keep retiring managers closed to new leases and close the right C handle A failed teardown has already retired loggers. Keep the manager in a retiring state that admits an explicit retry but never accepts another lease. Test acquisition rejection both during and after failure. Release a C handle with its own lease configuration, not the shared manager's creator configuration. Retain the creator's configuration for the manager lifetime so closing the creator first leaves its guests working. Reserve handles before acquiring, roll back a failed open, and reject distinct configs that would reuse a lease in the same pool. Test both close orders, wildcard rehoming, and survivor event intake. Files: lib/api/LogManagerFactory.{cpp,hpp} lib/api/LogManagerImpl.{cpp,hpp} lib/api/capi.cpp tests/functests/APITest.cpp tests/unittests/LogManagerImplTests.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2dc9129f-15f0-482c-a1ea-d48d05909daf --- lib/api/LogManagerFactory.cpp | 25 ++- lib/api/LogManagerFactory.hpp | 9 +- lib/api/LogManagerImpl.cpp | 6 +- lib/api/LogManagerImpl.hpp | 8 +- lib/api/capi.cpp | 194 +++++++++++------------- tests/functests/APITest.cpp | 65 ++++++++ tests/unittests/LogManagerImplTests.cpp | 2 + 7 files changed, 189 insertions(+), 120 deletions(-) diff --git a/lib/api/LogManagerFactory.cpp b/lib/api/LogManagerFactory.cpp index 793b795a3..8b394296a 100644 --- a/lib/api/LogManagerFactory.cpp +++ b/lib/api/LogManagerFactory.cpp @@ -29,10 +29,12 @@ namespace MAT_NS_BEGIN /// /// The configuration. /// ILogManager instance - ILogManager* LogManagerFactory::Create(ILogConfiguration& configuration) + ILogManager* LogManagerFactory::Create(ILogConfiguration& configuration, + const std::shared_ptr& owner) { LOCKGUARD(ILogManagerInternal::managers_lock); auto logManager = std::make_unique(configuration); + logManager->m_logConfigurationOwner = owner; ILogManagerInternal::managers.emplace(logManager.get()); return logManager.release(); } @@ -76,7 +78,7 @@ namespace MAT_NS_BEGIN lock.lock(); if (!complete) { - manager->m_teardownInProgress = false; + manager->EndTeardown(); return false; } @@ -138,14 +140,23 @@ namespace MAT_NS_BEGIN } } - ILogManager* LogManagerFactory::lease(ILogConfiguration& c) + ILogManager* LogManagerFactory::GetOwned(const std::shared_ptr& configuration, status_t& status) + { + auto manager = instance().lease(*configuration, configuration); + status = manager ? STATUS_SUCCESS : STATUS_EFAIL; + return manager; + } + + ILogManager* LogManagerFactory::lease(ILogConfiguration& c, const std::shared_ptr& owner) { std::string name; std::string host; parseConfig(c, name, host); RegistryLock lock(ILogManagerInternal::managers_lock); - const auto canLease = [](const Pool& pool) { - return !static_cast(pool.instance)->m_teardownInProgress; + const auto canLease = [&](const Pool& pool) { + // Each distinct C API handle must have its own lease. + return static_cast(pool.instance)->CanAcquireLease() && + (!owner || !pool.names.count(name)); }; // Exclusive mode @@ -155,7 +166,7 @@ namespace MAT_NS_BEGIN auto pool = exclusive.find(name); if (pool == exclusive.end()) { - pool = exclusive.emplace(name, Pool{{name}, Create(c)}).first; + pool = exclusive.emplace(name, Pool{{name}, Create(c, owner)}).first; } else if (!canLease(pool->second)) { @@ -195,7 +206,7 @@ namespace MAT_NS_BEGIN } else { - shared[host] = {{name}, Create(c)}; + shared[host] = {{name}, Create(c, owner)}; } } else diff --git a/lib/api/LogManagerFactory.hpp b/lib/api/LogManagerFactory.hpp index b8690ee96..b4346fdba 100644 --- a/lib/api/LogManagerFactory.hpp +++ b/lib/api/LogManagerFactory.hpp @@ -12,6 +12,7 @@ #include "NullObjects.hpp" #include +#include #include #include #include @@ -62,7 +63,8 @@ namespace MAT_NS_BEGIN { const ILogManager* find(const std::string& name); - ILogManager* lease(ILogConfiguration& configuration); + ILogManager* lease(ILogConfiguration& configuration, + const std::shared_ptr& owner = {}); bool release(const std::string& name, const std::string& host); @@ -99,7 +101,8 @@ namespace MAT_NS_BEGIN { /// /// Configuration settings to apply to the telemetry logging system. /// An ILogManager telemetry logging system instance created with the specified configuration and HTTP Client. - static ILogManager* Create(ILogConfiguration& configuration); + static ILogManager* Create(ILogConfiguration& configuration, + const std::shared_ptr& owner = {}); /// /// Destroys a ILogManager instance @@ -136,6 +139,8 @@ namespace MAT_NS_BEGIN { return result; } + static ILogManager* GetOwned(const std::shared_ptr& configuration, status_t& status); + static status_t Release(const char* module) { return (instance().release(module)) ? diff --git a/lib/api/LogManagerImpl.cpp b/lib/api/LogManagerImpl.cpp index b3e3931af..43fb53662 100644 --- a/lib/api/LogManagerImpl.cpp +++ b/lib/api/LogManagerImpl.cpp @@ -429,9 +429,9 @@ namespace MAT_NS_BEGIN } struct ResetOnExit { - std::atomic& pending; - ~ResetOnExit() { pending = false; } - } reset{m_teardownInProgress}; + LogManagerImpl& manager; + ~ResetOnExit() { manager.EndTeardown(); } + } reset{*this}; return CompleteTeardown(); } diff --git a/lib/api/LogManagerImpl.hpp b/lib/api/LogManagerImpl.hpp index 403568744..48a9c27ac 100644 --- a/lib/api/LogManagerImpl.hpp +++ b/lib/api/LogManagerImpl.hpp @@ -321,6 +321,7 @@ namespace MAT_NS_BEGIN MATSDK_LOG_DECL_COMPONENT_CLASS(); static DeadLoggers s_deadLoggers; + std::shared_ptr m_logConfigurationOwner; std::recursive_mutex m_lock; LoggerMap m_loggers; ContextFieldsProvider m_context; @@ -370,9 +371,12 @@ namespace MAT_NS_BEGIN private: friend class LogManagerFactory; - bool BeginTeardown() noexcept { return !m_teardownInProgress.exchange(true); } + enum class TeardownState { Open, InProgress, Retiring }; + bool BeginTeardown() noexcept { return m_teardownState.exchange(TeardownState::InProgress) != TeardownState::InProgress; } + void EndTeardown() noexcept { m_teardownState = TeardownState::Retiring; } + bool CanAcquireLease() const noexcept { return m_teardownState == TeardownState::Open; } bool CompleteTeardown(); - std::atomic m_teardownInProgress{false}; + std::atomic m_teardownState{TeardownState::Open}; }; } diff --git a/lib/api/capi.cpp b/lib/api/capi.cpp index 6ea064680..4f3dde3a9 100644 --- a/lib/api/capi.cpp +++ b/lib/api/capi.cpp @@ -8,6 +8,7 @@ #if !defined (ANDROID) || defined(ENABLE_CAPI_HTTP_CLIENT) #include "http/HttpClient_CAPI.hpp" #endif +#include "LogManagerFactory.hpp" #include "LogManagerImpl.hpp" #include "LogManagerProvider.hpp" #include "mat.h" @@ -27,7 +28,14 @@ static const char * libSemver = TELEMETRY_EVENTS_VERSION; using namespace MAT; static std::mutex mtx; -static std::map clients; +static std::map> clients; + +static std::shared_ptr find_open_client(evt_handle_t handle) +{ + LOCKGUARD(mtx); + const auto it = clients.find(handle); + return (it != clients.end() && it->second->logmanager) ? it->second : nullptr; +} /// /// Convert from C API handle to internal C API client struct. @@ -42,9 +50,7 @@ static std::map clients; /// capi_client * MAT::capi_get_client(evt_handle_t handle) { - LOCKGUARD(mtx); - const auto it = clients.find(handle); - return (it != clients.cend()) ? &(it->second) : nullptr; + return find_open_client(handle).get(); } /// @@ -52,8 +58,16 @@ capi_client * MAT::capi_get_client(evt_handle_t handle) /// static void remove_client(evt_handle_t handle) { - LOCKGUARD(mtx); - clients.erase(handle); + std::shared_ptr client; + { + LOCKGUARD(mtx); + const auto it = clients.find(handle); + if (it != clients.end()) + { + client = std::move(it->second); + clients.erase(it); + } + } } #define VERIFY_CLIENT_HANDLE(client, ctx) \ @@ -61,8 +75,8 @@ static void remove_client(evt_handle_t handle) { \ return EFAULT; /* bad address */ \ }; \ - auto client = MAT::capi_get_client(ctx->handle); \ - if ((client == nullptr) || (client->logmanager == nullptr)) \ + auto client = find_open_client(ctx->handle); \ + if (!client) \ { \ return ENOENT; \ }; @@ -87,123 +101,91 @@ static evt_status_t mat_open_core( } evt_handle_t code = static_cast(hashCode(config)); - bool isHashFound = false; - // Find the next available spare hashcode - do + bool reserved = false; + MATSDK_TRY { - const auto client = MAT::capi_get_client(code); - if (client != nullptr) + auto client = std::make_shared(); + client->ctx_data = config; { - if (client->ctx_data == config) + LOCKGUARD(mtx); + for (;; ++code) { - // Guest instance with the same config is already open. - // Return its handle so the caller still gets a usable handle - // (rather than leaving ctx->handle uninitialized), and set - // ctx->result to match the returned status like the other paths. - ctx->handle = code; - ctx->result = static_cast(EALREADY); - return EALREADY; - } - // hash code is assigned to another client, increment and retry - // with the next empty slot - code++; - continue; - }; - isHashFound = true; - } while (!isHashFound); - - // JSON configuration must start with { - if (config[0] == '{') - { - // Create new configuration object from JSON - clients[code].config = MAT::FromJSON(config); - } - else - { - // Assume that the config string is a token, not JSON. - // That approach allows to consume the lightweght C API without JSON parser compiled in. - std::string moduleName = "CAPI-Client-"; - moduleName += std::to_string(code); - clients[code].config = - { - { CFG_STR_FACTORY_NAME, moduleName }, - { "version", "1.0.0" }, - { CFG_MAP_FACTORY_CONFIG, + const auto existing = clients.find(code); + if (existing == clients.end()) { - { CFG_STR_FACTORY_HOST, "*" }, - { CFG_STR_CONTEXT_SCOPE, CONTEXT_SCOPE_NONE } + clients.emplace(code, client); + reserved = true; + break; } - }, - { CFG_STR_PRIMARY_TOKEN, config } - }; - } + if (existing->second->ctx_data == config) + { + const bool open = existing->second->logmanager != nullptr; + ctx->handle = open ? code : 0; + ctx->result = static_cast(open ? EALREADY : EFAULT); + return ctx->result; + } + } + } - // Remember the original config string. Needed to avoid hash code collisions - clients[code].ctx_data = config; + if (config[0] == '{') + { + client->config = MAT::FromJSON(config); + } + else + { + std::string moduleName = "CAPI-Client-" + std::to_string(code); + client->config = + { + { CFG_STR_FACTORY_NAME, moduleName }, + { "version", "1.0.0" }, + { CFG_MAP_FACTORY_CONFIG, + { + { CFG_STR_FACTORY_HOST, "*" }, + { CFG_STR_CONTEXT_SCOPE, CONTEXT_SCOPE_NONE } + } + }, + { CFG_STR_PRIMARY_TOKEN, config } + }; + } #if !defined (ANDROID) || defined(ENABLE_CAPI_HTTP_CLIENT) - // Create custom HttpClient - if (httpSendFn != nullptr && httpCancelFn != nullptr) - { -#if HAVE_EXCEPTIONS - try -#endif + if (httpSendFn != nullptr && httpCancelFn != nullptr) { auto http = std::make_shared(httpSendFn, httpCancelFn); - clients[code].http = http; - clients[code].config.AddModule(CFG_MODULE_HTTP_CLIENT, http); - } -#if HAVE_EXCEPTIONS - catch (...) - { - // Roll back the partially-populated client so a later open with the - // same config does not find stale half-initialized state. - remove_client(code); - ctx->result = static_cast(EFAULT); - ctx->handle = 0; - return EFAULT; + client->http = http; + client->config.AddModule(CFG_MODULE_HTTP_CLIENT, http); } #endif - } -#endif - // Create custom worker thread - if (taskDispatcherQueueFn != nullptr && taskDispatcherCancelFn != nullptr && taskDispatcherJoinFn != nullptr) - { -#if HAVE_EXCEPTIONS - try -#endif + if (taskDispatcherQueueFn != nullptr && taskDispatcherCancelFn != nullptr && taskDispatcherJoinFn != nullptr) { - auto taskDispatcher = std::make_shared(taskDispatcherQueueFn, taskDispatcherCancelFn, taskDispatcherJoinFn); - clients[code].taskDispatcher = taskDispatcher; - clients[code].config.AddModule(CFG_MODULE_TASK_DISPATCHER, taskDispatcher); + auto taskDispatcher = std::make_shared( + taskDispatcherQueueFn, taskDispatcherCancelFn, taskDispatcherJoinFn); + client->taskDispatcher = taskDispatcher; + client->config.AddModule(CFG_MODULE_TASK_DISPATCHER, taskDispatcher); } -#if HAVE_EXCEPTIONS - catch (...) + + // The creator can close before another client using its manager. + status_t status = STATUS_EFAIL; + auto manager = LogManagerFactory::GetOwned(std::shared_ptr(client, &client->config), status); + if (manager) { - // Roll back the partially-populated client so a later open with the - // same config does not find stale half-initialized state. - remove_client(code); - ctx->result = static_cast(EFAULT); - ctx->handle = 0; - return EFAULT; + LOCKGUARD(mtx); + client->logmanager = manager; + ctx->result = static_cast(status); + ctx->handle = code; + return ctx->result; } -#endif } - - status_t status = static_cast(EFAULT); - clients[code].logmanager = LogManagerProvider::CreateLogManager(clients[code].config, status); - - // Verify that the instance pointer is valid - if (clients[code].logmanager == nullptr) + MATSDK_CATCH(...) + { + } + if (reserved) { remove_client(code); - ctx->result = static_cast(EFAULT); - ctx->handle = 0; - return EFAULT; } - ctx->result = static_cast(status); - ctx->handle = code; - return ctx->result; + ctx->result = static_cast(EFAULT); + ctx->handle = 0; + return EFAULT; } static evt_status_t mat_open(evt_context_t *ctx) @@ -319,7 +301,7 @@ static evt_status_t mat_log(evt_context_t *ctx) static evt_status_t mat_close(evt_context_t *ctx) { VERIFY_CLIENT_HANDLE(client, ctx); - const auto result = static_cast(LogManagerProvider::Release(client->logmanager->GetLogConfiguration())); + const auto result = static_cast(LogManagerProvider::Release(client->config)); if (result != STATUS_SUCCESS) { ctx->result = result; diff --git a/tests/functests/APITest.cpp b/tests/functests/APITest.cpp index 6128fae1d..265b7e366 100644 --- a/tests/functests/APITest.cpp +++ b/tests/functests/APITest.cpp @@ -892,6 +892,71 @@ TEST(APITest, C_API_Test) } #ifdef HAVE_MAT_JSONHPP +TEST(APITest, C_API_SharedClientsReleaseTheirOwnLeases) +{ + const char* hostConfig = JSON_CONFIG({ + "name": "shared-capi-host", + "config": { "host": "shared-capi-host" }, + "maxTeardownUploadTimeInSec": 0 + }); + const char* guestConfig = JSON_CONFIG({ + "name": "shared-capi-guest", + "config": { "host": "shared-capi-host" } + }); + const char* wildcardConfig = JSON_CONFIG({ + "name": "shared-capi-guest", + "config": { "host": "*" }, + "maxTeardownUploadTimeInSec": 0 + }); + const char* conflictingConfig = JSON_CONFIG({ + "name": "shared-capi-host", + "config": { "host": "shared-capi-host" }, + "version": "2.0.0" + }); + + for (bool wildcardFirst : {false, true}) + { + for (bool closeCreatorFirst : {false, true}) + { + SCOPED_TRACE(wildcardFirst); + SCOPED_TRACE(closeCreatorFirst); + auto creator = evt_open(wildcardFirst ? wildcardConfig : hostConfig); + auto guest = evt_open(wildcardFirst ? hostConfig : guestConfig); + ASSERT_NE(creator, 0); + ASSERT_NE(guest, 0); + ASSERT_NE(creator, guest); + auto manager = capi_get_client(creator)->logmanager; + ASSERT_EQ(capi_get_client(guest)->logmanager, manager); + EXPECT_EQ(evt_open(hostConfig), wildcardFirst ? guest : creator); + EXPECT_EQ(evt_open(conflictingConfig), 0); + EXPECT_EQ(evt_open(conflictingConfig), 0); + EXPECT_EQ(evt_pause(creator), STATUS_SUCCESS); + + const auto first = closeCreatorFirst ? creator : guest; + const auto survivor = closeCreatorFirst ? guest : creator; + ASSERT_EQ(evt_close(first), STATUS_SUCCESS); + EXPECT_EQ(capi_get_client(first), nullptr); + ASSERT_EQ(capi_get_client(survivor)->logmanager, manager); + EXPECT_STREQ(manager->GetLogConfiguration()[CFG_STR_FACTORY_NAME], + wildcardFirst ? "shared-capi-guest" : "shared-capi-host"); + + TestDebugEventListener listener; + int accepted = 0; + listener.OnLogX = [&](::CsProtocol::Record&) { ++accepted; }; + manager->AddEventListener(EVT_LOG_EVENT, listener); + evt_prop event[] = TELEMETRY_EVENT( + _STR(COMMONFIELDS_EVENT_NAME, EVENT_NAME_PURE_C), + _STR(COMMONFIELDS_IKEY, TEST_TOKEN) + ); + EXPECT_EQ(evt_log(survivor, event), STATUS_SUCCESS); + manager->RemoveEventListener(EVT_LOG_EVENT, listener); + EXPECT_EQ(accepted, 1); + ASSERT_EQ(evt_close(survivor), STATUS_SUCCESS); + EXPECT_EQ(capi_get_client(survivor), nullptr); + } + } +} + #if defined(_WIN32) TEST(APITest, UTC_Callback_Test) { diff --git a/tests/unittests/LogManagerImplTests.cpp b/tests/unittests/LogManagerImplTests.cpp index 9adc472e3..a74c8601c 100644 --- a/tests/unittests/LogManagerImplTests.cpp +++ b/tests/unittests/LogManagerImplTests.cpp @@ -184,6 +184,8 @@ TEST_P(LogManagerFinalReleaseTests, FailedFinalFlushPreservesLeaseAndRetriesTheR })); ASSERT_EQ(release(), STATUS_EFAIL); ASSERT_FALSE(failedRecord.empty()); + EXPECT_EQ(LogManagerProvider::CreateLogManager(shared ? guest : configuration, status), nullptr); + EXPECT_EQ(status, STATUS_EFAIL); ASSERT_TRUE(Mock::VerifyAndClearExpectations(disk.get())); EXPECT_CALL(*disk, StoreRecord(Field(&StorageRecord::id, failedRecord))).WillOnce(Return(true)); From 8ec912adb63ff44ed4f1cac43e79bdc96192e064 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 11:30:41 -0600 Subject: [PATCH 17/19] Reject duplicate opens of a retiring C API handle An exact duplicate is idempotent only while its manager still accepts leases. Check that the original manager is registered and open before returning a duplicate handle, without nesting the handle and factory locks. Keep a failed close's original handle usable for retry. Cover a real failed final flush, rejection of a duplicate open, and successful cleanup, retry, and reopen on Windows and Linux. Files: lib/api/LogManagerFactory.{cpp,hpp} lib/api/capi.cpp tests/functests/APITest.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2dc9129f-15f0-482c-a1ea-d48d05909daf --- lib/api/LogManagerFactory.cpp | 7 +++++++ lib/api/LogManagerFactory.hpp | 2 ++ lib/api/capi.cpp | 23 +++++++++++++++++++---- tests/functests/APITest.cpp | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 4 deletions(-) diff --git a/lib/api/LogManagerFactory.cpp b/lib/api/LogManagerFactory.cpp index 8b394296a..0254a6093 100644 --- a/lib/api/LogManagerFactory.cpp +++ b/lib/api/LogManagerFactory.cpp @@ -147,6 +147,13 @@ namespace MAT_NS_BEGIN return manager; } + bool LogManagerFactory::CanAcquireLease(ILogManager* manager) + { + LOCKGUARD(ILogManagerInternal::managers_lock); + return ILogManagerInternal::managers.count(manager) && + static_cast(manager)->CanAcquireLease(); + } + ILogManager* LogManagerFactory::lease(ILogConfiguration& c, const std::shared_ptr& owner) { std::string name; diff --git a/lib/api/LogManagerFactory.hpp b/lib/api/LogManagerFactory.hpp index b4346fdba..58510ea6e 100644 --- a/lib/api/LogManagerFactory.hpp +++ b/lib/api/LogManagerFactory.hpp @@ -141,6 +141,8 @@ namespace MAT_NS_BEGIN { static ILogManager* GetOwned(const std::shared_ptr& configuration, status_t& status); + static bool CanAcquireLease(ILogManager* manager); + static status_t Release(const char* module) { return (instance().release(module)) ? diff --git a/lib/api/capi.cpp b/lib/api/capi.cpp index 4f3dde3a9..3ed82dcf5 100644 --- a/lib/api/capi.cpp +++ b/lib/api/capi.cpp @@ -106,6 +106,8 @@ static evt_status_t mat_open_core( { auto client = std::make_shared(); client->ctx_data = config; + std::shared_ptr duplicate; + ILogManager* duplicateManager = nullptr; { LOCKGUARD(mtx); for (;; ++code) @@ -119,14 +121,27 @@ static evt_status_t mat_open_core( } if (existing->second->ctx_data == config) { - const bool open = existing->second->logmanager != nullptr; - ctx->handle = open ? code : 0; - ctx->result = static_cast(open ? EALREADY : EFAULT); - return ctx->result; + duplicate = existing->second; + duplicateManager = duplicate->logmanager; + break; } } } + if (duplicate) + { + // Don't hold the handle lock while the factory verifies the manager's lifetime. + if (LogManagerFactory::CanAcquireLease(duplicateManager) && find_open_client(code) == duplicate) + { + ctx->handle = code; + ctx->result = static_cast(EALREADY); + return EALREADY; + } + ctx->handle = 0; + ctx->result = static_cast(EFAULT); + return EFAULT; + } + if (config[0] == '{') { client->config = MAT::FromJSON(config); diff --git a/tests/functests/APITest.cpp b/tests/functests/APITest.cpp index 265b7e366..552895196 100644 --- a/tests/functests/APITest.cpp +++ b/tests/functests/APITest.cpp @@ -957,6 +957,38 @@ TEST(APITest, C_API_SharedClientsReleaseTheirOwnLeases) } } +TEST(APITest, C_API_DuplicateOpenRejectsRetiringManagerAfterFailedClose) +{ + const auto directory = "missing-capi-" + PAL::generateUuidString(); +#ifdef _WIN32 + const auto path = directory + "\\\\cache.db"; +#else + const auto path = directory + "/cache.db"; +#endif + const auto config = "{\"name\":\"capi-failed-close\",\"maxTeardownUploadTimeInSec\":0,\"cacheFilePath\":\"" + path + "\"}"; + const auto handle = evt_open(config.c_str()); + ASSERT_NE(handle, 0); + ASSERT_EQ(evt_pause(handle), STATUS_SUCCESS); + EXPECT_EQ(evt_open(config.c_str()), handle); + evt_prop event[] = TELEMETRY_EVENT( + _STR(COMMONFIELDS_EVENT_NAME, EVENT_NAME_PURE_C), + _STR(COMMONFIELDS_IKEY, TEST_TOKEN) + ); + ASSERT_EQ(evt_log(handle, event), STATUS_SUCCESS); + + ASSERT_EQ(evt_close(handle), STATUS_EFAIL); + auto client = capi_get_client(handle); + ASSERT_NE(client, nullptr); + EXPECT_EQ(evt_open(config.c_str()), 0); + EXPECT_EQ(client->logmanager->DeleteData(), STATUS_SUCCESS); + ASSERT_EQ(evt_close(handle), STATUS_SUCCESS); + EXPECT_EQ(capi_get_client(handle), nullptr); + + const auto reopened = evt_open(config.c_str()); + ASSERT_NE(reopened, 0); + EXPECT_EQ(evt_close(reopened), STATUS_SUCCESS); +} + #if defined(_WIN32) TEST(APITest, UTC_Callback_Test) { From 0906134c28ea23518223553092d09158708e5d20 Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 11:45:54 -0600 Subject: [PATCH 18/19] Do not hand out loggers from a retiring LogManager A failed teardown leaves the manager available for retry but cannot accept events. Reject logger acquisition before and after normalization when teardown has started. Verify that singleton reinitialization and C API logging fail rather than silently accepting work during retirement. Files: lib/api/LogManagerImpl.cpp tests/functests/APITest.cpp Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2dc9129f-15f0-482c-a1ea-d48d05909daf --- lib/api/LogManagerImpl.cpp | 4 ++-- tests/functests/APITest.cpp | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/api/LogManagerImpl.cpp b/lib/api/LogManagerImpl.cpp index 43fb53662..2ab59381b 100644 --- a/lib/api/LogManagerImpl.cpp +++ b/lib/api/LogManagerImpl.cpp @@ -741,7 +741,7 @@ namespace MAT_NS_BEGIN { { LOCKGUARD(m_lock); - if (!m_alive) + if (!CanAcquireLease()) { return nullptr; } @@ -754,7 +754,7 @@ namespace MAT_NS_BEGIN std::string hash = normalizedTenantToken + "/" + normalizedSource; LOCKGUARD(m_lock); - if (!m_alive) + if (!CanAcquireLease()) { return nullptr; } diff --git a/tests/functests/APITest.cpp b/tests/functests/APITest.cpp index 552895196..8b910994e 100644 --- a/tests/functests/APITest.cpp +++ b/tests/functests/APITest.cpp @@ -980,6 +980,7 @@ TEST(APITest, C_API_DuplicateOpenRejectsRetiringManagerAfterFailedClose) auto client = capi_get_client(handle); ASSERT_NE(client, nullptr); EXPECT_EQ(evt_open(config.c_str()), 0); + EXPECT_NE(evt_log(handle, event), STATUS_SUCCESS); EXPECT_EQ(client->logmanager->DeleteData(), STATUS_SUCCESS); ASSERT_EQ(evt_close(handle), STATUS_SUCCESS); EXPECT_EQ(capi_get_client(handle), nullptr); @@ -1381,6 +1382,8 @@ TEST(APITest, LogManager_BadStoragePath_Test) #else EXPECT_EQ(LogManager::FlushAndTeardown(), STATUS_EFAIL); #endif + EXPECT_EQ(LogManager::GetLogger(), nullptr); + EXPECT_EQ(LogManager::Initialize(TEST_TOKEN, config), nullptr); LogManager::RemoveEventListener(DebugEventType::EVT_STORAGE_FAILED, debugListener); EXPECT_EQ(true, debugListener.storageFailed); EXPECT_EQ(LogManager::DeleteData(), STATUS_SUCCESS); From 15a7815ab5582fde33dbadc396d849b3d003391d Mon Sep 17 00:00:00 2001 From: Bhagirath Mehta Date: Sat, 5 Dec 2026 11:59:42 -0600 Subject: [PATCH 19/19] Keep the Apple embedding matrix compatible with CMake 3.15 The embedding suite advertises CMake 3.15, so its Apple CTest must not fail before the matrix runs on versions 3.15 through 3.18. Keep the matrix's existing 3.19 policy ceiling on newer CMake. Verified the prior failure and all 19 passing cases on CMake 3.15.7, and reran the matrix with current CMake on Windows and WSL. Files changed: - tests/apple/embedding-options-tests.cmake: align the driver minimum. - tests/apple/embedding-options/CMakeLists.txt: align the fixture minimum. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2dc9129f-15f0-482c-a1ea-d48d05909daf --- tests/apple/embedding-options-tests.cmake | 2 +- tests/apple/embedding-options/CMakeLists.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/apple/embedding-options-tests.cmake b/tests/apple/embedding-options-tests.cmake index 51d7365a5..68d2b39e0 100644 --- a/tests/apple/embedding-options-tests.cmake +++ b/tests/apple/embedding-options-tests.cmake @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.19) +cmake_minimum_required(VERSION 3.15...3.19) get_filename_component(sdk_root "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) if(NOT DEFINED OUTPUT_DIR) set(OUTPUT_DIR "${sdk_root}/out/apple-embedding-options") diff --git a/tests/apple/embedding-options/CMakeLists.txt b/tests/apple/embedding-options/CMakeLists.txt index b7491361a..355bd6b26 100644 --- a/tests/apple/embedding-options/CMakeLists.txt +++ b/tests/apple/embedding-options/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.19) +cmake_minimum_required(VERSION 3.15...3.19) project(apple_embedding_options LANGUAGES C CXX) file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/platform.cmake" "set(APPLE ${TEST_APPLE})\n")