Преглед изворни кода

feat: report the filtered match total the listing was already computing SV-127

The documents listing now answers `{documents, count, has_more, total}`.
`count` is unchanged and still the page size; `total` is the exact number of
rows matching the filters, computed by the database before pagination.

It costs nothing. `findWithMetrics` issues the identical single `Find` RPC with
a byte-identical request (client.cpp:964 against :1033 at the 2.20.0 pin) -
`find` simply drops two fields of the response on the floor. So this is a
discard being stopped, not a capability being added, and the same shape as the
files listing, whose `has_more`/`total` were discarded for a release.

Measured with a consumer 2026-11-20: the only way to learn that number was to
page the whole matching set, and for one real filter on a 13,093-row collection
that is a full scan plus 1750 documents of encoding to obtain one integer. A
customer-facing review portal had just dropped its result count as unaffordable,
for a number arriving in every response it already made.

Three decisions worth not rediscovering:

- `has_more`/`total`, matching files.cpp rather than the database's own
  `total_count` wire name. Two spellings for one concept across two of our own
  listing routes is how the next drift starts.
- `count` KEPT with its original meaning rather than redefined in place, the
  same additive discipline `details.unsupported` kept.
- Emitted UNCONDITIONALLY - unfiltered, empty, last page - so an absent field
  means exactly one thing, an older server.

The tests assert PRESENCE before value in every arm, and that is the one thing
the falsification taught rather than confirmed: reverting the handler first made
them ABORT, because `operator[]` on a missing key asserts inside nlohmann and
kills the binary - which in a suite that must run serially would take every
later test with it and report a regression as a crash. With the guards it
reports "the listing stopped reporting `total`" and the suite continues. The
three numbers in the main test are deliberately distinct (page 2, match total 4,
collection 7) so confusing any pair of them fails.

api/llms.txt and openapi.json also now document what a caller could previously
only learn by experiment, which is the larger half of this change: `limit` does
NOT bound the server's work (the whole match set is built and sorted before
pagination, measured identical at limit=1 and limit=1000), omitting `limit`
gives 100 rows rather than all of them, `sort` sorts the entire match set, and a
filter is index-accelerated only below ~10% selectivity - with the worked prod
example where two filters at 52% and 27% are each declined, and their 13.4%
intersection is declined too.

1410/1410 tests pass, serially, zero pending build steps before ctest.
fszontagh пре 1 недеља
родитељ
комит
861c6cf829
4 измењених фајлова са 139 додато и 4 уклоњено
  1. 6 1
      api/llms.txt
  2. 10 1
      api/openapi.json
  3. 41 2
      src/handlers/documents.cpp
  4. 82 0
      tests/test_api_integration.cpp

+ 6 - 1
api/llms.txt

@@ -134,7 +134,12 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 
   **It requires the document to exist** (**404** otherwise) and never creates one: the starting document is yours to describe. The idiom for a counter that may not exist yet is: increment; on **404** `POST .../documents` the document under a fixed `id` with its starting values; on **409** `duplicate_values` (someone else just created it) increment again.
 - `DELETE /api/v1/projects/{project}/collections/{name}/documents/{id}` - Delete a document. Returns **409** `relation_restricted` (with `error.details.impacts`) if a restrict relation has children referencing it; see delete-impact below to preview this first.
-- `GET   /api/v1/projects/{project}/collections/{name}/documents` - Find documents. Every row carries the same `_id`/`_version` metadata a single GET returns, so a filtered listing is a usable starting point for a conditional write without a second request per row.
+- `GET   /api/v1/projects/{project}/collections/{name}/documents` - Find documents. Returns `{documents, count, has_more, total}`. Every row carries the same `_id`/`_version` metadata a single GET returns, so a filtered listing is a usable starting point for a conditional write without a second request per row.
+  **`count` is the PAGE size; `total` is the exact number of rows matching your filters.** Both `has_more` and `total` are new in 0.18.2 and are emitted unconditionally, so an absent field means an older server and never "nothing to report". `total` is computed by the database before pagination and is exact rather than an estimate - it is not capped by `limit`, and it answers a multi-field filter, which nothing else here can: `indexes/{field}/values` counts ONE field over the whole collection. Before 0.18.2 the only way to get this number was to page the entire matching set, and one consumer measured that as a full scan plus 1750 documents of encoding to obtain a single integer, which is why their review portal shipped without a result count.
+  **`limit` DOES NOT BOUND THE SERVER'S WORK, and the natural assumption is the opposite.** The database builds the whole match set, sorts it, and only then applies `offset`/`limit`, so `limit=20` and `limit=1000` scan identically. What `limit` saves is materialising and encoding the rows you did not ask for - which is real and is usually the whole cost (one consumer's queue screen went from 2.9 s to 453 ms by stopping at a page), but it means a narrow filter does not make a read cheaper and a small page is not a cheap query. Measured 2026-11-20 against a 13,093-row collection: the same predicate at `limit=1` and at `limit=1000` costs the same server-side.
+  **Omitting `limit` gives you 100 rows, not every row.** A sweep written without one stops at 100 and returns a clean short page, which is indistinguishable from a set that really holds 100 rows - so pass `limit` explicitly, and use `has_more` rather than a short page to decide whether to continue.
+  **A filter is index-accelerated only when it is genuinely selective, and "selective" means under ~10% of the collection.** Declaring an index does not make a filter on it cheap. The database picks, per VALUE rather than per field, the most selective indexed equality whose match count is under `rows/10`, and otherwise scans - because reading an index candidate costs a full document decode where a scan costs one parse, measured upstream at a ratio of ~8.6x, so a broad index plan is slower than scanning. It can also intersect two equalities, but only if the INTERSECTION clears the same bar. Worked example from prod: on 13,093 rows, `channel:eq:audio` matches 6,836 (52%) and `departmentKey:eq:ber` matches 3,520 (27%), so each is declined alone; together they match 1,750 (13.4%), which misses the 1,309-row threshold and is declined too, after paying to read and intersect 10,356 index entries. Filter ORDER is irrelevant - the planner measures each candidate's exact size first and takes the smallest - so there is nothing to tune by reordering. A field with few distinct values (a status, a boolean, a channel) will essentially never be index-served on its common values, only on its rare ones.
+  **`sort` sorts the entire match set, not your page.** Sorting a filter that matches 13,000 rows to show 20 of them is a 13,000-element sort on every request.
 - `GET   /api/v1/projects/{project}/collections/{name}/documents/{id}/delete-impact` - Preview what deleting this document would affect, without deleting it: `{would_be_blocked, impacts:[{relation, child_collection, child_field, on_delete, child_count, sample_child_ids, blocks}]}`. Read-only; follows the collection's read grant (a scoped key with a read rule may call it).
 
 **Filter grammar**: `field:op:value`, repeatable and ANDed. On documents it is the `?filter=` query param; on vector search it is the `filters` body array. The same grammar, operators and semantics apply to both, because the database evaluates them.

+ 10 - 1
api/openapi.json

@@ -1447,7 +1447,16 @@
                       }
                     },
                     "count": {
-                      "type": "integer"
+                      "type": "integer",
+                      "description": "The number of rows in THIS PAGE, not the number matching the filters. See `total` for that. Kept with its original meaning rather than redefined, so existing callers are unaffected."
+                    },
+                    "has_more": {
+                      "type": "boolean",
+                      "description": "Whether rows matching the filters remain beyond this page. Emitted unconditionally, true or false, so an absent field means exactly one thing - a server older than 0.18.2 - and never \"nothing worth reporting\". Prefer this over a short page to decide whether to continue: omitting `limit` yields 100 rows, which is indistinguishable from a set that really holds 100."
+                    },
+                    "total": {
+                      "type": "integer",
+                      "description": "Exact number of rows matching the filters, computed by the database before pagination and NOT capped by `limit`. Nothing else here answers a multi-field filter: indexes/{field}/values counts one field over the whole collection. New in 0.18.2; before it, callers had to page an entire matching set to learn its size. Note `limit` does not bound the server's work - the whole match set is built and sorted before pagination - so this number is free, while a narrow filter does not make the read cheaper."
                     }
                   }
                 }

+ 41 - 2
src/handlers/documents.cpp

@@ -269,8 +269,47 @@ void registerDocumentRoutes(ApiServer& s) {
         // Each listed document carries the same `_id`/`_version` metadata a
         // single GET returns, so a filtered listing is a usable starting point
         // for a conditional write without a second round trip per row.
-        auto docs = d->db.client().find(t.qualified, opts);
-        sendJson(res, 200, {{"documents", docs}, {"count", docs.size()}});
+        //
+        // `findWithMetrics` RATHER THAN `find`, AND IT COSTS NOTHING. Both
+        // issue the identical single `Find` RPC with a byte-identical request
+        // (client.cpp:964 against :1033 at the 2.20.0 pin); `find` simply drops
+        // two fields of the response on the floor. The server computes both
+        // BEFORE pagination, so `total` is the exact number of rows matching
+        // the filters, not an estimate and not a page count.
+        //
+        // WHY IT MATTERS, measured with a consumer 2026-11-20: the only way to
+        // learn that number was to page the whole matching set, and for one
+        // real filter on a 13,093-row collection that is a full scan plus 1750
+        // documents of encoding to obtain one integer. A customer-facing review
+        // portal had just dropped its result count as unaffordable - for a
+        // number that was arriving in every response it already made and being
+        // discarded one frame short of the caller.
+        //
+        // `has_more` and `total`, matching the FILES listing (files.cpp) rather
+        // than the database's own `total_count` wire name. Two spellings for one
+        // concept across two of our own listing routes is exactly how the next
+        // drift starts, and this file already records what it costs when a
+        // caller learns a parameter's name on a sibling route.
+        //
+        // `count` is UNCHANGED and still the page size. Keeping it is the
+        // additive discipline `details.unsupported` kept: callers parse it
+        // today, and redefining a field in place is worse than adding two.
+        //
+        // Emitted UNCONDITIONALLY - unfiltered, empty, and on the last page -
+        // so an absent field means exactly one thing, a server older than this
+        // release. A flag present only when interesting is this codebase's most
+        // repeated trap.
+        //
+        // One asymmetry worth knowing before anyone extends this route:
+        // `findWithMetrics` has no `include_vector` parameter, where `find`
+        // grew one in 2.13.0. Behaviour is identical today because the 2-arg
+        // `find` defaults it to false and this listing never returned vectors,
+        // but "also return the vectors" cannot be built on this overload.
+        const auto page = d->db.client().findWithMetrics(t.qualified, opts);
+        sendJson(res, 200, {{"documents", page.documents},
+                            {"count", page.documents.size()},
+                            {"has_more", page.hasMore},
+                            {"total", page.totalCount}});
     });
 
     svr.Patch(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {

+ 82 - 0
tests/test_api_integration.cpp

@@ -5078,3 +5078,85 @@ TEST_F(ApiFixture, PatchReportsAnAbsentDocumentWithoutAnExistenceProbe) {
     EXPECT_EQ(body["v"], 1) << "the empty patch or the merge dropped an existing field";
     EXPECT_EQ(body["w"], 2);
 }
+
+// --- the documents listing's paging metadata ---------------------------------
+//
+// `total` and `has_more` are computed by the database BEFORE pagination and
+// were being discarded by our handler, which sent only `count` - the PAGE size.
+// A consumer therefore had to page an entire matching set to learn how big it
+// was, and one measured instance of that was a full scan plus 1750 documents of
+// encoding to obtain a single integer.
+
+TEST_F(ApiFixture, TheDocumentsListingReportsTheFILTEREDTotalNotThePageOrTheCollection) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","pagemeta"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/pagemeta/documents";
+    // SEVEN rows, FOUR of which match. Three distinct numbers - page 2, match
+    // total 4, collection 7 - so confusing any pair of them fails this test.
+    // With one shared number the assertions would pass under every mix-up.
+    for (const char* k : {"yes", "yes", "yes", "yes", "no", "no", "no"})
+        ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"flag", k}}.dump(),
+                         "application/json")->status, 201);
+
+    auto first = c.Get((docs + "?filter=flag:eq:yes&limit=2").c_str());
+    ASSERT_TRUE(first); ASSERT_EQ(first->status, 200);
+    const nlohmann::json a = nlohmann::json::parse(first->body);
+    // PRESENCE BEFORE VALUE, in every arm. Indexing a missing key with
+    // `operator[]` on a const json ASSERTS inside nlohmann and aborts the whole
+    // binary - which in a suite that must run serially would take every later
+    // test with it and report the regression as a crash rather than as a named
+    // failing assertion. Found by deliberately falsifying this test.
+    ASSERT_TRUE(a.contains("total")) << "the listing stopped reporting `total`";
+    ASSERT_TRUE(a.contains("has_more")) << "the listing stopped reporting `has_more`";
+    EXPECT_EQ(a["documents"].size(), 2u);
+    EXPECT_EQ(a["count"], 2) << "`count` must stay the PAGE size; callers parse it already";
+    EXPECT_EQ(a["total"], 4) << "the filtered match total, not the page (2) and not the "
+                                "collection (7)";
+    EXPECT_TRUE(a["has_more"].get<bool>());
+
+    // The PAIRING, and the half that makes `has_more` worth sending: the last
+    // page must say false while `total` is unchanged. Without this arm a
+    // handler hardcoding `true` would pass the assertion above.
+    auto last = c.Get((docs + "?filter=flag:eq:yes&limit=2&offset=2").c_str());
+    ASSERT_TRUE(last); ASSERT_EQ(last->status, 200);
+    const nlohmann::json b = nlohmann::json::parse(last->body);
+    ASSERT_TRUE(b.contains("total")); ASSERT_TRUE(b.contains("has_more"));
+    EXPECT_EQ(b["documents"].size(), 2u);
+    EXPECT_EQ(b["total"], 4);
+    EXPECT_FALSE(b["has_more"].get<bool>()) << "a full page and the LAST page must not look "
+                                               "identical - that was the original defect";
+
+    // Unfiltered, the total is the whole collection. Pins that the filter is
+    // what narrows `total`, rather than `total` happening to equal some
+    // constant this collection has.
+    auto all = c.Get((docs + "?limit=1").c_str());
+    ASSERT_TRUE(all); ASSERT_EQ(all->status, 200);
+    const nlohmann::json u = nlohmann::json::parse(all->body);
+    ASSERT_TRUE(u.contains("total"));
+    EXPECT_EQ(u["total"], 7);
+}
+
+TEST_F(ApiFixture, ThePagingFieldsArePRESENTEvenWhenNothingMatches) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","pagempty"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/pagempty/documents";
+    ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"flag","no"}}.dump(),
+                     "application/json")->status, 201);
+
+    auto r = c.Get((docs + "?filter=flag:eq:nothingmatchesthis").c_str());
+    ASSERT_TRUE(r); ASSERT_EQ(r->status, 200);
+    const nlohmann::json body = nlohmann::json::parse(r->body);
+    // KEY PRESENCE is the assertion, not the value. It is what makes "the field
+    // is absent" mean exactly one thing - a server older than this release -
+    // rather than also meaning "there was nothing interesting to report". A
+    // field emitted only when true is this codebase's most repeated trap.
+    ASSERT_TRUE(body.contains("total"));
+    ASSERT_TRUE(body.contains("has_more"));
+    EXPECT_EQ(body["total"], 0);
+    EXPECT_FALSE(body["has_more"].get<bool>());
+    EXPECT_TRUE(body["documents"].empty());
+}