#include #include "embeddings.hpp" #include "embedding_cache.hpp" #include "errors.hpp" #include #include #include #include #include using namespace svapi; TEST(Embeddings, ParsesWellFormedResponse) { auto v = parseEmbeddingResponse(nlohmann::json::parse(R"({"data":[{"embedding":[0.5,1.0,1.5]}]})")); ASSERT_EQ(v.size(), 3u); EXPECT_FLOAT_EQ(v[0], 0.5f); EXPECT_FLOAT_EQ(v[2], 1.5f); } TEST(Embeddings, MalformedThrows) { EXPECT_THROW(parseEmbeddingResponse(nlohmann::json::parse(R"({"data":[]})")), ApiError); EXPECT_THROW(parseEmbeddingResponse(nlohmann::json::object()), ApiError); } TEST(Embeddings, SplitBaseHandlesPathPrefix) { EXPECT_EQ(splitEmbeddingBase("https://api.openai.com").origin, "https://api.openai.com"); EXPECT_EQ(splitEmbeddingBase("https://api.openai.com").path, ""); EXPECT_EQ(splitEmbeddingBase("https://api.openai.com/").path, ""); auto orr = splitEmbeddingBase("https://openrouter.ai/api"); EXPECT_EQ(orr.origin, "https://openrouter.ai"); EXPECT_EQ(orr.path, "/api"); EXPECT_EQ(splitEmbeddingBase("https://openrouter.ai/api/").path, "/api"); EXPECT_EQ(splitEmbeddingBase("http://h:8080/a/b").origin, "http://h:8080"); EXPECT_EQ(splitEmbeddingBase("http://h:8080/a/b").path, "/a/b"); } TEST(Embeddings, ClientHitsMockServer) { httplib::Server mock; mock.Post("/v1/embeddings", [](const httplib::Request& req, httplib::Response& res) { auto j = nlohmann::json::parse(req.body); EXPECT_EQ(j["model"], "m"); EXPECT_EQ(j["input"], "hello"); res.set_content(R"({"data":[{"embedding":[1,2,3,4]}]})", "application/json"); }); int port = mock.bind_to_any_port("127.0.0.1"); std::thread t([&]{ mock.listen_after_bind(); }); EmbeddingClient cli("http://127.0.0.1:" + std::to_string(port), "k"); auto v = cli.embed("m", "hello"); EXPECT_EQ(v.size(), 4u); EXPECT_FLOAT_EQ(v[3], 4.0f); mock.stop(); t.join(); } TEST(Embeddings, ClientHonorsBasePathPrefix) { // Provider whose embeddings live under a path prefix (e.g. OpenRouter /api/v1/embeddings) httplib::Server mock; mock.Post("/api/v1/embeddings", [](const httplib::Request&, httplib::Response& res) { res.set_content(R"({"data":[{"embedding":[9,9]}]})", "application/json"); }); int port = mock.bind_to_any_port("127.0.0.1"); std::thread t([&]{ mock.listen_after_bind(); }); EmbeddingClient cli("http://127.0.0.1:" + std::to_string(port) + "/api", "k"); auto v = cli.embed("qwen/qwen3-embedding-8b", "hello"); EXPECT_EQ(v.size(), 2u); EXPECT_FLOAT_EQ(v[0], 9.0f); mock.stop(); t.join(); } TEST(Embeddings, PoolRunsRequestsConcurrently) { // A serialized impl (single Client + mutex) would pin maxInFlight at 1. // A real pool of N clients lets up to N requests overlap on independent sockets. std::atomic inFlight{0}; std::atomic maxInFlight{0}; httplib::Server mock; mock.Post("/v1/embeddings", [&](const httplib::Request&, httplib::Response& res) { int now = ++inFlight; int prev = maxInFlight.load(); while (now > prev && !maxInFlight.compare_exchange_weak(prev, now)) {} std::this_thread::sleep_for(std::chrono::milliseconds(180)); --inFlight; res.set_content(R"({"data":[{"embedding":[1,2,3,4]}]})", "application/json"); }); int port = mock.bind_to_any_port("127.0.0.1"); mock.set_keep_alive_max_count(1000); std::thread srv([&]{ mock.listen_after_bind(); }); while (!mock.is_running()) std::this_thread::sleep_for(std::chrono::milliseconds(5)); const std::string origin = "http://127.0.0.1:" + std::to_string(port); constexpr int K = 4; std::vector workers; std::atomic ok{0}; for (int i = 0; i < K; ++i) { workers.emplace_back([&]{ EmbeddingClient cli(origin, "", 10, 60, /*poolSize=*/4); auto v = cli.embed("m", "t"); if (v.size() == 4u && v[3] == 4.0f) ++ok; }); } for (auto& w : workers) w.join(); mock.stop(); srv.join(); EXPECT_EQ(ok.load(), K); // all requests succeeded EXPECT_GE(maxInFlight.load(), 2); // proves overlap - pool did NOT serialize } TEST(Embeddings, PoolSizeOneSerializes) { // poolSize=1 means a single keep-alive client → requests cannot overlap. std::atomic inFlight{0}; std::atomic maxInFlight{0}; httplib::Server mock; mock.Post("/v1/embeddings", [&](const httplib::Request&, httplib::Response& res) { int now = ++inFlight; int prev = maxInFlight.load(); while (now > prev && !maxInFlight.compare_exchange_weak(prev, now)) {} std::this_thread::sleep_for(std::chrono::milliseconds(120)); --inFlight; res.set_content(R"({"data":[{"embedding":[1,2,3,4]}]})", "application/json"); }); int port = mock.bind_to_any_port("127.0.0.1"); mock.set_keep_alive_max_count(1000); std::thread srv([&]{ mock.listen_after_bind(); }); while (!mock.is_running()) std::this_thread::sleep_for(std::chrono::milliseconds(5)); const std::string origin = "http://127.0.0.1:" + std::to_string(port); constexpr int K = 4; std::vector workers; std::atomic ok{0}; for (int i = 0; i < K; ++i) { workers.emplace_back([&]{ EmbeddingClient cli(origin, "", 10, 60, /*poolSize=*/1); auto v = cli.embed("m", "t"); if (v.size() == 4u) ++ok; }); } for (auto& w : workers) w.join(); mock.stop(); srv.join(); EXPECT_EQ(ok.load(), K); EXPECT_EQ(maxInFlight.load(), 1); // serialized by design (single client) } // ---- EmbeddingCache tests ----------------------------------------------- TEST(EmbeddingCache, ReturnsCachedVectorOnExactKey) { EmbeddingCache cache(16, 1024*1024, 0); EmbeddingCache::Key k{"https://api.openai.com", "text-embedding-3-small", "hello world"}; std::vector vec = {0.1f, 0.2f, 0.3f}; cache.put(k, vec); auto result = cache.get(k); ASSERT_TRUE(result.has_value()); ASSERT_EQ(result->size(), 3u); EXPECT_FLOAT_EQ((*result)[0], 0.1f); EXPECT_FLOAT_EQ((*result)[1], 0.2f); EXPECT_FLOAT_EQ((*result)[2], 0.3f); } TEST(EmbeddingCache, MissOnAbsentKey) { EmbeddingCache cache(16, 1024*1024, 0); EmbeddingCache::Key k{"https://api.openai.com", "text-embedding-3-small", "not stored"}; auto result = cache.get(k); EXPECT_FALSE(result.has_value()); auto s = cache.stats(); EXPECT_EQ(s.misses, 1u); EXPECT_EQ(s.hits, 0u); } TEST(EmbeddingCache, EvictsLeastRecentlyUsedWhenFull) { // capacity=3: insert A,B,C; then get(A) to refresh it; insert D → B should be evicted EmbeddingCache cache(3, 1024*1024, 0); EmbeddingCache::Key kA{"base", "m", "A"}; EmbeddingCache::Key kB{"base", "m", "B"}; EmbeddingCache::Key kC{"base", "m", "C"}; EmbeddingCache::Key kD{"base", "m", "D"}; cache.put(kA, {1.0f}); cache.put(kB, {2.0f}); cache.put(kC, {3.0f}); // Touch A so it's recently used; B becomes the LRU cache.get(kA); // Insert D - evicts B (least recently used) cache.put(kD, {4.0f}); EXPECT_TRUE(cache.get(kA).has_value()); EXPECT_FALSE(cache.get(kB).has_value()); // evicted EXPECT_TRUE(cache.get(kC).has_value()); EXPECT_TRUE(cache.get(kD).has_value()); } TEST(EmbeddingCache, DistinguishesModels) { EmbeddingCache cache(16, 1024*1024, 0); EmbeddingCache::Key k1{"https://api.openai.com", "model-A", "hello"}; EmbeddingCache::Key k2{"https://api.openai.com", "model-B", "hello"}; cache.put(k1, {1.0f}); cache.put(k2, {2.0f}); auto r1 = cache.get(k1); auto r2 = cache.get(k2); ASSERT_TRUE(r1.has_value()); ASSERT_TRUE(r2.has_value()); EXPECT_FLOAT_EQ((*r1)[0], 1.0f); EXPECT_FLOAT_EQ((*r2)[0], 2.0f); EXPECT_EQ(cache.stats().size, 2u); } TEST(EmbeddingCache, DistinguishesApiBase) { EmbeddingCache cache(16, 1024*1024, 0); EmbeddingCache::Key k1{"https://api.openai.com", "text-embedding-3-small", "hello"}; EmbeddingCache::Key k2{"https://openrouter.ai/api", "text-embedding-3-small", "hello"}; cache.put(k1, {1.0f}); cache.put(k2, {2.0f}); auto r1 = cache.get(k1); auto r2 = cache.get(k2); ASSERT_TRUE(r1.has_value()); ASSERT_TRUE(r2.has_value()); EXPECT_FLOAT_EQ((*r1)[0], 1.0f); EXPECT_FLOAT_EQ((*r2)[0], 2.0f); EXPECT_EQ(cache.stats().size, 2u); } TEST(EmbeddingCache, ExpiresAfterTtl) { EmbeddingCache cache(16, 1024*1024, /*ttlSec=*/60); int64_t fakeNow = 1000; cache.setClockForTesting([&fakeNow]{ return fakeNow; }); EmbeddingCache::Key k{"base", "m", "text"}; cache.put(k, {5.0f}); // Before expiry - hit EXPECT_TRUE(cache.get(k).has_value()); // Advance clock past TTL fakeNow = 1061; auto result = cache.get(k); EXPECT_FALSE(result.has_value()); // expired auto s = cache.stats(); EXPECT_GE(s.misses, 1u); // at least the expired-get counted as miss } TEST(EmbeddingCache, EvictsToStayUnderByteBudget) { // Each vector of 4 floats = 16 bytes. Budget = 40 bytes → max 2 full entries. EmbeddingCache cache(/*capacity=*/100, /*maxBytes=*/40, /*ttlSec=*/0); EmbeddingCache::Key kA{"b", "m", "A"}; EmbeddingCache::Key kB{"b", "m", "B"}; EmbeddingCache::Key kC{"b", "m", "C"}; cache.put(kA, {1.0f, 2.0f, 3.0f, 4.0f}); // 16 bytes cache.put(kB, {5.0f, 6.0f, 7.0f, 8.0f}); // 16 bytes; total=32 // inserting C (16 bytes) would push total to 48 > 40 → evict LRU (A) cache.put(kC, {9.0f, 10.0f, 11.0f, 12.0f}); EXPECT_LE(cache.stats().bytes, 40u); EXPECT_FALSE(cache.get(kA).has_value()); // evicted EXPECT_TRUE(cache.get(kB).has_value()); EXPECT_TRUE(cache.get(kC).has_value()); } TEST(EmbeddingCache, NormalizationCollapsesWhitespaceAndCaseWhenEnabled) { // With normalize=true: "Max DC" and "max dc" should map to ONE entry EmbeddingCache cacheOn(16, 1024*1024, 0, /*normalize=*/true); EmbeddingCache::Key k1{"base", "m", "Max DC"}; EmbeddingCache::Key k2{"base", "m", "max dc"}; cacheOn.put(k1, {1.0f}); auto r = cacheOn.get(k2); ASSERT_TRUE(r.has_value()); EXPECT_FLOAT_EQ((*r)[0], 1.0f); EXPECT_EQ(cacheOn.stats().size, 1u); // With normalize=false (default): they stay distinct EmbeddingCache cacheOff(16, 1024*1024, 0, /*normalize=*/false); EmbeddingCache::Key k3{"base", "m", "Max DC"}; EmbeddingCache::Key k4{"base", "m", "max dc"}; cacheOff.put(k3, {1.0f}); auto r2 = cacheOff.get(k4); EXPECT_FALSE(r2.has_value()); EXPECT_EQ(cacheOff.stats().size, 1u); } TEST(EmbeddingCache, StatsCountsHitsAndMisses) { EmbeddingCache cache(16, 1024*1024, 0); EmbeddingCache::Key k{"base", "m", "text"}; // 2 misses cache.get(k); cache.get(k); // put then 3 hits cache.put(k, {1.0f}); cache.get(k); cache.get(k); cache.get(k); auto s = cache.stats(); EXPECT_EQ(s.misses, 2u); EXPECT_EQ(s.hits, 3u); EXPECT_EQ(s.size, 1u); EXPECT_EQ(s.capacity, 16u); EXPECT_EQ(s.bytes, sizeof(float) * 1u); } TEST(EmbeddingCache, ReconfigureEvictsToTighterBounds) { EmbeddingCache cache(16, 1024*1024, 0); EmbeddingCache::Key kA{"b", "m", "A"}; EmbeddingCache::Key kB{"b", "m", "B"}; EmbeddingCache::Key kC{"b", "m", "C"}; cache.put(kA, {1.0f}); // A is least-recently used cache.put(kB, {2.0f}); cache.put(kC, {3.0f}); ASSERT_EQ(cache.stats().size, 3u); // Shrink capacity to 1 - reconfigure must evict immediately, keeping the MRU entry. cache.reconfigure(1, 1024*1024, 0, false); auto s = cache.stats(); EXPECT_EQ(s.size, 1u); EXPECT_EQ(s.capacity, 1u); EXPECT_FALSE(cache.get(kA).has_value()); // evicted EXPECT_TRUE(cache.get(kC).has_value()); // most-recently used survives } // A base URL that already ends in /v1 is the common OpenRouter mistake: the // client appends "/v1/embeddings" to whatever path the base carries, so the // request lands on /api/v1/v1/embeddings, which OpenRouter answers with 404. TEST(Embeddings, BaseEndingInV1DuplicatesTheVersionSegment) { auto wrong = splitEmbeddingBase("https://openrouter.ai/api/v1"); EXPECT_EQ(wrong.origin, "https://openrouter.ai"); EXPECT_EQ(wrong.path, "/api/v1"); EXPECT_EQ(wrong.path + "/v1/embeddings", "/api/v1/v1/embeddings"); auto right = splitEmbeddingBase("https://openrouter.ai/api"); EXPECT_EQ(right.path + "/v1/embeddings", "/api/v1/embeddings"); } // THE DEFECT: an unreachable provider and a provider that never answers used to // produce the IDENTICAL message, "could not reach embedding endpoint", because // httplib hands back an empty Result for both and nothing read `res.error()`. // The operator warning one layer up prints the windows we ALLOWED, so neither // the message nor the log could say which phase expired, and a live diagnosis // had to be recovered from the gap between two journal timestamps. // // These two tests are a PAIR and are only worth anything together: the first // alone would pass against a message that named "read" unconditionally, and the // second alone would pass against one that named "connect" unconditionally. // What has to hold is that the two DIFFER and each names its own phase. TEST(Embeddings, AReadThatNeverAnswersSaysSOandCarriesTheElapsedTime) { httplib::Server mock; // Accepts the connection, then outlives the client's read timeout. So // connect succeeded and the READ is what ran out - the shape measured on // prod, where the second rung's failures landed within 70 ms of their 3 s // read window while the connect cap was 2 s. mock.Post("/v1/embeddings", [](const httplib::Request&, httplib::Response& res) { std::this_thread::sleep_for(std::chrono::seconds(3)); res.set_content(R"({"data":[{"embedding":[1]}]})", "application/json"); }); int port = mock.bind_to_any_port("127.0.0.1"); std::thread t([&]{ mock.listen_after_bind(); }); EmbeddingClient cli("http://127.0.0.1:" + std::to_string(port), "k", 2 /*connect*/, 1 /*read*/); std::string msg; try { cli.embed("m", "hello"); FAIL() << "a server that never answers inside the read window must throw"; } catch (const ApiError& e) { msg = e.what(); // The code is deliberately UNCHANGED: a consumer branches on it. EXPECT_EQ(e.slug, "embedding_unreachable"); } // httplib's own wording: Error::Read is "Failed to read connection", // Error::Connection is "Could not establish connection". Matching on // "connection" would match BOTH, which is how a pair like this quietly // stops discriminating - so each arm matches the word only its own kind has. EXPECT_NE(msg.find("read"), std::string::npos) << msg; EXPECT_EQ(msg.find("establish"), std::string::npos) << msg; // The elapsed time is the half that makes the phase checkable rather than // merely asserted: a read window of 1 s cannot expire in 50 ms. EXPECT_NE(msg.find("ms"), std::string::npos) << msg; mock.stop(); t.join(); } TEST(Embeddings, ARefusedConnectionNamesTheCONNECTphaseInstead) { // Port 1 on loopback: the kernel answers RST immediately, so connect FAILS // rather than hanging. The first version of this test bound a port with // bind_to_any_port and let the Server go out of scope, assuming that closed // the listener - it does not, so connect SUCCEEDED, nothing accepted, and // the call died at the 1 s READ timeout reporting "Failed to read // connection". It was indistinguishable from the test above, which is // exactly the conflation this pair exists to rule out, and it was only // visible because the OTHER arm asserts the absence of this one's wording. EmbeddingClient cli("http://127.0.0.1:1", "k", 2, 1); std::string msg; try { cli.embed("m", "hello"); FAIL() << "a refused connection must throw"; } catch (const ApiError& e) { msg = e.what(); EXPECT_EQ(e.slug, "embedding_unreachable"); } EXPECT_NE(msg.find("establish"), std::string::npos) << msg; EXPECT_EQ(msg.find("read"), std::string::npos) << msg; } // THE DEFECT: a provider that answered 429 or 5xx and a provider that refused // our request both came back as 422. 422 means "your request is unprocessable, // correct it", which is the wrong instruction for a provider's own 503 and the // reason three of novitax's 26,186 writes were lost on 2026-11-05 instead of // retried - their retry set is keyed on STATUS and 422 is not in it. An // immediate retry of the same three texts then succeeded, so the class was // provably wrong rather than merely unhelpful. // // These two tests are a PAIR and are worth nothing apart. The first alone // passes against a mapping that answers 503 for EVERY non-200, which would // turn a misspelled model name into an endless retry; the second alone passes // against the old blanket 422. What has to hold is that they DIFFER, so each // arm asserts the absence of the other's answer. TEST(Embeddings, AProviderFivexxIsRetryableWithAShortRetryAfter) { httplib::Server mock; mock.Post("/v1/embeddings", [](const httplib::Request&, httplib::Response& res) { res.status = 503; res.set_content(R"({"error":"upstream busy"})", "application/json"); }); int port = mock.bind_to_any_port("127.0.0.1"); std::thread t([&]{ mock.listen_after_bind(); }); EmbeddingClient cli("http://127.0.0.1:" + std::to_string(port), "k"); try { cli.embed("baai/bge-m3", "ordinary Hungarian prose"); FAIL() << "a provider 503 must throw"; } catch (const ApiError& e) { EXPECT_EQ(e.slug, "embedding_failed"); // slug deliberately unchanged EXPECT_EQ(e.code, ErrCode::Unavailable); // NOT Unprocessable EXPECT_NE(e.code, ErrCode::Unprocessable); EXPECT_EQ(httpStatus(e.code), 503); // The header is the half a status-keyed caller cannot infer. EXPECT_EQ(retryAfterSeconds(e), kRetryAfterEmbeddingProviderSec); EXPECT_GT(retryAfterSeconds(e), 0); // The provider's own status survives into the message, which is the // only place it is recorded: our access log keeps no slug for a 4xx. EXPECT_NE(std::string(e.what()).find("503"), std::string::npos) << e.what(); } mock.stop(); t.join(); } TEST(Embeddings, AProviderFourxxStaysPermanentAndSaysNOTHINGaboutRetrying) { // An unknown model or a rejected key. Waiting cannot help, and a // Retry-After here would invite exactly the hot loop the split avoids. httplib::Server mock; mock.Post("/v1/embeddings", [](const httplib::Request&, httplib::Response& res) { res.status = 400; res.set_content(R"({"error":"no such model"})", "application/json"); }); int port = mock.bind_to_any_port("127.0.0.1"); std::thread t([&]{ mock.listen_after_bind(); }); EmbeddingClient cli("http://127.0.0.1:" + std::to_string(port), "k"); try { cli.embed("baai/bge-m3-nonexistent", "ordinary Hungarian prose"); FAIL() << "a provider 400 must throw"; } catch (const ApiError& e) { EXPECT_EQ(e.slug, "embedding_failed"); // same slug, different class EXPECT_EQ(e.code, ErrCode::Unprocessable); EXPECT_NE(e.code, ErrCode::Unavailable); EXPECT_EQ(httpStatus(e.code), 422); EXPECT_EQ(retryAfterSeconds(e), 0); // silence, not a guess EXPECT_NE(std::string(e.what()).find("400"), std::string::npos) << e.what(); } mock.stop(); t.join(); } // 429 is the one status that is NOT 5xx and is still the provider's problem, so // it is the single case a `status >= 500` test would miss entirely. TEST(Embeddings, AProvider429IsTransientDespiteBeingA4xx) { httplib::Server mock; mock.Post("/v1/embeddings", [](const httplib::Request&, httplib::Response& res) { res.status = 429; res.set_content(R"({"error":"rate limited"})", "application/json"); }); int port = mock.bind_to_any_port("127.0.0.1"); std::thread t([&]{ mock.listen_after_bind(); }); EmbeddingClient cli("http://127.0.0.1:" + std::to_string(port), "k"); try { cli.embed("baai/bge-m3", "t"); FAIL() << "a provider 429 must throw"; } catch (const ApiError& e) { EXPECT_EQ(e.code, ErrCode::Unavailable) << "429 from the PROVIDER is not our rate limit"; EXPECT_GT(retryAfterSeconds(e), 0); EXPECT_NE(std::string(e.what()).find("429"), std::string::npos) << e.what(); } mock.stop(); t.join(); } // A 200 carrying a body we cannot parse is a THIRD thing and must not have been // swept into the transient arm: the provider answered, so retrying is pointless. // This is the branch the gzip forensics below eliminated, and it is the one a // careless "any failure here is transient" change would silently reclassify. TEST(Embeddings, AMalformedTwoHundredStaysPermanent) { httplib::Server mock; mock.Post("/v1/embeddings", [](const httplib::Request&, httplib::Response& res) { res.set_content(R"({"data":[{"embedding":[]}]})", "application/json"); }); int port = mock.bind_to_any_port("127.0.0.1"); std::thread t([&]{ mock.listen_after_bind(); }); EmbeddingClient cli("http://127.0.0.1:" + std::to_string(port), "k"); try { cli.embed("m", "t"); FAIL() << "an empty embedding[] must throw"; } catch (const ApiError& e) { EXPECT_EQ(e.slug, "embedding_failed"); EXPECT_EQ(e.code, ErrCode::Unprocessable); EXPECT_EQ(retryAfterSeconds(e), 0); } mock.stop(); t.join(); }