Ver código fonte

fix: a provider's 5xx is transient, and calling it 422 cost a consumer rows

A non-200 from the embedding provider was mapped to 422 whatever the
status said. 422 means "your request is unprocessable, correct it", and
no correction of the text makes a provider's 503 go away.

Measured on prod 2026-11-05 at the cost of real data: three of novitax's
26,186 bulk writes died here, their retry set is keyed on STATUS (429,
502, 503, 504), 422 is not in it, so three rows were dropped rather than
retried and were found afterwards by hand. Retrying the same three texts
byte-for-byte then succeeded first time, which is what makes the old
class provably wrong rather than merely unhelpful.

Now: provider 429 or 5xx is 503 with Retry-After 2 (measured - the
recovery was sub-second, and too long converts a blip into a stalled
write); any other 4xx and an unparseable 200 stay 422, because waiting
cannot help and a slug-keyed retry there would be a hot loop. The SLUG
deliberately does not split, for the same reason embedding_unreachable
does not: it is a code consumers branch on, and the status already
carries the only distinction that changes the remedy. The consumer's
existing status-keyed retry therefore picks this up with no change on
their side.

Falsified both ways: blanket-transient fails only the 4xx arm, the old
blanket 422 fails only the two transient arms. The fourth test, on an
unparseable 200, passes under both falsifications and is labelled as
guarding the adjacent branch rather than the split.

AND THE DIAGNOSIS TURNED ON A BROKEN INSTRUMENT OF MINE. nginx has
`gzip on`, so the byte count in our access log is $body_bytes_sent after
compression. The 2026-10-22 note eliminating dimension_mismatch from an
unattributed 422 by comparing "82-85 bytes raw" against "95 observed"
was comparing uncompressed lengths with a compressed number; raw 84
gzips to exactly 95, so that elimination is void. Calibrated against a
401 whose 76-byte body logs as 88, the 95 is produced by "embedding
endpoint returned HTTP <nnn>" for any 3-digit status, while both
malformed-response messages give 87-89. The consumer's truncated log
line supplied the slug; the byte count alone could not.

Neither embedding_failed nor embedding_unreachable appeared in
api/llms.txt at all, which is why a consumer had to recover a code from
a truncated log. Both documented now, with the status split and what it
replaced.

Still open and both ours: we log no error slug for a 4xx, and we do not
record the provider's upstream status anywhere but the message - so even
now we cannot say WHICH status those three writes met.
fszontagh 3 semanas atrás
pai
commit
ed1a9ae3b1
4 arquivos alterados com 149 adições e 3 exclusões
  1. 0 0
      api/llms.txt
  2. 31 3
      src/embeddings.cpp
  3. 8 0
      src/errors.hpp
  4. 110 0
      tests/test_embeddings.cpp

Diferenças do arquivo suprimidas por serem muito extensas
+ 0 - 0
api/llms.txt


+ 31 - 3
src/embeddings.cpp

@@ -145,9 +145,37 @@ std::vector<float> EmbeddingClient::embed(const std::string& model, const std::s
                        "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));
+    if (res->status != 200) {
+        // A PROVIDER HAVING A BAD MOMENT AND A PROVIDER REFUSING OUR REQUEST ARE
+        // NOT THE SAME FAILURE, AND BOTH USED TO BE 422. That is the wrong
+        // instruction for the first one: 422 says "your request is
+        // unprocessable, correct it", and no correction of the text makes a
+        // provider's 503 go away. Measured on prod 2026-11-05 at the cost of
+        // real rows - three writes of 26,186 died here, a consumer's retry set
+        // is keyed on STATUS (429, 502, 503, 504), 422 is not in it, so three
+        // rows were silently dropped and found later by hand. An immediate
+        // retry of all three succeeded, which is what makes the old class
+        // provably wrong rather than merely unhelpful.
+        //
+        // 429 and 5xx are the provider's problem and wait is the remedy, so
+        // 503 with a short Retry-After. Any other 4xx is OURS - an unknown
+        // model, a rejected key, a malformed body - and stays 422, because
+        // waiting cannot help and a retry would be a hot loop.
+        //
+        // THE SLUG DELIBERATELY DOES NOT SPLIT, for the same reason
+        // `embedding_unreachable` does not: it is a code consumers branch on,
+        // and the STATUS already carries the only distinction that changes the
+        // remedy. The provider's own status code stays in the message, which
+        // is currently the ONLY place it is recorded anywhere - the access log
+        // keeps no error slug for a 4xx, which is why this took two incidents
+        // and a consumer's truncated log line to identify at all.
+        const bool transient = res->status == 429 || res->status >= 500;
+        throw ApiError(transient ? ErrCode::Unavailable : ErrCode::Unprocessable,
+                       "embedding_failed",
+                       "embedding endpoint returned HTTP " + std::to_string(res->status),
+                       nlohmann::json::object(),
+                       transient ? kRetryAfterEmbeddingProviderSec : 0);
+    }
     return parseEmbeddingResponse(nlohmann::json::parse(res->body));
 }
 }

+ 8 - 0
src/errors.hpp

@@ -64,5 +64,13 @@ constexpr int kRetryAfterRateLimitedSec = 60;    ///< the limiter's own window
 /// retryAfterSeconds(). It can still share the NUMBERS, which is the point of
 /// naming them here: two files quoting "5" would drift the first time one moved.
 constexpr int kRetryAfterRunnerUnreachableSec = 5;  ///< a runner is configured and did not answer
+/// A provider that answered 429 or 5xx, i.e. one having a bad moment rather than
+/// refusing our request. Deliberately the SHORTEST value here: measured on prod
+/// 2026-11-05, three writes of 26,186 failed this way 13 seconds apart and an
+/// immediate retry of all three with byte-identical text succeeded first time,
+/// so the outage was sub-second. The asymmetry noted above applies with full
+/// force - too long converts a blip into a stalled write.
+constexpr int kRetryAfterEmbeddingProviderSec = 2;
+
 
 } // namespace svapi

+ 110 - 0
tests/test_embeddings.cpp

@@ -373,3 +373,113 @@ TEST(Embeddings, ARefusedConnectionNamesTheCONNECTphaseInstead) {
     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();
+}

Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff