From 48e9247ea7f4f3703d71a8a1516d8a49d6caa94d Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Thu, 26 Nov 2026 18:52:52 +0100 Subject: [PATCH 1/7] Spill excess inline files before publishing a CAS manifest Text index rebuilds can produce hundreds of small files whose combined inline data exceeds the 16 MiB manifest limit. Count inline bytes from the final paths and store the largest added or replaced files as blobs until the manifest fits. Include unchanged base entries in the budget when updating a published part. Use the existing precommit and blob upload path for spilled files. Share their payload across upload requests and independent readers. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- src/Common/ProfileEvents.cpp | 1 + .../ContentAddressedTransaction.cpp | 274 +++++--- .../ContentAddressedTransaction.h | 21 +- .../ContentAddressed/Pool/CasPartWriteTxn.cpp | 23 +- .../ContentAddressed/Pool/CasPartWriteTxn.h | 2 + src/Disks/tests/gtest_cas_inline_cap_gaps.cpp | 609 ++++++++++++++++++ ...text_index_rebuild_inline_budget.reference | 8 + ...15_cas_text_index_rebuild_inline_budget.sh | 73 +++ 8 files changed, 889 insertions(+), 122 deletions(-) create mode 100644 src/Disks/tests/gtest_cas_inline_cap_gaps.cpp create mode 100644 tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.reference create mode 100755 tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.sh 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..757e4a707028a 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; } } @@ -117,13 +119,6 @@ bool hasTopLevelFile(const std::vector & entries) [](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 +290,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 +300,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 +397,80 @@ 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) +{ + if (inline_bytes_from_unchanged_base_entries > Cas::kMaxManifestInlineBytesTotal) + throw Exception(ErrorCodes::LIMIT_EXCEEDED, "Retained manifest entries contain {} inline bytes, exceeding the cap of {}", + inline_bytes_from_unchanged_base_entries, Cas::kMaxManifestInlineBytesTotal); + + 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 +480,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 +488,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 +540,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 +569,107 @@ 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); + } + } + + 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) { - 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)) - { - 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) + 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) + { + /// 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) { - /// `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 +677,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 +690,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. @@ -1657,7 +1723,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 +1731,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..d18161bc9fec2 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 @@ -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 @@ -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 diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index ecc586c4454e8..52c1dfbb532bf 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -56,7 +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 @@ -169,11 +168,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; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h index c6b0aeb75609d..52899574a4227 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h @@ -15,6 +15,8 @@ namespace DB { class WriteBuffer; } namespace DB::Cas { +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/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp new file mode 100644 index 0000000000000..f1191129f355e --- /dev/null +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -0,0 +1,609 @@ +#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()); +} 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..0f6cd234a393c --- /dev/null +++ b/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.reference @@ -0,0 +1,8 @@ +t_merge 1 +t_merge 1000000 1 +t_merge 1 +1 +t_mat 1 +t_mat 1000000 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..4834a069ec12c --- /dev/null +++ b/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# ^ 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=1000000 + +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/')" +} + +# One 64-character token per row, different in every row: the dictionary of a segment is about as large +# as the tokens it holds, whatever the codec. +fill() { + ${CLIENT} -q "INSERT INTO $1 SELECT number, concat(hex(sipHash128(number)), hex(sipHash128(number, 1))) + FROM numbers($2, $3) SETTINGS max_insert_threads = 1, max_block_size = 1000000, max_insert_block_size = 1000000" +} + +check() { + ${CLIENT} -q "SELECT '$1', count(), uniqExact(_part) FROM $1" + ${CLIENT} -q "SELECT '$1', count() FROM $1 + WHERE hasToken(s, concat(hex(sipHash128(toUInt64(7))), hex(sipHash128(toUInt64(7), 1)))) + SETTINGS force_data_skipping_indices = 'idx_s'" + ${CLIENT} -q "CHECK TABLE $1 SETTINGS check_query_single_value_result = 1" +} + +# A segment is flushed after every block that the builder reads, and a block is at least one granule. With +# 1024 rows per granule each segment holds about 1024 tokens (about 70 KiB), far below the size at which a +# file stops being small, and the rebuild leaves several hundred segments. +SEGMENTS="index_granularity = 1024, merge_max_block_size = 1024, text_index_max_processed_tokens_before_flush = 1, + 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', countIf(ProfileEvents['TextIndexTemporarySegmentsWritten'] >= 100 + AND ProfileEvents['CASManifestInlineEntriesSelectedForBlob'] > 0) = 1 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 = 1024" +segments t_mat MutatePart +check t_mat + +${CLIENT} -q "DROP TABLE t_merge SYNC" +${CLIENT} -q "DROP TABLE t_mat SYNC" From 1019b70dc00478a052b2450ad52853eb67382ce7 Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Fri, 27 Nov 2026 17:29:13 +0100 Subject: [PATCH 2/7] Stream oversized CAS inline candidates to local staging Text index files can outgrow the 1 MiB per-file inline limit while a merge is still writing them. Keeping the entire file in memory until finalize makes the peak allocation grow with the file size. Once a write crosses the limit, pass the buffered prefix and subsequent blocks to the local staging writer. Release the prefix allocation after the transfer. At finalize, register the staged file for publication through the existing precommit and blob upload path. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- .../ContentAddressedTransaction.cpp | 172 +++++++----------- .../ContentAddressedTransaction.h | 12 +- src/Disks/IO/WriteBufferInlineOrBlob.cpp | 3 +- src/Disks/tests/gtest_cas_inline_cap_gaps.cpp | 88 +++++++++ src/Disks/tests/gtest_cas_s3_staging.cpp | 23 +++ 5 files changed, 180 insertions(+), 118 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index 757e4a707028a..ad5d0d0dd1715 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -1147,128 +1147,82 @@ 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, INLINE_CAP, /*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); + entry.inline_bytes = std::move(inlined->data); + putEntry(st, std::move(entry), nullptr); + }, + buf_size); } void ContentAddressedTransaction::createDirectory(const std::string &) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index d18161bc9fec2..688da91806c77 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -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, @@ -450,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: @@ -468,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/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 index f1191129f355e..d0eb7cc105e83 100644 --- a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -6,9 +6,12 @@ #include #include #include +#include +#include #include #include +#include #include namespace DB::ErrorCodes @@ -607,3 +610,88 @@ TEST(CASInlineCapGaps, RepointRefusesBaseChangedAfterSpillUpload) 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) + GTEST_SKIP() << "operator new is not charged to the memory tracker under sanitizers"; +#endif + 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); +} + +} + +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) { From 64305201b60446f6453336c6ee9c71d3e2f5c526 Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Fri, 27 Nov 2026 18:57:31 +0100 Subject: [PATCH 3/7] Stage CAS part files before choosing inline placement Stream new part files to the configured local or S3 staging backend. Keep the size, content hash and staging handle when a writer closes. At commit, read the files selected for inline placement and publish the remaining blobs from staging. Hardlinks, moves and open readers retain the source until their last reference is released. Exercise the manifest budget with 100 rows and 20 temporary text index segments in both a merge and a mutation. Cover multipart staging and cleanup on RustFS after a successful insert or an injected failure. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- .../ContentAddressedTransaction.cpp | 676 ++++++++---------- .../ContentAddressedTransaction.h | 88 +-- src/Disks/tests/gtest_ca_wiring.cpp | 110 ++- src/Disks/tests/gtest_cas_inline_cap_gaps.cpp | 232 ++++++ src/Disks/tests/gtest_cas_s3_staging.cpp | 293 +++++++- .../test_cas_s3_staging/__init__.py | 0 .../configs/storage_conf.xml | 23 + tests/integration/test_cas_s3_staging/test.py | 78 ++ ...text_index_rebuild_inline_budget.reference | 4 +- ...15_cas_text_index_rebuild_inline_budget.sh | 24 +- 10 files changed, 1071 insertions(+), 457 deletions(-) create mode 100644 tests/integration/test_cas_s3_staging/__init__.py create mode 100644 tests/integration/test_cas_s3_staging/configs/storage_conf.xml create mode 100644 tests/integration/test_cas_s3_staging/test.py diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index ad5d0d0dd1715..ed4f79add6127 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -60,6 +60,24 @@ namespace DB::Cas namespace { +/// Ceiling for a CAS write-buffer allocation. An extreme `max_compress_block_size` (or any other +/// out-of-range buffer-size setting -- fuzzed or misconfigured) flows into `writeFile`'s `buf_size` / +/// `adaptive_write_buffer_initial_size` and, unclamped, reaches `Memory::alloc` where the allocator's +/// `checkSize` (>= 0x8000000000000000) fires a `LOGICAL_ERROR` and aborts the server in +/// debug/sanitizer builds. The ordinary MergeTree writers clamp compress-block sizes to 256 MiB +/// (`MergeTreeWriterSettings::MAX_COMPRESS_BLOCK_SIZE`) for exactly this reason; the CAS write path +/// received the value unclamped. Mirror that ceiling here, at the allocation site, so no caller can +/// pass an absurd size to the allocator. 256 MiB is duplicated (not #included) to keep the Disks layer +/// free of a Storages/MergeTree dependency; the regression guard is +/// `04070_no_crash_extreme_compress_block_size` run on a content-addressed storage policy. +constexpr size_t kMaxCasWriteBufferBytes = 256ULL * 1024 * 1024; + +size_t clampCasWriteBufferSize(size_t size) +{ + /// Even an empty S3 payload writes an envelope through the sink. A zero-sized buffer cannot flush. + return std::clamp(size, 1, kMaxCasWriteBufferBytes); +} + bool hasSuffix(std::string_view s, std::string_view suffix) { return s.size() >= suffix.size() && s.substr(s.size() - suffix.size()) == suffix; @@ -108,11 +126,24 @@ 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. +/// An eligible staged file can be embedded in the manifest up to this payload size. constexpr size_t INLINE_CAP = 1024 * 1024; /// 1 MiB +/// Destroy the underlying reader before releasing its source. A remote seek can start a new GET. +struct StagingFileOwner +{ + std::shared_ptr source; +}; + +template +class ReaderWithStagingFile final : private StagingFileOwner, public Reader +{ +public: + template + ReaderWithStagingFile(std::shared_ptr source_, Args &&... args) + : StagingFileOwner{std::move(source_)}, Reader(std::forward(args)...) {} +}; + bool hasTopLevelFile(const std::vector & entries) { return std::any_of(entries.begin(), entries.end(), @@ -130,7 +161,7 @@ ContentAddressedTransaction::~ContentAddressedTransaction() { /// On abort this is the cleanup of local and S3 staging. After a commit it finds nothing left, /// except when the commit published some parts and then threw. - cleanupPendingTempFiles(); + releaseStagedFiles(); /// An uncommitted transaction's uploads become min_active_build_sequence-spared debris: abandon every /// still-open PartWriteTxn so its build_seq is retired. This replaces the former pin machinery. @@ -198,68 +229,94 @@ ContentAddressedTransaction::PartStaging * ContentAddressedTransaction::findStag return it == parts.end() ? nullptr : &it->second; } -void ContentAddressedTransaction::cleanupPendingTempFiles() noexcept +namespace { - for (auto & [key, st] : parts) +void removeStagingObject(const ObjectStoragePtr & storage, const String & key) noexcept +{ + try { - for (const auto & pb : st.pending_blobs) - { - if (pb.backend == Cas::StagingBackend::Local) - { - std::error_code ec; - std::filesystem::remove(pb.staging_key, ec); - } - else - { - /// The S3 staging object is private to this transaction and nothing reads - /// `pending_blobs` after this call, so commit and abort delete it alike. An object that - /// outlived an abort would stay until the next mount of this `server_root_id`. - try - { - metadata_storage.objectStorage()->removeObjectIfExists(StoredObject(pb.staging_key)); - } - catch (...) // NOLINT(bugprone-empty-catch) - { - /// Best-effort (noexcept context): a stubborn delete leaves debris for the mount-start sweep. - } - } - } - st.pending_blobs.clear(); + storage->removeObjectIfExists(StoredObject(key)); + } + catch (...) + { + tryLogCurrentException(getLogger("ContentAddressedTransaction"), "removing a private staging object"); } } +} -const ContentAddressedTransaction::PartStaging::PendingBlob * -ContentAddressedTransaction::findPendingBlob(const PartStaging & st, const Cas::BlobRef & ref) const +ContentAddressedTransaction::StagedPartFile::~StagedPartFile() { - /// Locate a pending blob by ref. Returns nullptr when the blob has already been uploaded - /// (post-precommit, pending_blobs is cleared) or was never staged as pending. - for (const auto & pb : st.pending_blobs) - if (pb.ref == ref) - return &pb; - return nullptr; + if (!owns_file) + return; + if (remote_storage) + removeStagingObject(remote_storage, staging_path); + else + { + std::error_code ec; + fs::remove(staging_path, ec); + } } -void ContentAddressedTransaction::putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source) +void ContentAddressedTransaction::releaseStagedFiles() noexcept { - eraseEntry(st, entry.path); - if (source) - st.copy_sources.insert_or_assign(entry.path, std::move(source)); - st.entries.push_back(std::move(entry)); + for (auto & [key, st] : parts) + st.staged_part_files.clear(); +} + +ContentAddressedTransaction::StagedPartFilePtr ContentAddressedTransaction::stagedFileOf(const PartStaging & st, const String & path) +{ + const auto it = st.staged_part_files.find(path); + return it == st.staged_part_files.end() ? nullptr : it->second; +} + +void ContentAddressedTransaction::putEntry( + PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source, StagedPartFilePtr file) +{ + auto it = std::find_if(st.entries.begin(), st.entries.end(), [&](const auto & e) { return e.path == entry.path; }); + const bool inserted = it == st.entries.end(); + if (inserted) + { + st.entries.emplace_back(); + it = std::prev(st.entries.end()); + } + /// Install the possibly allocating map node before retiring the previous path or its source. + try + { + if (file) + st.staged_part_files.insert_or_assign(entry.path, file); + else if (source) + st.copy_sources.insert_or_assign(entry.path, source); + } + catch (...) + { + if (inserted) + st.entries.pop_back(); + throw; + } + if (!file) + st.staged_part_files.erase(entry.path); + if (!source) + st.copy_sources.erase(entry.path); + *it = std::move(entry); } void ContentAddressedTransaction::eraseEntry(PartStaging & st, const std::string & path) { std::erase_if(st.entries, [&](const Cas::ManifestEntry & e) { return e.path == path; }); st.copy_sources.erase(path); + st.staged_part_files.erase(path); } void ContentAddressedTransaction::rekeyEntry(PartStaging & st, Cas::ManifestEntry & entry, std::string new_path) { - if (auto node = st.copy_sources.extract(entry.path)) - { - node.key() = new_path; - st.copy_sources.insert(std::move(node)); - } + auto file = stagedFileOf(st, entry.path); + auto source = copySourceOf(st, entry.path); + if (file) + st.staged_part_files.emplace(new_path, std::move(file)); + if (source) + st.copy_sources.emplace(new_path, std::move(source)); + st.copy_sources.erase(entry.path); + st.staged_part_files.erase(entry.path); entry.path = std::move(new_path); } @@ -267,6 +324,8 @@ void ContentAddressedTransaction::clearEntries(PartStaging & st) { st.entries.clear(); st.copy_sources.clear(); + st.staged_part_files.clear(); + st.has_finalized_file_write = false; } void ContentAddressedTransaction::markVacatedInBase( @@ -365,29 +424,6 @@ void ContentAddressedTransaction::retargetCopySource(const Cas::PartRefKey & fro copy_sources_by_part.try_emplace(to.cacheKey(), borrow); } -void ContentAddressedTransaction::adoptStagedBlob( - const PartStaging::PendingBlob * pb, const Cas::ManifestEntry & entry, - PartStaging & dst_st, Cas::PartWriteTxn & dst_build, bool copy_pending) -{ - if (pb) - { - /// Pending blob (not yet uploaded): no dependency exists until publication succeeds. If - /// copy_pending, push a copy of the pb record into dst_st so publishStaging uploads it - /// for the dst part too (hardlink = copy semantics). If !copy_pending, the record is already - /// in dst_st (moved by caller) — skip the push. - if (copy_pending) - dst_st.pending_blobs.push_back(*pb); - } - else - { - /// Uploaded / committed: record trusted-manifest evidence — no pool HEAD/GET before precommit. - /// §4 manifest-trust: the publish gate (promote) TRUSTS this committed-source adopted leaf via the - /// durable manifest edge — it does not observe or republish it. Pending uploads establish - /// `Materialized` through `putBlob` before promote; a genuinely absent adopted blob is an fsck finding. - dst_build.adoptEvidence(entry); - } -} - std::optional ContentAddressedTransaction::routeOf(const std::string & path) const { @@ -397,58 +433,73 @@ ContentAddressedTransaction::routeOf(const std::string & path) const return metadata_storage.route(*p); } -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) +std::vector ContentAddressedTransaction::applyManifestInlineBudget( + PartStaging & st, uint64_t inline_bytes_from_unchanged_base_entries) const { if (inline_bytes_from_unchanged_base_entries > Cas::kMaxManifestInlineBytesTotal) throw Exception(ErrorCodes::LIMIT_EXCEEDED, "Retained manifest entries contain {} inline bytes, exceeding the cap of {}", inline_bytes_from_unchanged_base_entries, Cas::kMaxManifestInlineBytesTotal); + const auto pool = metadata_storage.store(); 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) + for (auto & entry : st.entries) { - if (lhs->inline_bytes.size() != rhs->inline_bytes.size()) - return lhs->inline_bytes.size() > rhs->inline_bytes.size(); - return lhs->path < rhs->path; - }); + const auto file = stagedFileOf(st, entry.path); + if (entry.placement == Cas::EntryPlacement::Inline || (file && file->allow_inline_by_name && entry.blob_size <= INLINE_CAP)) + { + candidates.push_back(&entry); + total_inline_bytes += entry.size(); + } + } + + if (total_inline_bytes > Cas::kMaxManifestInlineBytesTotal) + std::sort(candidates.begin(), candidates.end(), [](const auto * lhs, const auto * rhs) + { + if (lhs->size() != rhs->size()) + return lhs->size() > rhs->size(); + return lhs->path < rhs->path; + }); std::vector blob_upload_requests; + size_t spilled = 0; + 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); + const auto size = entry->size(); - blob_upload_requests.push_back({entry->ref, Cas::BlobSource::fromString(std::exchange(entry->inline_bytes, {})), size}); + if (total_inline_bytes > Cas::kMaxManifestInlineBytesTotal) + { + total_inline_bytes -= size; + ++spilled; + if (entry->placement == Cas::EntryPlacement::Inline) + { + /// A borrowed Inline has no staging file. Its bytes came from the committed manifest. + entry->ref = Cas::poolContentHash(pool->writeAlgo(), 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; + } + } + else if (entry->placement == Cas::EntryPlacement::Blob) + { + auto input = openStagedPayload(*st.staged_part_files.at(entry->path), size, pool); + String bytes(size, '\0'); + input->readStrict(bytes.data(), bytes.size()); - entry->blob_size = size; - entry->placement = Cas::EntryPlacement::Blob; - total_inline_bytes -= size; + if (!input->eof() || Cas::poolContentHash(entry->ref.algo, bytes) != entry->ref) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Staged inline payload does not match the size or hash of {}", entry->path); - if (total_inline_bytes <= Cas::kMaxManifestInlineBytesTotal) - break; + entry->inline_bytes = std::move(bytes); + entry->placement = Cas::EntryPlacement::Inline; + entry->blob_size = 0; + } } - ProfileEvents::increment(ProfileEvents::CASManifestInlineEntriesSelectedForBlob, blob_upload_requests.size()); - return blob_upload_requests; -} + if (spilled) + ProfileEvents::increment(ProfileEvents::CASManifestInlineEntriesSelectedForBlob, spilled); + return blob_upload_requests; } Cas::ManifestId ContentAddressedTransaction::precommitAndUpload( @@ -466,81 +517,44 @@ Cas::ManifestId ContentAddressedTransaction::precommitAndUpload( return id; } -void ContentAddressedTransaction::appendStagedBlobUploads(const PartStaging & st, std::vector & blob_upload_requests) const +std::unique_ptr ContentAddressedTransaction::openStagedPayload(const StagedPartFile & file, uint64_t size, const Cas::PoolPtr & pool) { - if (st.pending_blobs.empty()) - return; + if (!file.remote_storage) + return Cas::openLocalStagedBlobPayload(file.staging_path, size); - /// 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 - /// (it is an orphan). Its temp file is still cleaned by cleanupPendingTempFiles at commit end. - std::unordered_set referenced_hashes; + auto op = pool->mountRequests().admit(); + auto staged = op.stream(file.pool_staging_key, Cas::Retry::standard()); + if (!staged) + throw Exception(ErrorCodes::FILE_DOESNT_EXIST, "CAS staging object {} disappeared before publication", file.staging_path); + + const auto header_len = pool->poolMeta().blob_header_len; + String header(header_len, '\0'); + staged->readStrict(header.data(), header.size()); + const auto decoded = Cas::decodeEnvelopeHeader(header, header_len + size, Cas::ObjectKind::Blob); + + if (decoded.header_len != header_len) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Unexpected envelope length {} in staging object {}", decoded.header_len, file.staging_path); + return staged; +} + +Cas::BlobSource ContentAddressedTransaction::stagedUploadSource(const StagedPartFilePtr & file, uint64_t size) const +{ + return { + .size = size, + .open = [pool = metadata_storage.store(), file, size] { return openStagedPayload(*file, size, pool); }, + .server_side_copy_from = file->remote_storage ? std::optional(file->staging_path) : std::nullopt, + .publication_attempted = std::shared_ptr>(file, &file->publication_attempted), + }; +} + +void ContentAddressedTransaction::appendStagedBlobUploads(const PartStaging & st, std::vector & blob_upload_requests) const +{ for (const auto & entry : st.entries) - if (entry.placement == Cas::EntryPlacement::Blob) - referenced_hashes.insert(entry.ref); - - /// 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 - /// `[envelope][payload]` object. A record and its hardlink copies in other parts share one - /// `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. - 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)) - continue; /// The entry was removed by unlinkFile/replaceFile; skip this orphan. - Cas::BlobSource source; - source.size = pb.size; - source.publication_attempted = pb.publication_attempted; - if (pb.backend == Cas::StagingBackend::S3) - { - source.server_side_copy_from = pb.staging_key; - const Cas::PoolPtr store = metadata_storage.store(); - const std::string staging_key = pb.staging_key; - const uint64_t header_len = store->poolMeta().blob_header_len; - const uint64_t payload_size = pb.size; - source.open = [store, staging_key, header_len, payload_size]() -> std::unique_ptr - { - Cas::CasOperation op = store->mountRequests().admit(); - auto staged = op.stream(staging_key, Cas::Retry::standard()); - if (!staged) - throw Exception( - ErrorCodes::FILE_DOESNT_EXIST, - "CAS staging object {} disappeared before retagged blob publication", - staging_key); - - String encoded_header(header_len, '\0'); - staged->readStrict(encoded_header.data(), encoded_header.size()); - const Cas::EnvelopeHeader decoded = Cas::decodeEnvelopeHeader( - encoded_header, - header_len + payload_size, - Cas::ObjectKind::Blob); - if (decoded.header_len != header_len) - throw Exception( - ErrorCodes::CORRUPTED_DATA, - "CAS staging object {} uses envelope length {}, expected {}", - staging_key, - decoded.header_len, - header_len); - return staged; - }; - } - else - { - const std::string staging_key = pb.staging_key; - const uint64_t payload_size = pb.size; - source.open = [staging_key, payload_size]() -> std::unique_ptr - { - return Cas::openLocalStagedBlobPayload(staging_key, payload_size); - }; - } - /// `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. - blob_upload_requests.push_back(Cas::BlobUploadRequest{pb.ref, std::move(source), pb.size}); + if (entry.placement != Cas::EntryPlacement::Blob) + continue; + if (auto file = stagedFileOf(st, entry.path)) + blob_upload_requests.push_back({entry.ref, stagedUploadSource(file, entry.blob_size), entry.blob_size}); } } @@ -576,8 +590,8 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, /// 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 + /// A hardlink or move can open a build solely for the destination. Such a transfer must preserve its base. + const bool should_drop_existing_ref = existing_ref_view && st.has_finalized_file_write && (!st.base_manifest_ref || *st.base_manifest_ref == existing_ref_view->manifestId().ref) && !hasTopLevelFile(existing_ref_view->manifest()->entries) && hasTopLevelFile(st.entries); @@ -612,7 +626,7 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, } } - auto blob_upload_requests = applyManifestInlineBudget(st.entries, inline_bytes_from_unchanged_base_entries, metadata_storage.store()->writeAlgo()); + auto blob_upload_requests = applyManifestInlineBudget(st, inline_bytes_from_unchanged_base_entries); if (!blob_upload_requests.empty() && !st.build) buildFor({.ns = ns, .ref = ref, .file = {}}, st); @@ -717,7 +731,7 @@ void ContentAddressedTransaction::commit(const TransactionCommitOptionsVariant & /// staged parts to publish and no local staging to keep; run the same idempotent epilogue a /// normal empty commit runs. committed = true; - cleanupPendingTempFiles(); + releaseStagedFiles(); force_fresh_validated_refs.clear(); return; } @@ -783,8 +797,8 @@ void ContentAddressedTransaction::commit(const TransactionCommitOptionsVariant & copy_sources_by_part.clear(); for (auto & [key, st] : parts) st.copy_sources.clear(); - /// All pending blobs have been uploaded in publishStaging; remove their staging resources now. - cleanupPendingTempFiles(); + /// Uploads are complete. Readers opened during the transaction can still own their staging files. + releaseStagedFiles(); /// This transaction's unlinkFile ForceFresh-proof memoization is scoped to this transaction only; /// clear it alongside the other per-transaction state resets above. force_fresh_validated_refs.clear(); @@ -838,8 +852,8 @@ std::optional ContentAddressedTransaction::tryGetInFlightStorageO if (entry->placement == Cas::EntryPlacement::Blob) { /// A pending blob has not been uploaded yet — its storage object does not exist in - /// the pool. Return empty so the caller falls back to tryReadFileInFlight (local temp read). - if (findPendingBlob(it->second, entry->ref)) + /// the pool. Return empty so the caller reads the private staging file through tryReadFileInFlight. + if (stagedFileOf(it->second, entry->path)) return {}; const auto location = metadata_storage.store()->locate(*entry); return StoredObjects{StoredObject(location.key, path, location.length)}; @@ -869,30 +883,16 @@ std::unique_ptr ContentAddressedTransaction::tryReadFile return std::make_unique(path, entry->inline_bytes); if (entry->placement == Cas::EntryPlacement::Blob) { - /// A pending blob has not been uploaded yet — serve reads from the staging area (the - /// same bytes that will be promoted to the pool in publishStaging post-precommit): a local - /// temp file for `Cas::StagingBackend::Local`, or the S3 staging object for `Cas::StagingBackend::S3` - /// (`staging_key` is a remote object key there, never a - /// local path, so `ReadBufferFromFile` would misinterpret it as a filesystem path). - if (const auto * pb = findPendingBlob(it->second, entry->ref)) + if (auto file = stagedFileOf(it->second, entry->path)) { - if (pb->backend == Cas::StagingBackend::S3) + if (file->remote_storage) { - /// The staging object holds `[header][payload]` - /// (the fixed-length `blob_header_len` CABL envelope, so the promote can stay a - /// verbatim server-side copy). Read-your-writes must serve the PAYLOAD ONLY — wrap the - /// object read in a `ReadBufferFromFileView` windowed to `[header_len, header_len+size)` - /// so position 0 is the payload start, else the reader would see 256 bytes of header - /// prepended to the payload (corruption). The LOCAL staging temp file holds the payload - /// verbatim (no header), so its path is unchanged. - const uint64_t header_len = metadata_storage.store()->poolMeta().blob_header_len; - const uint64_t payload_end = header_len + pb->size; - auto impl = metadata_storage.objectStorage()->readObject( - StoredObject(pb->staging_key, path, payload_end), settings); - return std::make_unique( - std::move(impl), path, header_len, payload_end); + const auto offset = metadata_storage.store()->poolMeta().blob_header_len; + const auto end = offset + entry->blob_size; + auto input = file->remote_storage->readObject(StoredObject(file->staging_path, path, end), settings); + return std::make_unique>(file, std::move(input), path, offset, end); } - return std::make_unique(pb->staging_key); + return std::make_unique>(file, file->staging_path); } return metadata_storage.readBlobPayload(metadata_storage.store()->locate(*entry), path, settings); } @@ -972,22 +972,42 @@ void ContentAddressedTransaction::createMetadataFile(const std::string &, const void ContentAddressedTransaction::stageBlobPartFile( const ContentAddressedMetadataStorage::Route & route, - const Cas::BlobRef & ref, size_t size, const std::string & staging_key, Cas::StagingBackend backend) + const Cas::BlobRef & ref, size_t size, const std::string & staging_key, ObjectStoragePtr remote_storage, const String & pool_key) { - /// Do not upload here. Record the pending blob for post-precommit publication; dependency state - /// remains absent until the upload succeeds and its result is merged. - /// The staging bytes are kept (the transaction owns them) — a local temp file for - /// `Cas::StagingBackend::Local`, or an S3 staging object for `Cas::StagingBackend::S3`. - auto & st = stagingFor(route); - st.pending_blobs.push_back({ref, staging_key, size, backend}); - (void)buildFor(route, st); + /// Until registration succeeds the local writer still owns its file. The S3 sink has + /// already finalized its object, so release it here if registration throws. + try + { + auto file = std::make_shared(); + file->staging_path = staging_key; + file->remote_storage = remote_storage; + file->pool_staging_key = pool_key; + file->allow_inline_by_name = !Cas::partFileMustStayBlob(route.file); - Cas::ManifestEntry entry; - entry.path = route.file; - entry.placement = Cas::EntryPlacement::Blob; - entry.ref = ref; - entry.blob_size = size; - putEntry(st, std::move(entry), nullptr); + auto & st = stagingFor(route); + const bool had_build = bool(st.build); + buildFor(route, st); + + SCOPE_EXIT({ + if (!had_build && !file->owns_file) + st.build.reset(); + }); + + if (std::exchange(fail_next_file_registration, false)) + throw Exception(ErrorCodes::ABORTED, "Injected failure registering staged file {}", route.file); + + Cas::ManifestEntry entry{.path = route.file, .placement = Cas::EntryPlacement::Blob, .ref = ref, .blob_size = size, .inline_bytes = {}}; + putEntry(st, std::move(entry), nullptr, file); + + file->owns_file = true; + st.has_finalized_file_write = true; + } + catch (...) + { + if (remote_storage) + removeStagingObject(remote_storage, staging_key); + throw; + } } void ContentAddressedTransaction::stageUnprovenBlobEntryForTest(const std::string & path, const Cas::BlobRef & ref, uint64_t size) @@ -1044,6 +1064,7 @@ std::unique_ptr ContentAddressedTransaction::tryCreateW const std::string & path, size_t buf_size, WriteMode mode, const WriteSettings & settings, bool autocommit) { + buf_size = Cas::clampCasWriteBufferSize(buf_size); /// This transaction owns the write because the blob key is known only after hashing the payload. /// Append is serviceable (read-modify-rewrite) only for a non-part / table-level verbatim file /// (handled inside writeFile). A part file is a content blob or a whole-rewritten inline entry, so @@ -1139,18 +1160,9 @@ std::unique_ptr ContentAddressedTransaction::writeFile( throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ContentAddressedTransaction::writeFile: not a part file path: {}", path); - /// The former - /// mutable-per-part-file branch (uuid.txt/metadata_version.txt/txn_version.txt staging directly - /// into a separate mutable payload) is DELETED here — these three names fall through to the - /// ordinary content path below like any other tree file. There is no filename left to special-case: - /// `kMutablePerPartFiles`/`isMutablePerPartFile` predicate itself is gone too — there is no - /// 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. - - 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) + const auto remote_storage = metadata_storage.stagingBackend() == Cas::StagingBackend::S3 ? metadata_storage.objectStorage() : nullptr; + if (remote_storage) { /// Build the fixed-length CABL envelope header now (before /// the payload is streamed) so the staging object holds `[header][payload]` and the promote @@ -1165,9 +1177,14 @@ std::unique_ptr ContentAddressedTransaction::writeFile( /// 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"); + const auto leaf = getRandomASCIIString(32) + ".tmp"; + const auto pool_key = pool->layout().stagingKey(metadata_storage.serverRootId(), incarnation.writer_epoch, leaf); + const auto staging_key = metadata_storage.stagingKey(incarnation.writer_epoch, leaf); - auto object_sink = metadata_storage.objectStorage()->writeObject(StoredObject(staging_key), WriteMode::Rewrite); + auto staging_settings = settings; + staging_settings.adaptive_write_buffer_initial_size = Cas::clampCasWriteBufferSize(settings.adaptive_write_buffer_initial_size); + auto object_sink = remote_storage->writeObject( + StoredObject(staging_key), WriteMode::Rewrite, {}, Cas::clampCasWriteBufferSize(buf_size), staging_settings); return std::make_unique( std::move(object_sink), @@ -1177,52 +1194,20 @@ std::unique_ptr ContentAddressedTransaction::writeFile( 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) + [this, route = *r, hash_algo, remote_storage, pool_key](const String & hash, size_t size, const String & key) { - const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; - stageBlobPartFile(route, ref, size, key, Cas::StagingBackend::S3); + stageBlobPartFile(route, {hash_algo, Cas::codecFor(hash_algo).fromHex(hash)}, size, key, remote_storage, pool_key); }, [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); - }); - }; - - if (must_stay_blob) - return create_local_blob_writer(); - - return std::make_unique( - path, INLINE_CAP, /*create_blob_if_empty=*/false, std::move(create_local_blob_writer), - [this, route = std::move(*r), hash_algo](FinalizeResult result) + return std::make_unique( + metadata_storage.scratchPath(), hash_algo, buf_size, settings.use_adaptive_write_buffer, + settings.adaptive_write_buffer_initial_size, + [this, route = *r, hash_algo](const String & hash, size_t size, const String & key) { - 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); - entry.inline_bytes = std::move(inlined->data); - putEntry(st, std::move(entry), nullptr); - }, - buf_size); + stageBlobPartFile(route, {hash_algo, Cas::codecFor(hash_algo).fromHex(hash)}, size, key, nullptr, {}); + }); } void ContentAddressedTransaction::createDirectory(const std::string &) @@ -1414,23 +1399,13 @@ void ContentAddressedTransaction::createHardLink(const std::string & path_from, if (it != src_st->entries.end()) { entry = *it; - /// A copy of an adopted entry confirms the committed part the entry came from. - std::shared_ptr source; - if (entry.placement == Cas::EntryPlacement::Blob) - { - /// Unified adopt dispatch. copy_pending=(&dst_st != src_st) so the pending - /// blob record is copied into dst_st only when the destination is a different part - /// (hardlink = copy semantics; same-part is a self-ref that shouldn't duplicate the record). - const auto * pb = findPendingBlob(*src_st, entry.ref); - if (!pb) - source = copySourceOf(*src_st, src->file); - adoptStagedBlob(pb, entry, dst_st, buildFor(*dst, dst_st), /*copy_pending=*/(&dst_st != src_st)); - } - else if (entry.placement != Cas::EntryPlacement::Inline) - throw Exception(ErrorCodes::LOGICAL_ERROR, - "ContentAddressed: staged hardlink of unsupported placement for {}", path_from); + auto file = stagedFileOf(*src_st, src->file); + auto source = copySourceOf(*src_st, src->file); + auto & build = buildFor(*dst, dst_st); + if (!file) + build.adoptEvidence(entry); entry.path = dst->file; - putEntry(dst_st, std::move(entry), std::move(source)); + putEntry(dst_st, std::move(entry), std::move(source), std::move(file)); return; } } @@ -1597,40 +1572,49 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c /// The committed manifest the source staging was based on (a rename of a committed part with /// staged edits, e.g. a rollback's `delete_tmp_`); the re-key below drops it from the overlay. std::optional staged_source_base; + bool replacing_source_segments = false; if (auto src_it = parts.find(src_key); src_it != parts.end()) { had_staged_source = true; PartStaging & dst_st = parts[dst_key]; PartStaging & src_st = src_it->second; staged_source_base = src_st.base_manifest_ref; + replacing_source_segments = src_st.has_finalized_file_write && hasTopLevelFile(src_st.entries); + /// A written file still has provisional Blob placement. A borrowed Inline can + /// represent the same bytes, so compare its payload to the staged file's full hash. + /// Check every collision before moving ownership out of the source. + for (const auto & entry : src_st.entries) + { + const auto existing = std::find_if(dst_st.entries.begin(), dst_st.entries.end(), + [&](const Cas::ManifestEntry & other) { return other.path == entry.path; }); + if (existing == dst_st.entries.end() || *existing == entry) + continue; + if (existing->placement != entry.placement && existing->size() == entry.size()) + { + const bool source_is_blob = entry.placement == Cas::EntryPlacement::Blob; + const auto & blob = source_is_blob ? entry : *existing; + const auto & inlined = source_is_blob ? *existing : entry; + const auto staged = stagedFileOf(source_is_blob ? src_st : dst_st, blob.path); + if (staged && staged->allow_inline_by_name && blob.blob_size <= INLINE_CAP + && Cas::poolContentHash(blob.ref.algo, inlined.inline_bytes) == blob.ref) + continue; + } + throw Exception(ErrorCodes::LOGICAL_ERROR, + "ContentAddressed: moveDirectory file collision on '{}' ({} -> {}): " + "source and destination staged different entries for the same file", + entry.path, src->ref, dst->ref); + } for (auto & entry : src_st.entries) { - /// A genuine collision (both src and dst independently - /// staged DIFFERING bytes for the SAME path) is a fail-loud LOGICAL_ERROR rather than a - /// silent lost-update — the same defensive rule this loop used to apply only to the - /// three legacy mutable names now applies uniformly to every entry (that scoping was - /// itself a leftover of the mutable-file/entry split; there is only one kind of staged - /// file left). Identical bytes are a benign idempotent re-key; distinct paths are the - /// ordinary source-wins merge (a genuine collision is not expected in normal operation - /// — only some future op-order re-keying the same file under both stagings). - if (const auto existing = std::find_if(dst_st.entries.begin(), dst_st.entries.end(), - [&](const Cas::ManifestEntry & e) { return e.path == entry.path; }); - existing != dst_st.entries.end() && !(*existing == entry)) - throw Exception(ErrorCodes::LOGICAL_ERROR, - "ContentAddressed: moveDirectory file collision on '{}' ({} -> {}): " - "source and destination staged different bytes for the same file", - entry.path, src->ref, dst->ref); auto source = copySourceOf(src_st, entry.path); - putEntry(dst_st, std::move(entry), std::move(source)); + auto file = stagedFileOf(src_st, entry.path); + putEntry(dst_st, std::move(entry), std::move(source), std::move(file)); } /// Carry any staged removal marks forward too — a re-key of the /// staging key must not silently drop them. for (const auto & file : src_st.content_removed) dst_st.content_removed.insert(file); - /// Move pending blobs from src to dst — they will be uploaded in dst's publishStaging. - for (auto & pb : src_st.pending_blobs) - dst_st.pending_blobs.push_back(std::move(pb)); - src_st.pending_blobs.clear(); + dst_st.has_finalized_file_write |= src_st.has_finalized_file_write; if (!dst_st.build) { dst_st.build = std::move(src_st.build); @@ -1642,18 +1626,14 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c /// time is unnecessary - entries staged via putBlob/adopt carry deps in the SOURCE /// build... merge conservatively by abandoning nothing and re-observing): for (const auto & entry : dst_st.entries) - if (entry.placement == Cas::EntryPlacement::Blob) - { - /// Unified adopt dispatch. Pending blob records were already moved - /// to dst_st.pending_blobs above (MOVE semantics), so copy_pending=false. - adoptStagedBlob(findPendingBlob(dst_st, entry.ref), entry, dst_st, *dst_st.build, /*copy_pending=*/false); - } + if (entry.placement == Cas::EntryPlacement::Blob && !stagedFileOf(dst_st, entry.path)) + dst_st.build->adoptEvidence(entry); src_st.build->abandon(); } parts.erase(src_it); /// A freshly-written part finalized tmp->final is re-keyed in the - /// overlay above (entries/marks/pending blobs/build moved src->dst). The durable publish + /// overlay above (entries, removal marks, staging sources and build moved src->dst). The durable publish /// happens only in this transaction's commit (the existing publishStaging loop), not in /// this method. `MergeTree` commits a part right after `finalize` and renames it afterwards, /// so this re-key serves a rename staged before any commit. No early-published ref to @@ -1677,7 +1657,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 && hasTopLevelFile(base_entries)) + if (!ours && (!replacing_source_segments || 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 @@ -1685,7 +1665,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 && hasTopLevelFile(base_entries)) + if (ours && (!replacing_source_segments || hasTopLevelFile(base_entries))) { const auto renamed = metadata_storage.partAccess()->renameCommittedRef(src->refKey(), dst->refKey(), committed_ref); if (!renamed) @@ -1809,28 +1789,21 @@ void ContentAddressedTransaction::moveFile(const std::string & path_from, const [&](const Cas::ManifestEntry & e) { return e.path == src->file; }); if (it != src_st.entries.end()) { + if (&src_st == &dst_st && src->file == dst->file) + return; auto entry = *it; auto source = copySourceOf(src_st, src->file); - markVacatedInBase(*src, src_st, {src->file}); - eraseEntry(src_st, src->file); - entry.path = dst->file; - if (&src_st != &dst_st && entry.placement == Cas::EntryPlacement::Blob) + auto file = stagedFileOf(src_st, src->file); + if (&src_st != &dst_st) { - /// The record of a pending upload follows the entry. A hardlink left in the source still names the blob, - /// so the source keeps a copy: each part publishes every body it names, and may publish first. - auto pb_it = std::find_if(src_st.pending_blobs.begin(), src_st.pending_blobs.end(), - [&](const PartStaging::PendingBlob & pb) { return pb.ref == entry.ref; }); - if (pb_it != src_st.pending_blobs.end()) - { - const bool still_named_in_source = std::any_of(src_st.entries.begin(), src_st.entries.end(), - [&](const Cas::ManifestEntry & e) { return e.placement == Cas::EntryPlacement::Blob && e.ref == entry.ref; }); - dst_st.pending_blobs.push_back(*pb_it); - if (!still_named_in_source) - src_st.pending_blobs.erase(pb_it); - } - adoptStagedBlob(findPendingBlob(dst_st, entry.ref), entry, dst_st, buildFor(*dst, dst_st), /*copy_pending=*/false); + auto & build = buildFor(*dst, dst_st); + if (!file) + build.adoptEvidence(entry); } - putEntry(dst_st, std::move(entry), std::move(source)); + entry.path = dst->file; + markVacatedInBase(*src, src_st, {src->file}); + putEntry(dst_st, std::move(entry), std::move(source), std::move(file)); + eraseEntry(src_st, src->file); return; } /// Source not staged in this transaction: this would cover a standalone one-shot rename of a @@ -1845,17 +1818,6 @@ void ContentAddressedTransaction::replaceFile(const std::string & path_from, con { /// Write gate (rev.7 §1): refuse before dropping staged destination state on a Vanished/uncertain disk. metadata_storage.checkOpAdmitted(CasOpClass::Write); - /// replaceFile = moveFile that overwrites the destination. Drop any staged destination state - /// first, then delegate (the verbatim branch's putNamespaceFile already overwrites). - if (auto dst = routeOf(path_to); dst && !dst->file.empty()) - { - auto & dst_st = stagingFor(*dst); - /// A matching pending_blobs record (if any) is left in place — its temp file is cleaned by - /// cleanupPendingTempFiles at commit end, and the orphaned record is filtered out of the - /// publish upload by the staged-tree-hash check in publishStaging. We do NOT purge it - /// eagerly because the same hash may still be referenced by another staged entry. - eraseEntry(dst_st, dst->file); - } moveFile(path_from, path_to); } @@ -1892,10 +1854,6 @@ void ContentAddressedTransaction::unlinkFile(const std::string & path, bool if_e auto & st = stagingFor(*r); const bool staged_here = std::any_of(st.entries.begin(), st.entries.end(), [&](const Cas::ManifestEntry & e) { return e.path == r->file; }); - /// A matching pending_blobs record (if any) is left in place — its temp file is cleaned by - /// cleanupPendingTempFiles at commit end, and the orphaned record is filtered out of the - /// publish upload by the staged-tree-hash check in publishStaging. We do NOT purge it - /// eagerly because the same hash may still be referenced by another staged entry. if (staged_here) markVacatedInBase(*r, st, {r->file}); eraseEntry(st, r->file); @@ -1971,26 +1929,6 @@ void ContentAddressedTransaction::truncateFile(const std::string &, size_t) namespace DB::Cas { -namespace -{ -/// Ceiling for a CAS write-buffer allocation. An extreme `max_compress_block_size` (or any other -/// out-of-range buffer-size setting -- fuzzed or misconfigured) flows into `writeFile`'s `buf_size` / -/// `adaptive_write_buffer_initial_size` and, unclamped, reaches `Memory::alloc` where the allocator's -/// `checkSize` (>= 0x8000000000000000) fires a `LOGICAL_ERROR` and aborts the server in -/// debug/sanitizer builds. The ordinary MergeTree writers clamp compress-block sizes to 256 MiB -/// (`MergeTreeWriterSettings::MAX_COMPRESS_BLOCK_SIZE`) for exactly this reason; the CAS write path -/// received the value unclamped. Mirror that ceiling here, at the allocation site, so no caller can -/// pass an absurd size to the allocator. 256 MiB is duplicated (not #included) to keep the Disks layer -/// free of a Storages/MergeTree dependency; the regression guard is -/// `04070_no_crash_extreme_compress_block_size` run on a content-addressed storage policy. -constexpr size_t kMaxCasWriteBufferBytes = 256ULL * 1024 * 1024; - -size_t clampCasWriteBufferSize(size_t size) -{ - return std::min(size, kMaxCasWriteBufferBytes); -} -} - void fanOutBlobUploads( PartWriteTxn & build, std::span requests, diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index 688da91806c77..06666d0325c77 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -33,10 +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. /// -/// 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. +/// File writers stream to private staging. Commit chooses placement using the final paths and +/// sizes. Open readers and uploads can retain a staging file beyond the transaction lifetime. class ContentAddressedTransaction : public IMetadataTransaction { public: @@ -86,8 +84,7 @@ 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. Inline candidates that outgrow - /// the per-file limit stream to local staging. Part blobs are hashed as they are written, and + /// Creates a streaming staging writer for a part file. Its payload is hashed as it is written, and /// verbatim namespace or mountpoint files are read-modify-written when append is requested. std::unique_ptr writeFile( const std::string & path, @@ -127,6 +124,7 @@ class ContentAddressedTransaction : public IMetadataTransaction /// Test-only: stages the part file `path` as a blob entry naming `ref` with no pending upload and no copy /// source, a shape no operation produces. void stageUnprovenBlobEntryForTest(const std::string & path, const Cas::BlobRef & ref, uint64_t size); + void failNextFileRegistrationForTest() { fail_next_file_registration = true; } /// Test-only: the copy source shared by this transaction's borrows from the committed part `part_path`, or null. std::shared_ptr borrowedSourceForTest(const std::string & part_path) const; @@ -137,9 +135,22 @@ class ContentAddressedTransaction : public IMetadataTransaction ContentAddressedMetadataStorage & metadata_storage; private: - /// State for one routed part. The build is opened lazily at the first staged write so every - /// manifest dependency is recorded by the same `Cas::PartWriteTxn`; pending blobs remain in - /// staging until publication. + /// The local file or private S3 object of one successful write. Paths and readers can + /// share it across renames, replacement and transaction teardown. + struct StagedPartFile + { + String staging_path; /// Local filesystem path or the S3 key used by IObjectStorage. + ObjectStoragePtr remote_storage; + String pool_staging_key; /// Pool-relative address for reads through the request engine. + bool allow_inline_by_name = false; /// Set from the original write path, before any hardlink or rename. + bool owns_file = false; + mutable std::atomic publication_attempted{false}; + + ~StagedPartFile(); + }; + using StagedPartFilePtr = std::shared_ptr; + + /// State for one routed part. The build records its manifest dependencies at publication. struct PartStaging { /// Created lazily when a staged blob, inline entry, or adopted entry first needs publication. @@ -163,21 +174,9 @@ class ContentAddressedTransaction : public IMetadataTransaction bool published = false; /// set by publishStaging during commit(); the commit /// loop is idempotent (never re-publishes a staging). - /// `staging_key` is either a private local temp path or an S3 staging object key returned by - /// `CaContentWriteBuffer` at finalize. The backend selects the read-your-writes source; both - /// kinds are removed by this transaction on commit and on abort. - struct PendingBlob - { - Cas::BlobRef ref; - std::string staging_key; - uint64_t size = 0; - Cas::StagingBackend backend = Cas::StagingBackend::Local; - /// The once-only verbatim-copy privilege of the staging object. A hardlink copies this - /// record into another part, and the copy shares the flag, so the parts together copy - /// the staged envelope at most once. - std::shared_ptr> publication_attempted = std::make_shared>(false); - }; - std::vector pending_blobs; /// Staged blobs uploaded after the manifest edge is precommitted. + /// Each newly written path and its hardlinks retain the original staging source. + std::map staged_part_files; + bool has_finalized_file_write = false; /// A build opened only for a transfer cannot replace the temporary segment ref. }; /// Keyed by (namespace string, ref name) — the routed identity, so live/detached/shadow @@ -188,6 +187,7 @@ class ContentAddressedTransaction : public IMetadataTransaction std::unordered_map> copy_sources_by_part; bool committed = false; bool failed = false; + bool fail_next_file_registration = false; /// Memoizes, per (this transaction, ref), whether `unlinkFile` has already resolved a committed /// ref `ForceFresh`. The MergeTree fast-removal path unlinks every file of a part through ONE @@ -198,11 +198,10 @@ class ContentAddressedTransaction : public IMetadataTransaction /// Stage a content part file as a blob without recording a dependency proof, and add/replace its /// manifest entry. Successful post-precommit publication later records `Materialized`. Shared by - /// the streaming-blob path - /// (Local or S3-staging, `backend` says which) and the always-Local inline-cap fallback. + /// writers on both staging backends. void stageBlobPartFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::string & staging_key, - Cas::StagingBackend backend); + ObjectStoragePtr remote_storage, const String & pool_key); /// Builds the fixed-length CABL envelope header for a staging blob, with a fresh `incarnation_tag`, /// so the S3 staging object holds `[header][payload]` and the promote @@ -210,8 +209,8 @@ class ContentAddressedTransaction : public IMetadataTransaction std::string buildS3StagingBlobHeader(const ContentAddressedMetadataStorage::Route & route) const; /// Replaces the staged entry at `entry.path`; `source` is its committed source when it was adopted from - /// another part without its bytes, and nullopt when this transaction uploads or inlines the bytes. - static void putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source); + /// another part without its bytes, and null when this transaction owns the bytes. + static void putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source, StagedPartFilePtr file = {}); static void eraseEntry(PartStaging & st, const std::string & path); /// Renames `entry`, an element of `st.entries`, in place; `new_path` must not be staged. static void rekeyEntry(PartStaging & st, Cas::ManifestEntry & entry, std::string new_path); @@ -237,17 +236,21 @@ class ContentAddressedTransaction : public IMetadataTransaction PartStaging * findStaging(const ContentAddressedMetadataStorage::Route & r); /// Finds the staged manifest entry for a routed file without consulting committed storage. const Cas::ManifestEntry * findStagedEntry(const ContentAddressedMetadataStorage::Route & r) const; - /// Returns the pending (staged but not yet uploaded) blob for `ref`, or nullptr when it has - /// already been uploaded or was never staged. - const PartStaging::PendingBlob * findPendingBlob(const PartStaging & st, const Cas::BlobRef & ref) const; + + static StagedPartFilePtr stagedFileOf(const PartStaging & st, const String & path); + + static std::unique_ptr openStagedPayload(const StagedPartFile & file, uint64_t size, const Cas::PoolPtr & pool); + + Cas::BlobSource stagedUploadSource(const StagedPartFilePtr & file, uint64_t size) const; + + std::vector applyManifestInlineBudget(PartStaging & st, uint64_t inline_bytes_from_unchanged_base_entries) const; /// Returns the part build, creating it lazily with the routed ref as its intended destination. Cas::PartWriteTxn & buildFor(const ContentAddressedMetadataStorage::Route & r, PartStaging & st); /// Parses a disk path and maps a part-file path to its namespace/ref/file route. std::optional routeOf(const std::string & path) const; - /// Removes the transaction's staging after commit or abort: local files and S3 staging objects - /// alike. S3 deletes are best-effort; a lost delete leaves debris for the mount-start sweep. - void cleanupPendingTempFiles() noexcept; + /// Release this transaction's ownership. Readers and pending uploads retain their own handles. + void releaseStagedFiles() noexcept; /// 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; @@ -256,21 +259,6 @@ class ContentAddressedTransaction : public IMetadataTransaction Cas::ManifestId precommitAndUpload(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, 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 - /// has already been moved by the caller; no dependency exists until its upload succeeds. For - /// an uploaded or committed blob, the destination records trusted-manifest evidence and does not - /// perform a pool read before precommit. - /// - /// `pb != nullptr` (pending, not yet uploaded): - /// - `copy_pending=true` → push a copy of *pb into dst_st.pending_blobs (hardlink semantics: - /// both src and dst upload independently; src's copy is left in place by the caller). - /// - `copy_pending=false` → the pb record is already in dst_st (moved or already there). - /// In both cases the later successful upload records `Materialized` in the destination build. - /// - void adoptStagedBlob(const PartStaging::PendingBlob * pb, const Cas::ManifestEntry & entry, - PartStaging & dst_st, Cas::PartWriteTxn & dst_build, bool copy_pending); - /// Publishes one staged part, either by promoting a newly staged manifest or by repointing an /// existing ref after carrying its unchanged entries forward. It is idempotent within the commit /// loop and marks the staging as published. Writes the exact `Cas::CommitOutcome` into `out_slot` diff --git a/src/Disks/tests/gtest_ca_wiring.cpp b/src/Disks/tests/gtest_ca_wiring.cpp index e619a7cf6d50f..6381e42024f71 100644 --- a/src/Disks/tests/gtest_ca_wiring.cpp +++ b/src/Disks/tests/gtest_ca_wiring.cpp @@ -1624,7 +1624,7 @@ TEST(CASWiringInFlight, StagedFilesVisibleBeforeCommit) EXPECT_EQ(tx->tryGetInFlightFileSize("a11/a11a11a1-1111-4111-8111-111111111111/tmp_mut_all_1_1_0/uuid.txt"), std::optional(3)); EXPECT_FALSE(tx->tryGetInFlightFileSize("a11/a11a11a1-1111-4111-8111-111111111111/tmp_mut_all_1_1_0/missing.bin").has_value()); - /// Bytes read back: a pending blob from the local temp file (B188); staged mutable bytes from memory. + /// Both pending files are readable from staging before their final placement is chosen. { auto buf = tx->tryReadFileInFlight("a11/a11a11a1-1111-4111-8111-111111111111/tmp_mut_all_1_1_0/p.proj/data.bin", {}, std::nullopt); ASSERT_TRUE(buf); @@ -1768,6 +1768,47 @@ TEST(CASWiringGc, DisplacedTreeBlobsReclaimedThroughRealPath) << "not just recognized as unreachable; unreachable=" << after.unreachable; } +TEST(CASWiringGc, SharedBlobRemainsReadableAfterFailedMergeScratchIsReclaimed) +{ + auto storage = openWiringStorage(); + const String table = "a11/a11a11a1-1111-4111-8111-111111111111/"; + const String original = table + "all_1_1_0/data.bin"; + const String output = table + "tmp_merge_all_1_2_1"; + auto input = storage->createTransaction(); + writeThroughTransaction(*input, original, "shared"); + input->commit(DB::NoCommitOptions{}); + + auto segments = storage->createTransaction(); + writeThroughTransaction(*segments, output + "/text_index_tmp/shared.bin", "shared"); + writeThroughTransaction(*segments, output + "/text_index_tmp/unique.bin", "only scratch owns this"); + segments->commit(DB::NoCommitOptions{}); + const auto live_key = storage->getStorageObjects(original).at(0).remote_path; + ASSERT_EQ(live_key, storage->getStorageObjects(output + "/text_index_tmp/shared.bin").at(0).remote_path); + const auto dead_key = storage->getStorageObjects(output + "/text_index_tmp/unique.bin").at(0).remote_path; + ASSERT_FALSE(live_key.empty()); + ASSERT_NE(live_key, dead_key); + DB::Cas::tests::OperationForTest op(*storage->store()->poolBackendPtr()); + ASSERT_TRUE((*op).head(dead_key, Retry::standard())); + + { + auto failed_merge = storage->createTransaction(); + writeThroughTransaction(*failed_merge, output + "/data.bin", "unfinished output"); + } + auto cleanup = storage->createTransaction(); + cleanup->removeDirectory(output); + cleanup->commit(DB::NoCommitOptions{}); + + for (size_t i = 0; i < 8 && (*op).head(dead_key, Retry::standard()); ++i) + storage->runOneGcRoundForTest(); + ASSERT_FALSE((*op).head(dead_key, Retry::standard())); + const auto object = storage->getStorageObjects(original).at(0); + auto reader = storage->readBlobPayload({object.remote_path, storage->store()->poolMeta().blob_header_len, object.bytes_size}, + original, DB::ReadSettings{}); + String actual; + DB::readStringUntilEOF(actual, *reader); + EXPECT_EQ(actual, "shared"); +} + /// ==== The DataPartsExchange facade (manifest relink, part_manifest_v2) ==== /// Publish-then-confirm (Task 14) split the receiver's adoption into `prepare` + `promote`, with the @@ -2516,6 +2557,27 @@ int firstPrecommitWriteIdx(const std::vectorgetCommonKeyPrefix()) / "scratch"); + auto storage = std::make_shared(recording, "pool", "srv1", "", nullptr, settings); + storage->startup(); + recording->ops.clear(); + + const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/count.txt"; + auto tx = storage->createTransaction(); + writeThroughTransaction(*tx, path, "42"); + EXPECT_FALSE(std::filesystem::is_empty(storage->scratchPath())); + tx->commit(DB::NoCommitOptions{}); + + EXPECT_GE(firstPrecommitWriteIdx(recording->ops), 0); + for (const auto & op : recording->ops) + EXPECT_EQ(op.key.find("/blobs/"), String::npos) << op.op << " " << op.key; + EXPECT_EQ(storage->tryGetInManifestBytes(path), "42"); +} + /// B188: every pool op (read OR write) on /blobs/ or /trees/ must come AFTER the first write that /// appends the create-precommit owner event (the first root-shard CAS) — including HEAD /// (exists/getObjectMetadata) and GET (readObject), since the @@ -2710,6 +2772,52 @@ TEST(CASWiringPrecommitOrder, CommittedSourceAdoptNoHeadBeforePrecommit) /// (the cross-part pending-source branch: `&dst_st != src_st`, copies the PendingBlob record so /// publishStaging uploads it for the dst part too). After commit both parts must read back the /// identical content. +TEST(CASWiringInFlight, OpenLocalReaderRetainsFileThroughCommitOrAbort) +{ + for (bool commit : {false, true}) + { + SCOPED_TRACE(commit); + auto storage = openWiringStorage(); + auto tx = storage->createTransaction(); + const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/data.bin"; + writeThroughTransaction(*tx, path, "staged"); + auto reader = tx->tryReadFileInFlight(path, {}, {}); + ASSERT_TRUE(reader); + const auto staging_path = reader->getFileName(); + if (commit) + tx->commit(DB::NoCommitOptions{}); + tx.reset(); + ASSERT_TRUE(std::filesystem::exists(staging_path)); + reader->seek(5, SEEK_SET); + char byte; + reader->readStrict(&byte, 1); + EXPECT_EQ(byte, 'd'); + reader.reset(); + EXPECT_FALSE(std::filesystem::exists(staging_path)); + } +} + +TEST(CASWiringPending, SingleByteTransferCanPublishANewPart) +{ + for (const bool move : {false, true}) + { + SCOPED_TRACE(move); + auto storage = openWiringStorage(); + const String dir = "a11/a11a11a1-1111-4111-8111-111111111111/"; + const String src = dir + "all_2_2_0/a.txt"; + const String dst = dir + "all_1_1_0/b.txt"; + auto tx = storage->createTransaction(); + writeThroughTransaction(*tx, src, "x"); + if (move) + tx->moveFile(src, dst); + else + tx->createHardLink(src, dst); + tx->commit(DB::NoCommitOptions{}); + EXPECT_EQ(storage->tryGetInManifestBytes(dst), "x"); + EXPECT_EQ(storage->existsFile(src), !move); + } +} + TEST(CASWiringPending, HardlinkOfPendingBlobCommitsAndReadsBack) { auto storage = openWiringStorage(); diff --git a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp index d0eb7cc105e83..1cbeef7bfc50d 100644 --- a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -11,12 +11,14 @@ #include #include +#include #include #include namespace DB::ErrorCodes { extern const int INCORRECT_DATA; + extern const int LIMIT_EXCEEDED; } /// A part or a nested scratch storage whose small files sum past the manifest's inline budget must @@ -695,3 +697,233 @@ TEST(CASInlineCandidateMemory, ThresholdPreservesPlacementAndPayload) EXPECT_TRUE(storage->tryGetInManifestBytes(dir + "at.idx") == at_limit); expectBlob(*storage, ref, "over.idx", over_limit); } + +TEST(CASInlineCandidateMemory, ClosedCandidatesStayInStagingUntilPlacement) +{ + auto storage = openStorage(); + const std::string ref = "all_1_1_0"; + const std::string dir = table_dir + ref + "/"; + const std::string bytes = payload(600 * kib, 7); + auto tx = storage->createTransaction(); + const auto retained = std::async(std::launch::async, [&] + { + MemoryTracker tracker(&total_memory_tracker, VariableContext::Process, false); + DB::ThreadStatus thread_status; + thread_status.memory_tracker.setParent(&tracker); + thread_status.untracked_memory_limit = 0; + for (size_t i = 0; i < 64; ++i) + writeFileTx(*tx, dir + std::to_string(i) + ".idx", bytes); + return tracker.get(); + }).get(); +#if !defined(SANITIZER) + /// The closed payloads total 37.5 MiB. Only path metadata should remain on the writer thread. + EXPECT_LT(retained, static_cast(inline_total_budget)); +#endif + ::testing::Test::RecordProperty("retained_bytes_before_commit", std::to_string(retained)); + + size_t staged_bytes = 0; + for (const auto & file : std::filesystem::directory_iterator(storage->scratchPath())) + staged_bytes += file.file_size(); + EXPECT_EQ(staged_bytes, 64 * bytes.size()); + tx->commit(DB::NoCommitOptions{}); + const auto manifest = manifestOf(*storage, uuid, ref); + ASSERT_EQ(manifest.entries.size(), 64u); + EXPECT_EQ(inlineTotal(manifest), (inline_total_budget / bytes.size()) * bytes.size()); + for (const auto & entry : manifest.entries) + EXPECT_TRUE(readPartFile(*storage, dir + entry.path) == bytes) << entry.path; + EXPECT_TRUE(std::filesystem::is_empty(storage->scratchPath())); +} + +TEST(CASInlineCapGaps, StagedAliasesKeepTheirSourceAndOriginalPlacementEligibility) +{ + auto storage = openStorage(); + const auto src = table_dir + "all_1_1_0/"; + const auto dst = table_dir + "all_2_2_0/"; + auto tx = storage->createTransaction(); + writeFileTx(*tx, src + "a.txt", "x"); + writeFileTx(*tx, src + "a.bin", "x"); + tx->createHardLink(src + "a.txt", dst + "copied.bin"); + tx->moveFile(src + "a.bin", dst + "moved.txt"); + writeFileTx(*tx, src + "a.txt", "replacement"); + tx->commit(DB::NoCommitOptions{}); + EXPECT_EQ(storage->tryGetInManifestBytes(dst + "copied.bin"), "x"); + expectBlob(*storage, "all_2_2_0", "moved.txt", "x"); + EXPECT_FALSE(storage->existsFile(src + "a.bin")); + EXPECT_EQ(storage->tryGetInManifestBytes(src + "a.txt"), "replacement"); +} + +TEST(CASInlineCapGaps, TransferAlonePreservesNestedBaseButOwnWriteReplacesIt) +{ + for (const bool write_first : {false, true}) + { + for (const bool own_write : {false, true}) + { + SCOPED_TRACE(write_first); + SCOPED_TRACE(own_write); + auto storage = openStorage(); + const auto src = table_dir + "all_1_1_0/"; + const auto dst = table_dir + "tmp_merge_all_1_2_1/"; + auto tx = storage->createTransaction(); + writeFileTx(*tx, dst + "text_index_tmp/0.idx", "base"); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + writeFileTx(*tx, src + "pending.idx", "m"); + if (own_write && write_first) + writeFileTx(*tx, dst + "own.idx", "w"); + tx->moveFile(src + "pending.idx", dst + "moved.idx"); + if (own_write && !write_first) + writeFileTx(*tx, dst + "own.idx", "w"); + tx->commit(DB::NoCommitOptions{}); + + EXPECT_EQ(storage->tryGetInManifestBytes(dst + "moved.idx"), "m"); + EXPECT_FALSE(storage->existsFile(src + "pending.idx")); + EXPECT_EQ(storage->existsFile(dst + "text_index_tmp/0.idx"), !own_write); + } + } +} + +TEST(CASInlineCapGaps, ReusingRemovedPartNameDoesNotAllowReplacingAnotherWritersSegments) +{ + auto storage = openStorage(); + const auto dir = table_dir + "tmp_merge_all_1_2_1"; + auto tx = storage->createTransaction(); + writeFileTx(*tx, dir + "/discarded.txt", "old"); + tx->removeDirectory(dir); + auto segments = storage->createTransaction(); + writeFileTx(*segments, dir + "/text_index_tmp/0.idx", "segment"); + segments->commit(DB::NoCommitOptions{}); + + writeFileTx(*tx, table_dir + "all_1_1_0/moved.txt", "new"); + tx->moveFile(table_dir + "all_1_1_0/moved.txt", dir + "/moved.txt"); + EXPECT_THROW(tx->commit(DB::NoCommitOptions{}), DB::Exception); + EXPECT_EQ(storage->tryGetInManifestBytes(dir + "/text_index_tmp/0.idx"), "segment"); + EXPECT_FALSE(storage->existsFile(dir + "/moved.txt")); +} + +TEST(CASInlineCapGaps, RenamingStagedDirectoryAcceptsIdenticalBorrowedInline) +{ + auto storage = openStorage(); + const auto src = table_dir + "tmp_merge_all_1_2_1"; + const auto dst = table_dir + "all_1_2_1"; + auto tx = storage->createTransaction(); + writeFileTx(*tx, table_dir + "all_1_1_0/source.txt", "same"); + tx->commit(DB::NoCommitOptions{}); + tx = storage->createTransaction(); + tx->createHardLink(table_dir + "all_1_1_0/source.txt", dst + "/file.txt"); + writeFileTx(*tx, src + "/file.txt", "same"); + tx->moveDirectory(src, dst); + tx->commit(DB::NoCommitOptions{}); + EXPECT_EQ(storage->tryGetInManifestBytes(dst + "/file.txt"), "same"); +} + +TEST(CASInlineCapGaps, CorruptSelectedInlineDoesNotRepoint) +{ + for (const bool truncate : {false, true}) + { + SCOPED_TRACE(truncate); + auto storage = openStorage(); + const String path = table_dir + "all_1_1_0/small.idx"; + auto tx = storage->createTransaction(); + writeFileTx(*tx, path, "old"); + tx->commit(DB::NoCommitOptions{}); + tx = storage->createTransaction(); + auto writer = dynamic_cast(*tx).writeFile(path, 4096, DB::WriteMode::Rewrite, {}); + writer->write("new", 3); + writer->finalize(); + if (truncate) + std::filesystem::resize_file(writer->getFileName(), 2); + else + { + std::ofstream out(writer->getFileName(), std::ios::binary); + out.write("bad", 3); + ASSERT_TRUE(out.good()); + } + EXPECT_THROW(tx->commit(DB::NoCommitOptions{}), DB::Exception); + EXPECT_EQ(storage->tryGetInManifestBytes(path), "old"); + } +} + +TEST(CASInlineCapGaps, SpilledCandidateIsNotReadToChoosePlacement) +{ + auto storage = openStorage(); + const String bytes = payload(mib, 80); + const auto dir = table_dir + "all_2_2_0/"; + auto tx = storage->createTransaction(); + writeFileTx(*tx, table_dir + "all_1_1_0/same.bin", bytes); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + writeFullBudget(*tx, dir.substr(0, dir.size() - 1), "other"); + auto writer = dynamic_cast(*tx).writeFile(dir + "first.idx", 4096, DB::WriteMode::Rewrite, {}); + writer->write(bytes.data(), bytes.size()); + writer->finalize(); + /// The first path sorts first among 17 equally large candidates. Its blob already exists: + /// neither placement planning nor reuse requires reopening its staging file. + ASSERT_TRUE(std::filesystem::remove(writer->getFileName())); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, "all_2_2_0", "first.idx", bytes); +} + +TEST(CASInlineCapGaps, LoadTimeFileAboveThePerFileThresholdIsABlobToday) +{ + auto storage = openStorage(); + const std::string table = "e07/e07e07e0-0707-4707-8707-070707070707/"; + 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); + files["columns.txt"] = payload(inline_file_threshold, 2); + files["serialization.json"] = payload(inline_file_threshold + 1, 3); + + 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()) << error; + + expectReadsBack(*storage, final_part, files); + const auto manifest = manifestOf(*storage, "e07e07e0-0707-4707-8707-070707070707", "all_1_1_0"); + ASSERT_TRUE(DB::Cas::findEntry(manifest.entries, "columns.txt") && DB::Cas::findEntry(manifest.entries, "serialization.json")); + EXPECT_EQ(DB::Cas::findEntry(manifest.entries, "columns.txt")->placement, DB::Cas::EntryPlacement::Inline); + EXPECT_EQ(DB::Cas::findEntry(manifest.entries, "serialization.json")->placement, DB::Cas::EntryPlacement::Blob); +} + +/// A part name is carried in every ref-log record of the part, and a record has a byte cap. A partition +/// key of many integer columns gives a name of several kilobytes. The refusal arrives at commit, after +/// the part's files and its manifest were written, and the same insert can never pass. +TEST(CASInlineCapGaps, PartNameOverTheRefRecordCapIsRefusedOnlyAtCommit) +{ + auto storage = openStorage(); + const std::string table = "e08/e08e08e0-0808-4808-8808-080808080808/"; + + std::string partition_id; + for (size_t column = 0; column < 200; ++column) + partition_id += (column ? "-" : "") + std::string("18446744073709551615"); + const std::string part_name = partition_id + "_1_1_0"; + ASSERT_GT(part_name.size(), 4096u); + + auto tx = storage->createTransaction(); + writeFileTx(*tx, table + "tmp_insert_" + part_name + "/data.bin", payload(64 * kib, 1)); + writeFileTx(*tx, table + "tmp_insert_" + part_name + "/count.txt", "1"); + + const std::string error = commitErrorOf(*tx); + EXPECT_NE(error.find(std::to_string(DB::ErrorCodes::LIMIT_EXCEEDED) + ": "), std::string::npos) << error; + EXPECT_NE(error.find("per-op cap"), std::string::npos) << error; +} + +TEST(CASInlineCandidateMemory, LargeCandidateMatchesDirectBlobHashAndReadsBack) +{ + auto storage = openStorage(); + const auto dir = table_dir + "tmp_insert_all_1_1_0/"; + const auto bytes = payload(64 * mib, 13); + auto tx = storage->createTransaction(); + writeFileTx(*tx, dir + "same.bin", bytes); + writeFileTx(*tx, dir + "skp_idx_t.dct.idx", bytes); + tx->moveDirectory(table_dir + "tmp_insert_all_1_1_0", table_dir + "all_1_1_0"); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, "all_1_1_0", "same.bin", bytes); + expectBlob(*storage, "all_1_1_0", "skp_idx_t.dct.idx", bytes); +} diff --git a/src/Disks/tests/gtest_cas_s3_staging.cpp b/src/Disks/tests/gtest_cas_s3_staging.cpp index 1437f7f9f0ca5..f2c21a0c7592e 100644 --- a/src/Disks/tests/gtest_cas_s3_staging.cpp +++ b/src/Disks/tests/gtest_cas_s3_staging.cpp @@ -15,6 +15,8 @@ #include #include #include +#include +#include #include #include @@ -24,6 +26,8 @@ #include #include #include +#include +#include #include #include #include @@ -88,15 +92,50 @@ Poco::AutoPtr configWithDiskSection(const std::str return new Poco::Util::XMLConfiguration(xml_stream); } +/// Resolve the key again on every range read, as S3 does. A permanently open local +/// descriptor would keep serving bytes even if the key had already been deleted. +class StagingRangeReader final : public DB::ReadBufferFromFileBase +{ +public: + using Open = std::function()>; + StagingRangeReader(String name_, Open open_) : ReadBufferFromFileBase(4096, nullptr, 0), name(std::move(name_)), open(std::move(open_)) {} + + String getFileName() const override { return name; } + off_t getPosition() override { return end_offset - available(); } + off_t seek(off_t offset, int whence) override + { + end_offset = whence == SEEK_SET ? offset : getPosition() + offset; + working_buffer.resize(0); + pos = working_buffer.begin(); + return end_offset; + } + +private: + bool nextImpl() override + { + auto input = open(); + input->seek(end_offset, SEEK_SET); + const size_t count = input->read(internal_buffer.begin(), internal_buffer.size()); + working_buffer = Buffer(internal_buffer.begin(), internal_buffer.begin() + count); + end_offset += count; + return count != 0; + } + + String name; + Open open; + off_t end_offset = 0; +}; + /// A local test store whose copy-mode capability is configurable. Its ordinary `copyObject` /// implementation remains the real local implementation; only the advertised transport capability /// differs so mount selection can be tested independently of a live S3 service. class FakeNativeCopyObjectStorage final : public DB::LocalObjectStorage { public: - FakeNativeCopyObjectStorage(DB::LocalObjectStorageSettings settings_, bool native_only_copy_supported_) + FakeNativeCopyObjectStorage(DB::LocalObjectStorageSettings settings_, bool native_only_copy_supported_, bool observe_staging_ranges_) : DB::LocalObjectStorage(std::move(settings_)) , native_only_copy_supported(native_only_copy_supported_) + , observe_staging_ranges(observe_staging_ranges_) { } @@ -106,8 +145,26 @@ class FakeNativeCopyObjectStorage final : public DB::LocalObjectStorage || (mode == DB::ObjectStorageCopyMode::NativeOnly && native_only_copy_supported); } + std::unique_ptr readObject( + const DB::StoredObject & object, const DB::ReadSettings & settings, std::optional hint, + bool external, bool restrict_seek) const override + { + if (observe_staging_ranges && object.remote_path.contains("/staging/")) + return std::make_unique(object.remote_path, [this, object, settings, hint, external, restrict_seek] + { + ++staging_range_reads; + return DB::LocalObjectStorage::readObject(object, settings, hint, external, restrict_seek); + }); + return DB::LocalObjectStorage::readObject(object, settings, hint, external, restrict_seek); + } + + mutable std::atomic staging_range_reads{0}; + std::atomic staging_deletes{0}; + void removeObjectIfExists(const DB::StoredObject & object) override { + if (observe_staging_ranges && object.remote_path.contains("/staging/")) + ++staging_deletes; if (throw_on_remove.load()) throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected delete failure for {}", object.remote_path); DB::LocalObjectStorage::removeObjectIfExists(object); @@ -117,9 +174,10 @@ class FakeNativeCopyObjectStorage final : public DB::LocalObjectStorage private: const bool native_only_copy_supported; + const bool observe_staging_ranges; }; -std::shared_ptr makeFakeNativeCopyStorage(bool native_only_copy_supported) +std::shared_ptr makeFakeNativeCopyStorage(bool native_only_copy_supported, bool observe_staging_ranges = false) { static std::atomic counter{0}; const auto unique = std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)); @@ -131,7 +189,7 @@ std::shared_ptr makeFakeNativeCopyStorage(bool nati DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); return DB::Cas::tests::ownedByDirectory( - std::make_shared(std::move(settings), native_only_copy_supported), root); + std::make_shared(std::move(settings), native_only_copy_supported, observe_staging_ranges), root); } /// A fake object-store sink for Task 4 of the S3-native staging plan (`DB::Cas::CaContentWriteBuffer`'s @@ -825,9 +883,7 @@ TEST(CASS3Staging, UnsupportedNativeOnlyCopyDoesNotFallBackToLocal) } /// (a) A successful commit removes the S3 staging object of a pending blob it staged. Uses the B189 -/// orphan shape (the pending blob's entry is unlinked before commit) so `publishStaging` never calls -/// `putBlob` for it — only `cleanupPendingTempFiles`'s Task 6 branch ever touches this staging object, -/// which is exactly the seam this test targets. +/// orphan shape. An unlinked staged file and a file ultimately placed Inline must both be reclaimed. TEST(CASS3Staging, SuccessfulCommitRemovesOrphanedS3StagingObject) { auto object_storage = makeFakeNativeCopyStorage(/*native_only_copy_supported=*/true); @@ -847,7 +903,7 @@ TEST(CASS3Staging, SuccessfulCommitRemovesOrphanedS3StagingObject) DB::RelativePathsWithMetadata staged_before; object_storage->listObjects(metadata_storage->stagingKeyPrefix(), staged_before, /*max_keys=*/0); - ASSERT_EQ(staged_before.size(), 1u) << "exactly orphan.bin's S3 staging object should exist pre-commit"; + ASSERT_EQ(staged_before.size(), 2u); tx->unlinkFile("a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/orphan.bin", false, false); @@ -855,8 +911,7 @@ TEST(CASS3Staging, SuccessfulCommitRemovesOrphanedS3StagingObject) DB::RelativePathsWithMetadata staged_after; object_storage->listObjects(metadata_storage->stagingKeyPrefix(), staged_after, /*max_keys=*/0); - EXPECT_TRUE(staged_after.empty()) - << "cleanupPendingTempFiles must remove the orphaned S3 staging object after a successful commit"; + EXPECT_TRUE(staged_after.empty()); } /// (b) Read-your-writes over an S3 pending blob (before commit) returns the staged bytes from the S3 @@ -881,27 +936,189 @@ TEST(CASS3Staging, ReadYourWritesReturnsStagedBytesFromS3StagingObject) EXPECT_EQ(got, payload); } -TEST(CASS3Staging, OversizedInlineCandidateKeepsLocalStaging) +TEST(CASS3Staging, InlineCandidateUsesConfiguredStaging) { 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); + for (const size_t size : {0u, 1024u}) + { + SCOPED_TRACE(size); + const std::string bytes(size, 'x'); + auto & ca_tx = dynamic_cast(*tx); + auto writer = ca_tx.writeFile(path, size, DB::WriteMode::Rewrite, {}); + writer->write(bytes.data(), bytes.size()); + writer->finalize(); - 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()); + DB::RelativePathsWithMetadata staged; + objects->listObjects(storage->stagingKeyPrefix(), staged, 0); + ASSERT_EQ(staged.size(), 1u); + EXPECT_EQ(objects->getObjectMetadata(staged.front()->relative_path, false).size_bytes, storage->store()->poolMeta().blob_header_len + size); + 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_EQ(storage->tryGetInManifestBytes(path), bytes); + tx = storage->createTransaction(); + } +} + +TEST(CASS3Staging, OpenReaderKeepsPrivateObjectThroughCommitOrAbort) +{ + for (const bool commit : {false, true}) + { + SCOPED_TRACE(commit); + auto objects = makeFakeNativeCopyStorage(true, /*observe_staging_ranges=*/true); + auto storage = makeS3StagingMetadataStorageForTest(objects, "mountReaderLifetime"); + storage->startup(); + const std::string path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/skip.dct.idx"; + auto tx = storage->createTransaction(); + std::string bytes(64 * 1024, 'x'); + bytes.back() = 'z'; + writeThroughS3Transaction(dynamic_cast(*tx), path, bytes); + + DB::RelativePathsWithMetadata staged; + objects->listObjects(storage->stagingKeyPrefix(), staged, 0); + ASSERT_EQ(staged.size(), 1u); + auto reader = tx->tryReadFileInFlight(path, DB::ReadSettings{}, {}); + ASSERT_NE(reader, nullptr); + char byte; + reader->readStrict(&byte, 1); + ASSERT_EQ(byte, 'x'); + if (commit) + tx->commit(DB::NoCommitOptions{}); + tx.reset(); + + const size_t reads_before_seek = objects->staging_range_reads.load(); + staged.clear(); + objects->listObjects(storage->stagingKeyPrefix(), staged, 0); + ASSERT_EQ(staged.size(), 1u); + reader->seek(bytes.size() - 1, SEEK_SET); + reader->readStrict(&byte, 1); + EXPECT_EQ(byte, 'z'); + EXPECT_GT(objects->staging_range_reads.load(), reads_before_seek); + EXPECT_EQ(objects->staging_deletes.load(), 0u); + reader.reset(); + EXPECT_EQ(objects->staging_deletes.load(), 1u); + staged.clear(); + objects->listObjects(storage->stagingKeyPrefix(), staged, 0); + EXPECT_TRUE(staged.empty()); + } +} + +/// Run explicitly on both revisions with --gtest_also_run_disabled_tests and a descriptor +/// limit above 5,000. Record the observed peaks instead of imposing a backend-independent limit. +TEST(CASInlineCandidateMemory, DISABLED_FiveThousandOpenWriters) +{ + constexpr size_t num_writers = 5000; + constexpr size_t buffer_size = 64 * 1024; + struct rlimit limit{}; + const int status = getrlimit(RLIMIT_NOFILE, &limit); + ASSERT_EQ(status, 0); + if (limit.rlim_cur < num_writers + 128) + GTEST_SKIP() << "requires at least " << num_writers + 128 << " descriptors"; + ::testing::Test::RecordProperty("fd_limit", std::to_string(limit.rlim_cur)); + ::testing::Test::RecordProperty("buffer_bytes", buffer_size); + + for (bool remote : {false, true}) + { + auto objects = makeFakeNativeCopyStorage(true); + auto settings = DB::Cas::tests::makeSettingsForTest( + "mountManyWriters", std::filesystem::path(objects->getCommonKeyPrefix()) / "scratch"); + if (remote) + { + settings[DB::ContentAddressedSetting::staging_backend] = "s3"; + settings.validate(); + } + auto storage = std::make_shared(objects, "pool", "srv1", "", nullptr, settings); + storage->startup(); + std::async(std::launch::async, [&] + { + MemoryTracker tracker(&total_memory_tracker, VariableContext::Process, false); + DB::ThreadStatus thread_status; + thread_status.memory_tracker.setParent(&tracker); + thread_status.untracked_memory_limit = 0; + const String prefix = remote ? "s3_adapter_" : "local_"; + auto record = [&](const String & field, auto value) + { + ::testing::Test::RecordProperty(prefix + field, std::to_string(value)); + }; + DB::WriteSettings write_settings; + write_settings.use_adaptive_write_buffer = true; + write_settings.adaptive_write_buffer_initial_size = 4096; + record("adaptive_initial_bytes", write_settings.adaptive_write_buffer_initial_size); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const String dir = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/"; + std::vector> writers; + for (size_t i = 0; i < num_writers; ++i) + { + auto out = ca_tx.writeFile(dir + std::to_string(i) + ".idx", buffer_size, DB::WriteMode::Rewrite, write_settings); + out->write("prefix", 6); + if (i % 2 == 0) + out->next(); + writers.push_back(std::move(out)); + } + record("open_bytes", tracker.get()); +#if defined(OS_LINUX) + record("open_fds", std::distance(std::filesystem::directory_iterator("/proc/self/fd"), std::filesystem::directory_iterator{})); +#endif + for (size_t i = 0; i < num_writers; ++i) + { + if (i % 2 == 0) + writers[i]->finalize(); + else + writers[i]->cancel(); + writers[i].reset(); + } + record("closed_bytes", tracker.get()); + tx->commit(DB::NoCommitOptions{}); + record("committed_bytes", tracker.get()); + EXPECT_EQ(storage->tryGetInManifestBytes(dir + "0.idx"), "prefix"); + EXPECT_FALSE(storage->existsFile(dir + "1.idx")); + record("peak_bytes", tracker.getPeak()); + }).get(); + } +} + +TEST(CASS3Staging, FailedReplacementLeavesThePreviousSourceReadable) +{ + for (const bool remote : {false, true}) + { + SCOPED_TRACE(remote); + auto objects = makeFakeNativeCopyStorage(true); + auto settings = DB::Cas::tests::makeSettingsForTest( + "mountRegistration", std::filesystem::path(objects->getCommonKeyPrefix()) / "scratch"); + if (remote) + { + settings[DB::ContentAddressedSetting::staging_backend] = "s3"; + settings.validate(); + } + auto storage = std::make_shared(objects, "pool", "srv1", "", nullptr, settings); + storage->startup(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/a.idx"; + writeThroughS3Transaction(ca_tx, path, "old"); + ca_tx.failNextFileRegistrationForTest(); + EXPECT_THROW(writeThroughS3Transaction(ca_tx, path, "new"), DB::Exception); + + if (remote) + { + DB::RelativePathsWithMetadata staged; + objects->listObjects(storage->stagingKeyPrefix(), staged, 0); + EXPECT_EQ(staged.size(), 1u); + } + else + EXPECT_EQ(std::distance(std::filesystem::directory_iterator(storage->scratchPath()), std::filesystem::directory_iterator{}), 1); + tx->commit(DB::NoCommitOptions{}); + EXPECT_EQ(storage->tryGetInManifestBytes(path), "old"); + } } /// An aborted transaction deletes its own S3 staging object instead of leaving it for the next mount. @@ -1500,6 +1717,36 @@ std::shared_ptr makeFakeGenerationObjectStorageForT } +TEST(CASS3Staging, OversizedCandidatePublishesFromConfiguredPrivateObject) +{ + auto objects = makeFakeGenerationObjectStorageForTest(); + auto storage = makeS3StagingMetadataStorageForTest(objects, "mountLargeIndex"); + storage->startup(); + auto tx = storage->createTransaction(); + const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/skip.dct.idx"; + const String bytes(1024 * 1024 + 1, 'x'); + writeThroughS3Transaction(dynamic_cast(*tx), path, bytes); + DB::RelativePathsWithMetadata staged; + objects->listObjects(storage->stagingKeyPrefix(), staged, 0); + ASSERT_EQ(staged.size(), 1u); + EXPECT_TRUE(!std::filesystem::exists(storage->scratchPath()) || std::filesystem::is_empty(storage->scratchPath())); + tx->commit(DB::NoCommitOptions{}); + EXPECT_FALSE(storage->tryGetInManifestBytes(path).has_value()); + const auto copies = objects->copiesByDestination(); + ASSERT_EQ(copies.size(), 1u); + EXPECT_EQ(copies.begin()->second, 1u); + const auto published = storage->getStorageObjects(path); + ASSERT_EQ(published.size(), 1u); + auto reader = storage->readBlobPayload({.key = published[0].remote_path, + .offset = storage->store()->poolMeta().blob_header_len, .length = bytes.size()}, path, {}); + String got; + DB::readStringUntilEOF(got, *reader); + EXPECT_TRUE(got == bytes); + staged.clear(); + objects->listObjects(storage->stagingKeyPrefix(), staged, 0); + EXPECT_TRUE(staged.empty()); +} + /// A store whose iterator does not page (the fallback `IObjectStorage::iterate` lists `max_keys` keys /// once and ends) must still let a page-sized list report that more keys follow. A page that ended /// exactly at the limit with an empty cursor would read as the end of the prefix, and the startup diff --git a/tests/integration/test_cas_s3_staging/__init__.py b/tests/integration/test_cas_s3_staging/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/integration/test_cas_s3_staging/configs/storage_conf.xml b/tests/integration/test_cas_s3_staging/configs/storage_conf.xml new file mode 100644 index 0000000000000..e714ddaffd1ea --- /dev/null +++ b/tests/integration/test_cas_s3_staging/configs/storage_conf.xml @@ -0,0 +1,23 @@ + + + + + object_storage + s3 + cas + itest-staging + s3 + http://rustfs1:11121/test/cas_staging_it/ + clickhouse + clickhouse + 5242880 + 5242880 + + + + +
cas_staged
+
+
+
+
diff --git a/tests/integration/test_cas_s3_staging/test.py b/tests/integration/test_cas_s3_staging/test.py new file mode 100644 index 0000000000000..35f0eaadbfbd0 --- /dev/null +++ b/tests/integration/test_cas_s3_staging/test.py @@ -0,0 +1,78 @@ +import pytest + +from helpers.cluster import ClickHouseCluster + + +cluster = ClickHouseCluster(__file__) +node = cluster.add_instance( + "node", main_configs=["configs/storage_conf.xml"], with_rustfs=True, stay_alive=True +) + + +@pytest.fixture(scope="module", autouse=True) +def start_cluster(): + try: + cluster.start() + yield + finally: + cluster.shutdown() + + +@pytest.fixture +def staged_table(): + node.query( + "CREATE TABLE staged (n UInt64 CODEC(NONE)) ENGINE = MergeTree " + "ORDER BY tuple() SETTINGS storage_policy = 'cas_staged', " + "min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0" + ) + try: + yield + finally: + node.query("DROP TABLE staged SYNC") + + +rows = 2 * 1024 * 1024 +insert_query = f"INSERT INTO staged SELECT number FROM numbers({rows})" +insert_settings = { + "min_insert_block_size_rows": rows, + "min_insert_block_size_bytes": 0, + "max_insert_threads": 1, +} +multipart_counter = "SELECT sum(value) FROM system.events WHERE event = 'DiskS3UploadPart'" + + +def assert_staging_empty(): + bucket = cluster.rustfs_bucket + cluster.rustfs_client.stat_object(bucket, "cas_staging_it/_pool_meta") + objects = cluster.rustfs_client.list_objects( + bucket, prefix="cas_staging_it/staging/itest-staging/", recursive=True + ) + assert list(objects) == [] + + +def test_multipart_staging_is_released_and_part_reads_after_restart(staged_table): + before = int(node.query(multipart_counter)) + node.query(insert_query, settings=insert_settings) + assert int(node.query(multipart_counter)) > before + assert_staging_empty() + + node.restart_clickhouse() + assert node.query("SELECT count(), sum(n) FROM staged").strip() == ( + f"{rows}\t{rows * (rows - 1) // 2}" + ) + assert node.query("CHECK TABLE staged SETTINGS check_query_single_value_result = 1").strip() == "1" + + +def test_failed_disk_commit_releases_private_objects(staged_table): + before = int(node.query(multipart_counter)) + failpoint = "part_storage_fail_commit_transaction" + node.query(f"SYSTEM ENABLE FAILPOINT {failpoint}") + try: + error = node.query_and_get_error(insert_query, settings=insert_settings) + assert failpoint in error + finally: + node.query(f"SYSTEM DISABLE FAILPOINT {failpoint}") + + assert int(node.query(multipart_counter)) > before + assert node.query("SELECT count() FROM staged").strip() == "0" + assert_staging_empty() 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 index 0f6cd234a393c..c4a1485be9a07 100644 --- 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 @@ -1,8 +1,8 @@ t_merge 1 -t_merge 1000000 1 +t_merge 100 1 t_merge 1 1 t_mat 1 -t_mat 1000000 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 index 4834a069ec12c..7e9c8bd8c7f5b 100755 --- 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 @@ -11,37 +11,37 @@ CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) set -e -o pipefail CLIENT="${CLICKHOUSE_CLIENT} --allow_experimental_full_text_index=1" -ROWS=1000000 +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/')" } -# One 64-character token per row, different in every row: the dictionary of a segment is about as large -# as the tokens it holds, whatever the codec. +# 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, concat(hex(sipHash128(number)), hex(sipHash128(number, 1))) - FROM numbers($2, $3) SETTINGS max_insert_threads = 1, max_block_size = 1000000, max_insert_block_size = 1000000" + ${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, concat(hex(sipHash128(toUInt64(7))), hex(sipHash128(toUInt64(7), 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" } -# A segment is flushed after every block that the builder reads, and a block is at least one granule. With -# 1024 rows per granule each segment holds about 1024 tokens (about 70 KiB), far below the size at which a -# file stops being small, and the rebuild leaves several hundred segments. -SEGMENTS="index_granularity = 1024, merge_max_block_size = 1024, text_index_max_processed_tokens_before_flush = 1, +# Flush after each five-row block. The segment dictionaries remain eligible for Inline +# individually, while their combined size exceeds the manifest budget. +SEGMENTS="index_granularity = 5, merge_max_block_size = 5, text_index_max_processed_tokens_before_flush = 1, 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', countIf(ProfileEvents['TextIndexTemporarySegmentsWritten'] >= 100 + ${CLIENT} -q "SELECT '$1', countIf(ProfileEvents['TextIndexTemporarySegmentsWritten'] >= 20 AND ProfileEvents['CASManifestInlineEntriesSelectedForBlob'] > 0) = 1 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)" @@ -65,7 +65,7 @@ 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 = 1024" +${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 From 043e65856e10b0e32dddb686041ee2fc54da38d8 Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Sat, 28 Nov 2026 23:08:00 +0100 Subject: [PATCH 4/7] Revert "Stage CAS part files before choosing inline placement" This reverts commit 64305201b60446f6453336c6ee9c71d3e2f5c526. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- .../ContentAddressedTransaction.cpp | 676 ++++++++++-------- .../ContentAddressedTransaction.h | 88 ++- src/Disks/tests/gtest_ca_wiring.cpp | 110 +-- src/Disks/tests/gtest_cas_inline_cap_gaps.cpp | 232 ------ src/Disks/tests/gtest_cas_s3_staging.cpp | 293 +------- .../test_cas_s3_staging/__init__.py | 0 .../configs/storage_conf.xml | 23 - tests/integration/test_cas_s3_staging/test.py | 78 -- ...text_index_rebuild_inline_budget.reference | 4 +- ...15_cas_text_index_rebuild_inline_budget.sh | 24 +- 10 files changed, 457 insertions(+), 1071 deletions(-) delete mode 100644 tests/integration/test_cas_s3_staging/__init__.py delete mode 100644 tests/integration/test_cas_s3_staging/configs/storage_conf.xml delete mode 100644 tests/integration/test_cas_s3_staging/test.py diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index ed4f79add6127..ad5d0d0dd1715 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -60,24 +60,6 @@ namespace DB::Cas namespace { -/// Ceiling for a CAS write-buffer allocation. An extreme `max_compress_block_size` (or any other -/// out-of-range buffer-size setting -- fuzzed or misconfigured) flows into `writeFile`'s `buf_size` / -/// `adaptive_write_buffer_initial_size` and, unclamped, reaches `Memory::alloc` where the allocator's -/// `checkSize` (>= 0x8000000000000000) fires a `LOGICAL_ERROR` and aborts the server in -/// debug/sanitizer builds. The ordinary MergeTree writers clamp compress-block sizes to 256 MiB -/// (`MergeTreeWriterSettings::MAX_COMPRESS_BLOCK_SIZE`) for exactly this reason; the CAS write path -/// received the value unclamped. Mirror that ceiling here, at the allocation site, so no caller can -/// pass an absurd size to the allocator. 256 MiB is duplicated (not #included) to keep the Disks layer -/// free of a Storages/MergeTree dependency; the regression guard is -/// `04070_no_crash_extreme_compress_block_size` run on a content-addressed storage policy. -constexpr size_t kMaxCasWriteBufferBytes = 256ULL * 1024 * 1024; - -size_t clampCasWriteBufferSize(size_t size) -{ - /// Even an empty S3 payload writes an envelope through the sink. A zero-sized buffer cannot flush. - return std::clamp(size, 1, kMaxCasWriteBufferBytes); -} - bool hasSuffix(std::string_view s, std::string_view suffix) { return s.size() >= suffix.size() && s.substr(s.size() - suffix.size()) == suffix; @@ -126,24 +108,11 @@ namespace "content-addressed write path.", op); } -/// An eligible staged file can be embedded in the manifest up to this payload size. +/// 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 -/// Destroy the underlying reader before releasing its source. A remote seek can start a new GET. -struct StagingFileOwner -{ - std::shared_ptr source; -}; - -template -class ReaderWithStagingFile final : private StagingFileOwner, public Reader -{ -public: - template - ReaderWithStagingFile(std::shared_ptr source_, Args &&... args) - : StagingFileOwner{std::move(source_)}, Reader(std::forward(args)...) {} -}; - bool hasTopLevelFile(const std::vector & entries) { return std::any_of(entries.begin(), entries.end(), @@ -161,7 +130,7 @@ ContentAddressedTransaction::~ContentAddressedTransaction() { /// On abort this is the cleanup of local and S3 staging. After a commit it finds nothing left, /// except when the commit published some parts and then threw. - releaseStagedFiles(); + cleanupPendingTempFiles(); /// An uncommitted transaction's uploads become min_active_build_sequence-spared debris: abandon every /// still-open PartWriteTxn so its build_seq is retired. This replaces the former pin machinery. @@ -229,94 +198,68 @@ ContentAddressedTransaction::PartStaging * ContentAddressedTransaction::findStag return it == parts.end() ? nullptr : &it->second; } -namespace +void ContentAddressedTransaction::cleanupPendingTempFiles() noexcept { -void removeStagingObject(const ObjectStoragePtr & storage, const String & key) noexcept -{ - try - { - storage->removeObjectIfExists(StoredObject(key)); - } - catch (...) - { - tryLogCurrentException(getLogger("ContentAddressedTransaction"), "removing a private staging object"); - } -} -} - -ContentAddressedTransaction::StagedPartFile::~StagedPartFile() -{ - if (!owns_file) - return; - if (remote_storage) - removeStagingObject(remote_storage, staging_path); - else + for (auto & [key, st] : parts) { - std::error_code ec; - fs::remove(staging_path, ec); + for (const auto & pb : st.pending_blobs) + { + if (pb.backend == Cas::StagingBackend::Local) + { + std::error_code ec; + std::filesystem::remove(pb.staging_key, ec); + } + else + { + /// The S3 staging object is private to this transaction and nothing reads + /// `pending_blobs` after this call, so commit and abort delete it alike. An object that + /// outlived an abort would stay until the next mount of this `server_root_id`. + try + { + metadata_storage.objectStorage()->removeObjectIfExists(StoredObject(pb.staging_key)); + } + catch (...) // NOLINT(bugprone-empty-catch) + { + /// Best-effort (noexcept context): a stubborn delete leaves debris for the mount-start sweep. + } + } + } + st.pending_blobs.clear(); } } -void ContentAddressedTransaction::releaseStagedFiles() noexcept +const ContentAddressedTransaction::PartStaging::PendingBlob * +ContentAddressedTransaction::findPendingBlob(const PartStaging & st, const Cas::BlobRef & ref) const { - for (auto & [key, st] : parts) - st.staged_part_files.clear(); -} - -ContentAddressedTransaction::StagedPartFilePtr ContentAddressedTransaction::stagedFileOf(const PartStaging & st, const String & path) -{ - const auto it = st.staged_part_files.find(path); - return it == st.staged_part_files.end() ? nullptr : it->second; + /// Locate a pending blob by ref. Returns nullptr when the blob has already been uploaded + /// (post-precommit, pending_blobs is cleared) or was never staged as pending. + for (const auto & pb : st.pending_blobs) + if (pb.ref == ref) + return &pb; + return nullptr; } -void ContentAddressedTransaction::putEntry( - PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source, StagedPartFilePtr file) +void ContentAddressedTransaction::putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source) { - auto it = std::find_if(st.entries.begin(), st.entries.end(), [&](const auto & e) { return e.path == entry.path; }); - const bool inserted = it == st.entries.end(); - if (inserted) - { - st.entries.emplace_back(); - it = std::prev(st.entries.end()); - } - /// Install the possibly allocating map node before retiring the previous path or its source. - try - { - if (file) - st.staged_part_files.insert_or_assign(entry.path, file); - else if (source) - st.copy_sources.insert_or_assign(entry.path, source); - } - catch (...) - { - if (inserted) - st.entries.pop_back(); - throw; - } - if (!file) - st.staged_part_files.erase(entry.path); - if (!source) - st.copy_sources.erase(entry.path); - *it = std::move(entry); + eraseEntry(st, entry.path); + if (source) + st.copy_sources.insert_or_assign(entry.path, std::move(source)); + st.entries.push_back(std::move(entry)); } void ContentAddressedTransaction::eraseEntry(PartStaging & st, const std::string & path) { std::erase_if(st.entries, [&](const Cas::ManifestEntry & e) { return e.path == path; }); st.copy_sources.erase(path); - st.staged_part_files.erase(path); } void ContentAddressedTransaction::rekeyEntry(PartStaging & st, Cas::ManifestEntry & entry, std::string new_path) { - auto file = stagedFileOf(st, entry.path); - auto source = copySourceOf(st, entry.path); - if (file) - st.staged_part_files.emplace(new_path, std::move(file)); - if (source) - st.copy_sources.emplace(new_path, std::move(source)); - st.copy_sources.erase(entry.path); - st.staged_part_files.erase(entry.path); + if (auto node = st.copy_sources.extract(entry.path)) + { + node.key() = new_path; + st.copy_sources.insert(std::move(node)); + } entry.path = std::move(new_path); } @@ -324,8 +267,6 @@ void ContentAddressedTransaction::clearEntries(PartStaging & st) { st.entries.clear(); st.copy_sources.clear(); - st.staged_part_files.clear(); - st.has_finalized_file_write = false; } void ContentAddressedTransaction::markVacatedInBase( @@ -424,6 +365,29 @@ void ContentAddressedTransaction::retargetCopySource(const Cas::PartRefKey & fro copy_sources_by_part.try_emplace(to.cacheKey(), borrow); } +void ContentAddressedTransaction::adoptStagedBlob( + const PartStaging::PendingBlob * pb, const Cas::ManifestEntry & entry, + PartStaging & dst_st, Cas::PartWriteTxn & dst_build, bool copy_pending) +{ + if (pb) + { + /// Pending blob (not yet uploaded): no dependency exists until publication succeeds. If + /// copy_pending, push a copy of the pb record into dst_st so publishStaging uploads it + /// for the dst part too (hardlink = copy semantics). If !copy_pending, the record is already + /// in dst_st (moved by caller) — skip the push. + if (copy_pending) + dst_st.pending_blobs.push_back(*pb); + } + else + { + /// Uploaded / committed: record trusted-manifest evidence — no pool HEAD/GET before precommit. + /// §4 manifest-trust: the publish gate (promote) TRUSTS this committed-source adopted leaf via the + /// durable manifest edge — it does not observe or republish it. Pending uploads establish + /// `Materialized` through `putBlob` before promote; a genuinely absent adopted blob is an fsck finding. + dst_build.adoptEvidence(entry); + } +} + std::optional ContentAddressedTransaction::routeOf(const std::string & path) const { @@ -433,75 +397,60 @@ ContentAddressedTransaction::routeOf(const std::string & path) const return metadata_storage.route(*p); } -std::vector ContentAddressedTransaction::applyManifestInlineBudget( - PartStaging & st, uint64_t inline_bytes_from_unchanged_base_entries) const +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) { if (inline_bytes_from_unchanged_base_entries > Cas::kMaxManifestInlineBytesTotal) throw Exception(ErrorCodes::LIMIT_EXCEEDED, "Retained manifest entries contain {} inline bytes, exceeding the cap of {}", inline_bytes_from_unchanged_base_entries, Cas::kMaxManifestInlineBytesTotal); - const auto pool = metadata_storage.store(); uint64_t total_inline_bytes = inline_bytes_from_unchanged_base_entries; - std::vector candidates; + for (const auto & entry : entries_to_add_or_replace) + if (entry.placement == Cas::EntryPlacement::Inline) + total_inline_bytes += entry.inline_bytes.size(); - for (auto & entry : st.entries) - { - const auto file = stagedFileOf(st, entry.path); - if (entry.placement == Cas::EntryPlacement::Inline || (file && file->allow_inline_by_name && entry.blob_size <= INLINE_CAP)) - { + 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); - total_inline_bytes += entry.size(); - } - } - if (total_inline_bytes > Cas::kMaxManifestInlineBytesTotal) - std::sort(candidates.begin(), candidates.end(), [](const auto * lhs, const auto * rhs) - { - if (lhs->size() != rhs->size()) - return lhs->size() > rhs->size(); - return lhs->path < rhs->path; - }); + 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; - size_t spilled = 0; - for (auto * entry : candidates) { - const auto size = entry->size(); + /// 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); - if (total_inline_bytes > Cas::kMaxManifestInlineBytesTotal) - { - total_inline_bytes -= size; - ++spilled; - if (entry->placement == Cas::EntryPlacement::Inline) - { - /// A borrowed Inline has no staging file. Its bytes came from the committed manifest. - entry->ref = Cas::poolContentHash(pool->writeAlgo(), 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; - } - } - else if (entry->placement == Cas::EntryPlacement::Blob) - { - auto input = openStagedPayload(*st.staged_part_files.at(entry->path), size, pool); - String bytes(size, '\0'); - input->readStrict(bytes.data(), bytes.size()); + blob_upload_requests.push_back({entry->ref, Cas::BlobSource::fromString(std::exchange(entry->inline_bytes, {})), size}); - if (!input->eof() || Cas::poolContentHash(entry->ref.algo, bytes) != entry->ref) - throw Exception(ErrorCodes::CORRUPTED_DATA, "Staged inline payload does not match the size or hash of {}", entry->path); + entry->blob_size = size; + entry->placement = Cas::EntryPlacement::Blob; + total_inline_bytes -= size; - entry->inline_bytes = std::move(bytes); - entry->placement = Cas::EntryPlacement::Inline; - entry->blob_size = 0; - } + if (total_inline_bytes <= Cas::kMaxManifestInlineBytesTotal) + break; } - - if (spilled) - ProfileEvents::increment(ProfileEvents::CASManifestInlineEntriesSelectedForBlob, spilled); + 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) @@ -517,44 +466,81 @@ Cas::ManifestId ContentAddressedTransaction::precommitAndUpload( return id; } -std::unique_ptr ContentAddressedTransaction::openStagedPayload(const StagedPartFile & file, uint64_t size, const Cas::PoolPtr & pool) -{ - if (!file.remote_storage) - return Cas::openLocalStagedBlobPayload(file.staging_path, size); - - auto op = pool->mountRequests().admit(); - auto staged = op.stream(file.pool_staging_key, Cas::Retry::standard()); - if (!staged) - throw Exception(ErrorCodes::FILE_DOESNT_EXIST, "CAS staging object {} disappeared before publication", file.staging_path); - - const auto header_len = pool->poolMeta().blob_header_len; - String header(header_len, '\0'); - staged->readStrict(header.data(), header.size()); - const auto decoded = Cas::decodeEnvelopeHeader(header, header_len + size, Cas::ObjectKind::Blob); - - if (decoded.header_len != header_len) - throw Exception(ErrorCodes::CORRUPTED_DATA, "Unexpected envelope length {} in staging object {}", decoded.header_len, file.staging_path); - return staged; -} - -Cas::BlobSource ContentAddressedTransaction::stagedUploadSource(const StagedPartFilePtr & file, uint64_t size) const -{ - return { - .size = size, - .open = [pool = metadata_storage.store(), file, size] { return openStagedPayload(*file, size, pool); }, - .server_side_copy_from = file->remote_storage ? std::optional(file->staging_path) : std::nullopt, - .publication_attempted = std::shared_ptr>(file, &file->publication_attempted), - }; -} - 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 + /// (it is an orphan). Its temp file is still cleaned by cleanupPendingTempFiles at commit end. + std::unordered_set referenced_hashes; for (const auto & entry : st.entries) + if (entry.placement == Cas::EntryPlacement::Blob) + referenced_hashes.insert(entry.ref); + + /// 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 + /// `[envelope][payload]` object. A record and its hardlink copies in other parts share one + /// `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. + blob_upload_requests.reserve(blob_upload_requests.size() + st.pending_blobs.size()); + for (const auto & pb : st.pending_blobs) { - if (entry.placement != Cas::EntryPlacement::Blob) - continue; - if (auto file = stagedFileOf(st, entry.path)) - blob_upload_requests.push_back({entry.ref, stagedUploadSource(file, entry.blob_size), entry.blob_size}); + if (!referenced_hashes.contains(pb.ref)) + continue; /// The entry was removed by unlinkFile/replaceFile; skip this orphan. + Cas::BlobSource source; + source.size = pb.size; + source.publication_attempted = pb.publication_attempted; + if (pb.backend == Cas::StagingBackend::S3) + { + source.server_side_copy_from = pb.staging_key; + const Cas::PoolPtr store = metadata_storage.store(); + const std::string staging_key = pb.staging_key; + const uint64_t header_len = store->poolMeta().blob_header_len; + const uint64_t payload_size = pb.size; + source.open = [store, staging_key, header_len, payload_size]() -> std::unique_ptr + { + Cas::CasOperation op = store->mountRequests().admit(); + auto staged = op.stream(staging_key, Cas::Retry::standard()); + if (!staged) + throw Exception( + ErrorCodes::FILE_DOESNT_EXIST, + "CAS staging object {} disappeared before retagged blob publication", + staging_key); + + String encoded_header(header_len, '\0'); + staged->readStrict(encoded_header.data(), encoded_header.size()); + const Cas::EnvelopeHeader decoded = Cas::decodeEnvelopeHeader( + encoded_header, + header_len + payload_size, + Cas::ObjectKind::Blob); + if (decoded.header_len != header_len) + throw Exception( + ErrorCodes::CORRUPTED_DATA, + "CAS staging object {} uses envelope length {}, expected {}", + staging_key, + decoded.header_len, + header_len); + return staged; + }; + } + else + { + const std::string staging_key = pb.staging_key; + const uint64_t payload_size = pb.size; + source.open = [staging_key, payload_size]() -> std::unique_ptr + { + return Cas::openLocalStagedBlobPayload(staging_key, payload_size); + }; + } + /// `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. + blob_upload_requests.push_back(Cas::BlobUploadRequest{pb.ref, std::move(source), pb.size}); } } @@ -590,8 +576,8 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, /// 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. - /// A hardlink or move can open a build solely for the destination. Such a transfer must preserve its base. - const bool should_drop_existing_ref = existing_ref_view && st.has_finalized_file_write + /// 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); @@ -626,7 +612,7 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, } } - auto blob_upload_requests = applyManifestInlineBudget(st, inline_bytes_from_unchanged_base_entries); + 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); @@ -731,7 +717,7 @@ void ContentAddressedTransaction::commit(const TransactionCommitOptionsVariant & /// staged parts to publish and no local staging to keep; run the same idempotent epilogue a /// normal empty commit runs. committed = true; - releaseStagedFiles(); + cleanupPendingTempFiles(); force_fresh_validated_refs.clear(); return; } @@ -797,8 +783,8 @@ void ContentAddressedTransaction::commit(const TransactionCommitOptionsVariant & copy_sources_by_part.clear(); for (auto & [key, st] : parts) st.copy_sources.clear(); - /// Uploads are complete. Readers opened during the transaction can still own their staging files. - releaseStagedFiles(); + /// All pending blobs have been uploaded in publishStaging; remove their staging resources now. + cleanupPendingTempFiles(); /// This transaction's unlinkFile ForceFresh-proof memoization is scoped to this transaction only; /// clear it alongside the other per-transaction state resets above. force_fresh_validated_refs.clear(); @@ -852,8 +838,8 @@ std::optional ContentAddressedTransaction::tryGetInFlightStorageO if (entry->placement == Cas::EntryPlacement::Blob) { /// A pending blob has not been uploaded yet — its storage object does not exist in - /// the pool. Return empty so the caller reads the private staging file through tryReadFileInFlight. - if (stagedFileOf(it->second, entry->path)) + /// the pool. Return empty so the caller falls back to tryReadFileInFlight (local temp read). + if (findPendingBlob(it->second, entry->ref)) return {}; const auto location = metadata_storage.store()->locate(*entry); return StoredObjects{StoredObject(location.key, path, location.length)}; @@ -883,16 +869,30 @@ std::unique_ptr ContentAddressedTransaction::tryReadFile return std::make_unique(path, entry->inline_bytes); if (entry->placement == Cas::EntryPlacement::Blob) { - if (auto file = stagedFileOf(it->second, entry->path)) + /// A pending blob has not been uploaded yet — serve reads from the staging area (the + /// same bytes that will be promoted to the pool in publishStaging post-precommit): a local + /// temp file for `Cas::StagingBackend::Local`, or the S3 staging object for `Cas::StagingBackend::S3` + /// (`staging_key` is a remote object key there, never a + /// local path, so `ReadBufferFromFile` would misinterpret it as a filesystem path). + if (const auto * pb = findPendingBlob(it->second, entry->ref)) { - if (file->remote_storage) + if (pb->backend == Cas::StagingBackend::S3) { - const auto offset = metadata_storage.store()->poolMeta().blob_header_len; - const auto end = offset + entry->blob_size; - auto input = file->remote_storage->readObject(StoredObject(file->staging_path, path, end), settings); - return std::make_unique>(file, std::move(input), path, offset, end); + /// The staging object holds `[header][payload]` + /// (the fixed-length `blob_header_len` CABL envelope, so the promote can stay a + /// verbatim server-side copy). Read-your-writes must serve the PAYLOAD ONLY — wrap the + /// object read in a `ReadBufferFromFileView` windowed to `[header_len, header_len+size)` + /// so position 0 is the payload start, else the reader would see 256 bytes of header + /// prepended to the payload (corruption). The LOCAL staging temp file holds the payload + /// verbatim (no header), so its path is unchanged. + const uint64_t header_len = metadata_storage.store()->poolMeta().blob_header_len; + const uint64_t payload_end = header_len + pb->size; + auto impl = metadata_storage.objectStorage()->readObject( + StoredObject(pb->staging_key, path, payload_end), settings); + return std::make_unique( + std::move(impl), path, header_len, payload_end); } - return std::make_unique>(file, file->staging_path); + return std::make_unique(pb->staging_key); } return metadata_storage.readBlobPayload(metadata_storage.store()->locate(*entry), path, settings); } @@ -972,42 +972,22 @@ void ContentAddressedTransaction::createMetadataFile(const std::string &, const void ContentAddressedTransaction::stageBlobPartFile( const ContentAddressedMetadataStorage::Route & route, - const Cas::BlobRef & ref, size_t size, const std::string & staging_key, ObjectStoragePtr remote_storage, const String & pool_key) + const Cas::BlobRef & ref, size_t size, const std::string & staging_key, Cas::StagingBackend backend) { - /// Until registration succeeds the local writer still owns its file. The S3 sink has - /// already finalized its object, so release it here if registration throws. - try - { - auto file = std::make_shared(); - file->staging_path = staging_key; - file->remote_storage = remote_storage; - file->pool_staging_key = pool_key; - file->allow_inline_by_name = !Cas::partFileMustStayBlob(route.file); - - auto & st = stagingFor(route); - const bool had_build = bool(st.build); - buildFor(route, st); - - SCOPE_EXIT({ - if (!had_build && !file->owns_file) - st.build.reset(); - }); - - if (std::exchange(fail_next_file_registration, false)) - throw Exception(ErrorCodes::ABORTED, "Injected failure registering staged file {}", route.file); - - Cas::ManifestEntry entry{.path = route.file, .placement = Cas::EntryPlacement::Blob, .ref = ref, .blob_size = size, .inline_bytes = {}}; - putEntry(st, std::move(entry), nullptr, file); + /// Do not upload here. Record the pending blob for post-precommit publication; dependency state + /// remains absent until the upload succeeds and its result is merged. + /// The staging bytes are kept (the transaction owns them) — a local temp file for + /// `Cas::StagingBackend::Local`, or an S3 staging object for `Cas::StagingBackend::S3`. + auto & st = stagingFor(route); + st.pending_blobs.push_back({ref, staging_key, size, backend}); + (void)buildFor(route, st); - file->owns_file = true; - st.has_finalized_file_write = true; - } - catch (...) - { - if (remote_storage) - removeStagingObject(remote_storage, staging_key); - throw; - } + Cas::ManifestEntry entry; + entry.path = route.file; + entry.placement = Cas::EntryPlacement::Blob; + entry.ref = ref; + entry.blob_size = size; + putEntry(st, std::move(entry), nullptr); } void ContentAddressedTransaction::stageUnprovenBlobEntryForTest(const std::string & path, const Cas::BlobRef & ref, uint64_t size) @@ -1064,7 +1044,6 @@ std::unique_ptr ContentAddressedTransaction::tryCreateW const std::string & path, size_t buf_size, WriteMode mode, const WriteSettings & settings, bool autocommit) { - buf_size = Cas::clampCasWriteBufferSize(buf_size); /// This transaction owns the write because the blob key is known only after hashing the payload. /// Append is serviceable (read-modify-rewrite) only for a non-part / table-level verbatim file /// (handled inside writeFile). A part file is a content blob or a whole-rewritten inline entry, so @@ -1160,9 +1139,18 @@ std::unique_ptr ContentAddressedTransaction::writeFile( throw Exception(ErrorCodes::NOT_IMPLEMENTED, "ContentAddressedTransaction::writeFile: not a part file path: {}", path); + /// The former + /// mutable-per-part-file branch (uuid.txt/metadata_version.txt/txn_version.txt staging directly + /// into a separate mutable payload) is DELETED here — these three names fall through to the + /// ordinary content path below like any other tree file. There is no filename left to special-case: + /// `kMutablePerPartFiles`/`isMutablePerPartFile` predicate itself is gone too — there is no + /// 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. + + const bool must_stay_blob = Cas::partFileMustStayBlob(r->file); const auto hash_algo = metadata_storage.store()->writeAlgo(); - const auto remote_storage = metadata_storage.stagingBackend() == Cas::StagingBackend::S3 ? metadata_storage.objectStorage() : nullptr; - if (remote_storage) + + if (must_stay_blob && 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 @@ -1177,14 +1165,9 @@ std::unique_ptr ContentAddressedTransaction::writeFile( /// 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 auto leaf = getRandomASCIIString(32) + ".tmp"; - const auto pool_key = pool->layout().stagingKey(metadata_storage.serverRootId(), incarnation.writer_epoch, leaf); - const auto staging_key = metadata_storage.stagingKey(incarnation.writer_epoch, leaf); + const std::string staging_key = metadata_storage.stagingKey(incarnation.writer_epoch, getRandomASCIIString(32) + ".tmp"); - auto staging_settings = settings; - staging_settings.adaptive_write_buffer_initial_size = Cas::clampCasWriteBufferSize(settings.adaptive_write_buffer_initial_size); - auto object_sink = remote_storage->writeObject( - StoredObject(staging_key), WriteMode::Rewrite, {}, Cas::clampCasWriteBufferSize(buf_size), staging_settings); + auto object_sink = metadata_storage.objectStorage()->writeObject(StoredObject(staging_key), WriteMode::Rewrite); return std::make_unique( std::move(object_sink), @@ -1194,20 +1177,52 @@ std::unique_ptr ContentAddressedTransaction::writeFile( buf_size, settings.use_adaptive_write_buffer, settings.adaptive_write_buffer_initial_size, - [this, route = *r, hash_algo, remote_storage, pool_key](const String & hash, size_t size, const String & key) + [this, route = *r, hash_algo](const std::string & hash_hex, size_t size, const std::string & key) { - stageBlobPartFile(route, {hash_algo, Cas::codecFor(hash_algo).fromHex(hash)}, size, key, remote_storage, pool_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); }); } - return std::make_unique( - metadata_storage.scratchPath(), hash_algo, buf_size, settings.use_adaptive_write_buffer, - settings.adaptive_write_buffer_initial_size, - [this, route = *r, hash_algo](const String & hash, size_t size, const String & key) + /// 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); + }); + }; + + if (must_stay_blob) + return create_local_blob_writer(); + + return std::make_unique( + path, INLINE_CAP, /*create_blob_if_empty=*/false, std::move(create_local_blob_writer), + [this, route = std::move(*r), hash_algo](FinalizeResult result) { - stageBlobPartFile(route, {hash_algo, Cas::codecFor(hash_algo).fromHex(hash)}, size, key, nullptr, {}); - }); + 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); + entry.inline_bytes = std::move(inlined->data); + putEntry(st, std::move(entry), nullptr); + }, + buf_size); } void ContentAddressedTransaction::createDirectory(const std::string &) @@ -1399,13 +1414,23 @@ void ContentAddressedTransaction::createHardLink(const std::string & path_from, if (it != src_st->entries.end()) { entry = *it; - auto file = stagedFileOf(*src_st, src->file); - auto source = copySourceOf(*src_st, src->file); - auto & build = buildFor(*dst, dst_st); - if (!file) - build.adoptEvidence(entry); + /// A copy of an adopted entry confirms the committed part the entry came from. + std::shared_ptr source; + if (entry.placement == Cas::EntryPlacement::Blob) + { + /// Unified adopt dispatch. copy_pending=(&dst_st != src_st) so the pending + /// blob record is copied into dst_st only when the destination is a different part + /// (hardlink = copy semantics; same-part is a self-ref that shouldn't duplicate the record). + const auto * pb = findPendingBlob(*src_st, entry.ref); + if (!pb) + source = copySourceOf(*src_st, src->file); + adoptStagedBlob(pb, entry, dst_st, buildFor(*dst, dst_st), /*copy_pending=*/(&dst_st != src_st)); + } + else if (entry.placement != Cas::EntryPlacement::Inline) + throw Exception(ErrorCodes::LOGICAL_ERROR, + "ContentAddressed: staged hardlink of unsupported placement for {}", path_from); entry.path = dst->file; - putEntry(dst_st, std::move(entry), std::move(source), std::move(file)); + putEntry(dst_st, std::move(entry), std::move(source)); return; } } @@ -1572,49 +1597,40 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c /// The committed manifest the source staging was based on (a rename of a committed part with /// staged edits, e.g. a rollback's `delete_tmp_`); the re-key below drops it from the overlay. std::optional staged_source_base; - bool replacing_source_segments = false; if (auto src_it = parts.find(src_key); src_it != parts.end()) { had_staged_source = true; PartStaging & dst_st = parts[dst_key]; PartStaging & src_st = src_it->second; staged_source_base = src_st.base_manifest_ref; - replacing_source_segments = src_st.has_finalized_file_write && hasTopLevelFile(src_st.entries); - /// A written file still has provisional Blob placement. A borrowed Inline can - /// represent the same bytes, so compare its payload to the staged file's full hash. - /// Check every collision before moving ownership out of the source. - for (const auto & entry : src_st.entries) - { - const auto existing = std::find_if(dst_st.entries.begin(), dst_st.entries.end(), - [&](const Cas::ManifestEntry & other) { return other.path == entry.path; }); - if (existing == dst_st.entries.end() || *existing == entry) - continue; - if (existing->placement != entry.placement && existing->size() == entry.size()) - { - const bool source_is_blob = entry.placement == Cas::EntryPlacement::Blob; - const auto & blob = source_is_blob ? entry : *existing; - const auto & inlined = source_is_blob ? *existing : entry; - const auto staged = stagedFileOf(source_is_blob ? src_st : dst_st, blob.path); - if (staged && staged->allow_inline_by_name && blob.blob_size <= INLINE_CAP - && Cas::poolContentHash(blob.ref.algo, inlined.inline_bytes) == blob.ref) - continue; - } - throw Exception(ErrorCodes::LOGICAL_ERROR, - "ContentAddressed: moveDirectory file collision on '{}' ({} -> {}): " - "source and destination staged different entries for the same file", - entry.path, src->ref, dst->ref); - } for (auto & entry : src_st.entries) { + /// A genuine collision (both src and dst independently + /// staged DIFFERING bytes for the SAME path) is a fail-loud LOGICAL_ERROR rather than a + /// silent lost-update — the same defensive rule this loop used to apply only to the + /// three legacy mutable names now applies uniformly to every entry (that scoping was + /// itself a leftover of the mutable-file/entry split; there is only one kind of staged + /// file left). Identical bytes are a benign idempotent re-key; distinct paths are the + /// ordinary source-wins merge (a genuine collision is not expected in normal operation + /// — only some future op-order re-keying the same file under both stagings). + if (const auto existing = std::find_if(dst_st.entries.begin(), dst_st.entries.end(), + [&](const Cas::ManifestEntry & e) { return e.path == entry.path; }); + existing != dst_st.entries.end() && !(*existing == entry)) + throw Exception(ErrorCodes::LOGICAL_ERROR, + "ContentAddressed: moveDirectory file collision on '{}' ({} -> {}): " + "source and destination staged different bytes for the same file", + entry.path, src->ref, dst->ref); auto source = copySourceOf(src_st, entry.path); - auto file = stagedFileOf(src_st, entry.path); - putEntry(dst_st, std::move(entry), std::move(source), std::move(file)); + putEntry(dst_st, std::move(entry), std::move(source)); } /// Carry any staged removal marks forward too — a re-key of the /// staging key must not silently drop them. for (const auto & file : src_st.content_removed) dst_st.content_removed.insert(file); - dst_st.has_finalized_file_write |= src_st.has_finalized_file_write; + /// Move pending blobs from src to dst — they will be uploaded in dst's publishStaging. + for (auto & pb : src_st.pending_blobs) + dst_st.pending_blobs.push_back(std::move(pb)); + src_st.pending_blobs.clear(); if (!dst_st.build) { dst_st.build = std::move(src_st.build); @@ -1626,14 +1642,18 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c /// time is unnecessary - entries staged via putBlob/adopt carry deps in the SOURCE /// build... merge conservatively by abandoning nothing and re-observing): for (const auto & entry : dst_st.entries) - if (entry.placement == Cas::EntryPlacement::Blob && !stagedFileOf(dst_st, entry.path)) - dst_st.build->adoptEvidence(entry); + if (entry.placement == Cas::EntryPlacement::Blob) + { + /// Unified adopt dispatch. Pending blob records were already moved + /// to dst_st.pending_blobs above (MOVE semantics), so copy_pending=false. + adoptStagedBlob(findPendingBlob(dst_st, entry.ref), entry, dst_st, *dst_st.build, /*copy_pending=*/false); + } src_st.build->abandon(); } parts.erase(src_it); /// A freshly-written part finalized tmp->final is re-keyed in the - /// overlay above (entries, removal marks, staging sources and build moved src->dst). The durable publish + /// overlay above (entries/marks/pending blobs/build moved src->dst). The durable publish /// happens only in this transaction's commit (the existing publishStaging loop), not in /// this method. `MergeTree` commits a part right after `finalize` and renames it afterwards, /// so this re-key serves a rename staged before any commit. No early-published ref to @@ -1657,7 +1677,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 && (!replacing_source_segments || hasTopLevelFile(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 +1685,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 && (!replacing_source_segments || hasTopLevelFile(base_entries))) + if (ours && hasTopLevelFile(base_entries)) { const auto renamed = metadata_storage.partAccess()->renameCommittedRef(src->refKey(), dst->refKey(), committed_ref); if (!renamed) @@ -1789,21 +1809,28 @@ void ContentAddressedTransaction::moveFile(const std::string & path_from, const [&](const Cas::ManifestEntry & e) { return e.path == src->file; }); if (it != src_st.entries.end()) { - if (&src_st == &dst_st && src->file == dst->file) - return; auto entry = *it; auto source = copySourceOf(src_st, src->file); - auto file = stagedFileOf(src_st, src->file); - if (&src_st != &dst_st) - { - auto & build = buildFor(*dst, dst_st); - if (!file) - build.adoptEvidence(entry); - } - entry.path = dst->file; markVacatedInBase(*src, src_st, {src->file}); - putEntry(dst_st, std::move(entry), std::move(source), std::move(file)); eraseEntry(src_st, src->file); + entry.path = dst->file; + if (&src_st != &dst_st && entry.placement == Cas::EntryPlacement::Blob) + { + /// The record of a pending upload follows the entry. A hardlink left in the source still names the blob, + /// so the source keeps a copy: each part publishes every body it names, and may publish first. + auto pb_it = std::find_if(src_st.pending_blobs.begin(), src_st.pending_blobs.end(), + [&](const PartStaging::PendingBlob & pb) { return pb.ref == entry.ref; }); + if (pb_it != src_st.pending_blobs.end()) + { + const bool still_named_in_source = std::any_of(src_st.entries.begin(), src_st.entries.end(), + [&](const Cas::ManifestEntry & e) { return e.placement == Cas::EntryPlacement::Blob && e.ref == entry.ref; }); + dst_st.pending_blobs.push_back(*pb_it); + if (!still_named_in_source) + src_st.pending_blobs.erase(pb_it); + } + adoptStagedBlob(findPendingBlob(dst_st, entry.ref), entry, dst_st, buildFor(*dst, dst_st), /*copy_pending=*/false); + } + putEntry(dst_st, std::move(entry), std::move(source)); return; } /// Source not staged in this transaction: this would cover a standalone one-shot rename of a @@ -1818,6 +1845,17 @@ void ContentAddressedTransaction::replaceFile(const std::string & path_from, con { /// Write gate (rev.7 §1): refuse before dropping staged destination state on a Vanished/uncertain disk. metadata_storage.checkOpAdmitted(CasOpClass::Write); + /// replaceFile = moveFile that overwrites the destination. Drop any staged destination state + /// first, then delegate (the verbatim branch's putNamespaceFile already overwrites). + if (auto dst = routeOf(path_to); dst && !dst->file.empty()) + { + auto & dst_st = stagingFor(*dst); + /// A matching pending_blobs record (if any) is left in place — its temp file is cleaned by + /// cleanupPendingTempFiles at commit end, and the orphaned record is filtered out of the + /// publish upload by the staged-tree-hash check in publishStaging. We do NOT purge it + /// eagerly because the same hash may still be referenced by another staged entry. + eraseEntry(dst_st, dst->file); + } moveFile(path_from, path_to); } @@ -1854,6 +1892,10 @@ void ContentAddressedTransaction::unlinkFile(const std::string & path, bool if_e auto & st = stagingFor(*r); const bool staged_here = std::any_of(st.entries.begin(), st.entries.end(), [&](const Cas::ManifestEntry & e) { return e.path == r->file; }); + /// A matching pending_blobs record (if any) is left in place — its temp file is cleaned by + /// cleanupPendingTempFiles at commit end, and the orphaned record is filtered out of the + /// publish upload by the staged-tree-hash check in publishStaging. We do NOT purge it + /// eagerly because the same hash may still be referenced by another staged entry. if (staged_here) markVacatedInBase(*r, st, {r->file}); eraseEntry(st, r->file); @@ -1929,6 +1971,26 @@ void ContentAddressedTransaction::truncateFile(const std::string &, size_t) namespace DB::Cas { +namespace +{ +/// Ceiling for a CAS write-buffer allocation. An extreme `max_compress_block_size` (or any other +/// out-of-range buffer-size setting -- fuzzed or misconfigured) flows into `writeFile`'s `buf_size` / +/// `adaptive_write_buffer_initial_size` and, unclamped, reaches `Memory::alloc` where the allocator's +/// `checkSize` (>= 0x8000000000000000) fires a `LOGICAL_ERROR` and aborts the server in +/// debug/sanitizer builds. The ordinary MergeTree writers clamp compress-block sizes to 256 MiB +/// (`MergeTreeWriterSettings::MAX_COMPRESS_BLOCK_SIZE`) for exactly this reason; the CAS write path +/// received the value unclamped. Mirror that ceiling here, at the allocation site, so no caller can +/// pass an absurd size to the allocator. 256 MiB is duplicated (not #included) to keep the Disks layer +/// free of a Storages/MergeTree dependency; the regression guard is +/// `04070_no_crash_extreme_compress_block_size` run on a content-addressed storage policy. +constexpr size_t kMaxCasWriteBufferBytes = 256ULL * 1024 * 1024; + +size_t clampCasWriteBufferSize(size_t size) +{ + return std::min(size, kMaxCasWriteBufferBytes); +} +} + void fanOutBlobUploads( PartWriteTxn & build, std::span requests, diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index 06666d0325c77..688da91806c77 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -33,8 +33,10 @@ 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. /// -/// File writers stream to private staging. Commit chooses placement using the final paths and -/// sizes. Open readers and uploads can retain a staging file beyond the transaction lifetime. +/// 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 { public: @@ -84,7 +86,8 @@ class ContentAddressedTransaction : public IMetadataTransaction const std::string & path, size_t buf_size, WriteMode mode, const WriteSettings & settings, bool autocommit) override; - /// Creates a streaming staging writer for a part file. Its payload is hashed as it is written, 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, @@ -124,7 +127,6 @@ class ContentAddressedTransaction : public IMetadataTransaction /// Test-only: stages the part file `path` as a blob entry naming `ref` with no pending upload and no copy /// source, a shape no operation produces. void stageUnprovenBlobEntryForTest(const std::string & path, const Cas::BlobRef & ref, uint64_t size); - void failNextFileRegistrationForTest() { fail_next_file_registration = true; } /// Test-only: the copy source shared by this transaction's borrows from the committed part `part_path`, or null. std::shared_ptr borrowedSourceForTest(const std::string & part_path) const; @@ -135,22 +137,9 @@ class ContentAddressedTransaction : public IMetadataTransaction ContentAddressedMetadataStorage & metadata_storage; private: - /// The local file or private S3 object of one successful write. Paths and readers can - /// share it across renames, replacement and transaction teardown. - struct StagedPartFile - { - String staging_path; /// Local filesystem path or the S3 key used by IObjectStorage. - ObjectStoragePtr remote_storage; - String pool_staging_key; /// Pool-relative address for reads through the request engine. - bool allow_inline_by_name = false; /// Set from the original write path, before any hardlink or rename. - bool owns_file = false; - mutable std::atomic publication_attempted{false}; - - ~StagedPartFile(); - }; - using StagedPartFilePtr = std::shared_ptr; - - /// State for one routed part. The build records its manifest dependencies at publication. + /// State for one routed part. The build is opened lazily at the first staged write so every + /// manifest dependency is recorded by the same `Cas::PartWriteTxn`; pending blobs remain in + /// staging until publication. struct PartStaging { /// Created lazily when a staged blob, inline entry, or adopted entry first needs publication. @@ -174,9 +163,21 @@ class ContentAddressedTransaction : public IMetadataTransaction bool published = false; /// set by publishStaging during commit(); the commit /// loop is idempotent (never re-publishes a staging). - /// Each newly written path and its hardlinks retain the original staging source. - std::map staged_part_files; - bool has_finalized_file_write = false; /// A build opened only for a transfer cannot replace the temporary segment ref. + /// `staging_key` is either a private local temp path or an S3 staging object key returned by + /// `CaContentWriteBuffer` at finalize. The backend selects the read-your-writes source; both + /// kinds are removed by this transaction on commit and on abort. + struct PendingBlob + { + Cas::BlobRef ref; + std::string staging_key; + uint64_t size = 0; + Cas::StagingBackend backend = Cas::StagingBackend::Local; + /// The once-only verbatim-copy privilege of the staging object. A hardlink copies this + /// record into another part, and the copy shares the flag, so the parts together copy + /// the staged envelope at most once. + std::shared_ptr> publication_attempted = std::make_shared>(false); + }; + std::vector pending_blobs; /// Staged blobs uploaded after the manifest edge is precommitted. }; /// Keyed by (namespace string, ref name) — the routed identity, so live/detached/shadow @@ -187,7 +188,6 @@ class ContentAddressedTransaction : public IMetadataTransaction std::unordered_map> copy_sources_by_part; bool committed = false; bool failed = false; - bool fail_next_file_registration = false; /// Memoizes, per (this transaction, ref), whether `unlinkFile` has already resolved a committed /// ref `ForceFresh`. The MergeTree fast-removal path unlinks every file of a part through ONE @@ -198,10 +198,11 @@ class ContentAddressedTransaction : public IMetadataTransaction /// Stage a content part file as a blob without recording a dependency proof, and add/replace its /// manifest entry. Successful post-precommit publication later records `Materialized`. Shared by - /// writers on both staging backends. + /// the streaming-blob path + /// (Local or S3-staging, `backend` says which) and the always-Local inline-cap fallback. void stageBlobPartFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::string & staging_key, - ObjectStoragePtr remote_storage, const String & pool_key); + Cas::StagingBackend backend); /// Builds the fixed-length CABL envelope header for a staging blob, with a fresh `incarnation_tag`, /// so the S3 staging object holds `[header][payload]` and the promote @@ -209,8 +210,8 @@ class ContentAddressedTransaction : public IMetadataTransaction std::string buildS3StagingBlobHeader(const ContentAddressedMetadataStorage::Route & route) const; /// Replaces the staged entry at `entry.path`; `source` is its committed source when it was adopted from - /// another part without its bytes, and null when this transaction owns the bytes. - static void putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source, StagedPartFilePtr file = {}); + /// another part without its bytes, and nullopt when this transaction uploads or inlines the bytes. + static void putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source); static void eraseEntry(PartStaging & st, const std::string & path); /// Renames `entry`, an element of `st.entries`, in place; `new_path` must not be staged. static void rekeyEntry(PartStaging & st, Cas::ManifestEntry & entry, std::string new_path); @@ -236,21 +237,17 @@ class ContentAddressedTransaction : public IMetadataTransaction PartStaging * findStaging(const ContentAddressedMetadataStorage::Route & r); /// Finds the staged manifest entry for a routed file without consulting committed storage. const Cas::ManifestEntry * findStagedEntry(const ContentAddressedMetadataStorage::Route & r) const; - - static StagedPartFilePtr stagedFileOf(const PartStaging & st, const String & path); - - static std::unique_ptr openStagedPayload(const StagedPartFile & file, uint64_t size, const Cas::PoolPtr & pool); - - Cas::BlobSource stagedUploadSource(const StagedPartFilePtr & file, uint64_t size) const; - - std::vector applyManifestInlineBudget(PartStaging & st, uint64_t inline_bytes_from_unchanged_base_entries) const; + /// Returns the pending (staged but not yet uploaded) blob for `ref`, or nullptr when it has + /// already been uploaded or was never staged. + const PartStaging::PendingBlob * findPendingBlob(const PartStaging & st, const Cas::BlobRef & ref) const; /// Returns the part build, creating it lazily with the routed ref as its intended destination. Cas::PartWriteTxn & buildFor(const ContentAddressedMetadataStorage::Route & r, PartStaging & st); /// Parses a disk path and maps a part-file path to its namespace/ref/file route. std::optional routeOf(const std::string & path) const; - /// Release this transaction's ownership. Readers and pending uploads retain their own handles. - void releaseStagedFiles() noexcept; + /// Removes the transaction's staging after commit or abort: local files and S3 staging objects + /// alike. S3 deletes are best-effort; a lost delete leaves debris for the mount-start sweep. + void cleanupPendingTempFiles() noexcept; /// 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; @@ -259,6 +256,21 @@ class ContentAddressedTransaction : public IMetadataTransaction Cas::ManifestId precommitAndUpload(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, 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 + /// has already been moved by the caller; no dependency exists until its upload succeeds. For + /// an uploaded or committed blob, the destination records trusted-manifest evidence and does not + /// perform a pool read before precommit. + /// + /// `pb != nullptr` (pending, not yet uploaded): + /// - `copy_pending=true` → push a copy of *pb into dst_st.pending_blobs (hardlink semantics: + /// both src and dst upload independently; src's copy is left in place by the caller). + /// - `copy_pending=false` → the pb record is already in dst_st (moved or already there). + /// In both cases the later successful upload records `Materialized` in the destination build. + /// + void adoptStagedBlob(const PartStaging::PendingBlob * pb, const Cas::ManifestEntry & entry, + PartStaging & dst_st, Cas::PartWriteTxn & dst_build, bool copy_pending); + /// Publishes one staged part, either by promoting a newly staged manifest or by repointing an /// existing ref after carrying its unchanged entries forward. It is idempotent within the commit /// loop and marks the staging as published. Writes the exact `Cas::CommitOutcome` into `out_slot` diff --git a/src/Disks/tests/gtest_ca_wiring.cpp b/src/Disks/tests/gtest_ca_wiring.cpp index 6381e42024f71..e619a7cf6d50f 100644 --- a/src/Disks/tests/gtest_ca_wiring.cpp +++ b/src/Disks/tests/gtest_ca_wiring.cpp @@ -1624,7 +1624,7 @@ TEST(CASWiringInFlight, StagedFilesVisibleBeforeCommit) EXPECT_EQ(tx->tryGetInFlightFileSize("a11/a11a11a1-1111-4111-8111-111111111111/tmp_mut_all_1_1_0/uuid.txt"), std::optional(3)); EXPECT_FALSE(tx->tryGetInFlightFileSize("a11/a11a11a1-1111-4111-8111-111111111111/tmp_mut_all_1_1_0/missing.bin").has_value()); - /// Both pending files are readable from staging before their final placement is chosen. + /// Bytes read back: a pending blob from the local temp file (B188); staged mutable bytes from memory. { auto buf = tx->tryReadFileInFlight("a11/a11a11a1-1111-4111-8111-111111111111/tmp_mut_all_1_1_0/p.proj/data.bin", {}, std::nullopt); ASSERT_TRUE(buf); @@ -1768,47 +1768,6 @@ TEST(CASWiringGc, DisplacedTreeBlobsReclaimedThroughRealPath) << "not just recognized as unreachable; unreachable=" << after.unreachable; } -TEST(CASWiringGc, SharedBlobRemainsReadableAfterFailedMergeScratchIsReclaimed) -{ - auto storage = openWiringStorage(); - const String table = "a11/a11a11a1-1111-4111-8111-111111111111/"; - const String original = table + "all_1_1_0/data.bin"; - const String output = table + "tmp_merge_all_1_2_1"; - auto input = storage->createTransaction(); - writeThroughTransaction(*input, original, "shared"); - input->commit(DB::NoCommitOptions{}); - - auto segments = storage->createTransaction(); - writeThroughTransaction(*segments, output + "/text_index_tmp/shared.bin", "shared"); - writeThroughTransaction(*segments, output + "/text_index_tmp/unique.bin", "only scratch owns this"); - segments->commit(DB::NoCommitOptions{}); - const auto live_key = storage->getStorageObjects(original).at(0).remote_path; - ASSERT_EQ(live_key, storage->getStorageObjects(output + "/text_index_tmp/shared.bin").at(0).remote_path); - const auto dead_key = storage->getStorageObjects(output + "/text_index_tmp/unique.bin").at(0).remote_path; - ASSERT_FALSE(live_key.empty()); - ASSERT_NE(live_key, dead_key); - DB::Cas::tests::OperationForTest op(*storage->store()->poolBackendPtr()); - ASSERT_TRUE((*op).head(dead_key, Retry::standard())); - - { - auto failed_merge = storage->createTransaction(); - writeThroughTransaction(*failed_merge, output + "/data.bin", "unfinished output"); - } - auto cleanup = storage->createTransaction(); - cleanup->removeDirectory(output); - cleanup->commit(DB::NoCommitOptions{}); - - for (size_t i = 0; i < 8 && (*op).head(dead_key, Retry::standard()); ++i) - storage->runOneGcRoundForTest(); - ASSERT_FALSE((*op).head(dead_key, Retry::standard())); - const auto object = storage->getStorageObjects(original).at(0); - auto reader = storage->readBlobPayload({object.remote_path, storage->store()->poolMeta().blob_header_len, object.bytes_size}, - original, DB::ReadSettings{}); - String actual; - DB::readStringUntilEOF(actual, *reader); - EXPECT_EQ(actual, "shared"); -} - /// ==== The DataPartsExchange facade (manifest relink, part_manifest_v2) ==== /// Publish-then-confirm (Task 14) split the receiver's adoption into `prepare` + `promote`, with the @@ -2557,27 +2516,6 @@ int firstPrecommitWriteIdx(const std::vectorgetCommonKeyPrefix()) / "scratch"); - auto storage = std::make_shared(recording, "pool", "srv1", "", nullptr, settings); - storage->startup(); - recording->ops.clear(); - - const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/count.txt"; - auto tx = storage->createTransaction(); - writeThroughTransaction(*tx, path, "42"); - EXPECT_FALSE(std::filesystem::is_empty(storage->scratchPath())); - tx->commit(DB::NoCommitOptions{}); - - EXPECT_GE(firstPrecommitWriteIdx(recording->ops), 0); - for (const auto & op : recording->ops) - EXPECT_EQ(op.key.find("/blobs/"), String::npos) << op.op << " " << op.key; - EXPECT_EQ(storage->tryGetInManifestBytes(path), "42"); -} - /// B188: every pool op (read OR write) on /blobs/ or /trees/ must come AFTER the first write that /// appends the create-precommit owner event (the first root-shard CAS) — including HEAD /// (exists/getObjectMetadata) and GET (readObject), since the @@ -2772,52 +2710,6 @@ TEST(CASWiringPrecommitOrder, CommittedSourceAdoptNoHeadBeforePrecommit) /// (the cross-part pending-source branch: `&dst_st != src_st`, copies the PendingBlob record so /// publishStaging uploads it for the dst part too). After commit both parts must read back the /// identical content. -TEST(CASWiringInFlight, OpenLocalReaderRetainsFileThroughCommitOrAbort) -{ - for (bool commit : {false, true}) - { - SCOPED_TRACE(commit); - auto storage = openWiringStorage(); - auto tx = storage->createTransaction(); - const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/data.bin"; - writeThroughTransaction(*tx, path, "staged"); - auto reader = tx->tryReadFileInFlight(path, {}, {}); - ASSERT_TRUE(reader); - const auto staging_path = reader->getFileName(); - if (commit) - tx->commit(DB::NoCommitOptions{}); - tx.reset(); - ASSERT_TRUE(std::filesystem::exists(staging_path)); - reader->seek(5, SEEK_SET); - char byte; - reader->readStrict(&byte, 1); - EXPECT_EQ(byte, 'd'); - reader.reset(); - EXPECT_FALSE(std::filesystem::exists(staging_path)); - } -} - -TEST(CASWiringPending, SingleByteTransferCanPublishANewPart) -{ - for (const bool move : {false, true}) - { - SCOPED_TRACE(move); - auto storage = openWiringStorage(); - const String dir = "a11/a11a11a1-1111-4111-8111-111111111111/"; - const String src = dir + "all_2_2_0/a.txt"; - const String dst = dir + "all_1_1_0/b.txt"; - auto tx = storage->createTransaction(); - writeThroughTransaction(*tx, src, "x"); - if (move) - tx->moveFile(src, dst); - else - tx->createHardLink(src, dst); - tx->commit(DB::NoCommitOptions{}); - EXPECT_EQ(storage->tryGetInManifestBytes(dst), "x"); - EXPECT_EQ(storage->existsFile(src), !move); - } -} - TEST(CASWiringPending, HardlinkOfPendingBlobCommitsAndReadsBack) { auto storage = openWiringStorage(); diff --git a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp index 1cbeef7bfc50d..d0eb7cc105e83 100644 --- a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -11,14 +11,12 @@ #include #include -#include #include #include namespace DB::ErrorCodes { extern const int INCORRECT_DATA; - extern const int LIMIT_EXCEEDED; } /// A part or a nested scratch storage whose small files sum past the manifest's inline budget must @@ -697,233 +695,3 @@ TEST(CASInlineCandidateMemory, ThresholdPreservesPlacementAndPayload) EXPECT_TRUE(storage->tryGetInManifestBytes(dir + "at.idx") == at_limit); expectBlob(*storage, ref, "over.idx", over_limit); } - -TEST(CASInlineCandidateMemory, ClosedCandidatesStayInStagingUntilPlacement) -{ - auto storage = openStorage(); - const std::string ref = "all_1_1_0"; - const std::string dir = table_dir + ref + "/"; - const std::string bytes = payload(600 * kib, 7); - auto tx = storage->createTransaction(); - const auto retained = std::async(std::launch::async, [&] - { - MemoryTracker tracker(&total_memory_tracker, VariableContext::Process, false); - DB::ThreadStatus thread_status; - thread_status.memory_tracker.setParent(&tracker); - thread_status.untracked_memory_limit = 0; - for (size_t i = 0; i < 64; ++i) - writeFileTx(*tx, dir + std::to_string(i) + ".idx", bytes); - return tracker.get(); - }).get(); -#if !defined(SANITIZER) - /// The closed payloads total 37.5 MiB. Only path metadata should remain on the writer thread. - EXPECT_LT(retained, static_cast(inline_total_budget)); -#endif - ::testing::Test::RecordProperty("retained_bytes_before_commit", std::to_string(retained)); - - size_t staged_bytes = 0; - for (const auto & file : std::filesystem::directory_iterator(storage->scratchPath())) - staged_bytes += file.file_size(); - EXPECT_EQ(staged_bytes, 64 * bytes.size()); - tx->commit(DB::NoCommitOptions{}); - const auto manifest = manifestOf(*storage, uuid, ref); - ASSERT_EQ(manifest.entries.size(), 64u); - EXPECT_EQ(inlineTotal(manifest), (inline_total_budget / bytes.size()) * bytes.size()); - for (const auto & entry : manifest.entries) - EXPECT_TRUE(readPartFile(*storage, dir + entry.path) == bytes) << entry.path; - EXPECT_TRUE(std::filesystem::is_empty(storage->scratchPath())); -} - -TEST(CASInlineCapGaps, StagedAliasesKeepTheirSourceAndOriginalPlacementEligibility) -{ - auto storage = openStorage(); - const auto src = table_dir + "all_1_1_0/"; - const auto dst = table_dir + "all_2_2_0/"; - auto tx = storage->createTransaction(); - writeFileTx(*tx, src + "a.txt", "x"); - writeFileTx(*tx, src + "a.bin", "x"); - tx->createHardLink(src + "a.txt", dst + "copied.bin"); - tx->moveFile(src + "a.bin", dst + "moved.txt"); - writeFileTx(*tx, src + "a.txt", "replacement"); - tx->commit(DB::NoCommitOptions{}); - EXPECT_EQ(storage->tryGetInManifestBytes(dst + "copied.bin"), "x"); - expectBlob(*storage, "all_2_2_0", "moved.txt", "x"); - EXPECT_FALSE(storage->existsFile(src + "a.bin")); - EXPECT_EQ(storage->tryGetInManifestBytes(src + "a.txt"), "replacement"); -} - -TEST(CASInlineCapGaps, TransferAlonePreservesNestedBaseButOwnWriteReplacesIt) -{ - for (const bool write_first : {false, true}) - { - for (const bool own_write : {false, true}) - { - SCOPED_TRACE(write_first); - SCOPED_TRACE(own_write); - auto storage = openStorage(); - const auto src = table_dir + "all_1_1_0/"; - const auto dst = table_dir + "tmp_merge_all_1_2_1/"; - auto tx = storage->createTransaction(); - writeFileTx(*tx, dst + "text_index_tmp/0.idx", "base"); - tx->commit(DB::NoCommitOptions{}); - - tx = storage->createTransaction(); - writeFileTx(*tx, src + "pending.idx", "m"); - if (own_write && write_first) - writeFileTx(*tx, dst + "own.idx", "w"); - tx->moveFile(src + "pending.idx", dst + "moved.idx"); - if (own_write && !write_first) - writeFileTx(*tx, dst + "own.idx", "w"); - tx->commit(DB::NoCommitOptions{}); - - EXPECT_EQ(storage->tryGetInManifestBytes(dst + "moved.idx"), "m"); - EXPECT_FALSE(storage->existsFile(src + "pending.idx")); - EXPECT_EQ(storage->existsFile(dst + "text_index_tmp/0.idx"), !own_write); - } - } -} - -TEST(CASInlineCapGaps, ReusingRemovedPartNameDoesNotAllowReplacingAnotherWritersSegments) -{ - auto storage = openStorage(); - const auto dir = table_dir + "tmp_merge_all_1_2_1"; - auto tx = storage->createTransaction(); - writeFileTx(*tx, dir + "/discarded.txt", "old"); - tx->removeDirectory(dir); - auto segments = storage->createTransaction(); - writeFileTx(*segments, dir + "/text_index_tmp/0.idx", "segment"); - segments->commit(DB::NoCommitOptions{}); - - writeFileTx(*tx, table_dir + "all_1_1_0/moved.txt", "new"); - tx->moveFile(table_dir + "all_1_1_0/moved.txt", dir + "/moved.txt"); - EXPECT_THROW(tx->commit(DB::NoCommitOptions{}), DB::Exception); - EXPECT_EQ(storage->tryGetInManifestBytes(dir + "/text_index_tmp/0.idx"), "segment"); - EXPECT_FALSE(storage->existsFile(dir + "/moved.txt")); -} - -TEST(CASInlineCapGaps, RenamingStagedDirectoryAcceptsIdenticalBorrowedInline) -{ - auto storage = openStorage(); - const auto src = table_dir + "tmp_merge_all_1_2_1"; - const auto dst = table_dir + "all_1_2_1"; - auto tx = storage->createTransaction(); - writeFileTx(*tx, table_dir + "all_1_1_0/source.txt", "same"); - tx->commit(DB::NoCommitOptions{}); - tx = storage->createTransaction(); - tx->createHardLink(table_dir + "all_1_1_0/source.txt", dst + "/file.txt"); - writeFileTx(*tx, src + "/file.txt", "same"); - tx->moveDirectory(src, dst); - tx->commit(DB::NoCommitOptions{}); - EXPECT_EQ(storage->tryGetInManifestBytes(dst + "/file.txt"), "same"); -} - -TEST(CASInlineCapGaps, CorruptSelectedInlineDoesNotRepoint) -{ - for (const bool truncate : {false, true}) - { - SCOPED_TRACE(truncate); - auto storage = openStorage(); - const String path = table_dir + "all_1_1_0/small.idx"; - auto tx = storage->createTransaction(); - writeFileTx(*tx, path, "old"); - tx->commit(DB::NoCommitOptions{}); - tx = storage->createTransaction(); - auto writer = dynamic_cast(*tx).writeFile(path, 4096, DB::WriteMode::Rewrite, {}); - writer->write("new", 3); - writer->finalize(); - if (truncate) - std::filesystem::resize_file(writer->getFileName(), 2); - else - { - std::ofstream out(writer->getFileName(), std::ios::binary); - out.write("bad", 3); - ASSERT_TRUE(out.good()); - } - EXPECT_THROW(tx->commit(DB::NoCommitOptions{}), DB::Exception); - EXPECT_EQ(storage->tryGetInManifestBytes(path), "old"); - } -} - -TEST(CASInlineCapGaps, SpilledCandidateIsNotReadToChoosePlacement) -{ - auto storage = openStorage(); - const String bytes = payload(mib, 80); - const auto dir = table_dir + "all_2_2_0/"; - auto tx = storage->createTransaction(); - writeFileTx(*tx, table_dir + "all_1_1_0/same.bin", bytes); - tx->commit(DB::NoCommitOptions{}); - - tx = storage->createTransaction(); - writeFullBudget(*tx, dir.substr(0, dir.size() - 1), "other"); - auto writer = dynamic_cast(*tx).writeFile(dir + "first.idx", 4096, DB::WriteMode::Rewrite, {}); - writer->write(bytes.data(), bytes.size()); - writer->finalize(); - /// The first path sorts first among 17 equally large candidates. Its blob already exists: - /// neither placement planning nor reuse requires reopening its staging file. - ASSERT_TRUE(std::filesystem::remove(writer->getFileName())); - tx->commit(DB::NoCommitOptions{}); - expectBlob(*storage, "all_2_2_0", "first.idx", bytes); -} - -TEST(CASInlineCapGaps, LoadTimeFileAboveThePerFileThresholdIsABlobToday) -{ - auto storage = openStorage(); - const std::string table = "e07/e07e07e0-0707-4707-8707-070707070707/"; - 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); - files["columns.txt"] = payload(inline_file_threshold, 2); - files["serialization.json"] = payload(inline_file_threshold + 1, 3); - - 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()) << error; - - expectReadsBack(*storage, final_part, files); - const auto manifest = manifestOf(*storage, "e07e07e0-0707-4707-8707-070707070707", "all_1_1_0"); - ASSERT_TRUE(DB::Cas::findEntry(manifest.entries, "columns.txt") && DB::Cas::findEntry(manifest.entries, "serialization.json")); - EXPECT_EQ(DB::Cas::findEntry(manifest.entries, "columns.txt")->placement, DB::Cas::EntryPlacement::Inline); - EXPECT_EQ(DB::Cas::findEntry(manifest.entries, "serialization.json")->placement, DB::Cas::EntryPlacement::Blob); -} - -/// A part name is carried in every ref-log record of the part, and a record has a byte cap. A partition -/// key of many integer columns gives a name of several kilobytes. The refusal arrives at commit, after -/// the part's files and its manifest were written, and the same insert can never pass. -TEST(CASInlineCapGaps, PartNameOverTheRefRecordCapIsRefusedOnlyAtCommit) -{ - auto storage = openStorage(); - const std::string table = "e08/e08e08e0-0808-4808-8808-080808080808/"; - - std::string partition_id; - for (size_t column = 0; column < 200; ++column) - partition_id += (column ? "-" : "") + std::string("18446744073709551615"); - const std::string part_name = partition_id + "_1_1_0"; - ASSERT_GT(part_name.size(), 4096u); - - auto tx = storage->createTransaction(); - writeFileTx(*tx, table + "tmp_insert_" + part_name + "/data.bin", payload(64 * kib, 1)); - writeFileTx(*tx, table + "tmp_insert_" + part_name + "/count.txt", "1"); - - const std::string error = commitErrorOf(*tx); - EXPECT_NE(error.find(std::to_string(DB::ErrorCodes::LIMIT_EXCEEDED) + ": "), std::string::npos) << error; - EXPECT_NE(error.find("per-op cap"), std::string::npos) << error; -} - -TEST(CASInlineCandidateMemory, LargeCandidateMatchesDirectBlobHashAndReadsBack) -{ - auto storage = openStorage(); - const auto dir = table_dir + "tmp_insert_all_1_1_0/"; - const auto bytes = payload(64 * mib, 13); - auto tx = storage->createTransaction(); - writeFileTx(*tx, dir + "same.bin", bytes); - writeFileTx(*tx, dir + "skp_idx_t.dct.idx", bytes); - tx->moveDirectory(table_dir + "tmp_insert_all_1_1_0", table_dir + "all_1_1_0"); - tx->commit(DB::NoCommitOptions{}); - expectBlob(*storage, "all_1_1_0", "same.bin", bytes); - expectBlob(*storage, "all_1_1_0", "skp_idx_t.dct.idx", bytes); -} diff --git a/src/Disks/tests/gtest_cas_s3_staging.cpp b/src/Disks/tests/gtest_cas_s3_staging.cpp index f2c21a0c7592e..1437f7f9f0ca5 100644 --- a/src/Disks/tests/gtest_cas_s3_staging.cpp +++ b/src/Disks/tests/gtest_cas_s3_staging.cpp @@ -15,8 +15,6 @@ #include #include #include -#include -#include #include #include @@ -26,8 +24,6 @@ #include #include #include -#include -#include #include #include #include @@ -92,50 +88,15 @@ Poco::AutoPtr configWithDiskSection(const std::str return new Poco::Util::XMLConfiguration(xml_stream); } -/// Resolve the key again on every range read, as S3 does. A permanently open local -/// descriptor would keep serving bytes even if the key had already been deleted. -class StagingRangeReader final : public DB::ReadBufferFromFileBase -{ -public: - using Open = std::function()>; - StagingRangeReader(String name_, Open open_) : ReadBufferFromFileBase(4096, nullptr, 0), name(std::move(name_)), open(std::move(open_)) {} - - String getFileName() const override { return name; } - off_t getPosition() override { return end_offset - available(); } - off_t seek(off_t offset, int whence) override - { - end_offset = whence == SEEK_SET ? offset : getPosition() + offset; - working_buffer.resize(0); - pos = working_buffer.begin(); - return end_offset; - } - -private: - bool nextImpl() override - { - auto input = open(); - input->seek(end_offset, SEEK_SET); - const size_t count = input->read(internal_buffer.begin(), internal_buffer.size()); - working_buffer = Buffer(internal_buffer.begin(), internal_buffer.begin() + count); - end_offset += count; - return count != 0; - } - - String name; - Open open; - off_t end_offset = 0; -}; - /// A local test store whose copy-mode capability is configurable. Its ordinary `copyObject` /// implementation remains the real local implementation; only the advertised transport capability /// differs so mount selection can be tested independently of a live S3 service. class FakeNativeCopyObjectStorage final : public DB::LocalObjectStorage { public: - FakeNativeCopyObjectStorage(DB::LocalObjectStorageSettings settings_, bool native_only_copy_supported_, bool observe_staging_ranges_) + FakeNativeCopyObjectStorage(DB::LocalObjectStorageSettings settings_, bool native_only_copy_supported_) : DB::LocalObjectStorage(std::move(settings_)) , native_only_copy_supported(native_only_copy_supported_) - , observe_staging_ranges(observe_staging_ranges_) { } @@ -145,26 +106,8 @@ class FakeNativeCopyObjectStorage final : public DB::LocalObjectStorage || (mode == DB::ObjectStorageCopyMode::NativeOnly && native_only_copy_supported); } - std::unique_ptr readObject( - const DB::StoredObject & object, const DB::ReadSettings & settings, std::optional hint, - bool external, bool restrict_seek) const override - { - if (observe_staging_ranges && object.remote_path.contains("/staging/")) - return std::make_unique(object.remote_path, [this, object, settings, hint, external, restrict_seek] - { - ++staging_range_reads; - return DB::LocalObjectStorage::readObject(object, settings, hint, external, restrict_seek); - }); - return DB::LocalObjectStorage::readObject(object, settings, hint, external, restrict_seek); - } - - mutable std::atomic staging_range_reads{0}; - std::atomic staging_deletes{0}; - void removeObjectIfExists(const DB::StoredObject & object) override { - if (observe_staging_ranges && object.remote_path.contains("/staging/")) - ++staging_deletes; if (throw_on_remove.load()) throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected delete failure for {}", object.remote_path); DB::LocalObjectStorage::removeObjectIfExists(object); @@ -174,10 +117,9 @@ class FakeNativeCopyObjectStorage final : public DB::LocalObjectStorage private: const bool native_only_copy_supported; - const bool observe_staging_ranges; }; -std::shared_ptr makeFakeNativeCopyStorage(bool native_only_copy_supported, bool observe_staging_ranges = false) +std::shared_ptr makeFakeNativeCopyStorage(bool native_only_copy_supported) { static std::atomic counter{0}; const auto unique = std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)); @@ -189,7 +131,7 @@ std::shared_ptr makeFakeNativeCopyStorage(bool nati DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); return DB::Cas::tests::ownedByDirectory( - std::make_shared(std::move(settings), native_only_copy_supported, observe_staging_ranges), root); + std::make_shared(std::move(settings), native_only_copy_supported), root); } /// A fake object-store sink for Task 4 of the S3-native staging plan (`DB::Cas::CaContentWriteBuffer`'s @@ -883,7 +825,9 @@ TEST(CASS3Staging, UnsupportedNativeOnlyCopyDoesNotFallBackToLocal) } /// (a) A successful commit removes the S3 staging object of a pending blob it staged. Uses the B189 -/// orphan shape. An unlinked staged file and a file ultimately placed Inline must both be reclaimed. +/// orphan shape (the pending blob's entry is unlinked before commit) so `publishStaging` never calls +/// `putBlob` for it — only `cleanupPendingTempFiles`'s Task 6 branch ever touches this staging object, +/// which is exactly the seam this test targets. TEST(CASS3Staging, SuccessfulCommitRemovesOrphanedS3StagingObject) { auto object_storage = makeFakeNativeCopyStorage(/*native_only_copy_supported=*/true); @@ -903,7 +847,7 @@ TEST(CASS3Staging, SuccessfulCommitRemovesOrphanedS3StagingObject) DB::RelativePathsWithMetadata staged_before; object_storage->listObjects(metadata_storage->stagingKeyPrefix(), staged_before, /*max_keys=*/0); - ASSERT_EQ(staged_before.size(), 2u); + ASSERT_EQ(staged_before.size(), 1u) << "exactly orphan.bin's S3 staging object should exist pre-commit"; tx->unlinkFile("a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/orphan.bin", false, false); @@ -911,7 +855,8 @@ TEST(CASS3Staging, SuccessfulCommitRemovesOrphanedS3StagingObject) DB::RelativePathsWithMetadata staged_after; object_storage->listObjects(metadata_storage->stagingKeyPrefix(), staged_after, /*max_keys=*/0); - EXPECT_TRUE(staged_after.empty()); + EXPECT_TRUE(staged_after.empty()) + << "cleanupPendingTempFiles must remove the orphaned S3 staging object after a successful commit"; } /// (b) Read-your-writes over an S3 pending blob (before commit) returns the staged bytes from the S3 @@ -936,189 +881,27 @@ TEST(CASS3Staging, ReadYourWritesReturnsStagedBytesFromS3StagingObject) EXPECT_EQ(got, payload); } -TEST(CASS3Staging, InlineCandidateUsesConfiguredStaging) +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"; - for (const size_t size : {0u, 1024u}) - { - SCOPED_TRACE(size); - const std::string bytes(size, 'x'); - auto & ca_tx = dynamic_cast(*tx); - auto writer = ca_tx.writeFile(path, size, DB::WriteMode::Rewrite, {}); - writer->write(bytes.data(), bytes.size()); - writer->finalize(); - - DB::RelativePathsWithMetadata staged; - objects->listObjects(storage->stagingKeyPrefix(), staged, 0); - ASSERT_EQ(staged.size(), 1u); - EXPECT_EQ(objects->getObjectMetadata(staged.front()->relative_path, false).size_bytes, storage->store()->poolMeta().blob_header_len + size); - 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_EQ(storage->tryGetInManifestBytes(path), bytes); - tx = storage->createTransaction(); - } -} - -TEST(CASS3Staging, OpenReaderKeepsPrivateObjectThroughCommitOrAbort) -{ - for (const bool commit : {false, true}) - { - SCOPED_TRACE(commit); - auto objects = makeFakeNativeCopyStorage(true, /*observe_staging_ranges=*/true); - auto storage = makeS3StagingMetadataStorageForTest(objects, "mountReaderLifetime"); - storage->startup(); - const std::string path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/skip.dct.idx"; - auto tx = storage->createTransaction(); - std::string bytes(64 * 1024, 'x'); - bytes.back() = 'z'; - writeThroughS3Transaction(dynamic_cast(*tx), path, bytes); - - DB::RelativePathsWithMetadata staged; - objects->listObjects(storage->stagingKeyPrefix(), staged, 0); - ASSERT_EQ(staged.size(), 1u); - auto reader = tx->tryReadFileInFlight(path, DB::ReadSettings{}, {}); - ASSERT_NE(reader, nullptr); - char byte; - reader->readStrict(&byte, 1); - ASSERT_EQ(byte, 'x'); - if (commit) - tx->commit(DB::NoCommitOptions{}); - tx.reset(); - - const size_t reads_before_seek = objects->staging_range_reads.load(); - staged.clear(); - objects->listObjects(storage->stagingKeyPrefix(), staged, 0); - ASSERT_EQ(staged.size(), 1u); - reader->seek(bytes.size() - 1, SEEK_SET); - reader->readStrict(&byte, 1); - EXPECT_EQ(byte, 'z'); - EXPECT_GT(objects->staging_range_reads.load(), reads_before_seek); - EXPECT_EQ(objects->staging_deletes.load(), 0u); - reader.reset(); - EXPECT_EQ(objects->staging_deletes.load(), 1u); - staged.clear(); - objects->listObjects(storage->stagingKeyPrefix(), staged, 0); - EXPECT_TRUE(staged.empty()); - } -} - -/// Run explicitly on both revisions with --gtest_also_run_disabled_tests and a descriptor -/// limit above 5,000. Record the observed peaks instead of imposing a backend-independent limit. -TEST(CASInlineCandidateMemory, DISABLED_FiveThousandOpenWriters) -{ - constexpr size_t num_writers = 5000; - constexpr size_t buffer_size = 64 * 1024; - struct rlimit limit{}; - const int status = getrlimit(RLIMIT_NOFILE, &limit); - ASSERT_EQ(status, 0); - if (limit.rlim_cur < num_writers + 128) - GTEST_SKIP() << "requires at least " << num_writers + 128 << " descriptors"; - ::testing::Test::RecordProperty("fd_limit", std::to_string(limit.rlim_cur)); - ::testing::Test::RecordProperty("buffer_bytes", buffer_size); - - for (bool remote : {false, true}) - { - auto objects = makeFakeNativeCopyStorage(true); - auto settings = DB::Cas::tests::makeSettingsForTest( - "mountManyWriters", std::filesystem::path(objects->getCommonKeyPrefix()) / "scratch"); - if (remote) - { - settings[DB::ContentAddressedSetting::staging_backend] = "s3"; - settings.validate(); - } - auto storage = std::make_shared(objects, "pool", "srv1", "", nullptr, settings); - storage->startup(); - std::async(std::launch::async, [&] - { - MemoryTracker tracker(&total_memory_tracker, VariableContext::Process, false); - DB::ThreadStatus thread_status; - thread_status.memory_tracker.setParent(&tracker); - thread_status.untracked_memory_limit = 0; - const String prefix = remote ? "s3_adapter_" : "local_"; - auto record = [&](const String & field, auto value) - { - ::testing::Test::RecordProperty(prefix + field, std::to_string(value)); - }; - DB::WriteSettings write_settings; - write_settings.use_adaptive_write_buffer = true; - write_settings.adaptive_write_buffer_initial_size = 4096; - record("adaptive_initial_bytes", write_settings.adaptive_write_buffer_initial_size); - auto tx = storage->createTransaction(); - auto & ca_tx = dynamic_cast(*tx); - const String dir = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/"; - std::vector> writers; - for (size_t i = 0; i < num_writers; ++i) - { - auto out = ca_tx.writeFile(dir + std::to_string(i) + ".idx", buffer_size, DB::WriteMode::Rewrite, write_settings); - out->write("prefix", 6); - if (i % 2 == 0) - out->next(); - writers.push_back(std::move(out)); - } - record("open_bytes", tracker.get()); -#if defined(OS_LINUX) - record("open_fds", std::distance(std::filesystem::directory_iterator("/proc/self/fd"), std::filesystem::directory_iterator{})); -#endif - for (size_t i = 0; i < num_writers; ++i) - { - if (i % 2 == 0) - writers[i]->finalize(); - else - writers[i]->cancel(); - writers[i].reset(); - } - record("closed_bytes", tracker.get()); - tx->commit(DB::NoCommitOptions{}); - record("committed_bytes", tracker.get()); - EXPECT_EQ(storage->tryGetInManifestBytes(dir + "0.idx"), "prefix"); - EXPECT_FALSE(storage->existsFile(dir + "1.idx")); - record("peak_bytes", tracker.getPeak()); - }).get(); - } -} - -TEST(CASS3Staging, FailedReplacementLeavesThePreviousSourceReadable) -{ - for (const bool remote : {false, true}) - { - SCOPED_TRACE(remote); - auto objects = makeFakeNativeCopyStorage(true); - auto settings = DB::Cas::tests::makeSettingsForTest( - "mountRegistration", std::filesystem::path(objects->getCommonKeyPrefix()) / "scratch"); - if (remote) - { - settings[DB::ContentAddressedSetting::staging_backend] = "s3"; - settings.validate(); - } - auto storage = std::make_shared(objects, "pool", "srv1", "", nullptr, settings); - storage->startup(); - auto tx = storage->createTransaction(); - auto & ca_tx = dynamic_cast(*tx); - const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/a.idx"; - writeThroughS3Transaction(ca_tx, path, "old"); - ca_tx.failNextFileRegistrationForTest(); - EXPECT_THROW(writeThroughS3Transaction(ca_tx, path, "new"), DB::Exception); + const std::string bytes(1024 * 1024 + 1, 'x'); + writeThroughS3Transaction(dynamic_cast(*tx), path, bytes); - if (remote) - { - DB::RelativePathsWithMetadata staged; - objects->listObjects(storage->stagingKeyPrefix(), staged, 0); - EXPECT_EQ(staged.size(), 1u); - } - else - EXPECT_EQ(std::distance(std::filesystem::directory_iterator(storage->scratchPath()), std::filesystem::directory_iterator{}), 1); - tx->commit(DB::NoCommitOptions{}); - EXPECT_EQ(storage->tryGetInManifestBytes(path), "old"); - } + 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. @@ -1717,36 +1500,6 @@ std::shared_ptr makeFakeGenerationObjectStorageForT } -TEST(CASS3Staging, OversizedCandidatePublishesFromConfiguredPrivateObject) -{ - auto objects = makeFakeGenerationObjectStorageForTest(); - auto storage = makeS3StagingMetadataStorageForTest(objects, "mountLargeIndex"); - storage->startup(); - auto tx = storage->createTransaction(); - const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/skip.dct.idx"; - const String bytes(1024 * 1024 + 1, 'x'); - writeThroughS3Transaction(dynamic_cast(*tx), path, bytes); - DB::RelativePathsWithMetadata staged; - objects->listObjects(storage->stagingKeyPrefix(), staged, 0); - ASSERT_EQ(staged.size(), 1u); - EXPECT_TRUE(!std::filesystem::exists(storage->scratchPath()) || std::filesystem::is_empty(storage->scratchPath())); - tx->commit(DB::NoCommitOptions{}); - EXPECT_FALSE(storage->tryGetInManifestBytes(path).has_value()); - const auto copies = objects->copiesByDestination(); - ASSERT_EQ(copies.size(), 1u); - EXPECT_EQ(copies.begin()->second, 1u); - const auto published = storage->getStorageObjects(path); - ASSERT_EQ(published.size(), 1u); - auto reader = storage->readBlobPayload({.key = published[0].remote_path, - .offset = storage->store()->poolMeta().blob_header_len, .length = bytes.size()}, path, {}); - String got; - DB::readStringUntilEOF(got, *reader); - EXPECT_TRUE(got == bytes); - staged.clear(); - objects->listObjects(storage->stagingKeyPrefix(), staged, 0); - EXPECT_TRUE(staged.empty()); -} - /// A store whose iterator does not page (the fallback `IObjectStorage::iterate` lists `max_keys` keys /// once and ends) must still let a page-sized list report that more keys follow. A page that ended /// exactly at the limit with an empty cursor would read as the end of the prefix, and the startup diff --git a/tests/integration/test_cas_s3_staging/__init__.py b/tests/integration/test_cas_s3_staging/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/tests/integration/test_cas_s3_staging/configs/storage_conf.xml b/tests/integration/test_cas_s3_staging/configs/storage_conf.xml deleted file mode 100644 index e714ddaffd1ea..0000000000000 --- a/tests/integration/test_cas_s3_staging/configs/storage_conf.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - object_storage - s3 - cas - itest-staging - s3 - http://rustfs1:11121/test/cas_staging_it/ - clickhouse - clickhouse - 5242880 - 5242880 - - - - -
cas_staged
-
-
-
-
diff --git a/tests/integration/test_cas_s3_staging/test.py b/tests/integration/test_cas_s3_staging/test.py deleted file mode 100644 index 35f0eaadbfbd0..0000000000000 --- a/tests/integration/test_cas_s3_staging/test.py +++ /dev/null @@ -1,78 +0,0 @@ -import pytest - -from helpers.cluster import ClickHouseCluster - - -cluster = ClickHouseCluster(__file__) -node = cluster.add_instance( - "node", main_configs=["configs/storage_conf.xml"], with_rustfs=True, stay_alive=True -) - - -@pytest.fixture(scope="module", autouse=True) -def start_cluster(): - try: - cluster.start() - yield - finally: - cluster.shutdown() - - -@pytest.fixture -def staged_table(): - node.query( - "CREATE TABLE staged (n UInt64 CODEC(NONE)) ENGINE = MergeTree " - "ORDER BY tuple() SETTINGS storage_policy = 'cas_staged', " - "min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0" - ) - try: - yield - finally: - node.query("DROP TABLE staged SYNC") - - -rows = 2 * 1024 * 1024 -insert_query = f"INSERT INTO staged SELECT number FROM numbers({rows})" -insert_settings = { - "min_insert_block_size_rows": rows, - "min_insert_block_size_bytes": 0, - "max_insert_threads": 1, -} -multipart_counter = "SELECT sum(value) FROM system.events WHERE event = 'DiskS3UploadPart'" - - -def assert_staging_empty(): - bucket = cluster.rustfs_bucket - cluster.rustfs_client.stat_object(bucket, "cas_staging_it/_pool_meta") - objects = cluster.rustfs_client.list_objects( - bucket, prefix="cas_staging_it/staging/itest-staging/", recursive=True - ) - assert list(objects) == [] - - -def test_multipart_staging_is_released_and_part_reads_after_restart(staged_table): - before = int(node.query(multipart_counter)) - node.query(insert_query, settings=insert_settings) - assert int(node.query(multipart_counter)) > before - assert_staging_empty() - - node.restart_clickhouse() - assert node.query("SELECT count(), sum(n) FROM staged").strip() == ( - f"{rows}\t{rows * (rows - 1) // 2}" - ) - assert node.query("CHECK TABLE staged SETTINGS check_query_single_value_result = 1").strip() == "1" - - -def test_failed_disk_commit_releases_private_objects(staged_table): - before = int(node.query(multipart_counter)) - failpoint = "part_storage_fail_commit_transaction" - node.query(f"SYSTEM ENABLE FAILPOINT {failpoint}") - try: - error = node.query_and_get_error(insert_query, settings=insert_settings) - assert failpoint in error - finally: - node.query(f"SYSTEM DISABLE FAILPOINT {failpoint}") - - assert int(node.query(multipart_counter)) > before - assert node.query("SELECT count() FROM staged").strip() == "0" - assert_staging_empty() 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 index c4a1485be9a07..0f6cd234a393c 100644 --- 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 @@ -1,8 +1,8 @@ t_merge 1 -t_merge 100 1 +t_merge 1000000 1 t_merge 1 1 t_mat 1 -t_mat 100 1 +t_mat 1000000 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 index 7e9c8bd8c7f5b..4834a069ec12c 100755 --- 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 @@ -11,37 +11,37 @@ CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) set -e -o pipefail CLIENT="${CLICKHOUSE_CLIENT} --allow_experimental_full_text_index=1" -ROWS=100 +ROWS=1000000 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. +# One 64-character token per row, different in every row: the dictionary of a segment is about as large +# as the tokens it holds, whatever the codec. 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}" + ${CLIENT} -q "INSERT INTO $1 SELECT number, concat(hex(sipHash128(number)), hex(sipHash128(number, 1))) + FROM numbers($2, $3) SETTINGS max_insert_threads = 1, max_block_size = 1000000, max_insert_block_size = 1000000" } 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)))) + WHERE hasToken(s, concat(hex(sipHash128(toUInt64(7))), hex(sipHash128(toUInt64(7), 1)))) SETTINGS force_data_skipping_indices = 'idx_s'" ${CLIENT} -q "CHECK TABLE $1 SETTINGS check_query_single_value_result = 1" } -# Flush after each five-row block. The segment dictionaries remain eligible for Inline -# individually, while their combined size exceeds the manifest budget. -SEGMENTS="index_granularity = 5, merge_max_block_size = 5, text_index_max_processed_tokens_before_flush = 1, +# A segment is flushed after every block that the builder reads, and a block is at least one granule. With +# 1024 rows per granule each segment holds about 1024 tokens (about 70 KiB), far below the size at which a +# file stops being small, and the rebuild leaves several hundred segments. +SEGMENTS="index_granularity = 1024, merge_max_block_size = 1024, text_index_max_processed_tokens_before_flush = 1, 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', countIf(ProfileEvents['TextIndexTemporarySegmentsWritten'] >= 20 + ${CLIENT} -q "SELECT '$1', countIf(ProfileEvents['TextIndexTemporarySegmentsWritten'] >= 100 AND ProfileEvents['CASManifestInlineEntriesSelectedForBlob'] > 0) = 1 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)" @@ -65,7 +65,7 @@ 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" +${CLIENT} -q "ALTER TABLE t_mat MATERIALIZE INDEX idx_s SETTINGS mutations_sync = 2, max_block_size = 1024" segments t_mat MutatePart check t_mat From ba9a6103321011a4e248146c9181d12597e4d182 Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Sat, 28 Nov 2026 23:47:51 +0100 Subject: [PATCH 5/7] Trim unused string capacity in staged CAS inline entries An inline candidate written in chunks can retain substantially more memory than its payload when the transaction takes ownership. Request a smaller allocation before moving the finalized string into the manifest entry. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- .../ContentAddressed/ContentAddressedTransaction.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index ad5d0d0dd1715..0cbe44209b686 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -1207,7 +1207,7 @@ std::unique_ptr ContentAddressedTransaction::writeFile( return std::make_unique( path, INLINE_CAP, /*create_blob_if_empty=*/false, std::move(create_local_blob_writer), - [this, route = std::move(*r), hash_algo](FinalizeResult result) + [this, route = std::move(*r), hash_algo](FinalizeResult && result) { auto * inlined = std::get_if(&result); if (!inlined) @@ -1219,6 +1219,10 @@ std::unique_ptr ContentAddressedTransaction::writeFile( 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); }, From a2b90dc739fc9e8169a4784148258164f8b191de Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Sun, 29 Nov 2026 00:20:11 +0100 Subject: [PATCH 6/7] Make CAS inline-budget regression tests deterministic in CI Pin LZ4 for the text index rebuild so randomized server codecs cannot make the segment dictionaries fit below the manifest limit. Generate 100 rows across 20 segments and check that both the merge and mutation still select entries for blob placement. Exclude the memory measurement at compile time under sanitizers, where the allocation tracker cannot support the assertion. This avoids Clang's unreachable-code diagnostic after `GTEST_SKIP`. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- src/Disks/tests/gtest_cas_inline_cap_gaps.cpp | 4 +++- ...text_index_rebuild_inline_budget.reference | 4 ++-- ...15_cas_text_index_rebuild_inline_budget.sh | 24 +++++++++---------- 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp index d0eb7cc105e83..300355f5bd787 100644 --- a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -617,8 +617,9 @@ 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"; -#endif +#else auto storage = openStorage(); auto tx = storage->createTransaction(); auto & ca_tx = dynamic_cast(*tx); @@ -643,6 +644,7 @@ void checkInlineCandidateWritePeak(size_t num_files, size_t chunks_per_file, Int }).get(); ::testing::Test::RecordProperty("peak_bytes", std::to_string(peak)); EXPECT_LE(peak, limit); +#endif } } 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 index 0f6cd234a393c..c4a1485be9a07 100644 --- 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 @@ -1,8 +1,8 @@ t_merge 1 -t_merge 1000000 1 +t_merge 100 1 t_merge 1 1 t_mat 1 -t_mat 1000000 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 index 4834a069ec12c..d57c59f25ff7d 100755 --- 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 @@ -11,37 +11,37 @@ CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) set -e -o pipefail CLIENT="${CLICKHOUSE_CLIENT} --allow_experimental_full_text_index=1" -ROWS=1000000 +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/')" } -# One 64-character token per row, different in every row: the dictionary of a segment is about as large -# as the tokens it holds, whatever the codec. +# 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, concat(hex(sipHash128(number)), hex(sipHash128(number, 1))) - FROM numbers($2, $3) SETTINGS max_insert_threads = 1, max_block_size = 1000000, max_insert_block_size = 1000000" + ${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, concat(hex(sipHash128(toUInt64(7))), hex(sipHash128(toUInt64(7), 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" } -# A segment is flushed after every block that the builder reads, and a block is at least one granule. With -# 1024 rows per granule each segment holds about 1024 tokens (about 70 KiB), far below the size at which a -# file stops being small, and the rebuild leaves several hundred segments. -SEGMENTS="index_granularity = 1024, merge_max_block_size = 1024, text_index_max_processed_tokens_before_flush = 1, +# Pin LZ4 so files from the 20 five-row segments exceed the 16 MiB inline budget even when the server defaults to ZSTD. +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', countIf(ProfileEvents['TextIndexTemporarySegmentsWritten'] >= 100 + ${CLIENT} -q "SELECT '$1', countIf(ProfileEvents['TextIndexTemporarySegmentsWritten'] >= 20 AND ProfileEvents['CASManifestInlineEntriesSelectedForBlob'] > 0) = 1 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)" @@ -65,7 +65,7 @@ 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 = 1024" +${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 From bf97da29ae4d3a74b3460c12a2fbbcd0ff830410 Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Sun, 29 Nov 2026 09:50:00 +0100 Subject: [PATCH 7/7] Stabilize the CAS text-index rebuild test and share the inline entry limit Randomized dictionary settings can make the 100-row fixture fit within the manifest budget. Keep the dictionary settings stable and report the segment and blob-placement checks separately for the merge and mutation. Use the same per-file inline limit in the writer and the manifest validator. Include the namespace and ref in the retained-entry limit error and document staging, the placement counter and failed commits. CI: https://altinity-build-artifacts.s3.amazonaws.com/json.html?PR=2969&sha=a2b90dc739fc9e8169a4784148258164f8b191de&name_0=PR PR: https://github.com/Altinity/ClickHouse/pull/2969 Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- .../server-config/storing-data.mdx | 9 +++++---- docs/en/antalya/metrics_and_events.md | 6 ++++++ .../ContentAddressedTransaction.cpp | 17 +++++++---------- .../ContentAddressedTransaction.h | 2 +- .../ContentAddressed/Pool/CasPartWriteTxn.cpp | 5 ++--- .../ContentAddressed/Pool/CasPartWriteTxn.h | 3 ++- ...s_text_index_rebuild_inline_budget.reference | 4 ++-- ...5815_cas_text_index_rebuild_inline_budget.sh | 11 +++++++---- 8 files changed, 32 insertions(+), 25 deletions(-) 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/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index 0cbe44209b686..0802a4a2ec397 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -108,11 +108,6 @@ 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(), @@ -405,10 +400,6 @@ namespace std::vector applyManifestInlineBudget( std::vector & entries_to_add_or_replace, uint64_t inline_bytes_from_unchanged_base_entries, Cas::BlobHashAlgo algo) { - if (inline_bytes_from_unchanged_base_entries > Cas::kMaxManifestInlineBytesTotal) - throw Exception(ErrorCodes::LIMIT_EXCEEDED, "Retained manifest entries contain {} inline bytes, exceeding the cap of {}", - inline_bytes_from_unchanged_base_entries, Cas::kMaxManifestInlineBytesTotal); - 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) @@ -610,6 +601,10 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, 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()); @@ -765,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 @@ -1206,7 +1203,7 @@ std::unique_ptr ContentAddressedTransaction::writeFile( return create_local_blob_writer(); return std::make_unique( - path, INLINE_CAP, /*create_blob_if_empty=*/false, std::move(create_local_blob_writer), + path, Cas::kMaxManifestInlineEntryBytes, /*create_blob_if_empty=*/false, std::move(create_local_blob_writer), [this, route = std::move(*r), hash_algo](FinalizeResult && result) { auto * inlined = std::get_if(&result); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index 688da91806c77..8d9271f112fe0 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -294,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 diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index 52c1dfbb532bf..9d5bf1bcdf55e 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -56,7 +56,6 @@ namespace /// Backpressure caps, enforced fail-closed in stageManifest before the body write returns. constexpr uint64_t kMaxManifestEntries = 1048576; -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). @@ -638,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 52899574a4227..6ffe5920a3ea7 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h @@ -15,7 +15,8 @@ namespace DB { class WriteBuffer; } namespace DB::Cas { -inline constexpr uint64_t kMaxManifestInlineBytesTotal = 16ULL << 20; /// 16 MiB +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. /// 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 index c4a1485be9a07..052293bfd3081 100644 --- 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 @@ -1,8 +1,8 @@ -t_merge 1 +t_merge 1 1 1 t_merge 100 1 t_merge 1 1 -t_mat 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 index d57c59f25ff7d..0aa4ffdf41a75 100755 --- 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 @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Tags: no-fasttest +# 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 @@ -33,7 +33,8 @@ check() { ${CLIENT} -q "CHECK TABLE $1 SETTINGS check_query_single_value_result = 1" } -# Pin LZ4 so files from the 20 five-row segments exceed the 16 MiB inline budget even when the server defaults to ZSTD. +# 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'" @@ -41,8 +42,10 @@ SEGMENTS="index_granularity = 5, merge_max_block_size = 5, text_index_max_proces # 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', countIf(ProfileEvents['TextIndexTemporarySegmentsWritten'] >= 20 - AND ProfileEvents['CASManifestInlineEntriesSelectedForBlob'] > 0) = 1 FROM system.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)" }