Răsfoiți Sursa

fix: a taken document id is duplicate_id, not duplicate_values

AlreadyExists covers two different collisions and they have different
remedies: a unique FIELD value is taken, so change the value; or the document
ID you chose is taken, so pick another id or upsert with PUT. Both reported as
`duplicate_values`, which sent a caller looking for a field that was never the
problem. The database has set reason `duplicate_id` since 2.12.1 and we never
read it.

The mapping had NO unit tests, which is how it accumulated three reason
branches without anyone checking the table. test_db_errors.cpp now drives it
through the FailureDetail overload - plain data in, ApiError out, no database
needed - and covers the whole table: both AlreadyExists collisions, all three
FailedPrecondition reasons including read_only being 503 rather than the
caller's mistake, an unknown reason falling back to the broader answer instead
of guessing the narrower one, Aborted as 409, Ok meaning "did not apply", and
which codes carry the database's own message versus our phrasing.

Writing those tests corrected one of my own assumptions: NotFound deliberately
uses the route's message, not the database's, so the answer does not change if
the database rewords itself. The test now asserts that contract rather than the
one I assumed.

849/849 natively and in the Debian container, including 837/837 against a
database upgraded to 2.12.3 - so the error-shape changes in 2.12.1-2.12.3
break nothing here.
fszontagh 1 lună în urmă
părinte
comite
d801a255d5
5 a modificat fișierele cu 154 adăugiri și 5 ștergeri
  1. 1 1
      CLAUDE.md
  2. 1 1
      api/llms.txt
  3. 14 3
      src/db_errors.cpp
  4. 7 0
      tests/CMakeLists.txt
  5. 131 0
      tests/test_db_errors.cpp

+ 1 - 1
CLAUDE.md

@@ -107,7 +107,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **`patch` with a field set to null REMOVES the field** (RFC 7396 merge), it does not store null. Use `update` for an explicit null.
 - **Null and absent are both unconstrained on a unique index** since database 2.12.0 - only real values collide. Before that, two nulls collided.
 - **`relations_enforced` is readable since client 2.11.4** via `tryGetRelationsEnforced()`, which DECLINES to answer on a failed read rather than defaulting (`getRelationsEnforced()` is the fail-to-enforced variant, for code deciding whether it may rely on enforcement). The collection GET surfaces it, omitting the field when undetermined - absence never means disabled, so the web UI renders three states, not two.
-- **Database failures keep their classification** (`db_errors.hpp`, client 2.11.4). `Client::Error::code()` on the throwing calls and the `Failure&` overloads on `update`/`patch`/`remove` feed one `translate()`: AlreadyExists → 409 `duplicate_values`, FailedPrecondition → 422 `relation_violation`, NotFound → 404, Unavailable/DeadlineExceeded/Unknown → 503, everything else → 500. **`ErrorCode::Ok` on a call that returned false means "did not apply", not an error** - map it to 404, or a plain missing document becomes a 500 with an empty message.
+- **Database failures keep their classification** (`db_errors.hpp`, client 2.11.4). `Client::Error::code()` on the throwing calls and the `Failure&` overloads on `update`/`patch`/`remove` feed one `translate()`: AlreadyExists → 409 `duplicate_values`, or `duplicate_id` when `reason` says so (database 2.12.1: a taken document id and a taken unique field value are the same code but different remedies), FailedPrecondition → 422 `relation_violation`, NotFound → 404, Unavailable/DeadlineExceeded/Unknown → 503, everything else → 500. **`ErrorCode::Ok` on a call that returned false means "did not apply", not an error** - map it to 404, or a plain missing document becomes a 500 with an empty message.
 - **Document write bodies accept two shapes, via one reader.** `documentBody()` in `handlers/documents.cpp` is used by POST, PUT and PATCH: it unwraps `{"data":{...}}`, strips `id` (the document's identity, from the body on POST and from the URL on PUT/PATCH), and rejects `data` alongside any other top-level key with **422** `ambiguous_body`. Before 0.3.3 only POST unwrapped, so a `{"data":...}` PUT stored the wrapper as a literal field and a `data`-plus-siblings POST dropped the siblings silently. A literal top-level `data` field is still writable as `{"data":{"data":...}}`.
 - **QuickJS is pinned to an exact quickjs-ng tag** (`SVAPI_QUICKJS_TAG`, `runner/CMakeLists.txt`). QuickJS bytecode carries **no version stamp**, so a silent upgrade makes a cached blob *misread* rather than fail. quickjs-ng, not Bellard's tree: the module/promise/stack entry points the core needs (`JS_GetModuleNamespace`, `JS_PromiseState`, `JS_SetMaxStackSize`, `JS_IsJobPending`) are public API there. `JsBytecode` is an in-process cache only - never persist it without a QuickJS build fingerprint.
 - **QuickJS's job queue belongs to the `JSRuntime`, not the `JSContext`.** A fresh context per run is therefore *not* enough to isolate tenants: a run that times out mid-microtask leaves its jobs queued, and they would execute inside the next tenant's run. The core flushes them with the deadline forced into the past and marks the runtime `poisoned()` if anything survives; the pool destroys a poisoned runtime instead of leasing it out. An OOM poisons it too.

+ 1 - 1
api/llms.txt

@@ -67,7 +67,7 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 
 - `POST  /api/v1/projects/{project}/collections/{name}/documents` `{data:{...}}` or `{...}` - Insert a document. Returns `{id}`. Optional `?ttl_seconds=N` query param sets an expiry; absent means no expiry.
 
-  **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values` (the same slug `POST /indexes` returns), and `error.details` names the index: `field`, the colliding `value` when that field is at the top level of the body you sent, and `conflicting_document_id` (the document already holding it). A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A failed conditional write is **409** `version_conflict`. A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write.
+  **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values`, while a document **id** that is already taken is **409** `duplicate_id` (different remedies: change the value, versus choose another id or upsert with `PUT`) (the same slug `POST /indexes` returns), and `error.details` names the index: `field`, the colliding `value` when that field is at the top level of the body you sent, and `conflicting_document_id` (the document already holding it). A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A failed conditional write is **409** `version_conflict`. A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write.
 
   **Body shape (the same on POST, PUT and PATCH).** Send either the document wrapped as `{"data":{...}}` or the document on its own; both store identical content. `id` is never a field: POST reads the document id from the top level of the body, PUT and PATCH from the URL, and it is stripped from what gets stored. A `data` key next to any other top-level field (other than `id`) is **422** `ambiguous_body` rather than silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: `{"data":{"data":...}}`. The metadata fields below (`_id`, `_version`, `_created_at`, `_updated_at`, `_created_by`, `_updated_by`) are stripped from every write body, so you can read a document, edit a field and send the whole thing back without storing stale metadata as real fields.
 - `GET   /api/v1/projects/{project}/collections/{name}/documents/{id}` - Fetch a document by ID. The body is the stored document **plus the database's read-only metadata**: `_id`, `_version` (an integer, starting at 1 and incremented by every write), `_created_at`, `_updated_at` (epoch ms), `_created_by`, `_updated_by`. `_version` is the value `?if_version=` takes, and it is also returned as an `ETag` header. These names are reserved: a field of your own called `_version` cannot be stored or read back.

+ 14 - 3
src/db_errors.cpp

@@ -10,9 +10,12 @@ using Code = smartbotic::database::Client::ErrorCode;
 /// `duplicate_values` deliberately matches what POST /indexes already returns
 /// for the same condition, so a caller sees one slug for "this value is taken"
 /// however it was hit.
-/// `reason` is what disambiguates FailedPrecondition, which the database uses
-/// for three unrelated refusals. Empty means an older server, or a
-/// FailedPrecondition raised somewhere that does not set one.
+/// `reason` disambiguates TWO codes, not one: FailedPrecondition, which the
+/// database uses for three unrelated refusals, and AlreadyExists, which covers
+/// both a unique field collision and a taken document id. Empty means an older
+/// server, or a refusal raised somewhere that does not set one - and in both
+/// cases the fallback must be the broader answer, never a guess at the
+/// narrower one.
 ApiError translate(Code code, const std::string& message, const std::string& notFoundMessage,
                    const std::string& reason, const nlohmann::json& details) {
     switch (code) {
@@ -22,6 +25,14 @@ ApiError translate(Code code, const std::string& message, const std::string& not
         case Code::Ok:
             return ApiError(ErrCode::NotFound, "not_found", notFoundMessage);
         case Code::AlreadyExists:
+            // TWO different collisions share this code, and they have
+            // different remedies: a unique FIELD value is taken, so change the
+            // value; or the document ID you chose is taken, so choose another
+            // id or upsert with PUT. Reporting both as `duplicate_values` sent
+            // a caller looking for a field that was never the problem.
+            // `duplicate_id` is the reason the database sets since 2.12.1.
+            if (reason == "duplicate_id")
+                return ApiError(ErrCode::Conflict, "duplicate_id", message, details);
             // `details` carries the field that collided and the colliding
             // value, straight from the database. This used to be recovered by
             // taking the error SENTENCE apart, which broke the moment anyone

+ 7 - 0
tests/CMakeLists.txt

@@ -220,6 +220,13 @@ gtest_discover_tests(test_embed_budget)
 
 # fileNameRejection() is pure, but file_store.cpp also holds the store, which
 # links the database client - so this links vectorapi_core like the rest.
+# The database-failure mapping, driven through the FailureDetail overload: plain
+# data in, ApiError out, so no database is needed.
+add_executable(test_db_errors test_db_errors.cpp)
+target_include_directories(test_db_errors PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_db_errors PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_db_errors)
+
 add_executable(test_file_name test_file_name.cpp)
 target_include_directories(test_file_name PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_file_name PRIVATE vectorapi_core GTest::gtest_main)

+ 131 - 0
tests/test_db_errors.cpp

@@ -0,0 +1,131 @@
+#include "db_errors.hpp"
+#include <gtest/gtest.h>
+
+// The database-failure mapping. It had no tests at all until a third reason
+// branch went in, which is one branch too many for "it looked right".
+//
+// Driven through the FailureDetail overload because that struct is plain data:
+// the whole mapping is assertable with no database, no network and no clock,
+// and every one of these decisions is behaviour a caller depends on.
+namespace {
+
+using Detail = smartbotic::database::Client::FailureDetail;
+using Code = smartbotic::database::Client::ErrorCode;
+
+Detail detail(Code code, std::string reason = "", std::string message = "boom") {
+    Detail d;
+    d.code = code;
+    d.reason = std::move(reason);
+    d.message = std::move(message);
+    return d;
+}
+
+// --- AlreadyExists covers TWO different collisions --------------------------
+
+TEST(DbErrors, ADuplicateFieldValueIsDuplicateValues) {
+    const svapi::ApiError e = svapi::apiErrorFor(detail(Code::AlreadyExists));
+    EXPECT_EQ(svapi::httpStatus(e.code), 409);
+    EXPECT_EQ(e.slug, "duplicate_values");
+}
+
+TEST(DbErrors, ATakenDocumentIdIsDuplicateIdNotDuplicateValues) {
+    // Different remedies: a unique FIELD collision means change the value, a
+    // taken ID means choose another id or upsert with PUT. Reporting both as
+    // duplicate_values sent a caller looking for a field that was never the
+    // problem. The reason arrived with database 2.12.1.
+    const svapi::ApiError e = svapi::apiErrorFor(detail(Code::AlreadyExists, "duplicate_id"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 409);
+    EXPECT_EQ(e.slug, "duplicate_id");
+}
+
+TEST(DbErrors, AnUnknownAlreadyExistsReasonFallsBackToTheBroaderAnswer) {
+    // An older server sets no reason, and a future one may set a reason we do
+    // not know. Both must take the general answer rather than a guess at a
+    // specific one.
+    EXPECT_EQ(svapi::apiErrorFor(detail(Code::AlreadyExists, "")).slug, "duplicate_values");
+    EXPECT_EQ(svapi::apiErrorFor(detail(Code::AlreadyExists, "something_new")).slug,
+              "duplicate_values");
+}
+
+// --- FailedPrecondition means three unrelated things ------------------------
+
+TEST(DbErrors, MissingParentAndRestrictedDeleteAreUnprocessable) {
+    for (const char* reason : {"missing_parent", "delete_restricted"}) {
+        const svapi::ApiError e = svapi::apiErrorFor(detail(Code::FailedPrecondition, reason));
+        EXPECT_EQ(svapi::httpStatus(e.code), 422) << reason;
+        EXPECT_EQ(e.slug, "relation_violation") << reason;
+    }
+}
+
+TEST(DbErrors, AReadOnlyDatabaseIs503NotTheCallersMistake) {
+    // The one that mattered: mapping the bare code to 422 told a caller that a
+    // read-only database was its own validation error, so it would fix its
+    // payload and retry forever instead of waiting.
+    const svapi::ApiError e = svapi::apiErrorFor(detail(Code::FailedPrecondition, "read_only"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 503);
+    EXPECT_EQ(e.slug, "read_only");
+}
+
+TEST(DbErrors, AnUnknownFailedPreconditionReasonIs500NotAGuessedFourTwentyTwo) {
+    // Three unrelated refusals share the code, so with no reason we genuinely
+    // do not know - and 500 says "we do not know" where 422 would assert the
+    // caller was wrong.
+    for (const char* reason : {"", "something_new"}) {
+        const svapi::ApiError e = svapi::apiErrorFor(detail(Code::FailedPrecondition, reason));
+        EXPECT_EQ(svapi::httpStatus(e.code), 500) << "reason='" << reason << "'";
+    }
+}
+
+// --- the rest of the table --------------------------------------------------
+
+TEST(DbErrors, AVersionConflictIs409AndSaysSo) {
+    // Arrived as Unknown before 2.12.0 and folded into 503 "retry as-is",
+    // which is the opposite of the required instruction: re-read first.
+    const svapi::ApiError e = svapi::apiErrorFor(detail(Code::Aborted, "version_conflict"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 409);
+    EXPECT_EQ(e.slug, "version_conflict");
+}
+
+TEST(DbErrors, NotFoundIs404) {
+    EXPECT_EQ(svapi::httpStatus(svapi::apiErrorFor(detail(Code::NotFound)).code), 404);
+}
+
+TEST(DbErrors, TransportFailuresAre503) {
+    for (const Code c : {Code::Unavailable, Code::DeadlineExceeded, Code::Unknown})
+        EXPECT_EQ(svapi::httpStatus(svapi::apiErrorFor(detail(c)).code), 503)
+            << static_cast<int>(c);
+}
+
+TEST(DbErrors, OkMeansDidNotApplyWhichIsA404) {
+    // A call that returned false while the database raised nothing: the
+    // document was simply not there. Mapping this to 500 turned a plain
+    // missing document into a server fault with an empty message.
+    const svapi::ApiError e = svapi::apiErrorFor(detail(Code::Ok, "", ""), "no such document");
+    EXPECT_EQ(svapi::httpStatus(e.code), 404);
+    EXPECT_EQ(e.what(), std::string("no such document"))
+        << "the empty database message must not be surfaced in place of ours";
+}
+
+TEST(DbErrors, NotFoundUsesOurMessageNotTheDatabasesWording) {
+    // Deliberate: the caller gets the route's own phrasing for a missing
+    // document, so the answer does not change if the database rewords itself.
+    const svapi::ApiError e = svapi::apiErrorFor(detail(Code::NotFound, "", "no row 7"),
+                                                 "no such document");
+    EXPECT_EQ(e.what(), std::string("no such document"));
+}
+
+TEST(DbErrors, TheDatabaseMessageIsCarriedThroughWhereItIsTheUsefulOne) {
+    // For a validation refusal the database knows WHY and we do not, so its
+    // sentence is the one worth showing.
+    const svapi::ApiError bad =
+        svapi::apiErrorFor(detail(Code::InvalidArgument, "", "field 'x' is not a number"));
+    EXPECT_EQ(svapi::httpStatus(bad.code), 422);
+    EXPECT_EQ(bad.what(), std::string("field 'x' is not a number"));
+
+    const svapi::ApiError denied =
+        svapi::apiErrorFor(detail(Code::PermissionDenied, "", "collection is read-protected"));
+    EXPECT_EQ(svapi::httpStatus(denied.code), 403);
+    EXPECT_EQ(denied.what(), std::string("collection is read-protected"));
+}
+
+} // namespace