Procházet zdrojové kódy

feat: Retry-After keyed on the cause, and silence where a timer is not the fix

Until now the only route setting Retry-After was a 429, hardcoded at the
exception handler. A read-only database and an unreachable one both
answered a bare 503, so a caller had no way to tell "wait and it will
come back" from "this write did not apply" - and the measured recovery
of the October crash loop was 13-15 s a cycle, which is exactly the kind
of number a caller cannot guess.

ApiError gains a 5th constructor parameter, filled at the RAISE site,
because that is the only place that knows whether a duration is the
remedy at all. retryAfterSeconds() prefers that hint, then gives a 429
the limiter's own window, then returns 0.

The restraint is the point rather than the coverage. Most 503s here are
db_error "insert failed" - a write that did not apply - or no_runner,
which needs an operator; no amount of waiting makes either succeed, so a
number there would invent a remedy a caller would honour. The two
pairing tests pin that, and were falsified by making the mapping blanket
for Unavailable: exactly those two go red while the four positive ones
stay green, which is the only way to know the positive four test
selectivity rather than presence.

/fn cannot route through this - it sends its own JSON so a function's
error text never reaches an unauthenticated caller - so it shares the
constants instead, and its two runner_unavailable 503s now differ
deliberately: configured-and-silent carries 5, not-configured-at-all
carries nothing. openapi.json had promised "carries Retry-After" for
both, which half that route does not meet.

Values are deliberately conservative because NEITHER consumer honours
the header today: too long is far more expensive than too short, since a
caller honouring 60 s on a transient blip turns a fast error into a
stalled transaction.
fszontagh před 1 měsícem
rodič
revize
90a3f6360a

+ 2 - 0
CLAUDE.md

@@ -374,6 +374,8 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   **The dangerous class is history that grows with READ traffic**, because it has no natural ceiling and looks harmless in exactly the period before anyone uses the feature - theirs measured 266 KiB with only 16 of 122 rows ever touched, purely because the customer had barely used the assistant since cutover. Three shapes, needing different answers: read-driven (unbounded, fix the write), content-driven like their `calls` at ~13 KiB per call for transcript-then-analysis patches (bounded by real volume, fine), and human-driven like their `settings/main` at version 172 (bounded by how often a person changes a setting, fine).
   **Audited OURS against that: we are clean, and the audit is the point rather than the result.** `function_registry.cpp` writes only in `put` (a code push), `setPolicy` and `setEnabled` - nothing stamps the row on a read or a run. So the 195 MiB over 18 rows is genuinely push-driven: `put` upserts the WHOLE row including the script source at ~199 KiB, so ~1000 pushes accounts for it exactly. And `default:vectorapi_keys.hlog` measures 0.0 MB, which is the measurement that rules out a per-request `last_used_at` stamp on the key store - the one place this pathology would have grown with every API call we serve.
   **What disabling versioning costs**, confirmed from their code rather than assumed, because the plan is to turn it OFF for the queue and the run log and keep a small N (5-10) on the registry: version history and `restoreVersion`/`restoreToDate` stop working for new writes, and **a DELETED row can no longer be restored**, because restore-after-delete reads the pre-delete state from history. That is why the REGISTRY keeps versions - an accidentally deleted function is exactly the row worth recovering - while a claimed-and-deleted queue row has no reader. It does NOT touch the WAL, replication, the event stream (actor included) or `_version`, which still increments; none of them read history, and recovery is snapshots plus WAL.
