Jelajahi Sumber

fix: refuse an unhonoured query param on every listing route, not just one

#72 fixed the index-values route and left six siblings answering 200 to a
parameter they could not honour - the instance-not-the-class mistake that
defect is itself the specimen of. `requireHonourableParams()` now covers
documents, collections, files, export, the function run log and schema
suggest, and indexes.cpp is converted to it so there is one idiom.

The candidate lists are mostly this API's OWN other spellings, which is what
makes them non-hypothetical: /documents takes sort+desc, index-values takes
order=desc, /collections searches with q while /documents filters with
filter, and the export takes vector_format where `format` is the obvious
guess. `?format=base64` on the export was ignored, silently producing the
array export at roughly three times the bytes - and looking like it worked.
`details.instead` names the local spelling.

An incidental parameter is still ignored, deliberately, and a test asserts
it: a blanket refusal would break callers over cache-busters and proxy
additions that never asked for behaviour. That test was deliberately
falsified by adding `_` to a candidate list and confirming it goes red.

`details.unsupported` keeps the flat-array shape 0.13.0 published; the
replacements arrive as a separate `details.instead` map rather than
reshaping a live field one release after shipping it.

Checks are now ordered the same way everywhere - authorize, server
capability (501), request (422), resource (404) - so a misspelled parameter
no longer hides behind a 404 on the run log.

Also: the files listing was DISCARDING has_more/total_count, which the
client already returns, so a full page and the last page were identical.
Both are now emitted unconditionally as has_more/total.

1267/1267 green. api/llms.txt and api/openapi.json updated.
fszontagh 1 bulan lalu
induk
melakukan
30d32b8781

+ 8 - 1
CLAUDE.md

