浏览代码

fix: the embedding failure message names the phase that expired

cpp-httplib returns an empty Result for a connect failure and for a read
timeout alike, and nothing read `res.error()`, so both threw the identical
"could not reach embedding endpoint". The operator warning one layer up
reports the windows we ALLOWED rather than the ones that elapsed, so
neither the message nor the log could say which phase ran out.

That cost a live diagnosis. A consumer chasing repeated embedding
timeouts asked whether connect or read was expiring; the answer had to be
recovered from the GAP between two journal timestamps (3.004, 3.072,
3.024, 3.016 s against a 3 s read window and a 2 s connect cap, so read),
because the field built to say it said the same thing either way. A check
that fires reliably and answers a different question reads as evidence.

The message now carries httplib's error kind and the elapsed
milliseconds. The SLUG deliberately does not split: `embedding_unreachable`
is a code a consumer branches on, and two codes would be a breaking
change for a distinction only an operator needs.

The two tests are a PAIR and are worth nothing apart - each asserts the
ABSENCE of the other's wording, so neither can pass against a message
that names one phase unconditionally. That is what caught a defect in the
test itself: the "refused connection" arm bound a port with
bind_to_any_port and let the Server go out of scope, assuming that closed
the listener. It does not. Connect SUCCEEDED, nothing accepted, and the
call died at the read timeout reporting "Failed to read connection" -
byte-identical to the case it was written to contrast with. Port 1 on
loopback answers RST and discriminates.

Falsified before being trusted: restoring the old constant message turns
both red, for the right reason.
fszontagh 3 周之前
父节点
当前提交
24ddb6e55a
共有 2 个文件被更改,包括 91 次插入 和 1 次删除
  1. 24 1
      src/embeddings.cpp
  2. 67 0
      tests/test_embeddings.cpp

+ 24 - 1
src/embeddings.cpp

@@ -2,6 +2,7 @@
 #include "errors.hpp"
 #include "outbound_http.hpp"
 #include <httplib.h>
+#include <chrono>
 #include <condition_variable>
 #include <map>
 #include <memory>
@@ -120,8 +121,30 @@ std::vector<float> EmbeddingClient::embed(const std::string& model, const std::s
     ClientPool& pool = poolFor(ep.origin, apiKey_, connectTimeoutSec_, readTimeoutSec_, poolSize_);
     ClientPool::Lease lease(pool);  // EXCLUSIVE use of one keep-alive Client until scope exit
     nlohmann::json req{{"model", model}, {"input", text}};
+    // The elapsed time and httplib's own error kind are BOTH carried into the
+    // message, because without them a failure here cannot say which PHASE ran
+    // out. httplib returns an empty Result for a connect failure and for a read
+    // timeout alike, so "could not reach embedding endpoint" was identical in
+    // both cases - and the operator warning above this layer reports the
+    // windows we ALLOWED rather than the ones that elapsed. A consumer chasing
+    // repeated timeouts had to derive the answer from the gap between two
+    // journal lines; a check that fires reliably and answers a different
+    // question is worse than one that fails, because it reads as evidence.
+    //
+    // The SLUG deliberately does not split. `embedding_unreachable` is a code a
+    // consumer branches on, and two codes here would be a breaking change in
+    // exchange for a distinction only an operator needs. The message carries
+    // it, appended rather than reshaped.
+    const auto startedAt = std::chrono::steady_clock::now();
     auto res = lease.client().Post(ep.path + "/v1/embeddings", req.dump(), "application/json");
-    if (!res) throw ApiError(ErrCode::Unavailable, "embedding_unreachable", "could not reach embedding endpoint");
+    const auto elapsedMs = std::chrono::duration_cast<std::chrono::milliseconds>(
+                               std::chrono::steady_clock::now() - startedAt)
+                               .count();
+    if (!res)
+        throw ApiError(ErrCode::Unavailable, "embedding_unreachable",
+                       "could not reach embedding endpoint: " +
+                           httplib::to_string(res.error()) + " after " +
+                           std::to_string(elapsedMs) + "ms");
     if (res->status != 200)
         throw ApiError(ErrCode::Unprocessable, "embedding_failed",
                        "embedding endpoint returned HTTP " + std::to_string(res->status));

+ 67 - 0
tests/test_embeddings.cpp

@@ -306,3 +306,70 @@ TEST(Embeddings, BaseEndingInV1DuplicatesTheVersionSegment) {
     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;
+}