diff --git a/docs/concepts/features/configuration/server-config/storing-data.mdx b/docs/concepts/features/configuration/server-config/storing-data.mdx index cdd4621e2ddcf..74458761d9c76 100644 --- a/docs/concepts/features/configuration/server-config/storing-data.mdx +++ b/docs/concepts/features/configuration/server-config/storing-data.mdx @@ -510,10 +510,11 @@ disk-level and server-level settings surface. is committed to the pool (never the object-storage key prefix). Defaults to `/disks//cas_scratch/`. A relative override is anchored to the server data path, not the process's current working directory. -- `cas_staging_backend` — `local` (default) or `s3`. Selects where in-flight part data is staged before - being committed into the pool; `local` is byte-for-byte the original write path, `s3` enables - S3-native staging. A writable disk configured with `s3` must support native same-store copy and - fails closed instead of falling back to client-side copy. +- `cas_staging_backend` — `local` (default) or `s3`. Selects where CAS stages part files that always + use blob placement, such as column data and marks. A writable disk configured with `s3` requires native + same-store copy. Files eligible for inline placement stay in memory up to 1 MiB per file. + Crossing that threshold spills the file to local temporary storage with either backend. At commit, + CAS can also select smaller files for blob placement to fit the 16 MiB inline budget per manifest. - `cas_blob_hash` — `cityhash128` (default), `xxh3-128`, or `sha256`. Selects the pool's blob content-hash function. The choice is fixed at pool creation; a reopen whose `cas_blob_hash` disagrees with the pool's recorded algorithm fails closed. See diff --git a/docs/en/antalya/metrics_and_events.md b/docs/en/antalya/metrics_and_events.md index 30356a6f1cde6..30b36530b330f 100644 --- a/docs/en/antalya/metrics_and_events.md +++ b/docs/en/antalya/metrics_and_events.md @@ -105,6 +105,12 @@ This counter covers batch deletion of write-once keys. | --- | --- | --- | | `CASBulkDeleteRequests` | `Number` | Number of CAS batch delete requests: one DeleteObjects carrying up to 1000 write-once keys (manifest bodies, ref logs, ref snapshots). The per-key class counters (CASManifestDelete, CASRootDelete) say how many keys each request carried. | +#### Manifest inline budget {#cas-manifest-inline-budget} + +| Event | Type | Description | +| --- | --- | --- | +| `CASManifestInlineEntriesSelectedForBlob` | `Number` | Number of staged CAS file entries selected for blob placement because their manifest exceeded the total inline byte budget. | + #### Manifest requests {#cas-manifest-requests} These counters total object-store requests for manifest keys. diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index c9b79615610b7..e3f0c10d8c131 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -910,6 +910,7 @@ The server successfully detected this situation and will download merged part fr M(CASRefRepoint, "Number of CAS committed-reference repoints that republish a manifest. Growth indicates standalone part updates or removals.", ValueType::Number) \ M(CASRefMove, "Number of CAS committed-reference renames done as one ref-log owner move, with no manifest republication.", ValueType::Number) \ M(CASOwnershipConflict, "Number of CAS operations refused with CAS_OWNERSHIP_CONFLICT: the committed reference the writer had read was moved, dropped or repointed before its change landed.", ValueType::Number) \ + M(CASManifestInlineEntriesSelectedForBlob, "Number of staged CAS file entries selected for blob placement because their manifest exceeded the total inline byte budget.", ValueType::Number) \ M(CASManifestPut, "Number of CAS manifest PUT requests. Grows with manifest creation and indicates metadata write traffic.", ValueType::Number) \ M(CASManifestPutDeduplicated, "Number of CAS deduplicating manifest PUT requests. Grows when existing manifests are reused.", ValueType::Number) \ M(CASManifestOverwrite, "Number of CAS manifest overwrite requests. Growing values indicate repeated manifest replacement.", ValueType::Number) \ diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index 130c3222ee058..0802a4a2ec397 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -36,6 +36,7 @@ namespace ProfileEvents { extern const Event CASBlobUploadFanoutBatches; extern const Event CASBlobUploadFanoutTasks; + extern const Event CASManifestInlineEntriesSelectedForBlob; } namespace fs = std::filesystem; @@ -48,6 +49,7 @@ namespace ErrorCodes extern const int CORRUPTED_DATA; extern const int FILE_DOESNT_EXIST; extern const int LOGICAL_ERROR; + extern const int LIMIT_EXCEEDED; extern const int NOT_IMPLEMENTED; } } @@ -106,24 +108,12 @@ namespace "content-addressed write path.", op); } -/// Inline candidates above this size spill to a blob instead of riding the tree object — a tuning -/// knob (could become a disk setting later). Keeps the tree object bounded against an unexpectedly -/// large eager file. -constexpr size_t INLINE_CAP = 1024 * 1024; /// 1 MiB - bool hasTopLevelFile(const std::vector & entries) { return std::any_of(entries.begin(), entries.end(), [](const Cas::ManifestEntry & e) { return e.path.find('/') == std::string::npos; }); } -/// A committed manifest with no top-level file is not a part: it is the scratch of a sub-storage nested -/// under the part's directory (`createTemporaryTextIndexStorage`), committed at the part's own name. -bool isNestedScratchManifest(const std::vector & entries) -{ - return !hasTopLevelFile(entries); -} - } ContentAddressedTransaction::ContentAddressedTransaction(ContentAddressedMetadataStorage & metadata_storage_) @@ -295,7 +285,7 @@ std::shared_ptr ContentAddressedTransaction::copySourceOf(const } void ContentAddressedTransaction::confirmCopySources(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, - const PendingRefs & pending_refs) + const PendingRefs & blob_refs_with_upload_requests) { /// An entry whose bytes this transaction uploads is protected by its own precommit, whatever it was copied from. std::vector> sources; @@ -305,7 +295,7 @@ void ContentAddressedTransaction::confirmCopySources(const Cas::RootNamespace & { return s->part == source.part && s->manifest_ref == source.manifest_ref; }); }; for (const auto & entry : st.entries) - if (auto source = copySourceOf(st, entry.path); source && !pending_refs.contains(entry.ref) && !listed(*source)) + if (auto source = copySourceOf(st, entry.path); source && !blob_refs_with_upload_requests.contains(entry.ref) && !listed(*source)) sources.push_back(std::move(source)); /// A source this transaction changes before it publishes the copy no longer commits the manifest the copy @@ -402,20 +392,76 @@ ContentAddressedTransaction::routeOf(const std::string & path) const return metadata_storage.route(*p); } -Cas::ManifestId ContentAddressedTransaction::precommitAndUpload(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, - const PendingRefs & pending_refs) +namespace +{ + +/// Only entries supplied by this transaction may change placement. The caller has already +/// excluded shadowed and removed paths from the retained base. +std::vector applyManifestInlineBudget( + std::vector & entries_to_add_or_replace, uint64_t inline_bytes_from_unchanged_base_entries, Cas::BlobHashAlgo algo) +{ + uint64_t total_inline_bytes = inline_bytes_from_unchanged_base_entries; + for (const auto & entry : entries_to_add_or_replace) + if (entry.placement == Cas::EntryPlacement::Inline) + total_inline_bytes += entry.inline_bytes.size(); + + if (total_inline_bytes <= Cas::kMaxManifestInlineBytesTotal) + return {}; + + std::vector candidates; + for (auto & entry : entries_to_add_or_replace) + if (entry.placement == Cas::EntryPlacement::Inline && !entry.inline_bytes.empty()) + candidates.push_back(&entry); + + std::sort(candidates.begin(), candidates.end(), [](const auto * lhs, const auto * rhs) + { + if (lhs->inline_bytes.size() != rhs->inline_bytes.size()) + return lhs->inline_bytes.size() > rhs->inline_bytes.size(); + return lhs->path < rhs->path; + }); + + std::vector blob_upload_requests; + for (auto * entry : candidates) + { + /// Decoded Inline entries borrowed from a committed manifest have no serialized BlobRef. + const size_t size = entry->inline_bytes.size(); + entry->ref = Cas::poolContentHash(algo, entry->inline_bytes); + + blob_upload_requests.push_back({entry->ref, Cas::BlobSource::fromString(std::exchange(entry->inline_bytes, {})), size}); + + entry->blob_size = size; + entry->placement = Cas::EntryPlacement::Blob; + total_inline_bytes -= size; + + if (total_inline_bytes <= Cas::kMaxManifestInlineBytesTotal) + break; + } + ProfileEvents::increment(ProfileEvents::CASManifestInlineEntriesSelectedForBlob, blob_upload_requests.size()); + return blob_upload_requests; +} + +} + +Cas::ManifestId ContentAddressedTransaction::precommitAndUpload( + const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, const PendingRefs & blob_refs_with_upload_requests, + const std::vector & blob_upload_requests) { - /// Edge before observe: the precommit names every blob before `putBlob` observes one, so a condemnation between - /// the upload and the promote cannot delete a body this build relies on. + /// Edge before observe: the precommit names every blob before the pool observes it. const Cas::ManifestId id = st.build->stageManifest(st.entries); st.build->precommitAdd(ns, ref, id); - confirmCopySources(ns, ref, st, pending_refs); - uploadPendingBlobs(st); + confirmCopySources(ns, ref, st, blob_refs_with_upload_requests); + + if (!blob_upload_requests.empty()) + Cas::fanOutBlobUploads(*st.build, blob_upload_requests, Cas::blobUploadPool()); + return id; } -void ContentAddressedTransaction::uploadPendingBlobs(PartStaging & st) +void ContentAddressedTransaction::appendStagedBlobUploads(const PartStaging & st, std::vector & blob_upload_requests) const { + if (st.pending_blobs.empty()) + return; + /// Build the set of blob hashes actually referenced by the staged manifest. Only Blob /// entries represent pending content uploads — Inline are not pending blobs. A pending_blob whose /// hash is NOT in this set had its entry removed by unlinkFile/replaceFile and must not be uploaded @@ -425,7 +471,7 @@ void ContentAddressedTransaction::uploadPendingBlobs(PartStaging & st) if (entry.placement == Cas::EntryPlacement::Blob) referenced_hashes.insert(entry.ref); - /// Build one upload request per referenced pending blob. Duplicate refs (staged-hardlink copies push + /// Build one blob upload request per referenced pending blob. Duplicate refs (staged-hardlink copies push /// a copy of the record) are collapsed by `fanOutBlobUploads`' grouping, which SUBSUMES the former /// duplicate-membership filter here — the fan-out launches one task per unique ref and merges one /// dep. Local staging re-opens the payload file directly. S3 staging owns a complete @@ -433,8 +479,7 @@ void ContentAddressedTransaction::uploadPendingBlobs(PartStaging & st) /// `publication_attempted` flag, so at most one publication across all of them copies that object /// verbatim: the first one, and only after an absent destination. Every other publication re-opens /// it, validates and skips its fixed envelope, and streams only the payload under a fresh envelope. - std::vector requests; - requests.reserve(st.pending_blobs.size()); + blob_upload_requests.reserve(blob_upload_requests.size() + st.pending_blobs.size()); for (const auto & pb : st.pending_blobs) { if (!referenced_hashes.contains(pb.ref)) @@ -486,16 +531,8 @@ void ContentAddressedTransaction::uploadPendingBlobs(PartStaging & st) } /// `declared_size` mirrors `source.size` (both are `pb.size`); the fan-out fail-closes if they /// ever diverge, so build them together from the one authority. - requests.push_back(Cas::BlobUploadRequest{pb.ref, std::move(source), pb.size}); + blob_upload_requests.push_back(Cas::BlobUploadRequest{pb.ref, std::move(source), pb.size}); } - - if (requests.empty()) - return; - - /// Fan out the uploads on the server-wide pool (spec §1). The fan-out enforces - /// one-task-per-unique-ref grouping, the merge-nothing failure contract, and merges every result - /// into `st.build`'s dep set on THIS (the owning writer) thread after the join. - Cas::fanOutBlobUploads(*st.build, requests, Cas::blobUploadPool()); } void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, @@ -523,87 +560,111 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, return; } - PendingRefs pending_refs; - for (const auto & pb : st.pending_blobs) - pending_refs.insert(pb.ref); + std::shared_ptr existing_ref_view; + if (!st.entries.empty() || !st.content_removed.empty()) + existing_ref_view = metadata_storage.partAccess()->getView({ns, ref}, Cas::Freshness::ForceFresh); + + /// A merge can use two disk transactions under `tmp_merge_`. The first publishes the `text_index_tmp/` segments. + /// Once the merge has read them and written the final index files, the part transaction can drop the ref to the + /// segment manifest and publish the complete part manifest under the same name. + /// Check `st.build` before `buildFor` below so a staged move that needs a build only for uploads keeps its base manifest. + const bool should_drop_existing_ref = existing_ref_view && st.build + && (!st.base_manifest_ref || *st.base_manifest_ref == existing_ref_view->manifestId().ref) + && !hasTopLevelFile(existing_ref_view->manifest()->entries) + && hasTopLevelFile(st.entries); + + /// A rewrite requires the ref to still point to its base manifest. + /// A write with no base expects the name to be free unless it can replace the temporary segment ref described above. + if (st.base_manifest_ref && (!existing_ref_view || existing_ref_view->manifestId().ref != *st.base_manifest_ref)) + Cas::throwCasOwnershipConflict("ContentAddressedTransaction: committed part {}/{} was moved, dropped or repointed while its rewrite was staged; " + "the operation must be re-resolved", ns.string(), ref); + if (!st.base_manifest_ref && existing_ref_view && !should_drop_existing_ref) + Cas::throwCasOwnershipConflict("ContentAddressedTransaction: {}/{} was published by another writer while this transaction was staging it", ns.string(), ref); + + std::vector merged_manifest_entries; + uint64_t inline_bytes_from_unchanged_base_entries = 0; + + /// After `BEGIN TRANSACTION`, an `INSERT` can publish part `all_1_1_0` in CAS while the SQL transaction is still open. + /// At `COMMIT`, `MergeTree` rewrites `txn_version.txt` to record the assigned commit sequence number. That disk transaction + /// stages only the new `txn_version.txt`. Carry forward the base entries for `data.bin` and the other untouched files, + /// including their inline bytes in the budget for the new manifest. + if (existing_ref_view && !should_drop_existing_ref) + { + std::unordered_set staged_entry_paths; + for (const auto & entry : st.entries) + staged_entry_paths.insert(entry.path); + for (const auto & entry : existing_ref_view->manifest()->entries) + { + if (st.content_removed.contains(entry.path) || staged_entry_paths.contains(entry.path)) + continue; + if (entry.placement == Cas::EntryPlacement::Inline) + inline_bytes_from_unchanged_base_entries += entry.inline_bytes.size(); + merged_manifest_entries.push_back(entry); + } + if (inline_bytes_from_unchanged_base_entries > Cas::kMaxManifestInlineBytesTotal) + throw Exception(ErrorCodes::LIMIT_EXCEEDED, + "Unchanged manifest entries for {}/{} contain {} inline bytes, exceeding the cap of {}", + ns.string(), ref, inline_bytes_from_unchanged_base_entries, Cas::kMaxManifestInlineBytesTotal); + } + + auto blob_upload_requests = applyManifestInlineBudget(st.entries, inline_bytes_from_unchanged_base_entries, metadata_storage.store()->writeAlgo()); + if (!blob_upload_requests.empty() && !st.build) + buildFor({.ns = ns, .ref = ref, .file = {}}, st); + + appendStagedBlobUploads(st, blob_upload_requests); + + PendingRefs blob_refs_with_upload_requests; + + for (const auto & blob_upload_request : blob_upload_requests) + blob_refs_with_upload_requests.insert(blob_upload_request.ref); - /// A blob entry's body is either uploaded by this part or confirmed at its committed source; a part may be - /// promoted before any other part of this transaction publishes, so nothing else can supply the body. for (const auto & entry : st.entries) - if (entry.placement == Cas::EntryPlacement::Blob && !pending_refs.contains(entry.ref) && !copySourceOf(st, entry.path)) + if (entry.placement == Cas::EntryPlacement::Blob && !blob_refs_with_upload_requests.contains(entry.ref) && !copySourceOf(st, entry.path)) throw Exception(ErrorCodes::LOGICAL_ERROR, "ContentAddressedTransaction: staged blob '{}' of {}/{} has neither a pending upload nor a copy source", entry.path, ns.string(), ref); - /// For committed-ref standalone writes and removal marks, `st.entries` holds only the - /// CHANGED/ADDED entries (see stageBlobPartFile / the inline writeFile path) — never the whole - /// part once the ref already exists; `st.content_removed` holds paths a same-transaction - /// unlinkFile staged for removal (§6). Carry every OTHER committed entry forward (minus any - /// content_removed path) and republish once via the repoint path, rather than letting the - /// PartWriteTxn path below replace the manifest with just the delta. That would either reject a - /// genuine content change or silently drop untouched files. This handles both sub-cases the - /// interface allows: entries staged - /// WITH a PartWriteTxn (this transaction uploaded new content) and WITHOUT one (a former mutable - /// per-part file that is now an ordinary tree entry, or a marks-only removal with no writes). - if (!st.entries.empty() || !st.content_removed.empty()) + if (should_drop_existing_ref) + { + if (metadata_storage.partAccess()->dropRefExact({ns, ref}, existing_ref_view->manifestId().ref) == Cas::Removal::Mismatch) + Cas::throwCasOwnershipConflict("ContentAddressedTransaction: scratch ref {}/{} was repointed while this transaction was staging the part", + ns.string(), ref); + + st.base_manifest_ref.reset(); + existing_ref_view.reset(); + } + else if (existing_ref_view) { - auto view = metadata_storage.partAccess()->getView({ns, ref}, Cas::Freshness::ForceFresh); - /// A build that stages the part's own top-level files replaces a nested scratch manifest at the - /// same name instead of merging into it. - if (view && st.build && (!st.base_manifest_ref || *st.base_manifest_ref == view->manifestId().ref) - && isNestedScratchManifest(view->manifest()->entries) && hasTopLevelFile(st.entries)) + /// The scratch precommit protects new blobs until repointRef publishes the merged manifest. + if (st.build) + (void)precommitAndUpload(ns, ref, st, blob_refs_with_upload_requests, blob_upload_requests); + + for (auto & entry : st.entries) + merged_manifest_entries.push_back(std::move(entry)); + + /// Test-only fault seam (Task 3 TDD): simulate a promote-time backend failure for `ref` + /// right before the durable repoint call. A no-op in production (nothing ever arms it). + if (metadata_storage.shouldFailPromoteForTest({ns, ref})) + throw Exception(ErrorCodes::ABORTED, + "ContentAddressedTransaction: test-injected promote failure for {}/{}", ns.string(), ref); + + /// Capture the exact `CommitOutcome` IMMEDIATELY -- into the caller-provided slot, before + /// the scratch-build `abandon()` below (which can itself throw), and before the test-only + /// after-promote hook (which can run arbitrary test code) -- so a later throw in either + /// cannot lose it (publish before any throwable post-commit work). + const Cas::CommitOutcome oc = metadata_storage.partAccess()->repointRef({ns, ref}, std::move(merged_manifest_entries), Cas::ProvenanceOp::Other, *st.base_manifest_ref); + out_slot = oc; /// always created=false here: this block only runs once `existing_ref_view` already resolved + /// Test-only: models a concurrent writer racing in right after this transaction's own + /// confirm (e.g. repointing `ref` again). A no-op in production. + metadata_storage.runAfterPromoteHookForTest({ns, ref}); + + if (st.build) { - if (metadata_storage.partAccess()->dropRefExact({ns, ref}, view->manifestId().ref) - == Cas::Removal::Mismatch) - Cas::throwCasOwnershipConflict("ContentAddressedTransaction: scratch ref {}/{} was repointed while this transaction was staging the part", - ns.string(), ref); - st.base_manifest_ref.reset(); - view.reset(); - } - if (st.base_manifest_ref && (!view || !(view->manifestId().ref == *st.base_manifest_ref))) - Cas::throwCasOwnershipConflict("ContentAddressedTransaction: committed part {}/{} was moved, dropped or repointed while its rewrite was staged; " - "the operation must be re-resolved", ns.string(), ref); - if (!st.base_manifest_ref && view) - Cas::throwCasOwnershipConflict("ContentAddressedTransaction: {}/{} was published by another writer while this transaction was staging it", ns.string(), ref); - if (view) - { - /// `repointRef` promotes through its own build, which adopts existing bodies and uploads none. This build's - /// scratch precommit protects the uploads until that promote, then is abandoned, never promoted. - if (st.build) - (void)precommitAndUpload(ns, ref, st, pending_refs); - - std::vector merged; - for (const auto & e : view->manifest()->entries) - if (!st.content_removed.contains(e.path) - && std::none_of(st.entries.begin(), st.entries.end(), - [&](const Cas::ManifestEntry & s) { return s.path == e.path; })) - merged.push_back(e); - for (auto & s : st.entries) - merged.push_back(std::move(s)); - - /// Test-only fault seam (Task 3 TDD): simulate a promote-time backend failure for `ref` - /// right before the durable repoint call. A no-op in production (nothing ever arms it). - if (metadata_storage.shouldFailPromoteForTest({ns, ref})) - throw Exception(ErrorCodes::ABORTED, - "ContentAddressedTransaction: test-injected promote failure for {}/{}", ns.string(), ref); - - /// Capture the exact `CommitOutcome` IMMEDIATELY -- into the caller-provided slot, before - /// the scratch-build `abandon()` below (which can itself throw), and before the test-only - /// after-promote hook (which can run arbitrary test code) -- so a later throw in either - /// cannot lose it (publish before any throwable post-commit work). - const Cas::CommitOutcome oc = metadata_storage.partAccess()->repointRef({ns, ref}, std::move(merged), Cas::ProvenanceOp::Other, *st.base_manifest_ref); - out_slot = oc; /// always created=false here: this block only runs once `view` already resolved - /// Test-only: models a concurrent writer racing in right after this transaction's own - /// confirm (e.g. repointing `ref` again). A no-op in production. - metadata_storage.runAfterPromoteHookForTest({ns, ref}); - if (st.build) - { - st.build->abandon(); /// scratch precommit's protecting job is done; the real manifest is live - st.build.reset(); /// never re-abandon this build from the destructor - } - st.published = true; - return; + st.build->abandon(); /// scratch precommit's protecting job is done; the real manifest is live + st.build.reset(); /// never re-abandon this build from the destructor } + st.published = true; + return; } if (!st.build) @@ -611,7 +672,7 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, "ContentAddressedTransaction: staged entries or removal marks for {}/{} without a Build", ns.string(), ref); /// Promote is an atomic owner move that validates every blob dependency proof. - const Cas::ManifestId id = precommitAndUpload(ns, ref, st, pending_refs); + const Cas::ManifestId manifest_id = precommitAndUpload(ns, ref, st, blob_refs_with_upload_requests, blob_upload_requests); /// Test-only fault seam (Task 3 TDD): simulate a promote-time backend failure for `ref` right /// before the durable promote call. A no-op in production (nothing ever arms it). @@ -624,7 +685,7 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, /// before the promote's own append confirms). Captured into `out_slot` IMMEDIATELY -- before the /// test-only after-promote hook below (which can run arbitrary test code) or `st.build.reset()` /// -- so a later throw there cannot lose it. - const Cas::CommitOutcome oc = metadata_storage.partAccess()->promoteBuild(*st.build, {ns, ref}, st.build->buildId(), id); + const Cas::CommitOutcome oc = metadata_storage.partAccess()->promoteBuild(*st.build, {ns, ref}, st.build->buildId(), manifest_id); out_slot = oc; /// Test-only: models a concurrent writer racing in right after this transaction's own confirm. A /// no-op in production. @@ -699,6 +760,8 @@ void ContentAddressedTransaction::commit(const TransactionCommitOptionsVariant & } catch (...) { + /// Publication may already have moved inline bytes out of staged entries into blob upload requests. + /// Retrying requires a new transaction with fresh entries. failed = true; /// Compensating rollback. Best-effort: a ref we cannot unpublish becomes unreferenced debris /// (GC-reclaimed); never mask the original failure with a rollback failure. Only a slot whose @@ -1081,128 +1144,86 @@ std::unique_ptr ContentAddressedTransaction::writeFile( /// filename left to special-case. During part build these files land in the initial manifest with /// every other staged file; a standalone write on an already-committed part repoints. - /// A CONTENT part file that must stay a blob (per-column data/marks, primary.idx): spill + hash, - /// then stage the blob as PENDING (precommit-first). The blob is NOT uploaded/promoted here; - /// `publishStaging` uploads it (Local) or promotes the S3 staging object post-precommit. - /// Staging records no dependency proof and performs no pool operation; successful post-precommit - /// publication records `Materialized`. - if (Cas::partFileMustStayBlob(r->file)) + const bool must_stay_blob = Cas::partFileMustStayBlob(r->file); + const auto hash_algo = metadata_storage.store()->writeAlgo(); + + if (must_stay_blob && metadata_storage.stagingBackend() == Cas::StagingBackend::S3) { - /// When this disk explicitly opts in to `staging_backend=s3`, `startup` has already required - /// provider-native same-store copy, so stream directly to a fresh per-mount staging object - /// while hashing. The default `local` setting keeps the existing local-temp-file path below. - /// Hash with this pool's node-local write algorithm rather than a hardcoded city hash; - /// `PoolMeta` no longer records a single pool-wide algorithm -- - /// mixed-algo pools track `algos_used`; `writeAlgo()` is the write-mint accessor now). - const auto hash_algo = metadata_storage.store()->writeAlgo(); - /// `hash_hex` is rendered by the streaming write buffer at `hash_algo`'s own width — - /// parse it back at that SAME width via `Cas::codecFor(hash_algo)` (never a pool-wide - /// `DigestCodec`, which no longer exists) into a full `BlobRef` pair. - - if (metadata_storage.stagingBackend() == Cas::StagingBackend::S3) - { - /// Build the fixed-length CABL envelope header now (before - /// the payload is streamed) so the staging object holds `[header][payload]` and the promote - /// stays a verbatim server-side copy. The header carries a FRESH `incarnation_tag`; `build_id` - /// is left 0 (not known at stream time — diagnostic-only, not read by GC/read paths). The - /// buffer writes this header first, UNHASHED and excluded from the reported size, so the - /// content key stays the pool's hash of `payload` and `blob_size` stays the payload size. - std::string envelope_header = buildS3StagingBlobHeader(*r); - /// The staged upload becomes durable in `sink->finalize()`, outside this request contract by - /// design, so its admission is re-checked there through the callback below, against the - /// generation captured HERE. The epoch in the key and the generation the finalize rechecks are - /// one capture, so a remount between them cannot stage new-generation bytes under an old epoch. - const Cas::PoolPtr pool = metadata_storage.store(); - const Cas::MountIncarnation incarnation = pool->captureMountIncarnation(); - const std::string staging_key = metadata_storage.stagingKey(incarnation.writer_epoch, getRandomASCIIString(32) + ".tmp"); - auto object_sink = metadata_storage.objectStorage()->writeObject(StoredObject(staging_key), WriteMode::Rewrite); - return std::make_unique( - std::move(object_sink), - staging_key, - std::move(envelope_header), - hash_algo, - buf_size, - settings.use_adaptive_write_buffer, - settings.adaptive_write_buffer_initial_size, - [this, route = *r, hash_algo](const std::string & hash_hex, size_t size, const std::string & key) - { - const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; - stageBlobPartFile(route, ref, size, key, Cas::StagingBackend::S3); - }, - [pool, generation = incarnation.fence_generation] { pool->checkFenceOrThrow(generation); }); - } + /// Build the fixed-length CABL envelope header now (before + /// the payload is streamed) so the staging object holds `[header][payload]` and the promote + /// stays a verbatim server-side copy. The header carries a FRESH `incarnation_tag`; `build_id` + /// is left 0 (not known at stream time — diagnostic-only, not read by GC/read paths). The + /// buffer writes this header first, UNHASHED and excluded from the reported size, so the + /// content key stays the pool's hash of `payload` and `blob_size` stays the payload size. + std::string envelope_header = buildS3StagingBlobHeader(*r); + /// The staged upload becomes durable in `sink->finalize()`, outside this request contract by + /// design, so its admission is re-checked there through the callback below, against the + /// generation captured HERE. The epoch in the key and the generation the finalize rechecks are + /// one capture, so a remount between them cannot stage new-generation bytes under an old epoch. + const Cas::PoolPtr pool = metadata_storage.store(); + const Cas::MountIncarnation incarnation = pool->captureMountIncarnation(); + const std::string staging_key = metadata_storage.stagingKey(incarnation.writer_epoch, getRandomASCIIString(32) + ".tmp"); + + auto object_sink = metadata_storage.objectStorage()->writeObject(StoredObject(staging_key), WriteMode::Rewrite); return std::make_unique( - metadata_storage.scratchPath(), + std::move(object_sink), + staging_key, + std::move(envelope_header), hash_algo, buf_size, settings.use_adaptive_write_buffer, settings.adaptive_write_buffer_initial_size, - [this, route = *r, hash_algo](const std::string & hash_hex, size_t size, const std::string & temp_path) + [this, route = *r, hash_algo](const std::string & hash_hex, size_t size, const std::string & key) + { + const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; + stageBlobPartFile(route, ref, size, key, Cas::StagingBackend::S3); + }, + [pool, generation = incarnation.fence_generation] { pool->checkFenceOrThrow(generation); }); + } + + /// Oversized inline candidates use local staging even on disks with S3 staging enabled. + auto create_local_blob_writer = [this, route = *r, hash_algo, buf_size, + adaptive = settings.use_adaptive_write_buffer, initial_size = settings.adaptive_write_buffer_initial_size] + { + return std::make_unique( + metadata_storage.scratchPath(), + hash_algo, + buf_size, + adaptive, + initial_size, + [this, route, hash_algo](const std::string & hash_hex, size_t size, const std::string & temp_path) { const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; stageBlobPartFile(route, ref, size, temp_path, Cas::StagingBackend::Local); }); - } + }; - /// Inline candidate (small eager metadata): buffer in memory, decide at finalize. <= INLINE_CAP - /// rides the single tree object as an Inline entry (one-GET part open); an oversized - /// candidate spills to a blob (the safety net). - return std::make_unique( - [this, route = *r](std::string bytes) + if (must_stay_blob) + return create_local_blob_writer(); + + return std::make_unique( + path, Cas::kMaxManifestInlineEntryBytes, /*create_blob_if_empty=*/false, std::move(create_local_blob_writer), + [this, route = std::move(*r), hash_algo](FinalizeResult && result) { - /// Mint via the one write hash function, `Cas::poolContentHash` (algorithm, payload) -> BlobRef - /// (`CasPartWriteTxn.h`) -- the SAME mint the streaming blob path's callers use, so an inline file - /// and a standalone blob of identical content get the same ref (same content hash identity) - /// under EVERY algo, including sha256. - const auto hash_algo = metadata_storage.store()->writeAlgo(); - const Cas::BlobRef ref = Cas::poolContentHash(hash_algo, bytes); - if (bytes.size() <= INLINE_CAP) - { - auto & st = stagingFor(route); - /// An inline (no-blob) entry still requires a PartWriteTxn. `publishStaging` stages the - /// manifest body, precommits, and promotes the ref even for a part with NO blob uploads; - /// it asserts `st.build != nullptr` whenever `st.entries` is non-empty. Without this, a - /// part whose files are ALL inline (a tiny/empty merge output, every file <= INLINE_CAP) - /// reaches `publishStaging` with entries but no PartWriteTxn -> LOGICAL_ERROR "staged entries - /// without a PartWriteTxn" -> a logical-error exception under abort_on_logical_error - /// since the inline-files feature). The blob path already establishes the PartWriteTxn via - /// `buildFor`; the inline path must do the same. - buildFor(route, st); - Cas::ManifestEntry entry; - entry.path = route.file; - entry.placement = Cas::EntryPlacement::Inline; - entry.ref = ref; /// content hash identity (same for inline and blob of same content) - /// `blob_size` stays 0 (its default) for an Inline entry — matching decode, which never - /// fills it for Inline. `entry.size()` is the logical size, derived from `inline_bytes`. - entry.inline_bytes = std::move(bytes); - putEntry(st, std::move(entry), nullptr); - } - else - { - /// Safety fallback: an unexpectedly large candidate spills to a blob (preserves the - /// invariant that big files are not held inline). Write the buffered bytes to a unique - /// local temp file (same scratchPath + random-name scheme as CaContentWriteBuffer), then - /// stage exactly like a streaming blob. - std::filesystem::create_directories(metadata_storage.scratchPath()); - const std::string temp_path = - metadata_storage.scratchPath() + "/inline_overflow_" + getRandomASCIIString(32) + ".tmp"; - { - WriteBufferFromFile tmp(temp_path); - tmp.write(bytes.data(), bytes.size()); - tmp.finalize(); - } - /// Until stageBlobPartFile takes ownership, WE own the temp file — mirror the blob path, - /// where CaContentWriteBuffer's dtor removes it unless the callback succeeded. If - /// stageBlobPartFile throws, drop the orphan instead of leaking it into scratch. This - /// fallback is always `Cas::StagingBackend::Local` — an oversized inline candidate is rare - /// enough (a safety net, not a hot path) that S3-staging mode does not cover it. - bool staged = false; - SCOPE_EXIT({ if (!staged) { std::error_code ec; std::filesystem::remove(temp_path, ec); } }); - stageBlobPartFile(route, ref, bytes.size(), temp_path, Cas::StagingBackend::Local); - staged = true; - } - }); + auto * inlined = std::get_if(&result); + if (!inlined) + return; /// The local writer already registered the pending blob. + + auto & st = stagingFor(route); + buildFor(route, st); + Cas::ManifestEntry entry; + entry.path = route.file; + entry.placement = Cas::EntryPlacement::Inline; + entry.ref = Cas::poolContentHash(hash_algo, inlined->data); + /// Closed inline candidates keep their string allocations until commit. With 64 KiB writes, + /// a 600 KiB file can retain about 1 MiB of capacity. Trimming 64 such files saves about + /// 26.5 MiB of unused capacity across the transaction. + inlined->data.shrink_to_fit(); + entry.inline_bytes = std::move(inlined->data); + putEntry(st, std::move(entry), nullptr); + }, + buf_size); } void ContentAddressedTransaction::createDirectory(const std::string &) @@ -1657,7 +1678,7 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c const Cas::ManifestRef committed_ref = committed_at_src->manifestId().ref; const auto & base_entries = committed_at_src->manifest()->entries; const bool ours = staged_source_base && *staged_source_base == committed_ref; - if (!ours && !isNestedScratchManifest(base_entries)) + if (!ours && hasTopLevelFile(base_entries)) Cas::throwCasOwnershipConflict("ContentAddressedTransaction: {} was published as a part by another writer while a staged part is renamed from it", path_from); /// Our staged edits ride on their base: rename the committed ref now (durable at this call, like @@ -1665,7 +1686,7 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c /// `publishStaging` merges the delta into it under the new name the way it does for an edit in /// place; files neither removed nor rewritten survive. The rename is conditional on the manifest /// the ownership check read. - if (ours && !isNestedScratchManifest(base_entries)) + if (ours && hasTopLevelFile(base_entries)) { const auto renamed = metadata_storage.partAccess()->renameCommittedRef(src->refKey(), dst->refKey(), committed_ref); if (!renamed) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index 84f544b4abd95..8d9271f112fe0 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -33,8 +33,8 @@ namespace DB /// `Cas::PartWriteTxn`, created lazily before the first staged dependency, so the durable manifest /// edge is established before the pool observes or uploads a new blob. /// -/// Content blobs are first represented by local or S3 staging objects and are uploaded only during -/// publication. Inline entries remain in the manifest tree when they fit `INLINE_CAP`. The +/// File writes stage blobs locally or on S3. During publication the transaction also moves +/// excess inline entries into blobs, uploading them directly from their buffered bytes. The /// destructor removes the transaction's local and S3 staging and abandons any open part builds; /// it never publishes an uncommitted ref. class ContentAddressedTransaction : public IMetadataTransaction @@ -86,8 +86,8 @@ class ContentAddressedTransaction : public IMetadataTransaction const std::string & path, size_t buf_size, WriteMode mode, const WriteSettings & settings, bool autocommit) override; - /// Creates the inner buffer for a content-addressed path. Part blobs are hashed while being - /// staged, small metadata files are accumulated in memory and classified at finalize, and + /// Creates the inner buffer for a content-addressed path. Inline candidates that outgrow + /// the per-file limit stream to local staging. Part blobs are hashed as they are written, and /// verbatim namespace or mountpoint files are read-modify-written when append is requested. std::unique_ptr writeFile( const std::string & path, @@ -223,9 +223,9 @@ class ContentAddressedTransaction : public IMetadataTransaction /// The refs of `st`'s pending uploads, collected once per publication. using PendingRefs = std::unordered_set; /// Confirms each distinct committed source of `st`'s adopted entries, skipping entries whose ref is in - /// `pending_refs`. Runs after the precommit of `st.build` is durable and before its promote; on a refusal it + /// `blob_refs_with_upload_requests`. Runs after the precommit of `st.build` is durable and before its promote; on a refusal it /// abandons the build and throws `NO_REPLICA_HAS_PART`, and on a failed read it abandons the build and rethrows. - void confirmCopySources(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, const PendingRefs & pending_refs); + void confirmCopySources(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, const PendingRefs & blob_refs_with_upload_requests); /// After this transaction renamed `from` to `to`, points the borrow of `from` at `to`, when the rename moved the /// manifest the borrow read and `to` still commits the manifest the rename produced. Any other borrow keeps its /// source, and its confirmation refuses it. @@ -249,15 +249,12 @@ class ContentAddressedTransaction : public IMetadataTransaction /// alike. S3 deletes are best-effort; a lost delete leaves debris for the mount-start sweep. void cleanupPendingTempFiles() noexcept; - /// Uploads through `st.build` only the pending blobs still referenced by `st.entries`. An entry - /// removed by `unlinkFile` or `replaceFile` is skipped, but its staging resource is still cleaned - /// by `cleanupPendingTempFiles`. Used for both new refs and committed-ref repoints. - void uploadPendingBlobs(PartStaging & st); + /// Append sources from local or S3 staging only for blob refs still named by the staged entries. + void appendStagedBlobUploads(const PartStaging & st, std::vector & blob_upload_requests) const; - /// Stages `st.entries` as a manifest of `st.build`, precommits it at `ref`, confirms the copy sources and uploads - /// the pending blobs, in that order. Returns the staged manifest's id. + /// Stage the manifest and precommit its blob refs before confirming copied files and uploading payloads. Cas::ManifestId precommitAndUpload(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, - const PendingRefs & pending_refs); + const PendingRefs & blob_refs_with_upload_requests, const std::vector & blob_upload_requests); /// Adopts a manifest entry into another part while preserving its storage state. For a pending /// blob, `copy_pending` controls whether the staging record is copied (hardlink semantics) or @@ -297,7 +294,7 @@ namespace DB::Cas /// Part files that must NOT be inlined into the tree: per-column data (`.bin`) and marks (`.mrk*`/ /// `.cmrk*`) — inlining them would force a full-part fetch and destroy column-read selectivity — plus /// `primary.idx`, which can be large (a size-threshold inlining of small primary.idx is a follow-up). -/// Everything else (the small eager metadata files) is an inline candidate, subject to INLINE_CAP. +/// Other files are inline candidates, subject to the per-entry and total manifest byte limits. bool partFileMustStayBlob(std::string_view file_name); /// Opens a locally staged blob payload of `payload_size` bytes for upload, with a read buffer no larger @@ -305,7 +302,7 @@ bool partFileMustStayBlob(std::string_view file_name); std::unique_ptr openLocalStagedBlobPayload(const std::string & path, uint64_t payload_size); /// Test-only fault-injection seams for the intra-part blob-upload fan-out. Inert in production -/// (`ContentAddressedTransaction::uploadPendingBlobs` passes `nullptr`). +/// (`ContentAddressedTransaction::precommitAndUpload` passes `nullptr`). struct BlobUploadFanoutHooksForTest { /// Invoked ONCE per DISPATCHED task, on the calling (dispatch) thread, immediately before the task @@ -453,10 +450,7 @@ class CaContentWriteBuffer : public WriteBufferFromFileBase std::function check_fence_before_finalize; }; -/// Write buffer for bytes that live INSIDE pool metadata (a small inline part file staged into the -/// manifest tree, or a verbatim namespace file PUT on finalize). Accumulates in memory (the bytes are -/// tiny) and hands them to the callback at finalize; the callback decides where they go and whether -/// they are durable immediately (verbatim) or at commit (staged into the part's manifest entries). +/// Accumulates a verbatim namespace or mountpoint file for the write performed at finalize. class CaInlineWriteBuffer : public WriteBufferFromFileBase { public: @@ -471,8 +465,7 @@ class CaInlineWriteBuffer : public WriteBufferFromFileBase private: /// Appends bytes to the in-memory payload under the base write-buffer contract. void nextImpl() override; - /// Hands the complete inline payload to the callback; the callback decides whether it is staged - /// in a manifest or written immediately as a verbatim file. + /// Passes the complete verbatim payload to the callback. void finalizeImpl() override; OnInlined on_inlined; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index ecc586c4454e8..9d5bf1bcdf55e 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -56,8 +56,6 @@ namespace /// Backpressure caps, enforced fail-closed in stageManifest before the body write returns. constexpr uint64_t kMaxManifestEntries = 1048576; -constexpr uint64_t kMaxManifestInlineBytesTotal = 16ULL << 20; /// 16 MiB -constexpr uint64_t kMaxLargestInlineEntryBytes = 1ULL << 20; /// 1 MiB /// Two thread_local_rng draws composed into a UInt128. Used both to mint build ids and to mint, on /// every upload/re-upload, a FRESH incarnation_tag (W-FRESH-TAG). @@ -169,11 +167,23 @@ BlobSource BlobSource::fromString(String bytes) { BlobSource source; source.size = bytes.size(); - /// Owning reader: `ReadBufferFromString` only borrows, and this factory outlives no single call - /// -- an owning copy per attempt removes the question entirely for a source that is small by - /// construction (this helper exists for tests and inline payloads). - source.open = [b = std::move(bytes)]() -> std::unique_ptr - { return std::make_unique(b); }; + /// Requests copied into the upload queue and readers opened on retry share the payload. + /// Each reader owns a reference independently of the lifetime of the request. + class Reader final : public ReadBufferFromString + { + public: + explicit Reader(std::shared_ptr bytes_) + : ReadBufferFromString(*bytes_), payload_owner(std::move(bytes_)) + { + } + + private: + std::shared_ptr payload_owner; + }; + source.open = [owner = std::make_shared(std::move(bytes))] + { + return std::make_unique(owner); + }; return source; } @@ -627,10 +637,10 @@ ManifestId PartWriteTxn::stageManifest(std::vector entries) { if (e.placement == EntryPlacement::Inline) { - if (e.inline_bytes.size() > kMaxLargestInlineEntryBytes) + if (e.inline_bytes.size() > kMaxManifestInlineEntryBytes) throw Exception(ErrorCodes::LIMIT_EXCEEDED, "stageManifest: inline entry '{}' of {} bytes exceeds cap {}", - e.path, e.inline_bytes.size(), kMaxLargestInlineEntryBytes); + e.path, e.inline_bytes.size(), kMaxManifestInlineEntryBytes); inline_total += e.inline_bytes.size(); } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h index c6b0aeb75609d..6ffe5920a3ea7 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h @@ -15,6 +15,9 @@ namespace DB { class WriteBuffer; } namespace DB::Cas { +inline constexpr uint64_t kMaxManifestInlineEntryBytes = 1ULL << 20; /// 1 MiB +inline constexpr uint64_t kMaxManifestInlineBytesTotal = 16ULL << 20; /// 16 MiB + /// Re-readable source for one content-addressed blob upload. /// /// `open` returns a fresh reader over exactly `size` logical bytes and may be called more than once. diff --git a/src/Disks/IO/WriteBufferInlineOrBlob.cpp b/src/Disks/IO/WriteBufferInlineOrBlob.cpp index 66a078cad7d61..b47fd6e997f26 100644 --- a/src/Disks/IO/WriteBufferInlineOrBlob.cpp +++ b/src/Disks/IO/WriteBufferInlineOrBlob.cpp @@ -34,7 +34,8 @@ void WriteBufferInlineOrBlob::spill() underlying = create_underlying(); if (!accumulated.empty()) underlying->write(accumulated.data(), accumulated.size()); - accumulated.clear(); + + String{}.swap(accumulated); } void WriteBufferInlineOrBlob::nextImpl() diff --git a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp new file mode 100644 index 0000000000000..300355f5bd787 --- /dev/null +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -0,0 +1,699 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace DB::ErrorCodes +{ + extern const int INCORRECT_DATA; +} + +/// A part or a nested scratch storage whose small files sum past the manifest's inline budget must +/// still commit: the budget bounds what rides inside the manifest, not what a part may contain. + +namespace +{ + +constexpr size_t kib = 1024; +constexpr size_t mib = 1024 * kib; +constexpr size_t inline_file_threshold = mib; +constexpr size_t inline_total_budget = 16 * mib; + +std::shared_ptr openStorage( + DB::ObjectStoragePtr objects = DB::Cas::tests::makeLocalObjectStorageForTest()) +{ + auto settings = DB::Cas::tests::makeSettingsForTest( + "test", std::filesystem::path(objects->getCommonKeyPrefix()) / "scratch"); + auto storage = std::make_shared( + objects, "pool", "srv1", "", nullptr, settings); + storage->startup(); + return storage; +} + +/// Incompressible and different for every `seed`, so no two files share a content hash. +std::string payload(size_t size, uint64_t seed) +{ + std::string bytes(size, '\0'); + uint64_t state = seed * 0x9E3779B97F4A7C15ULL + 0xD1B54A32D192ED03ULL; + for (size_t i = 0; i < size; ++i) + { + state = state * 6364136223846793005ULL + 1442695040888963407ULL; + bytes[i] = static_cast(state >> 56); + } + return bytes; +} + +void writeFileTx(DB::IMetadataTransaction & tx, const std::string & path, const std::string & bytes) +{ + auto & ca_tx = dynamic_cast(tx); + auto buf = ca_tx.writeFile(path, 65536, DB::WriteMode::Rewrite, {}); + buf->write(bytes.data(), bytes.size()); + buf->finalize(); +} + +/// Reads a committed part file the way a reader does: from the manifest when inline, else from its blob. +std::string readPartFile(const DB::ContentAddressedMetadataStorage & storage, const std::string & path) +{ + if (auto in_manifest = storage.tryGetInManifestBytes(path)) + return *in_manifest; + const auto objects = storage.getStorageObjects(path); + if (objects.size() != 1) + throw std::runtime_error("expected one object for " + path); + const DB::Cas::BlobLocation location{ + .key = objects[0].remote_path, + .offset = storage.store()->poolMeta().blob_header_len, + .length = objects[0].bytes_size}; + auto buf = storage.readBlobPayload(location, path, DB::ReadSettings{}); + std::string got; + DB::readStringUntilEOF(got, *buf); + return got; +} + +void expectReadsBack( + const DB::ContentAddressedMetadataStorage & storage, const std::string & part_dir, + const std::map & files) +{ + for (const auto & [name, bytes] : files) + { + const std::string got = readPartFile(storage, part_dir + "/" + name); + EXPECT_EQ(got.size(), bytes.size()) << name; + EXPECT_TRUE(got == bytes) << name << " does not read back byte-identical"; + } +} + +std::string commitErrorOf(DB::IMetadataTransaction & tx) +{ + try + { + tx.commit(DB::NoCommitOptions{}); + } + catch (const DB::Exception & e) + { + return std::to_string(e.code()) + ": " + e.message(); + } + return {}; +} + +DB::Cas::PartManifest manifestOf( + DB::ContentAddressedMetadataStorage & storage, const std::string & table_uuid, const std::string & ref) +{ + const auto resolved = storage.store()->resolveRef(storage.liveNamespace(table_uuid), ref); + if (!resolved) + throw std::runtime_error("ref " + ref + " does not resolve"); + return storage.store()->readManifest(resolved->manifest_id); +} + +uint64_t inlineTotal(const DB::Cas::PartManifest & manifest) +{ + uint64_t total = 0; + for (const auto & e : manifest.entries) + if (e.placement == DB::Cas::EntryPlacement::Inline) + total += e.inline_bytes.size(); + return total; +} + +/// The files one text-index segment leaves in `text_index_tmp/`, named as `BuildTextIndexTransform` names them. +std::string segmentFile(size_t segment, const std::string & index, const std::string & substream) +{ + return "text_index_tmp/tmp_all_1_2_1_" + std::to_string(segment) + "_skp_idx_" + index + substream + ".idx"; +} + +} + +/// A merge that rebuilds text indexes commits `/text_index_tmp/` as its own manifest, before the +/// part's own files exist. Its segment files are each under the per-file threshold and are many. +TEST(CASInlineCapGaps, TextIndexScratchOverTheInlineBudgetCommits) +{ + auto storage = openStorage(); + const std::string part_dir = "e01/e01e01e0-0101-4101-8101-010101010101/tmp_merge_all_1_2_1"; + + std::map files; + for (size_t segment = 0; segment < 20; ++segment) + files[segmentFile(segment, "idx_s", ".dct")] = payload(900 * kib, segment); + + auto tx = storage->createTransaction(); + for (const auto & [name, bytes] : files) + writeFileTx(*tx, part_dir + "/" + name, bytes); + + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "20 files of 900 KiB did not commit: " << error; + expectReadsBack(*storage, part_dir, files); + EXPECT_LE(inlineTotal(manifestOf(*storage, "e01e01e0-0101-4101-8101-010101010101", "tmp_merge_all_1_2_1")), + inline_total_budget); +} + +/// The same with every stream of a segment: a small sparse index, a dictionary and postings per segment, +/// for two indexes. No single file is large; the sum is. +TEST(CASInlineCapGaps, TextIndexScratchWithAllSubstreamsCommits) +{ + auto storage = openStorage(); + const std::string part_dir = "e02/e02e02e0-0202-4202-8202-020202020202/tmp_merge_all_1_2_1"; + + std::map files; + uint64_t seed = 1000; + for (const char * index : {"idx_body", "idx_attrs"}) + { + for (size_t segment = 0; segment < 40; ++segment) + { + files[segmentFile(segment, index, "")] = payload(4 * kib, ++seed); + files[segmentFile(segment, index, ".dct")] = payload(200 * kib, ++seed); + files[segmentFile(segment, index, ".pst")] = payload(60 * kib, ++seed); + } + } + + auto tx = storage->createTransaction(); + for (const auto & [name, bytes] : files) + writeFileTx(*tx, part_dir + "/" + name, bytes); + + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "240 segment files summing to about 20 MiB did not commit: " << error; + expectReadsBack(*storage, part_dir, files); +} + +/// An ordinary part: index files are written first and the files a part load reads are written last, so a +/// rule that fills the budget in write order would push exactly the load-time files out of the manifest. +TEST(CASInlineCapGaps, PartOverTheInlineBudgetCommitsAndKeepsLoadTimeFilesInline) +{ + auto storage = openStorage(); + const std::string table = "e03/e03e03e0-0303-4303-8303-030303030303/"; + const std::string tmp_part = table + "tmp_insert_all_1_1_0"; + const std::string final_part = table + "all_1_1_0"; + + std::vector> in_write_order; + in_write_order.emplace_back("data.bin", payload(64 * kib, 1)); + for (size_t index = 0; index < 20; ++index) + in_write_order.emplace_back("skp_idx_t" + std::to_string(index) + ".dct.idx", payload(900 * kib, 100 + index)); + const std::vector load_time_files{"count.txt", "columns.txt", "serialization.json", "checksums.txt"}; + in_write_order.emplace_back("count.txt", "1000"); + in_write_order.emplace_back("columns.txt", payload(34 * kib, 2)); + in_write_order.emplace_back("serialization.json", payload(222 * kib, 3)); + in_write_order.emplace_back("checksums.txt", payload(150 * kib, 4)); + + auto tx = storage->createTransaction(); + for (const auto & [name, bytes] : in_write_order) + writeFileTx(*tx, tmp_part + "/" + name, bytes); + tx->moveDirectory(tmp_part, final_part); + + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "a part with 18 MiB of small index files did not commit: " << error; + + expectReadsBack(*storage, final_part, {in_write_order.begin(), in_write_order.end()}); + const auto manifest = manifestOf(*storage, "e03e03e0-0303-4303-8303-030303030303", "all_1_1_0"); + for (const auto & name : load_time_files) + { + const auto * entry = DB::Cas::findEntry(manifest.entries, name); + ASSERT_TRUE(entry) << name; + EXPECT_EQ(entry->placement, DB::Cas::EntryPlacement::Inline) << name << " must stay in the manifest"; + } + EXPECT_LE(inlineTotal(manifest), inline_total_budget); +} + +/// Rewriting an existing path and adding an empty file consume no additional inline bytes. +TEST(CASInlineCapGaps, InlineTotalExactlyAtTheBudgetCommits) +{ + auto storage = openStorage(); + const std::string part_dir = "e04/e04e04e0-0404-4404-8404-040404040404/tmp_merge_all_1_2_1"; + + std::map files; + for (size_t segment = 0; segment < 16; ++segment) + files[segmentFile(segment, "idx_s", ".dct")] = payload(inline_file_threshold, segment); + + auto tx = storage->createTransaction(); + for (const auto & [name, bytes] : files) + writeFileTx(*tx, part_dir + "/" + name, bytes); + + writeFileTx(*tx, part_dir + "/" + files.begin()->first, files.begin()->second); + files["text_index_tmp/empty.idx"] = ""; + writeFileTx(*tx, part_dir + "/text_index_tmp/empty.idx", ""); + + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "16 files of 1 MiB did not commit: " << error; + const auto manifest = manifestOf(*storage, "e04e04e0-0404-4404-8404-040404040404", "tmp_merge_all_1_2_1"); + ASSERT_EQ(manifest.entries.size(), files.size()); + EXPECT_EQ(inlineTotal(manifest), inline_total_budget); + for (const auto & entry : manifest.entries) + EXPECT_EQ(entry.placement, DB::Cas::EntryPlacement::Inline) << entry.path; + expectReadsBack(*storage, part_dir, files); +} + +/// One byte more than the budget must not turn a committable write into a permanent failure. +TEST(CASInlineCapGaps, InlineTotalOneByteOverTheBudgetCommits) +{ + auto storage = openStorage(); + + std::map files; + for (size_t segment = 0; segment < 16; ++segment) + files[segmentFile(segment, "idx_s", ".dct")] = payload(inline_file_threshold, segment); + files[segmentFile(16, "idx_s", "")] = "x"; + + const std::string table_uuid = "e05e05e0-0505-4505-8505-050505050505"; + for (const bool reverse : {false, true}) + { + const std::string ref = reverse ? "tmp_merge_all_3_4_1" : "tmp_merge_all_1_2_1"; + const std::string directory = "e05/" + table_uuid + "/" + ref; + auto tx = storage->createTransaction(); + if (reverse) + { + for (auto it = files.rbegin(); it != files.rend(); ++it) + writeFileTx(*tx, directory + "/" + it->first, it->second); + } + else + { + for (const auto & [name, bytes] : files) + writeFileTx(*tx, directory + "/" + name, bytes); + } + ASSERT_NO_THROW(tx->commit(DB::NoCommitOptions{})); + const auto manifest = manifestOf(*storage, table_uuid, ref); + EXPECT_EQ(inlineTotal(manifest), 15 * mib + 1); + for (const auto & entry : manifest.entries) + { + const auto placement = entry.path == files.begin()->first ? DB::Cas::EntryPlacement::Blob : DB::Cas::EntryPlacement::Inline; + EXPECT_EQ(entry.placement, placement) << entry.path; + } + expectReadsBack(*storage, directory, files); + } +} + +/// A standalone rewrite of one small file of a committed part republishes the whole manifest, so the +/// files the part already holds inline count against the budget again. +TEST(CASInlineCapGaps, StandaloneWriteOntoPartAtTheBudgetCommits) +{ + auto storage = openStorage(); + const std::string table = "e06/e06e06e0-0606-4606-8606-060606060606/"; + const std::string tmp_part = table + "tmp_insert_all_1_1_0"; + const std::string final_part = table + "all_1_1_0"; + + std::map files; + files["data.bin"] = payload(64 * kib, 1); + for (size_t index = 0; index < 16; ++index) + files["skp_idx_t" + std::to_string(index) + ".dct.idx"] = payload(inline_file_threshold, 100 + index); + { + auto tx = storage->createTransaction(); + for (const auto & [name, bytes] : files) + writeFileTx(*tx, tmp_part + "/" + name, bytes); + tx->moveDirectory(tmp_part, final_part); + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "the part at exactly the budget did not commit: " << error; + } + + files["metadata_version.txt"] = "7"; + auto tx = storage->createTransaction(); + writeFileTx(*tx, final_part + "/metadata_version.txt", files["metadata_version.txt"]); + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "a 1-byte file could not be added to a committed part: " << error; + expectReadsBack(*storage, final_part, files); +} + +namespace +{ + +const std::string uuid = "e07e07e0-0707-4707-8707-070707070707"; +const std::string table_dir = "e07/" + uuid + "/"; + +void writeFullBudget(DB::IMetadataTransaction & tx, const std::string & directory, const std::string & prefix = {}) +{ + for (size_t i = 0; i < 16; ++i) + writeFileTx(tx, directory + "/" + prefix + std::to_string(i) + ".idx", payload(mib, i)); +} + +void expectBlob(DB::ContentAddressedMetadataStorage & storage, const std::string & ref, const std::string & path, const std::string & bytes) +{ + const auto manifest = manifestOf(storage, uuid, ref); + const auto * entry = DB::Cas::findEntry(manifest.entries, path); + ASSERT_NE(entry, nullptr) << path; + EXPECT_EQ(entry->placement, DB::Cas::EntryPlacement::Blob); + EXPECT_EQ(entry->blob_size, bytes.size()); + EXPECT_EQ(entry->ref, DB::Cas::poolContentHash(storage.store()->writeAlgo(), bytes)); + EXPECT_TRUE(readPartFile(storage, table_dir + ref + "/" + path) == bytes); +} + +} + +TEST(CASInlineCapGaps, RepointCountsOnlyRetainedBasePaths) +{ + auto storage = openStorage(); + const std::string ref = "all_1_1_0"; + const std::string dir = table_dir + ref; + auto tx = storage->createTransaction(); + writeFullBudget(*tx, dir); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + tx->unlinkFile(dir + "/0.idx", false, true); + writeFileTx(*tx, dir + "/1.idx", "short"); + writeFileTx(*tx, dir + "/extra.idx", payload(mib, 58)); + tx->commit(DB::NoCommitOptions{}); + + const auto manifest = manifestOf(*storage, uuid, ref); + EXPECT_EQ(inlineTotal(manifest), 15 * mib + 5); + EXPECT_FALSE(storage->existsFile(dir + "/0.idx")); + EXPECT_EQ(readPartFile(*storage, dir + "/1.idx"), "short"); + EXPECT_TRUE(readPartFile(*storage, dir + "/extra.idx") == payload(mib, 58)); +} + +TEST(CASInlineCapGaps, SpillsCommittedHardlinkWithoutChangingItsSource) +{ + auto storage = openStorage(); + const std::string src = table_dir + "all_1_1_0"; + const std::string dst_ref = "all_2_2_0"; + const std::string dst = table_dir + dst_ref; + auto tx = storage->createTransaction(); + writeFileTx(*tx, src + "/link.idx", "x"); + writeFullBudget(*tx, dst); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + tx->createHardLink(src + "/link.idx", dst + "/new.idx"); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, dst_ref, "new.idx", "x"); + EXPECT_EQ(storage->tryGetInManifestBytes(src + "/link.idx"), "x"); + EXPECT_TRUE(readPartFile(*storage, dst + "/15.idx") == payload(mib, 15)); +} + +TEST(CASInlineCapGaps, PartialMutationSpillsLargestBorrowedEntry) +{ + auto storage = openStorage(); + const std::string src = table_dir + "all_1_1_0"; + const std::string ref = "tmp_mut_all_1_1_0_2"; + const auto borrowed = payload(mib, 91); + auto tx = storage->createTransaction(); + writeFileTx(*tx, src + "/source.idx", borrowed); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + tx->createHardLink(src + "/source.idx", table_dir + ref + "/a.idx"); + writeFullBudget(*tx, table_dir + ref, "fresh"); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, ref, "a.idx", borrowed); + EXPECT_TRUE(readPartFile(*storage, src + "/source.idx") == borrowed); + for (size_t i = 0; i < 16; ++i) + EXPECT_TRUE(readPartFile(*storage, table_dir + ref + "/fresh" + std::to_string(i) + ".idx") == payload(mib, i)); +} + +TEST(CASInlineCapGaps, MovingStagedInlineIntoNestedBasePreservesThatBase) +{ + auto storage = openStorage(); + const std::string ref = "tmp_merge_all_1_2_1"; + const std::string dst = table_dir + ref; + const std::string src = table_dir + "all_3_3_0"; + auto tx = storage->createTransaction(); + writeFullBudget(*tx, dst, "text_index_tmp/"); + writeFileTx(*tx, src + "/keep.idx", "keep"); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + writeFileTx(*tx, src + "/transfer.idx", "m"); + tx->moveFile(src + "/transfer.idx", dst + "/new.idx"); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, ref, "new.idx", "m"); + EXPECT_TRUE(readPartFile(*storage, dst + "/text_index_tmp/0.idx") == payload(mib, 0)); + EXPECT_FALSE(storage->existsFile(src + "/transfer.idx")); + EXPECT_EQ(readPartFile(*storage, src + "/keep.idx"), "keep"); +} + +TEST(CASInlineCapGaps, ScratchExtensionAndReplacementHaveSeparateBudgets) +{ + auto storage = openStorage(); + const std::string ref = "tmp_merge_all_1_2_1"; + const std::string dir = table_dir + ref; + auto tx = storage->createTransaction(); + writeFullBudget(*tx, dir, "text_index_tmp/"); + writeFileTx(*tx, dir + "/text_index_tmp/small", "s"); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, ref, "text_index_tmp/0.idx", payload(mib, 0)); + + tx = storage->createTransaction(); + writeFileTx(*tx, dir + "/text_index_tmp/later", "later"); + tx->commit(DB::NoCommitOptions{}); + EXPECT_TRUE(storage->existsFile(dir + "/text_index_tmp/0.idx")); + + tx = storage->createTransaction(); + writeFullBudget(*tx, dir); + writeFileTx(*tx, dir + "/small", "f"); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, ref, "0.idx", payload(mib, 0)); + EXPECT_EQ(inlineTotal(manifestOf(*storage, uuid, ref)), 15 * mib + 1); + EXPECT_FALSE(storage->existsFile(dir + "/text_index_tmp/later")); + EXPECT_FALSE(storage->existsFile(dir + "/text_index_tmp/0.idx")); +} + +TEST(CASInlineCapGaps, UploadReadersShareBytesAndOwnIndependentPositions) +{ + std::unique_ptr first; + std::unique_ptr second; + { + auto source = DB::Cas::BlobSource::fromString("abcdef"); + auto copy = source; + first = source.open(); + second = copy.open(); + } + EXPECT_EQ(first->position(), second->position()); + char prefix[2]; + first->readStrict(prefix, sizeof(prefix)); + std::string tail, full; + DB::readStringUntilEOF(tail, *first); + DB::readStringUntilEOF(full, *second); + EXPECT_EQ(tail, "cdef"); + EXPECT_EQ(full, "abcdef"); +} + +namespace +{ + +/// The emulated backend writes a blob into a unique temporary object before renaming it. +class FailBlobWriteStorage : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + std::string fail_key; + std::atomic failures{0}; + + std::unique_ptr writeObject( + const DB::StoredObject & object, DB::WriteMode mode, std::optional attributes, + size_t buffer_size, const DB::WriteSettings & settings) override + { + if (!fail_key.empty() && object.remote_path.find(fail_key + ".publish-") != std::string::npos) + { + ++failures; + throw DB::Exception(DB::ErrorCodes::INCORRECT_DATA, "Fault while publishing the selected spill"); + } + return LocalObjectStorage::writeObject(object, mode, std::move(attributes), buffer_size, settings); + } +}; + +enum class Publication +{ + NewRef, + Repoint, + ReplaceScratch, +}; + +void checkSpillFailure(Publication mode) +{ + const auto directory_owner = DB::Cas::tests::makeLocalObjectStorageForTest(); + const auto root = directory_owner->getCommonKeyPrefix(); + auto objects = std::make_shared(DB::LocalObjectStorageSettings("fault", root, false)); + auto storage = openStorage(objects); + const auto ns = storage->liveNamespace(uuid); + const std::string ref = "tmp_merge_all_1_2_1"; + const std::string dst = table_dir + ref; + const std::string input = table_dir + "all_1_1_0"; + const bool repoint = mode == Publication::Repoint; + { + auto tx = storage->createTransaction(); + writeFileTx(*tx, input + "/source.idx", "input"); + if (repoint) + writeFullBudget(*tx, dst); + else if (mode == Publication::ReplaceScratch) + writeFileTx(*tx, dst + "/text_index_tmp/segment", "scratch"); + tx->commit(DB::NoCommitOptions{}); + } + const auto base = storage->store()->resolveRef(ns, ref); + const auto bytes = repoint ? std::string("fresh") : payload(mib, 0); + objects->fail_key = storage->store()->layout().blobKey(DB::Cas::poolContentHash(storage->store()->writeAlgo(), bytes)); + auto publish = [&] + { + auto tx = storage->createTransaction(); + if (!repoint) + writeFullBudget(*tx, dst); + writeFileTx(*tx, dst + "/extra.idx", "fresh"); + tx->commit(DB::NoCommitOptions{}); + }; + + EXPECT_THROW(publish(), DB::Exception); + ASSERT_GT(objects->failures.load(), 0); + EXPECT_TRUE(storage->store()->livePrecommitsForTest(ns).empty()); + const auto after = storage->store()->resolveRef(ns, ref); + if (repoint) + { + ASSERT_TRUE(after && base); + EXPECT_EQ(after->manifest_id, base->manifest_id); + EXPECT_TRUE(readPartFile(*storage, dst + "/0.idx") == payload(mib, 0)); + } + else + EXPECT_FALSE(after); + EXPECT_EQ(readPartFile(*storage, input + "/source.idx"), "input"); + + objects->fail_key.clear(); + if (mode == Publication::ReplaceScratch) + { + auto tx = storage->createTransaction(); + writeFileTx(*tx, dst + "/text_index_tmp/segment", "rebuilt scratch"); + tx->commit(DB::NoCommitOptions{}); + } + ASSERT_NO_THROW(publish()); + expectBlob(*storage, ref, repoint ? "extra.idx" : "0.idx", bytes); +} +} + +TEST(CASInlineCapGaps, FailedSpillDoesNotPublishNewRef) +{ + checkSpillFailure(Publication::NewRef); +} + +TEST(CASInlineCapGaps, FailedSpillPreservesRepointBase) +{ + checkSpillFailure(Publication::Repoint); +} + +TEST(CASInlineCapGaps, FailedScratchReplacementCanRebuildFromInput) +{ + checkSpillFailure(Publication::ReplaceScratch); +} + +TEST(CASInlineCapGaps, RepointRefusesBaseChangedAfterSpillUpload) +{ + auto storage = openStorage(); + const std::string ref = "all_1_1_0"; + const std::string dir = table_dir + ref; + auto tx = storage->createTransaction(); + writeFullBudget(*tx, dir); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + writeFileTx(*tx, dir + "/spill.idx", "x"); + bool uploaded = false; + bool interposed = false; + bool rival_committed = false; + /// The next manifest PUT after the blob PUT stages the combined manifest on the writer + /// thread, after fan-out has joined and before promotion checks the expected base. + storage->store()->setEventSink([&](const DB::Cas::CasEvent & event) + { + if (event.type == DB::Cas::CasEventType::BlobPut) + uploaded = true; + if (event.type == DB::Cas::CasEventType::ManifestPut && uploaded && !interposed) + { + interposed = true; + auto rival = storage->createTransaction(); + writeFileTx(*rival, dir + "/0.idx", "winner"); + rival->commit(DB::NoCommitOptions{}); + rival_committed = true; + } + }); + const std::string failure = commitErrorOf(*tx); + storage->store()->setEventSink(nullptr); + ASSERT_TRUE(rival_committed); + EXPECT_FALSE(failure.empty()); + tx.reset(); + EXPECT_EQ(readPartFile(*storage, dir + "/0.idx"), "winner"); + EXPECT_FALSE(storage->existsFile(dir + "/spill.idx")); + EXPECT_TRUE(storage->store()->livePrecommitsForTest(storage->liveNamespace(uuid)).empty()); +} + +namespace +{ + +void checkInlineCandidateWritePeak(size_t num_files, size_t chunks_per_file, Int64 limit) +{ +#if defined(SANITIZER) + UNUSED(num_files, chunks_per_file, limit); + GTEST_SKIP() << "operator new is not charged to the memory tracker under sanitizers"; +#else + auto storage = openStorage(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const std::string directory = table_dir + "all_1_1_0/"; + const Int64 peak = std::async(std::launch::async, [&] + { + MemoryTracker tracker(&total_memory_tracker, VariableContext::Process, /*log_peak_memory_usage_in_destructor_=*/false); + DB::ThreadStatus thread_status; + thread_status.memory_tracker.setParent(&tracker); + thread_status.untracked_memory_limit = 0; + + const std::string chunk(mib, 'x'); + std::vector> writers; + for (size_t i = 0; i < num_files; ++i) + writers.push_back(ca_tx.writeFile(directory + std::to_string(i) + ".dct.idx", mib, DB::WriteMode::Rewrite, {})); + for (size_t i = 0; i < chunks_per_file; ++i) + for (auto & writer : writers) + writer->write(chunk.data(), chunk.size()); + for (auto & writer : writers) + writer->finalize(); + return tracker.getPeak(); + }).get(); + ::testing::Test::RecordProperty("peak_bytes", std::to_string(peak)); + EXPECT_LE(peak, limit); +#endif +} + +} + +TEST(CASInlineCandidateMemory, ALargeInlineCandidateIsNotHeldWholeInMemory) +{ + checkInlineCandidateWritePeak(1, 64, 8 * mib); +} + +TEST(CASInlineCandidateMemory, TwoLargeInlineCandidatesOpenAtOnceStayBounded) +{ + checkInlineCandidateWritePeak(2, 32, 12 * mib); +} + +TEST(CASInlineCandidateMemory, BytesPastTheThresholdReachScratchBeforeFinalize) +{ + auto storage = openStorage(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const std::string path = table_dir + "all_1_1_0/skip.dct.idx"; + auto writer = ca_tx.writeFile(path, 64 * kib, DB::WriteMode::Rewrite, {}); + const auto bytes = payload(2 * mib, 13); + writer->write(bytes.data(), bytes.size()); + writer->sync(); + const auto & scratch = storage->scratchPath(); + size_t staged_bytes = 0; + if (std::filesystem::exists(scratch)) + for (const auto & entry : std::filesystem::directory_iterator(scratch)) + if (entry.is_regular_file()) + staged_bytes += entry.file_size(); + EXPECT_EQ(staged_bytes, bytes.size()); + + writer->cancel(); + EXPECT_TRUE(!std::filesystem::exists(scratch) || std::filesystem::is_empty(scratch)); + EXPECT_FALSE(tx->tryGetInFlightFileSize(path).has_value()); +} + +TEST(CASInlineCandidateMemory, ThresholdPreservesPlacementAndPayload) +{ + auto storage = openStorage(); + const std::string ref = "all_1_1_0"; + const std::string dir = table_dir + ref + "/"; + const auto at_limit = payload(mib, 5); + const auto over_limit = at_limit + 'Z'; + auto tx = storage->createTransaction(); + writeFileTx(*tx, dir + "at.idx", at_limit); + writeFileTx(*tx, dir + "over.idx", over_limit); + tx->commit(DB::NoCommitOptions{}); + + EXPECT_TRUE(storage->tryGetInManifestBytes(dir + "at.idx") == at_limit); + expectBlob(*storage, ref, "over.idx", over_limit); +} diff --git a/src/Disks/tests/gtest_cas_s3_staging.cpp b/src/Disks/tests/gtest_cas_s3_staging.cpp index e32fc4b55e1e9..1437f7f9f0ca5 100644 --- a/src/Disks/tests/gtest_cas_s3_staging.cpp +++ b/src/Disks/tests/gtest_cas_s3_staging.cpp @@ -881,6 +881,29 @@ TEST(CASS3Staging, ReadYourWritesReturnsStagedBytesFromS3StagingObject) EXPECT_EQ(got, payload); } +TEST(CASS3Staging, OversizedInlineCandidateKeepsLocalStaging) +{ + auto objects = makeFakeNativeCopyStorage(/*native_only_copy_supported=*/true); + auto storage = makeS3StagingMetadataStorageForTest(objects, "mountInlineOverflow"); + storage->startup(); + auto tx = storage->createTransaction(); + const std::string path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/skip.dct.idx"; + const std::string bytes(1024 * 1024 + 1, 'x'); + writeThroughS3Transaction(dynamic_cast(*tx), path, bytes); + + DB::RelativePathsWithMetadata staged; + objects->listObjects(storage->stagingKeyPrefix(), staged, /*max_keys=*/0); + EXPECT_TRUE(staged.empty()); + auto reader = tx->tryReadFileInFlight(path, DB::ReadSettings{}, {}); + ASSERT_NE(reader, nullptr); + std::string actual; + DB::readStringUntilEOF(actual, *reader); + EXPECT_TRUE(actual == bytes); + reader.reset(); + tx->commit(DB::NoCommitOptions{}); + EXPECT_FALSE(storage->tryGetInManifestBytes(path).has_value()); +} + /// An aborted transaction deletes its own S3 staging object instead of leaving it for the next mount. TEST(CASS3Staging, AbortDeletesS3Staging) { diff --git a/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.reference b/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.reference new file mode 100644 index 0000000000000..052293bfd3081 --- /dev/null +++ b/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.reference @@ -0,0 +1,8 @@ +t_merge 1 1 1 +t_merge 100 1 +t_merge 1 +1 +t_mat 1 1 1 +t_mat 100 1 +t_mat 1 +1 diff --git a/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.sh b/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.sh new file mode 100755 index 0000000000000..0aa4ffdf41a75 --- /dev/null +++ b/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-random-merge-tree-settings +# ^ cas is an object-storage metadata type; keep it off the minimal fasttest image. +# A merge or a mutation that rebuilds a text index writes one temporary segment per flush into +# `/text_index_tmp/` and commits that directory on its own. Every segment file is small; their sum is +# not bounded. On a content-addressed disk the commit must not depend on that sum. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +set -e -o pipefail + +CLIENT="${CLICKHOUSE_CLIENT} --allow_experimental_full_text_index=1" +ROWS=100 + +disk() { + echo "disk(type = object_storage, object_storage_type = local, metadata_type = cas, cas_unsafe_remount_no_delay = 1, cas_server_root_id = '${CLICKHOUSE_DATABASE}_$1', name = '${CLICKHOUSE_DATABASE}_$1', path = '${CLICKHOUSE_USER_FILES_UNIQUE}_$1_pool/')" +} + +# Each row contributes 192 KiB of distinct hex tokens before dictionary encoding. +# Their hashes depend on both row and token number so each segment adds distinct tokens to the manifest. +fill() { + ${CLIENT} -q "INSERT INTO $1 SELECT number, + arrayStringConcat(arrayMap(i -> hex(sipHash128(number, i)), range(toUInt64(6144))), ' ') + FROM numbers($2, $3) SETTINGS max_insert_threads = 1, max_block_size = ${ROWS}, max_insert_block_size = ${ROWS}" +} + +check() { + ${CLIENT} -q "SELECT '$1', count(), uniqExact(_part) FROM $1" + ${CLIENT} -q "SELECT '$1', count() FROM $1 + WHERE hasToken(s, hex(sipHash128(toUInt64(7), toUInt64(0)))) + SETTINGS force_data_skipping_indices = 'idx_s'" + ${CLIENT} -q "CHECK TABLE $1 SETTINGS check_query_single_value_result = 1" +} + +# Dictionary block size and front coding affect the size of each segment file. +# Use the default dictionary settings and LZ4 so the 20 segments exceed the 16 MiB inline budget. +SEGMENTS="index_granularity = 5, merge_max_block_size = 5, text_index_max_processed_tokens_before_flush = 1, + default_compression_codec = 'LZ4', + max_bytes_to_merge_at_max_space_in_pool = 1, text_index_max_memory_usage_before_flush = '1Gi'" + +# Both counters must come from the successful operation that produced the readable part. +segments() { + ${CLIENT} -q "SYSTEM FLUSH LOGS part_log" + ${CLIENT} -q "SELECT '$1', count() = 1, + max(ProfileEvents['TextIndexTemporarySegmentsWritten']) >= 20, + max(ProfileEvents['CASManifestInlineEntriesSelectedForBlob']) > 0 + FROM system.part_log + WHERE database = currentDatabase() AND table = '$1' AND event_type = '$2' AND error = 0 + AND part_name IN (SELECT name FROM system.parts WHERE database = currentDatabase() AND table = '$1' AND active)" +} + +# A merge that may reduce rows rebuilds the index of the result part. +${CLIENT} -q "CREATE TABLE t_merge (k UInt64, s String, INDEX idx_s (s) TYPE text(tokenizer = 'splitByNonAlpha')) + ENGINE = MergeTree ORDER BY k + SETTINGS disk = $(disk merge), min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, ${SEGMENTS}" +fill t_merge 0 $((ROWS / 2)) +fill t_merge $((ROWS / 2)) $((ROWS / 2)) +${CLIENT} -q "OPTIMIZE TABLE t_merge FINAL DEDUPLICATE" +segments t_merge MergeParts +check t_merge + +# A mutation that materializes the index of a part written before the index existed. +${CLIENT} -q "CREATE TABLE t_mat (k UInt64, s String) + ENGINE = MergeTree ORDER BY k + SETTINGS disk = $(disk mat), min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, ${SEGMENTS}" +fill t_mat 0 ${ROWS} +# One part, so that one mutation builds all the segments. +${CLIENT} -q "OPTIMIZE TABLE t_mat FINAL" +${CLIENT} -q "ALTER TABLE t_mat ADD INDEX idx_s (s) TYPE text(tokenizer = 'splitByNonAlpha')" +${CLIENT} -q "ALTER TABLE t_mat MATERIALIZE INDEX idx_s SETTINGS mutations_sync = 2, max_block_size = 5" +segments t_mat MutatePart +check t_mat + +${CLIENT} -q "DROP TABLE t_merge SYNC" +${CLIENT} -q "DROP TABLE t_mat SYNC"