From 17d8e634a2e2de13f503bcd24aca4c8aa913d7e9 Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Mon, 30 Nov 2026 12:14:14 +0100 Subject: [PATCH 1/8] Prototype a transaction-wide memory budget for CAS inline writes Share payload reservations across writers in a disk transaction. When a writer cannot grow its reservation, spill the file to local staging and keep it eligible for inline placement at commit. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- src/Common/ProfileEvents.cpp | 1 + .../ContentAddressedTransaction.cpp | 650 +++++++++--------- .../ContentAddressedTransaction.h | 108 +-- .../CasInlineCandidateWriteBuffer.cpp | 159 +++++ .../CasInlineCandidateWriteBuffer.h | 85 +++ src/Disks/tests/gtest_cas_inline_cap_gaps.cpp | 133 ++++ src/Disks/tests/gtest_cas_s3_staging.cpp | 39 ++ 7 files changed, 791 insertions(+), 384 deletions(-) create mode 100644 src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp create mode 100644 src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index e3f0c10d8c13..fe7dd9d19c14 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -911,6 +911,7 @@ The server successfully detected this situation and will download merged part fr 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(CASInlineWriteMemoryBudgetSpills, "Number of CAS inline-candidate files spilled to local staging because their transaction could not reserve more payload memory.", 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 0802a4a2ec39..c5d3c845ca93 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -108,6 +109,24 @@ namespace "content-addressed write path.", op); } +/// Capacity reserved for new inline candidates across all parts of one transaction. +constexpr size_t INLINE_WRITE_MEMORY_LIMIT = 16ULL << 20; + +/// Destroy the underlying reader before releasing its source. A remote seek can start a new GET. +struct StagedPayloadOwner +{ + std::shared_ptr source; +}; + +template +class ReaderWithStagedPayload final : private StagedPayloadOwner, public Reader +{ +public: + template + ReaderWithStagedPayload(std::shared_ptr source_, Args &&... args) + : StagedPayloadOwner{std::move(source_)}, Reader(std::forward(args)...) {} +}; + bool hasTopLevelFile(const std::vector & entries) { return std::any_of(entries.begin(), entries.end(), @@ -118,6 +137,7 @@ bool hasTopLevelFile(const std::vector & entries) ContentAddressedTransaction::ContentAddressedTransaction(ContentAddressedMetadataStorage & metadata_storage_) : metadata_storage(metadata_storage_) + , inline_write_budget(std::make_shared(INLINE_WRITE_MEMORY_LIMIT)) { } @@ -125,7 +145,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. @@ -193,68 +213,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 (!registered || memory) + 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); } @@ -262,6 +308,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( @@ -360,29 +408,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 { @@ -392,54 +417,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 { + 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 <= Cas::kMaxManifestInlineEntryBytes)) + { + 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); - - blob_upload_requests.push_back({entry->ref, Cas::BlobSource::fromString(std::exchange(entry->inline_bytes, {})), size}); + const auto size = entry->size(); - entry->blob_size = size; - entry->placement = Cas::EntryPlacement::Blob; - total_inline_bytes -= size; - - if (total_inline_bytes <= Cas::kMaxManifestInlineBytesTotal) - break; + 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) + { + const auto & file = st.staged_part_files.at(entry->path); + if (file->memory) + entry->inline_bytes.assign(file->memory->view()); + else + { + auto input = openStagedPayload(file, size, pool); + String bytes(size, '\0'); + input->readStrict(bytes.data(), 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->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( @@ -457,81 +501,46 @@ Cas::ManifestId ContentAddressedTransaction::precommitAndUpload( return id; } -void ContentAddressedTransaction::appendStagedBlobUploads(const PartStaging & st, std::vector & blob_upload_requests) const +std::unique_ptr ContentAddressedTransaction::openStagedPayload(const StagedPartFilePtr & file, uint64_t size, const Cas::PoolPtr & pool) { - if (st.pending_blobs.empty()) - return; + if (file->memory) + return std::make_unique>(file, file->memory->view()); + 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; +} - /// 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; +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}); } } @@ -567,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. - /// 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); @@ -607,7 +616,7 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, 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()); + 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); @@ -712,7 +721,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; } @@ -780,8 +789,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(); @@ -835,9 +844,13 @@ 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 (auto file = stagedFileOf(it->second, entry->path)) + { + if (file->allow_inline_by_name && entry->blob_size <= Cas::kMaxManifestInlineEntryBytes) + return StoredObjects{StoredObject("", path, entry->blob_size)}; return {}; + } const auto location = metadata_storage.store()->locate(*entry); return StoredObjects{StoredObject(location.key, path, location.length)}; } @@ -866,30 +879,19 @@ 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->memory) + return std::make_unique>( + file, /*owns_memory=*/false, path, file->memory->view()); + 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); } @@ -967,24 +969,55 @@ void ContentAddressedTransaction::createMetadataFile(const std::string &, const notYet("createMetadataFile"); } +void ContentAddressedTransaction::registerStagedFile( + const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::shared_ptr & file) +{ + std::lock_guard lock(file_registration_mutex); + auto & st = stagingFor(route); + const bool had_build = bool(st.build); + buildFor(route, st); + + SCOPE_EXIT({ + if (!had_build && !file->registered) + st.build.reset(); + }); + + if (std::exchange(fail_next_file_registration, false)) + throw Exception(ErrorCodes::ABORTED, "Injected failure registering staged file {}", route.file); + + file->allow_inline_by_name = !Cas::partFileMustStayBlob(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->registered = true; + st.has_finalized_file_write = true; +} + 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); + /// The local writer still owns its scratch path if registration throws. The S3 sink + /// has already finalized the object, so this callback cleans it up on failure. + try + { + auto file = std::make_shared(); + file->staging_path = staging_key; + file->remote_storage = remote_storage; + file->pool_staging_key = pool_key; + registerStagedFile(route, ref, size, file); + } + 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); +size_t ContentAddressedTransaction::inlineCandidateReservedBytesForTest() const noexcept +{ + return inline_write_budget->reservedBytes(); } void ContentAddressedTransaction::stageUnprovenBlobEntryForTest(const std::string & path, const Cas::BlobRef & ref, uint64_t size) @@ -1136,14 +1169,6 @@ 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(); @@ -1162,9 +1187,11 @@ 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"); - - auto object_sink = metadata_storage.objectStorage()->writeObject(StoredObject(staging_key), WriteMode::Rewrite); + 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 auto remote_storage = metadata_storage.objectStorage(); + auto object_sink = remote_storage->writeObject(StoredObject(staging_key), WriteMode::Rewrite); return std::make_unique( std::move(object_sink), @@ -1174,15 +1201,15 @@ 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 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); + stageBlobPartFile(route, ref, 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. + /// Spill inline candidates locally on either backend, whether the per-file or transaction limit was reached. 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] { @@ -1195,35 +1222,23 @@ std::unique_ptr ContentAddressedTransaction::writeFile( [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); + stageBlobPartFile(route, ref, size, temp_path, nullptr, {}); }); }; if (must_stay_blob) return create_local_blob_writer(); - return std::make_unique( - path, Cas::kMaxManifestInlineEntryBytes, /*create_blob_if_empty=*/false, std::move(create_local_blob_writer), - [this, route = std::move(*r), hash_algo](FinalizeResult && result) + return std::make_unique( + path, buf_size, Cas::kMaxManifestInlineEntryBytes, inline_write_budget, std::move(create_local_blob_writer), + [this, route = std::move(*r), hash_algo](Cas::InlineCandidatePayloadPtr payload) { - auto * inlined = std::get_if(&result); - if (!inlined) - return; /// The local writer already registered the pending blob. - - auto & st = stagingFor(route); - buildFor(route, st); - Cas::ManifestEntry entry; - entry.path = route.file; - entry.placement = Cas::EntryPlacement::Inline; - entry.ref = Cas::poolContentHash(hash_algo, inlined->data); - /// Closed inline candidates keep their string allocations until commit. With 64 KiB writes, - /// a 600 KiB file can retain about 1 MiB of capacity. Trimming 64 such files saves about - /// 26.5 MiB of unused capacity across the transaction. - inlined->data.shrink_to_fit(); - entry.inline_bytes = std::move(inlined->data); - putEntry(st, std::move(entry), nullptr); - }, - buf_size); + const auto bytes = payload->view(); + const auto ref = Cas::poolContentHash(hash_algo, bytes); + auto file = std::make_shared(); + file->memory = std::move(payload); + registerStagedFile(route, ref, bytes.size(), file); + }); } void ContentAddressedTransaction::createDirectory(const std::string &) @@ -1415,23 +1430,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; } } @@ -1598,40 +1603,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 <= Cas::kMaxManifestInlineEntryBytes + && 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); @@ -1643,18 +1657,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 @@ -1678,7 +1688,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 @@ -1686,7 +1696,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) @@ -1810,28 +1820,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 @@ -1846,17 +1849,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); } @@ -1893,10 +1885,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); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index 8d9271f112fe..f2adfa2ddf2b 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -24,6 +25,12 @@ #include #include +namespace DB::Cas +{ +class InlineCandidatePayload; +class InlineWriteMemoryBudget; +} + namespace DB { @@ -33,10 +40,9 @@ 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. +/// Inline-eligible files share a transaction-wide memory budget and spill to local staging +/// when a write exceeds either memory limit. Commit chooses placement per manifest from the +/// final paths and sizes. Readers and uploads can retain the source after publication. class ContentAddressedTransaction : public IMetadataTransaction { public: @@ -86,9 +92,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. 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. + /// Opens a part-file writer or a verbatim namespace or mountpoint writer. Only verbatim files + /// support append, by reading and rewriting the existing contents. std::unique_ptr writeFile( const std::string & path, size_t buf_size, @@ -127,6 +132,8 @@ 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); + size_t inlineCandidateReservedBytesForTest() const noexcept; + 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 +144,23 @@ 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. + /// One finalized source shared across paths, readers and uploads. The memory payload + /// owns its reservation until the last holder releases its bytes. + struct StagedPartFile + { + std::shared_ptr memory; + 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 registered = false; /// The local writer owns its scratch path until registration succeeds. + 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,23 +184,15 @@ 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. }; + std::shared_ptr inline_write_budget; + /// Separate writers may finalize concurrently. Commit and other overlay operations follow writer finalization. + std::mutex file_registration_mutex; + /// Keyed by (namespace string, ref name) — the routed identity, so live/detached/shadow /// stagings never collide. std::map, PartStaging> parts; @@ -188,6 +201,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 @@ -196,13 +210,12 @@ class ContentAddressedTransaction : public IMetadataTransaction /// Cleared in `commit()`'s epilogue. std::unordered_set force_fresh_validated_refs; - /// 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. + void registerStagedFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, + const std::shared_ptr & file); + /// Transfer the writer's private file or S3 object only on successful registration. 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 +223,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 +250,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 StagedPartFilePtr & 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 +273,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/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp new file mode 100644 index 000000000000..747b58bb3659 --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp @@ -0,0 +1,159 @@ +#include + +#include + +#include +#include + +namespace ProfileEvents +{ + extern const Event CASInlineWriteMemoryBudgetSpills; +} + +namespace DB::Cas +{ + +bool InlineWriteMemoryBudget::tryReserve(size_t size) noexcept +{ + size_t current = reservedBytes(); + for (;;) + { + chassert(current <= limit); + if (size > limit - current) + return false; + if (reserved.compare_exchange_weak(current, current + size, std::memory_order_relaxed)) + return true; + } +} + +InlineCandidatePayload::~InlineCandidatePayload() +{ + buffer.reset(); + budget->release(capacity); +} + +bool InlineCandidatePayload::trySetCapacity(size_t new_capacity) +{ + if (new_capacity == capacity) + return true; + if (!budget->tryReserve(new_capacity)) + return false; + + std::unique_ptr replacement; + try + { + replacement = std::make_unique_for_overwrite(new_capacity); + } + catch (...) + { + budget->release(new_capacity); + throw; + } + if (length) + std::memcpy(replacement.get(), buffer.get(), length); + buffer = std::move(replacement); + budget->release(capacity); + capacity = new_capacity; + return true; +} + +InlineCandidateWriteBuffer::InlineCandidateWriteBuffer( + String path_, size_t buf_size, size_t max_inline_bytes_, std::shared_ptr budget, + CreateLocalWriter create_local_writer_, OnInline on_inline_) + : WriteBufferFromFileBase(0, nullptr, 0) + , path(std::move(path_)) + , transfer_size(std::clamp(buf_size, 1, 65536)) + , max_inline_bytes(max_inline_bytes_) + , create_local_writer(std::move(create_local_writer_)) + , on_inline(std::move(on_inline_)) + , payload(std::make_shared(std::move(budget))) +{ + /// The caller can write directly into a payload array, so there is no separate uncharged inline I/O buffer. + padded = false; + set(&overflow_byte, 1); +} + +InlineCandidateWriteBuffer::~InlineCandidateWriteBuffer() +{ + cancel(); +} + +void InlineCandidateWriteBuffer::nextImpl() +{ + if (local) + { + local->write(working_buffer.begin(), offset()); + return; + } + + if (working_buffer.begin() == &overflow_byte) + { + const size_t needed = payload->length + 1; + const size_t target = finishing ? needed + : std::min(max_inline_bytes, payload->capacity ? 2 * payload->capacity : std::min(transfer_size, 4096)); + if (needed > max_inline_bytes || !payload->trySetCapacity(std::max(needed, target))) + { + local = create_local_writer(); + const auto prefix = payload->view(); + if (!prefix.empty()) + local->write(prefix.data(), prefix.size()); + local->write(overflow_byte); + payload.reset(); + resize(transfer_size); + if (needed <= max_inline_bytes) + ProfileEvents::increment(ProfileEvents::CASInlineWriteMemoryBudgetSpills); + return; + } + payload->buffer[payload->length++] = overflow_byte; + } + else + { + payload->length += offset(); + } + + if (payload->length == payload->capacity) + set(&overflow_byte, 1); + else + set(payload->buffer.get() + payload->length, payload->capacity - payload->length); +} + +void InlineCandidateWriteBuffer::preFinalize() +{ + finishing = true; + next(); + if (local) + local->preFinalize(); +} + +void InlineCandidateWriteBuffer::finalizeImpl() +{ + finishing = true; + next(); + if (local) + { + local->finalize(); + return; + } + + set(&overflow_byte, 1); + /// Keep the current allocation if the budget cannot also accommodate a compact copy. + payload->trySetCapacity(payload->length); + on_inline(std::move(payload)); +} + +void InlineCandidateWriteBuffer::cancelImpl() noexcept +{ + set(&overflow_byte, 1); + payload.reset(); + if (local) + local->cancel(); +} + +void InlineCandidateWriteBuffer::sync() +{ + next(); + if (local) + local->sync(); +} + +} diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h new file mode 100644 index 000000000000..ab2e4f105319 --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h @@ -0,0 +1,85 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace DB::Cas +{ + +/// Shared by the inline-candidate writers of one disk transaction and by their finalized payloads. +/// Charges the requested capacity of payload arrays, including both arrays during a reallocation. +class InlineWriteMemoryBudget +{ +public: + explicit InlineWriteMemoryBudget(size_t limit_) : limit(limit_) {} + size_t reservedBytes() const noexcept { return reserved.load(std::memory_order_relaxed); } + +private: + friend class InlineCandidatePayload; + + bool tryReserve(size_t size) noexcept; + void release(size_t size) noexcept { reserved.fetch_sub(size, std::memory_order_relaxed); } + + const size_t limit; + std::atomic reserved{0}; +}; + +/// After finalize, hardlinks and in-flight readers share the same allocation and reservation. +class InlineCandidatePayload +{ +public: + explicit InlineCandidatePayload(std::shared_ptr budget_) : budget(std::move(budget_)) {} + ~InlineCandidatePayload(); + + std::string_view view() const noexcept { return length ? std::string_view(buffer.get(), length) : std::string_view{""}; } + +private: + friend class InlineCandidateWriteBuffer; + + bool trySetCapacity(size_t new_capacity); + + const std::shared_ptr budget; + std::unique_ptr buffer; + size_t length = 0; + size_t capacity = 0; +}; + +using InlineCandidatePayloadPtr = std::shared_ptr; + +class InlineCandidateWriteBuffer final : public WriteBufferFromFileBase +{ +public: + using CreateLocalWriter = std::function()>; + using OnInline = std::function; + + InlineCandidateWriteBuffer( + String path_, size_t buf_size, size_t max_inline_bytes_, std::shared_ptr budget, + CreateLocalWriter create_local_writer_, OnInline on_inline_); + ~InlineCandidateWriteBuffer() override; + + String getFileName() const override { return path; } + void preFinalize() override; + void sync() override; + +private: + void nextImpl() override; + void finalizeImpl() override; + void cancelImpl() noexcept override; + + String path; + size_t transfer_size; + size_t max_inline_bytes; + CreateLocalWriter create_local_writer; + OnInline on_inline; + std::shared_ptr payload; + std::unique_ptr local; + /// Detect the first byte beyond the current allocation. In particular, exactly 1 MiB can still be inline. + char overflow_byte = 0; + bool finishing = false; +}; + +} diff --git a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp index 300355f5bd78..c0aa36c38df5 100644 --- a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -697,3 +698,135 @@ TEST(CASInlineCandidateMemory, ThresholdPreservesPlacementAndPayload) EXPECT_TRUE(storage->tryGetInManifestBytes(dir + "at.idx") == at_limit); expectBlob(*storage, ref, "over.idx", over_limit); } + +TEST(CASInlineCandidateMemory, OpenAndFinalizedWritersShareOneBudgetAcrossParts) +{ + auto storage = openStorage(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const auto first = table_dir + "all_1_1_0/"; + const auto second = table_dir + "all_2_2_0/"; + const std::string bytes = payload(600 * kib, 27); + for (size_t i = 0; i < 12; ++i) + writeFileTx(*tx, first + std::to_string(i) + ".idx", bytes); + const auto retained = ca_tx.inlineCandidateReservedBytesForTest(); + EXPECT_GE(retained, 12 * bytes.size()); + EXPECT_LE(retained, inline_total_budget); + + std::vector> writers; + for (size_t i = 0; i < 20; ++i) + { + auto writer = ca_tx.writeFile(second + std::to_string(i) + ".idx", 64 * kib, DB::WriteMode::Rewrite, {}); + writer->write(bytes.data(), bytes.size()); + writer->sync(); + EXPECT_LE(ca_tx.inlineCandidateReservedBytesForTest(), inline_total_budget); + writers.push_back(std::move(writer)); + } + + /// All files are smaller than the per-file threshold. Scratch here must be caused by transaction pressure. + ASSERT_TRUE(std::filesystem::is_directory(storage->scratchPath())); + EXPECT_FALSE(std::filesystem::is_empty(storage->scratchPath())); + for (auto & writer : writers) + writer->cancel(); + EXPECT_EQ(ca_tx.inlineCandidateReservedBytesForTest(), retained); + EXPECT_TRUE(std::filesystem::is_empty(storage->scratchPath())); +} + +TEST(CASInlineCandidateMemory, LocalSpillCanStillBecomeInlineAndReadersRetainTheirSource) +{ + auto storage = openStorage(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const auto first = table_dir + "all_1_1_0/"; + const auto second = table_dir + "all_2_2_0/"; + const auto bytes = payload(600 * kib, 42); + std::vector> writers; + /// Hold other candidates open to force at least one local spill under the same transaction. + for (size_t i = 0; i < 32; ++i) + { + auto writer = ca_tx.writeFile(first + std::to_string(i) + ".idx", 64 * kib, DB::WriteMode::Rewrite, {}); + writer->write(bytes.data(), bytes.size()); + writers.push_back(std::move(writer)); + } + + const auto path = second + "dict.dct.idx"; + ASSERT_TRUE(std::filesystem::is_directory(storage->scratchPath())); + const auto before = std::distance(std::filesystem::directory_iterator(storage->scratchPath()), std::filesystem::directory_iterator{}); + auto probe = ca_tx.writeFile(path, 64 * kib, DB::WriteMode::Rewrite, {}); + probe->write(bytes.data(), bytes.size()); + probe->finalize(); + const auto after = std::distance(std::filesystem::directory_iterator(storage->scratchPath()), std::filesystem::directory_iterator{}); + ASSERT_EQ(after, before + 1); + + auto reader = ca_tx.tryReadFileInFlight(path, {}, {}); + ASSERT_NE(reader, nullptr); + for (auto & writer : writers) + writer->cancel(); + tx->commit(DB::NoCommitOptions{}); + tx.reset(); + EXPECT_TRUE(storage->tryGetInManifestBytes(path) == bytes); + std::string result; + DB::readStringUntilEOF(result, *reader); + EXPECT_TRUE(result == bytes); + reader.reset(); + EXPECT_TRUE(std::filesystem::is_empty(storage->scratchPath())); +} + +TEST(CASInlineCandidateMemory, HardlinkSharesOneReservationUntilTheLastOwnerReleasesIt) +{ + auto storage = openStorage(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const auto dir = table_dir + "all_1_1_0/"; + const auto bytes = payload(600 * kib, 17); + writeFileTx(*tx, dir + "source.idx", bytes); + const size_t retained = ca_tx.inlineCandidateReservedBytesForTest(); + ASSERT_GE(retained, bytes.size()); + tx->createHardLink(dir + "source.idx", dir + "link.idx"); + EXPECT_EQ(ca_tx.inlineCandidateReservedBytesForTest(), retained); + auto reader = ca_tx.tryReadFileInFlight(dir + "link.idx", {}, {}); + ASSERT_NE(reader, nullptr); + tx->unlinkFile(dir + "source.idx", false, true); + tx->unlinkFile(dir + "link.idx", false, true); + EXPECT_EQ(ca_tx.inlineCandidateReservedBytesForTest(), retained); + std::string result; + DB::readStringUntilEOF(result, *reader); + EXPECT_TRUE(result == bytes); + reader.reset(); + EXPECT_EQ(ca_tx.inlineCandidateReservedBytesForTest(), 0); +} + +TEST(CASInlineCandidateMemory, FailedRegistrationReturnsTheMemoryReservation) +{ + auto storage = openStorage(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const auto path = table_dir + "all_1_1_0/dict.dct.idx"; + ca_tx.failNextFileRegistrationForTest(); + EXPECT_THROW(writeFileTx(*tx, path, payload(600 * kib, 51)), DB::Exception); + EXPECT_EQ(ca_tx.inlineCandidateReservedBytesForTest(), 0); + EXPECT_FALSE(ca_tx.tryGetInFlightFileSize(path).has_value()); + writeFileTx(*tx, path, "retry"); + tx->commit(DB::NoCommitOptions{}); + EXPECT_EQ(readPartFile(*storage, path), "retry"); +} + +TEST(CASInlineCandidateMemory, FailedLocalSpillReleasesAnOpenWritersReservation) +{ + using namespace DB; + auto budget = std::make_shared(4 * kib); + Cas::InlineCandidateWriteBuffer writer( + "pressure.idx", 64 * kib, mib, budget, + []() -> std::unique_ptr { throw std::runtime_error("injected local staging failure"); }, + [](Cas::InlineCandidatePayloadPtr) { FAIL() << "failed write was finalized"; }); + + const std::string block(3 * kib, 'a'); + writer.write(block.data(), block.size()); + const auto allocated = budget->reservedBytes(); + writer.next(); + EXPECT_EQ(budget->reservedBytes(), allocated); + EXPECT_GE(allocated, block.size()); + EXPECT_THROW(writer.write(block.data(), block.size()), std::runtime_error); + EXPECT_TRUE(writer.isCanceled()); + EXPECT_EQ(budget->reservedBytes(), 0); +} diff --git a/src/Disks/tests/gtest_cas_s3_staging.cpp b/src/Disks/tests/gtest_cas_s3_staging.cpp index 1437f7f9f0ca..6589aa97c92c 100644 --- a/src/Disks/tests/gtest_cas_s3_staging.cpp +++ b/src/Disks/tests/gtest_cas_s3_staging.cpp @@ -881,6 +881,45 @@ TEST(CASS3Staging, ReadYourWritesReturnsStagedBytesFromS3StagingObject) EXPECT_EQ(got, payload); } +TEST(CASS3Staging, OpenBlobReaderKeepsStagingObjectThroughCommitOrAbort) +{ + for (bool commit : {false, true}) + { + SCOPED_TRACE(commit); + auto objects = makeFakeNativeCopyStorage(/*native_only_copy_supported=*/true); + auto storage = makeS3StagingMetadataStorageForTest(objects, "mountReaderLifetime"); + storage->startup(); + auto tx = storage->createTransaction(); + const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/data.bin"; + String bytes(64 * 1024, 'a'); + bytes.back() = 'z'; + writeThroughS3Transaction(dynamic_cast(*tx), path, bytes); + + DB::RelativePathsWithMetadata staged; + objects->listObjects(storage->stagingKeyPrefix(), staged, /*max_keys=*/0); + ASSERT_EQ(staged.size(), 1u); + const DB::StoredObject key(staged.front()->relative_path); + DB::ReadSettings settings; + settings.local_fs_settings.buffer_size = 4096; + auto reader = tx->tryReadFileInFlight(path, settings, {}); + ASSERT_NE(reader, nullptr); + char byte; + reader->readStrict(&byte, 1); + EXPECT_EQ(byte, 'a'); + if (commit) + tx->commit(DB::NoCommitOptions{}); + tx.reset(); + + /// The fake store can read an unlinked file through an open descriptor. S3 needs the key for a later range GET. + ASSERT_TRUE(objects->exists(key)); + reader->seek(bytes.size() - 1, SEEK_SET); + reader->readStrict(&byte, 1); + EXPECT_EQ(byte, 'z'); + reader.reset(); + EXPECT_FALSE(objects->exists(key)); + } +} + TEST(CASS3Staging, OversizedInlineCandidateKeepsLocalStaging) { auto objects = makeFakeNativeCopyStorage(/*native_only_copy_supported=*/true); From daaa834da5a62f9b9a578f6454d6cb9d847ca4ea Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Mon, 30 Nov 2026 18:55:49 +0100 Subject: [PATCH 2/8] Test transaction-wide CAS inline memory budgeting Cover the last available byte and its reuse, hardlinks from published parts under memory pressure, and placement when the same dictionary files spill to local staging in different orders. Check that an open reader keeps its S3 staging object through commit or abort. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- src/Disks/tests/gtest_cas_inline_cap_gaps.cpp | 179 ++++++++++++++++++ src/Disks/tests/gtest_cas_s3_staging.cpp | 78 ++++---- 2 files changed, 218 insertions(+), 39 deletions(-) diff --git a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp index c0aa36c38df5..3a869ae8075b 100644 --- a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -6,15 +6,28 @@ #include #include #include +#include +#include #include #include +#include #include #include +#include + +#include +#include #include #include #include +namespace ProfileEvents +{ + extern const Event CASInlineWriteMemoryBudgetSpills; + extern const Event CASManifestInlineEntriesSelectedForBlob; +} + namespace DB::ErrorCodes { extern const int INCORRECT_DATA; @@ -699,6 +712,110 @@ TEST(CASInlineCandidateMemory, ThresholdPreservesPlacementAndPayload) expectBlob(*storage, ref, "over.idx", over_limit); } +TEST(CASInlineCandidateMemory, LastAvailableByteCanBeReservedAndReused) +{ + using namespace DB; + auto budget = std::make_shared(1); + Cas::InlineCandidatePayloadPtr retained; + size_t spills = 0; + auto write_one_byte = [&](char byte) + { + Cas::InlineCandidateWriteBuffer writer( + "count.txt", + 64 * kib, + mib, + budget, + [&] + { + ++spills; + return std::make_unique(); + }, + [&](Cas::InlineCandidatePayloadPtr bytes) { retained = std::move(bytes); }); + writer.write(byte); + writer.finalize(); + }; + + write_one_byte('1'); + ASSERT_NE(retained, nullptr); + EXPECT_EQ(retained->view(), "1"); + EXPECT_EQ(budget->reservedBytes(), 1); + EXPECT_EQ(spills, 0); + + write_one_byte('2'); + EXPECT_EQ(retained->view(), "1"); + EXPECT_EQ(budget->reservedBytes(), 1); + EXPECT_EQ(spills, 1); + + retained.reset(); + EXPECT_EQ(budget->reservedBytes(), 0); + write_one_byte('3'); + ASSERT_NE(retained, nullptr); + EXPECT_EQ(retained->view(), "3"); + EXPECT_EQ(budget->reservedBytes(), 1); + EXPECT_EQ(spills, 1); +} + +TEST(CASInlineCandidateMemory, PublishedInlineHardlinkPreservesNestedFilesAtAnyBudget) +{ + const std::string dictionary = "skp_idx_msg.dct.idx"; + const std::string segment = segmentFile(0, "msg", ".dct"); + const std::string source = table_dir + "all_1_1_0/" + dictionary; + const std::string destination = table_dir + "tmp_mut_all_1_1_0_2/"; + const auto bytes = payload(600 * kib, 71); + + for (const bool fill_budget : {false, true}) + { + SCOPED_TRACE(fill_budget); + auto storage = openStorage(); + auto setup = storage->createTransaction(); + writeFileTx(*setup, source, bytes); + writeFileTx(*setup, destination + segment, "original segment"); + setup->commit(DB::NoCommitOptions{}); + ASSERT_TRUE(storage->tryGetInManifestBytes(source) == bytes); + + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + std::vector> pressure; + if (fill_budget) + { + const std::string block(mib, 'x'); + size_t reserved = 0; + while (reserved < inline_total_budget) + { + /// Leave room for the old and new allocations while this writer grows. + const size_t remaining = inline_total_budget - reserved; + const size_t size = std::min(mib, std::max(remaining / 2, 1)); + auto writer = ca_tx.writeFile( + table_dir + "all_2_2_0/" + std::to_string(pressure.size()) + ".idx", size, DB::WriteMode::Rewrite, {}); + writer->write(block.data(), size); + writer->sync(); + pressure.emplace_back(std::move(writer)); + const size_t now = ca_tx.inlineCandidateReservedBytesForTest(); + ASSERT_GT(now, reserved); + ASSERT_LE(now, inline_total_budget); + reserved = now; + } + } + ASSERT_EQ(ca_tx.inlineCandidateReservedBytesForTest(), fill_budget ? inline_total_budget : 0); + + const auto link = destination + dictionary; + tx->createHardLink(source, link); + auto reader = ca_tx.tryReadFileInFlight(link, {}, {}); + ASSERT_NE(reader, nullptr); + std::string result; + DB::readStringUntilEOF(result, *reader); + EXPECT_TRUE(result == bytes); + reader.reset(); + + for (auto & writer : pressure) + writer->cancel(); + tx->commit(DB::NoCommitOptions{}); + EXPECT_TRUE(storage->tryGetInManifestBytes(link) == bytes); + EXPECT_TRUE(readPartFile(*storage, source) == bytes); + EXPECT_EQ(readPartFile(*storage, destination + segment), "original segment"); + } +} + TEST(CASInlineCandidateMemory, OpenAndFinalizedWritersShareOneBudgetAcrossParts) { auto storage = openStorage(); @@ -732,6 +849,68 @@ TEST(CASInlineCandidateMemory, OpenAndFinalizedWritersShareOneBudgetAcrossParts) EXPECT_TRUE(std::filesystem::is_empty(storage->scratchPath())); } +TEST(CASInlineCandidateMemory, ManifestPlacementIsIndependentOfLocalSpillOrder) +{ + constexpr size_t file_count = 64; + constexpr size_t file_size = 600 * kib; + constexpr size_t inline_count = inline_total_budget / file_size; + constexpr size_t blob_count = file_count - inline_count; + const auto filename = [](size_t i) { return fmt::format("skp_idx_msg_{:02}.dct.idx", i); }; + + std::array, 2> in_memory{}; + for (size_t pass = 0; pass < in_memory.size(); ++pass) + { + SCOPED_TRACE(pass); + auto storage = openStorage(); + const std::string ref = "all_1_1_0"; + const std::string dir = table_dir + ref + "/"; + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const auto & events = DB::CurrentThread::getProfileEvents(); + const auto spills_before = events[ProfileEvents::CASInlineWriteMemoryBudgetSpills]; + size_t reserved = 0; + for (size_t n = 0; n < file_count; ++n) + { + const size_t i = pass == 0 ? n : file_count - 1 - n; + writeFileTx(*tx, dir + filename(i), payload(file_size, i)); + const size_t after = ca_tx.inlineCandidateReservedBytesForTest(); + ASSERT_LE(after, inline_total_budget); + ASSERT_GE(after, reserved); + in_memory[pass][i] = after > reserved; + reserved = after; + } + + const auto disk_files = std::ranges::count(in_memory[pass], false); + ASSERT_TRUE(std::filesystem::is_directory(storage->scratchPath())); + EXPECT_EQ(std::ranges::distance(std::filesystem::directory_iterator(storage->scratchPath())), disk_files); + EXPECT_EQ(events[ProfileEvents::CASInlineWriteMemoryBudgetSpills] - spills_before, static_cast(disk_files)); + const auto selected_before = events[ProfileEvents::CASManifestInlineEntriesSelectedForBlob]; + tx->commit(DB::NoCommitOptions{}); + EXPECT_EQ(events[ProfileEvents::CASManifestInlineEntriesSelectedForBlob] - selected_before, blob_count); + + const auto manifest = manifestOf(*storage, uuid, ref); + ASSERT_EQ(manifest.entries.size(), file_count); + EXPECT_EQ(inlineTotal(manifest), inline_count * file_size); + for (size_t i = 0; i < file_count; ++i) + { + const auto name = filename(i); + const auto * entry = DB::Cas::findEntry(manifest.entries, name); + ASSERT_NE(entry, nullptr) << name; + /// Equal sizes make the relative path the tie-breaker. The first names must become blobs in both runs. + EXPECT_EQ(entry->placement, i < blob_count ? DB::Cas::EntryPlacement::Blob : DB::Cas::EntryPlacement::Inline) << name; + EXPECT_TRUE(readPartFile(*storage, dir + name) == payload(file_size, i)) << name; + } + const std::string order = pass == 0 ? "forward_" : "reverse_"; + ::testing::Test::RecordProperty(order + "reserved_before_commit", std::to_string(reserved)); + ::testing::Test::RecordProperty(order + "local_files", std::to_string(disk_files)); + } + + /// Both final placements include a file that changed its staging source when written in reverse order. + const auto & [forward, reverse] = in_memory; + EXPECT_FALSE(std::equal(forward.begin(), forward.begin() + blob_count, reverse.begin())); + EXPECT_FALSE(std::equal(forward.begin() + blob_count, forward.end(), reverse.begin() + blob_count)); +} + TEST(CASInlineCandidateMemory, LocalSpillCanStillBecomeInlineAndReadersRetainTheirSource) { auto storage = openStorage(); diff --git a/src/Disks/tests/gtest_cas_s3_staging.cpp b/src/Disks/tests/gtest_cas_s3_staging.cpp index 6589aa97c92c..20a43bb52996 100644 --- a/src/Disks/tests/gtest_cas_s3_staging.cpp +++ b/src/Disks/tests/gtest_cas_s3_staging.cpp @@ -881,45 +881,6 @@ TEST(CASS3Staging, ReadYourWritesReturnsStagedBytesFromS3StagingObject) EXPECT_EQ(got, payload); } -TEST(CASS3Staging, OpenBlobReaderKeepsStagingObjectThroughCommitOrAbort) -{ - for (bool commit : {false, true}) - { - SCOPED_TRACE(commit); - auto objects = makeFakeNativeCopyStorage(/*native_only_copy_supported=*/true); - auto storage = makeS3StagingMetadataStorageForTest(objects, "mountReaderLifetime"); - storage->startup(); - auto tx = storage->createTransaction(); - const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/data.bin"; - String bytes(64 * 1024, 'a'); - bytes.back() = 'z'; - writeThroughS3Transaction(dynamic_cast(*tx), path, bytes); - - DB::RelativePathsWithMetadata staged; - objects->listObjects(storage->stagingKeyPrefix(), staged, /*max_keys=*/0); - ASSERT_EQ(staged.size(), 1u); - const DB::StoredObject key(staged.front()->relative_path); - DB::ReadSettings settings; - settings.local_fs_settings.buffer_size = 4096; - auto reader = tx->tryReadFileInFlight(path, settings, {}); - ASSERT_NE(reader, nullptr); - char byte; - reader->readStrict(&byte, 1); - EXPECT_EQ(byte, 'a'); - if (commit) - tx->commit(DB::NoCommitOptions{}); - tx.reset(); - - /// The fake store can read an unlinked file through an open descriptor. S3 needs the key for a later range GET. - ASSERT_TRUE(objects->exists(key)); - reader->seek(bytes.size() - 1, SEEK_SET); - reader->readStrict(&byte, 1); - EXPECT_EQ(byte, 'z'); - reader.reset(); - EXPECT_FALSE(objects->exists(key)); - } -} - TEST(CASS3Staging, OversizedInlineCandidateKeepsLocalStaging) { auto objects = makeFakeNativeCopyStorage(/*native_only_copy_supported=*/true); @@ -1560,6 +1521,45 @@ TEST(CASS3Staging, ListPageOverANonPagingStoreStillReportsMoreKeys) EXPECT_TRUE(rest.next_cursor.empty()); } +TEST(CASS3Staging, OpenBlobReaderKeepsStagingObjectThroughCommitOrAbort) +{ + for (bool commit : {false, true}) + { + SCOPED_TRACE(commit); + auto objects = makeFakeGenerationObjectStorageForTest(); + objects->content_derived_etags = true; + auto storage = makeS3StagingMetadataStorageForTest(objects, "mountReaderLifetime"); + storage->startup(); + auto tx = storage->createTransaction(); + const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/data.bin"; + String bytes(64 * 1024, 'a'); + bytes.back() = 'z'; + writeThroughS3Transaction(dynamic_cast(*tx), path, bytes); + + DB::RelativePathsWithMetadata staged; + objects->listObjects(storage->stagingKeyPrefix(), staged, /*max_keys=*/0); + ASSERT_EQ(staged.size(), 1u); + const DB::StoredObject key(staged.front()->relative_path); + auto reader = tx->tryReadFileInFlight(path, DB::ReadSettings{}, {}); + ASSERT_NE(reader, nullptr); + char byte; + reader->readStrict(&byte, 1); + EXPECT_EQ(byte, 'a'); + if (commit) + tx->commit(DB::NoCommitOptions{}); + tx.reset(); + + EXPECT_EQ(objects->copiesByDestination().size(), commit ? 1u : 0u); + /// The in-memory reader retains a copy. A later S3 range GET also needs the staging key to exist. + ASSERT_TRUE(objects->exists(key)); + reader->seek(bytes.size() - 1, SEEK_SET); + reader->readStrict(&byte, 1); + EXPECT_EQ(byte, 'z'); + reader.reset(); + EXPECT_FALSE(objects->exists(key)); + } +} + TEST(CASS3Staging, GenerationBackendMayUseNativeOnlyCopy) { auto object_storage = makeFakeGenerationObjectStorageForTest(); From 291e93504dff788635f78aa4eec76d06ccb16fa2 Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Mon, 30 Nov 2026 18:56:02 +0100 Subject: [PATCH 3/8] Release the staging source after materializing a CAS inline entry Once the manifest entry owns the file bytes, erase its path from the transaction's staging map. This lets unshared payloads release their memory before manifest encoding. An open reader or a hardlink can still hold the source independently. Check all three lifetimes during publication, including a hardlink whose destination needs the same bytes for blob placement. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- .../ContentAddressedTransaction.cpp | 2 + src/Disks/tests/gtest_cas_inline_cap_gaps.cpp | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index c5d3c845ca93..7296f94ca85d 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -478,6 +478,8 @@ std::vector ContentAddressedTransaction::applyManifestIn } entry->placement = Cas::EntryPlacement::Inline; entry->blob_size = 0; + /// The entry now owns its bytes. Hardlinks and open readers retain their own references to the staging source. + st.staged_part_files.erase(entry->path); } } diff --git a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp index 3a869ae8075b..b3485050800d 100644 --- a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -21,6 +21,7 @@ #include #include #include +#include namespace ProfileEvents { @@ -951,6 +952,55 @@ TEST(CASInlineCandidateMemory, LocalSpillCanStillBecomeInlineAndReadersRetainThe EXPECT_TRUE(std::filesystem::is_empty(storage->scratchPath())); } +TEST(CASInlineCandidateMemory, InlinePlacementReleasesOnlyTheMaterializedPath) +{ + auto storage = openStorage(); + const std::string src_ref = "all_1_1_0"; + const std::string dst_ref = "all_2_2_0"; + const auto src = table_dir + src_ref + "/"; + const auto dst = table_dir + dst_ref; + { + auto setup = storage->createTransaction(); + writeFullBudget(*setup, dst); + setup->commit(DB::NoCommitOptions{}); + } + + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const auto reader_bytes = payload(600 * kib, 41); + writeFileTx(*tx, src + "reader.idx", reader_bytes); + const size_t reader_reservation = ca_tx.inlineCandidateReservedBytesForTest(); + ASSERT_GE(reader_reservation, reader_bytes.size()); + auto reader = ca_tx.tryReadFileInFlight(src + "reader.idx", {}, {}); + ASSERT_NE(reader, nullptr); + + const auto linked_bytes = payload(600 * kib, 42); + writeFileTx(*tx, src + "source.idx", linked_bytes); + tx->createHardLink(src + "source.idx", dst + "/link.idx"); + const size_t shared_reservations = ca_tx.inlineCandidateReservedBytesForTest(); + ASSERT_GE(shared_reservations, reader_reservation + linked_bytes.size()); + const auto unshared_bytes = payload(600 * kib, 43); + writeFileTx(*tx, src + "unshared.idx", unshared_bytes); + ASSERT_GT(ca_tx.inlineCandidateReservedBytesForTest(), shared_reservations); + + /// The source part publishes first. Only the open reader and the destination hardlink still need their sources. + std::optional reserved_after_source_publish; + storage->setAfterPromoteHookForTest( + {storage->liveNamespace(uuid), src_ref}, [&] { reserved_after_source_publish = ca_tx.inlineCandidateReservedBytesForTest(); }); + tx->commit(DB::NoCommitOptions{}); + EXPECT_EQ(reserved_after_source_publish, shared_reservations); + EXPECT_TRUE(storage->tryGetInManifestBytes(src + "unshared.idx") == unshared_bytes); + EXPECT_TRUE(storage->tryGetInManifestBytes(src + "source.idx") == linked_bytes); + expectBlob(*storage, dst_ref, "link.idx", linked_bytes); + EXPECT_EQ(ca_tx.inlineCandidateReservedBytesForTest(), reader_reservation); + + std::string result; + DB::readStringUntilEOF(result, *reader); + EXPECT_TRUE(result == reader_bytes); + reader.reset(); + EXPECT_EQ(ca_tx.inlineCandidateReservedBytesForTest(), 0); +} + TEST(CASInlineCandidateMemory, HardlinkSharesOneReservationUntilTheLastOwnerReleasesIt) { auto storage = openStorage(); From ba4225ad449f16e98318e702b41d2fca0c29073b Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Wed, 2 Dec 2026 16:16:34 +0100 Subject: [PATCH 4/8] Make CAS manifest entry registration explicit about its source Register copied inline bytes, finalized staged files, and borrowed blobs through separate paths. Hardlinks and moves carry the original source to the destination path. Use hash maps for the two path lookups and retain the commit-time check for a blob with no known source. Signed-off-by: Konstantin Morozov Co-authored-by: Codex (GPT-6) --- .../ContentAddressedTransaction.cpp | 195 ++++++++++++------ .../ContentAddressedTransaction.h | 31 ++- 2 files changed, 154 insertions(+), 72 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index b01c38e98276..3429b35103fe 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -231,11 +232,11 @@ ContentAddressedTransaction::PartStaging * ContentAddressedTransaction::findStag namespace { -void removeStagingObject(const ObjectStoragePtr & storage, const String & key) noexcept +void tryRemoveStagingObject(const ObjectStoragePtr & storage, const String & staging_object_key) noexcept { try { - storage->removeObjectIfExists(StoredObject(key)); + storage->removeObjectIfExists(StoredObject(staging_object_key)); } catch (...) { @@ -249,7 +250,7 @@ ContentAddressedTransaction::StagedPartFile::~StagedPartFile() if (!registered || memory) return; if (remote_storage) - removeStagingObject(remote_storage, staging_path); + tryRemoveStagingObject(remote_storage, staging_path); else { std::error_code ec; @@ -260,51 +261,109 @@ ContentAddressedTransaction::StagedPartFile::~StagedPartFile() void ContentAddressedTransaction::releaseStagedFiles() noexcept { for (auto & [key, st] : parts) - st.staged_part_files.clear(); + st.staged_part_files_by_path.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; + const auto it = st.staged_part_files_by_path.find(path); + return it == st.staged_part_files_by_path.end() ? nullptr : it->second; } -void ContentAddressedTransaction::putEntry( - PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source, StagedPartFilePtr file) +namespace +{ +void replaceManifestEntry(std::vector & entries, Cas::ManifestEntry && entry, auto && update_source_maps) { - 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(); + auto it = std::ranges::find(entries, entry.path, &Cas::ManifestEntry::path); + const bool inserted = it == entries.end(); if (inserted) { - st.entries.emplace_back(); - it = std::prev(st.entries.end()); + entries.emplace_back(); + it = std::prev(entries.end()); } - /// Install the possibly allocating map node before retiring the previous path or its source. + + /// Installing a new source can allocate. Keep the previous entry intact until that succeeds. 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); + update_source_maps(entry.path); } catch (...) { if (inserted) - st.entries.pop_back(); + 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::putCopiedInlineEntry(PartStaging & part_staging, Cas::ManifestEntry && entry) +{ + chassert(entry.placement == Cas::EntryPlacement::Inline); + + replaceManifestEntry(part_staging.entries, std::move(entry), [&](const String & path) + { + part_staging.staged_part_files_by_path.erase(path); + part_staging.borrowed_blob_sources_by_path.erase(path); + }); +} + +void ContentAddressedTransaction::putEntryWithStagedFile( + PartStaging & part_staging, Cas::ManifestEntry && entry, StagedPartFilePtr staged_file) +{ + chassert(staged_file); + + replaceManifestEntry(part_staging.entries, std::move(entry), [&](const String & path) + { + part_staging.staged_part_files_by_path.insert_or_assign(path, std::move(staged_file)); + part_staging.borrowed_blob_sources_by_path.erase(path); + }); +} + +void ContentAddressedTransaction::putBorrowedBlobEntry( + PartStaging & part_staging, Cas::ManifestEntry && entry, std::shared_ptr borrowed_blob_source) +{ + chassert(borrowed_blob_source); + chassert(entry.placement == Cas::EntryPlacement::Blob); + + replaceManifestEntry(part_staging.entries, std::move(entry), [&](const String & path) + { + part_staging.borrowed_blob_sources_by_path.insert_or_assign(path, std::move(borrowed_blob_source)); + part_staging.staged_part_files_by_path.erase(path); + }); +} + +void ContentAddressedTransaction::putEntryForHardLinkOrMove( + PartStaging & part_staging, Cas::ManifestEntry && entry, std::shared_ptr borrowed_blob_source, StagedPartFilePtr staged_file) +{ + chassert(!(borrowed_blob_source && staged_file)); + + if (staged_file) + { + putEntryWithStagedFile(part_staging, std::move(entry), std::move(staged_file)); + return; + } + + if (borrowed_blob_source) + { + putBorrowedBlobEntry(part_staging, std::move(entry), std::move(borrowed_blob_source)); + return; + } + + if (entry.placement == Cas::EntryPlacement::Inline) + { + putCopiedInlineEntry(part_staging, std::move(entry)); + return; + } + + UNREACHABLE(); +} 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); + st.borrowed_blob_sources_by_path.erase(path); + st.staged_part_files_by_path.erase(path); } void ContentAddressedTransaction::rekeyEntry(PartStaging & st, Cas::ManifestEntry & entry, std::string new_path) @@ -312,19 +371,19 @@ void ContentAddressedTransaction::rekeyEntry(PartStaging & st, Cas::ManifestEntr auto file = stagedFileOf(st, entry.path); auto source = copySourceOf(st, entry.path); if (file) - st.staged_part_files.emplace(new_path, std::move(file)); + st.staged_part_files_by_path.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); + st.borrowed_blob_sources_by_path.emplace(new_path, std::move(source)); + st.borrowed_blob_sources_by_path.erase(entry.path); + st.staged_part_files_by_path.erase(entry.path); entry.path = std::move(new_path); } void ContentAddressedTransaction::clearEntries(PartStaging & st) { st.entries.clear(); - st.copy_sources.clear(); - st.staged_part_files.clear(); + st.borrowed_blob_sources_by_path.clear(); + st.staged_part_files_by_path.clear(); st.has_finalized_file_write = false; } @@ -342,8 +401,8 @@ void ContentAddressedTransaction::markVacatedInBase( std::shared_ptr ContentAddressedTransaction::copySourceOf(const PartStaging & st, const std::string & path) { - const auto it = st.copy_sources.find(path); - if (it == st.copy_sources.end()) + const auto it = st.borrowed_blob_sources_by_path.find(path); + if (it == st.borrowed_blob_sources_by_path.end()) return nullptr; return it->second; } @@ -480,7 +539,7 @@ std::vector ContentAddressedTransaction::applyManifestIn } else if (entry->placement == Cas::EntryPlacement::Blob) { - const auto & file = st.staged_part_files.at(entry->path); + const auto & file = st.staged_part_files_by_path.at(entry->path); if (file->memory) entry->inline_bytes.assign(file->memory->view()); else @@ -495,7 +554,7 @@ std::vector ContentAddressedTransaction::applyManifestIn entry->placement = Cas::EntryPlacement::Inline; entry->blob_size = 0; /// The entry now owns its bytes. Hardlinks and open readers retain their own references to the staging source. - st.staged_part_files.erase(entry->path); + st.staged_part_files_by_path.erase(entry->path); } } @@ -808,7 +867,7 @@ void ContentAddressedTransaction::commit(const TransactionCommitOptionsVariant & /// A projection of the new part keeps this transaction for the part's life; the sources were needed only to publish. copy_sources_by_part.clear(); for (auto & [key, st] : parts) - st.copy_sources.clear(); + st.borrowed_blob_sources_by_path.clear(); /// 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; @@ -989,48 +1048,50 @@ void ContentAddressedTransaction::createMetadataFile(const std::string &, const notYet("createMetadataFile"); } -void ContentAddressedTransaction::registerStagedFile( - const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::shared_ptr & file) +void ContentAddressedTransaction::registerFinalizedPartFile( + const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::shared_ptr & staged_file) { std::lock_guard lock(file_registration_mutex); - auto & st = stagingFor(route); - const bool had_build = bool(st.build); - buildFor(route, st); + auto & part_staging = stagingFor(route); + const bool had_build = bool(part_staging.build); + buildFor(route, part_staging); SCOPE_EXIT({ - if (!had_build && !file->registered) - st.build.reset(); + if (!had_build && !staged_file->registered) + part_staging.build.reset(); }); if (std::exchange(fail_next_file_registration, false)) throw Exception(ErrorCodes::ABORTED, "Injected failure registering staged file {}", route.file); - file->allow_inline_by_name = !Cas::partFileMustStayBlob(route.file); + staged_file->allow_inline_by_name = !Cas::partFileMustStayBlob(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); + putEntryWithStagedFile(part_staging, std::move(entry), staged_file); - file->registered = true; - st.has_finalized_file_write = true; + staged_file->registered = true; + part_staging.has_finalized_file_write = true; } 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, ObjectStoragePtr remote_storage, const String & pool_staging_key) { /// The local writer still owns its scratch path if registration throws. The S3 sink /// has already finalized the object, so this callback cleans it up on failure. try { - auto file = std::make_shared(); - file->staging_path = staging_key; - file->remote_storage = remote_storage; - file->pool_staging_key = pool_key; - registerStagedFile(route, ref, size, file); + auto staged_file = std::make_shared(); + staged_file->staging_path = staging_key; + staged_file->remote_storage = remote_storage; + staged_file->pool_staging_key = pool_staging_key; + + registerFinalizedPartFile(route, ref, size, staged_file); } catch (...) { if (remote_storage) - removeStagingObject(remote_storage, staging_key); + tryRemoveStagingObject(remote_storage, staging_key); throw; } } @@ -1045,14 +1106,17 @@ void ContentAddressedTransaction::stageUnprovenBlobEntryForTest(const std::strin const auto route = routeOf(path); if (!route || route->file.empty()) throw Exception(ErrorCodes::LOGICAL_ERROR, "ContentAddressed: {} is not a part file", path); + auto & st = stagingFor(*route); (void)buildFor(*route, st); + 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); + + st.entries.push_back(std::move(entry)); } std::shared_ptr ContentAddressedTransaction::borrowedSourceForTest(const std::string & part_path) const @@ -1208,9 +1272,10 @@ std::unique_ptr ContentAddressedTransaction::writeFile( 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 pool_staging_key = pool->layout().stagingKey(metadata_storage.serverRootId(), incarnation.writer_epoch, leaf); const auto staging_key = metadata_storage.stagingKey(incarnation.writer_epoch, leaf); const auto remote_storage = metadata_storage.objectStorage(); + auto object_sink = remote_storage->writeObject(StoredObject(staging_key), WriteMode::Rewrite); return std::make_unique( @@ -1221,10 +1286,10 @@ 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 std::string & hash_hex, size_t size, const std::string & key) + [this, route = *r, hash_algo, remote_storage, pool_staging_key](const std::string & hash_hex, size_t size, const std::string & staging_object_key) { const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; - stageBlobPartFile(route, ref, size, key, remote_storage, pool_key); + stageBlobPartFile(route, ref, size, staging_object_key, remote_storage, pool_staging_key); }, [pool, generation = incarnation.fence_generation] { pool->checkFenceOrThrow(generation); }); } @@ -1257,7 +1322,8 @@ std::unique_ptr ContentAddressedTransaction::writeFile( const auto ref = Cas::poolContentHash(hash_algo, bytes); auto file = std::make_shared(); file->memory = std::move(payload); - registerStagedFile(route, ref, bytes.size(), file); + + registerFinalizedPartFile(route, ref, bytes.size(), file); }); } @@ -1463,7 +1529,8 @@ void ContentAddressedTransaction::createHardLink(const std::string & path_from, if (!file) build.adoptEvidence(entry); entry.path = dst->file; - putEntry(dst_st, std::move(entry), std::move(source), std::move(file)); + + putEntryForHardLinkOrMove(dst_st, std::move(entry), std::move(source), std::move(file)); return; } } @@ -1479,15 +1546,18 @@ void ContentAddressedTransaction::createHardLink(const std::string & path_from, auto & borrowed = copy_sources_by_part[src->refKey().cacheKey()]; if (!borrowed || !(borrowed->manifest_ref == resolved->manifest_ref)) borrowed = std::make_shared(std::move(*resolved)); + const auto * src_entry = Cas::findEntry(borrowed->manifest->entries, src->file); if (!src_entry) throw Exception(ErrorCodes::FILE_DOESNT_EXIST, "ContentAddressed: createHardLink source file missing in manifest: {}", path_from); + buildFor(*dst, dst_st).adoptEvidence(*src_entry); entry = *src_entry; entry.path = dst->file; auto source = entry.placement == Cas::EntryPlacement::Blob ? borrowed : nullptr; - putEntry(dst_st, std::move(entry), std::move(source)); + + putEntryForHardLinkOrMove(dst_st, std::move(entry), std::move(source), {}); } void ContentAddressedTransaction::setLastModified(const std::string &, const Poco::Timestamp &) @@ -1666,7 +1736,7 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c { 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)); + putEntryForHardLinkOrMove(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. @@ -1862,7 +1932,8 @@ void ContentAddressedTransaction::moveFile(const std::string & path_from, const } entry.path = dst->file; markVacatedInBase(*src, src_st, {src->file}); - putEntry(dst_st, std::move(entry), std::move(source), std::move(file)); + + putEntryForHardLinkOrMove(dst_st, std::move(entry), std::move(source), std::move(file)); eraseEntry(src_st, src->file); return; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index f2adfa2ddf2b..ac4b9dcb970a 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -168,10 +169,9 @@ class ContentAddressedTransaction : public IMetadataTransaction std::vector entries; /// staged manifest entries (uploads + adoptions) /// The committed source of each entry in `entries` adopted without reading its body, keyed by entry path. /// It follows the entry through staged copies and renames; `confirmCopySources` checks it before promote. - /// Written only by `putEntry`, `eraseEntry`, `rekeyEntry` and `clearEntries`, which keep it in step with `entries`, - /// until a successful `commit` clears it. + /// Adding, replacing, renaming or removing an entry keeps this map in step with `entries`. A successful commit clears it. /// Entries borrowed from one source share one handle (`copy_sources_by_part`). - std::map> copy_sources; + std::unordered_map> borrowed_blob_sources_by_path; /// The committed manifest this transaction found under the part's name when it first staged a /// write to it; a later commit requires exactly that binding. Empty for a part the transaction /// creates (`tmp_*`), where a committed row at commit time is somebody else's part, not ours, @@ -185,7 +185,7 @@ class ContentAddressedTransaction : public IMetadataTransaction /// 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; + std::unordered_map staged_part_files_by_path; bool has_finalized_file_write = false; /// A build opened only for a transfer cannot replace the temporary segment ref. }; @@ -210,21 +210,32 @@ class ContentAddressedTransaction : public IMetadataTransaction /// Cleared in `commit()`'s epilogue. std::unordered_set force_fresh_validated_refs; - void registerStagedFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, - const std::shared_ptr & file); + void registerFinalizedPartFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, + const std::shared_ptr & staged_file); /// Transfer the writer's private file or S3 object only on successful registration. 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); + ObjectStoragePtr remote_storage, const String & pool_staging_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 /// stays a verbatim server-side copy. `build_id` is left 0 (not known at stream time; diagnostic-only). 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 = {}); + /// An Inline entry copied from a committed manifest already contains its file bytes. + static void putCopiedInlineEntry(PartStaging & part_staging, Cas::ManifestEntry && entry); + + /// A writer finalized the file in this transaction. Keep its bytes in memory or staging for this path and any hardlinks. + static void putEntryWithStagedFile(PartStaging & part_staging, Cas::ManifestEntry && entry, StagedPartFilePtr staged_file); + + /// A hardlink reuses a Blob entry from a committed manifest. Keep the source so commit can confirm the borrowed blob. + static void putBorrowedBlobEntry( + PartStaging & part_staging, Cas::ManifestEntry && entry, std::shared_ptr borrowed_blob_source); + + /// Hardlinks and moves carry the original file or copy source to the destination path. An entry can have at most one. + static void putEntryForHardLinkOrMove( + PartStaging & part_staging, Cas::ManifestEntry && entry, std::shared_ptr borrowed_blob_source, StagedPartFilePtr staged_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); From db96369f203e5200a8986775988ae06e108e3162 Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Wed, 2 Dec 2026 17:26:31 +0100 Subject: [PATCH 5/8] Extract CAS manifest placement conversions and test staging corruption Keep inline budget selection separate from converting a manifest entry between inline bytes and a blob reference. Cover the local staging read by changing one byte after finalization and checking that commit reports `CORRUPTED_DATA` and leaves the new part unpublished. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- .../ContentAddressedTransaction.cpp | 121 ++++++++++-------- .../ContentAddressedTransaction.h | 9 +- src/Disks/tests/gtest_cas_inline_cap_gaps.cpp | 65 ++++++++-- 3 files changed, 133 insertions(+), 62 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index 3429b35103fe..3fc74d60d007 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -247,7 +247,7 @@ void tryRemoveStagingObject(const ObjectStoragePtr & storage, const String & sta ContentAddressedTransaction::StagedPartFile::~StagedPartFile() { - if (!registered || memory) + if (!registered || in_memory_payload) return; if (remote_storage) tryRemoveStagingObject(remote_storage, staging_path); @@ -492,25 +492,67 @@ ContentAddressedTransaction::routeOf(const std::string & path) const return metadata_storage.route(*p); } +void ContentAddressedTransaction::convertInlineEntryToBlob( + Cas::ManifestEntry & entry, Cas::BlobHashAlgo hash_algo, std::vector & blob_upload_requests) +{ + chassert(entry.placement == Cas::EntryPlacement::Inline); + + /// A borrowed Inline has no staging file. Its bytes came from the committed manifest. + const auto size = entry.inline_bytes.size(); + entry.ref = Cas::poolContentHash(hash_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; +} + +void ContentAddressedTransaction::convertBlobEntryToInline( + Cas::ManifestEntry & entry, PartStaging & part_staging, const Cas::PoolPtr & pool) +{ + chassert(entry.placement == Cas::EntryPlacement::Blob); + + const auto & staged_file = part_staging.staged_part_files_by_path.at(entry.path); + + if (staged_file->in_memory_payload) + entry.inline_bytes.assign(staged_file->in_memory_payload->view()); + else + { + auto input = openStagedPayload(staged_file, entry.blob_size, pool); + String bytes(entry.blob_size, '\0'); + + input->readStrict(bytes.data(), 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.inline_bytes = std::move(bytes); + } + + entry.placement = Cas::EntryPlacement::Inline; + entry.blob_size = 0; + /// The entry now owns its bytes. Hardlinks and open readers retain their own references to the staging source. + part_staging.staged_part_files_by_path.erase(entry.path); +} + std::vector ContentAddressedTransaction::applyManifestInlineBudget( - PartStaging & st, uint64_t inline_bytes_from_unchanged_base_entries) const + PartStaging & part_staging, const uint64_t inline_bytes_from_unchanged_base_entries) const { const auto pool = metadata_storage.store(); - uint64_t total_inline_bytes = inline_bytes_from_unchanged_base_entries; - std::vector candidates; + uint64_t inline_bytes_with_candidates = inline_bytes_from_unchanged_base_entries; + std::vector inline_placement_candidates; - for (auto & entry : st.entries) + for (auto & entry : part_staging.entries) { - const auto file = stagedFileOf(st, entry.path); - if (entry.placement == Cas::EntryPlacement::Inline || (file && file->allow_inline_by_name && entry.blob_size <= Cas::kMaxManifestInlineEntryBytes)) + const auto staged_file = stagedFileOf(part_staging, entry.path); + if (entry.placement == Cas::EntryPlacement::Inline || (staged_file && staged_file->allow_inline_by_name && entry.blob_size <= Cas::kMaxManifestInlineEntryBytes)) { - candidates.push_back(&entry); - total_inline_bytes += entry.size(); + inline_placement_candidates.push_back(&entry); + inline_bytes_with_candidates += entry.size(); } } - if (total_inline_bytes > Cas::kMaxManifestInlineBytesTotal) - std::sort(candidates.begin(), candidates.end(), [](const auto * lhs, const auto * rhs) + if (inline_bytes_with_candidates > Cas::kMaxManifestInlineBytesTotal) + std::sort(inline_placement_candidates.begin(), inline_placement_candidates.end(), [](const auto * lhs, const auto * rhs) { if (lhs->size() != rhs->size()) return lhs->size() > rhs->size(); @@ -518,48 +560,23 @@ std::vector ContentAddressedTransaction::applyManifestIn }); std::vector blob_upload_requests; - size_t spilled = 0; + size_t entries_selected_for_blob = 0; - for (auto * entry : candidates) + for (auto * inline_candidate_entry : inline_placement_candidates) { - const auto size = entry->size(); - - if (total_inline_bytes > Cas::kMaxManifestInlineBytesTotal) + if (inline_bytes_with_candidates > 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) - { - const auto & file = st.staged_part_files_by_path.at(entry->path); - if (file->memory) - entry->inline_bytes.assign(file->memory->view()); - else - { - auto input = openStagedPayload(file, size, pool); - String bytes(size, '\0'); - input->readStrict(bytes.data(), 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->inline_bytes = std::move(bytes); - } - entry->placement = Cas::EntryPlacement::Inline; - entry->blob_size = 0; - /// The entry now owns its bytes. Hardlinks and open readers retain their own references to the staging source. - st.staged_part_files_by_path.erase(entry->path); + inline_bytes_with_candidates -= inline_candidate_entry->size(); + ++entries_selected_for_blob; + if (inline_candidate_entry->placement == Cas::EntryPlacement::Inline) + convertInlineEntryToBlob(*inline_candidate_entry, pool->writeAlgo(), blob_upload_requests); } + else if (inline_candidate_entry->placement == Cas::EntryPlacement::Blob) + convertBlobEntryToInline(*inline_candidate_entry, part_staging, pool); } - if (spilled) - ProfileEvents::increment(ProfileEvents::CASManifestInlineEntriesSelectedForBlob, spilled); + if (entries_selected_for_blob) + ProfileEvents::increment(ProfileEvents::CASManifestInlineEntriesSelectedForBlob, entries_selected_for_blob); return blob_upload_requests; } @@ -580,8 +597,8 @@ Cas::ManifestId ContentAddressedTransaction::precommitAndUpload( std::unique_ptr ContentAddressedTransaction::openStagedPayload(const StagedPartFilePtr & file, uint64_t size, const Cas::PoolPtr & pool) { - if (file->memory) - return std::make_unique>(file, file->memory->view()); + if (file->in_memory_payload) + return std::make_unique>(file, file->in_memory_payload->view()); if (!file->remote_storage) return Cas::openLocalStagedBlobPayload(file->staging_path, size); @@ -960,9 +977,9 @@ std::unique_ptr ContentAddressedTransaction::tryReadFile { if (auto file = stagedFileOf(it->second, entry->path)) { - if (file->memory) + if (file->in_memory_payload) return std::make_unique>( - file, /*owns_memory=*/false, path, file->memory->view()); + file, /*owns_memory=*/false, path, file->in_memory_payload->view()); if (file->remote_storage) { const auto offset = metadata_storage.store()->poolMeta().blob_header_len; @@ -1321,7 +1338,7 @@ std::unique_ptr ContentAddressedTransaction::writeFile( const auto bytes = payload->view(); const auto ref = Cas::poolContentHash(hash_algo, bytes); auto file = std::make_shared(); - file->memory = std::move(payload); + file->in_memory_payload = std::move(payload); registerFinalizedPartFile(route, ref, bytes.size(), file); }); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index ac4b9dcb970a..9ac835066bbd 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -149,7 +149,7 @@ class ContentAddressedTransaction : public IMetadataTransaction /// owns its reservation until the last holder releases its bytes. struct StagedPartFile { - std::shared_ptr memory; + std::shared_ptr in_memory_payload; 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. @@ -268,7 +268,12 @@ class ContentAddressedTransaction : public IMetadataTransaction Cas::BlobSource stagedUploadSource(const StagedPartFilePtr & file, uint64_t size) const; - std::vector applyManifestInlineBudget(PartStaging & st, uint64_t inline_bytes_from_unchanged_base_entries) const; + static void convertInlineEntryToBlob( + Cas::ManifestEntry & entry, Cas::BlobHashAlgo hash_algo, std::vector & blob_upload_requests); + static void convertBlobEntryToInline(Cas::ManifestEntry & entry, PartStaging & part_staging, const Cas::PoolPtr & pool); + + std::vector applyManifestInlineBudget( + PartStaging & part_staging, 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. diff --git a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp index b3485050800d..fffae575b870 100644 --- a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +32,7 @@ namespace ProfileEvents namespace DB::ErrorCodes { + extern const int CORRUPTED_DATA; extern const int INCORRECT_DATA; } @@ -912,22 +914,34 @@ TEST(CASInlineCandidateMemory, ManifestPlacementIsIndependentOfLocalSpillOrder) EXPECT_FALSE(std::equal(forward.begin() + blob_count, forward.end(), reverse.begin() + blob_count)); } -TEST(CASInlineCandidateMemory, LocalSpillCanStillBecomeInlineAndReadersRetainTheirSource) +namespace { - auto storage = openStorage(); - auto tx = storage->createTransaction(); - auto & ca_tx = dynamic_cast(*tx); - const auto first = table_dir + "all_1_1_0/"; - const auto second = table_dir + "all_2_2_0/"; - const auto bytes = payload(600 * kib, 42); + +std::vector> openWritersToForceLocalSpill( + DB::ContentAddressedTransaction & tx, const std::string & bytes) +{ + const auto directory = table_dir + "all_1_1_0/"; std::vector> writers; /// Hold other candidates open to force at least one local spill under the same transaction. for (size_t i = 0; i < 32; ++i) { - auto writer = ca_tx.writeFile(first + std::to_string(i) + ".idx", 64 * kib, DB::WriteMode::Rewrite, {}); + auto writer = tx.writeFile(directory + std::to_string(i) + ".idx", 64 * kib, DB::WriteMode::Rewrite, {}); writer->write(bytes.data(), bytes.size()); writers.push_back(std::move(writer)); } + return writers; +} + +} + +TEST(CASInlineCandidateMemory, LocalSpillCanStillBecomeInlineAndReadersRetainTheirSource) +{ + auto storage = openStorage(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const auto second = table_dir + "all_2_2_0/"; + const auto bytes = payload(600 * kib, 42); + auto writers = openWritersToForceLocalSpill(ca_tx, bytes); const auto path = second + "dict.dct.idx"; ASSERT_TRUE(std::filesystem::is_directory(storage->scratchPath())); @@ -952,6 +966,41 @@ TEST(CASInlineCandidateMemory, LocalSpillCanStillBecomeInlineAndReadersRetainThe EXPECT_TRUE(std::filesystem::is_empty(storage->scratchPath())); } +TEST(CASInlineCandidateMemory, CorruptedLocalDictionaryDoesNotPublishPart) +{ + auto storage = openStorage(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const std::string ref = "all_2_2_0"; + const auto ns = storage->liveNamespace(uuid); + ASSERT_FALSE(storage->store()->resolveRef(ns, ref)); + + const std::string bytes(600 * kib, 'd'); + auto writers = openWritersToForceLocalSpill(ca_tx, bytes); + writeFileTx(*tx, table_dir + ref + "/dict.dct.idx", bytes); + for (auto & writer : writers) + writer->cancel(); + + /// Only the finalized dictionary remains in scratch after cancelling the other writers. + const auto & scratch = storage->scratchPath(); + ASSERT_TRUE(std::filesystem::is_directory(scratch)); + ASSERT_EQ(std::ranges::distance(std::filesystem::directory_iterator(scratch)), 1); + const auto staged_dictionary = std::filesystem::directory_iterator(scratch)->path(); + ASSERT_EQ(std::filesystem::file_size(staged_dictionary), bytes.size()); + + std::fstream file(staged_dictionary, std::ios::binary | std::ios::in | std::ios::out); + ASSERT_EQ(file.get(), 'd'); + file.seekp(0); + file.put('D'); + file.close(); + ASSERT_TRUE(file.good()); + ASSERT_EQ(std::filesystem::file_size(staged_dictionary), bytes.size()); + + DB::Cas::tests::expectThrowsCodeWithMessage( + DB::ErrorCodes::CORRUPTED_DATA, "dict.dct.idx", [&] { tx->commit(DB::NoCommitOptions{}); }); + EXPECT_FALSE(storage->store()->resolveRef(ns, ref)); +} + TEST(CASInlineCandidateMemory, InlinePlacementReleasesOnlyTheMaterializedPath) { auto storage = openStorage(); From 1150da1a5df457093c67db8e8c4e606b445f139d Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Fri, 4 Dec 2026 15:44:15 +0100 Subject: [PATCH 6/8] Skip small compactions of CAS inline candidate buffers Only try to compact an in-memory inline candidate at finalize when at least 1 KiB and 25% of its capacity can be reclaimed. Cover both cutoffs and the 600 KiB dictionary case. Name the staged payload and its callback explicitly, and document when the transaction chooses manifest placement. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- .../ContentAddressedTransaction.cpp | 160 +++++++++--------- .../ContentAddressedTransaction.h | 20 +-- .../CasInlineCandidateWriteBuffer.cpp | 81 +++++---- .../CasInlineCandidateWriteBuffer.h | 25 +-- src/Disks/tests/gtest_cas_inline_cap_gaps.cpp | 35 ++++ 5 files changed, 191 insertions(+), 130 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index 1f20ffde697a..efd85cb70f06 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -246,7 +246,7 @@ void tryRemoveStagingObject(const ObjectStoragePtr & storage, const String & sta } } -ContentAddressedTransaction::StagedPartFile::~StagedPartFile() +ContentAddressedTransaction::StagedPartFilePayload::~StagedPartFilePayload() { if (!registered || in_memory_payload) return; @@ -262,13 +262,13 @@ ContentAddressedTransaction::StagedPartFile::~StagedPartFile() void ContentAddressedTransaction::releaseStagedFiles() noexcept { for (auto & [key, st] : parts) - st.staged_part_files_by_path.clear(); + st.staged_payloads_by_path.clear(); } -ContentAddressedTransaction::StagedPartFilePtr ContentAddressedTransaction::stagedFileOf(const PartStaging & st, const String & path) +ContentAddressedTransaction::StagedPartFilePayloadPtr ContentAddressedTransaction::findStagedPayload(const PartStaging & st, const String & path) { - const auto it = st.staged_part_files_by_path.find(path); - return it == st.staged_part_files_by_path.end() ? nullptr : it->second; + const auto it = st.staged_payloads_by_path.find(path); + return it == st.staged_payloads_by_path.end() ? nullptr : it->second; } namespace @@ -304,19 +304,19 @@ void ContentAddressedTransaction::putCopiedInlineEntry(PartStaging & part_stagin replaceManifestEntry(part_staging.entries, std::move(entry), [&](const String & path) { - part_staging.staged_part_files_by_path.erase(path); + part_staging.staged_payloads_by_path.erase(path); part_staging.borrowed_blob_sources_by_path.erase(path); }); } -void ContentAddressedTransaction::putEntryWithStagedFile( - PartStaging & part_staging, Cas::ManifestEntry && entry, StagedPartFilePtr staged_file) +void ContentAddressedTransaction::putEntryWithStagedPayload( + PartStaging & part_staging, Cas::ManifestEntry && entry, StagedPartFilePayloadPtr staged_payload) { - chassert(staged_file); + chassert(staged_payload); replaceManifestEntry(part_staging.entries, std::move(entry), [&](const String & path) { - part_staging.staged_part_files_by_path.insert_or_assign(path, std::move(staged_file)); + part_staging.staged_payloads_by_path.insert_or_assign(path, std::move(staged_payload)); part_staging.borrowed_blob_sources_by_path.erase(path); }); } @@ -330,18 +330,18 @@ void ContentAddressedTransaction::putBorrowedBlobEntry( replaceManifestEntry(part_staging.entries, std::move(entry), [&](const String & path) { part_staging.borrowed_blob_sources_by_path.insert_or_assign(path, std::move(borrowed_blob_source)); - part_staging.staged_part_files_by_path.erase(path); + part_staging.staged_payloads_by_path.erase(path); }); } void ContentAddressedTransaction::putEntryForHardLinkOrMove( - PartStaging & part_staging, Cas::ManifestEntry && entry, std::shared_ptr borrowed_blob_source, StagedPartFilePtr staged_file) + PartStaging & part_staging, Cas::ManifestEntry && entry, std::shared_ptr borrowed_blob_source, StagedPartFilePayloadPtr staged_payload) { - chassert(!(borrowed_blob_source && staged_file)); + chassert(!(borrowed_blob_source && staged_payload)); - if (staged_file) + if (staged_payload) { - putEntryWithStagedFile(part_staging, std::move(entry), std::move(staged_file)); + putEntryWithStagedPayload(part_staging, std::move(entry), std::move(staged_payload)); return; } @@ -364,19 +364,19 @@ void ContentAddressedTransaction::eraseEntry(PartStaging & st, const std::string { std::erase_if(st.entries, [&](const Cas::ManifestEntry & e) { return e.path == path; }); st.borrowed_blob_sources_by_path.erase(path); - st.staged_part_files_by_path.erase(path); + st.staged_payloads_by_path.erase(path); } void ContentAddressedTransaction::rekeyEntry(PartStaging & st, Cas::ManifestEntry & entry, std::string new_path) { - auto file = stagedFileOf(st, entry.path); + auto staged_payload = findStagedPayload(st, entry.path); auto source = copySourceOf(st, entry.path); - if (file) - st.staged_part_files_by_path.emplace(new_path, std::move(file)); + if (staged_payload) + st.staged_payloads_by_path.emplace(new_path, std::move(staged_payload)); if (source) st.borrowed_blob_sources_by_path.emplace(new_path, std::move(source)); st.borrowed_blob_sources_by_path.erase(entry.path); - st.staged_part_files_by_path.erase(entry.path); + st.staged_payloads_by_path.erase(entry.path); entry.path = std::move(new_path); } @@ -384,7 +384,7 @@ void ContentAddressedTransaction::clearEntries(PartStaging & st) { st.entries.clear(); st.borrowed_blob_sources_by_path.clear(); - st.staged_part_files_by_path.clear(); + st.staged_payloads_by_path.clear(); st.has_finalized_file_write = false; } @@ -513,13 +513,13 @@ void ContentAddressedTransaction::convertBlobEntryToInline( { chassert(entry.placement == Cas::EntryPlacement::Blob); - const auto & staged_file = part_staging.staged_part_files_by_path.at(entry.path); + const auto & staged_payload = part_staging.staged_payloads_by_path.at(entry.path); - if (staged_file->in_memory_payload) - entry.inline_bytes.assign(staged_file->in_memory_payload->view()); + if (staged_payload->in_memory_payload) + entry.inline_bytes.assign(staged_payload->in_memory_payload->view()); else { - auto input = openStagedPayload(staged_file, entry.blob_size, pool); + auto input = openStagedPayload(staged_payload, entry.blob_size, pool); String bytes(entry.blob_size, '\0'); input->readStrict(bytes.data(), bytes.size()); @@ -532,7 +532,7 @@ void ContentAddressedTransaction::convertBlobEntryToInline( entry.placement = Cas::EntryPlacement::Inline; entry.blob_size = 0; /// The entry now owns its bytes. Hardlinks and open readers retain their own references to the staging source. - part_staging.staged_part_files_by_path.erase(entry.path); + part_staging.staged_payloads_by_path.erase(entry.path); } std::vector ContentAddressedTransaction::applyManifestInlineBudget( @@ -544,8 +544,8 @@ std::vector ContentAddressedTransaction::applyManifestIn for (auto & entry : part_staging.entries) { - const auto staged_file = stagedFileOf(part_staging, entry.path); - if (entry.placement == Cas::EntryPlacement::Inline || (staged_file && staged_file->allow_inline_by_name && entry.blob_size <= Cas::kMaxManifestInlineEntryBytes)) + const auto staged_payload = findStagedPayload(part_staging, entry.path); + if (entry.placement == Cas::EntryPlacement::Inline || (staged_payload && staged_payload->allow_inline_by_name && entry.blob_size <= Cas::kMaxManifestInlineEntryBytes)) { inline_placement_candidates.push_back(&entry); inline_bytes_with_candidates += entry.size(); @@ -596,17 +596,17 @@ Cas::ManifestId ContentAddressedTransaction::precommitAndUpload( return id; } -std::unique_ptr ContentAddressedTransaction::openStagedPayload(const StagedPartFilePtr & file, uint64_t size, const Cas::PoolPtr & pool) +std::unique_ptr ContentAddressedTransaction::openStagedPayload(const StagedPartFilePayloadPtr & staged_payload, uint64_t size, const Cas::PoolPtr & pool) { - if (file->in_memory_payload) - return std::make_unique>(file, file->in_memory_payload->view()); - if (!file->remote_storage) - return Cas::openLocalStagedBlobPayload(file->staging_path, size); + if (staged_payload->in_memory_payload) + return std::make_unique>(staged_payload, staged_payload->in_memory_payload->view()); + if (!staged_payload->remote_storage) + return Cas::openLocalStagedBlobPayload(staged_payload->staging_path, size); auto op = pool->mountRequests().admit(); - auto staged = op.stream(file->pool_staging_key, Cas::Retry::standard()); + auto staged = op.stream(staged_payload->pool_staging_key, Cas::Retry::standard()); if (!staged) - throw Exception(ErrorCodes::FILE_DOESNT_EXIST, "CAS staging object {} disappeared before publication", file->staging_path); + throw Exception(ErrorCodes::FILE_DOESNT_EXIST, "CAS staging object {} disappeared before publication", staged_payload->staging_path); const auto header_len = pool->poolMeta().blob_header_len; String header(header_len, '\0'); @@ -614,18 +614,18 @@ std::unique_ptr ContentAddressedTransaction::openStagedPayload(const 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); + throw Exception(ErrorCodes::CORRUPTED_DATA, "Unexpected envelope length {} in staging object {}", decoded.header_len, staged_payload->staging_path); return staged; } -Cas::BlobSource ContentAddressedTransaction::stagedUploadSource(const StagedPartFilePtr & file, uint64_t size) const +Cas::BlobSource ContentAddressedTransaction::stagedUploadSource(const StagedPartFilePayloadPtr & staged_payload, 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), - .remote_throttler = file->remote_throttler, + .open = [pool = metadata_storage.store(), staged_payload, size] { return openStagedPayload(staged_payload, size, pool); }, + .server_side_copy_from = staged_payload->remote_storage ? std::optional(staged_payload->staging_path) : std::nullopt, + .publication_attempted = std::shared_ptr>(staged_payload, &staged_payload->publication_attempted), + .remote_throttler = staged_payload->remote_throttler, }; } @@ -635,8 +635,8 @@ void ContentAddressedTransaction::appendStagedBlobUploads(const PartStaging & st { 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 (auto staged_payload = findStagedPayload(st, entry.path)) + blob_upload_requests.push_back({entry.ref, stagedUploadSource(staged_payload, entry.blob_size), entry.blob_size}); } } @@ -948,9 +948,9 @@ std::optional ContentAddressedTransaction::tryGetInFlightStorageO { /// 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 (auto file = stagedFileOf(it->second, entry->path)) + if (auto staged_payload = findStagedPayload(it->second, entry->path)) { - if (file->allow_inline_by_name && entry->blob_size <= Cas::kMaxManifestInlineEntryBytes) + if (staged_payload->allow_inline_by_name && entry->blob_size <= Cas::kMaxManifestInlineEntryBytes) return StoredObjects{StoredObject("", path, entry->blob_size)}; return {}; } @@ -982,19 +982,19 @@ 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)) + if (auto staged_payload = findStagedPayload(it->second, entry->path)) { - if (file->in_memory_payload) + if (staged_payload->in_memory_payload) return std::make_unique>( - file, /*owns_memory=*/false, path, file->in_memory_payload->view()); - if (file->remote_storage) + staged_payload, /*owns_memory=*/false, path, staged_payload->in_memory_payload->view()); + if (staged_payload->remote_storage) { 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); + auto input = staged_payload->remote_storage->readObject(StoredObject(staged_payload->staging_path, path, end), settings); + return std::make_unique>(staged_payload, std::move(input), path, offset, end); } - return std::make_unique>(file, file->staging_path); + return std::make_unique>(staged_payload, staged_payload->staging_path); } return metadata_storage.readBlobPayload(metadata_storage.store()->locate(*entry), path, settings); } @@ -1073,7 +1073,7 @@ void ContentAddressedTransaction::createMetadataFile(const std::string &, const } void ContentAddressedTransaction::registerFinalizedPartFile( - const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::shared_ptr & staged_file) + const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::shared_ptr & staged_payload) { std::lock_guard lock(file_registration_mutex); auto & part_staging = stagingFor(route); @@ -1081,19 +1081,22 @@ void ContentAddressedTransaction::registerFinalizedPartFile( buildFor(route, part_staging); SCOPE_EXIT({ - if (!had_build && !staged_file->registered) + if (!had_build && !staged_payload->registered) part_staging.build.reset(); }); if (std::exchange(fail_next_file_registration, false)) throw Exception(ErrorCodes::ABORTED, "Injected failure registering staged file {}", route.file); - staged_file->allow_inline_by_name = !Cas::partFileMustStayBlob(route.file); + staged_payload->allow_inline_by_name = !Cas::partFileMustStayBlob(route.file); + /// The `Blob` form records the hash and size while `staged_payload` owns the bytes, even when they are in RAM. + /// During `commit`, `applyManifestInlineBudget` converts eligible entries to `Inline` if they fit the manifest's + /// inline budget. The remaining entries keep their `Blob` placement. Cas::ManifestEntry entry{.path = route.file, .placement = Cas::EntryPlacement::Blob, .ref = ref, .blob_size = size, .inline_bytes = {}}; - putEntryWithStagedFile(part_staging, std::move(entry), staged_file); + putEntryWithStagedPayload(part_staging, std::move(entry), staged_payload); - staged_file->registered = true; + staged_payload->registered = true; part_staging.has_finalized_file_write = true; } @@ -1106,13 +1109,13 @@ void ContentAddressedTransaction::stageBlobPartFile( /// has already finalized the object, so this callback cleans it up on failure. try { - auto staged_file = std::make_shared(); - staged_file->staging_path = staging_key; - staged_file->remote_storage = remote_storage; - staged_file->pool_staging_key = pool_staging_key; - staged_file->remote_throttler = std::move(remote_throttler); + auto staged_payload = std::make_shared(); + staged_payload->staging_path = staging_key; + staged_payload->remote_storage = remote_storage; + staged_payload->pool_staging_key = pool_staging_key; + staged_payload->remote_throttler = std::move(remote_throttler); - registerFinalizedPartFile(route, ref, size, staged_file); + registerFinalizedPartFile(route, ref, size, staged_payload); } catch (...) { @@ -1351,11 +1354,12 @@ std::unique_ptr ContentAddressedTransaction::writeFile( { const auto bytes = payload->view(); const auto ref = Cas::poolContentHash(hash_algo, bytes); - auto file = std::make_shared(); - file->in_memory_payload = std::move(payload); - file->remote_throttler = throttler; - registerFinalizedPartFile(route, ref, bytes.size(), file); + auto staged_payload = std::make_shared(); + staged_payload->in_memory_payload = std::move(payload); + staged_payload->remote_throttler = throttler; + + registerFinalizedPartFile(route, ref, bytes.size(), staged_payload); }); } @@ -1556,14 +1560,14 @@ void ContentAddressedTransaction::createHardLink(const std::string & path_from, if (it != src_st->entries.end()) { entry = *it; - auto file = stagedFileOf(*src_st, src->file); + auto staged_payload = findStagedPayload(*src_st, src->file); auto source = copySourceOf(*src_st, src->file); auto & build = buildFor(*dst, dst_st); - if (!file) + if (!staged_payload) build.adoptEvidence(entry); entry.path = dst->file; - putEntryForHardLinkOrMove(dst_st, std::move(entry), std::move(source), std::move(file)); + putEntryForHardLinkOrMove(dst_st, std::move(entry), std::move(source), std::move(staged_payload)); return; } } @@ -1755,8 +1759,8 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c 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 <= Cas::kMaxManifestInlineEntryBytes + const auto staged_payload = findStagedPayload(source_is_blob ? src_st : dst_st, blob.path); + if (staged_payload && staged_payload->allow_inline_by_name && blob.blob_size <= Cas::kMaxManifestInlineEntryBytes && Cas::poolContentHash(blob.ref.algo, inlined.inline_bytes) == blob.ref) continue; } @@ -1768,8 +1772,8 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c for (auto & entry : src_st.entries) { auto source = copySourceOf(src_st, entry.path); - auto file = stagedFileOf(src_st, entry.path); - putEntryForHardLinkOrMove(dst_st, std::move(entry), std::move(source), std::move(file)); + auto staged_payload = findStagedPayload(src_st, entry.path); + putEntryForHardLinkOrMove(dst_st, std::move(entry), std::move(source), std::move(staged_payload)); } /// Carry any staged removal marks forward too — a re-key of the /// staging key must not silently drop them. @@ -1787,7 +1791,7 @@ 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)) + if (entry.placement == Cas::EntryPlacement::Blob && !findStagedPayload(dst_st, entry.path)) dst_st.build->adoptEvidence(entry); src_st.build->abandon(); } @@ -1956,17 +1960,17 @@ void ContentAddressedTransaction::moveFile(const std::string & path_from, const return; auto entry = *it; auto source = copySourceOf(src_st, src->file); - auto file = stagedFileOf(src_st, src->file); + auto staged_payload = findStagedPayload(src_st, src->file); if (&src_st != &dst_st) { auto & build = buildFor(*dst, dst_st); - if (!file) + if (!staged_payload) build.adoptEvidence(entry); } entry.path = dst->file; markVacatedInBase(*src, src_st, {src->file}); - putEntryForHardLinkOrMove(dst_st, std::move(entry), std::move(source), std::move(file)); + putEntryForHardLinkOrMove(dst_st, std::move(entry), std::move(source), std::move(staged_payload)); eraseEntry(src_st, src->file); return; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index 85cd14aad82c..faa9c66382f6 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -147,7 +147,7 @@ class ContentAddressedTransaction : public IMetadataTransaction private: /// One finalized source shared across paths, readers and uploads. The memory payload /// owns its reservation until the last holder releases its bytes. - struct StagedPartFile + struct StagedPartFilePayload { std::shared_ptr in_memory_payload; String staging_path; /// Local filesystem path or the S3 key used by IObjectStorage. @@ -158,9 +158,9 @@ class ContentAddressedTransaction : public IMetadataTransaction bool registered = false; /// The local writer owns its scratch path until registration succeeds. mutable std::atomic publication_attempted{false}; - ~StagedPartFile(); + ~StagedPartFilePayload(); }; - using StagedPartFilePtr = std::shared_ptr; + using StagedPartFilePayloadPtr = std::shared_ptr; /// State for one routed part. The build records its manifest dependencies at publication. struct PartStaging @@ -186,7 +186,7 @@ class ContentAddressedTransaction : public IMetadataTransaction /// loop is idempotent (never re-publishes a staging). /// Each newly written path and its hardlinks retain the original staging source. - std::unordered_map staged_part_files_by_path; + std::unordered_map staged_payloads_by_path; bool has_finalized_file_write = false; /// A build opened only for a transfer cannot replace the temporary segment ref. }; @@ -212,7 +212,7 @@ class ContentAddressedTransaction : public IMetadataTransaction std::unordered_set force_fresh_validated_refs; void registerFinalizedPartFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, - const std::shared_ptr & staged_file); + const std::shared_ptr & staged_payload); /// Transfer the writer's private file or S3 object only on successful registration. void stageBlobPartFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::string & staging_key, @@ -227,7 +227,7 @@ class ContentAddressedTransaction : public IMetadataTransaction static void putCopiedInlineEntry(PartStaging & part_staging, Cas::ManifestEntry && entry); /// A writer finalized the file in this transaction. Keep its bytes in memory or staging for this path and any hardlinks. - static void putEntryWithStagedFile(PartStaging & part_staging, Cas::ManifestEntry && entry, StagedPartFilePtr staged_file); + static void putEntryWithStagedPayload(PartStaging & part_staging, Cas::ManifestEntry && entry, StagedPartFilePayloadPtr staged_payload); /// A hardlink reuses a Blob entry from a committed manifest. Keep the source so commit can confirm the borrowed blob. static void putBorrowedBlobEntry( @@ -235,7 +235,7 @@ class ContentAddressedTransaction : public IMetadataTransaction /// Hardlinks and moves carry the original file or copy source to the destination path. An entry can have at most one. static void putEntryForHardLinkOrMove( - PartStaging & part_staging, Cas::ManifestEntry && entry, std::shared_ptr borrowed_blob_source, StagedPartFilePtr staged_file); + PartStaging & part_staging, Cas::ManifestEntry && entry, std::shared_ptr borrowed_blob_source, StagedPartFilePayloadPtr staged_payload); static void eraseEntry(PartStaging & st, const std::string & path); /// Renames `entry`, an element of `st.entries`, in place; `new_path` must not be staged. @@ -267,11 +267,11 @@ class ContentAddressedTransaction : public IMetadataTransaction /// 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 StagedPartFilePayloadPtr findStagedPayload(const PartStaging & st, const String & path); - static std::unique_ptr openStagedPayload(const StagedPartFilePtr & file, uint64_t size, const Cas::PoolPtr & pool); + static std::unique_ptr openStagedPayload(const StagedPartFilePayloadPtr & staged_payload, uint64_t size, const Cas::PoolPtr & pool); - Cas::BlobSource stagedUploadSource(const StagedPartFilePtr & file, uint64_t size) const; + Cas::BlobSource stagedUploadSource(const StagedPartFilePayloadPtr & staged_payload, uint64_t size) const; static void convertInlineEntryToBlob( Cas::ManifestEntry & entry, Cas::BlobHashAlgo hash_algo, std::vector & blob_upload_requests); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp index 747b58bb3659..40de092793fa 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -49,24 +50,39 @@ bool InlineCandidatePayload::trySetCapacity(size_t new_capacity) budget->release(new_capacity); throw; } + if (length) std::memcpy(replacement.get(), buffer.get(), length); + buffer = std::move(replacement); budget->release(capacity); capacity = new_capacity; + return true; } +void InlineCandidatePayload::tryShrinkToFit() +{ + constexpr size_t min_bytes_to_reclaim = 1_KiB; + constexpr size_t max_bytes_to_copy_per_byte_reclaimed = 3; + + /// Skip the extra allocation for small savings. A 3:1 copy limit requires at least 25% unused capacity. + /// Keep the current allocation if the budget cannot also accommodate the compact copy. + const size_t unused_capacity = capacity - length; + if (unused_capacity >= min_bytes_to_reclaim && length <= max_bytes_to_copy_per_byte_reclaimed * unused_capacity) + trySetCapacity(length); +} + InlineCandidateWriteBuffer::InlineCandidateWriteBuffer( String path_, size_t buf_size, size_t max_inline_bytes_, std::shared_ptr budget, - CreateLocalWriter create_local_writer_, OnInline on_inline_) + CreateLocalStagingWriter create_local_staging_writer_, OnInMemoryPayloadFinalized on_in_memory_payload_finalized_) : WriteBufferFromFileBase(0, nullptr, 0) , path(std::move(path_)) , transfer_size(std::clamp(buf_size, 1, 65536)) , max_inline_bytes(max_inline_bytes_) - , create_local_writer(std::move(create_local_writer_)) - , on_inline(std::move(on_inline_)) - , payload(std::make_shared(std::move(budget))) + , create_local_staging_writer(std::move(create_local_staging_writer_)) + , on_in_memory_payload_finalized(std::move(on_in_memory_payload_finalized_)) + , in_memory_payload(std::make_shared(std::move(budget))) { /// The caller can write directly into a payload array, so there is no separate uncharged inline I/O buffer. padded = false; @@ -80,80 +96,83 @@ InlineCandidateWriteBuffer::~InlineCandidateWriteBuffer() void InlineCandidateWriteBuffer::nextImpl() { - if (local) + if (local_staging_writer) { - local->write(working_buffer.begin(), offset()); + local_staging_writer->write(working_buffer.begin(), offset()); return; } - if (working_buffer.begin() == &overflow_byte) + /// `length` excludes the bytes pending in this flush. When it already equals `capacity` + /// (including zero at construction), the active write range is `overflow_byte`. + /// `WriteBuffer::next` skips empty flushes, so that byte has been written. + if (in_memory_payload->length == in_memory_payload->capacity) { - const size_t needed = payload->length + 1; + const size_t needed = in_memory_payload->length + 1; const size_t target = finishing ? needed - : std::min(max_inline_bytes, payload->capacity ? 2 * payload->capacity : std::min(transfer_size, 4096)); - if (needed > max_inline_bytes || !payload->trySetCapacity(std::max(needed, target))) + : std::min(max_inline_bytes, in_memory_payload->capacity ? 2 * in_memory_payload->capacity : std::min(transfer_size, 4096)); + + if (needed > max_inline_bytes || !in_memory_payload->trySetCapacity(std::max(needed, target))) { - local = create_local_writer(); - const auto prefix = payload->view(); + local_staging_writer = create_local_staging_writer(); + const auto prefix = in_memory_payload->view(); if (!prefix.empty()) - local->write(prefix.data(), prefix.size()); - local->write(overflow_byte); - payload.reset(); + local_staging_writer->write(prefix.data(), prefix.size()); + local_staging_writer->write(overflow_byte); + in_memory_payload.reset(); resize(transfer_size); if (needed <= max_inline_bytes) ProfileEvents::increment(ProfileEvents::CASInlineWriteMemoryBudgetSpills); return; } - payload->buffer[payload->length++] = overflow_byte; + in_memory_payload->buffer[in_memory_payload->length++] = overflow_byte; } else { - payload->length += offset(); + in_memory_payload->length += offset(); } - if (payload->length == payload->capacity) + if (in_memory_payload->length == in_memory_payload->capacity) set(&overflow_byte, 1); else - set(payload->buffer.get() + payload->length, payload->capacity - payload->length); + set(in_memory_payload->buffer.get() + in_memory_payload->length, in_memory_payload->capacity - in_memory_payload->length); } void InlineCandidateWriteBuffer::preFinalize() { finishing = true; next(); - if (local) - local->preFinalize(); + if (local_staging_writer) + local_staging_writer->preFinalize(); } void InlineCandidateWriteBuffer::finalizeImpl() { finishing = true; next(); - if (local) + if (local_staging_writer) { - local->finalize(); + local_staging_writer->finalize(); return; } set(&overflow_byte, 1); - /// Keep the current allocation if the budget cannot also accommodate a compact copy. - payload->trySetCapacity(payload->length); - on_inline(std::move(payload)); + in_memory_payload->tryShrinkToFit(); + on_in_memory_payload_finalized(std::move(in_memory_payload)); } void InlineCandidateWriteBuffer::cancelImpl() noexcept { set(&overflow_byte, 1); - payload.reset(); - if (local) - local->cancel(); + in_memory_payload.reset(); + if (local_staging_writer) + local_staging_writer->cancel(); } void InlineCandidateWriteBuffer::sync() { next(); - if (local) - local->sync(); + if (local_staging_writer) + local_staging_writer->sync(); } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h index ab2e4f105319..eb4c1bd0efec 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h @@ -41,6 +41,7 @@ class InlineCandidatePayload friend class InlineCandidateWriteBuffer; bool trySetCapacity(size_t new_capacity); + void tryShrinkToFit(); const std::shared_ptr budget; std::unique_ptr buffer; @@ -53,12 +54,12 @@ using InlineCandidatePayloadPtr = std::shared_ptr; class InlineCandidateWriteBuffer final : public WriteBufferFromFileBase { public: - using CreateLocalWriter = std::function()>; - using OnInline = std::function; + using CreateLocalStagingWriter = std::function()>; + using OnInMemoryPayloadFinalized = std::function; InlineCandidateWriteBuffer( String path_, size_t buf_size, size_t max_inline_bytes_, std::shared_ptr budget, - CreateLocalWriter create_local_writer_, OnInline on_inline_); + CreateLocalStagingWriter create_local_staging_writer_, OnInMemoryPayloadFinalized on_in_memory_payload_finalized_); ~InlineCandidateWriteBuffer() override; String getFileName() const override { return path; } @@ -70,14 +71,16 @@ class InlineCandidateWriteBuffer final : public WriteBufferFromFileBase void finalizeImpl() override; void cancelImpl() noexcept override; - String path; - size_t transfer_size; - size_t max_inline_bytes; - CreateLocalWriter create_local_writer; - OnInline on_inline; - std::shared_ptr payload; - std::unique_ptr local; - /// Detect the first byte beyond the current allocation. In particular, exactly 1 MiB can still be inline. + const String path; + const size_t transfer_size; + const size_t max_inline_bytes; + const CreateLocalStagingWriter create_local_staging_writer; + const OnInMemoryPayloadFinalized on_in_memory_payload_finalized; + + std::shared_ptr in_memory_payload; + std::unique_ptr local_staging_writer; + /// Hold the first byte beyond the current allocation so that growth or spill waits for more input. + /// Flushing a file of exactly 1 MiB can then leave its payload in memory. char overflow_byte = 0; bool finishing = false; }; diff --git a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp index fffae575b870..eb321cad2380 100644 --- a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -715,6 +715,41 @@ TEST(CASInlineCandidateMemory, ThresholdPreservesPlacementAndPayload) expectBlob(*storage, ref, "over.idx", over_limit); } +TEST(CASInlineCandidateMemory, FinalizeCompactsWhenBothUnusedCapacityThresholdsAreMet) +{ + using namespace DB; + auto check_reservation = [](size_t file_size, size_t expected_before_finalize, size_t expected_after_finalize) + { + SCOPED_TRACE(file_size); + auto budget = std::make_shared(2 * mib); + Cas::InlineCandidatePayloadPtr retained; + Cas::InlineCandidateWriteBuffer writer( + "dict.dct.idx", 2 * kib, mib, budget, + [] { return std::make_unique(); }, + [&](Cas::InlineCandidatePayloadPtr bytes) { retained = std::move(bytes); }); + + const auto bytes = payload(file_size, 1); + writer.write(bytes.data(), bytes.size()); + ASSERT_EQ(budget->reservedBytes(), expected_before_finalize); + writer.finalize(); + + ASSERT_NE(retained, nullptr); + EXPECT_EQ(budget->reservedBytes(), expected_after_finalize); + EXPECT_TRUE(retained->view() == bytes); + }; + + /// Both buffers are more than 25% unused. Only the second can return a full KiB. + check_reservation(kib + 1, 2 * kib, 2 * kib); + check_reservation(kib, 2 * kib, kib); + + /// Both buffers can return at least 1 KiB. Only the second reaches 25% unused capacity. + check_reservation(6 * kib + 1, 8 * kib, 8 * kib); + check_reservation(6 * kib, 8 * kib, 6 * kib); + + check_reservation(4095, 4096, 4096); + check_reservation(600 * kib, mib, 600 * kib); +} + TEST(CASInlineCandidateMemory, LastAvailableByteCanBeReservedAndReused) { using namespace DB; From 42f5b9cccbc076d3fc9c4347b8c936acad60f72a Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Fri, 4 Dec 2026 17:44:53 +0100 Subject: [PATCH 7/8] Avoid copying CAS manifest entries to compute the payload digest Encode the zero digest directly when hashing the manifest payload. Check the resulting digest and wire bytes against the existing format. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- .../Formats/CasPartManifestFormat.cpp | 21 ++++++++++++------- .../tests/gtest_cas_part_manifest_format.cpp | 5 ++--- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Formats/CasPartManifestFormat.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Formats/CasPartManifestFormat.cpp index 2061f26225a2..31fa608b2dec 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Formats/CasPartManifestFormat.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Formats/CasPartManifestFormat.cpp @@ -108,7 +108,9 @@ EntryPlacement entryPlacementFromWireWord(std::string_view w) return kEntryPlacementWords.fromWord(w, "PartManifest: EntryPlacement"); } -String encodePartManifest(const PartManifest & m) +namespace +{ +String encodePartManifestWithDigest(const PartManifest & m, const UInt128 & payload_digest) { /// Canonical path order plus duplicate-path rejection makes the encoded record sequence /// deterministic and establishes the ordering required by the lookup helpers. @@ -144,7 +146,7 @@ String encodePartManifest(const PartManifest & m) bool first = true; writeManifestRefFields(out, first, kBareManifestRefKeys, m.ref); writeStringField(out, PartManifestWire::ns, m.root_namespace_id.string(), first); - writeHex128Field(out, PartManifestWire::payload_digest, m.payload_digest, first); + writeHex128Field(out, PartManifestWire::payload_digest, payload_digest, first); closeObject(out, first); check_line_bytes(out.size() - line_start, "descriptor"); writeChar('\n', out); @@ -176,6 +178,13 @@ String encodePartManifest(const PartManifest & m) return std::move(out).take(); } +} + +String encodePartManifest(const PartManifest & m) +{ + return encodePartManifestWithDigest(m, m.payload_digest); +} + PartManifest decodePartManifest(std::string_view data) { ReadBufferFromMemory in(data.data(), data.size()); @@ -321,9 +330,7 @@ PartManifest decodePartManifest(std::string_view data) throw Exception(ErrorCodes::CORRUPTED_DATA, "PartManifest: trailing bytes after the payload zone"); /// Recompute and verify `payload_digest` last, over the fully-decoded body. `computePayloadDigest` - /// builds its own probe copy with payload_digest zeroed before hashing (see below), so calling it - /// directly here on `m` (whose payload_digest is whatever was read off the wire) is safe and - /// matches encode's own computation exactly. + /// encodes a zero digest in the descriptor regardless of the value read from the wire. /// /// The decoder accepts strings the encoder would escape longer (a raw control byte), so a line that fit /// the cap as stored can exceed it once re-encoded: these bytes are corrupt, not a writer's limit. @@ -353,9 +360,7 @@ UInt128 computePayloadDigest(const PartManifest & m) /// itself (it would be circular otherwise) and is stable for identical bodies, changing whenever /// ref / namespace / entries change. Uses the CAS content-hash primitive (CityHash128) over the /// deterministic encodePartManifest bytes - the same primitive blob/tree hashing uses. - PartManifest probe = m; - probe.payload_digest = UInt128{}; - const String bytes = encodePartManifest(probe); + const String bytes = encodePartManifestWithDigest(m, UInt128{}); const auto h = CityHash_v1_0_2::CityHash128(bytes.data(), bytes.size()); return (static_cast(h.high64) << 64) | static_cast(h.low64); } diff --git a/src/Disks/tests/gtest_cas_part_manifest_format.cpp b/src/Disks/tests/gtest_cas_part_manifest_format.cpp index c6afd70e8f8e..dbfa2c05c9d4 100644 --- a/src/Disks/tests/gtest_cas_part_manifest_format.cpp +++ b/src/Disks/tests/gtest_cas_part_manifest_format.cpp @@ -74,11 +74,10 @@ CAS_BATTERY_COVERS(PartManifest); TEST(CASFormatBattery, PartManifest) { const PartManifest m = sample(); - /// Interpolate the REAL digest (never hand-compute a CityHash128 hex by hand) so the golden text - /// stays self-consistent with whatever sample() produces, now that decode verifies payload_digest. + /// Pin the stored digest along with the canonical bytes used to compute it. const String golden = currentFormatHeader("cas_part_manifest") + - "{\"epoch\":\"5\",\"build\":\"15\",\"ord\":1,\"namespace\":\"00/aa@cas@\",\"payload_digest\":\"" + u128ToHex(m.payload_digest) + "\"}\n" // NOLINT(modernize-raw-string-literal): mixes '\"' quoting with '\n' line endings across this concatenated literal; a raw string can't hold the newline as-is. + "{\"epoch\":\"5\",\"build\":\"15\",\"ord\":1,\"namespace\":\"00/aa@cas@\",\"payload_digest\":\"dd3aabd8e491516ad60dd43e1e4a3700\"}\n" // NOLINT(modernize-raw-string-literal): mixes '\"' quoting with '\n' line endings across this concatenated literal; a raw string can't hold the newline as-is. "{\"path\":\"a/b.bin\",\"place\":\"blob\",\"algo\":\"ch128\",\"digest\":\"00112233445566778899aabbccddeeff\",\"size\":4096}\n" "{\"path\":\"c/small.txt\",\"place\":\"inline\",\"size\":12}\n" "{\"n\":2}\n" From 99cf2ac1f990fbc27d45a6e422d3dcc561eabcd1 Mon Sep 17 00:00:00 2001 From: Konstantin Morozov Date: Fri, 4 Dec 2026 18:02:24 +0100 Subject: [PATCH 8/8] Cover CAS inline file transfers and mixed blob uploads Check one-byte moves and hardlinks into a fresh part, local spills under S3 staging, and publication of distinct and identical blobs from two sources. Require the ownership conflict when the base manifest changes. Clean up the 05815 tables and pools on either exit path. Co-authored-by: Codex (GPT-6) Signed-off-by: Konstantin Morozov --- src/Disks/tests/gtest_cas_inline_cap_gaps.cpp | 42 +++++- src/Disks/tests/gtest_cas_s3_staging.cpp | 131 ++++++++++++++++++ ...15_cas_text_index_rebuild_inline_budget.sh | 17 ++- 3 files changed, 185 insertions(+), 5 deletions(-) diff --git a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp index eb321cad2380..34245140ad34 100644 --- a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -32,6 +32,7 @@ namespace ProfileEvents namespace DB::ErrorCodes { + extern const int CAS_OWNERSHIP_CONFLICT; extern const int CORRUPTED_DATA; extern const int INCORRECT_DATA; } @@ -379,6 +380,43 @@ TEST(CASInlineCapGaps, RepointCountsOnlyRetainedBasePaths) EXPECT_TRUE(readPartFile(*storage, dir + "/extra.idx") == payload(mib, 58)); } +TEST(CASInlineCapGaps, MoveStagedInlineFileIntoFreshPart) +{ + auto storage = openStorage(); + const std::string src = table_dir + "all_1_1_0/source.idx"; + const std::string dst_ref = "all_2_2_0"; + const std::string dst = table_dir + dst_ref + "/moved.idx"; + + auto tx = storage->createTransaction(); + writeFileTx(*tx, src, "m"); + tx->moveFile(src, dst); + tx->commit(DB::NoCommitOptions{}); + + EXPECT_EQ(manifestOf(*storage, uuid, dst_ref).entries.size(), 1u); + EXPECT_EQ(storage->tryGetInManifestBytes(dst), "m"); + EXPECT_FALSE(storage->existsFile(src)); +} + +TEST(CASInlineCapGaps, HardLinkCommittedInlineFileIntoFreshPart) +{ + auto storage = openStorage(); + const std::string src = table_dir + "all_1_1_0/source.idx"; + const std::string dst_ref = "all_2_2_0"; + const std::string dst = table_dir + dst_ref + "/linked.idx"; + auto tx = storage->createTransaction(); + writeFileTx(*tx, src, "x"); + tx->commit(DB::NoCommitOptions{}); + ASSERT_EQ(storage->tryGetInManifestBytes(src), "x"); + + tx = storage->createTransaction(); + tx->createHardLink(src, dst); + tx->commit(DB::NoCommitOptions{}); + + EXPECT_EQ(manifestOf(*storage, uuid, dst_ref).entries.size(), 1u); + EXPECT_EQ(storage->tryGetInManifestBytes(dst), "x"); + EXPECT_EQ(storage->tryGetInManifestBytes(src), "x"); +} + TEST(CASInlineCapGaps, SpillsCommittedHardlinkWithoutChangingItsSource) { auto storage = openStorage(); @@ -618,10 +656,10 @@ TEST(CASInlineCapGaps, RepointRefusesBaseChangedAfterSpillUpload) rival_committed = true; } }); - const std::string failure = commitErrorOf(*tx); + DB::Cas::tests::expectThrowsCode( + DB::ErrorCodes::CAS_OWNERSHIP_CONFLICT, [&] { tx->commit(DB::NoCommitOptions{}); }); 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")); diff --git a/src/Disks/tests/gtest_cas_s3_staging.cpp b/src/Disks/tests/gtest_cas_s3_staging.cpp index ef986e4568bd..49f8418a45f4 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 @@ -25,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -44,6 +47,11 @@ namespace DB::ContentAddressedSetting extern const ContentAddressedSettingsString staging_backend; } +namespace ProfileEvents +{ + extern const Event CASInlineWriteMemoryBudgetSpills; +} + namespace DB::ErrorCodes { extern const int CORRUPTED_DATA; @@ -905,6 +913,45 @@ TEST(CASS3Staging, OversizedInlineCandidateKeepsLocalStaging) EXPECT_FALSE(storage->tryGetInManifestBytes(path).has_value()); } +TEST(CASS3Staging, InlineCandidateSpillsToLocalScratchWhenTransactionMemoryIsFull) +{ + auto objects = makeFakeNativeCopyStorage(/*native_only_copy_supported=*/true); + auto storage = makeS3StagingMetadataStorageForTest(objects, "mountInlineMemorySpill"); + storage->startup(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const String directory = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/"; + const String bytes(600 * 1024, 'd'); + + std::vector> writers; + for (size_t i = 0; i < 32; ++i) + { + auto writer = ca_tx.writeFile(directory + std::to_string(i) + ".idx", 65536, DB::WriteMode::Rewrite, {}); + writer->write(bytes.data(), bytes.size()); + writers.push_back(std::move(writer)); + } + const auto path = directory + "dict.dct.idx"; + const auto & events = DB::CurrentThread::getProfileEvents(); + const auto spills_before = events[ProfileEvents::CASInlineWriteMemoryBudgetSpills]; + writeThroughS3Transaction(ca_tx, path, bytes); + EXPECT_EQ(events[ProfileEvents::CASInlineWriteMemoryBudgetSpills] - spills_before, 1u); + for (auto & writer : writers) + writer->cancel(); + + /// Only the finalized dictionary can still own a staging file. + const auto & scratch = storage->scratchPath(); + ASSERT_TRUE(std::filesystem::is_directory(scratch)); + ASSERT_EQ(std::ranges::distance(std::filesystem::directory_iterator(scratch)), 1); + EXPECT_EQ(std::filesystem::file_size(std::filesystem::directory_iterator(scratch)->path()), bytes.size()); + DB::RelativePathsWithMetadata staged; + objects->listObjects(storage->stagingKeyPrefix(), staged, /*max_keys=*/0); + EXPECT_TRUE(staged.empty()); + + tx->commit(DB::NoCommitOptions{}); + EXPECT_TRUE(storage->tryGetInManifestBytes(path) == bytes); + EXPECT_TRUE(std::filesystem::is_empty(scratch)); +} + /// An aborted transaction deletes its own S3 staging object instead of leaving it for the next mount. TEST(CASS3Staging, AbortDeletesS3Staging) { @@ -1236,6 +1283,90 @@ TEST(CASS3Staging, GenerationBackendMayUseNativeOnlyCopy) EXPECT_EQ(staged.size(), 1u); } +namespace +{ + +void checkMixedBlobUpload(const String & inline_bytes, const String & staged_bytes) +{ + auto objects = makeFakeGenerationObjectStorageForTest(); + auto storage = makeS3StagingMetadataStorageForTest(objects, "mixedUploads"); + storage->startup(); + + const String uuid = "a11a11a1-1111-4111-8111-111111111111"; + const String table = "a11/" + uuid + "/"; + const String source = table + "all_1_1_0/source.idx"; + const String ref = "all_2_2_0"; + const String destination = table + ref + "/"; + { + auto setup = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*setup); + writeThroughS3Transaction(ca_tx, source, inline_bytes); + /// Unchanged inline entries in the destination leave no room for the hardlink added below. + const String filler(DB::Cas::kMaxManifestInlineEntryBytes, 'x'); + for (size_t n = 0; n < DB::Cas::kMaxManifestInlineBytesTotal / filler.size(); ++n) + writeThroughS3Transaction(ca_tx, destination + std::to_string(n) + ".idx", filler); + setup->commit(DB::NoCommitOptions{}); + } + ASSERT_EQ(storage->tryGetInManifestBytes(source), inline_bytes); + + const auto pool = storage->store(); + const auto inline_ref = DB::Cas::poolContentHash(pool->writeAlgo(), inline_bytes); + const auto staged_ref = DB::Cas::poolContentHash(pool->writeAlgo(), staged_bytes); + const auto inline_key = pool->layout().blobKey(inline_ref); + const auto staged_key = pool->layout().blobKey(staged_ref); + + auto tx = storage->createTransaction(); + tx->createHardLink(source, destination + "linked.idx"); + writeThroughS3Transaction(dynamic_cast(*tx), destination + "data.bin", staged_bytes); + DB::RelativePathsWithMetadata staged; + objects->listObjects(storage->stagingKeyPrefix(), staged, /*max_keys=*/0); + ASSERT_EQ(staged.size(), 1u); + ASSERT_FALSE(objects->exists(DB::StoredObject(inline_key))); + ASSERT_FALSE(objects->exists(DB::StoredObject(staged_key))); + tx->commit(DB::NoCommitOptions{}); + + const auto resolved = pool->resolveRef(storage->liveNamespace(uuid), ref); + ASSERT_TRUE(resolved); + const auto manifest = pool->readManifest(resolved->manifest_id); + const auto expect_blob = [&](const String & name, const DB::Cas::BlobRef & expected_ref, const String & expected_bytes) + { + const auto * entry = DB::Cas::findEntry(manifest.entries, name); + ASSERT_NE(entry, nullptr) << name; + ASSERT_EQ(entry->placement, DB::Cas::EntryPlacement::Blob) << name; + EXPECT_EQ(entry->ref, expected_ref) << name; + auto reader = storage->readBlobPayload(pool->locate(*entry), destination + name, {}); + String bytes; + DB::readStringUntilEOF(bytes, *reader); + EXPECT_EQ(bytes, expected_bytes) << name; + }; + expect_blob("linked.idx", inline_ref, inline_bytes); + expect_blob("data.bin", staged_ref, staged_bytes); + + /// Count both writes and copies to the final blob keys. Either source can supply a shared blob. + size_t publications = 0; + for (const auto & record : objects->records()) + { + if (record->key != inline_key && record->key != staged_key) + continue; + ++publications; + if (inline_bytes != staged_bytes) + EXPECT_EQ(record->copy, record->key == staged_key) << record->key; + } + EXPECT_EQ(publications, inline_bytes == staged_bytes ? 1u : 2u); +} + +} + +TEST(CASS3Staging, PublishesConvertedInlineAndS3StagedBlobsTogether) +{ + checkMixedBlobUpload("inline source", "staged source"); +} + +TEST(CASS3Staging, PublishesSharedBlobOnceForConvertedInlineAndS3StagedSources) +{ + checkMixedBlobUpload("shared source", "shared source"); +} + /// Native prefix: keys pass through unchanged on both sides, so a `physicalKey` that started adding a /// root for Native, or a drain that started adding one, would miss the writer's objects. TEST(CASDecommissionStaging, StagingDrainRemovesWhatTheWriterStagedUnderTheNativePrefix) 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 0aa4ffdf41a7..2d4c0636dc86 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 @@ -13,6 +13,20 @@ set -e -o pipefail CLIENT="${CLICKHOUSE_CLIENT} --allow_experimental_full_text_index=1" ROWS=100 +cleanup() +{ + local test_status=$? cleanup_status=0 suffix + for suffix in merge mat; do + # Only remove a pool after its table is gone and FORGET has stopped the disk's background work. + ${CLIENT} -q "DROP TABLE IF EXISTS t_${suffix} SYNC" && + ${CLIENT} --allow_repeated_settings --send_logs_level=fatal -q "SYSTEM CAS FORGET '${CLICKHOUSE_DATABASE}_${suffix}'" && + rm -rf -- "${CLICKHOUSE_USER_FILES_UNIQUE:?}_${suffix}_pool" || cleanup_status=1 + done + if (( test_status != 0 )); then exit "$test_status"; fi + exit "$cleanup_status" +} +trap cleanup EXIT + 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/')" } @@ -71,6 +85,3 @@ ${CLIENT} -q "ALTER TABLE t_mat ADD INDEX idx_s (s) TYPE text(tokenizer = 'split ${CLIENT} -q "ALTER TABLE t_mat MATERIALIZE INDEX idx_s SETTINGS mutations_sync = 2, max_block_size = 5" segments t_mat MutatePart check t_mat - -${CLIENT} -q "DROP TABLE t_merge SYNC" -${CLIENT} -q "DROP TABLE t_mat SYNC"