@@ -85,8 +85,15 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A blocking host call cannot be interrupted, so host timeouts ARE the enforcement.** The wall budget is enforced by a QuickJS interrupt handler that fires between bytecode ops; while an embedding or `ctx.fetch` request is in flight the engine never regains control, so the deadline is noticed only once the call returns. Bounding a host call therefore means handing the HTTP client timeouts that already fit the remaining budget - which is what `resolveEmbedBudget()` (`functions/embed_budget.hpp`, pure) does. It exists because a 10 s-budget run took **14314 ms**: the READ timeout was clamped to the budget and the CONNECT timeout was not, and the two are additive, so a connect stall burned the full `embedding_connect_timeout_sec` outside the budget. Connect gets at most HALF the available time (a reachable provider connects in well under a second, and a large connect allowance only starves the read phase). Below a 2 s budget the 1 s floor on each phase dominates and the worst case is 2 s - bounded, and stated rather than glossed over.
 - **Embedding timeouts are per-project and NARROWING ONLY**, resolved by the same `resolveEmbedding()` that picks the endpoint, so a project's override applies identically to a function and to an HTTP vector route. The effective value is `min(project, global)`: these govern a shared provider connection and a pooled runtime waiting on it, so an override that could RAISE them would let one tenant hold both longer than the operator allowed. A stored value above the global is kept rather than refused - it becomes effective if the global is later lowered. A zero override is "unset", never "no timeout", because 0 means no timeout to the HTTP client and that is precisely the unbounded call the split prevents.
 - **THE FUNCTION SURFACE NEEDED THE SAME FIX, AND NEEDED IT MORE.** `.search()`/`.store()` build their payload in `host_prelude.js` from an EXPLICIT key list, so an unrecognised option is discarded in the prelude **before the host can ever see it** - the host cannot refuse what never arrives, so a host-side check is no protection at all there. That is precisely how `embedTimeoutMs` came to be honoured host-side and never sent by the prelude while a consumer was told a bound was in force. `onlyKnownKeys()` (renamed from `mailOnlyKeys`, since the job is not mail's) now refuses by name in the prelude, and `expectRefused()` asserts the host was never reached rather than only that something threw. A consumer's call sites were ALL on this surface and none on the HTTP route, so fixing only the route would have left the real callers exposed while looking finished.
-- **THAT FIX WAS APPLIED TO ONE HANDLER AND NOT TO THE CLASS, AND A SIBLING IS STILL BROKEN.** Audited 2026-10-13: `unknownKeys()` is called in exactly ONE place service-wide, `handlers/vectors.cpp:121`, on the search BODY. **Six handler files read query parameters and none of them refuse an unknown one** (`indexes`, `files`, `collections`, `documents`, `export`, `functions`). The live consequence a consumer measured: `GET .../indexes/{field}/values?offset=1000` answers **200 with the first page**, because the handler reads only `limit` and `order` and the client has no offset parameter to honour. A caller paginating that route loops forever believing it is progressing - see task #72.
+- **THAT FIX WAS APPLIED TO ONE HANDLER AND NOT TO THE CLASS, AND A SIBLING WAS LEFT BROKEN** (CLOSED 2026-10-13, and the lesson is kept because the shape recurs). Audited 2026-10-13: `unknownKeys()` is called in exactly ONE place service-wide, `handlers/vectors.cpp:121`, on the search BODY. **Six handler files read query parameters and none of them refuse an unknown one** (`indexes`, `files`, `collections`, `documents`, `export`, `functions`). The live consequence a consumer measured: `GET .../indexes/{field}/values?offset=1000` answers **200 with the first page**, because the handler reads only `limit` and `order` and the client has no offset parameter to honour. A caller paginating that route loops forever believing it is progressing - see task #72.
   **The general form, which a consumer put better than I did: a fix applied in the handler where the lesson was LEARNED, rather than to the CLASS of handler, is how one correction leaves its siblings broken - and the silent-wrong-answer family is the one where nobody notices the sibling, because every sibling answers 200.** When a defect of this kind is fixed, grep for the shape rather than patching the instance.
+  **CLOSED: `requireHonourableParams()` (`query_params.hpp`) now covers all seven listing routes and `indexes.cpp` was converted to it, so there is one idiom rather than two.** Three things in that fix are worth keeping rather than rediscovering:
+  - **The candidate lists are mostly OUR OWN other routes' spellings, which is what makes them non-hypothetical.** `/documents` takes `sort`+`desc=true`, index-values takes `order=desc`, `/collections` searches with `q` while `/documents` filters with `filter`, and the export takes `vector_format` where `format` is the obvious guess. So the likeliest author of a plausible-but-ignored parameter is a caller who learned it on a SIBLING route of this same API - and `details.instead` names the local spelling. The costly one is the export: `?format=base64` was ignored, silently producing the ARRAY export at roughly three times the bytes, which looks like it worked.
+  - **`details.unsupported` KEPT its flat-array shape from 0.13.0 and the replacements arrived as a separate `details.instead` map.** Turning each entry into an object would have been tidier and would have broken anyone already parsing the field one release after it shipped - the same additive-not-reshaped discipline as the `FailureDetail&` overloads.
+  - **The ordering is now one rule everywhere: authorize, then the server's own capability (501), then the REQUEST (422), then the resource (404).** The run log refused `?status=failed` only after its 404, so the answer depended on whether the function existed; the export's check had to be split out of `parseExportQuery` to get above the registry lookup, since the refusal needs no metadata. A request-level fault that no amount of creating the resource fixes should not hide behind the resource.
+  **And the audit found a SECOND instance of the absent-flag defect, in the same family as the missing `truncated`: the files listing was DISCARDING `has_more` and `total_count`, which the client already returns.** A full page and the last page were byte-identical, so a caller could not tell whether to ask for the next one - and unlike index-values, the information was in hand and thrown away rather than unavailable. Now emitted unconditionally as `has_more`/`total`. Note its newest-first sort is applied WITHIN a page, after paging, so it is not a stable global order to page through; the route refuses `sort` rather than implying one.
+  **Two of my own mistakes in doing it, both caught by assertions rather than by review.** A scripted edit on an anchor that appears in several near-identical function handlers silently landed in the wrong one - the trap this file already records for the `network_egress` edit - and was only visible because the next attempt asserted the shape it expected before moving anything. And the falsifiability-pairing test (`NoListingRouteRefusesAnIncidentalParameter`, which proves the refusal is SELECTIVE rather than blanket) first failed because it leaned on a collection another test created, so it passed or failed on ctest ordering. It was then deliberately falsified by adding `_` to a candidate list and confirming it goes red - because a test asserting "this is NOT refused" is exactly the kind that can quietly stop testing anything.
+
   **But the query string CANNOT take the body's blanket treatment, and that is why this needs design rather than a copy-paste.** Every key in a JSON body is deliberate, so refusing all unknowns is safe. A query string legitimately collects things nobody meant as options - a cache-buster, a proxy's addition, a UI's `_=<timestamp>` - so a blanket 422 would break callers for params that were never asking for behaviour. The defensible line is to refuse the params a caller plausibly sends EXPECTING AN EFFECT and that we do not implement (`offset`, `page`, `cursor`, `sort`, `fields`), and to keep ignoring genuinely incidental ones. Refusing `offset` is the point; refusing `_=1760000000` is a regression.
 - **An unknown key on a vector `/search` body is REFUSED (422 `unknown_option`), not ignored** (`functions/known_keys.hpp`, pure). It was ignored until 0.10.3, and measured on prod that produced silently wrong answers rather than errors: `topK: 3` returned the DEFAULT five rows, `minScore: 0.99` returned rows where the correct spelling returns none, and **`filter:` in the singular returned the rows the caller meant to EXCLUDE** - a dropped filter is frequently a tenancy boundary in the caller's mind, which is what makes this a defect and not an ergonomic wish. Every unrecognised key is named at once, and the accepted set is listed, because the usual cause is a plausible spelling of a real option. Matching is exact and case-sensitive on purpose: accepting `Top_K` would give the service two spellings for one option, which is how the next drift starts. `ctx.fetch`, `ctx.mail` and `ctx.jobs` already behaved this way; this brought the HTTP surface in line.
 - **`embedTimeoutMs` on `.search()`/`.store()` is validated, not coerced.** A non-integer or non-positive value is 422, and exceeding it is **504** `embedding_timeout` (distinct from the run simply running out of budget, because the remedies differ). It went unnoticed for a release while being silently accepted and ignored, which is exactly why an unsupported option must be refused rather than dropped.

+ 11 - 2
api/llms.txt

@@ -96,7 +96,7 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 
   **Conditional writes: `?if_version=N`** on PUT and PATCH. The write applies only if the document is still at version `N`; otherwise **409** `version_conflict` with `error.details.expected_version` and, when it can be read, `error.details.current_version`. Read `_version` from a GET or from a `?filter=` listing, write with `?if_version=` that value, and retry from a fresh read on 409. `N` must be a positive integer (**422** `validation` otherwise; versions start at 1, so `if_version=0` is not "must not exist"). A conditional write never creates: `?if_version=` on an absent document is **404**, on PUT as well as PATCH. On PATCH it cannot be combined with `?ttl_seconds=` (**422** `conditional_unsupported`): the version-checked write has no expiry field, and silently dropping one of the two would be worse than refusing. It IS available on a `kind=vector` collection - a conditional PATCH is a server-side MERGE and preserves the stored embedding (measured). What is refused there is a whole-document **replace**: see `PUT` below.
 - `POST  /api/v1/projects/{project}/collections/{name}/documents/{id}/increment` `{field: n, ...}` (or `{data:{...}}`) - **Atomic increment.** Adds each number to the named field in ONE locked server-side read-modify-write, so concurrent increments cannot lose each other. Dotted keys address nested fields (`counts.sent`). Returns **200** `{id, values}` where `values` holds the NEW value of every field you named. An absent or null field counts as 0. Integer + integer stays an integer (overflow is refused); anything else becomes a double. A field holding a non-number is **422** `validation` and **nothing at all is applied** - the whole set applies or none of it does. Needs the `update` grant (it is a write, so a read-only scope gets **403**); it is a separate route rather than a flag on PATCH because `{"calls":1}` means "set calls to 1" on PATCH and "add 1 to calls" here.
-- `GET   /api/v1/projects/{project}/collections/{name}/export` - **Streaming backup, including stored vectors.** Answers **NDJSON** (`application/x-ndjson`): one JSON object per line, so the LINE is the unit of recovery and a truncated download loses the last row rather than the file. First line `{type:'header', collection, snapshot_at, vector_dimension, vector_dtype, rows_at_snapshot, batch_rows_cap, max_stream_seconds, include_vectors, vector_format}` (`snapshot_at` is server epoch seconds - "as of when" is the first question anyone asks of a backup, and a filesystem mtime does not survive a copy); then `{type:'row', id, document, vector_state, vector|vector_b64}` per document - **the vector field is named `vector` (a JSON array) with `vector_format=array`, and `vector_b64` (base64 of float32-little-endian) with `vector_format=base64`.** Handle BOTH names: a consumer who read only `vector` and exported as base64 saw a row reporting `vector_state: present` with no `vector` key, which looks exactly like the data loss `vector_state` exists to report; then `{type:'trailer', rows_sent, last_id, complete, content_sha256}`. **`content_sha256` is over each row's id and its RAW VECTOR BYTES, not over the emitted text**, so it is IDENTICAL whichever `vector_format` you asked for - you can export as base64, restore, re-export as an array and still compare digests. It is omitted rather than empty if it could not be computed.
+- `GET   /api/v1/projects/{project}/collections/{name}/export` - **Streaming backup, including stored vectors.** Answers **NDJSON** (`application/x-ndjson`): one JSON object per line, so the LINE is the unit of recovery and a truncated download loses the last row rather than the file. First line `{type:'header', collection, snapshot_at, vector_dimension, vector_dtype, rows_at_snapshot, batch_rows_cap, max_stream_seconds, include_vectors, vector_format}` (`snapshot_at` is server epoch seconds - "as of when" is the first question anyone asks of a backup, and a filesystem mtime does not survive a copy); then `{type:'row', id, document, vector_state, vector|vector_b64}` per document - **the vector field is named `vector` (a JSON array) with `vector_format=array`, and `vector_b64` (base64 of float32-little-endian) with `vector_format=base64`.** Handle BOTH names: a consumer who read only `vector` and exported as base64 saw a row reporting `vector_state: present` with no `vector` key, which looks exactly like the data loss `vector_state` exists to report; then `{type:'trailer', rows_sent, last_id, complete, content_sha256}`. **`content_sha256` is over each row's id and its RAW VECTOR BYTES, not over the emitted text**, so it is IDENTICAL whichever `vector_format` you asked for - you can export as base64, restore, re-export as an array and still compare digests. It is omitted rather than empty if it could not be computed. **`format` is NOT the parameter name and is now refused** - it used to be ignored, so `?format=base64` silently produced the ARRAY export, which for 12448 rows at dim 4096 is roughly three times the bytes and looks like it worked. The name is `vector_format`.
   **The exact construction, so you can recompute it rather than only echo it.** ONE rolling SHA-256 over every row in stream order, feeding exactly:
   `id` (UTF-8 bytes, not length-prefixed) || `0x1F` || the vector as float32 little-endian (ZERO bytes when the row has no vector) || `0x1E`
   The two separators are load-bearing: without them `"ab"+"c"` and `"a"+"bc"` would hash alike. It is NOT a hash per row combined afterwards, and it is NOT over the vector alone.
@@ -129,6 +129,14 @@ Example: `?filter=age:gte:30&filter=name:eq:Alice`.
 
 Additional query params: `limit` (default 20), `offset` (default 0), `sort` (field name), `desc` (bool).
 
+**EVERY LISTING ROUTE NOW REFUSES A PARAMETER IT CANNOT HONOUR (422 `unknown_option`), AND THE RULE IS DERIVABLE RATHER THAN A LIST OF NAMES.** If a route implements a parameter it accepts it; if it does not, it says so instead of answering 200 with the parameter ignored. So `limit`, `offset`, `sort` and `desc` are correct HERE, because this route implements all four - and the same names are refused on routes that do not. The error names what you sent, lists what the route accepts, and carries `details.unsupported` (the names) plus `details.instead` (a map to the right name on THIS route, when there is one).
+
+Two things worth knowing before you adapt:
+- **An INCIDENTAL parameter is still ignored, deliberately.** A cache-buster, a proxy's addition, `_=<timestamp>`, `utm_*` - none of those ask for behaviour, so refusing them would be a regression rather than a fix. What is refused is the set a caller plausibly sends EXPECTING AN EFFECT.
+- **The names refused on each route are mostly OUR OWN other routes' spellings**, because that is where the real confusion comes from: `/documents` takes `sort`+`desc=true`, the index-values route takes `order=desc`, `/collections` searches with `q` while `/documents` filters with `filter`, and the export takes `vector_format` where `format` is the obvious guess. Each route therefore refuses the sibling spellings and `details.instead` names the local one.
+
+Per route: `/documents` accepts `filter`, `limit`, `offset`, `sort`, `desc`. `/collections` accepts `q`, `sort`, `desc` and is **not paginated**. `/files` accepts `limit`, `offset` only (fixed newest-first order, no search). The export accepts `include_vectors`, `vector_format`, `after_id`, `batch_rows` and **cannot export a subset**. A function's `/logs` accepts `limit` only - there is **no** `status` filter, so a request for just the failures would otherwise have returned runs of every outcome. `/schema/suggest` accepts `sample_limit` only.
+
 ## Collection schema (needs database 2.16.0+)
 
 An OPTIONAL per-collection JSON Schema, validated on every write. All four routes answer **501** `server_unsupported` against an older database - not 503, because no amount of retrying upgrades a database, and not 422, because the request is valid and there is nothing in the body to fix. Read `has_schema` on the collection GET to know whether one is set; it is OMITTED there when the database is too old, so absent means "cannot be determined", never "no schema".
@@ -237,7 +245,8 @@ Small named binary assets per project, so everything customer-specific (a logo,
 - `PUT    /api/v1/projects/{project}/files/{name}` - Store the **raw request body** under `name`, taking the content type from the `Content-Type` header (default `application/octet-stream`). Not base64 and not a JSON wrapper: a file is bytes. **201** for a new name, **200** for a replacement, and a replacement makes the old bytes unreadable. Answers `{name, content_type, size, checksum, created_at}`. An empty body is **422**; over the size cap is **422** `file_too_large` (default **2 MiB**, `max_file_bytes` in the global settings).
 - `GET    /api/v1/projects/{project}/files/{name}` - The bytes, with the stored content type, plus `X-File-Checksum` and a `Content-Disposition` naming the file. **404** when there is no such file.
 - `GET    /api/v1/projects/{project}/files/{name}/info` - Metadata only, without moving the bytes.
-- `GET    /api/v1/projects/{project}/files` - `{files:[{name, content_type, size, checksum, created_at}]}`, newest first. `limit` (1-1000, default 100, clamped rather than refused) and `offset`.
+- `GET    /api/v1/projects/{project}/files` - `{files:[{name, content_type, size, checksum, created_at}], has_more, total}`, newest first. `limit` (1-1000, default 100, clamped rather than refused) and `offset`.
+  **`has_more` and `total` are ALWAYS present**, true or false, so an absent `has_more` means exactly one thing - a server older than this release - and never "that was everything". They come from the database and were previously discarded, which left a full page and the last page looking identical. `sort`, `order`, `q` and the rest are **refused 422**: the order is fixed and there is no search, so fetch a known file at `/files/{name}` instead. Note the newest-first order is applied WITHIN a page, so it is not a stable global ordering to page through.
 - `DELETE /api/v1/projects/{project}/files/{name}` - **404** when absent. Safe against content dedup: identical bytes stored under two names share storage and are reference-counted, so deleting one name leaves the other readable.
 - **A file name is an identifier, not a label.** Letters, digits, `.`, `-` and `_`, at most 128 characters, no leading `.`, no `..`, no path separator and no `:`. A bad name is **422** with the reason, never 404 - the name is unusable rather than missing, and a caller told "not found" would retry a name that can never work.
 - **Deleting a project deletes its files**, so a recycled project name does not inherit the previous tenant's assets.

File diff ditekan karena terlalu besar
+ 14 - 4
api/openapi.json


+ 22 - 6
src/file_store.cpp

@@ -127,10 +127,17 @@ std::optional<std::pair<StoredFile, std::vector<uint8_t>>> FileStore::get(
     return std::make_pair(meta, db_.client().downloadFile(rec->id));
 }
 
-std::vector<StoredFile> FileStore::list(const std::string& project, uint32_t limit,
-                                        uint32_t offset) {
+FileListing FileStore::listPage(const std::string& project, uint32_t limit, uint32_t offset) {
+    // `project` is the client's `related_id` argument, so the database filters
+    // by project server-side and `limit` is spent on this project's files
+    // only. The `related_id` re-check below is belt and braces, not the
+    // isolation itself - but it stays, because project isolation for files is
+    // OURS rather than the database's and a silent change in that argument's
+    // meaning would be a cross-tenant leak.
     const auto found = db_.client().listFiles(kFileTypeMarker, project, limit, offset, "", "");
-    std::vector<StoredFile> out;
+    FileListing out;
+    out.hasMore = found.has_more;
+    out.total = found.total_count;
     for (const auto& f : found.files) {
         if (f.related_id != project) continue;
         StoredFile s;
@@ -139,14 +146,23 @@ std::vector<StoredFile> FileStore::list(const std::string& project, uint32_t lim
         s.size = f.size;
         s.checksum = f.checksum;
         s.createdAt = f.created_at;
-        out.push_back(std::move(s));
+        out.files.push_back(std::move(s));
     }
-    // Newest first, so a listing is useful without a sort parameter.
-    std::sort(out.begin(), out.end(),
+    // Newest first WITHIN THE PAGE. Stated precisely because the sort happens
+    // after paging: it is not a global ordering, so page 2's rows are not
+    // guaranteed older than page 1's. Callers that need a stable total order
+    // have no parameter for it, which is why the route refuses `sort` instead
+    // of implying one.
+    std::sort(out.files.begin(), out.files.end(),
               [](const StoredFile& a, const StoredFile& b) { return a.createdAt > b.createdAt; });
     return out;
 }
 
+std::vector<StoredFile> FileStore::list(const std::string& project, uint32_t limit,
+                                        uint32_t offset) {
+    return listPage(project, limit, offset).files;
+}
+
 bool FileStore::remove(const std::string& project, const std::string& name) {
     const auto found =
         db_.client().listFiles(kFileTypeMarker, project, kNameLookupLimit, 0, "", name);

+ 15 - 0
src/file_store.hpp

@@ -55,6 +55,18 @@ struct StoredFile {
     nlohmann::json toJson() const;
 };
 
+/// One page of a project's files, with what the database said about the rest.
+///
+/// `hasMore` and `total` exist because the client's `listFiles` returns both
+/// and this service used to throw them away, leaving a caller unable to tell a
+/// full page from the last one - the same ambiguity `truncated` was added to
+/// the index-values route for.
+struct FileListing {
+    std::vector<StoredFile> files;
+    bool hasMore = false;
+    uint64_t total = 0;
+};
+
 /// Why a name was refused, or empty when it is acceptable.
 ///
 /// Pure and separately testable because the name arrives in a URL path and is
@@ -88,6 +100,9 @@ public:
     /// Newest first. `limit` is clamped by the caller, not here.
     std::vector<StoredFile> list(const std::string& project, uint32_t limit, uint32_t offset);
 
+    /// The same page, plus whether more follow it.
+    FileListing listPage(const std::string& project, uint32_t limit, uint32_t offset);
+
     /// False when there was nothing of that name.
     ///
     /// Safe against the database's content dedup: identical bytes under two

+ 12 - 0
src/handlers/collection_schema.cpp

@@ -2,6 +2,7 @@
 #include "errors.hpp"
 #include "functions/known_keys.hpp"
 #include "json_http.hpp"
+#include "query_params.hpp"
 #include "server.hpp"
 
 namespace svapi {
@@ -230,6 +231,17 @@ void registerCollectionSchemaRoutes(ApiServer& s) {
         std::string project = req.matches[1], name = req.matches[2];
         requireProjectManage(k, project);
         requireSchemaSupport(*d);
+        // `limit` is the obvious guess for the sample size and would be
+        // ignored, which on a large collection means scanning every row when
+        // the caller asked for a sample.
+        requireHonourableParams(req,
+                                {{"limit", "sample_limit"}, {"sample", "sample_limit"},
+                                 {"rows", "sample_limit"}, {"samples", "sample_limit"},
+                                 {"mode"}, {"offset"}, {"filter"}, {"apply"}},
+                                {"sample_limit"},
+                                "it only reads; a suggestion is never applied, so there is no "
+                                "`mode` here - PUT the edited schema to arm it");
+
         if (!d->registry.get(project, name))
             throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
 

+ 15 - 0
src/handlers/collections.cpp

@@ -1,6 +1,7 @@
 #include "collection_registry.hpp"
 #include "errors.hpp"
 #include "json_http.hpp"
+#include "query_params.hpp"
 #include "server.hpp"
 #include <algorithm>
 #include <cctype>
@@ -92,6 +93,20 @@ void registerCollectionRoutes(ApiServer& s) {
             std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (char)std::tolower(c); });
             return s;
         };
+        // This listing is NOT paginated - it returns every collection the key
+        // may see - so `limit`, `offset` and friends are refused rather than
+        // ignored. A caller sending `limit=10` and receiving fifty would at
+        // least notice; a caller sending `offset=50` and receiving the first
+        // fifty again would not, and that is the same loop the index-values
+        // route produced.
+        requireHonourableParams(req,
+                                {{"limit"}, {"offset"}, {"page"}, {"cursor"}, {"after"},
+                                 {"skip"}, {"fields"}, {"order", "desc"}, {"asc", "desc"},
+                                 {"filter", "q"}, {"search", "q"}},
+                                {"q", "sort", "desc"},
+                                "it is not paginated: every collection this key may see is "
+                                "returned, and `q` is a case-insensitive name match");
+
         const std::string q    = lower(req.has_param("q") ? req.get_param_value("q") : "");
         const std::string sort = req.has_param("sort") ? req.get_param_value("sort") : "name";
         const bool        desc = req.has_param("desc") && req.get_param_value("desc") == "true";

+ 15 - 0
src/handlers/documents.cpp

@@ -4,6 +4,7 @@
 #include "errors.hpp"
 #include "filters.hpp"
 #include "json_http.hpp"
+#include "query_params.hpp"
 #include "server.hpp"
 #include <string>
 #include <vector>
@@ -181,6 +182,20 @@ void registerDocumentRoutes(ApiServer& s) {
 
     svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
         Target t = scoped(d, req, 1, 2, KeyOp::List);
+        // The sibling routes' spellings are the ones worth refusing here:
+        // `order=desc` is how the index-values route says it and `q=` is how
+        // the collections listing says it, so a caller moving between our own
+        // routes is the likeliest author of a parameter we would otherwise
+        // accept and ignore. This route DOES implement `limit`, `offset`,
+        // `sort` and `desc`, which is why accepting those is correct and
+        // refusing them on index-values was not - the rule is "refuse what
+        // you cannot honour", never a fixed list of names.
+        requireHonourableParams(req,
+                                {{"order", "desc"}, {"asc", "desc"}, {"sort_by", "sort"},
+                                 {"q", "filter"}, {"search", "filter"}, {"where", "filter"},
+                                 {"page"}, {"cursor"}, {"after"}, {"skip"}, {"fields"}},
+                                {"filter", "limit", "offset", "sort", "desc"},
+                                "`filter` is repeatable and takes `field:op:value`");
         smartbotic::database::Client::QueryOptions opts;
         auto range = req.params.equal_range("filter");
         for (auto it = range.first; it != range.second; ++it) opts.filters.push_back(parseFilter(it->second));

+ 35 - 0
src/handlers/export.cpp

@@ -1,6 +1,7 @@
 #include "db_errors.hpp"
 #include "errors.hpp"
 #include "json_http.hpp"
+#include "query_params.hpp"
 #include "server.hpp"
 
 #include <spdlog/spdlog.h>
@@ -35,6 +36,38 @@ struct ExportQuery {
     uint32_t batchRows = 0;   // 0 = the database's own default
 };
 
+/// The parameters this route cannot honour.
+///
+/// Separate from `parseExportQuery` because it needs no collection metadata,
+/// which lets it run BEFORE the registry lookup - so the answer to a
+/// misspelled parameter is the same whether or not the collection exists. The
+/// ordering everywhere is: authorize, then the server's own capability, then
+/// the REQUEST, then the resource.
+void refuseUnexportableParams(const httplib::Request& req) {
+    // `format` is the dangerous one, and it is dangerous in a specific
+    // direction: a caller who means `vector_format=base64` and writes
+    // `format=base64` gets the ARRAY export, which for a 12448-row collection
+    // at dim 4096 is a ~294 MB download instead of a ~100 MB one - and it
+    // looks like it worked. The singular/plural pairs are the same shape as
+    // `filter:` for `filters:` on the search body, which is the misspelling
+    // that silently returned the rows a caller meant to exclude.
+    //
+    // There is also no way to export a SUBSET: this route streams the whole
+    // collection, so `filter`, `limit` and `sort` are refused rather than
+    // ignored. A caller testing a backup with `?limit=10` and receiving every
+    // row would discover it from the transfer size at best.
+    requireHonourableParams(req,
+                            {{"format", "vector_format"}, {"vectors", "include_vectors"},
+                             {"include_vector", "include_vectors"},
+                             {"batch_size", "batch_rows"}, {"batch", "batch_rows"},
+                             {"rows", "batch_rows"}, {"after", "after_id"},
+                             {"cursor", "after_id"}, {"filter"}, {"filters"}, {"limit"},
+                             {"offset"}, {"page"}, {"sort"}, {"desc"}, {"fields"}},
+                            {"include_vectors", "vector_format", "after_id", "batch_rows"},
+                            "it exports the WHOLE collection and cannot filter, sort or "
+                            "limit; resume a transfer with `after_id`");
+}
+
 ExportQuery parseExportQuery(const httplib::Request& req, const CollectionMeta& meta) {
     ExportQuery q;
     // Vectors default to ON for a vector collection and are impossible for a
@@ -186,6 +219,8 @@ void registerExportRoutes(ApiServer& s) {
         requireCapability(*d, key, req, project, name, KeyOp::List);
         requireCapability(*d, key, req, project, name, KeyOp::Read);
 
+        refuseUnexportableParams(req);
+
         auto meta = d->registry.get(project, name);
         if (!meta) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
         const ExportQuery q = parseExportQuery(req, *meta);

+ 26 - 2
src/handlers/files.cpp

@@ -1,6 +1,7 @@
 #include "errors.hpp"
 #include "file_store.hpp"
 #include "json_http.hpp"
+#include "query_params.hpp"
 #include "server.hpp"
 
 #include <algorithm>
@@ -60,15 +61,38 @@ void registerFileRoutes(ApiServer& s) {
                                std::string(what) + " must be a non-negative integer");
             }
         };
+        // Ordering is fixed (newest first) and there is no name search, so a
+        // caller asking for either is refused rather than quietly served the
+        // default order. `limit` and `offset` ARE honoured - the client's
+        // listFiles takes both, and its `related_id` argument filters by
+        // project server-side, so the page is this project's files and the
+        // limit is not consumed by other tenants' rows.
+        requireHonourableParams(req,
+                                {{"sort"}, {"order"}, {"desc"}, {"asc"}, {"page"},
+                                 {"cursor"}, {"after"}, {"skip"}, {"fields"},
+                                 {"q"}, {"filter"}, {"search"}, {"name"}},
+                                {"limit", "offset"},
+                                "files are returned newest first and cannot be sorted or "
+                                "searched; fetch one by name at "
+                                "`/files/{name}` or `/files/{name}/info`");
+
         uint32_t limit = 100, offset = 0;
         if (req.has_param("limit"))
             limit = std::clamp<uint32_t>(parseUInt(req.get_param_value("limit"), "limit"), 1, 1000);
         if (req.has_param("offset")) offset = parseUInt(req.get_param_value("offset"), "offset");
 
         FileStore store(d->db);
+        FileListing listing = store.listPage(project, limit, offset);
         nlohmann::json out = nlohmann::json::array();
-        for (const StoredFile& f : store.list(project, limit, offset)) out.push_back(f.toJson());
-        sendJson(res, 200, {{"files", out}});
+        for (const StoredFile& f : listing.files) out.push_back(f.toJson());
+        // `has_more` and `total` come from the database and were previously
+        // DISCARDED, which left this listing with the defect index-values was
+        // just fixed for: a full page and the last page look identical, so a
+        // caller cannot tell whether to ask for the next one. Emitted
+        // unconditionally, true or false, so an absent field means exactly one
+        // thing - a server older than this release.
+        sendJson(res, 200,
+                 {{"files", out}, {"has_more", listing.hasMore}, {"total", listing.total}});
     });
 
     // Download. Answers with the stored bytes and the stored content type, not

+ 15 - 0
src/handlers/functions.cpp

@@ -2,6 +2,7 @@
 #include "function_record.hpp"
 #include "json_http.hpp"
 #include "project_settings.hpp"
+#include "query_params.hpp"
 #include "server.hpp"
 #include <cstdlib>
 #include <ctime>
@@ -334,6 +335,20 @@ void registerFunctionRoutes(ApiServer& s) {
             [d](const httplib::Request& req, httplib::Response& res) {
         std::string project = req.matches[1], id = req.matches[2];
         requireProjectManage(requireKey(*d, req), project);
+        // The run log takes `limit` and NOTHING else. `status`/`state` are the
+        // ones worth naming, because filtering a run log to the failures is
+        // the first thing anyone wants from it and there is no such parameter
+        // - so a caller passing one would be handed the newest runs of EVERY
+        // outcome and read them as the failures.
+        requireHonourableParams(req,
+                                {{"status"}, {"state"}, {"outcome"}, {"failed"}, {"error"},
+                                 {"offset"}, {"page"}, {"cursor"}, {"after"}, {"skip"},
+                                 {"since"}, {"until"}, {"sort"}, {"order"}, {"desc"},
+                                 {"run_id"}, {"fields"}},
+                                {"limit"},
+                                "it returns the newest runs of every outcome and cannot be "
+                                "filtered or paged; the retained count per function is "
+                                "`runs_kept` on the function settings");
         if (!d->functions.get(project, id))
             throw ApiError(ErrCode::NotFound, "not_found", "no such function");
         nlohmann::json arr = nlohmann::json::array();

+ 14 - 27
src/handlers/indexes.cpp

@@ -4,6 +4,7 @@
 #include "errors.hpp"
 #include "index_request.hpp"
 #include "json_http.hpp"
+#include "query_params.hpp"
 #include "server.hpp"
 
 namespace svapi {
@@ -223,34 +224,20 @@ void registerIndexRoutes(ApiServer& s) {
         // does not implement. Measured on prod: `?offset=1000` answered 200
         // with the FIRST page, because the handler reads only `limit` and
         // `order` and the client's indexValues() has no offset to honour - so
-        // a caller paginating looped forever believing it was progressing. A
-        // 200 with the wrong answer to a well-formed request, which is exactly
-        // what the search body refuses as `unknown_option`; that lesson was
-        // applied to the handler where it was learned and not to this one.
+        // a caller paginating looped forever believing it was progressing.
         //
-        // NOT a blanket refusal of unknown query params, deliberately. Every
-        // key in a JSON body is deliberate, but a query string legitimately
-        // collects things nobody meant as options - a cache-buster, a proxy's
-        // addition, a UI's `_=<timestamp>` - so refusing everything unknown
-        // would be a regression. Refusing `offset` is the point; refusing
-        // `_=1760000000` is not.
-        static constexpr const char* kPretenders[] = {"offset", "page", "cursor",
-                                                      "sort", "fields", "after", "skip"};
-        std::vector<std::string> pretending;
-        for (const char* k : kPretenders)
-            if (req.has_param(k)) pretending.push_back(k);
-        if (!pretending.empty()) {
-            std::string names;
-            for (size_t i = 0; i < pretending.size(); ++i)
-                names += (i ? ", " : "") + pretending[i];
-            throw ApiError(ErrCode::Unprocessable, "unknown_option",
-                           "this route does not support " + names +
-                               ". It is not paginated and has no total: it returns at most "
-                               "`limit` distinct values (max 1000) and sets `truncated` when "
-                               "there may be more. Accepted parameters are `limit` and `order`.",
-                           {{"unsupported", pretending},
-                            {"accepted", nlohmann::json::array({"limit", "order"})}});
-        }
+        // The list and the reasoning now live in `query_params.hpp` and are
+        // shared with every other listing route. They were inline here first,
+        // which was the instance-not-the-class mistake this very defect is the
+        // specimen of: the fix landed in the handler where the lesson was
+        // learned and left six siblings answering 200 to the same question.
+        requireHonourableParams(req,
+                                {{"offset"}, {"page"}, {"cursor"}, {"after"}, {"skip"},
+                                 {"sort"}, {"fields"}, {"desc", "order"}, {"q"}, {"filter"}},
+                                {"limit", "order"},
+                                "It is not paginated and has no total: it returns at most "
+                                "`limit` distinct values (max 1000) and sets `truncated` when "
+                                "there may be more");
 
         constexpr uint32_t kValuesLimitCap = 1000;
         uint32_t limit = 100;

+ 149 - 0
src/query_params.hpp

@@ -0,0 +1,149 @@
+#pragma once
+
+#include <httplib.h>
+#include <nlohmann/json.hpp>
+
+#include <initializer_list>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include "errors.hpp"
+
+namespace svapi {
+
+/// A query parameter a route cannot honour, and the name that would have
+/// worked here.
+///
+/// `instead` is empty when this route has no equivalent at all - "we do not
+/// paginate" is a different statement from "you meant `desc`", and conflating
+/// them sends a caller looking for a parameter that does not exist.
+struct UnhonouredParam {
+    std::string_view name;
+    std::string_view instead = {};
+};
+
+/// REFUSE WHAT YOU CANNOT HONOUR - the rule, applied to the query string.
+///
+/// A parameter accepted and silently ignored answers a well-formed request
+/// with the wrong result, which is the defect the vector `/search` body was
+/// fixed for. The measured instance here was `GET .../indexes/{field}/values
+/// ?offset=1000` answering **200 with the first page**, so a caller paginating
+/// looped forever believing it was progressing.
+///
+/// It must NOT be a blanket refusal of every unknown parameter, and that is
+/// the whole reason this is a per-route list rather than one shared validator.
+/// Every key in a JSON body is deliberate; a query string legitimately
+/// collects things nobody meant as options - a cache-buster, a proxy's
+/// addition, a UI's `_=<timestamp>` - so refusing everything unknown would
+/// break callers over parameters that were never asking for behaviour.
+/// Refusing `offset` is the point; refusing `_=1760000000` is a regression.
+///
+/// WHAT MAKES THE CANDIDATE LISTS NON-HYPOTHETICAL: our own routes disagree
+/// about how to spell the same idea. `/documents` takes `sort` + `desc=true`,
+/// the index-values route takes `order=desc`, `/collections` searches with `q`
+/// while `/documents` filters with `filter`, and the export takes
+/// `vector_format` where `format` is the obvious guess. So the likeliest
+/// source of a plausible-but-ignored parameter is a caller who learned it on a
+/// SIBLING route of this same API - which is why each list names the other
+/// routes' spellings first and points at the local one.
+///
+/// Pure, so the decision is testable without a request or a database.
+inline std::vector<UnhonouredParam> unhonouredPresent(
+    const std::vector<std::string>& present,
+    std::initializer_list<UnhonouredParam> candidates) {
+    std::vector<UnhonouredParam> out;
+    // Candidate order, not request order: the message must be stable for the
+    // same request whatever order a client serialised its query string in.
+    for (const UnhonouredParam& c : candidates)
+        for (const std::string& p : present)
+            if (p == c.name) { out.push_back(c); break; }
+    return out;
+}
+
+/// The message for a refused parameter, naming every offender at once.
+///
+/// All of them rather than the first, for the same reason the body check does:
+/// a caller who fixes one name and gets the identical error learns nothing
+/// about how many are left. The accepted set is always listed, because the
+/// usual cause is a plausible spelling rather than an invented parameter.
+inline std::string unhonouredMessage(const std::vector<UnhonouredParam>& offending,
+                                     std::initializer_list<std::string_view> accepted,
+                                     std::string_view note) {
+    // Each offender is rendered whole - "'order' (use 'desc')" - and the
+    // pieces are joined afterwards, rather than appended across loop
+    // iterations. The first version of this built the string inline and left
+    // an unclosed parenthesis on every message carrying a replacement, which
+    // is the kind of defect a test over the MESSAGE catches and a test over
+    // the status code never does.
+    std::vector<std::string> parts;
+    parts.reserve(offending.size());
+    for (const UnhonouredParam& o : offending) {
+        std::string one = "'";
+        one.append(o.name);
+        one += "'";
+        if (!o.instead.empty()) {
+            one += " (use '";
+            one.append(o.instead);
+            one += "')";
+        }
+        parts.push_back(std::move(one));
+    }
+
+    std::string msg = "this route does not support ";
+    for (std::size_t i = 0; i < parts.size(); ++i) {
+        if (i > 0) msg += i + 1 == parts.size() ? " and " : ", ";
+        msg += parts[i];
+    }
+    if (!note.empty()) { msg += ". "; msg.append(note); }
+    msg += ". Accepted parameters are ";
+    bool first = true;
+    for (const std::string_view a : accepted) {
+        if (!first) msg += ", ";
+        msg += "'";
+        msg.append(a);
+        msg += "'";
+        first = false;
+    }
+    return msg;
+}
+
+/// Throw 422 `unknown_option` when the request carries a parameter this route
+/// cannot honour. Same slug as the body check, because it is the same defect.
+inline void requireHonourableParams(const httplib::Request& req,
+                                    std::initializer_list<UnhonouredParam> candidates,
+                                    std::initializer_list<std::string_view> accepted,
+                                    std::string_view note = {}) {
+    std::vector<std::string> present;
+    present.reserve(req.params.size());
+    for (const auto& kv : req.params) present.push_back(kv.first);
+
+    const std::vector<UnhonouredParam> offending = unhonouredPresent(present, candidates);
+    if (offending.empty()) return;
+
+    // `unsupported` STAYS a flat array of names, because that is the shape
+    // 0.13.0 published and a consumer may already read it. The replacements
+    // arrive as a SEPARATE `instead` map rather than by turning each entry
+    // into an object - additive, so nothing that parses the old shape breaks.
+    // Reshaping a field one release after shipping it is the same mistake as
+    // growing a by-value struct under one soname.
+    nlohmann::json unsupported = nlohmann::json::array();
+    nlohmann::json instead = nlohmann::json::object();
+    for (const UnhonouredParam& o : offending) {
+        unsupported.push_back(std::string(o.name));
+        if (!o.instead.empty()) instead[std::string(o.name)] = std::string(o.instead);
+    }
+    nlohmann::json acceptedJson = nlohmann::json::array();
+    for (const std::string_view a : accepted) acceptedJson.push_back(std::string(a));
+
+    nlohmann::json details{{"unsupported", std::move(unsupported)},
+                           {"accepted", std::move(acceptedJson)}};
+    // Omitted entirely when nothing has a local equivalent, so an empty object
+    // never reads as "there is a replacement and it is blank".
+    if (!instead.empty()) details["instead"] = std::move(instead);
+
+    throw ApiError(ErrCode::Unprocessable, "unknown_option",
+                   unhonouredMessage(offending, accepted, note), details);
+}
+
+}  // namespace svapi

+ 5 - 0
tests/CMakeLists.txt

@@ -258,6 +258,11 @@ target_include_directories(test_known_keys PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_known_keys PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_known_keys)
 
+add_executable(test_query_params test_query_params.cpp)
+target_include_directories(test_query_params PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_query_params PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_query_params)
+
 add_executable(test_vector_scan test_vector_scan.cpp)
 target_include_directories(test_vector_scan PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_vector_scan PRIVATE vectorapi_core GTest::gtest_main)

+ 122 - 0
tests/test_api_integration.cpp

@@ -4139,3 +4139,125 @@ TEST_F(ApiFixture, AnIndexOnAnEncryptedFieldIsRefusedPermanentlyNotAs503) {
     EXPECT_EQ(nlohmann::json::parse(dup->body)["error"].value("code", ""), "duplicate_values");
     c.Delete(base.c_str());
 }
+
+// THE CLASS, NOT THE INSTANCE. #72 fixed the index-values route and left six
+// siblings answering 200 to a parameter they could not honour, which is the
+// exact failure mode that defect was the specimen of. One test per route,
+// because a settings key - or a refusal - is not done until a test drives its
+// ROUTE: the `network_egress` edit that landed in the wrong handler compiled,
+// passed the suite and was caught by prod acceptance.
+TEST_F(ApiFixture, EveryListingRouteRefusesParamsItCannotHonour) {
+    auto c = admin();
+    const std::string proj = "/api/v1/projects/" + project_;
+    const std::string coll = proj + "/collections/qparams";
+    c.Delete(coll.c_str());
+    ASSERT_EQ(c.Post((proj + "/collections").c_str(),
+                     nlohmann::json{{"name", "qparams"}, {"kind", "json"}}.dump(),
+                     "application/json")->status, 201);
+    ASSERT_EQ(c.Post((coll + "/documents").c_str(),
+                     nlohmann::json{{"id", "q1"}, {"tag", "a"}}.dump(),
+                     "application/json")->status, 201);
+
+    struct Case { const char* path; const char* param; const char* instead; };
+    // `instead` is the sibling route's spelling where there is one - the whole
+    // reason these lists are not hypothetical is that our own routes disagree
+    // about how to say the same thing.
+    const std::vector<Case> cases = {
+        // /documents implements limit/offset/sort/desc, so the refusals are
+        // the OTHER routes' names for them.
+        {"/documents?order=desc",            "order",  "desc"},
+        {"/documents?q=hello",               "q",      "filter"},
+        {"/documents?page=2",                "page",   nullptr},
+        {"/documents?search=hello",          "search", "filter"},
+    };
+    for (const Case& k : cases) {
+        auto res = c.Get((coll + k.path).c_str());
+        ASSERT_TRUE(res) << k.param;
+        ASSERT_EQ(res->status, 422) << k.param << ": " << res->body;
+        auto err = nlohmann::json::parse(res->body)["error"];
+        EXPECT_EQ(err.value("code", ""), "unknown_option") << k.param;
+        // `unsupported` keeps the flat-array shape 0.13.0 published.
+        ASSERT_TRUE(err["details"]["unsupported"].is_array()) << res->body;
+        EXPECT_EQ(err["details"]["unsupported"][0].get<std::string>(), k.param);
+        if (k.instead)
+            EXPECT_EQ(err["details"]["instead"][k.param].get<std::string>(), k.instead)
+                << res->body;
+        else
+            EXPECT_FALSE(err["details"].contains("instead")) << res->body;
+    }
+
+    // Collections listing: refuses pagination it does not have.
+    auto cl = c.Get((proj + "/collections?limit=5").c_str());
+    ASSERT_EQ(cl->status, 422) << cl->body;
+    EXPECT_EQ(nlohmann::json::parse(cl->body)["error"].value("code", ""), "unknown_option");
+    // ...and still honours the two it does implement, or the refusal has
+    // broken the web UI, which sends exactly these.
+    auto okc = c.Get((proj + "/collections?q=qpar&sort=name&desc=true").c_str());
+    EXPECT_EQ(okc->status, 200) << okc->body;
+
+    // Files listing: fixed order, no search.
+    auto fl = c.Get((proj + "/files?sort=name").c_str());
+    ASSERT_EQ(fl->status, 422) << fl->body;
+    auto flok = c.Get((proj + "/files?limit=5&offset=0").c_str());
+    ASSERT_EQ(flok->status, 200) << flok->body;
+    // The completeness the client hands us and we used to discard. Emitted
+    // unconditionally, so ABSENCE means only "older server".
+    auto flj = nlohmann::json::parse(flok->body);
+    EXPECT_TRUE(flj.contains("has_more")) << flok->body;
+    EXPECT_TRUE(flj["has_more"].is_boolean()) << flok->body;
+    EXPECT_TRUE(flj.contains("total")) << flok->body;
+
+    // Export: `format` for `vector_format` is the costly one - it silently
+    // produces the array export, which is ~3x the bytes of base64.
+    auto ex = c.Get((coll + "/export?format=base64").c_str());
+    ASSERT_EQ(ex->status, 422) << ex->body;
+    EXPECT_EQ(nlohmann::json::parse(ex->body)["error"]["details"]["instead"]["format"]
+                  .get<std::string>(), "vector_format");
+    // An export cannot take a subset, so asking for one is refused rather than
+    // answered with the whole collection.
+    auto exl = c.Get((coll + "/export?limit=10").c_str());
+    EXPECT_EQ(exl->status, 422) << exl->body;
+
+    // The run log takes `limit` and nothing else. `status=failed` is the one
+    // everybody reaches for, and it would have returned runs of EVERY outcome.
+    const std::string fn = proj + "/functions/nosuchfn/logs";
+    auto rl = c.Get((fn + "?status=failed").c_str());
+    ASSERT_TRUE(rl);
+    // 422 BEFORE the 404: the parameter is wrong whether or not the function
+    // exists, and answering 404 first would hide it until they created one.
+    EXPECT_EQ(rl->status, 422) << rl->body;
+
+    // Schema suggest: `limit` would be ignored and scan every row.
+    auto sg = c.Get((coll + "/schema/suggest?limit=10").c_str());
+    ASSERT_TRUE(sg);
+    if (sg->status != 501)  // older database: no collection_schema capability
+        EXPECT_EQ(sg->status, 422) << sg->body;
+}
+
+// The pairing that proves the refusals above are SELECTIVE. Without this, the
+// whole family could be a blanket refusal of unknown parameters and every test
+// above would still pass - and a blanket refusal would break callers over
+// cache-busters and proxy additions that were never asking for behaviour.
+TEST_F(ApiFixture, NoListingRouteRefusesAnIncidentalParameter) {
+    auto c = admin();
+    const std::string proj = "/api/v1/projects/" + project_;
+    const std::string coll = proj + "/collections/qincidental";
+    // Creates its own collection rather than reusing the one the previous test
+    // made. The first version leaned on that leftover and failed the moment
+    // ctest ran it first: a 404 for a collection that did not exist yet, which
+    // would ALSO have masked a wrongly refused parameter. The fixture already
+    // shares one database and a fixed project name, so a test that depends on
+    // another test's residue passes or fails on ordering.
+    c.Delete(coll.c_str());
+    ASSERT_EQ(c.Post((proj + "/collections").c_str(),
+                     nlohmann::json{{"name", "qincidental"}, {"kind", "json"}}.dump(),
+                     "application/json")->status, 201);
+
+    for (const std::string& path : {coll + "/documents?_=1760000000",
+                                    proj + "/collections?_=1760000000&utm_source=x",
+                                    proj + "/files?_=1760000000"}) {
+        auto res = c.Get(path.c_str());
+        ASSERT_TRUE(res) << path;
+        EXPECT_EQ(res->status, 200) << path << ": " << res->body;
+    }
+}

+ 83 - 0
tests/test_query_params.cpp

@@ -0,0 +1,83 @@
+#include <gtest/gtest.h>
+
+#include <algorithm>
+
+#include "query_params.hpp"
+
+using namespace svapi;
+
+namespace {
+
+std::vector<std::string> names(const std::vector<UnhonouredParam>& v) {
+    std::vector<std::string> out;
+    for (const auto& p : v) out.emplace_back(p.name);
+    return out;
+}
+
+}  // namespace
+
+// THE ASSERTION THAT MAKES THE REST MEAN ANYTHING. Every other test here
+// proves the refusal FIRES; this one proves it can also NOT fire, which is
+// what distinguishes "refuse what you cannot honour" from a blanket refusal of
+// every unknown query parameter. A query string legitimately carries a
+// cache-buster, a proxy's addition or a UI's `_=<timestamp>`, and refusing
+// those would be a regression rather than a fix.
+TEST(QueryParams, IncidentalParametersAreNotRefused) {
+    const std::vector<std::string> present = {"limit", "_", "utm_source", "X-Request-Id"};
+    const auto bad = unhonouredPresent(present, {{"offset"}, {"page"}, {"sort"}});
+    EXPECT_TRUE(bad.empty());
+}
+
+TEST(QueryParams, APresentCandidateIsReportedAndAnAbsentOneIsNot) {
+    const std::vector<std::string> present = {"offset"};
+    const auto bad = unhonouredPresent(present, {{"offset"}, {"page"}});
+    ASSERT_EQ(1u, bad.size());
+    EXPECT_EQ("offset", std::string(bad[0].name));
+}
+
+// The message must be stable for one request however the client serialised the
+// query string, or two identical requests produce two different error bodies.
+TEST(QueryParams, OrderFollowsTheCandidateListNotTheRequest) {
+    const auto a = unhonouredPresent({"sort", "offset"}, {{"offset"}, {"page"}, {"sort"}});
+    const auto b = unhonouredPresent({"offset", "sort"}, {{"offset"}, {"page"}, {"sort"}});
+    EXPECT_EQ(names(a), names(b));
+    EXPECT_EQ((std::vector<std::string>{"offset", "sort"}), names(a));
+}
+
+// Regression: the first version of the builder appended the replacement across
+// loop iterations and left EVERY such message with an unclosed parenthesis.
+// A test over the status code could never have caught that, which is the
+// reason this one reads the string.
+TEST(QueryParams, AReplacementIsNamedAndItsParenthesisIsClosed) {
+    const auto bad = unhonouredPresent({"order"}, {{"order", "desc"}});
+    const std::string msg = unhonouredMessage(bad, {"sort", "desc"}, "");
+    EXPECT_NE(std::string::npos, msg.find("'order' (use 'desc')")) << msg;
+    // Balanced, counted rather than eyeballed.
+    EXPECT_EQ(std::count(msg.begin(), msg.end(), '('), std::count(msg.begin(), msg.end(), ')'))
+        << msg;
+}
+
+// "we do not paginate" is a different statement from "you meant `desc`", and
+// inventing a replacement would send a caller looking for a parameter that
+// does not exist on this route.
+TEST(QueryParams, AParamWithNoLocalEquivalentIsNotGivenOne) {
+    const auto bad = unhonouredPresent({"page"}, {{"page"}});
+    const std::string msg = unhonouredMessage(bad, {"limit"}, "it is not paginated");
+    EXPECT_NE(std::string::npos, msg.find("'page'")) << msg;
+    EXPECT_EQ(std::string::npos, msg.find("use '")) << msg;
+    EXPECT_NE(std::string::npos, msg.find("it is not paginated")) << msg;
+}
+
+// Every offender at once: a caller who fixes one name and meets the identical
+// error learns nothing about how many are left.
+TEST(QueryParams, EveryOffenderIsNamedAndTheAcceptedSetIsListed) {
+    const auto bad = unhonouredPresent({"page", "order", "fields"},
+                                       {{"order", "desc"}, {"page"}, {"fields"}});
+    ASSERT_EQ(3u, bad.size());
+    const std::string msg = unhonouredMessage(bad, {"filter", "limit"}, "");
+    EXPECT_NE(std::string::npos, msg.find("'order' (use 'desc')")) << msg;
+    EXPECT_NE(std::string::npos, msg.find("'page'")) << msg;
+    EXPECT_NE(std::string::npos, msg.find("'fields'")) << msg;
+    EXPECT_NE(std::string::npos, msg.find(" and ")) << msg;
+    EXPECT_NE(std::string::npos, msg.find("Accepted parameters are 'filter', 'limit'")) << msg;
+}

Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini