Prechádzať zdrojové kódy

feat(settings): per-project default function policy, and a 504

ProjectEmbeddingSettings becomes ProjectSettings: it now carries
`default_function_policy` beside the embedding overrides, which is what a
function's FIRST registration in a project inherits. Consulted only for a
first registration - mergeForCodePush keeps an existing function's policy -
so changing a project's default never retroactively alters anything
already deployed.

The rename was worth doing rather than adding a field to a misnamed
struct, because reading all 36 call sites found a bug: the embeddings
handler deletes a project's settings document when hasOverrides() goes
false. Keyed on the embedding fields alone, clearing an embedding
override would have silently deleted the function policy with it. Split
into hasEmbeddingOverrides() and hasAnyOverrides(), with the delete on
the latter, and a test named for that case.

An absent `default_function_policy` and a stored empty one are kept
distinct: both deny today, but the second is an admin deliberately saying
"a new function here gets nothing" and must survive a change to the
built-in floor.

Also ErrCode::GatewayTimeout -> 504, for a function that ran past its
wall-time budget. The design document's own "Still open" list asked for
it, and function dispatch had no honest status without it: 408 would
blame the client for an upstream that did not answer.
fszontagh 1 mesiac pred
rodič
commit
bfe2bb43fb

+ 4 - 0
src/errors.cpp

@@ -12,6 +12,10 @@ int httpStatus(ErrCode code) {
         case ErrCode::Unprocessable:    return 422;
         case ErrCode::TooManyRequests:  return 429;
         case ErrCode::Unavailable:      return 503;
+        // A function that ran past its wall-time budget. 504 rather than 408:
+        // nothing was slow about the client, the upstream we were waiting on
+        // did not answer. Nothing but function dispatch produces this.
+        case ErrCode::GatewayTimeout:   return 504;
         case ErrCode::Internal:      return 500;
     }
     return 500;

+ 2 - 1
src/errors.hpp

@@ -6,7 +6,8 @@
 namespace svapi {
 
 enum class ErrCode { BadRequest, Unauthorized, Forbidden, NotFound, Conflict,
-                     Unprocessable, TooManyRequests, Unavailable, Internal };
+                     Unprocessable, TooManyRequests, Unavailable, GatewayTimeout,
+                     Internal };
 
 int httpStatus(ErrCode code);
 

+ 6 - 4
src/handlers/project_settings.cpp

@@ -26,7 +26,7 @@ void applyOverride(const nlohmann::json& body, const char* name, std::string& fi
     field = s;
 }
 