+- **`Retry-After` IS KEYED ON THE CAUSE, AND ITS ABSENCE ON MOST 503s IS THE INFORMATION - WHICH IS WHY IT CANNOT BE SET AT THE HANDLER THAT MAPS THE STATUS.** 0.15.0+. `ApiError::retryAfterSec` is a 5th constructor parameter filled at the RAISE site, because that is the only place that knows whether a duration is the remedy; `retryAfterSeconds()` (`errors.cpp`, pure) prefers that hint, then gives a 429 the limiter's own window, then **returns 0**. The values are measured rather than round: `kRetryAfterDbUnreachableSec = 5` (the OOM crash loop recovered in 13-15 s a cycle), `kRetryAfterReadOnlySec = 30` (recovery, not a blip), `kRetryAfterRateLimitedSec = 60`. **The temptation is to stamp every 503, and that is the defect rather than the feature:** most of this service's 503s are `db_error` "insert failed" - a write that did not apply - or `no_runner`, which needs an operator. No duration makes either succeed, so a number there invents a remedy a caller would honour. So the tests that matter are the PAIRING ones (`AnOrdinary503SaysNOTHING`, `NoRunnerConfiguredSaysNOTHING`), deliberately falsified by making the mapping blanket for `Unavailable`: exactly those two go red and the four positive ones stay green, which is the only way to know the four are testing selectivity rather than presence. Note `/fn` sets its own headers directly and CANNOT route through this (a function's error text must never reach an unauthenticated caller), so it shares the CONSTANTS instead - and its two `runner_unavailable` 503s differ on purpose: configured-and-silent carries 5, not-configured-at-all carries nothing. `api/openapi.json` had described that route as simply "carries Retry-After", which was a documented guarantee half of it does not meet.
+  **The reason this is worth a note at all is that NEITHER consumer honours the header today** - one keys its retries on status alone, the other does not retry - so the numbers are for future callers and were chosen with the asymmetry stated: too LONG is far more expensive than too short, because a caller honouring 60 s on a transient blip converts a fast error into a stalled transaction, and on the one live public write path recorded here that is an abandoned customer order. The honest framing for a consumer is "read presence as a positive signal and absence as 'a timer is not the fix', never as 'the server forgot, so I will pick a number'".
 - **`FailedPrecondition` means three different things** and must be branched on `FailureDetail.reason`: `missing_parent` and `delete_restricted` are 422, `read_only` is **503**, and an absent or unrecognised reason is **500**, never a guessed 422. Mapping the bare code to 422 told a caller that a read-only database was its own validation mistake, so it would fix its payload and retry forever instead of waiting. Use the `FailureDetail&` overloads wherever a call offers one - the reason-less `Failure` form cannot tell these apart.
 - **A version conflict is `ErrorCode::Aborted`** (client 2.12.0) carrying `currentVersion`, and maps to **409** `version_conflict`. It used to arrive as `Unknown` and fold into 503 "retry as-is", which is the opposite of the required instruction: re-read first. Never match on the message text for this.
 - **`patch` with a field set to null REMOVES the field** (RFC 7396 merge), it does not store null. Use `update` for an explicit null.

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 2 - 0
api/llms.txt


+ 2 - 2
api/openapi.json

@@ -111,7 +111,7 @@
               "description": "The function's own rate_limit_per_min is exhausted for this minute. Charged per function, not per caller. A refused call is NOT written to the run log: nothing ran, and recording refusals would let an unauthenticated caller append a database row per request.",
               "headers": {
                 "Retry-After": {
-                  "description": "Seconds to wait; always 60.",
+                  "description": "Seconds to wait; always 60, the limiter's own window.",
                   "schema": {
                     "type": "string"
                   }
@@ -136,7 +136,7 @@
               }
             },
             "503": {
-              "description": "No healthy runner (code runner_unavailable). Transient; carries Retry-After.",
+              "description": "No healthy runner (code runner_unavailable). TWO different conditions share this slug and only one carries Retry-After, which is the signal rather than an omission: a runner was configured and did not answer is transient and carries Retry-After: 5, while no functions.runners endpoint is configured at all carries NO Retry-After, because an operator has to act and no amount of waiting changes it.",
               "headers": {
                 "Retry-After": {
                   "schema": {

+ 2 - 1
src/collection_registry.cpp

@@ -75,7 +75,8 @@ std::optional<CollectionMeta> CollectionRegistry::get(const std::string& project
         if (mapped.code == ErrCode::Unavailable)
             throw ApiError(ErrCode::Unavailable, "db_error",
                            "cannot determine whether collection '" + name +
-                               "' exists: the database is not reachable");
+                               "' exists: the database is not reachable",
+                           nlohmann::json::object(), kRetryAfterDbUnreachableSec);
         throw mapped;
     }
 }

+ 6 - 3
src/db_errors.cpp

@@ -47,7 +47,8 @@ ApiError translate(Code code, const std::string& message, const std::string& not
                 return ApiError(ErrCode::Unprocessable, "relation_violation", message, details);
             if (reason == "read_only")
                 // Not the caller's fault and not permanent: it waits.
-                return ApiError(ErrCode::Unavailable, "read_only", message, details);
+                return ApiError(ErrCode::Unavailable, "read_only", message, details,
+                                kRetryAfterReadOnlySec);
             // An unrecognised or absent reason is NOT assumed to be a relation
             // violation. We do not know what refused this, and saying "your
             // request is invalid" when we cannot tell is worse than admitting
@@ -207,9 +208,11 @@ ApiError translate(Code code, const std::string& message, const std::string& not
                                     : message + " - the write may or may not have been applied; "
                                       "re-read before retrying",
                                 details);
-            return ApiError(ErrCode::Unavailable, "db_unavailable", message);
+            return ApiError(ErrCode::Unavailable, "db_unavailable", message,
+                            nlohmann::json::object(), kRetryAfterDbUnreachableSec);
         case Code::Unavailable:
-            return ApiError(ErrCode::Unavailable, "db_unavailable", message);
+            return ApiError(ErrCode::Unavailable, "db_unavailable", message,
+                            nlohmann::json::object(), kRetryAfterDbUnreachableSec);
         // Unknown no longer covers the in-band refusals - since client 2.12.0
         // each one carries its own code. What is left here is a genuinely
         // unclassified failure, and 503 stays the honest answer: not the

+ 10 - 0
src/errors.cpp

@@ -29,6 +29,16 @@ int httpStatus(ErrCode code) {
     return 500;
 }
 
+int retryAfterSeconds(const ApiError& e) {
+    // The raise site's own hint first: it knew the cause.
+    if (e.retryAfterSec > 0) return e.retryAfterSec;
+    // Then the one status whose duration is a property of the status itself.
+    if (e.code == ErrCode::TooManyRequests) return kRetryAfterRateLimitedSec;
+    // And otherwise nothing. See the note on ApiError::retryAfterSec: silence
+    // is the honest answer for a failure whose remedy has no duration.
+    return 0;
+}
+
 nlohmann::json errorBody(const std::string& code, const std::string& message,
                          const nlohmann::json& details) {
     nlohmann::json err{{"code", code}, {"message", message}};

+ 41 - 2
src/errors.hpp

@@ -21,9 +21,48 @@ struct ApiError : std::runtime_error {
     ErrCode code;
     std::string slug;
     nlohmann::json details;   // optional structured payload; empty object = omitted
+    /// Seconds to advise in `Retry-After`, or 0 for "say nothing".
+    ///
+    /// SET AT THE RAISE SITE, because only that site knows the CAUSE, and the
+    /// cause is the whole point: a database that is briefly unreachable and one
+    /// in read-only recovery are both 503 and want very different numbers. The
+    /// global handler must not infer this from the slug - matching on a slug
+    /// string to recover information the thrower already had is the same
+    /// mistake as matching on a message string, which is forbidden here.
+    ///
+    /// 0 rather than an optional, and SILENCE rather than a guess: most of the
+    /// 503s in this service are "did not apply" results whose remedy has no
+    /// natural duration, and inventing a number for those would be worse than
+    /// the current absence - a caller would honour it.
+    int retryAfterSec = 0;
     ApiError(ErrCode c, std::string slug_, const std::string& msg,
-             nlohmann::json det = nlohmann::json::object())
-        : std::runtime_error(msg), code(c), slug(std::move(slug_)), details(std::move(det)) {}
+             nlohmann::json det = nlohmann::json::object(), int retryAfter = 0)
+        : std::runtime_error(msg), code(c), slug(std::move(slug_)), details(std::move(det)),
+          retryAfterSec(retryAfter) {}
 };
 
+/// What `Retry-After` should say for this error, or 0 for no header at all.
+/// Pure, so the policy is testable without a server.
+///
+/// An explicit hint from the raise site WINS over the status default, so a
+/// future rate limit with its own budget can say so rather than inheriting 60.
+int retryAfterSeconds(const ApiError& e);
+
+/// Advisory values, named so the reasoning survives.
+///
+/// Both are deliberately conservative, and the reason is worth stating: NEITHER
+/// consumer honours this header today - one retries on status alone, the other
+/// does not retry at all - so these numbers are for future callers, and the
+/// cost of being too long is far higher than of being too short. A caller that
+/// honours 60 s on a transient failure converts a fast error into a stalled
+/// transaction, which for one live write path means a lost customer order.
+constexpr int kRetryAfterDbUnreachableSec = 5;   ///< measured recovery was 13-15 s a cycle
+constexpr int kRetryAfterReadOnlySec = 30;       ///< recovery, not a blip
+constexpr int kRetryAfterRateLimitedSec = 60;    ///< the limiter's own window
+/// `/fn` sets its own headers rather than throwing (a function's error text must
+/// never reach an unauthenticated caller), so it cannot route through
+/// 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
+
 } // namespace svapi

+ 6 - 2
src/handlers/function_dispatch.cpp

@@ -344,7 +344,7 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
     if (policies[idx]->rateLimitPerMin > 0 &&
         !rateLimiter().allow(functions::fnHttpThrottleBucket(project, functionId),
                              policies[idx]->rateLimitPerMin)) {
-        res.set_header("Retry-After", "60");
+        res.set_header("Retry-After", std::to_string(kRetryAfterRateLimitedSec));
         sendJson(res, 429,
                  errorBody("rate_limited", "this function's per-minute limit is exhausted"));
         return;
@@ -364,6 +364,10 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
         entry.status = 503;
         entry.error = "no runner configured";
         recordRun(d, project, entry);
+        // Deliberately NO Retry-After, unlike the transport-failure 503 below.
+        // An operator has to add a `functions.runners` endpoint; no duration
+        // makes this request succeed, and a number here would have a caller
+        // retry a timer against a configuration gap. The absence is the signal.
         sendJson(res, 503, errorBody("runner_unavailable", "no function runner is configured"));
         return;
     }
@@ -393,7 +397,7 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
         // We never got an answer from any runner. 503 with Retry-After, because
         // the same request may well succeed once a runner is back.
         entry.status = 503;
-        res.set_header("Retry-After", "5");
+        res.set_header("Retry-After", std::to_string(kRetryAfterRunnerUnreachableSec));
         sendJson(res, 503, errorBody("runner_unavailable", "no function runner is available"));
     } else if (r.timedOut) {
         // 504: the thing we delegated to never finished. Not 408 - nothing was

+ 6 - 1
src/server.cpp

@@ -117,7 +117,12 @@ void ApiServer::registerRoutes() {
         // One sender for every classified failure, so a database-raised 429
         // carries Retry-After exactly as one of ours does.
         auto send = [&res](const ApiError& e) {
-            if (e.code == ErrCode::TooManyRequests) res.set_header("Retry-After", "60");
+            // One decider (errors.hpp), so the header cannot drift from the
+            // raise sites that set it - and so the handler never has to
+            // recover the CAUSE by matching on a slug, which would be the
+            // message-text trap one layer along.
+            if (const int secs = retryAfterSeconds(e); secs > 0)
+                res.set_header("Retry-After", std::to_string(secs));
             sendJson(res, httpStatus(e.code), errorBody(e.slug, e.what(), e.details));
         };
         try { std::rethrow_exception(ep); }

+ 65 - 0
tests/test_errors.cpp

@@ -54,3 +54,68 @@ TEST(Errors, GatewayTimeoutIsFiveOhFour) {
     // an upstream that did not answer, not a slow client (which would be 408).
     EXPECT_EQ(httpStatus(ErrCode::GatewayTimeout), 504);
 }
+
+// ---------------------------------------------------------------------------
+// Retry-After is keyed on the CAUSE, and the raise site is what knows it.
+//
+// The point of these is the PAIRING. A test that only asserts "a transient
+// 503 advises 5 seconds" would pass equally against a handler that stamped
+// every error with a header, which is the defect being avoided rather than
+// the behaviour being added - most of this service's 503s are "did not
+// apply" results whose remedy has no duration, and a number there would be
+// honoured by a caller and would be a lie.
+// ---------------------------------------------------------------------------
+
+TEST(RetryAfter, ARateLimitKeepsItsHistoricalSixtySeconds) {
+    EXPECT_EQ(svapi::retryAfterSeconds(
+                  svapi::ApiError(svapi::ErrCode::TooManyRequests, "rate_limited", "slow down")),
+              svapi::kRetryAfterRateLimitedSec);
+}
+
+TEST(RetryAfter, AnExplicitHintFromTheRaiseSiteBeatsTheStatusDefault) {
+    // So a future limiter with a real budget can say so rather than inherit 60.
+    svapi::ApiError e(svapi::ErrCode::TooManyRequests, "rate_limited", "slow down",
+                      nlohmann::json::object(), 7);
+    EXPECT_EQ(svapi::retryAfterSeconds(e), 7);
+}
+
+TEST(RetryAfter, AnUnreachableDatabaseAdvisesTheShortTransientValue) {
+    svapi::ApiError e(svapi::ErrCode::Unavailable, "db_unavailable", "deadline exceeded",
+                      nlohmann::json::object(), svapi::kRetryAfterDbUnreachableSec);
+    EXPECT_EQ(svapi::retryAfterSeconds(e), svapi::kRetryAfterDbUnreachableSec);
+}
+
+TEST(RetryAfter, ReadOnlyRecoveryAdvisesLongerThanAMereOutage) {
+    svapi::ApiError e(svapi::ErrCode::Unavailable, "read_only", "read-only mode",
+                      nlohmann::json::object(), svapi::kRetryAfterReadOnlySec);
+    EXPECT_EQ(svapi::retryAfterSeconds(e), svapi::kRetryAfterReadOnlySec);
+    // The ORDERING is the decision, not the two numbers: whatever they are,
+    // recovery must never advise a shorter wait than a transient blip.
+    EXPECT_GT(svapi::kRetryAfterReadOnlySec, svapi::kRetryAfterDbUnreachableSec);
+}
+
+// --- the falsifiability pairing: the header is SELECTIVE, not blanket -------
+
+TEST(RetryAfter, AnOrdinary503SaysNOTHING) {
+    // "insert failed", "drop failed", "failed to create relation": a write
+    // that did not apply. No duration makes it apply, so advising one would
+    // be inventing a remedy.
+    EXPECT_EQ(svapi::retryAfterSeconds(
+                  svapi::ApiError(svapi::ErrCode::Unavailable, "db_error", "insert failed")),
+              0);
+}
+
+TEST(RetryAfter, NoRunnerConfiguredSaysNOTHING) {
+    // An operator has to act. Retrying never helps, so the header must not
+    // suggest it does.
+    EXPECT_EQ(svapi::retryAfterSeconds(
+                  svapi::ApiError(svapi::ErrCode::Unavailable, "no_runner", "no runner")),
+              0);
+}
+
+TEST(RetryAfter, ARefusalTheCallerMustFixSaysNOTHING) {
+    for (auto code : {svapi::ErrCode::Unprocessable, svapi::ErrCode::Forbidden,
+                      svapi::ErrCode::NotFound, svapi::ErrCode::Conflict}) {
+        EXPECT_EQ(svapi::retryAfterSeconds(svapi::ApiError(code, "x", "y")), 0);
+    }
+}

Některé soubory nejsou zobrazeny, neboť je v těchto rozdílových datech změněno mnoho souborů