Forráskód Böngészése

fix: 2.12.3 - the file store: a dropped project's files are deleted, the size limit refuses mid-stream, downloads stream from disk

smartbotic-vectorapi asked four questions before building on file storage;
answering them from source found three defects.

dropProject never touched files: records live in a global tree under
<filesDir>/records, not in the project's env, so a dropped project's files
survived and were served to a later project of the same name. DropProject now
deletes every record of the project through the refcounted path, so bytes
another project also holds are kept.

The upload size limit was checked only after UploadFile had buffered the whole
body, so an oversized upload cost its full size in memory (times
max_concurrent_file_streams) before being refused, and the refusal surfaced as
INTERNAL. The handler now refuses mid-stream with INVALID_ARGUMENT, reason
file_too_large; storeFile throws a typed FileRejected for that and for
mime_type_not_allowed. Measured: a 64 MB upload against a 1 MB cap raises the
server's peak RSS by 5 MB, 81 MB with the fix reverted.

DownloadFile read the whole file into memory before streaming it; it now
streams the blob from disk in 64 KB chunks.

No wire or client ABI change: the client's upload refusal now carries its
detail, the headers changed in comments only, and the library exports the same
7174 symbols. Also replaces em-dashes in this work's version-tagged comments.

Test: test_file_store, a peak-memory check on a fresh server plus 18 checks and
3 after a restart. Reverted alone: typed refusal fails 1, project file deletion
2, the mid-stream size check fails the memory check (invisible to every
functional assertion, which is why that check exists). The streaming download
has no memory check; it is pinned by byte-for-byte equality. ctest 23/23, 16/16
e2e suites.
fszontagh 1 hónapja
szülő
commit
48e9fc1a2a

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.12.2
+2.12.3

+ 3 - 0
client/include/smartbotic/database/client.hpp

@@ -148,6 +148,9 @@ public:
      *   "read_only"          the database is in read-only mode
      *   "memory_pressure"    refused under memory pressure; retry later
      *   "view_write"         the name is a view, which is read-only
+     *   "duplicate_id"       insert of an id that exists (2.12.1); conflictingId
+     *   "file_too_large"     upload over the size limit (2.12.3)
+     *   "mime_type_not_allowed"  upload type outside the allow-list (2.12.3)
      *   ""                   no further detail (transport errors, denials...)
      *
      * Reset at the start of every call that fills it.

+ 2 - 2
client/src/client.cpp

@@ -54,7 +54,7 @@ Client::ErrorCode toErrorCode(grpc::StatusCode code) {
     return static_cast<Client::ErrorCode>(static_cast<int>(code));
 }
 
-// v2.12.0 — the refusal detail the server attaches as trailing metadata (see
+// v2.12.0 - the refusal detail the server attaches as trailing metadata (see
 // `service DatabaseService` in database.proto). Empty when absent.
 constexpr const char* kErrorDetailKey = "sbdb-error-detail-bin";
 
@@ -2455,7 +2455,7 @@ public:
         auto status = writer->Finish();
         if (!status.ok()) {
             spdlog::error("Client::uploadFile failed: {}", status.error_message());
-            throwStatus(status, status.error_message());
+            throwStatus(status, status.error_message(), trailerDetail(context));   // v2.12.3: reason file_too_large / mime_type_not_allowed
         }
 
         return {response.id(), response.size(), response.checksum(), response.deduplicated()};

+ 8 - 2
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # Smartbotic Database - Status and Roadmap
 
-**Released version: 2.12.2** (see `VERSION`). Last reviewed: 2026-10-07.
+**Released version: 2.12.3** (see `VERSION`). Last reviewed: 2026-10-07.
 
 > 2.11.5 was prepared but never released on its own: its work (event actors,
 > `removeAs()`) ships inside 2.12.0. There is no 2.11.5 package.
@@ -56,7 +56,7 @@ Consequences of that substitution, which trip up readers:
 
 ## Shipped
 
-Every item below is in the installed product as of 2.12.2. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.12.3. `CLAUDE.md` has the
 detail and the failure modes.
 
 - JSON document store: collections, version history, field-level encryption, TTL
@@ -85,6 +85,8 @@ detail and the failure modes.
   dropped project's documents are really gone, including after a restart
   (2.12.2); `dropIndex` / `dropCollection` repair a name left poisoned by an
   older version (2.12.2)
+- File store: `dropProject` deletes the project's files, the upload size limit
+  refuses mid-stream with `file_too_large`, downloads stream from disk (2.12.3)
 - Conditional partial update (`patchIfVersion`) and atomic increment
   (`increment`) (2.12.0)
 - Event provenance: the actor on every `DatabaseEvent`, `removeAs()`,
@@ -293,6 +295,10 @@ Two reports from smartbotic-vectorapi produced v2.11.4. Left open, with reasons:
   rule for NULL, extended to values that have no single key.
 - **`BatchInsert` reports failed items only as a count**, with no per-item code;
   a duplicate id there is not distinguishable from any other failure.
+- **File uploads are still buffered whole in server memory** (up to the size
+  limit, per concurrent upload), and the client API is whole-buffer both ways
+  (`uploadFile` takes, `downloadFile` returns a full `std::vector`). Streaming
+  both ends needs new client methods; nobody has asked yet.
 - **Most management calls still return a bare `false`.** `createRelation`,
   `configureCollection`, `createIndex`, `createCollection` and the like log the
   reason and return `false`. The `Failure&` overloads cover the five document

+ 28 - 0
docs/integration-guide.md

@@ -305,6 +305,8 @@ try {
 |---|---|---|
 | `unique_violation` | `AlreadyExists` | `fields` (several for a composite), `values` (field -> value), `conflictingId` |
 | `duplicate_id` (2.12.1+) | `AlreadyExists` | `conflictingId` = the id; `fields` empty - the identity collided, not a field |
+| `file_too_large` (2.12.3+) | `InvalidArgument` | an upload over `storage.files.max_file_size_mb` |
+| `mime_type_not_allowed` (2.12.3+) | `InvalidArgument` | an upload outside `storage.files.allowed_types` |
 | `missing_parent` | `FailedPrecondition` | `fields` (the reference field), `values` (the missing id), `relation` |
 | `delete_restricted` | `FailedPrecondition` | |
 | `read_only` | `FailedPrecondition` | |
@@ -1309,6 +1311,32 @@ project holds that file.
 `FileRecord` gained a `project` member, which changes the struct size, so
 **consumers must rebuild** against 2.6.0 headers.
 
+#### Names, deletion, limits and memory (2.12.3+)
+
+- **Names are not unique.** Two uploads with the same name are two records with
+  two ids. Find a file by name with `listFiles("", "", 100, 0, "", name)`; a
+  consumer that wants name-addressed files must decide what a second upload of
+  the same name means.
+- **Deleting one record is always safe.** Identical bytes are stored once and
+  reference-counted across every record and project that holds them; deleting a
+  record decrements the count, and the bytes go only with the last reference.
+- **Size limit:** `storage.files.max_file_size_mb` (default 500). An upload over
+  it is refused **while it streams** - the server stops reading at the limit -
+  with `ErrorCode::InvalidArgument`, `FailureDetail::reason == "file_too_large"`.
+  A type outside `storage.files.allowed_types` is refused the same way with
+  `"mime_type_not_allowed"`. Before 2.12.3 both arrived as `Internal`, and an
+  oversized upload was buffered whole on the server before being refused.
+- **Memory:** file content lives on disk, not in the document store, and does not
+  count against `max_memory_mb`. A download streams from disk in 64 KB chunks
+  (2.12.3+; before, the whole file was read into memory first). An upload is
+  still held in server memory until it is complete, up to the size limit per
+  concurrent upload (`storage.grpc.max_concurrent_file_streams`, default 10) -
+  so on a small machine, lower `max_file_size_mb`. The client side holds the
+  whole file too: `uploadFile` takes and `downloadFile` returns a full buffer.
+- **`dropProject` deletes the project's files** (2.12.3+). Bytes another project
+  also holds are kept. Before 2.12.3 a dropped project's files survived and were
+  served to a later project of the same name.
+
 #### Deduplication is per project
 
 `result.deduplicated` means **this project** already referenced those bytes. Blob

+ 2 - 0
proto/database.proto

@@ -28,6 +28,8 @@ package smartbotic.databasepb;
 //   reason           "unique_violation" | "missing_parent" | "delete_restricted"
 //                    | "read_only" | "memory_pressure" | "view_write"
 //                    | "not_found" | "version_conflict" | "invalid_increment"
+//                    | "duplicate_id" (2.12.1) | "file_too_large"
+//                    | "mime_type_not_allowed" (2.12.3)
 //   code             the gRPC status code number - present for in-band
 //                    refusals, whose status is OK
 //   fields           the field(s) concerned: the constrained field(s) of a

+ 1 - 1
service/src/config/collection_config_manager.cpp

@@ -35,7 +35,7 @@ CollectionCfg fromJson(const nlohmann::json& j) {
     // fields (nothing enforces those yet).
     c.relationsEnforced = j.value("relations_enforced", true);
     c.uniqueFields = j.value("unique_fields", std::vector<std::string>{});
-    // v2.12.0 — absent on every older record: no composite constraints.
+    // v2.12.0 - absent on every older record: no composite constraints.
     c.compositeUniques = j.value("composite_uniques", std::vector<std::vector<std::string>>{});
     return c;
 }

+ 2 - 2
service/src/config/collection_config_manager.hpp

@@ -81,7 +81,7 @@ struct CollectionCfg {
     // (T11), armed at boot by DatabaseService::applyIndexDeclarations().
     std::vector<std::string> uniqueFields;
 
-    // v2.12.0 — COMPOSITE unique constraints, each a list of two or more
+    // v2.12.0 - COMPOSITE unique constraints, each a list of two or more
     // fields. Persisted here for the same reason as uniqueFields: this record
     // lives in `_collection_meta`, so it is WAL'd and snapshotted for free.
     // Armed at boot by applyIndexDeclarations(); a declared constraint whose
@@ -117,7 +117,7 @@ public:
     bool setConfig(const std::string& collection, const CollectionCfg& cfg, std::string& errorOut);
 
     /**
-     * v2.12.2 — forget a collection's config entirely (persisted record and
+     * v2.12.2 - forget a collection's config entirely (persisted record and
      * cache), so the name reverts to defaults. Called when the collection is
      * dropped: without it the record - declared indexes, unique and composite
      * constraints, relations_enforced, versioning - outlived the collection and

+ 66 - 25
service/src/database_grpc_impl.cpp

@@ -17,6 +17,7 @@
 
 #include <algorithm>
 #include <chrono>
+#include <fstream>
 #include <functional>
 #include <memory>
 #include <mutex>
@@ -31,7 +32,7 @@ namespace smartbotic::database {
 namespace pb = smartbotic::databasepb;
 
 namespace {
-// v2.12.0 — refusal detail. See the comment above `service DatabaseService` in
+// v2.12.0 - refusal detail. See the comment above `service DatabaseService` in
 // database.proto for the key and its JSON shape. Attached to the call's
 // trailing metadata, so it accompanies an error status AND an in-band refusal
 // (status OK, success=false) alike.
@@ -82,7 +83,7 @@ grpc::Status refuseInBand(grpc::ServerContext* context, Response* response,
 // Used by write handlers whose responses don't have set_success/set_error fields.
 grpc::Status readOnlyStatus(grpc::ServerContext* context, const std::string& rpcName,
                             const DatabaseService& svc) {
-    // v2.12.0 — reason "read_only": FAILED_PRECONDITION alone is ambiguous with
+    // v2.12.0 - reason "read_only": FAILED_PRECONDITION alone is ambiguous with
     // a relation refusal, which uses the same code.
     attachErrorDetail(context, {{"reason", "read_only"}});
     return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
@@ -470,7 +471,7 @@ grpc::Status DatabaseGrpcImpl::Insert(
         return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
                            "Invalid JSON: " + std::string(e.what()));
     } catch (const DuplicateDocumentId& e) {
-        // v2.12.1 — a duplicate PRIMARY id is the caller's business exactly as
+        // v2.12.1 - a duplicate PRIMARY id is the caller's business exactly as
         // a unique-index collision is; it used to fall through to INTERNAL.
         // No field collided - the identity did - so `fields` stays empty and
         // the reason says which kind of collision this is.
@@ -607,7 +608,7 @@ grpc::Status DatabaseGrpcImpl::Update(
         return st;
     }
 
-    // v2.12.0 — still in-band (status OK) so older clients see what they always
+    // v2.12.0 - still in-band (status OK) so older clients see what they always
     // saw, now with error_code and a reason in the refusal detail.
     if (service_.isReadOnly()) {
         return refuseInBand(context, response, grpc::StatusCode::FAILED_PRECONDITION, "read_only",
@@ -645,7 +646,7 @@ grpc::Status DatabaseGrpcImpl::Update(
                 expiryOverrideFrom(*request)
             );
             if (!success) {
-                // v2.12.0 — updateIfVersion answers false for a missing
+                // v2.12.0 - updateIfVersion answers false for a missing
                 // document AND a stale version, and both used to be reported
                 // as "Version conflict". The message stays (older clients may
                 // match it); the code and detail now tell them apart.
@@ -710,7 +711,7 @@ grpc::Status DatabaseGrpcImpl::PatchDocument(
         return st;
     }
 
-    // v2.12.0 — still in-band (status OK) so older clients see what they always
+    // v2.12.0 - still in-band (status OK) so older clients see what they always
     // saw, now with error_code and a reason in the refusal detail.
     if (service_.isReadOnly()) {
         return refuseInBand(context, response, grpc::StatusCode::FAILED_PRECONDITION, "read_only",
@@ -726,7 +727,7 @@ grpc::Status DatabaseGrpcImpl::PatchDocument(
                             "cannot write to view '" + request->collection() + "': views are read-only");
     }
     try {
-        // v2.12.0 — an increment-only request may send no merge patch at all.
+        // v2.12.0 - an increment-only request may send no merge patch at all.
         nlohmann::json patch = request->patch_json().empty()
             ? nlohmann::json::object()
             : smartbotic::db::parse_to_nlohmann(request->patch_json());
@@ -1411,7 +1412,7 @@ grpc::Status DatabaseGrpcImpl::BatchDelete(
     uint64_t deleted = 0;
     std::vector<std::string> plain;      // ids with no destructive relation
     plain.reserve(ids.size());
-    std::unordered_set<std::string> gone;   // v2.12.0 — for deleted_ids
+    std::unordered_set<std::string> gone;   // v2.12.0 - for deleted_ids
     for (const auto& id : ids) {
         bool handled = false;
         bool parentExisted = false;
@@ -1434,7 +1435,7 @@ grpc::Status DatabaseGrpcImpl::BatchDelete(
             plain.push_back(id);
         }
     }
-    // v2.12.0 — one remove() per id rather than bulkDelete(), which is the same
+    // v2.12.0 - one remove() per id rather than bulkDelete(), which is the same
     // loop but reports only a count: the caller now learns WHICH ids existed.
     for (const auto& id : plain) {
         if (store_.remove(request->collection(), id, request->actor())) {
@@ -1969,7 +1970,7 @@ grpc::Status DatabaseGrpcImpl::CreateCollection(
     return grpc::Status::OK;
 }
 
-// v2.12.2 — forget everything declared on a collection name: disarm the
+// v2.12.2 - forget everything declared on a collection name: disarm the
 // store (so no write maintains the old indexes), remove the config record,
 // then drop the index and composite-constraint sub-dbs. Safe on a name whose
 // collection - or whole project - no longer exists.
@@ -2063,7 +2064,7 @@ grpc::Status DatabaseGrpcImpl::DropCollection(
     }
 
     bool dropped = store_.dropCollection(request->name());
-    // v2.12.2 — and everything DECLARED on the name, whether or not the
+    // v2.12.2 - and everything DECLARED on the name, whether or not the
     // collection still existed (dropped == false). Before this the config
     // record survived the drop, so a later collection of the same name
     // inherited its indexes and unique constraints - a legitimate write refused
@@ -2226,7 +2227,7 @@ grpc::Status DatabaseGrpcImpl::DropProject(
     if (service_.isReadOnly()) {
         return readOnlyStatus(context, "DropProject", service_);
     }
-    // v2.12.2 — collect the project's in-memory collections BEFORE the drop.
+    // v2.12.2 - collect the project's in-memory collections BEFORE the drop.
     const std::string prefix = request->name() + ":";
     std::vector<std::string> doomed;
     for (const auto& c : store_.listCollections()) {
@@ -2235,7 +2236,7 @@ grpc::Status DatabaseGrpcImpl::DropProject(
 
     std::string error;
     bool dropped = service_.dropProject(request->name(), error);
-    // v2.12.2 — the project drop removed the project's LMDB env, but its
+    // v2.12.2 - the project drop removed the project's LMDB env, but its
     // collections stayed in MemoryStore and in the WAL. So the "dropped" data
     // was still served (an insert of a dropped id said "already exists"), and a
     // restart would replay it back. Drop each collection the way DropCollection
@@ -2244,6 +2245,15 @@ grpc::Status DatabaseGrpcImpl::DropProject(
     // refuses some names (`default`), and purging first would destroy data the
     // refused drop was meant to keep.
     if (dropped) {
+        // v2.12.3 - and its FILES. File records live in a global tree (not the
+        // project's env), so the env drop left every one of them - and their
+        // blobs - behind, served to a later project of the same name. Deleted
+        // one record at a time through the refcounted path, so a blob another
+        // project also references survives.
+        const uint32_t files = files_.deleteAllIn(request->name());
+        if (files > 0) {
+            spdlog::info("DropProject '{}': deleted {} file(s)", request->name(), files);
+        }
         for (const auto& c : doomed) {
             if (store_.dropCollection(c)) {
                 persistence_.logDropCollection(c);
@@ -2286,11 +2296,24 @@ grpc::Status DatabaseGrpcImpl::UploadFile(
     std::vector<uint8_t> fileData;
     pb::FileMetadata metadata;
 
+    // v2.12.3 - enforce the size limit WHILE reading. It used to be checked
+    // only after the whole body had been buffered here, so an oversized upload
+    // cost its full size in memory (times max_concurrent_file_streams) before
+    // being refused - and the refusal surfaced as INTERNAL. Returning now
+    // stops reading: the client's remaining Writes fail and Finish() gets this
+    // status.
+    const uint64_t maxBytes = files_.maxFileSizeBytes();
     while (reader->Read(&chunk)) {
         if (chunk.has_metadata()) {
             metadata = chunk.metadata();
         } else if (chunk.has_data()) {
             const auto& data = chunk.data();
+            if (fileData.size() + data.size() > maxBytes) {
+                attachErrorDetail(context, {{"reason", "file_too_large"},
+                                            {"max_bytes", maxBytes}});
+                return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                    "File too large (max: " + std::to_string(maxBytes / (1024 * 1024)) + " MB)");
+            }
             fileData.insert(fileData.end(), data.begin(), data.end());
         }
     }
@@ -2343,6 +2366,10 @@ grpc::Status DatabaseGrpcImpl::UploadFile(
 
         return grpc::Status::OK;
 
+    } catch (const FileRejected& e) {
+        // v2.12.3 - the caller's doing (size, MIME type), not a server fault.
+        attachErrorDetail(context, {{"reason", e.reason}});
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what());
     } catch (const std::exception& e) {
         return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
     }
@@ -2394,15 +2421,29 @@ grpc::Status DatabaseGrpcImpl::DownloadFile(
         }
         writer->Write(metadataChunk);
 
-        // Stream file data in chunks
-        constexpr size_t CHUNK_SIZE = 64 * 1024;  // 64KB chunks
-        auto data = files_.readFileIn(request->project(), request->id());
-
-        for (size_t offset = 0; offset < data.size() && !context->IsCancelled(); offset += CHUNK_SIZE) {
+        // Stream file data in chunks.
+        //
+        // v2.12.3 - straight from the blob on disk, one 64 KB chunk at a time.
+        // It used to read the WHOLE file into memory first, so every download
+        // cost the file's full size (up to max_file_size_mb, times the number
+        // of concurrent file streams) for as long as the transfer took.
+        constexpr size_t CHUNK_SIZE = 64 * 1024;
+        auto bp = files_.blobPathIn(request->project(), request->id());
+        if (!bp) {
+            return grpc::Status(grpc::StatusCode::NOT_FOUND, "File not found");
+        }
+        std::ifstream in(*bp, std::ios::binary);
+        if (!in) {
+            return grpc::Status(grpc::StatusCode::INTERNAL, "failed to open the file's content");
+        }
+        std::vector<char> buf(CHUNK_SIZE);
+        while (!context->IsCancelled()) {
+            in.read(buf.data(), static_cast<std::streamsize>(buf.size()));
+            const std::streamsize got = in.gcount();
+            if (got <= 0) break;
             pb::FileChunk dataChunk;
-            size_t chunkSize = std::min(CHUNK_SIZE, data.size() - offset);
-            dataChunk.set_data(data.data() + offset, chunkSize);
-            writer->Write(dataChunk);
+            dataChunk.set_data(buf.data(), static_cast<size_t>(got));
+            if (!writer->Write(dataChunk)) break;   // client went away
         }
 
         return grpc::Status::OK;
@@ -3942,7 +3983,7 @@ grpc::Status DatabaseReplicationGrpcImpl::GetNodeState(
 // error.
 // -------------------------------------------------------------------------
 
-// v2.12.0 — CreateIndex with `fields` set: a COMPOSITE unique constraint. See
+// v2.12.0 - CreateIndex with `fields` set: a COMPOSITE unique constraint. See
 // CreateIndexRequest.fields in database.proto for the contract.
 grpc::Status DatabaseGrpcImpl::createCompositeUnique(
     grpc::ServerContext* /*context*/,
@@ -4215,13 +4256,13 @@ grpc::Status DatabaseGrpcImpl::DropIndex(
     try {
         const auto rc = smartbotic::database::resolveCollection(request->collection());
         auto* ds = service_.docStore(rc.project);
-        // v2.12.2 — may be null: the project's storage is gone (dropped)
+        // v2.12.2 - may be null: the project's storage is gone (dropped)
         // while a declaration on one of its names survived. The declaration
         // lives in the global `_collection_meta`, so it can and must still be
         // removed - refusing here is what made such a name unrepairable.
         auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
 
-        // v2.12.0 — a composite unique constraint, named by its exact field list.
+        // v2.12.0 - a composite unique constraint, named by its exact field list.
         if (request->fields_size() > 0) {
             if (!request->field().empty()) {
                 response->set_success(false);
@@ -4332,7 +4373,7 @@ grpc::Status DatabaseGrpcImpl::ListIndexes(
                 }
             }
         }
-        // v2.12.0 — composite unique constraints. Hidden when ANY of their
+        // v2.12.0 - composite unique constraints. Hidden when ANY of their
         // fields is masked, for the same reason a masked field's index is.
         for (const auto& cf : cfg.compositeUniques) {
             bool masked = false;

+ 2 - 2
service/src/database_grpc_impl.hpp

@@ -499,10 +499,10 @@ private:
     //
     // v2.12.0 - `actor` is the deleting caller's; it is reported on the event
     // of the parent AND of every child the cascade deletes or nulls.
-    // v2.12.2 — see the definition.
+    // v2.12.2 - see the definition.
     void purgeCollectionDeclarations(const std::string& name);
 
-    // v2.12.0 — CreateIndex's composite-unique branch.
+    // v2.12.0 - CreateIndex's composite-unique branch.
     grpc::Status createCompositeUnique(grpc::ServerContext* context,
                                        const pb::CreateIndexRequest* request,
                                        pb::CreateIndexResponse* response,

+ 2 - 2
service/src/database_service.cpp

@@ -406,7 +406,7 @@ bool DatabaseService::dropProject(const std::string& name, std::string& error) {
 
     if (!projects_->drop(name, error)) return false;
 
-    // v2.12.2 — collection configs live in the GLOBAL `_collection_meta`, not
+    // v2.12.2 - collection configs live in the GLOBAL `_collection_meta`, not
     // in the project's env, so dropping the env left every one of the project's
     // declarations behind - and a recreated project silently inherited them.
     // The index sub-dbs went with the env; only the records remain to remove.
@@ -527,7 +527,7 @@ void DatabaseService::applyIndexDeclarations() {
             // call would silently stop enforcing a constraint every write
             // handler still advertises as active.
             lmdb->set_unique_fields(rc.collection, cfg.uniqueFields);
-            // v2.12.0 — composite constraints, armed the same way and for the
+            // v2.12.0 - composite constraints, armed the same way and for the
             // same reason: skipping this would stop enforcing a constraint the
             // record still declares. Self-healed below if its sub-db is gone.
             lmdb->set_composite_uniques(rc.collection, cfg.compositeUniques);

+ 29 - 2
service/src/files/file_manager.cpp

@@ -233,7 +233,8 @@ uint32_t FileManager::purgeExpired() {
 FileManager::StoreResult FileManager::storeFile(const std::vector<uint8_t>& data, FileInfo info) {
     uint64_t maxBytes = config_.maxFileSizeMb * 1024 * 1024;
     if (data.size() > maxBytes) {
-        throw std::runtime_error("File too large (max: " + std::to_string(config_.maxFileSizeMb) + " MB)");
+        throw FileRejected("file_too_large",
+                           "File too large (max: " + std::to_string(config_.maxFileSizeMb) + " MB)");
     }
 
     if (!config_.allowedMimeTypes.empty()) {
@@ -241,7 +242,7 @@ FileManager::StoreResult FileManager::storeFile(const std::vector<uint8_t>& data
         for (const auto& pattern : config_.allowedMimeTypes) {
             if (matchMimeType(pattern, info.mimeType)) { allowed = true; break; }
         }
-        if (!allowed) throw std::runtime_error("MIME type not allowed: " + info.mimeType);
+        if (!allowed) throw FileRejected("mime_type_not_allowed", "MIME type not allowed: " + info.mimeType);
     }
 
     auto checksum = calculateChecksum(data);
@@ -467,6 +468,32 @@ std::vector<uint8_t> FileManager::readFileIn(const std::string& project,
     return readFile(id);
 }
 
+std::optional<std::filesystem::path> FileManager::blobPathIn(const std::string& project,
+                                                             const std::string& id) const {
+    auto info = getFileInfoIn(project, id);
+    if (!info) return std::nullopt;
+    auto bp = blobPath(info->checksum);
+    if (!std::filesystem::exists(bp)) return std::nullopt;
+    return bp;
+}
+
+uint32_t FileManager::deleteAllIn(const std::string& project) {
+    // Page from offset 0 each time: every record we delete leaves the listing.
+    // Bounded by the record count, and by a no-progress stop so a record that
+    // cannot be deleted cannot spin this forever.
+    uint32_t deleted = 0;
+    while (true) {
+        auto page = listFiles(project, "", "", 500, 0);
+        if (page.files.empty()) break;
+        uint32_t thisRound = 0;
+        for (const auto& f : page.files) {
+            if (deleteFileIn(project, f.id)) { ++deleted; ++thisRound; }
+        }
+        if (thisRound == 0) break;
+    }
+    return deleted;
+}
+
 bool FileManager::deleteFileIn(const std::string& project, const std::string& id) {
     if (!getFileInfoIn(project, id)) return false;
     return deleteFile(id);

+ 25 - 0
service/src/files/file_manager.hpp

@@ -19,6 +19,17 @@ namespace smartbotic::database {
  * Blobs: stored by SHA-256 checksum, ref-counted.
  * Records: UUID-keyed metadata pointing to a blob via checksum.
  */
+// v2.12.3 - an upload refused for something the CALLER controls (too large, a
+// MIME type the configuration does not allow). A distinct type so the gRPC layer
+// answers INVALID_ARGUMENT with a reason instead of INTERNAL. Still a
+// runtime_error with the old message for any other caller.
+class FileRejected : public std::runtime_error {
+public:
+    FileRejected(std::string reason_, const std::string& message)
+        : std::runtime_error(message), reason(std::move(reason_)) {}
+    std::string reason;   // "file_too_large" | "mime_type_not_allowed"
+};
+
 class FileManager {
 public:
     struct Config {
@@ -111,6 +122,20 @@ public:
     // exist", since that difference is itself a cross-project oracle.
     [[nodiscard]] std::optional<FileInfo> getFileInfoIn(const std::string& project,
                                                         const std::string& id) const;
+    // v2.12.3 - the configured upload limit in bytes, so the upload handler
+    // can refuse WHILE streaming instead of buffering the whole body first.
+    [[nodiscard]] uint64_t maxFileSizeBytes() const { return config_.maxFileSizeMb * 1024 * 1024; }
+
+    // v2.12.3 - the blob holding a file's bytes, for streaming a download from
+    // disk instead of reading the whole file into memory. Same project check
+    // and same "absent" answer for a foreign file as readFileIn().
+    [[nodiscard]] std::optional<std::filesystem::path> blobPathIn(const std::string& project,
+                                                                  const std::string& id) const;
+
+    // v2.12.3 - delete every file record of a project (refcounted: a blob
+    // shared with another project survives). For DropProject.
+    uint32_t deleteAllIn(const std::string& project);
+
     [[nodiscard]] std::vector<uint8_t> readFileIn(const std::string& project,
                                                   const std::string& id) const;
     bool deleteFileIn(const std::string& project, const std::string& id);

+ 3 - 3
service/src/memory_store.cpp

@@ -1356,7 +1356,7 @@ bool MemoryStore::updateIfVersion(const std::string& collection, const std::stri
 
 namespace {
 
-// v2.12.0 — fields that live on the Document, not in its data. Incrementing
+// v2.12.0 - fields that live on the Document, not in its data. Incrementing
 // one would create a same-named user field instead, which is never meant.
 bool isMetadataPath(const std::string& first) {
     return first == "_id" || first == "_version" || first == "_created_at" ||
@@ -1503,7 +1503,7 @@ uint64_t MemoryStore::patchDocument(const std::string& collection, const std::st
         return 0;
     }
 
-    // v2.12.0 — the version condition, under the same lock the write takes,
+    // v2.12.0 - the version condition, under the same lock the write takes,
     // so nothing can change the document between the check and the write.
     if (expectedVersion.has_value() && it->second.version != *expectedVersion) {
         if (refusal) {
@@ -1513,7 +1513,7 @@ uint64_t MemoryStore::patchDocument(const std::string& collection, const std::st
         return 0;
     }
 
-    // v2.12.0 — compute the merged body (and apply any increments to it)
+    // v2.12.0 - compute the merged body (and apply any increments to it)
     // BEFORE touching the stored document, its expiry index or its history:
     // a refused increment must leave no trace.
     nlohmann::json merged = it->second.data();

+ 4 - 4
service/src/memory_store.hpp

@@ -60,7 +60,7 @@ using EventCallback = std::function<void(const DatabaseEvent&)>;
 // or update stamps doc.updatedBy with the request's actor on every write);
 // a value - even empty - is used as given. A delete has no document left to
 // read, and a TTL expiry has no caller, so those always pass a value.
-// v2.12.1 — insert() of an id that already exists. A distinct type so the gRPC
+// v2.12.1 - insert() of an id that already exists. A distinct type so the gRPC
 // layer answers ALREADY_EXISTS (reason "duplicate_id") instead of INTERNAL: a
 // duplicate primary id is the caller's business, exactly like a unique-index
 // collision. Derives from std::runtime_error with the same message, so every
@@ -624,7 +624,7 @@ public:
                            const nlohmann::json& patch, const std::string& actor = "",
                            std::optional<uint64_t> expiryOverride = std::nullopt);
 
-    // v2.12.0 — why patchDocument() below returned 0.
+    // v2.12.0 - why patchDocument() below returned 0.
     struct PatchRefusal {
         enum class Kind { None, NotFound, VersionConflict, InvalidIncrement };
         Kind kind = Kind::None;
@@ -634,7 +634,7 @@ public:
     };
 
     /**
-     * v2.12.0 — patch with a version condition and atomic increments. Both are
+     * v2.12.0 - patch with a version condition and atomic increments. Both are
      * decided under the collection lock BEFORE anything is mutated, so a
      * refusal leaves the document, its history and its expiry untouched.
      *
@@ -1225,7 +1225,7 @@ private:
                      const std::optional<Document>& doc, EventType eventType,
                      const std::optional<std::string>& actor = std::nullopt);
 
-    // v2.12.1 — every write path calls this (after its InFlightWriteGuard, so
+    // v2.12.1 - every write path calls this (after its InFlightWriteGuard, so
     // the reloaded document cannot be evicted again before the write) and
     // before looking the document up. Since v2.0 reads are served from LMDB
     // and no longer hot-load an evicted document, so without this an evicted

+ 144 - 0
tests/load_test/test_file_store.cpp

@@ -0,0 +1,144 @@
+// v2.12.3 client/server boundary test: the file store answers to the questions
+// smartbotic-vectorapi asked before building on it, plus three fixes.
+//
+//  - Two records holding identical bytes share one refcounted blob: deleting
+//    one leaves the other readable (asked: "is deleting one name safe?").
+//  - The size limit is a CLEAN refusal: InvalidArgument, reason
+//    "file_too_large", enforced while the upload streams. It used to be
+//    checked only after the whole body was buffered, and surfaced as Internal.
+//    A disallowed MIME type likewise: "mime_type_not_allowed".
+//  - A download streams from disk; checked here by byte-for-byte equality of
+//    a file at the size limit.
+//  - dropProject deletes the project's FILES. They used to survive it - served
+//    to a later project of the same name. A blob another project also holds
+//    must survive (refcount), checked across a restart.
+//
+// The .sh runs the server with a 1 MB cap and an allow-list of text/* and
+// application/octet-stream.
+
+#include <smartbotic/database/client.hpp>
+#include <iostream>
+#include <string>
+
+using namespace smartbotic::database;
+using Code = Client::ErrorCode;
+static int pass = 0, fail = 0;
+static void ck(bool c, const std::string& m) {
+    if (c) { ++pass; } else { ++fail; std::cerr << "FAIL: " << m << "\n"; }
+}
+static const char* ADDR = "127.0.0.1:9021";
+static std::vector<uint8_t> bytes(size_t n, uint8_t seed) {
+    std::vector<uint8_t> v(n);
+    for (size_t i = 0; i < n; ++i) v[i] = static_cast<uint8_t>((i * 31 + seed) & 0xFF);
+    return v;
+}
+static Client::FileUploadMeta meta(const std::string& name, const std::string& mime = "application/octet-stream") {
+    Client::FileUploadMeta m;
+    m.name = name;
+    m.mime_type = mime;
+    m.file_type = "document";
+    return m;
+}
+
+static void beforeRestart() {
+    Client c({.address = ADDR, .project = "acme"});
+    c.connect();
+
+    // ---- dedup + delete one name
+    auto blob = bytes(20000, 7);
+    auto a = c.uploadFile(blob, meta("a.bin"));
+    auto b = c.uploadFile(blob, meta("b.bin"));
+    ck(!a.id.empty() && !b.id.empty() && a.id != b.id, "two names, two records");
+    ck(b.deduplicated && a.checksum == b.checksum, "identical bytes share one blob (deduplicated)");
+    ck(c.deleteFile(a.id), "delete one of the two names");
+    ck(c.downloadFile(b.id) == blob, "the other name is still readable, byte for byte");
+    ck(!c.getFileInfo(a.id).has_value(), "the deleted name is gone");
+    ck(c.listFiles("", "", 100, 0, "", "b.bin").files.size() == 1, "listFiles finds a file by exact name");
+
+    // ---- size limit: a clean refusal, while streaming
+    {
+        bool threw = false;
+        Client::FailureDetail d;
+        try { c.uploadFile(bytes(2 * 1024 * 1024, 1), meta("big.bin")); }
+        catch (const Client::Error& e) {
+            threw = true;
+            if (const auto* p = Client::errorDetail(e)) d = *p; else d.code = e.code();
+        }
+        ck(threw, "an upload over the limit is refused");
+        ck(d.code == Code::InvalidArgument, "over the limit: InvalidArgument (was Internal)");
+        ck(d.reason == "file_too_large", "over the limit: reason file_too_large, got '" + d.reason + "'");
+        ck(c.listFiles("", "", 100, 0, "", "big.bin").files.empty(), "over the limit: nothing stored");
+    }
+    {
+        // exactly at the limit is accepted, and streams back intact
+        auto atLimit = bytes(1024 * 1024, 3);
+        auto r = c.uploadFile(atLimit, meta("limit.bin"));
+        ck(!r.id.empty() && r.size == atLimit.size(), "an upload of exactly the limit is accepted");
+        ck(c.downloadFile(r.id) == atLimit, "a 1 MB file downloads intact (streamed from disk)");
+    }
+
+    // ---- MIME allow-list: a clean refusal too
+    {
+        Client::FailureDetail d;
+        try { c.uploadFile(bytes(100, 2), meta("x.png", "image/png")); }
+        catch (const Client::Error& e) { if (const auto* p = Client::errorDetail(e)) d = *p; else d.code = e.code(); }
+        ck(d.code == Code::InvalidArgument && d.reason == "mime_type_not_allowed",
+           "a disallowed MIME type: InvalidArgument, mime_type_not_allowed (was Internal)");
+        auto ok = c.uploadFile(bytes(100, 2), meta("x.txt", "text/plain"));
+        ck(!ok.id.empty(), "an allowed MIME type is accepted");
+    }
+
+    // ---- dropProject deletes the project's files, not shared content
+    Client admin({.address = ADDR, .project = "default"});
+    admin.connect();
+    admin.createProject("fp");
+    Client fp({.address = ADDR, .project = "fp"});
+    fp.connect();
+    auto shared = bytes(30000, 9);
+    auto own = fp.uploadFile(bytes(25000, 4), meta("own.bin"));
+    auto mine = fp.uploadFile(shared, meta("shared.bin"));
+    auto theirs = c.uploadFile(shared, meta("shared-elsewhere.bin"));   // project acme, same bytes
+    ck(!own.id.empty() && !mine.id.empty() && !theirs.id.empty(), "fp holds two files, acme one with shared bytes");
+    admin.dropProject("fp");
+    admin.createProject("fp");
+    ck(fp.listFiles().files.empty(), "recreated project: no files survive the drop");
+    ck(!fp.getFileInfo(own.id).has_value(), "recreated project: the dropped file id is gone");
+    ck(c.downloadFile(theirs.id) == shared, "another project's file with the same bytes survives (refcount)");
+    admin.dropProject("fp");
+    std::cout << "theirs=" << theirs.id << " b=" << b.id << "\n";
+}
+
+static void afterRestart(const std::string& theirsId, const std::string& bId) {
+    Client c({.address = ADDR, .project = "acme"});
+    c.connect();
+    ck(c.downloadFile(theirsId).size() == 30000, "after restart: the shared-bytes file is intact");
+    ck(c.downloadFile(bId).size() == 20000, "after restart: the deduplicated survivor is intact");
+    Client admin({.address = ADDR, .project = "default"});
+    admin.connect();
+    admin.createProject("fp");
+    Client fp({.address = ADDR, .project = "fp"});
+    fp.connect();
+    ck(fp.listFiles().files.empty(), "after restart: the dropped project's files did not come back");
+}
+
+// One oversized upload, nothing else, so the .sh can compare the server's peak
+// resident memory (VmHWM) before and after: refusing WHILE streaming keeps the
+// server from buffering the whole body, which is the point of the fix and is
+// otherwise invisible - the refusal itself looks the same either way.
+static void oversize() {
+    Client c({.address = ADDR, .project = "acme"});
+    c.connect();
+    bool refused = false;
+    try { c.uploadFile(std::vector<uint8_t>(64 * 1024 * 1024, 0x5A), meta("huge.bin")); }
+    catch (const Client::Error& e) { refused = e.code() == Code::InvalidArgument; }
+    ck(refused, "a 64 MB upload against a 1 MB cap is refused");
+}
+
+int main(int argc, char** argv) {
+    const std::string phase = argc > 1 ? argv[1] : "before-restart";
+    if (phase == "oversize") oversize();
+    else if (phase == "before-restart") beforeRestart();
+    else afterRestart(argc > 2 ? argv[2] : "", argc > 3 ? argv[3] : "");
+    std::cout << "\n[" << phase << "] passed=" << pass << " failed=" << fail << "\n";
+    return fail == 0 ? 0 : 1;
+}

+ 93 - 0
tests/load_test/test_file_store.sh

@@ -0,0 +1,93 @@
+#!/usr/bin/env bash
+# v2.12.3 client/server boundary e2e - the file store: dedup, size and MIME
+# refusals, streaming download, and dropProject deleting files, across a real
+# restart. See
+# test_file_store.cpp for what each assertion covers.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-file-store
+PORT=9021
+
+rm -rf "$DIR"
+mkdir -p "$DIR/data"
+
+cat > "$DIR/config.json" <<CFG
+{
+  "storage": {
+    "data_directory": "$DIR/data",
+    "bind_address": "127.0.0.1",
+    "rpc_port": $PORT,
+    "encryption": { "enabled": false },
+    "migrations": { "enabled": false },
+    "replication": { "enabled": false },
+    "files": { "max_file_size_mb": 1, "allowed_types": ["text/*", "application/octet-stream"] }
+  }
+}
+CFG
+
+echo "=== building test binary ==="
+g++ -std=c++20 -O1 -o "$DIR/t" test_file_store.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+SERVER_PID=""
+boot() {
+    "$ROOT/build/service/smartbotic-database" --config "$DIR/config.json" \
+        > "$DIR/server-$1.log" 2>&1 &
+    SERVER_PID=$!
+    for _ in $(seq 1 60); do
+        grep -q "Notified systemd: READY" "$DIR/server-$1.log" && return 0
+        sleep 0.5
+    done
+    echo "server failed to become ready; log:"
+    tail -30 "$DIR/server-$1.log"
+    exit 1
+}
+stop() { kill "$SERVER_PID" 2>/dev/null || true; wait "$SERVER_PID" 2>/dev/null || true; }
+trap stop EXIT
+
+run() {   # run <phase> [args...]
+    set +e
+    LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" "$@" | tee "$DIR/out-$1.txt"
+    local rc=${PIPESTATUS[0]}
+    set -e
+    if [[ $rc -ne 0 ]]; then
+        echo ""
+        echo "FAILED in phase $1 - server log tail:"
+        tail -30 "$DIR"/server-*.log | tail -30
+        exit $rc
+    fi
+}
+
+echo "=== phase 1 ==="
+boot 1
+
+# First, on a fresh server: the peak RSS (VmHWM) only ever rises, so this has to
+# run before anything else could have pushed the peak past what it measures.
+echo "=== memory: an oversized upload must not be buffered whole ==="
+hwm() { awk '/VmHWM/{print $2}' /proc/$SERVER_PID/status; }
+before=$(hwm)
+run oversize
+after=$(hwm)
+grew=$(( (after - before) / 1024 ))
+echo "server peak RSS grew by ${grew} MB for a 64 MB upload refused at 1 MB"
+if [[ $grew -ge 32 ]]; then
+    echo "FAILED - the server buffered the oversized upload (grew ${grew} MB)"
+    exit 1
+fi
+
+run before-restart
+stop
+
+echo "=== restart: files must stay deleted ==="
+boot 2
+ids=$(grep -o 'theirs=[^ ]* b=[^ ]*' "$DIR/out-before-restart.txt" | sed 's/theirs=//; s/ b=/ /')
+run after-restart $ids
+
+echo ""
+echo "OK - file store e2e passed"

Nem az összes módosított fájl került megjelenítésre, mert túl sok fájl változott