-nlohmann::json viewJson(const Settings& global, const ProjectEmbeddingSettings* p) {
+nlohmann::json viewJson(const Settings& global, const ProjectSettings* p) {
     // An empty CollectionMeta means "no per-collection model pin", so this shows
     // what a collection without its own model would resolve to.
     const CollectionMeta none;
@@ -67,7 +67,7 @@ void registerProjectSettingsRoutes(ApiServer& s) {
 
         // Start from what is stored so a partial PUT leaves the rest alone.
         auto current = d->settings.projectSnapshot(project);
-        ProjectEmbeddingSettings updated = current ? *current : ProjectEmbeddingSettings{};
+        ProjectSettings updated = current ? *current : ProjectSettings{};
         updated.project = project;
         applyOverride(body, "openai_api_base", updated.openaiApiBase);
         applyOverride(body, "openai_api_key", updated.openaiApiKey);
@@ -85,8 +85,10 @@ void registerProjectSettingsRoutes(ApiServer& s) {
             throw ApiError(ErrCode::Unprocessable, "embedding_base_requires_key",
                            "openai_api_base requires openai_api_key for the same project");
 
-        // No overrides left: drop the document so the project plainly inherits.
-        if (!updated.hasOverrides()) d->settings.removeProject(project);
+        // Nothing stored at all: drop the document so the project plainly
+        // inherits. hasAnyOverrides, not hasEmbeddingOverrides - clearing an
+        // embedding override must not take a function policy with it.
+        if (!updated.hasAnyOverrides()) d->settings.removeProject(project);
         else if (!d->settings.saveProject(updated))
             throw ApiError(ErrCode::Unavailable, "db_error", "could not save project settings");
 

+ 24 - 8
src/project_settings.cpp

@@ -1,28 +1,39 @@
 #include "project_settings.hpp"
 #include "collection_registry.hpp"
+#include "function_record.hpp"
 #include "settings.hpp"
 
 namespace svapi {
 
-ProjectEmbeddingSettings ProjectEmbeddingSettings::fromJson(const nlohmann::json& j) {
-    ProjectEmbeddingSettings p;
+ProjectSettings ProjectSettings::fromJson(const nlohmann::json& j) {
+    ProjectSettings p;
     p.project               = j.value("project", p.project);
     p.openaiApiBase         = j.value("openai_api_base", p.openaiApiBase);
     p.openaiApiKey          = j.value("openai_api_key", p.openaiApiKey);
     p.defaultEmbeddingModel = j.value("default_embedding_model", p.defaultEmbeddingModel);
+    // Absent and present-but-empty are different: an absent key means "inherit
+    // the built-in floor", while a stored empty object is an admin deliberately
+    // saying "a new function here gets nothing". Both deny, but only the second
+    // survives a change to the built-in default.
+    if (j.contains("default_function_policy") && j.at("default_function_policy").is_object())
+        p.defaultFunctionPolicy = KeyScope::fromJson(j.at("default_function_policy"));
     return p;
 }
 
-nlohmann::json ProjectEmbeddingSettings::toJson() const {
-    return {{"project", project},
-            {"openai_api_base", openaiApiBase},
-            {"openai_api_key", openaiApiKey},
-            {"default_embedding_model", defaultEmbeddingModel}};
+nlohmann::json ProjectSettings::toJson() const {
+    nlohmann::json j = {{"project", project},
+                        {"openai_api_base", openaiApiBase},
+                        {"openai_api_key", openaiApiKey},
+                        {"default_embedding_model", defaultEmbeddingModel}};
+    // Written only when set, so round-tripping a project that never configured
+    // one does not quietly pin today's built-in default into storage.
+    if (defaultFunctionPolicy) j["default_function_policy"] = defaultFunctionPolicy->toJson();
+    return j;
 }
 
 std::string projectSettingsDocId(const std::string& project) { return "project_" + project; }
 
-ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectEmbeddingSettings* proj,
+ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectSettings* proj,
                                    const CollectionMeta& coll) {
     ResolvedEmbedding r{global.openaiApiBase, global.openaiApiKey, global.defaultEmbeddingModel};
     if (proj) {
@@ -34,4 +45,9 @@ ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectEmbeddin
     return r;
 }
 
+KeyScope defaultFunctionPolicyFor(const ProjectSettings* proj) {
+    if (proj && proj->defaultFunctionPolicy) return *proj->defaultFunctionPolicy;
+    return builtinDefaultFunctionPolicy();
+}
+
 } // namespace svapi

+ 29 - 6
src/project_settings.hpp

@@ -1,5 +1,7 @@
 #pragma once
+#include "apikey.hpp"
 #include <nlohmann/json.hpp>
+#include <optional>
 #include <string>
 
 namespace svapi {
@@ -7,7 +9,8 @@ namespace svapi {
 struct Settings;
 struct CollectionMeta;
 
-/// Per-project embedding overrides. An empty field means "inherit the global
+/// Per-project settings: embedding overrides, and the policy a newly
+/// registered function inherits. An empty field means "inherit the global
 /// value" - there is no separate presence flag, because an empty base URL, API
 /// key or model is meaningless on its own.
 ///
@@ -15,23 +18,38 @@ struct CollectionMeta;
 /// `vectorapi_settings` collection under projectSettingsDocId(project). The DB
 /// client strips a top-level `id` from stored bodies, so the project name also
 /// travels in the body as `project` (same approach as KeyStore's `key_id`).
-struct ProjectEmbeddingSettings {
+struct ProjectSettings {
     std::string project;
     std::string openaiApiBase;
     std::string openaiApiKey;
     std::string defaultEmbeddingModel;
 
-    /// True when at least one field overrides the global value.
-    bool hasOverrides() const {
+    /// The policy a function gets on FIRST registration in this project.
+    /// Unset means fall back to builtinDefaultFunctionPolicy(), which grants
+    /// nothing. Only ever consulted for a first registration - an existing
+    /// function keeps the policy an admin gave it, so changing this never
+    /// retroactively widens or narrows anything already deployed.
+    std::optional<KeyScope> defaultFunctionPolicy;
+
+    /// True when at least one EMBEDDING field overrides the global value.
+    bool hasEmbeddingOverrides() const {
         return !openaiApiBase.empty() || !openaiApiKey.empty() || !defaultEmbeddingModel.empty();
     }
 
+    /// True when the project has anything stored at all. The settings document
+    /// is deleted when this goes false, so it has to account for every field:
+    /// keying the delete on the embedding fields alone would silently drop a
+    /// function policy the moment someone cleared an embedding override.
+    bool hasAnyOverrides() const {
+        return hasEmbeddingOverrides() || defaultFunctionPolicy.has_value();
+    }
+
     /// A project base URL must carry its own API key, otherwise the global
     /// credential would be sent to a foreign endpoint. A project key without a
     /// base URL is fine (own key, default endpoint).
     bool baseHasItsOwnKey() const { return openaiApiBase.empty() || !openaiApiKey.empty(); }
 
-    static ProjectEmbeddingSettings fromJson(const nlohmann::json& j);
+    static ProjectSettings fromJson(const nlohmann::json& j);
     nlohmann::json toJson() const;
 };
 
@@ -50,7 +68,12 @@ struct ResolvedEmbedding {
 ///   apiBase / apiKey : project override, else global.
 ///   model            : collection pin, else project override, else global default.
 /// `proj` may be null when the project has no overrides stored.
-ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectEmbeddingSettings* proj,
+ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectSettings* proj,
                                    const CollectionMeta& coll);
 
+/// The policy a first-time function registration in this project inherits:
+/// the project's configured default, else the built-in floor. `proj` may be
+/// null when the project has nothing stored.
+KeyScope defaultFunctionPolicyFor(const ProjectSettings* proj);
+
 } // namespace svapi

+ 3 - 3
tests/test_api_integration.cpp

@@ -1282,7 +1282,7 @@ std::string projSettingsPath(const std::string& project) {
 }
 }  // namespace
 
-TEST_F(ApiFixture, ProjectEmbeddingSettingsDefaultToInherited) {
+TEST_F(ApiFixture, ProjectSettingsDefaultToInherited) {
     auto c = admin();
     auto r = c.Get(projSettingsPath(project_).c_str());
     ASSERT_EQ(r->status, 200);
@@ -1344,14 +1344,14 @@ TEST_F(ApiFixture, ProjectOverrideClearedWithExplicitNull) {
     EXPECT_EQ(j["overrides"]["default_embedding_model"], "");
 }
 
-TEST_F(ApiFixture, ProjectEmbeddingSettingsRejectEmptyStringValues) {
+TEST_F(ApiFixture, ProjectSettingsRejectEmptyStringValues) {
     auto c = admin();
     auto r = c.Put(projSettingsPath(project_).c_str(),
         nlohmann::json{{"default_embedding_model", ""}}.dump(), "application/json");
     EXPECT_EQ(r->status, 422);
 }
 
-TEST_F(ApiFixture, ProjectEmbeddingSettingsAuthorization) {
+TEST_F(ApiFixture, ProjectSettingsAuthorization) {
     auto c = admin();
     // A plain (non-admin, unscoped) key granted this project may manage it.
     auto mk = c.Post("/api/v1/keys",

+ 6 - 0
tests/test_errors.cpp

@@ -48,3 +48,9 @@ TEST(Errors, ErrorBodyOmitsEmptyDetails) {
     auto body = svapi::errorBody("validation", "bad");
     EXPECT_FALSE(body["error"].contains("details"));
 }
+
+TEST(Errors, GatewayTimeoutIsFiveOhFour) {
+    // Added for function dispatch: a function that blew its wall-time budget is
+    // an upstream that did not answer, not a slow client (which would be 408).
+    EXPECT_EQ(httpStatus(ErrCode::GatewayTimeout), 504);
+}

+ 64 - 15
tests/test_project_settings.cpp

@@ -21,23 +21,23 @@ CollectionMeta unpinnedCollection() {
 }  // namespace
 
 TEST(ProjectSettings, DefaultsAreAllEmptyMeaningInherit) {
-    ProjectEmbeddingSettings p = ProjectEmbeddingSettings::fromJson(nlohmann::json::object());
+    ProjectSettings p = ProjectSettings::fromJson(nlohmann::json::object());
     EXPECT_EQ(p.openaiApiBase, "");
     EXPECT_EQ(p.openaiApiKey, "");
     EXPECT_EQ(p.defaultEmbeddingModel, "");
-    EXPECT_FALSE(p.hasOverrides());
+    EXPECT_FALSE(p.hasEmbeddingOverrides());
 }
 
 TEST(ProjectSettings, RoundTripPreservesFields) {
     nlohmann::json j{{"openai_api_base", "https://api.mistral.ai"},
                      {"openai_api_key", "sk-proj"},
                      {"default_embedding_model", "mistral-embed"}};
-    ProjectEmbeddingSettings p = ProjectEmbeddingSettings::fromJson(j);
+    ProjectSettings p = ProjectSettings::fromJson(j);
     EXPECT_EQ(p.openaiApiBase, "https://api.mistral.ai");
     EXPECT_EQ(p.openaiApiKey, "sk-proj");
     EXPECT_EQ(p.defaultEmbeddingModel, "mistral-embed");
-    EXPECT_TRUE(p.hasOverrides());
-    EXPECT_EQ(ProjectEmbeddingSettings::fromJson(p.toJson()).toJson(), p.toJson());
+    EXPECT_TRUE(p.hasEmbeddingOverrides());
+    EXPECT_EQ(ProjectSettings::fromJson(p.toJson()).toJson(), p.toJson());
 }
 
 TEST(ProjectSettings, NoProjectOverrideResolvesToGlobal) {
@@ -50,7 +50,7 @@ TEST(ProjectSettings, NoProjectOverrideResolvesToGlobal) {
 
 TEST(ProjectSettings, EmptyProjectOverrideResolvesToGlobal) {
     Settings g = globalSettings();
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     ResolvedEmbedding r = resolveEmbedding(g, &p, unpinnedCollection());
     EXPECT_EQ(r.apiBase, "https://api.openai.com");
     EXPECT_EQ(r.apiKey, "sk-global");
@@ -59,7 +59,7 @@ TEST(ProjectSettings, EmptyProjectOverrideResolvesToGlobal) {
 
 TEST(ProjectSettings, ProjectBaseAndKeyOverrideGlobal) {
     Settings g = globalSettings();
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.openaiApiBase = "https://api.mistral.ai";
     p.openaiApiKey  = "sk-proj";
     ResolvedEmbedding r = resolveEmbedding(g, &p, unpinnedCollection());
@@ -71,7 +71,7 @@ TEST(ProjectSettings, ProjectBaseAndKeyOverrideGlobal) {
 TEST(ProjectSettings, ProjectKeyAloneKeepsGlobalBase) {
     // The metering case: a customer's own key billed against the default endpoint.
     Settings g = globalSettings();
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.openaiApiKey = "sk-customer";
     ResolvedEmbedding r = resolveEmbedding(g, &p, unpinnedCollection());
     EXPECT_EQ(r.apiBase, "https://api.openai.com");
@@ -80,7 +80,7 @@ TEST(ProjectSettings, ProjectKeyAloneKeepsGlobalBase) {
 
 TEST(ProjectSettings, ProjectModelOverridesGlobalDefault) {
     Settings g = globalSettings();
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.defaultEmbeddingModel = "text-embedding-3-large";
     ResolvedEmbedding r = resolveEmbedding(g, &p, unpinnedCollection());
     EXPECT_EQ(r.model, "text-embedding-3-large");
@@ -90,7 +90,7 @@ TEST(ProjectSettings, ProjectModelOverridesGlobalDefault) {
 
 TEST(ProjectSettings, CollectionModelPinBeatsProjectAndGlobal) {
     Settings g = globalSettings();
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.defaultEmbeddingModel = "text-embedding-3-large";
     CollectionMeta m = unpinnedCollection();
     m.embeddingModel = "bge-m3";
@@ -108,20 +108,20 @@ TEST(ProjectSettings, CollectionModelPinBeatsGlobalWithoutProject) {
 
 TEST(ProjectSettings, BaseWithoutKeyIsRejected) {
     // Guards the global credential: a foreign endpoint must carry its own key.
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.openaiApiBase = "https://api.mistral.ai";
     EXPECT_FALSE(p.baseHasItsOwnKey());
 }
 
 TEST(ProjectSettings, BaseWithKeyIsAccepted) {
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.openaiApiBase = "https://api.mistral.ai";
     p.openaiApiKey  = "sk-proj";
     EXPECT_TRUE(p.baseHasItsOwnKey());
 }
 
 TEST(ProjectSettings, KeyWithoutBaseNeedsNoPairing) {
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.openaiApiKey = "sk-customer";
     EXPECT_TRUE(p.baseHasItsOwnKey());
 }
@@ -134,9 +134,58 @@ TEST(ProjectSettings, DocIdIsDerivedFromProjectName) {
 TEST(ProjectSettings, JsonCarriesProjectNameBecauseDbStripsId) {
     // The DB client strips a top-level `id` from stored bodies, so the project
     // name has to live in the body itself (same trick as key_store's key_id).
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.project      = "acme";
     p.openaiApiKey = "sk-proj";
     EXPECT_EQ(p.toJson().value("project", ""), "acme");
-    EXPECT_EQ(ProjectEmbeddingSettings::fromJson(p.toJson()).project, "acme");
+    EXPECT_EQ(ProjectSettings::fromJson(p.toJson()).project, "acme");
+}
+
+// --------------------------------------------- default function policy
+
+TEST(DefaultFunctionPolicy, FallsBackToTheBuiltinFloorWhenUnset) {
+    const ProjectSettings p;
+    EXPECT_TRUE(defaultFunctionPolicyFor(&p).rules.empty());
+    EXPECT_TRUE(defaultFunctionPolicyFor(nullptr).rules.empty())
+        << "a project with nothing stored must still resolve to the floor";
+}
+
+TEST(DefaultFunctionPolicy, UsesTheProjectOverrideWhenSet) {
+    ProjectSettings p;
+    KeyScope s;
+    KeyScopeRule r;
+    r.collection = "kb_*";
+    r.ops = {KeyOp::Read, KeyOp::List};
+    s.rules.push_back(r);
+    p.defaultFunctionPolicy = s;
+
+    const KeyScope got = defaultFunctionPolicyFor(&p);
+    EXPECT_NE(got.findRule("kb_chunks", KeyOp::Read), nullptr);
+    EXPECT_EQ(got.findRule("kb_chunks", KeyOp::Delete), nullptr);
+}
+
+TEST(DefaultFunctionPolicy, AnEmptyStoredPolicyIsNotTheSameAsAbsent) {
+    // Both deny everything today, but a stored empty policy is an explicit
+    // decision that must survive a change to the built-in floor.
+    ProjectSettings p;
+    p.defaultFunctionPolicy = KeyScope{};
+    EXPECT_TRUE(p.hasAnyOverrides());
+    EXPECT_FALSE(p.hasEmbeddingOverrides());
+
+    const ProjectSettings back = ProjectSettings::fromJson(p.toJson());
+    EXPECT_TRUE(back.defaultFunctionPolicy.has_value());
+}
+
+TEST(ProjectSettings, APolicyOnlyProjectIsNotTreatedAsEmpty) {
+    // The embeddings handler deletes the settings document when the project has
+    // nothing stored. If that test used the embedding fields alone, clearing an
+    // embedding override would silently drop the function policy with it.
+    ProjectSettings p;
+    p.defaultFunctionPolicy = KeyScope{};
+    EXPECT_TRUE(p.hasAnyOverrides());
+}
+
+TEST(ProjectSettings, AnUnsetPolicyIsNotWrittenToStorage) {
+    const ProjectSettings p;
+    EXPECT_FALSE(p.toJson().contains("default_function_policy"));
 }

+ 4 - 4
tests/test_stores.cpp

@@ -86,7 +86,7 @@ TEST(SettingsStore, ProjectOverridesRoundTripThroughDb) {
     ss.bootstrap("");
     EXPECT_EQ(ss.projectSnapshot("acme"), nullptr);
 
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.project               = "acme";
     p.openaiApiBase         = "https://api.mistral.ai";
     p.openaiApiKey          = "sk-acme";
@@ -110,7 +110,7 @@ TEST(SettingsStore, ProjectOverridesSurviveAFreshStore) {
 
     SettingsStore ss(*db, coll);
     ss.bootstrap("");
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.project      = "acme";
     p.openaiApiKey = "sk-acme";
     ss.saveProject(p);
@@ -132,7 +132,7 @@ TEST(SettingsStore, RemoveProjectRevertsToInherit) {
 
     SettingsStore ss(*db, coll);
     ss.bootstrap("");
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.project      = "acme";
     p.openaiApiKey = "sk-acme";
     ss.saveProject(p);
@@ -152,7 +152,7 @@ TEST(SettingsStore, ProjectDocsDoNotCorruptGlobalSettings) {
 
     SettingsStore ss(*db, coll);
     ss.bootstrap("sk-global");
-    ProjectEmbeddingSettings p;
+    ProjectSettings p;
     p.project       = "acme";
     p.openaiApiBase = "https://api.mistral.ai";
     p.openaiApiKey  = "sk-acme";