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 e92692915508..efd85cb70f06 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -29,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -125,6 +127,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(), @@ -135,6 +155,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)) { } @@ -142,7 +163,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. @@ -210,75 +231,161 @@ ContentAddressedTransaction::PartStaging * ContentAddressedTransaction::findStag return it == parts.end() ? nullptr : &it->second; } -void ContentAddressedTransaction::cleanupPendingTempFiles() noexcept +namespace +{ +void tryRemoveStagingObject(const ObjectStoragePtr & storage, const String & staging_object_key) noexcept +{ + try + { + storage->removeObjectIfExists(StoredObject(staging_object_key)); + } + catch (...) + { + tryLogCurrentException(getLogger("ContentAddressedTransaction"), "removing a private staging object"); + } +} +} + +ContentAddressedTransaction::StagedPartFilePayload::~StagedPartFilePayload() +{ + if (!registered || in_memory_payload) + return; + if (remote_storage) + tryRemoveStagingObject(remote_storage, staging_path); + else + { + std::error_code ec; + fs::remove(staging_path, ec); + } +} + +void ContentAddressedTransaction::releaseStagedFiles() noexcept { for (auto & [key, st] : parts) + st.staged_payloads_by_path.clear(); +} + +ContentAddressedTransaction::StagedPartFilePayloadPtr ContentAddressedTransaction::findStagedPayload(const PartStaging & st, const String & path) +{ + const auto it = st.staged_payloads_by_path.find(path); + return it == st.staged_payloads_by_path.end() ? nullptr : it->second; +} + +namespace +{ +void replaceManifestEntry(std::vector & entries, Cas::ManifestEntry && entry, auto && update_source_maps) +{ + auto it = std::ranges::find(entries, entry.path, &Cas::ManifestEntry::path); + const bool inserted = it == entries.end(); + if (inserted) { - 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(); + entries.emplace_back(); + it = std::prev(entries.end()); + } + + /// Installing a new source can allocate. Keep the previous entry intact until that succeeds. + try + { + update_source_maps(entry.path); + } + catch (...) + { + if (inserted) + entries.pop_back(); + throw; } + *it = std::move(entry); +} } -const ContentAddressedTransaction::PartStaging::PendingBlob * -ContentAddressedTransaction::findPendingBlob(const PartStaging & st, const Cas::BlobRef & ref) const +void ContentAddressedTransaction::putCopiedInlineEntry(PartStaging & part_staging, Cas::ManifestEntry && entry) { - /// 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; + chassert(entry.placement == Cas::EntryPlacement::Inline); + + replaceManifestEntry(part_staging.entries, std::move(entry), [&](const String & path) + { + part_staging.staged_payloads_by_path.erase(path); + part_staging.borrowed_blob_sources_by_path.erase(path); + }); } -void ContentAddressedTransaction::putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source) +void ContentAddressedTransaction::putEntryWithStagedPayload( + PartStaging & part_staging, Cas::ManifestEntry && entry, StagedPartFilePayloadPtr staged_payload) { - eraseEntry(st, entry.path); - if (source) - st.copy_sources.insert_or_assign(entry.path, std::move(source)); - st.entries.push_back(std::move(entry)); + chassert(staged_payload); + + replaceManifestEntry(part_staging.entries, std::move(entry), [&](const String & path) + { + part_staging.staged_payloads_by_path.insert_or_assign(path, std::move(staged_payload)); + 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_payloads_by_path.erase(path); + }); +} + +void ContentAddressedTransaction::putEntryForHardLinkOrMove( + PartStaging & part_staging, Cas::ManifestEntry && entry, std::shared_ptr borrowed_blob_source, StagedPartFilePayloadPtr staged_payload) +{ + chassert(!(borrowed_blob_source && staged_payload)); + + if (staged_payload) + { + putEntryWithStagedPayload(part_staging, std::move(entry), std::move(staged_payload)); + 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.borrowed_blob_sources_by_path.erase(path); + st.staged_payloads_by_path.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 staged_payload = findStagedPayload(st, entry.path); + auto source = copySourceOf(st, entry.path); + 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_payloads_by_path.erase(entry.path); entry.path = std::move(new_path); } void ContentAddressedTransaction::clearEntries(PartStaging & st) { st.entries.clear(); - st.copy_sources.clear(); + st.borrowed_blob_sources_by_path.clear(); + st.staged_payloads_by_path.clear(); + st.has_finalized_file_write = false; } void ContentAddressedTransaction::markVacatedInBase( @@ -295,8 +402,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; } @@ -377,29 +484,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 { @@ -409,54 +493,92 @@ ContentAddressedTransaction::routeOf(const std::string & path) const return metadata_storage.route(*p); } -namespace +void ContentAddressedTransaction::convertInlineEntryToBlob( + Cas::ManifestEntry & entry, Cas::BlobHashAlgo hash_algo, std::vector & blob_upload_requests) { + chassert(entry.placement == Cas::EntryPlacement::Inline); -/// Only entries supplied by this transaction may change placement. The caller has already -/// excluded shadowed and removed paths from the retained base. -std::vector applyManifestInlineBudget( - std::vector & entries_to_add_or_replace, uint64_t inline_bytes_from_unchanged_base_entries, Cas::BlobHashAlgo algo) -{ - uint64_t total_inline_bytes = inline_bytes_from_unchanged_base_entries; - for (const auto & entry : entries_to_add_or_replace) - if (entry.placement == Cas::EntryPlacement::Inline) - total_inline_bytes += entry.inline_bytes.size(); + /// 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); - if (total_inline_bytes <= Cas::kMaxManifestInlineBytesTotal) - return {}; + 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; +} - 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); +void ContentAddressedTransaction::convertBlobEntryToInline( + Cas::ManifestEntry & entry, PartStaging & part_staging, const Cas::PoolPtr & pool) +{ + chassert(entry.placement == Cas::EntryPlacement::Blob); - std::sort(candidates.begin(), candidates.end(), [](const auto * lhs, const auto * rhs) + const auto & staged_payload = part_staging.staged_payloads_by_path.at(entry.path); + + if (staged_payload->in_memory_payload) + entry.inline_bytes.assign(staged_payload->in_memory_payload->view()); + else { - if (lhs->inline_bytes.size() != rhs->inline_bytes.size()) - return lhs->inline_bytes.size() > rhs->inline_bytes.size(); - return lhs->path < rhs->path; - }); + auto input = openStagedPayload(staged_payload, entry.blob_size, pool); + String bytes(entry.blob_size, '\0'); - std::vector blob_upload_requests; - for (auto * entry : candidates) + 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_payloads_by_path.erase(entry.path); +} + +std::vector ContentAddressedTransaction::applyManifestInlineBudget( + PartStaging & part_staging, const uint64_t inline_bytes_from_unchanged_base_entries) const +{ + const auto pool = metadata_storage.store(); + uint64_t inline_bytes_with_candidates = inline_bytes_from_unchanged_base_entries; + std::vector inline_placement_candidates; + + for (auto & entry : part_staging.entries) { - /// Decoded Inline entries borrowed from a committed manifest have no serialized BlobRef. - const size_t size = entry->inline_bytes.size(); - entry->ref = Cas::poolContentHash(algo, entry->inline_bytes); + const auto 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(); + } + } - blob_upload_requests.push_back({entry->ref, Cas::BlobSource::fromString(std::exchange(entry->inline_bytes, {})), size}); + 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(); + return lhs->path < rhs->path; + }); - entry->blob_size = size; - entry->placement = Cas::EntryPlacement::Blob; - total_inline_bytes -= size; + std::vector blob_upload_requests; + size_t entries_selected_for_blob = 0; - if (total_inline_bytes <= Cas::kMaxManifestInlineBytesTotal) - break; + for (auto * inline_candidate_entry : inline_placement_candidates) + { + if (inline_bytes_with_candidates > Cas::kMaxManifestInlineBytesTotal) + { + 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); } - ProfileEvents::increment(ProfileEvents::CASManifestInlineEntriesSelectedForBlob, blob_upload_requests.size()); - return blob_upload_requests; -} + if (entries_selected_for_blob) + ProfileEvents::increment(ProfileEvents::CASManifestInlineEntriesSelectedForBlob, entries_selected_for_blob); + return blob_upload_requests; } Cas::ManifestId ContentAddressedTransaction::precommitAndUpload( @@ -474,82 +596,47 @@ Cas::ManifestId ContentAddressedTransaction::precommitAndUpload( return id; } -void ContentAddressedTransaction::appendStagedBlobUploads(const PartStaging & st, std::vector & blob_upload_requests) const +std::unique_ptr ContentAddressedTransaction::openStagedPayload(const StagedPartFilePayloadPtr & staged_payload, uint64_t size, const Cas::PoolPtr & pool) { - if (st.pending_blobs.empty()) - return; + 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(staged_payload->pool_staging_key, Cas::Retry::standard()); + if (!staged) + throw Exception(ErrorCodes::FILE_DOESNT_EXIST, "CAS staging object {} disappeared before publication", staged_payload->staging_path); - /// 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; + 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, staged_payload->staging_path); + return staged; +} + +Cas::BlobSource ContentAddressedTransaction::stagedUploadSource(const StagedPartFilePayloadPtr & staged_payload, uint64_t size) const +{ + return { + .size = size, + .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, + }; +} + +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; - source.remote_throttler = pb.remote_throttler; - 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 staged_payload = findStagedPayload(st, entry.path)) + blob_upload_requests.push_back({entry.ref, stagedUploadSource(staged_payload, entry.blob_size), entry.blob_size}); } } @@ -585,8 +672,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); @@ -625,7 +712,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); @@ -735,7 +822,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; } @@ -804,9 +891,9 @@ 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(); - /// All pending blobs have been uploaded in publishStaging; remove their staging resources now. - cleanupPendingTempFiles(); + 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; /// clear it alongside the other per-transaction state resets above. force_fresh_validated_refs.clear(); @@ -860,9 +947,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 staged_payload = findStagedPayload(it->second, entry->path)) + { + if (staged_payload->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)}; } @@ -891,30 +982,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 staged_payload = findStagedPayload(it->second, entry->path)) { - if (pb->backend == Cas::StagingBackend::S3) + if (staged_payload->in_memory_payload) + return std::make_unique>( + staged_payload, /*owns_memory=*/false, path, staged_payload->in_memory_payload->view()); + if (staged_payload->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 = 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(pb->staging_key); + return std::make_unique>(staged_payload, staged_payload->staging_path); } return metadata_storage.readBlobPayload(metadata_storage.store()->locate(*entry), path, settings); } @@ -992,26 +1072,62 @@ void ContentAddressedTransaction::createMetadataFile(const std::string &, const notYet("createMetadataFile"); } +void ContentAddressedTransaction::registerFinalizedPartFile( + 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); + const bool had_build = bool(part_staging.build); + buildFor(route, part_staging); + + SCOPE_EXIT({ + 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_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 = {}}; + putEntryWithStagedPayload(part_staging, std::move(entry), staged_payload); + + staged_payload->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, Cas::StagingBackend backend, - ThrottlerPtr remote_throttler) -{ - /// 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, std::make_shared>(false), std::move(remote_throttler)}); - (void)buildFor(route, st); + const Cas::BlobRef & ref, size_t size, const std::string & staging_key, ObjectStoragePtr remote_storage, + const String & pool_staging_key, ThrottlerPtr remote_throttler) +{ + /// 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 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); - 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); + registerFinalizedPartFile(route, ref, size, staged_payload); + } + catch (...) + { + if (remote_storage) + tryRemoveStagingObject(remote_storage, staging_key); + throw; + } +} + +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) @@ -1019,14 +1135,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 @@ -1163,14 +1282,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(); @@ -1189,11 +1300,15 @@ std::unique_ptr ContentAddressedTransaction::writeFile( /// one capture, so a remount between them cannot stage new-generation bytes under an old epoch. const Cas::PoolPtr pool = metadata_storage.store(); const Cas::MountIncarnation incarnation = pool->captureMountIncarnation(); - const std::string staging_key = metadata_storage.stagingKey(incarnation.writer_epoch, getRandomASCIIString(32) + ".tmp"); + const auto leaf = getRandomASCIIString(32) + ".tmp"; + const auto pool_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(); + /// Only the throttler travels: the caller's other settings describe its own buffer, not this upload. WriteSettings sink_settings; sink_settings.remote_throttler = Cas::makeUploadGuard(settings.remote_throttler, Cas::uploadStopCheck()); - auto object_sink = metadata_storage.objectStorage()->writeObject( + auto object_sink = remote_storage->writeObject( StoredObject(staging_key), WriteMode::Rewrite, /*attributes=*/std::nullopt, DBMS_DEFAULT_BUFFER_SIZE, sink_settings); return std::make_unique( @@ -1204,16 +1319,16 @@ std::unique_ptr ContentAddressedTransaction::writeFile( buf_size, settings.use_adaptive_write_buffer, settings.adaptive_write_buffer_initial_size, - [this, route = *r, hash_algo, throttler = settings.remote_throttler]( - const std::string & hash_hex, size_t size, const std::string & key) + [this, route = *r, hash_algo, remote_storage, pool_staging_key, throttler = settings.remote_throttler]( + 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, Cas::StagingBackend::S3, throttler); + stageBlobPartFile(route, ref, size, staging_object_key, remote_storage, pool_staging_key, throttler); }, [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, throttler = settings.remote_throttler, adaptive = settings.use_adaptive_write_buffer, initial_size = settings.adaptive_write_buffer_initial_size] { @@ -1226,35 +1341,26 @@ std::unique_ptr ContentAddressedTransaction::writeFile( [this, route, hash_algo, throttler](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, throttler); + stageBlobPartFile(route, ref, size, temp_path, nullptr, {}, throttler); }); }; 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, throttler = settings.remote_throttler](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 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); + }); } void ContentAddressedTransaction::createDirectory(const std::string &) @@ -1454,23 +1560,14 @@ 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 staged_payload = findStagedPayload(*src_st, src->file); + auto source = copySourceOf(*src_st, src->file); + auto & build = buildFor(*dst, dst_st); + if (!staged_payload) + build.adoptEvidence(entry); entry.path = dst->file; - putEntry(dst_st, std::move(entry), std::move(source)); + + putEntryForHardLinkOrMove(dst_st, std::move(entry), std::move(source), std::move(staged_payload)); return; } } @@ -1486,15 +1583,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 &) @@ -1637,40 +1737,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_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; + } + 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 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. 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); @@ -1682,18 +1791,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 && !findStagedPayload(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 @@ -1717,7 +1822,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 @@ -1725,7 +1830,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) @@ -1851,28 +1956,22 @@ 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 staged_payload = findStagedPayload(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 (!staged_payload) + build.adoptEvidence(entry); } - putEntry(dst_st, std::move(entry), std::move(source)); + entry.path = dst->file; + markVacatedInBase(*src, src_st, {src->file}); + + putEntryForHardLinkOrMove(dst_st, std::move(entry), std::move(source), std::move(staged_payload)); + eraseEntry(src_st, src->file); return; } /// Source not staged in this transaction: this would cover a standalone one-shot rename of a @@ -1887,17 +1986,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); } @@ -1934,10 +2022,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 dd9d1ec2756e..faa9c66382f6 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -16,14 +16,22 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include +namespace DB::Cas +{ +class InlineCandidatePayload; +class InlineWriteMemoryBudget; +} + namespace DB { @@ -33,10 +41,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 +93,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 +133,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 +145,24 @@ 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 StagedPartFilePayload + { + 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. + ThrottlerPtr remote_throttler; /// The original writer's bandwidth limiter follows the file through hardlinks and moves. + 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}; + + ~StagedPartFilePayload(); + }; + using StagedPartFilePayloadPtr = 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. @@ -147,10 +170,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, @@ -163,25 +185,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); - /// The `remote_throttler` of the settings the file was written with; a hardlink or a move keeps it. - ThrottlerPtr remote_throttler; - }; - 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::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. }; + 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; @@ -190,6 +202,7 @@ class ContentAddressedTransaction : public IMetadataTransaction std::unordered_map> copy_sources_by_part; bool committed = false; bool failed = false; + bool fail_next_file_registration = false; /// Memoizes, per (this transaction, ref), whether `unlinkFile` has already resolved a committed /// ref `ForceFresh`. The MergeTree fast-removal path unlinks every file of a part through ONE @@ -198,22 +211,32 @@ 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 registerFinalizedPartFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, + 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, - Cas::StagingBackend backend, ThrottlerPtr remote_throttler); + ObjectStoragePtr remote_storage, const String & pool_staging_key, ThrottlerPtr remote_throttler); /// 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 nullopt when this transaction uploads or inlines the bytes. - static void putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source); + /// 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 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( + 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, 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. static void rekeyEntry(PartStaging & st, Cas::ManifestEntry & entry, std::string new_path); @@ -243,17 +266,26 @@ class ContentAddressedTransaction : public IMetadataTransaction void discardStagingOf(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 StagedPartFilePayloadPtr findStagedPayload(const PartStaging & st, const String & path); + + static std::unique_ptr openStagedPayload(const StagedPartFilePayloadPtr & staged_payload, uint64_t size, const Cas::PoolPtr & pool); + + 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); + 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. 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; @@ -262,21 +294,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/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/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp new file mode 100644 index 000000000000..40de092793fa --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp @@ -0,0 +1,178 @@ +#include + +#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; +} + +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, + 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_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; + set(&overflow_byte, 1); +} + +InlineCandidateWriteBuffer::~InlineCandidateWriteBuffer() +{ + cancel(); +} + +void InlineCandidateWriteBuffer::nextImpl() +{ + if (local_staging_writer) + { + local_staging_writer->write(working_buffer.begin(), offset()); + return; + } + + /// `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 = in_memory_payload->length + 1; + const size_t target = finishing ? needed + : 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_staging_writer = create_local_staging_writer(); + const auto prefix = in_memory_payload->view(); + if (!prefix.empty()) + 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; + } + in_memory_payload->buffer[in_memory_payload->length++] = overflow_byte; + } + else + { + in_memory_payload->length += offset(); + } + + if (in_memory_payload->length == in_memory_payload->capacity) + set(&overflow_byte, 1); + else + 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_staging_writer) + local_staging_writer->preFinalize(); +} + +void InlineCandidateWriteBuffer::finalizeImpl() +{ + finishing = true; + next(); + if (local_staging_writer) + { + local_staging_writer->finalize(); + return; + } + + set(&overflow_byte, 1); + in_memory_payload->tryShrinkToFit(); + on_in_memory_payload_finalized(std::move(in_memory_payload)); +} + +void InlineCandidateWriteBuffer::cancelImpl() noexcept +{ + set(&overflow_byte, 1); + in_memory_payload.reset(); + if (local_staging_writer) + local_staging_writer->cancel(); +} + +void InlineCandidateWriteBuffer::sync() +{ + next(); + 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 new file mode 100644 index 000000000000..eb4c1bd0efec --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h @@ -0,0 +1,88 @@ +#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); + void tryShrinkToFit(); + + 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 CreateLocalStagingWriter = std::function()>; + using OnInMemoryPayloadFinalized = std::function; + + InlineCandidateWriteBuffer( + String path_, size_t buf_size, size_t max_inline_bytes_, std::shared_ptr budget, + CreateLocalStagingWriter create_local_staging_writer_, OnInMemoryPayloadFinalized on_in_memory_payload_finalized_); + ~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; + + 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 300355f5bd78..34245140ad34 100644 --- a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -2,20 +2,38 @@ #include #include #include +#include #include #include #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 CAS_OWNERSHIP_CONFLICT; + extern const int CORRUPTED_DATA; extern const int INCORRECT_DATA; } @@ -362,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(); @@ -601,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")); @@ -697,3 +752,432 @@ TEST(CASInlineCandidateMemory, ThresholdPreservesPlacementAndPayload) EXPECT_TRUE(storage->tryGetInManifestBytes(dir + "at.idx") == at_limit); 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; + 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(); + 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, 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)); +} + +namespace +{ + +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 = 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())); + 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, 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(); + 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(); + 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_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" diff --git a/src/Disks/tests/gtest_cas_s3_staging.cpp b/src/Disks/tests/gtest_cas_s3_staging.cpp index f96a1c3f5aec..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) { @@ -1179,6 +1226,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(); @@ -1197,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"