diff --git a/docs/concepts/features/configuration/server-config/storing-data.mdx b/docs/concepts/features/configuration/server-config/storing-data.mdx index cdd4621e2ddcf..74458761d9c76 100644 --- a/docs/concepts/features/configuration/server-config/storing-data.mdx +++ b/docs/concepts/features/configuration/server-config/storing-data.mdx @@ -510,10 +510,11 @@ disk-level and server-level settings surface. is committed to the pool (never the object-storage key prefix). Defaults to `/disks//cas_scratch/`. A relative override is anchored to the server data path, not the process's current working directory. -- `cas_staging_backend` — `local` (default) or `s3`. Selects where in-flight part data is staged before - being committed into the pool; `local` is byte-for-byte the original write path, `s3` enables - S3-native staging. A writable disk configured with `s3` must support native same-store copy and - fails closed instead of falling back to client-side copy. +- `cas_staging_backend` — `local` (default) or `s3`. Selects where CAS stages part files that always + use blob placement, such as column data and marks. A writable disk configured with `s3` requires native + same-store copy. Files eligible for inline placement stay in memory up to 1 MiB per file. + Crossing that threshold spills the file to local temporary storage with either backend. At commit, + CAS can also select smaller files for blob placement to fit the 16 MiB inline budget per manifest. - `cas_blob_hash` — `cityhash128` (default), `xxh3-128`, or `sha256`. Selects the pool's blob content-hash function. The choice is fixed at pool creation; a reopen whose `cas_blob_hash` disagrees with the pool's recorded algorithm fails closed. See diff --git a/docs/en/antalya/metrics_and_events.md b/docs/en/antalya/metrics_and_events.md index 30356a6f1cde6..30b36530b330f 100644 --- a/docs/en/antalya/metrics_and_events.md +++ b/docs/en/antalya/metrics_and_events.md @@ -105,6 +105,12 @@ This counter covers batch deletion of write-once keys. | --- | --- | --- | | `CASBulkDeleteRequests` | `Number` | Number of CAS batch delete requests: one DeleteObjects carrying up to 1000 write-once keys (manifest bodies, ref logs, ref snapshots). The per-key class counters (CASManifestDelete, CASRootDelete) say how many keys each request carried. | +#### Manifest inline budget {#cas-manifest-inline-budget} + +| Event | Type | Description | +| --- | --- | --- | +| `CASManifestInlineEntriesSelectedForBlob` | `Number` | Number of staged CAS file entries selected for blob placement because their manifest exceeded the total inline byte budget. | + #### Manifest requests {#cas-manifest-requests} These counters total object-store requests for manifest keys. diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index c9b79615610b7..fe7dd9d19c141 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -910,6 +910,8 @@ The server successfully detected this situation and will download merged part fr M(CASRefRepoint, "Number of CAS committed-reference repoints that republish a manifest. Growth indicates standalone part updates or removals.", ValueType::Number) \ M(CASRefMove, "Number of CAS committed-reference renames done as one ref-log owner move, with no manifest republication.", ValueType::Number) \ M(CASOwnershipConflict, "Number of CAS operations refused with CAS_OWNERSHIP_CONFLICT: the committed reference the writer had read was moved, dropped or repointed before its change landed.", ValueType::Number) \ + M(CASManifestInlineEntriesSelectedForBlob, "Number of staged CAS file entries selected for blob placement because their manifest exceeded the total inline byte budget.", ValueType::Number) \ + M(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 130c3222ee058..7296f94ca85d4 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -36,6 +37,7 @@ namespace ProfileEvents { extern const Event CASBlobUploadFanoutBatches; extern const Event CASBlobUploadFanoutTasks; + extern const Event CASManifestInlineEntriesSelectedForBlob; } namespace fs = std::filesystem; @@ -48,6 +50,7 @@ namespace ErrorCodes extern const int CORRUPTED_DATA; extern const int FILE_DOESNT_EXIST; extern const int LOGICAL_ERROR; + extern const int LIMIT_EXCEEDED; extern const int NOT_IMPLEMENTED; } } @@ -106,10 +109,23 @@ namespace "content-addressed write path.", op); } -/// Inline candidates above this size spill to a blob instead of riding the tree object — a tuning -/// knob (could become a disk setting later). Keeps the tree object bounded against an unexpectedly -/// large eager file. -constexpr size_t INLINE_CAP = 1024 * 1024; /// 1 MiB +/// 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) { @@ -117,17 +133,11 @@ bool hasTopLevelFile(const std::vector & entries) [](const Cas::ManifestEntry & e) { return e.path.find('/') == std::string::npos; }); } -/// A committed manifest with no top-level file is not a part: it is the scratch of a sub-storage nested -/// under the part's directory (`createTemporaryTextIndexStorage`), committed at the part's own name. -bool isNestedScratchManifest(const std::vector & entries) -{ - return !hasTopLevelFile(entries); -} - } ContentAddressedTransaction::ContentAddressedTransaction(ContentAddressedMetadataStorage & metadata_storage_) : metadata_storage(metadata_storage_) + , inline_write_budget(std::make_shared(INLINE_WRITE_MEMORY_LIMIT)) { } @@ -135,7 +145,7 @@ ContentAddressedTransaction::~ContentAddressedTransaction() { /// On abort this is the cleanup of local and S3 staging. After a commit it finds nothing left, /// except when the commit published some parts and then threw. - cleanupPendingTempFiles(); + releaseStagedFiles(); /// An uncommitted transaction's uploads become min_active_build_sequence-spared debris: abandon every /// still-open PartWriteTxn so its build_seq is retired. This replaces the former pin machinery. @@ -203,68 +213,94 @@ ContentAddressedTransaction::PartStaging * ContentAddressedTransaction::findStag return it == parts.end() ? nullptr : &it->second; } -void ContentAddressedTransaction::cleanupPendingTempFiles() noexcept +namespace { - for (auto & [key, st] : parts) +void removeStagingObject(const ObjectStoragePtr & storage, const String & key) noexcept +{ + try { - for (const auto & pb : st.pending_blobs) - { - if (pb.backend == Cas::StagingBackend::Local) - { - std::error_code ec; - std::filesystem::remove(pb.staging_key, ec); - } - else - { - /// The S3 staging object is private to this transaction and nothing reads - /// `pending_blobs` after this call, so commit and abort delete it alike. An object that - /// outlived an abort would stay until the next mount of this `server_root_id`. - try - { - metadata_storage.objectStorage()->removeObjectIfExists(StoredObject(pb.staging_key)); - } - catch (...) // NOLINT(bugprone-empty-catch) - { - /// Best-effort (noexcept context): a stubborn delete leaves debris for the mount-start sweep. - } - } - } - st.pending_blobs.clear(); + storage->removeObjectIfExists(StoredObject(key)); + } + catch (...) + { + tryLogCurrentException(getLogger("ContentAddressedTransaction"), "removing a private staging object"); } } +} -const ContentAddressedTransaction::PartStaging::PendingBlob * -ContentAddressedTransaction::findPendingBlob(const PartStaging & st, const Cas::BlobRef & ref) const +ContentAddressedTransaction::StagedPartFile::~StagedPartFile() { - /// Locate a pending blob by ref. Returns nullptr when the blob has already been uploaded - /// (post-precommit, pending_blobs is cleared) or was never staged as pending. - for (const auto & pb : st.pending_blobs) - if (pb.ref == ref) - return &pb; - return nullptr; + if (!registered || memory) + return; + if (remote_storage) + removeStagingObject(remote_storage, staging_path); + else + { + std::error_code ec; + fs::remove(staging_path, ec); + } } -void ContentAddressedTransaction::putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source) +void ContentAddressedTransaction::releaseStagedFiles() noexcept { - eraseEntry(st, entry.path); - if (source) - st.copy_sources.insert_or_assign(entry.path, std::move(source)); - st.entries.push_back(std::move(entry)); + for (auto & [key, st] : parts) + st.staged_part_files.clear(); +} + +ContentAddressedTransaction::StagedPartFilePtr ContentAddressedTransaction::stagedFileOf(const PartStaging & st, const String & path) +{ + const auto it = st.staged_part_files.find(path); + return it == st.staged_part_files.end() ? nullptr : it->second; +} + +void ContentAddressedTransaction::putEntry( + PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source, StagedPartFilePtr file) +{ + auto it = std::find_if(st.entries.begin(), st.entries.end(), [&](const auto & e) { return e.path == entry.path; }); + const bool inserted = it == st.entries.end(); + if (inserted) + { + st.entries.emplace_back(); + it = std::prev(st.entries.end()); + } + /// Install the possibly allocating map node before retiring the previous path or its source. + try + { + if (file) + st.staged_part_files.insert_or_assign(entry.path, file); + else if (source) + st.copy_sources.insert_or_assign(entry.path, source); + } + catch (...) + { + if (inserted) + st.entries.pop_back(); + throw; + } + if (!file) + st.staged_part_files.erase(entry.path); + if (!source) + st.copy_sources.erase(entry.path); + *it = std::move(entry); } void ContentAddressedTransaction::eraseEntry(PartStaging & st, const std::string & path) { std::erase_if(st.entries, [&](const Cas::ManifestEntry & e) { return e.path == path; }); st.copy_sources.erase(path); + st.staged_part_files.erase(path); } void ContentAddressedTransaction::rekeyEntry(PartStaging & st, Cas::ManifestEntry & entry, std::string new_path) { - if (auto node = st.copy_sources.extract(entry.path)) - { - node.key() = new_path; - st.copy_sources.insert(std::move(node)); - } + auto file = stagedFileOf(st, entry.path); + auto source = copySourceOf(st, entry.path); + if (file) + st.staged_part_files.emplace(new_path, std::move(file)); + if (source) + st.copy_sources.emplace(new_path, std::move(source)); + st.copy_sources.erase(entry.path); + st.staged_part_files.erase(entry.path); entry.path = std::move(new_path); } @@ -272,6 +308,8 @@ void ContentAddressedTransaction::clearEntries(PartStaging & st) { st.entries.clear(); st.copy_sources.clear(); + st.staged_part_files.clear(); + st.has_finalized_file_write = false; } void ContentAddressedTransaction::markVacatedInBase( @@ -295,7 +333,7 @@ std::shared_ptr ContentAddressedTransaction::copySourceOf(const } void ContentAddressedTransaction::confirmCopySources(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, - const PendingRefs & pending_refs) + const PendingRefs & blob_refs_with_upload_requests) { /// An entry whose bytes this transaction uploads is protected by its own precommit, whatever it was copied from. std::vector> sources; @@ -305,7 +343,7 @@ void ContentAddressedTransaction::confirmCopySources(const Cas::RootNamespace & { return s->part == source.part && s->manifest_ref == source.manifest_ref; }); }; for (const auto & entry : st.entries) - if (auto source = copySourceOf(st, entry.path); source && !pending_refs.contains(entry.ref) && !listed(*source)) + if (auto source = copySourceOf(st, entry.path); source && !blob_refs_with_upload_requests.contains(entry.ref) && !listed(*source)) sources.push_back(std::move(source)); /// A source this transaction changes before it publishes the copy no longer commits the manifest the copy @@ -370,29 +408,6 @@ void ContentAddressedTransaction::retargetCopySource(const Cas::PartRefKey & fro copy_sources_by_part.try_emplace(to.cacheKey(), borrow); } -void ContentAddressedTransaction::adoptStagedBlob( - const PartStaging::PendingBlob * pb, const Cas::ManifestEntry & entry, - PartStaging & dst_st, Cas::PartWriteTxn & dst_build, bool copy_pending) -{ - if (pb) - { - /// Pending blob (not yet uploaded): no dependency exists until publication succeeds. If - /// copy_pending, push a copy of the pb record into dst_st so publishStaging uploads it - /// for the dst part too (hardlink = copy semantics). If !copy_pending, the record is already - /// in dst_st (moved by caller) — skip the push. - if (copy_pending) - dst_st.pending_blobs.push_back(*pb); - } - else - { - /// Uploaded / committed: record trusted-manifest evidence — no pool HEAD/GET before precommit. - /// §4 manifest-trust: the publish gate (promote) TRUSTS this committed-source adopted leaf via the - /// durable manifest edge — it does not observe or republish it. Pending uploads establish - /// `Materialized` through `putBlob` before promote; a genuinely absent adopted blob is an fsck finding. - dst_build.adoptEvidence(entry); - } -} - std::optional ContentAddressedTransaction::routeOf(const std::string & path) const { @@ -402,100 +417,133 @@ ContentAddressedTransaction::routeOf(const std::string & path) const return metadata_storage.route(*p); } -Cas::ManifestId ContentAddressedTransaction::precommitAndUpload(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, - const PendingRefs & pending_refs) +std::vector ContentAddressedTransaction::applyManifestInlineBudget( + PartStaging & st, uint64_t inline_bytes_from_unchanged_base_entries) const { - /// Edge before observe: the precommit names every blob before `putBlob` observes one, so a condemnation between - /// the upload and the promote cannot delete a body this build relies on. - const Cas::ManifestId id = st.build->stageManifest(st.entries); - st.build->precommitAdd(ns, ref, id); - confirmCopySources(ns, ref, st, pending_refs); - uploadPendingBlobs(st); - return id; -} + const auto pool = metadata_storage.store(); + uint64_t total_inline_bytes = inline_bytes_from_unchanged_base_entries; + std::vector candidates; -void ContentAddressedTransaction::uploadPendingBlobs(PartStaging & st) -{ - /// Build the set of blob hashes actually referenced by the staged manifest. Only Blob - /// entries represent pending content uploads — Inline are not pending blobs. A pending_blob whose - /// hash is NOT in this set had its entry removed by unlinkFile/replaceFile and must not be uploaded - /// (it is an orphan). Its temp file is still cleaned by cleanupPendingTempFiles at commit end. - std::unordered_set referenced_hashes; - for (const auto & entry : st.entries) - if (entry.placement == Cas::EntryPlacement::Blob) - referenced_hashes.insert(entry.ref); - - /// Build one 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. - std::vector requests; - requests.reserve(st.pending_blobs.size()); - for (const auto & pb : st.pending_blobs) + for (auto & entry : st.entries) + { + const auto file = stagedFileOf(st, entry.path); + if (entry.placement == Cas::EntryPlacement::Inline || (file && file->allow_inline_by_name && entry.blob_size <= Cas::kMaxManifestInlineEntryBytes)) + { + candidates.push_back(&entry); + total_inline_bytes += entry.size(); + } + } + + if (total_inline_bytes > Cas::kMaxManifestInlineBytesTotal) + std::sort(candidates.begin(), candidates.end(), [](const auto * lhs, const auto * rhs) + { + if (lhs->size() != rhs->size()) + return lhs->size() > rhs->size(); + return lhs->path < rhs->path; + }); + + std::vector blob_upload_requests; + size_t spilled = 0; + + for (auto * entry : candidates) { - if (!referenced_hashes.contains(pb.ref)) - continue; /// The entry was removed by unlinkFile/replaceFile; skip this orphan. - Cas::BlobSource source; - source.size = pb.size; - source.publication_attempted = pb.publication_attempted; - if (pb.backend == Cas::StagingBackend::S3) + const auto size = entry->size(); + + if (total_inline_bytes > Cas::kMaxManifestInlineBytesTotal) { - 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 + total_inline_bytes -= size; + ++spilled; + if (entry->placement == Cas::EntryPlacement::Inline) { - 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; - }; + /// A borrowed Inline has no staging file. Its bytes came from the committed manifest. + entry->ref = Cas::poolContentHash(pool->writeAlgo(), entry->inline_bytes); + blob_upload_requests.push_back({entry->ref, Cas::BlobSource::fromString(std::exchange(entry->inline_bytes, {})), size}); + entry->blob_size = size; + entry->placement = Cas::EntryPlacement::Blob; + } } - else + else if (entry->placement == Cas::EntryPlacement::Blob) { - const std::string staging_key = pb.staging_key; - const uint64_t payload_size = pb.size; - source.open = [staging_key, payload_size]() -> std::unique_ptr + const auto & file = st.staged_part_files.at(entry->path); + if (file->memory) + entry->inline_bytes.assign(file->memory->view()); + else { - return Cas::openLocalStagedBlobPayload(staging_key, payload_size); - }; + auto input = openStagedPayload(file, size, pool); + String bytes(size, '\0'); + input->readStrict(bytes.data(), bytes.size()); + if (!input->eof() || Cas::poolContentHash(entry->ref.algo, bytes) != entry->ref) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Staged inline payload does not match the size or hash of {}", entry->path); + entry->inline_bytes = std::move(bytes); + } + entry->placement = Cas::EntryPlacement::Inline; + entry->blob_size = 0; + /// The entry now owns its bytes. Hardlinks and open readers retain their own references to the staging source. + st.staged_part_files.erase(entry->path); } - /// `declared_size` mirrors `source.size` (both are `pb.size`); the fan-out fail-closes if they - /// ever diverge, so build them together from the one authority. - requests.push_back(Cas::BlobUploadRequest{pb.ref, std::move(source), pb.size}); } - if (requests.empty()) - return; + if (spilled) + ProfileEvents::increment(ProfileEvents::CASManifestInlineEntriesSelectedForBlob, spilled); + return blob_upload_requests; +} + +Cas::ManifestId ContentAddressedTransaction::precommitAndUpload( + const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, const PendingRefs & blob_refs_with_upload_requests, + const std::vector & blob_upload_requests) +{ + /// Edge before observe: the precommit names every blob before the pool observes it. + const Cas::ManifestId id = st.build->stageManifest(st.entries); + st.build->precommitAdd(ns, ref, id); + confirmCopySources(ns, ref, st, blob_refs_with_upload_requests); + + if (!blob_upload_requests.empty()) + Cas::fanOutBlobUploads(*st.build, blob_upload_requests, Cas::blobUploadPool()); + + return id; +} + +std::unique_ptr ContentAddressedTransaction::openStagedPayload(const StagedPartFilePtr & file, uint64_t size, const Cas::PoolPtr & pool) +{ + if (file->memory) + return std::make_unique>(file, file->memory->view()); + if (!file->remote_storage) + return Cas::openLocalStagedBlobPayload(file->staging_path, size); + + auto op = pool->mountRequests().admit(); + auto staged = op.stream(file->pool_staging_key, Cas::Retry::standard()); + if (!staged) + throw Exception(ErrorCodes::FILE_DOESNT_EXIST, "CAS staging object {} disappeared before publication", file->staging_path); + + const auto header_len = pool->poolMeta().blob_header_len; + String header(header_len, '\0'); + staged->readStrict(header.data(), header.size()); + const auto decoded = Cas::decodeEnvelopeHeader(header, header_len + size, Cas::ObjectKind::Blob); + + if (decoded.header_len != header_len) + throw Exception(ErrorCodes::CORRUPTED_DATA, "Unexpected envelope length {} in staging object {}", decoded.header_len, file->staging_path); + return staged; +} + +Cas::BlobSource ContentAddressedTransaction::stagedUploadSource(const StagedPartFilePtr & file, uint64_t size) const +{ + return { + .size = size, + .open = [pool = metadata_storage.store(), file, size] { return openStagedPayload(file, size, pool); }, + .server_side_copy_from = file->remote_storage ? std::optional(file->staging_path) : std::nullopt, + .publication_attempted = std::shared_ptr>(file, &file->publication_attempted), + }; +} - /// Fan out the uploads on the server-wide pool (spec §1). The fan-out enforces - /// one-task-per-unique-ref grouping, the merge-nothing failure contract, and merges every result - /// into `st.build`'s dep set on THIS (the owning writer) thread after the join. - Cas::fanOutBlobUploads(*st.build, requests, Cas::blobUploadPool()); +void ContentAddressedTransaction::appendStagedBlobUploads(const PartStaging & st, std::vector & blob_upload_requests) const +{ + for (const auto & entry : st.entries) + { + if (entry.placement != Cas::EntryPlacement::Blob) + continue; + if (auto file = stagedFileOf(st, entry.path)) + blob_upload_requests.push_back({entry.ref, stagedUploadSource(file, entry.blob_size), entry.blob_size}); + } } void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, @@ -523,87 +571,111 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, return; } - PendingRefs pending_refs; - for (const auto & pb : st.pending_blobs) - pending_refs.insert(pb.ref); + std::shared_ptr existing_ref_view; + if (!st.entries.empty() || !st.content_removed.empty()) + existing_ref_view = metadata_storage.partAccess()->getView({ns, ref}, Cas::Freshness::ForceFresh); + + /// A merge can use two disk transactions under `tmp_merge_`. The first publishes the `text_index_tmp/` segments. + /// Once the merge has read them and written the final index files, the part transaction can drop the ref to the + /// segment manifest and publish the complete part manifest under the same name. + /// 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); + + /// A rewrite requires the ref to still point to its base manifest. + /// A write with no base expects the name to be free unless it can replace the temporary segment ref described above. + if (st.base_manifest_ref && (!existing_ref_view || existing_ref_view->manifestId().ref != *st.base_manifest_ref)) + Cas::throwCasOwnershipConflict("ContentAddressedTransaction: committed part {}/{} was moved, dropped or repointed while its rewrite was staged; " + "the operation must be re-resolved", ns.string(), ref); + if (!st.base_manifest_ref && existing_ref_view && !should_drop_existing_ref) + Cas::throwCasOwnershipConflict("ContentAddressedTransaction: {}/{} was published by another writer while this transaction was staging it", ns.string(), ref); + + std::vector merged_manifest_entries; + uint64_t inline_bytes_from_unchanged_base_entries = 0; + + /// After `BEGIN TRANSACTION`, an `INSERT` can publish part `all_1_1_0` in CAS while the SQL transaction is still open. + /// At `COMMIT`, `MergeTree` rewrites `txn_version.txt` to record the assigned commit sequence number. That disk transaction + /// stages only the new `txn_version.txt`. Carry forward the base entries for `data.bin` and the other untouched files, + /// including their inline bytes in the budget for the new manifest. + if (existing_ref_view && !should_drop_existing_ref) + { + std::unordered_set staged_entry_paths; + for (const auto & entry : st.entries) + staged_entry_paths.insert(entry.path); + for (const auto & entry : existing_ref_view->manifest()->entries) + { + if (st.content_removed.contains(entry.path) || staged_entry_paths.contains(entry.path)) + continue; + if (entry.placement == Cas::EntryPlacement::Inline) + inline_bytes_from_unchanged_base_entries += entry.inline_bytes.size(); + merged_manifest_entries.push_back(entry); + } + if (inline_bytes_from_unchanged_base_entries > Cas::kMaxManifestInlineBytesTotal) + throw Exception(ErrorCodes::LIMIT_EXCEEDED, + "Unchanged manifest entries for {}/{} contain {} inline bytes, exceeding the cap of {}", + ns.string(), ref, inline_bytes_from_unchanged_base_entries, Cas::kMaxManifestInlineBytesTotal); + } + + auto blob_upload_requests = applyManifestInlineBudget(st, inline_bytes_from_unchanged_base_entries); + if (!blob_upload_requests.empty() && !st.build) + buildFor({.ns = ns, .ref = ref, .file = {}}, st); + + appendStagedBlobUploads(st, blob_upload_requests); + + PendingRefs blob_refs_with_upload_requests; + + for (const auto & blob_upload_request : blob_upload_requests) + blob_refs_with_upload_requests.insert(blob_upload_request.ref); - /// A blob entry's body is either uploaded by this part or confirmed at its committed source; a part may be - /// promoted before any other part of this transaction publishes, so nothing else can supply the body. for (const auto & entry : st.entries) - if (entry.placement == Cas::EntryPlacement::Blob && !pending_refs.contains(entry.ref) && !copySourceOf(st, entry.path)) + if (entry.placement == Cas::EntryPlacement::Blob && !blob_refs_with_upload_requests.contains(entry.ref) && !copySourceOf(st, entry.path)) throw Exception(ErrorCodes::LOGICAL_ERROR, "ContentAddressedTransaction: staged blob '{}' of {}/{} has neither a pending upload nor a copy source", entry.path, ns.string(), ref); - /// For committed-ref standalone writes and removal marks, `st.entries` holds only the - /// CHANGED/ADDED entries (see stageBlobPartFile / the inline writeFile path) — never the whole - /// part once the ref already exists; `st.content_removed` holds paths a same-transaction - /// unlinkFile staged for removal (§6). Carry every OTHER committed entry forward (minus any - /// content_removed path) and republish once via the repoint path, rather than letting the - /// PartWriteTxn path below replace the manifest with just the delta. That would either reject a - /// genuine content change or silently drop untouched files. This handles both sub-cases the - /// interface allows: entries staged - /// WITH a PartWriteTxn (this transaction uploaded new content) and WITHOUT one (a former mutable - /// per-part file that is now an ordinary tree entry, or a marks-only removal with no writes). - if (!st.entries.empty() || !st.content_removed.empty()) + if (should_drop_existing_ref) { - auto view = metadata_storage.partAccess()->getView({ns, ref}, Cas::Freshness::ForceFresh); - /// A build that stages the part's own top-level files replaces a nested scratch manifest at the - /// same name instead of merging into it. - if (view && st.build && (!st.base_manifest_ref || *st.base_manifest_ref == view->manifestId().ref) - && isNestedScratchManifest(view->manifest()->entries) && hasTopLevelFile(st.entries)) - { - if (metadata_storage.partAccess()->dropRefExact({ns, ref}, view->manifestId().ref) - == Cas::Removal::Mismatch) - Cas::throwCasOwnershipConflict("ContentAddressedTransaction: scratch ref {}/{} was repointed while this transaction was staging the part", - ns.string(), ref); - st.base_manifest_ref.reset(); - view.reset(); - } - if (st.base_manifest_ref && (!view || !(view->manifestId().ref == *st.base_manifest_ref))) - Cas::throwCasOwnershipConflict("ContentAddressedTransaction: committed part {}/{} was moved, dropped or repointed while its rewrite was staged; " - "the operation must be re-resolved", ns.string(), ref); - if (!st.base_manifest_ref && view) - Cas::throwCasOwnershipConflict("ContentAddressedTransaction: {}/{} was published by another writer while this transaction was staging it", ns.string(), ref); - if (view) + if (metadata_storage.partAccess()->dropRefExact({ns, ref}, existing_ref_view->manifestId().ref) == Cas::Removal::Mismatch) + Cas::throwCasOwnershipConflict("ContentAddressedTransaction: scratch ref {}/{} was repointed while this transaction was staging the part", + ns.string(), ref); + + st.base_manifest_ref.reset(); + existing_ref_view.reset(); + } + else if (existing_ref_view) + { + /// The scratch precommit protects new blobs until repointRef publishes the merged manifest. + if (st.build) + (void)precommitAndUpload(ns, ref, st, blob_refs_with_upload_requests, blob_upload_requests); + + for (auto & entry : st.entries) + merged_manifest_entries.push_back(std::move(entry)); + + /// Test-only fault seam (Task 3 TDD): simulate a promote-time backend failure for `ref` + /// right before the durable repoint call. A no-op in production (nothing ever arms it). + if (metadata_storage.shouldFailPromoteForTest({ns, ref})) + throw Exception(ErrorCodes::ABORTED, + "ContentAddressedTransaction: test-injected promote failure for {}/{}", ns.string(), ref); + + /// Capture the exact `CommitOutcome` IMMEDIATELY -- into the caller-provided slot, before + /// the scratch-build `abandon()` below (which can itself throw), and before the test-only + /// after-promote hook (which can run arbitrary test code) -- so a later throw in either + /// cannot lose it (publish before any throwable post-commit work). + const Cas::CommitOutcome oc = metadata_storage.partAccess()->repointRef({ns, ref}, std::move(merged_manifest_entries), Cas::ProvenanceOp::Other, *st.base_manifest_ref); + out_slot = oc; /// always created=false here: this block only runs once `existing_ref_view` already resolved + /// Test-only: models a concurrent writer racing in right after this transaction's own + /// confirm (e.g. repointing `ref` again). A no-op in production. + metadata_storage.runAfterPromoteHookForTest({ns, ref}); + + if (st.build) { - /// `repointRef` promotes through its own build, which adopts existing bodies and uploads none. This build's - /// scratch precommit protects the uploads until that promote, then is abandoned, never promoted. - if (st.build) - (void)precommitAndUpload(ns, ref, st, pending_refs); - - std::vector merged; - for (const auto & e : view->manifest()->entries) - if (!st.content_removed.contains(e.path) - && std::none_of(st.entries.begin(), st.entries.end(), - [&](const Cas::ManifestEntry & s) { return s.path == e.path; })) - merged.push_back(e); - for (auto & s : st.entries) - merged.push_back(std::move(s)); - - /// Test-only fault seam (Task 3 TDD): simulate a promote-time backend failure for `ref` - /// right before the durable repoint call. A no-op in production (nothing ever arms it). - if (metadata_storage.shouldFailPromoteForTest({ns, ref})) - throw Exception(ErrorCodes::ABORTED, - "ContentAddressedTransaction: test-injected promote failure for {}/{}", ns.string(), ref); - - /// Capture the exact `CommitOutcome` IMMEDIATELY -- into the caller-provided slot, before - /// the scratch-build `abandon()` below (which can itself throw), and before the test-only - /// after-promote hook (which can run arbitrary test code) -- so a later throw in either - /// cannot lose it (publish before any throwable post-commit work). - const Cas::CommitOutcome oc = metadata_storage.partAccess()->repointRef({ns, ref}, std::move(merged), Cas::ProvenanceOp::Other, *st.base_manifest_ref); - out_slot = oc; /// always created=false here: this block only runs once `view` already resolved - /// Test-only: models a concurrent writer racing in right after this transaction's own - /// confirm (e.g. repointing `ref` again). A no-op in production. - metadata_storage.runAfterPromoteHookForTest({ns, ref}); - if (st.build) - { - st.build->abandon(); /// scratch precommit's protecting job is done; the real manifest is live - st.build.reset(); /// never re-abandon this build from the destructor - } - st.published = true; - return; + st.build->abandon(); /// scratch precommit's protecting job is done; the real manifest is live + st.build.reset(); /// never re-abandon this build from the destructor } + st.published = true; + return; } if (!st.build) @@ -611,7 +683,7 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, "ContentAddressedTransaction: staged entries or removal marks for {}/{} without a Build", ns.string(), ref); /// Promote is an atomic owner move that validates every blob dependency proof. - const Cas::ManifestId id = precommitAndUpload(ns, ref, st, pending_refs); + const Cas::ManifestId manifest_id = precommitAndUpload(ns, ref, st, blob_refs_with_upload_requests, blob_upload_requests); /// Test-only fault seam (Task 3 TDD): simulate a promote-time backend failure for `ref` right /// before the durable promote call. A no-op in production (nothing ever arms it). @@ -624,7 +696,7 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, /// before the promote's own append confirms). Captured into `out_slot` IMMEDIATELY -- before the /// test-only after-promote hook below (which can run arbitrary test code) or `st.build.reset()` /// -- so a later throw there cannot lose it. - const Cas::CommitOutcome oc = metadata_storage.partAccess()->promoteBuild(*st.build, {ns, ref}, st.build->buildId(), id); + const Cas::CommitOutcome oc = metadata_storage.partAccess()->promoteBuild(*st.build, {ns, ref}, st.build->buildId(), manifest_id); out_slot = oc; /// Test-only: models a concurrent writer racing in right after this transaction's own confirm. A /// no-op in production. @@ -651,7 +723,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; } @@ -699,6 +771,8 @@ void ContentAddressedTransaction::commit(const TransactionCommitOptionsVariant & } catch (...) { + /// Publication may already have moved inline bytes out of staged entries into blob upload requests. + /// Retrying requires a new transaction with fresh entries. failed = true; /// Compensating rollback. Best-effort: a ref we cannot unpublish becomes unreferenced debris /// (GC-reclaimed); never mask the original failure with a rollback failure. Only a slot whose @@ -717,8 +791,8 @@ void ContentAddressedTransaction::commit(const TransactionCommitOptionsVariant & copy_sources_by_part.clear(); for (auto & [key, st] : parts) st.copy_sources.clear(); - /// All pending blobs have been uploaded in publishStaging; remove their staging resources now. - cleanupPendingTempFiles(); + /// Uploads are complete. Readers opened during the transaction can still own their staging files. + releaseStagedFiles(); /// This transaction's unlinkFile ForceFresh-proof memoization is scoped to this transaction only; /// clear it alongside the other per-transaction state resets above. force_fresh_validated_refs.clear(); @@ -772,9 +846,13 @@ std::optional ContentAddressedTransaction::tryGetInFlightStorageO if (entry->placement == Cas::EntryPlacement::Blob) { /// A pending blob has not been uploaded yet — its storage object does not exist in - /// the pool. Return empty so the caller falls back to tryReadFileInFlight (local temp read). - if (findPendingBlob(it->second, entry->ref)) + /// the pool. Return empty so the caller reads the private staging file through tryReadFileInFlight. + if (auto file = stagedFileOf(it->second, entry->path)) + { + if (file->allow_inline_by_name && entry->blob_size <= Cas::kMaxManifestInlineEntryBytes) + return StoredObjects{StoredObject("", path, entry->blob_size)}; return {}; + } const auto location = metadata_storage.store()->locate(*entry); return StoredObjects{StoredObject(location.key, path, location.length)}; } @@ -803,30 +881,19 @@ std::unique_ptr ContentAddressedTransaction::tryReadFile return std::make_unique(path, entry->inline_bytes); if (entry->placement == Cas::EntryPlacement::Blob) { - /// A pending blob has not been uploaded yet — serve reads from the staging area (the - /// same bytes that will be promoted to the pool in publishStaging post-precommit): a local - /// temp file for `Cas::StagingBackend::Local`, or the S3 staging object for `Cas::StagingBackend::S3` - /// (`staging_key` is a remote object key there, never a - /// local path, so `ReadBufferFromFile` would misinterpret it as a filesystem path). - if (const auto * pb = findPendingBlob(it->second, entry->ref)) + if (auto file = stagedFileOf(it->second, entry->path)) { - if (pb->backend == Cas::StagingBackend::S3) + if (file->memory) + return std::make_unique>( + file, /*owns_memory=*/false, path, file->memory->view()); + if (file->remote_storage) { - /// The staging object holds `[header][payload]` - /// (the fixed-length `blob_header_len` CABL envelope, so the promote can stay a - /// verbatim server-side copy). Read-your-writes must serve the PAYLOAD ONLY — wrap the - /// object read in a `ReadBufferFromFileView` windowed to `[header_len, header_len+size)` - /// so position 0 is the payload start, else the reader would see 256 bytes of header - /// prepended to the payload (corruption). The LOCAL staging temp file holds the payload - /// verbatim (no header), so its path is unchanged. - const uint64_t header_len = metadata_storage.store()->poolMeta().blob_header_len; - const uint64_t payload_end = header_len + pb->size; - auto impl = metadata_storage.objectStorage()->readObject( - StoredObject(pb->staging_key, path, payload_end), settings); - return std::make_unique( - std::move(impl), path, header_len, payload_end); + const auto offset = metadata_storage.store()->poolMeta().blob_header_len; + const auto end = offset + entry->blob_size; + auto input = file->remote_storage->readObject(StoredObject(file->staging_path, path, end), settings); + return std::make_unique>(file, std::move(input), path, offset, end); } - return std::make_unique(pb->staging_key); + return std::make_unique>(file, file->staging_path); } return metadata_storage.readBlobPayload(metadata_storage.store()->locate(*entry), path, settings); } @@ -904,24 +971,55 @@ void ContentAddressedTransaction::createMetadataFile(const std::string &, const notYet("createMetadataFile"); } +void ContentAddressedTransaction::registerStagedFile( + const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::shared_ptr & file) +{ + std::lock_guard lock(file_registration_mutex); + auto & st = stagingFor(route); + const bool had_build = bool(st.build); + buildFor(route, st); + + SCOPE_EXIT({ + if (!had_build && !file->registered) + st.build.reset(); + }); + + if (std::exchange(fail_next_file_registration, false)) + throw Exception(ErrorCodes::ABORTED, "Injected failure registering staged file {}", route.file); + + file->allow_inline_by_name = !Cas::partFileMustStayBlob(route.file); + Cas::ManifestEntry entry{.path = route.file, .placement = Cas::EntryPlacement::Blob, .ref = ref, .blob_size = size, .inline_bytes = {}}; + putEntry(st, std::move(entry), nullptr, file); + + file->registered = true; + st.has_finalized_file_write = true; +} + void ContentAddressedTransaction::stageBlobPartFile( const ContentAddressedMetadataStorage::Route & route, - const Cas::BlobRef & ref, size_t size, const std::string & staging_key, Cas::StagingBackend backend) + const Cas::BlobRef & ref, size_t size, const std::string & staging_key, ObjectStoragePtr remote_storage, const String & pool_key) { - /// Do not upload here. Record the pending blob for post-precommit publication; dependency state - /// remains absent until the upload succeeds and its result is merged. - /// The staging bytes are kept (the transaction owns them) — a local temp file for - /// `Cas::StagingBackend::Local`, or an S3 staging object for `Cas::StagingBackend::S3`. - auto & st = stagingFor(route); - st.pending_blobs.push_back({ref, staging_key, size, backend}); - (void)buildFor(route, st); + /// The local writer still owns its scratch path if registration throws. The S3 sink + /// has already finalized the object, so this callback cleans it up on failure. + try + { + auto file = std::make_shared(); + file->staging_path = staging_key; + file->remote_storage = remote_storage; + file->pool_staging_key = pool_key; + registerStagedFile(route, ref, size, file); + } + catch (...) + { + if (remote_storage) + removeStagingObject(remote_storage, staging_key); + throw; + } +} - Cas::ManifestEntry entry; - entry.path = route.file; - entry.placement = Cas::EntryPlacement::Blob; - entry.ref = ref; - entry.blob_size = size; - putEntry(st, std::move(entry), nullptr); +size_t ContentAddressedTransaction::inlineCandidateReservedBytesForTest() const noexcept +{ + return inline_write_budget->reservedBytes(); } void ContentAddressedTransaction::stageUnprovenBlobEntryForTest(const std::string & path, const Cas::BlobRef & ref, uint64_t size) @@ -1073,135 +1171,75 @@ 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. - - /// A CONTENT part file that must stay a blob (per-column data/marks, primary.idx): spill + hash, - /// then stage the blob as PENDING (precommit-first). The blob is NOT uploaded/promoted here; - /// `publishStaging` uploads it (Local) or promotes the S3 staging object post-precommit. - /// Staging records no dependency proof and performs no pool operation; successful post-precommit - /// publication records `Materialized`. - if (Cas::partFileMustStayBlob(r->file)) + const bool must_stay_blob = Cas::partFileMustStayBlob(r->file); + const auto hash_algo = metadata_storage.store()->writeAlgo(); + + if (must_stay_blob && metadata_storage.stagingBackend() == Cas::StagingBackend::S3) { - /// When this disk explicitly opts in to `staging_backend=s3`, `startup` has already required - /// provider-native same-store copy, so stream directly to a fresh per-mount staging object - /// while hashing. The default `local` setting keeps the existing local-temp-file path below. - /// Hash with this pool's node-local write algorithm rather than a hardcoded city hash; - /// `PoolMeta` no longer records a single pool-wide algorithm -- - /// mixed-algo pools track `algos_used`; `writeAlgo()` is the write-mint accessor now). - const auto hash_algo = metadata_storage.store()->writeAlgo(); - /// `hash_hex` is rendered by the streaming write buffer at `hash_algo`'s own width — - /// parse it back at that SAME width via `Cas::codecFor(hash_algo)` (never a pool-wide - /// `DigestCodec`, which no longer exists) into a full `BlobRef` pair. - - if (metadata_storage.stagingBackend() == Cas::StagingBackend::S3) - { - /// Build the fixed-length CABL envelope header now (before - /// the payload is streamed) so the staging object holds `[header][payload]` and the promote - /// stays a verbatim server-side copy. The header carries a FRESH `incarnation_tag`; `build_id` - /// is left 0 (not known at stream time — diagnostic-only, not read by GC/read paths). The - /// buffer writes this header first, UNHASHED and excluded from the reported size, so the - /// content key stays the pool's hash of `payload` and `blob_size` stays the payload size. - std::string envelope_header = buildS3StagingBlobHeader(*r); - /// The staged upload becomes durable in `sink->finalize()`, outside this request contract by - /// design, so its admission is re-checked there through the callback below, against the - /// generation captured HERE. The epoch in the key and the generation the finalize rechecks are - /// one capture, so a remount between them cannot stage new-generation bytes under an old epoch. - const Cas::PoolPtr pool = metadata_storage.store(); - const Cas::MountIncarnation incarnation = pool->captureMountIncarnation(); - const std::string staging_key = metadata_storage.stagingKey(incarnation.writer_epoch, getRandomASCIIString(32) + ".tmp"); - auto object_sink = metadata_storage.objectStorage()->writeObject(StoredObject(staging_key), WriteMode::Rewrite); - return std::make_unique( - std::move(object_sink), - staging_key, - std::move(envelope_header), - hash_algo, - buf_size, - settings.use_adaptive_write_buffer, - settings.adaptive_write_buffer_initial_size, - [this, route = *r, hash_algo](const std::string & hash_hex, size_t size, const std::string & key) - { - const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; - stageBlobPartFile(route, ref, size, key, Cas::StagingBackend::S3); - }, - [pool, generation = incarnation.fence_generation] { pool->checkFenceOrThrow(generation); }); - } + /// Build the fixed-length CABL envelope header now (before + /// the payload is streamed) so the staging object holds `[header][payload]` and the promote + /// stays a verbatim server-side copy. The header carries a FRESH `incarnation_tag`; `build_id` + /// is left 0 (not known at stream time — diagnostic-only, not read by GC/read paths). The + /// buffer writes this header first, UNHASHED and excluded from the reported size, so the + /// content key stays the pool's hash of `payload` and `blob_size` stays the payload size. + std::string envelope_header = buildS3StagingBlobHeader(*r); + /// The staged upload becomes durable in `sink->finalize()`, outside this request contract by + /// design, so its admission is re-checked there through the callback below, against the + /// generation captured HERE. The epoch in the key and the generation the finalize rechecks are + /// one capture, so a remount between them cannot stage new-generation bytes under an old epoch. + const Cas::PoolPtr pool = metadata_storage.store(); + const Cas::MountIncarnation incarnation = pool->captureMountIncarnation(); + const auto leaf = getRandomASCIIString(32) + ".tmp"; + const auto pool_key = pool->layout().stagingKey(metadata_storage.serverRootId(), incarnation.writer_epoch, leaf); + const auto staging_key = metadata_storage.stagingKey(incarnation.writer_epoch, leaf); + const auto remote_storage = metadata_storage.objectStorage(); + auto object_sink = remote_storage->writeObject(StoredObject(staging_key), WriteMode::Rewrite); return std::make_unique( - metadata_storage.scratchPath(), + std::move(object_sink), + staging_key, + std::move(envelope_header), hash_algo, buf_size, settings.use_adaptive_write_buffer, settings.adaptive_write_buffer_initial_size, - [this, route = *r, hash_algo](const std::string & hash_hex, size_t size, const std::string & temp_path) + [this, route = *r, hash_algo, remote_storage, pool_key](const std::string & hash_hex, size_t size, const std::string & key) { const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; - stageBlobPartFile(route, ref, size, temp_path, Cas::StagingBackend::Local); - }); + stageBlobPartFile(route, ref, size, key, remote_storage, pool_key); + }, + [pool, generation = incarnation.fence_generation] { pool->checkFenceOrThrow(generation); }); } - /// Inline candidate (small eager metadata): buffer in memory, decide at finalize. <= INLINE_CAP - /// rides the single tree object as an Inline entry (one-GET part open); an oversized - /// candidate spills to a blob (the safety net). - return std::make_unique( - [this, route = *r](std::string bytes) - { - /// Mint via the one write hash function, `Cas::poolContentHash` (algorithm, payload) -> BlobRef - /// (`CasPartWriteTxn.h`) -- the SAME mint the streaming blob path's callers use, so an inline file - /// and a standalone blob of identical content get the same ref (same content hash identity) - /// under EVERY algo, including sha256. - const auto hash_algo = metadata_storage.store()->writeAlgo(); - const Cas::BlobRef ref = Cas::poolContentHash(hash_algo, bytes); - if (bytes.size() <= INLINE_CAP) - { - auto & st = stagingFor(route); - /// An inline (no-blob) entry still requires a PartWriteTxn. `publishStaging` stages the - /// manifest body, precommits, and promotes the ref even for a part with NO blob uploads; - /// it asserts `st.build != nullptr` whenever `st.entries` is non-empty. Without this, a - /// part whose files are ALL inline (a tiny/empty merge output, every file <= INLINE_CAP) - /// reaches `publishStaging` with entries but no PartWriteTxn -> LOGICAL_ERROR "staged entries - /// without a PartWriteTxn" -> a logical-error exception under abort_on_logical_error - /// since the inline-files feature). The blob path already establishes the PartWriteTxn via - /// `buildFor`; the inline path must do the same. - buildFor(route, st); - Cas::ManifestEntry entry; - entry.path = route.file; - entry.placement = Cas::EntryPlacement::Inline; - entry.ref = ref; /// content hash identity (same for inline and blob of same content) - /// `blob_size` stays 0 (its default) for an Inline entry — matching decode, which never - /// fills it for Inline. `entry.size()` is the logical size, derived from `inline_bytes`. - entry.inline_bytes = std::move(bytes); - putEntry(st, std::move(entry), nullptr); - } - else + /// Spill inline candidates locally on either backend, whether the per-file or transaction limit was reached. + auto create_local_blob_writer = [this, route = *r, hash_algo, buf_size, + adaptive = settings.use_adaptive_write_buffer, initial_size = settings.adaptive_write_buffer_initial_size] + { + return std::make_unique( + metadata_storage.scratchPath(), + hash_algo, + buf_size, + adaptive, + initial_size, + [this, route, hash_algo](const std::string & hash_hex, size_t size, const std::string & temp_path) { - /// Safety fallback: an unexpectedly large candidate spills to a blob (preserves the - /// invariant that big files are not held inline). Write the buffered bytes to a unique - /// local temp file (same scratchPath + random-name scheme as CaContentWriteBuffer), then - /// stage exactly like a streaming blob. - std::filesystem::create_directories(metadata_storage.scratchPath()); - const std::string temp_path = - metadata_storage.scratchPath() + "/inline_overflow_" + getRandomASCIIString(32) + ".tmp"; - { - WriteBufferFromFile tmp(temp_path); - tmp.write(bytes.data(), bytes.size()); - tmp.finalize(); - } - /// Until stageBlobPartFile takes ownership, WE own the temp file — mirror the blob path, - /// where CaContentWriteBuffer's dtor removes it unless the callback succeeded. If - /// stageBlobPartFile throws, drop the orphan instead of leaking it into scratch. This - /// fallback is always `Cas::StagingBackend::Local` — an oversized inline candidate is rare - /// enough (a safety net, not a hot path) that S3-staging mode does not cover it. - bool staged = false; - SCOPE_EXIT({ if (!staged) { std::error_code ec; std::filesystem::remove(temp_path, ec); } }); - stageBlobPartFile(route, ref, bytes.size(), temp_path, Cas::StagingBackend::Local); - staged = true; - } + const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; + stageBlobPartFile(route, ref, size, temp_path, nullptr, {}); + }); + }; + + if (must_stay_blob) + return create_local_blob_writer(); + + return std::make_unique( + path, buf_size, Cas::kMaxManifestInlineEntryBytes, inline_write_budget, std::move(create_local_blob_writer), + [this, route = std::move(*r), hash_algo](Cas::InlineCandidatePayloadPtr payload) + { + const auto bytes = payload->view(); + const auto ref = Cas::poolContentHash(hash_algo, bytes); + auto file = std::make_shared(); + file->memory = std::move(payload); + registerStagedFile(route, ref, bytes.size(), file); }); } @@ -1394,23 +1432,13 @@ void ContentAddressedTransaction::createHardLink(const std::string & path_from, if (it != src_st->entries.end()) { entry = *it; - /// A copy of an adopted entry confirms the committed part the entry came from. - std::shared_ptr source; - if (entry.placement == Cas::EntryPlacement::Blob) - { - /// Unified adopt dispatch. copy_pending=(&dst_st != src_st) so the pending - /// blob record is copied into dst_st only when the destination is a different part - /// (hardlink = copy semantics; same-part is a self-ref that shouldn't duplicate the record). - const auto * pb = findPendingBlob(*src_st, entry.ref); - if (!pb) - source = copySourceOf(*src_st, src->file); - adoptStagedBlob(pb, entry, dst_st, buildFor(*dst, dst_st), /*copy_pending=*/(&dst_st != src_st)); - } - else if (entry.placement != Cas::EntryPlacement::Inline) - throw Exception(ErrorCodes::LOGICAL_ERROR, - "ContentAddressed: staged hardlink of unsupported placement for {}", path_from); + auto file = stagedFileOf(*src_st, src->file); + auto source = copySourceOf(*src_st, src->file); + auto & build = buildFor(*dst, dst_st); + if (!file) + build.adoptEvidence(entry); entry.path = dst->file; - putEntry(dst_st, std::move(entry), std::move(source)); + putEntry(dst_st, std::move(entry), std::move(source), std::move(file)); return; } } @@ -1577,40 +1605,49 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c /// The committed manifest the source staging was based on (a rename of a committed part with /// staged edits, e.g. a rollback's `delete_tmp_`); the re-key below drops it from the overlay. std::optional staged_source_base; + bool replacing_source_segments = false; if (auto src_it = parts.find(src_key); src_it != parts.end()) { had_staged_source = true; PartStaging & dst_st = parts[dst_key]; PartStaging & src_st = src_it->second; staged_source_base = src_st.base_manifest_ref; + replacing_source_segments = src_st.has_finalized_file_write && hasTopLevelFile(src_st.entries); + /// A written file still has provisional Blob placement. A borrowed Inline can + /// represent the same bytes, so compare its payload to the staged file's full hash. + /// Check every collision before moving ownership out of the source. + for (const auto & entry : src_st.entries) + { + const auto existing = std::find_if(dst_st.entries.begin(), dst_st.entries.end(), + [&](const Cas::ManifestEntry & other) { return other.path == entry.path; }); + if (existing == dst_st.entries.end() || *existing == entry) + continue; + if (existing->placement != entry.placement && existing->size() == entry.size()) + { + const bool source_is_blob = entry.placement == Cas::EntryPlacement::Blob; + const auto & blob = source_is_blob ? entry : *existing; + const auto & inlined = source_is_blob ? *existing : entry; + const auto staged = stagedFileOf(source_is_blob ? src_st : dst_st, blob.path); + if (staged && staged->allow_inline_by_name && blob.blob_size <= Cas::kMaxManifestInlineEntryBytes + && Cas::poolContentHash(blob.ref.algo, inlined.inline_bytes) == blob.ref) + continue; + } + throw Exception(ErrorCodes::LOGICAL_ERROR, + "ContentAddressed: moveDirectory file collision on '{}' ({} -> {}): " + "source and destination staged different entries for the same file", + entry.path, src->ref, dst->ref); + } for (auto & entry : src_st.entries) { - /// A genuine collision (both src and dst independently - /// staged DIFFERING bytes for the SAME path) is a fail-loud LOGICAL_ERROR rather than a - /// silent lost-update — the same defensive rule this loop used to apply only to the - /// three legacy mutable names now applies uniformly to every entry (that scoping was - /// itself a leftover of the mutable-file/entry split; there is only one kind of staged - /// file left). Identical bytes are a benign idempotent re-key; distinct paths are the - /// ordinary source-wins merge (a genuine collision is not expected in normal operation - /// — only some future op-order re-keying the same file under both stagings). - if (const auto existing = std::find_if(dst_st.entries.begin(), dst_st.entries.end(), - [&](const Cas::ManifestEntry & e) { return e.path == entry.path; }); - existing != dst_st.entries.end() && !(*existing == entry)) - throw Exception(ErrorCodes::LOGICAL_ERROR, - "ContentAddressed: moveDirectory file collision on '{}' ({} -> {}): " - "source and destination staged different bytes for the same file", - entry.path, src->ref, dst->ref); auto source = copySourceOf(src_st, entry.path); - putEntry(dst_st, std::move(entry), std::move(source)); + auto file = stagedFileOf(src_st, entry.path); + putEntry(dst_st, std::move(entry), std::move(source), std::move(file)); } /// Carry any staged removal marks forward too — a re-key of the /// staging key must not silently drop them. for (const auto & file : src_st.content_removed) dst_st.content_removed.insert(file); - /// Move pending blobs from src to dst — they will be uploaded in dst's publishStaging. - for (auto & pb : src_st.pending_blobs) - dst_st.pending_blobs.push_back(std::move(pb)); - src_st.pending_blobs.clear(); + dst_st.has_finalized_file_write |= src_st.has_finalized_file_write; if (!dst_st.build) { dst_st.build = std::move(src_st.build); @@ -1622,18 +1659,14 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c /// time is unnecessary - entries staged via putBlob/adopt carry deps in the SOURCE /// build... merge conservatively by abandoning nothing and re-observing): for (const auto & entry : dst_st.entries) - if (entry.placement == Cas::EntryPlacement::Blob) - { - /// Unified adopt dispatch. Pending blob records were already moved - /// to dst_st.pending_blobs above (MOVE semantics), so copy_pending=false. - adoptStagedBlob(findPendingBlob(dst_st, entry.ref), entry, dst_st, *dst_st.build, /*copy_pending=*/false); - } + if (entry.placement == Cas::EntryPlacement::Blob && !stagedFileOf(dst_st, entry.path)) + dst_st.build->adoptEvidence(entry); src_st.build->abandon(); } parts.erase(src_it); /// A freshly-written part finalized tmp->final is re-keyed in the - /// overlay above (entries/marks/pending blobs/build moved src->dst). The durable publish + /// overlay above (entries, removal marks, staging sources and build moved src->dst). The durable publish /// happens only in this transaction's commit (the existing publishStaging loop), not in /// this method. `MergeTree` commits a part right after `finalize` and renames it afterwards, /// so this re-key serves a rename staged before any commit. No early-published ref to @@ -1657,7 +1690,7 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c const Cas::ManifestRef committed_ref = committed_at_src->manifestId().ref; const auto & base_entries = committed_at_src->manifest()->entries; const bool ours = staged_source_base && *staged_source_base == committed_ref; - if (!ours && !isNestedScratchManifest(base_entries)) + if (!ours && (!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 @@ -1665,7 +1698,7 @@ void ContentAddressedTransaction::moveDirectory(const std::string & path_from, c /// `publishStaging` merges the delta into it under the new name the way it does for an edit in /// place; files neither removed nor rewritten survive. The rename is conditional on the manifest /// the ownership check read. - if (ours && !isNestedScratchManifest(base_entries)) + if (ours && (!replacing_source_segments || hasTopLevelFile(base_entries))) { const auto renamed = metadata_storage.partAccess()->renameCommittedRef(src->refKey(), dst->refKey(), committed_ref); if (!renamed) @@ -1789,28 +1822,21 @@ void ContentAddressedTransaction::moveFile(const std::string & path_from, const [&](const Cas::ManifestEntry & e) { return e.path == src->file; }); if (it != src_st.entries.end()) { + if (&src_st == &dst_st && src->file == dst->file) + return; auto entry = *it; auto source = copySourceOf(src_st, src->file); - markVacatedInBase(*src, src_st, {src->file}); - eraseEntry(src_st, src->file); - entry.path = dst->file; - if (&src_st != &dst_st && entry.placement == Cas::EntryPlacement::Blob) + auto file = stagedFileOf(src_st, src->file); + if (&src_st != &dst_st) { - /// The record of a pending upload follows the entry. A hardlink left in the source still names the blob, - /// so the source keeps a copy: each part publishes every body it names, and may publish first. - auto pb_it = std::find_if(src_st.pending_blobs.begin(), src_st.pending_blobs.end(), - [&](const PartStaging::PendingBlob & pb) { return pb.ref == entry.ref; }); - if (pb_it != src_st.pending_blobs.end()) - { - const bool still_named_in_source = std::any_of(src_st.entries.begin(), src_st.entries.end(), - [&](const Cas::ManifestEntry & e) { return e.placement == Cas::EntryPlacement::Blob && e.ref == entry.ref; }); - dst_st.pending_blobs.push_back(*pb_it); - if (!still_named_in_source) - src_st.pending_blobs.erase(pb_it); - } - adoptStagedBlob(findPendingBlob(dst_st, entry.ref), entry, dst_st, buildFor(*dst, dst_st), /*copy_pending=*/false); + auto & build = buildFor(*dst, dst_st); + if (!file) + build.adoptEvidence(entry); } - putEntry(dst_st, std::move(entry), std::move(source)); + entry.path = dst->file; + markVacatedInBase(*src, src_st, {src->file}); + putEntry(dst_st, std::move(entry), std::move(source), std::move(file)); + eraseEntry(src_st, src->file); return; } /// Source not staged in this transaction: this would cover a standalone one-shot rename of a @@ -1825,17 +1851,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); } @@ -1872,10 +1887,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 84f544b4abd95..f2adfa2ddf2be 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -24,6 +25,12 @@ #include #include +namespace DB::Cas +{ +class InlineCandidatePayload; +class InlineWriteMemoryBudget; +} + namespace DB { @@ -33,10 +40,9 @@ namespace DB /// `Cas::PartWriteTxn`, created lazily before the first staged dependency, so the durable manifest /// edge is established before the pool observes or uploads a new blob. /// -/// Content blobs are first represented by local or S3 staging objects and are uploaded only during -/// publication. Inline entries remain in the manifest tree when they fit `INLINE_CAP`. The -/// destructor removes the transaction's local and S3 staging and abandons any open part builds; -/// it never publishes an uncommitted ref. +/// Inline-eligible files share a transaction-wide memory budget and spill to local staging +/// when a write exceeds either memory limit. Commit chooses placement per manifest from the +/// final paths and sizes. Readers and uploads can retain the source after publication. class ContentAddressedTransaction : public IMetadataTransaction { public: @@ -86,9 +92,8 @@ class ContentAddressedTransaction : public IMetadataTransaction const std::string & path, size_t buf_size, WriteMode mode, const WriteSettings & settings, bool autocommit) override; - /// Creates the inner buffer for a content-addressed path. Part blobs are hashed while being - /// staged, small metadata files are accumulated in memory and classified at finalize, and - /// verbatim namespace or mountpoint files are read-modify-written when append is requested. + /// Opens a part-file writer or a verbatim namespace or mountpoint writer. Only verbatim files + /// support append, by reading and rewriting the existing contents. std::unique_ptr writeFile( const std::string & path, size_t buf_size, @@ -127,6 +132,8 @@ class ContentAddressedTransaction : public IMetadataTransaction /// Test-only: stages the part file `path` as a blob entry naming `ref` with no pending upload and no copy /// source, a shape no operation produces. void stageUnprovenBlobEntryForTest(const std::string & path, const Cas::BlobRef & ref, uint64_t size); + size_t inlineCandidateReservedBytesForTest() const noexcept; + void failNextFileRegistrationForTest() { fail_next_file_registration = true; } /// Test-only: the copy source shared by this transaction's borrows from the committed part `part_path`, or null. std::shared_ptr borrowedSourceForTest(const std::string & part_path) const; @@ -137,9 +144,23 @@ class ContentAddressedTransaction : public IMetadataTransaction ContentAddressedMetadataStorage & metadata_storage; private: - /// State for one routed part. The build is opened lazily at the first staged write so every - /// manifest dependency is recorded by the same `Cas::PartWriteTxn`; pending blobs remain in - /// staging until publication. + /// One finalized source shared across paths, readers and uploads. The memory payload + /// owns its reservation until the last holder releases its bytes. + struct StagedPartFile + { + std::shared_ptr memory; + String staging_path; /// Local filesystem path or the S3 key used by IObjectStorage. + ObjectStoragePtr remote_storage; + String pool_staging_key; /// Pool-relative address for reads through the request engine. + bool allow_inline_by_name = false; /// Set from the original write path, before any hardlink or rename. + bool registered = false; /// The local writer owns its scratch path until registration succeeds. + mutable std::atomic publication_attempted{false}; + + ~StagedPartFile(); + }; + using StagedPartFilePtr = std::shared_ptr; + + /// State for one routed part. The build records its manifest dependencies at publication. struct PartStaging { /// Created lazily when a staged blob, inline entry, or adopted entry first needs publication. @@ -163,23 +184,15 @@ class ContentAddressedTransaction : public IMetadataTransaction bool published = false; /// set by publishStaging during commit(); the commit /// loop is idempotent (never re-publishes a staging). - /// `staging_key` is either a private local temp path or an S3 staging object key returned by - /// `CaContentWriteBuffer` at finalize. The backend selects the read-your-writes source; both - /// kinds are removed by this transaction on commit and on abort. - struct PendingBlob - { - Cas::BlobRef ref; - std::string staging_key; - uint64_t size = 0; - Cas::StagingBackend backend = Cas::StagingBackend::Local; - /// The once-only verbatim-copy privilege of the staging object. A hardlink copies this - /// record into another part, and the copy shares the flag, so the parts together copy - /// the staged envelope at most once. - std::shared_ptr> publication_attempted = std::make_shared>(false); - }; - std::vector pending_blobs; /// Staged blobs uploaded after the manifest edge is precommitted. + /// Each newly written path and its hardlinks retain the original staging source. + std::map staged_part_files; + bool has_finalized_file_write = false; /// A build opened only for a transfer cannot replace the temporary segment ref. }; + std::shared_ptr inline_write_budget; + /// Separate writers may finalize concurrently. Commit and other overlay operations follow writer finalization. + std::mutex file_registration_mutex; + /// Keyed by (namespace string, ref name) — the routed identity, so live/detached/shadow /// stagings never collide. std::map, PartStaging> parts; @@ -188,6 +201,7 @@ class ContentAddressedTransaction : public IMetadataTransaction std::unordered_map> copy_sources_by_part; bool committed = false; bool failed = false; + bool fail_next_file_registration = false; /// Memoizes, per (this transaction, ref), whether `unlinkFile` has already resolved a committed /// ref `ForceFresh`. The MergeTree fast-removal path unlinks every file of a part through ONE @@ -196,13 +210,12 @@ class ContentAddressedTransaction : public IMetadataTransaction /// Cleared in `commit()`'s epilogue. std::unordered_set force_fresh_validated_refs; - /// Stage a content part file as a blob without recording a dependency proof, and add/replace its - /// manifest entry. Successful post-precommit publication later records `Materialized`. Shared by - /// the streaming-blob path - /// (Local or S3-staging, `backend` says which) and the always-Local inline-cap fallback. + void registerStagedFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, + const std::shared_ptr & file); + /// Transfer the writer's private file or S3 object only on successful registration. void stageBlobPartFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::string & staging_key, - Cas::StagingBackend backend); + ObjectStoragePtr remote_storage, const String & pool_key); /// Builds the fixed-length CABL envelope header for a staging blob, with a fresh `incarnation_tag`, /// so the S3 staging object holds `[header][payload]` and the promote @@ -210,8 +223,8 @@ class ContentAddressedTransaction : public IMetadataTransaction std::string buildS3StagingBlobHeader(const ContentAddressedMetadataStorage::Route & route) const; /// Replaces the staged entry at `entry.path`; `source` is its committed source when it was adopted from - /// another part without its bytes, and nullopt when this transaction uploads or inlines the bytes. - static void putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source); + /// another part without its bytes, and null when this transaction owns the bytes. + static void putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr source, StagedPartFilePtr file = {}); static void eraseEntry(PartStaging & st, const std::string & path); /// Renames `entry`, an element of `st.entries`, in place; `new_path` must not be staged. static void rekeyEntry(PartStaging & st, Cas::ManifestEntry & entry, std::string new_path); @@ -223,9 +236,9 @@ class ContentAddressedTransaction : public IMetadataTransaction /// The refs of `st`'s pending uploads, collected once per publication. using PendingRefs = std::unordered_set; /// Confirms each distinct committed source of `st`'s adopted entries, skipping entries whose ref is in - /// `pending_refs`. Runs after the precommit of `st.build` is durable and before its promote; on a refusal it + /// `blob_refs_with_upload_requests`. Runs after the precommit of `st.build` is durable and before its promote; on a refusal it /// abandons the build and throws `NO_REPLICA_HAS_PART`, and on a failed read it abandons the build and rethrows. - void confirmCopySources(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, const PendingRefs & pending_refs); + void confirmCopySources(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, const PendingRefs & blob_refs_with_upload_requests); /// After this transaction renamed `from` to `to`, points the borrow of `from` at `to`, when the rename moved the /// manifest the borrow read and `to` still commits the manifest the rename produced. Any other borrow keeps its /// source, and its confirmation refuses it. @@ -237,42 +250,28 @@ class ContentAddressedTransaction : public IMetadataTransaction PartStaging * findStaging(const ContentAddressedMetadataStorage::Route & r); /// Finds the staged manifest entry for a routed file without consulting committed storage. const Cas::ManifestEntry * findStagedEntry(const ContentAddressedMetadataStorage::Route & r) const; - /// Returns the pending (staged but not yet uploaded) blob for `ref`, or nullptr when it has - /// already been uploaded or was never staged. - const PartStaging::PendingBlob * findPendingBlob(const PartStaging & st, const Cas::BlobRef & ref) const; + + static StagedPartFilePtr stagedFileOf(const PartStaging & st, const String & path); + + static std::unique_ptr openStagedPayload(const StagedPartFilePtr & file, uint64_t size, const Cas::PoolPtr & pool); + + Cas::BlobSource stagedUploadSource(const StagedPartFilePtr & file, uint64_t size) const; + + std::vector applyManifestInlineBudget(PartStaging & st, uint64_t inline_bytes_from_unchanged_base_entries) const; /// Returns the part build, creating it lazily with the routed ref as its intended destination. Cas::PartWriteTxn & buildFor(const ContentAddressedMetadataStorage::Route & r, PartStaging & st); /// Parses a disk path and maps a part-file path to its namespace/ref/file route. std::optional routeOf(const std::string & path) const; - /// Removes the transaction's staging after commit or abort: local files and S3 staging objects - /// alike. S3 deletes are best-effort; a lost delete leaves debris for the mount-start sweep. - void cleanupPendingTempFiles() noexcept; + /// Release this transaction's ownership. Readers and pending uploads retain their own handles. + void releaseStagedFiles() noexcept; - /// Uploads through `st.build` only the pending blobs still referenced by `st.entries`. An entry - /// removed by `unlinkFile` or `replaceFile` is skipped, but its staging resource is still cleaned - /// by `cleanupPendingTempFiles`. Used for both new refs and committed-ref repoints. - void uploadPendingBlobs(PartStaging & st); + /// Append sources from local or S3 staging only for blob refs still named by the staged entries. + void appendStagedBlobUploads(const PartStaging & st, std::vector & blob_upload_requests) const; - /// Stages `st.entries` as a manifest of `st.build`, precommits it at `ref`, confirms the copy sources and uploads - /// the pending blobs, in that order. Returns the staged manifest's id. + /// Stage the manifest and precommit its blob refs before confirming copied files and uploading payloads. Cas::ManifestId precommitAndUpload(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st, - const PendingRefs & pending_refs); - - /// 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); + const PendingRefs & blob_refs_with_upload_requests, const std::vector & blob_upload_requests); /// 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 @@ -297,7 +296,7 @@ namespace DB::Cas /// Part files that must NOT be inlined into the tree: per-column data (`.bin`) and marks (`.mrk*`/ /// `.cmrk*`) — inlining them would force a full-part fetch and destroy column-read selectivity — plus /// `primary.idx`, which can be large (a size-threshold inlining of small primary.idx is a follow-up). -/// Everything else (the small eager metadata files) is an inline candidate, subject to INLINE_CAP. +/// Other files are inline candidates, subject to the per-entry and total manifest byte limits. bool partFileMustStayBlob(std::string_view file_name); /// Opens a locally staged blob payload of `payload_size` bytes for upload, with a read buffer no larger @@ -305,7 +304,7 @@ bool partFileMustStayBlob(std::string_view file_name); std::unique_ptr openLocalStagedBlobPayload(const std::string & path, uint64_t payload_size); /// Test-only fault-injection seams for the intra-part blob-upload fan-out. Inert in production -/// (`ContentAddressedTransaction::uploadPendingBlobs` passes `nullptr`). +/// (`ContentAddressedTransaction::precommitAndUpload` passes `nullptr`). struct BlobUploadFanoutHooksForTest { /// Invoked ONCE per DISPATCHED task, on the calling (dispatch) thread, immediately before the task @@ -453,10 +452,7 @@ class CaContentWriteBuffer : public WriteBufferFromFileBase std::function check_fence_before_finalize; }; -/// Write buffer for bytes that live INSIDE pool metadata (a small inline part file staged into the -/// manifest tree, or a verbatim namespace file PUT on finalize). Accumulates in memory (the bytes are -/// tiny) and hands them to the callback at finalize; the callback decides where they go and whether -/// they are durable immediately (verbatim) or at commit (staged into the part's manifest entries). +/// Accumulates a verbatim namespace or mountpoint file for the write performed at finalize. class CaInlineWriteBuffer : public WriteBufferFromFileBase { public: @@ -471,8 +467,7 @@ class CaInlineWriteBuffer : public WriteBufferFromFileBase private: /// Appends bytes to the in-memory payload under the base write-buffer contract. void nextImpl() override; - /// Hands the complete inline payload to the callback; the callback decides whether it is staged - /// in a manifest or written immediately as a verbatim file. + /// Passes the complete verbatim payload to the callback. void finalizeImpl() override; OnInlined on_inlined; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index ecc586c4454e8..9d5bf1bcdf55e 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -56,8 +56,6 @@ namespace /// Backpressure caps, enforced fail-closed in stageManifest before the body write returns. constexpr uint64_t kMaxManifestEntries = 1048576; -constexpr uint64_t kMaxManifestInlineBytesTotal = 16ULL << 20; /// 16 MiB -constexpr uint64_t kMaxLargestInlineEntryBytes = 1ULL << 20; /// 1 MiB /// Two thread_local_rng draws composed into a UInt128. Used both to mint build ids and to mint, on /// every upload/re-upload, a FRESH incarnation_tag (W-FRESH-TAG). @@ -169,11 +167,23 @@ BlobSource BlobSource::fromString(String bytes) { BlobSource source; source.size = bytes.size(); - /// Owning reader: `ReadBufferFromString` only borrows, and this factory outlives no single call - /// -- an owning copy per attempt removes the question entirely for a source that is small by - /// construction (this helper exists for tests and inline payloads). - source.open = [b = std::move(bytes)]() -> std::unique_ptr - { return std::make_unique(b); }; + /// Requests copied into the upload queue and readers opened on retry share the payload. + /// Each reader owns a reference independently of the lifetime of the request. + class Reader final : public ReadBufferFromString + { + public: + explicit Reader(std::shared_ptr bytes_) + : ReadBufferFromString(*bytes_), payload_owner(std::move(bytes_)) + { + } + + private: + std::shared_ptr payload_owner; + }; + source.open = [owner = std::make_shared(std::move(bytes))] + { + return std::make_unique(owner); + }; return source; } @@ -627,10 +637,10 @@ ManifestId PartWriteTxn::stageManifest(std::vector entries) { if (e.placement == EntryPlacement::Inline) { - if (e.inline_bytes.size() > kMaxLargestInlineEntryBytes) + if (e.inline_bytes.size() > kMaxManifestInlineEntryBytes) throw Exception(ErrorCodes::LIMIT_EXCEEDED, "stageManifest: inline entry '{}' of {} bytes exceeds cap {}", - e.path, e.inline_bytes.size(), kMaxLargestInlineEntryBytes); + e.path, e.inline_bytes.size(), kMaxManifestInlineEntryBytes); inline_total += e.inline_bytes.size(); } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h index c6b0aeb75609d..6ffe5920a3ea7 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h @@ -15,6 +15,9 @@ namespace DB { class WriteBuffer; } namespace DB::Cas { +inline constexpr uint64_t kMaxManifestInlineEntryBytes = 1ULL << 20; /// 1 MiB +inline constexpr uint64_t kMaxManifestInlineBytesTotal = 16ULL << 20; /// 16 MiB + /// Re-readable source for one content-addressed blob upload. /// /// `open` returns a fresh reader over exactly `size` logical bytes and may be called more than once. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp new file mode 100644 index 0000000000000..747b58bb36592 --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.cpp @@ -0,0 +1,159 @@ +#include + +#include + +#include +#include + +namespace ProfileEvents +{ + extern const Event CASInlineWriteMemoryBudgetSpills; +} + +namespace DB::Cas +{ + +bool InlineWriteMemoryBudget::tryReserve(size_t size) noexcept +{ + size_t current = reservedBytes(); + for (;;) + { + chassert(current <= limit); + if (size > limit - current) + return false; + if (reserved.compare_exchange_weak(current, current + size, std::memory_order_relaxed)) + return true; + } +} + +InlineCandidatePayload::~InlineCandidatePayload() +{ + buffer.reset(); + budget->release(capacity); +} + +bool InlineCandidatePayload::trySetCapacity(size_t new_capacity) +{ + if (new_capacity == capacity) + return true; + if (!budget->tryReserve(new_capacity)) + return false; + + std::unique_ptr replacement; + try + { + replacement = std::make_unique_for_overwrite(new_capacity); + } + catch (...) + { + budget->release(new_capacity); + throw; + } + if (length) + std::memcpy(replacement.get(), buffer.get(), length); + buffer = std::move(replacement); + budget->release(capacity); + capacity = new_capacity; + return true; +} + +InlineCandidateWriteBuffer::InlineCandidateWriteBuffer( + String path_, size_t buf_size, size_t max_inline_bytes_, std::shared_ptr budget, + CreateLocalWriter create_local_writer_, OnInline on_inline_) + : WriteBufferFromFileBase(0, nullptr, 0) + , path(std::move(path_)) + , transfer_size(std::clamp(buf_size, 1, 65536)) + , max_inline_bytes(max_inline_bytes_) + , create_local_writer(std::move(create_local_writer_)) + , on_inline(std::move(on_inline_)) + , payload(std::make_shared(std::move(budget))) +{ + /// The caller can write directly into a payload array, so there is no separate uncharged inline I/O buffer. + padded = false; + set(&overflow_byte, 1); +} + +InlineCandidateWriteBuffer::~InlineCandidateWriteBuffer() +{ + cancel(); +} + +void InlineCandidateWriteBuffer::nextImpl() +{ + if (local) + { + local->write(working_buffer.begin(), offset()); + return; + } + + if (working_buffer.begin() == &overflow_byte) + { + const size_t needed = payload->length + 1; + const size_t target = finishing ? needed + : std::min(max_inline_bytes, payload->capacity ? 2 * payload->capacity : std::min(transfer_size, 4096)); + if (needed > max_inline_bytes || !payload->trySetCapacity(std::max(needed, target))) + { + local = create_local_writer(); + const auto prefix = payload->view(); + if (!prefix.empty()) + local->write(prefix.data(), prefix.size()); + local->write(overflow_byte); + payload.reset(); + resize(transfer_size); + if (needed <= max_inline_bytes) + ProfileEvents::increment(ProfileEvents::CASInlineWriteMemoryBudgetSpills); + return; + } + payload->buffer[payload->length++] = overflow_byte; + } + else + { + payload->length += offset(); + } + + if (payload->length == payload->capacity) + set(&overflow_byte, 1); + else + set(payload->buffer.get() + payload->length, payload->capacity - payload->length); +} + +void InlineCandidateWriteBuffer::preFinalize() +{ + finishing = true; + next(); + if (local) + local->preFinalize(); +} + +void InlineCandidateWriteBuffer::finalizeImpl() +{ + finishing = true; + next(); + if (local) + { + local->finalize(); + return; + } + + set(&overflow_byte, 1); + /// Keep the current allocation if the budget cannot also accommodate a compact copy. + payload->trySetCapacity(payload->length); + on_inline(std::move(payload)); +} + +void InlineCandidateWriteBuffer::cancelImpl() noexcept +{ + set(&overflow_byte, 1); + payload.reset(); + if (local) + local->cancel(); +} + +void InlineCandidateWriteBuffer::sync() +{ + next(); + if (local) + local->sync(); +} + +} diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h new file mode 100644 index 0000000000000..ab2e4f1053198 --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h @@ -0,0 +1,85 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace DB::Cas +{ + +/// Shared by the inline-candidate writers of one disk transaction and by their finalized payloads. +/// Charges the requested capacity of payload arrays, including both arrays during a reallocation. +class InlineWriteMemoryBudget +{ +public: + explicit InlineWriteMemoryBudget(size_t limit_) : limit(limit_) {} + size_t reservedBytes() const noexcept { return reserved.load(std::memory_order_relaxed); } + +private: + friend class InlineCandidatePayload; + + bool tryReserve(size_t size) noexcept; + void release(size_t size) noexcept { reserved.fetch_sub(size, std::memory_order_relaxed); } + + const size_t limit; + std::atomic reserved{0}; +}; + +/// After finalize, hardlinks and in-flight readers share the same allocation and reservation. +class InlineCandidatePayload +{ +public: + explicit InlineCandidatePayload(std::shared_ptr budget_) : budget(std::move(budget_)) {} + ~InlineCandidatePayload(); + + std::string_view view() const noexcept { return length ? std::string_view(buffer.get(), length) : std::string_view{""}; } + +private: + friend class InlineCandidateWriteBuffer; + + bool trySetCapacity(size_t new_capacity); + + const std::shared_ptr budget; + std::unique_ptr buffer; + size_t length = 0; + size_t capacity = 0; +}; + +using InlineCandidatePayloadPtr = std::shared_ptr; + +class InlineCandidateWriteBuffer final : public WriteBufferFromFileBase +{ +public: + using CreateLocalWriter = std::function()>; + using OnInline = std::function; + + InlineCandidateWriteBuffer( + String path_, size_t buf_size, size_t max_inline_bytes_, std::shared_ptr budget, + CreateLocalWriter create_local_writer_, OnInline on_inline_); + ~InlineCandidateWriteBuffer() override; + + String getFileName() const override { return path; } + void preFinalize() override; + void sync() override; + +private: + void nextImpl() override; + void finalizeImpl() override; + void cancelImpl() noexcept override; + + String path; + size_t transfer_size; + size_t max_inline_bytes; + CreateLocalWriter create_local_writer; + OnInline on_inline; + std::shared_ptr payload; + std::unique_ptr local; + /// Detect the first byte beyond the current allocation. In particular, exactly 1 MiB can still be inline. + char overflow_byte = 0; + bool finishing = false; +}; + +} diff --git a/src/Disks/IO/WriteBufferInlineOrBlob.cpp b/src/Disks/IO/WriteBufferInlineOrBlob.cpp index 66a078cad7d61..b47fd6e997f26 100644 --- a/src/Disks/IO/WriteBufferInlineOrBlob.cpp +++ b/src/Disks/IO/WriteBufferInlineOrBlob.cpp @@ -34,7 +34,8 @@ void WriteBufferInlineOrBlob::spill() underlying = create_underlying(); if (!accumulated.empty()) underlying->write(accumulated.data(), accumulated.size()); - accumulated.clear(); + + String{}.swap(accumulated); } void WriteBufferInlineOrBlob::nextImpl() diff --git a/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp new file mode 100644 index 0000000000000..b3485050800d8 --- /dev/null +++ b/src/Disks/tests/gtest_cas_inline_cap_gaps.cpp @@ -0,0 +1,1061 @@ +#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 INCORRECT_DATA; +} + +/// A part or a nested scratch storage whose small files sum past the manifest's inline budget must +/// still commit: the budget bounds what rides inside the manifest, not what a part may contain. + +namespace +{ + +constexpr size_t kib = 1024; +constexpr size_t mib = 1024 * kib; +constexpr size_t inline_file_threshold = mib; +constexpr size_t inline_total_budget = 16 * mib; + +std::shared_ptr openStorage( + DB::ObjectStoragePtr objects = DB::Cas::tests::makeLocalObjectStorageForTest()) +{ + auto settings = DB::Cas::tests::makeSettingsForTest( + "test", std::filesystem::path(objects->getCommonKeyPrefix()) / "scratch"); + auto storage = std::make_shared( + objects, "pool", "srv1", "", nullptr, settings); + storage->startup(); + return storage; +} + +/// Incompressible and different for every `seed`, so no two files share a content hash. +std::string payload(size_t size, uint64_t seed) +{ + std::string bytes(size, '\0'); + uint64_t state = seed * 0x9E3779B97F4A7C15ULL + 0xD1B54A32D192ED03ULL; + for (size_t i = 0; i < size; ++i) + { + state = state * 6364136223846793005ULL + 1442695040888963407ULL; + bytes[i] = static_cast(state >> 56); + } + return bytes; +} + +void writeFileTx(DB::IMetadataTransaction & tx, const std::string & path, const std::string & bytes) +{ + auto & ca_tx = dynamic_cast(tx); + auto buf = ca_tx.writeFile(path, 65536, DB::WriteMode::Rewrite, {}); + buf->write(bytes.data(), bytes.size()); + buf->finalize(); +} + +/// Reads a committed part file the way a reader does: from the manifest when inline, else from its blob. +std::string readPartFile(const DB::ContentAddressedMetadataStorage & storage, const std::string & path) +{ + if (auto in_manifest = storage.tryGetInManifestBytes(path)) + return *in_manifest; + const auto objects = storage.getStorageObjects(path); + if (objects.size() != 1) + throw std::runtime_error("expected one object for " + path); + const DB::Cas::BlobLocation location{ + .key = objects[0].remote_path, + .offset = storage.store()->poolMeta().blob_header_len, + .length = objects[0].bytes_size}; + auto buf = storage.readBlobPayload(location, path, DB::ReadSettings{}); + std::string got; + DB::readStringUntilEOF(got, *buf); + return got; +} + +void expectReadsBack( + const DB::ContentAddressedMetadataStorage & storage, const std::string & part_dir, + const std::map & files) +{ + for (const auto & [name, bytes] : files) + { + const std::string got = readPartFile(storage, part_dir + "/" + name); + EXPECT_EQ(got.size(), bytes.size()) << name; + EXPECT_TRUE(got == bytes) << name << " does not read back byte-identical"; + } +} + +std::string commitErrorOf(DB::IMetadataTransaction & tx) +{ + try + { + tx.commit(DB::NoCommitOptions{}); + } + catch (const DB::Exception & e) + { + return std::to_string(e.code()) + ": " + e.message(); + } + return {}; +} + +DB::Cas::PartManifest manifestOf( + DB::ContentAddressedMetadataStorage & storage, const std::string & table_uuid, const std::string & ref) +{ + const auto resolved = storage.store()->resolveRef(storage.liveNamespace(table_uuid), ref); + if (!resolved) + throw std::runtime_error("ref " + ref + " does not resolve"); + return storage.store()->readManifest(resolved->manifest_id); +} + +uint64_t inlineTotal(const DB::Cas::PartManifest & manifest) +{ + uint64_t total = 0; + for (const auto & e : manifest.entries) + if (e.placement == DB::Cas::EntryPlacement::Inline) + total += e.inline_bytes.size(); + return total; +} + +/// The files one text-index segment leaves in `text_index_tmp/`, named as `BuildTextIndexTransform` names them. +std::string segmentFile(size_t segment, const std::string & index, const std::string & substream) +{ + return "text_index_tmp/tmp_all_1_2_1_" + std::to_string(segment) + "_skp_idx_" + index + substream + ".idx"; +} + +} + +/// A merge that rebuilds text indexes commits `/text_index_tmp/` as its own manifest, before the +/// part's own files exist. Its segment files are each under the per-file threshold and are many. +TEST(CASInlineCapGaps, TextIndexScratchOverTheInlineBudgetCommits) +{ + auto storage = openStorage(); + const std::string part_dir = "e01/e01e01e0-0101-4101-8101-010101010101/tmp_merge_all_1_2_1"; + + std::map files; + for (size_t segment = 0; segment < 20; ++segment) + files[segmentFile(segment, "idx_s", ".dct")] = payload(900 * kib, segment); + + auto tx = storage->createTransaction(); + for (const auto & [name, bytes] : files) + writeFileTx(*tx, part_dir + "/" + name, bytes); + + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "20 files of 900 KiB did not commit: " << error; + expectReadsBack(*storage, part_dir, files); + EXPECT_LE(inlineTotal(manifestOf(*storage, "e01e01e0-0101-4101-8101-010101010101", "tmp_merge_all_1_2_1")), + inline_total_budget); +} + +/// The same with every stream of a segment: a small sparse index, a dictionary and postings per segment, +/// for two indexes. No single file is large; the sum is. +TEST(CASInlineCapGaps, TextIndexScratchWithAllSubstreamsCommits) +{ + auto storage = openStorage(); + const std::string part_dir = "e02/e02e02e0-0202-4202-8202-020202020202/tmp_merge_all_1_2_1"; + + std::map files; + uint64_t seed = 1000; + for (const char * index : {"idx_body", "idx_attrs"}) + { + for (size_t segment = 0; segment < 40; ++segment) + { + files[segmentFile(segment, index, "")] = payload(4 * kib, ++seed); + files[segmentFile(segment, index, ".dct")] = payload(200 * kib, ++seed); + files[segmentFile(segment, index, ".pst")] = payload(60 * kib, ++seed); + } + } + + auto tx = storage->createTransaction(); + for (const auto & [name, bytes] : files) + writeFileTx(*tx, part_dir + "/" + name, bytes); + + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "240 segment files summing to about 20 MiB did not commit: " << error; + expectReadsBack(*storage, part_dir, files); +} + +/// An ordinary part: index files are written first and the files a part load reads are written last, so a +/// rule that fills the budget in write order would push exactly the load-time files out of the manifest. +TEST(CASInlineCapGaps, PartOverTheInlineBudgetCommitsAndKeepsLoadTimeFilesInline) +{ + auto storage = openStorage(); + const std::string table = "e03/e03e03e0-0303-4303-8303-030303030303/"; + const std::string tmp_part = table + "tmp_insert_all_1_1_0"; + const std::string final_part = table + "all_1_1_0"; + + std::vector> in_write_order; + in_write_order.emplace_back("data.bin", payload(64 * kib, 1)); + for (size_t index = 0; index < 20; ++index) + in_write_order.emplace_back("skp_idx_t" + std::to_string(index) + ".dct.idx", payload(900 * kib, 100 + index)); + const std::vector load_time_files{"count.txt", "columns.txt", "serialization.json", "checksums.txt"}; + in_write_order.emplace_back("count.txt", "1000"); + in_write_order.emplace_back("columns.txt", payload(34 * kib, 2)); + in_write_order.emplace_back("serialization.json", payload(222 * kib, 3)); + in_write_order.emplace_back("checksums.txt", payload(150 * kib, 4)); + + auto tx = storage->createTransaction(); + for (const auto & [name, bytes] : in_write_order) + writeFileTx(*tx, tmp_part + "/" + name, bytes); + tx->moveDirectory(tmp_part, final_part); + + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "a part with 18 MiB of small index files did not commit: " << error; + + expectReadsBack(*storage, final_part, {in_write_order.begin(), in_write_order.end()}); + const auto manifest = manifestOf(*storage, "e03e03e0-0303-4303-8303-030303030303", "all_1_1_0"); + for (const auto & name : load_time_files) + { + const auto * entry = DB::Cas::findEntry(manifest.entries, name); + ASSERT_TRUE(entry) << name; + EXPECT_EQ(entry->placement, DB::Cas::EntryPlacement::Inline) << name << " must stay in the manifest"; + } + EXPECT_LE(inlineTotal(manifest), inline_total_budget); +} + +/// Rewriting an existing path and adding an empty file consume no additional inline bytes. +TEST(CASInlineCapGaps, InlineTotalExactlyAtTheBudgetCommits) +{ + auto storage = openStorage(); + const std::string part_dir = "e04/e04e04e0-0404-4404-8404-040404040404/tmp_merge_all_1_2_1"; + + std::map files; + for (size_t segment = 0; segment < 16; ++segment) + files[segmentFile(segment, "idx_s", ".dct")] = payload(inline_file_threshold, segment); + + auto tx = storage->createTransaction(); + for (const auto & [name, bytes] : files) + writeFileTx(*tx, part_dir + "/" + name, bytes); + + writeFileTx(*tx, part_dir + "/" + files.begin()->first, files.begin()->second); + files["text_index_tmp/empty.idx"] = ""; + writeFileTx(*tx, part_dir + "/text_index_tmp/empty.idx", ""); + + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "16 files of 1 MiB did not commit: " << error; + const auto manifest = manifestOf(*storage, "e04e04e0-0404-4404-8404-040404040404", "tmp_merge_all_1_2_1"); + ASSERT_EQ(manifest.entries.size(), files.size()); + EXPECT_EQ(inlineTotal(manifest), inline_total_budget); + for (const auto & entry : manifest.entries) + EXPECT_EQ(entry.placement, DB::Cas::EntryPlacement::Inline) << entry.path; + expectReadsBack(*storage, part_dir, files); +} + +/// One byte more than the budget must not turn a committable write into a permanent failure. +TEST(CASInlineCapGaps, InlineTotalOneByteOverTheBudgetCommits) +{ + auto storage = openStorage(); + + std::map files; + for (size_t segment = 0; segment < 16; ++segment) + files[segmentFile(segment, "idx_s", ".dct")] = payload(inline_file_threshold, segment); + files[segmentFile(16, "idx_s", "")] = "x"; + + const std::string table_uuid = "e05e05e0-0505-4505-8505-050505050505"; + for (const bool reverse : {false, true}) + { + const std::string ref = reverse ? "tmp_merge_all_3_4_1" : "tmp_merge_all_1_2_1"; + const std::string directory = "e05/" + table_uuid + "/" + ref; + auto tx = storage->createTransaction(); + if (reverse) + { + for (auto it = files.rbegin(); it != files.rend(); ++it) + writeFileTx(*tx, directory + "/" + it->first, it->second); + } + else + { + for (const auto & [name, bytes] : files) + writeFileTx(*tx, directory + "/" + name, bytes); + } + ASSERT_NO_THROW(tx->commit(DB::NoCommitOptions{})); + const auto manifest = manifestOf(*storage, table_uuid, ref); + EXPECT_EQ(inlineTotal(manifest), 15 * mib + 1); + for (const auto & entry : manifest.entries) + { + const auto placement = entry.path == files.begin()->first ? DB::Cas::EntryPlacement::Blob : DB::Cas::EntryPlacement::Inline; + EXPECT_EQ(entry.placement, placement) << entry.path; + } + expectReadsBack(*storage, directory, files); + } +} + +/// A standalone rewrite of one small file of a committed part republishes the whole manifest, so the +/// files the part already holds inline count against the budget again. +TEST(CASInlineCapGaps, StandaloneWriteOntoPartAtTheBudgetCommits) +{ + auto storage = openStorage(); + const std::string table = "e06/e06e06e0-0606-4606-8606-060606060606/"; + const std::string tmp_part = table + "tmp_insert_all_1_1_0"; + const std::string final_part = table + "all_1_1_0"; + + std::map files; + files["data.bin"] = payload(64 * kib, 1); + for (size_t index = 0; index < 16; ++index) + files["skp_idx_t" + std::to_string(index) + ".dct.idx"] = payload(inline_file_threshold, 100 + index); + { + auto tx = storage->createTransaction(); + for (const auto & [name, bytes] : files) + writeFileTx(*tx, tmp_part + "/" + name, bytes); + tx->moveDirectory(tmp_part, final_part); + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "the part at exactly the budget did not commit: " << error; + } + + files["metadata_version.txt"] = "7"; + auto tx = storage->createTransaction(); + writeFileTx(*tx, final_part + "/metadata_version.txt", files["metadata_version.txt"]); + const std::string error = commitErrorOf(*tx); + ASSERT_TRUE(error.empty()) << "a 1-byte file could not be added to a committed part: " << error; + expectReadsBack(*storage, final_part, files); +} + +namespace +{ + +const std::string uuid = "e07e07e0-0707-4707-8707-070707070707"; +const std::string table_dir = "e07/" + uuid + "/"; + +void writeFullBudget(DB::IMetadataTransaction & tx, const std::string & directory, const std::string & prefix = {}) +{ + for (size_t i = 0; i < 16; ++i) + writeFileTx(tx, directory + "/" + prefix + std::to_string(i) + ".idx", payload(mib, i)); +} + +void expectBlob(DB::ContentAddressedMetadataStorage & storage, const std::string & ref, const std::string & path, const std::string & bytes) +{ + const auto manifest = manifestOf(storage, uuid, ref); + const auto * entry = DB::Cas::findEntry(manifest.entries, path); + ASSERT_NE(entry, nullptr) << path; + EXPECT_EQ(entry->placement, DB::Cas::EntryPlacement::Blob); + EXPECT_EQ(entry->blob_size, bytes.size()); + EXPECT_EQ(entry->ref, DB::Cas::poolContentHash(storage.store()->writeAlgo(), bytes)); + EXPECT_TRUE(readPartFile(storage, table_dir + ref + "/" + path) == bytes); +} + +} + +TEST(CASInlineCapGaps, RepointCountsOnlyRetainedBasePaths) +{ + auto storage = openStorage(); + const std::string ref = "all_1_1_0"; + const std::string dir = table_dir + ref; + auto tx = storage->createTransaction(); + writeFullBudget(*tx, dir); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + tx->unlinkFile(dir + "/0.idx", false, true); + writeFileTx(*tx, dir + "/1.idx", "short"); + writeFileTx(*tx, dir + "/extra.idx", payload(mib, 58)); + tx->commit(DB::NoCommitOptions{}); + + const auto manifest = manifestOf(*storage, uuid, ref); + EXPECT_EQ(inlineTotal(manifest), 15 * mib + 5); + EXPECT_FALSE(storage->existsFile(dir + "/0.idx")); + EXPECT_EQ(readPartFile(*storage, dir + "/1.idx"), "short"); + EXPECT_TRUE(readPartFile(*storage, dir + "/extra.idx") == payload(mib, 58)); +} + +TEST(CASInlineCapGaps, SpillsCommittedHardlinkWithoutChangingItsSource) +{ + auto storage = openStorage(); + const std::string src = table_dir + "all_1_1_0"; + const std::string dst_ref = "all_2_2_0"; + const std::string dst = table_dir + dst_ref; + auto tx = storage->createTransaction(); + writeFileTx(*tx, src + "/link.idx", "x"); + writeFullBudget(*tx, dst); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + tx->createHardLink(src + "/link.idx", dst + "/new.idx"); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, dst_ref, "new.idx", "x"); + EXPECT_EQ(storage->tryGetInManifestBytes(src + "/link.idx"), "x"); + EXPECT_TRUE(readPartFile(*storage, dst + "/15.idx") == payload(mib, 15)); +} + +TEST(CASInlineCapGaps, PartialMutationSpillsLargestBorrowedEntry) +{ + auto storage = openStorage(); + const std::string src = table_dir + "all_1_1_0"; + const std::string ref = "tmp_mut_all_1_1_0_2"; + const auto borrowed = payload(mib, 91); + auto tx = storage->createTransaction(); + writeFileTx(*tx, src + "/source.idx", borrowed); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + tx->createHardLink(src + "/source.idx", table_dir + ref + "/a.idx"); + writeFullBudget(*tx, table_dir + ref, "fresh"); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, ref, "a.idx", borrowed); + EXPECT_TRUE(readPartFile(*storage, src + "/source.idx") == borrowed); + for (size_t i = 0; i < 16; ++i) + EXPECT_TRUE(readPartFile(*storage, table_dir + ref + "/fresh" + std::to_string(i) + ".idx") == payload(mib, i)); +} + +TEST(CASInlineCapGaps, MovingStagedInlineIntoNestedBasePreservesThatBase) +{ + auto storage = openStorage(); + const std::string ref = "tmp_merge_all_1_2_1"; + const std::string dst = table_dir + ref; + const std::string src = table_dir + "all_3_3_0"; + auto tx = storage->createTransaction(); + writeFullBudget(*tx, dst, "text_index_tmp/"); + writeFileTx(*tx, src + "/keep.idx", "keep"); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + writeFileTx(*tx, src + "/transfer.idx", "m"); + tx->moveFile(src + "/transfer.idx", dst + "/new.idx"); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, ref, "new.idx", "m"); + EXPECT_TRUE(readPartFile(*storage, dst + "/text_index_tmp/0.idx") == payload(mib, 0)); + EXPECT_FALSE(storage->existsFile(src + "/transfer.idx")); + EXPECT_EQ(readPartFile(*storage, src + "/keep.idx"), "keep"); +} + +TEST(CASInlineCapGaps, ScratchExtensionAndReplacementHaveSeparateBudgets) +{ + auto storage = openStorage(); + const std::string ref = "tmp_merge_all_1_2_1"; + const std::string dir = table_dir + ref; + auto tx = storage->createTransaction(); + writeFullBudget(*tx, dir, "text_index_tmp/"); + writeFileTx(*tx, dir + "/text_index_tmp/small", "s"); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, ref, "text_index_tmp/0.idx", payload(mib, 0)); + + tx = storage->createTransaction(); + writeFileTx(*tx, dir + "/text_index_tmp/later", "later"); + tx->commit(DB::NoCommitOptions{}); + EXPECT_TRUE(storage->existsFile(dir + "/text_index_tmp/0.idx")); + + tx = storage->createTransaction(); + writeFullBudget(*tx, dir); + writeFileTx(*tx, dir + "/small", "f"); + tx->commit(DB::NoCommitOptions{}); + expectBlob(*storage, ref, "0.idx", payload(mib, 0)); + EXPECT_EQ(inlineTotal(manifestOf(*storage, uuid, ref)), 15 * mib + 1); + EXPECT_FALSE(storage->existsFile(dir + "/text_index_tmp/later")); + EXPECT_FALSE(storage->existsFile(dir + "/text_index_tmp/0.idx")); +} + +TEST(CASInlineCapGaps, UploadReadersShareBytesAndOwnIndependentPositions) +{ + std::unique_ptr first; + std::unique_ptr second; + { + auto source = DB::Cas::BlobSource::fromString("abcdef"); + auto copy = source; + first = source.open(); + second = copy.open(); + } + EXPECT_EQ(first->position(), second->position()); + char prefix[2]; + first->readStrict(prefix, sizeof(prefix)); + std::string tail, full; + DB::readStringUntilEOF(tail, *first); + DB::readStringUntilEOF(full, *second); + EXPECT_EQ(tail, "cdef"); + EXPECT_EQ(full, "abcdef"); +} + +namespace +{ + +/// The emulated backend writes a blob into a unique temporary object before renaming it. +class FailBlobWriteStorage : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + std::string fail_key; + std::atomic failures{0}; + + std::unique_ptr writeObject( + const DB::StoredObject & object, DB::WriteMode mode, std::optional attributes, + size_t buffer_size, const DB::WriteSettings & settings) override + { + if (!fail_key.empty() && object.remote_path.find(fail_key + ".publish-") != std::string::npos) + { + ++failures; + throw DB::Exception(DB::ErrorCodes::INCORRECT_DATA, "Fault while publishing the selected spill"); + } + return LocalObjectStorage::writeObject(object, mode, std::move(attributes), buffer_size, settings); + } +}; + +enum class Publication +{ + NewRef, + Repoint, + ReplaceScratch, +}; + +void checkSpillFailure(Publication mode) +{ + const auto directory_owner = DB::Cas::tests::makeLocalObjectStorageForTest(); + const auto root = directory_owner->getCommonKeyPrefix(); + auto objects = std::make_shared(DB::LocalObjectStorageSettings("fault", root, false)); + auto storage = openStorage(objects); + const auto ns = storage->liveNamespace(uuid); + const std::string ref = "tmp_merge_all_1_2_1"; + const std::string dst = table_dir + ref; + const std::string input = table_dir + "all_1_1_0"; + const bool repoint = mode == Publication::Repoint; + { + auto tx = storage->createTransaction(); + writeFileTx(*tx, input + "/source.idx", "input"); + if (repoint) + writeFullBudget(*tx, dst); + else if (mode == Publication::ReplaceScratch) + writeFileTx(*tx, dst + "/text_index_tmp/segment", "scratch"); + tx->commit(DB::NoCommitOptions{}); + } + const auto base = storage->store()->resolveRef(ns, ref); + const auto bytes = repoint ? std::string("fresh") : payload(mib, 0); + objects->fail_key = storage->store()->layout().blobKey(DB::Cas::poolContentHash(storage->store()->writeAlgo(), bytes)); + auto publish = [&] + { + auto tx = storage->createTransaction(); + if (!repoint) + writeFullBudget(*tx, dst); + writeFileTx(*tx, dst + "/extra.idx", "fresh"); + tx->commit(DB::NoCommitOptions{}); + }; + + EXPECT_THROW(publish(), DB::Exception); + ASSERT_GT(objects->failures.load(), 0); + EXPECT_TRUE(storage->store()->livePrecommitsForTest(ns).empty()); + const auto after = storage->store()->resolveRef(ns, ref); + if (repoint) + { + ASSERT_TRUE(after && base); + EXPECT_EQ(after->manifest_id, base->manifest_id); + EXPECT_TRUE(readPartFile(*storage, dst + "/0.idx") == payload(mib, 0)); + } + else + EXPECT_FALSE(after); + EXPECT_EQ(readPartFile(*storage, input + "/source.idx"), "input"); + + objects->fail_key.clear(); + if (mode == Publication::ReplaceScratch) + { + auto tx = storage->createTransaction(); + writeFileTx(*tx, dst + "/text_index_tmp/segment", "rebuilt scratch"); + tx->commit(DB::NoCommitOptions{}); + } + ASSERT_NO_THROW(publish()); + expectBlob(*storage, ref, repoint ? "extra.idx" : "0.idx", bytes); +} +} + +TEST(CASInlineCapGaps, FailedSpillDoesNotPublishNewRef) +{ + checkSpillFailure(Publication::NewRef); +} + +TEST(CASInlineCapGaps, FailedSpillPreservesRepointBase) +{ + checkSpillFailure(Publication::Repoint); +} + +TEST(CASInlineCapGaps, FailedScratchReplacementCanRebuildFromInput) +{ + checkSpillFailure(Publication::ReplaceScratch); +} + +TEST(CASInlineCapGaps, RepointRefusesBaseChangedAfterSpillUpload) +{ + auto storage = openStorage(); + const std::string ref = "all_1_1_0"; + const std::string dir = table_dir + ref; + auto tx = storage->createTransaction(); + writeFullBudget(*tx, dir); + tx->commit(DB::NoCommitOptions{}); + + tx = storage->createTransaction(); + writeFileTx(*tx, dir + "/spill.idx", "x"); + bool uploaded = false; + bool interposed = false; + bool rival_committed = false; + /// The next manifest PUT after the blob PUT stages the combined manifest on the writer + /// thread, after fan-out has joined and before promotion checks the expected base. + storage->store()->setEventSink([&](const DB::Cas::CasEvent & event) + { + if (event.type == DB::Cas::CasEventType::BlobPut) + uploaded = true; + if (event.type == DB::Cas::CasEventType::ManifestPut && uploaded && !interposed) + { + interposed = true; + auto rival = storage->createTransaction(); + writeFileTx(*rival, dir + "/0.idx", "winner"); + rival->commit(DB::NoCommitOptions{}); + rival_committed = true; + } + }); + const std::string failure = commitErrorOf(*tx); + storage->store()->setEventSink(nullptr); + ASSERT_TRUE(rival_committed); + EXPECT_FALSE(failure.empty()); + tx.reset(); + EXPECT_EQ(readPartFile(*storage, dir + "/0.idx"), "winner"); + EXPECT_FALSE(storage->existsFile(dir + "/spill.idx")); + EXPECT_TRUE(storage->store()->livePrecommitsForTest(storage->liveNamespace(uuid)).empty()); +} + +namespace +{ + +void checkInlineCandidateWritePeak(size_t num_files, size_t chunks_per_file, Int64 limit) +{ +#if defined(SANITIZER) + UNUSED(num_files, chunks_per_file, limit); + GTEST_SKIP() << "operator new is not charged to the memory tracker under sanitizers"; +#else + auto storage = openStorage(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const std::string directory = table_dir + "all_1_1_0/"; + const Int64 peak = std::async(std::launch::async, [&] + { + MemoryTracker tracker(&total_memory_tracker, VariableContext::Process, /*log_peak_memory_usage_in_destructor_=*/false); + DB::ThreadStatus thread_status; + thread_status.memory_tracker.setParent(&tracker); + thread_status.untracked_memory_limit = 0; + + const std::string chunk(mib, 'x'); + std::vector> writers; + for (size_t i = 0; i < num_files; ++i) + writers.push_back(ca_tx.writeFile(directory + std::to_string(i) + ".dct.idx", mib, DB::WriteMode::Rewrite, {})); + for (size_t i = 0; i < chunks_per_file; ++i) + for (auto & writer : writers) + writer->write(chunk.data(), chunk.size()); + for (auto & writer : writers) + writer->finalize(); + return tracker.getPeak(); + }).get(); + ::testing::Test::RecordProperty("peak_bytes", std::to_string(peak)); + EXPECT_LE(peak, limit); +#endif +} + +} + +TEST(CASInlineCandidateMemory, ALargeInlineCandidateIsNotHeldWholeInMemory) +{ + checkInlineCandidateWritePeak(1, 64, 8 * mib); +} + +TEST(CASInlineCandidateMemory, TwoLargeInlineCandidatesOpenAtOnceStayBounded) +{ + checkInlineCandidateWritePeak(2, 32, 12 * mib); +} + +TEST(CASInlineCandidateMemory, BytesPastTheThresholdReachScratchBeforeFinalize) +{ + auto storage = openStorage(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const std::string path = table_dir + "all_1_1_0/skip.dct.idx"; + auto writer = ca_tx.writeFile(path, 64 * kib, DB::WriteMode::Rewrite, {}); + const auto bytes = payload(2 * mib, 13); + writer->write(bytes.data(), bytes.size()); + writer->sync(); + const auto & scratch = storage->scratchPath(); + size_t staged_bytes = 0; + if (std::filesystem::exists(scratch)) + for (const auto & entry : std::filesystem::directory_iterator(scratch)) + if (entry.is_regular_file()) + staged_bytes += entry.file_size(); + EXPECT_EQ(staged_bytes, bytes.size()); + + writer->cancel(); + EXPECT_TRUE(!std::filesystem::exists(scratch) || std::filesystem::is_empty(scratch)); + EXPECT_FALSE(tx->tryGetInFlightFileSize(path).has_value()); +} + +TEST(CASInlineCandidateMemory, ThresholdPreservesPlacementAndPayload) +{ + auto storage = openStorage(); + const std::string ref = "all_1_1_0"; + const std::string dir = table_dir + ref + "/"; + const auto at_limit = payload(mib, 5); + const auto over_limit = at_limit + 'Z'; + auto tx = storage->createTransaction(); + writeFileTx(*tx, dir + "at.idx", at_limit); + writeFileTx(*tx, dir + "over.idx", over_limit); + tx->commit(DB::NoCommitOptions{}); + + EXPECT_TRUE(storage->tryGetInManifestBytes(dir + "at.idx") == at_limit); + expectBlob(*storage, ref, "over.idx", over_limit); +} + +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)); +} + +TEST(CASInlineCandidateMemory, LocalSpillCanStillBecomeInlineAndReadersRetainTheirSource) +{ + auto storage = openStorage(); + auto tx = storage->createTransaction(); + auto & ca_tx = dynamic_cast(*tx); + const auto first = table_dir + "all_1_1_0/"; + const auto second = table_dir + "all_2_2_0/"; + const auto bytes = payload(600 * kib, 42); + std::vector> writers; + /// Hold other candidates open to force at least one local spill under the same transaction. + for (size_t i = 0; i < 32; ++i) + { + auto writer = ca_tx.writeFile(first + std::to_string(i) + ".idx", 64 * kib, DB::WriteMode::Rewrite, {}); + writer->write(bytes.data(), bytes.size()); + writers.push_back(std::move(writer)); + } + + const auto path = second + "dict.dct.idx"; + ASSERT_TRUE(std::filesystem::is_directory(storage->scratchPath())); + const auto before = std::distance(std::filesystem::directory_iterator(storage->scratchPath()), std::filesystem::directory_iterator{}); + auto probe = ca_tx.writeFile(path, 64 * kib, DB::WriteMode::Rewrite, {}); + probe->write(bytes.data(), bytes.size()); + probe->finalize(); + const auto after = std::distance(std::filesystem::directory_iterator(storage->scratchPath()), std::filesystem::directory_iterator{}); + ASSERT_EQ(after, before + 1); + + auto reader = ca_tx.tryReadFileInFlight(path, {}, {}); + ASSERT_NE(reader, nullptr); + for (auto & writer : writers) + writer->cancel(); + tx->commit(DB::NoCommitOptions{}); + tx.reset(); + EXPECT_TRUE(storage->tryGetInManifestBytes(path) == bytes); + std::string result; + DB::readStringUntilEOF(result, *reader); + EXPECT_TRUE(result == bytes); + reader.reset(); + EXPECT_TRUE(std::filesystem::is_empty(storage->scratchPath())); +} + +TEST(CASInlineCandidateMemory, 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_s3_staging.cpp b/src/Disks/tests/gtest_cas_s3_staging.cpp index e32fc4b55e1e9..20a43bb529960 100644 --- a/src/Disks/tests/gtest_cas_s3_staging.cpp +++ b/src/Disks/tests/gtest_cas_s3_staging.cpp @@ -881,6 +881,29 @@ TEST(CASS3Staging, ReadYourWritesReturnsStagedBytesFromS3StagingObject) EXPECT_EQ(got, payload); } +TEST(CASS3Staging, OversizedInlineCandidateKeepsLocalStaging) +{ + auto objects = makeFakeNativeCopyStorage(/*native_only_copy_supported=*/true); + auto storage = makeS3StagingMetadataStorageForTest(objects, "mountInlineOverflow"); + storage->startup(); + auto tx = storage->createTransaction(); + const std::string path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/skip.dct.idx"; + const std::string bytes(1024 * 1024 + 1, 'x'); + writeThroughS3Transaction(dynamic_cast(*tx), path, bytes); + + DB::RelativePathsWithMetadata staged; + objects->listObjects(storage->stagingKeyPrefix(), staged, /*max_keys=*/0); + EXPECT_TRUE(staged.empty()); + auto reader = tx->tryReadFileInFlight(path, DB::ReadSettings{}, {}); + ASSERT_NE(reader, nullptr); + std::string actual; + DB::readStringUntilEOF(actual, *reader); + EXPECT_TRUE(actual == bytes); + reader.reset(); + tx->commit(DB::NoCommitOptions{}); + EXPECT_FALSE(storage->tryGetInManifestBytes(path).has_value()); +} + /// An aborted transaction deletes its own S3 staging object instead of leaving it for the next mount. TEST(CASS3Staging, AbortDeletesS3Staging) { @@ -1498,6 +1521,45 @@ TEST(CASS3Staging, ListPageOverANonPagingStoreStillReportsMoreKeys) EXPECT_TRUE(rest.next_cursor.empty()); } +TEST(CASS3Staging, OpenBlobReaderKeepsStagingObjectThroughCommitOrAbort) +{ + for (bool commit : {false, true}) + { + SCOPED_TRACE(commit); + auto objects = makeFakeGenerationObjectStorageForTest(); + objects->content_derived_etags = true; + auto storage = makeS3StagingMetadataStorageForTest(objects, "mountReaderLifetime"); + storage->startup(); + auto tx = storage->createTransaction(); + const String path = "a11/a11a11a1-1111-4111-8111-111111111111/all_1_1_0/data.bin"; + String bytes(64 * 1024, 'a'); + bytes.back() = 'z'; + writeThroughS3Transaction(dynamic_cast(*tx), path, bytes); + + DB::RelativePathsWithMetadata staged; + objects->listObjects(storage->stagingKeyPrefix(), staged, /*max_keys=*/0); + ASSERT_EQ(staged.size(), 1u); + const DB::StoredObject key(staged.front()->relative_path); + auto reader = tx->tryReadFileInFlight(path, DB::ReadSettings{}, {}); + ASSERT_NE(reader, nullptr); + char byte; + reader->readStrict(&byte, 1); + EXPECT_EQ(byte, 'a'); + if (commit) + tx->commit(DB::NoCommitOptions{}); + tx.reset(); + + EXPECT_EQ(objects->copiesByDestination().size(), commit ? 1u : 0u); + /// The in-memory reader retains a copy. A later S3 range GET also needs the staging key to exist. + ASSERT_TRUE(objects->exists(key)); + reader->seek(bytes.size() - 1, SEEK_SET); + reader->readStrict(&byte, 1); + EXPECT_EQ(byte, 'z'); + reader.reset(); + EXPECT_FALSE(objects->exists(key)); + } +} + TEST(CASS3Staging, GenerationBackendMayUseNativeOnlyCopy) { auto object_storage = makeFakeGenerationObjectStorageForTest(); diff --git a/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.reference b/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.reference new file mode 100644 index 0000000000000..052293bfd3081 --- /dev/null +++ b/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.reference @@ -0,0 +1,8 @@ +t_merge 1 1 1 +t_merge 100 1 +t_merge 1 +1 +t_mat 1 1 1 +t_mat 100 1 +t_mat 1 +1 diff --git a/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.sh b/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.sh new file mode 100755 index 0000000000000..0aa4ffdf41a75 --- /dev/null +++ b/tests/queries/0_stateless/05815_cas_text_index_rebuild_inline_budget.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-random-merge-tree-settings +# ^ cas is an object-storage metadata type; keep it off the minimal fasttest image. +# A merge or a mutation that rebuilds a text index writes one temporary segment per flush into +# `/text_index_tmp/` and commits that directory on its own. Every segment file is small; their sum is +# not bounded. On a content-addressed disk the commit must not depend on that sum. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh +set -e -o pipefail + +CLIENT="${CLICKHOUSE_CLIENT} --allow_experimental_full_text_index=1" +ROWS=100 + +disk() { + echo "disk(type = object_storage, object_storage_type = local, metadata_type = cas, cas_unsafe_remount_no_delay = 1, cas_server_root_id = '${CLICKHOUSE_DATABASE}_$1', name = '${CLICKHOUSE_DATABASE}_$1', path = '${CLICKHOUSE_USER_FILES_UNIQUE}_$1_pool/')" +} + +# Each row contributes 192 KiB of distinct hex tokens before dictionary encoding. +# Their hashes depend on both row and token number so each segment adds distinct tokens to the manifest. +fill() { + ${CLIENT} -q "INSERT INTO $1 SELECT number, + arrayStringConcat(arrayMap(i -> hex(sipHash128(number, i)), range(toUInt64(6144))), ' ') + FROM numbers($2, $3) SETTINGS max_insert_threads = 1, max_block_size = ${ROWS}, max_insert_block_size = ${ROWS}" +} + +check() { + ${CLIENT} -q "SELECT '$1', count(), uniqExact(_part) FROM $1" + ${CLIENT} -q "SELECT '$1', count() FROM $1 + WHERE hasToken(s, hex(sipHash128(toUInt64(7), toUInt64(0)))) + SETTINGS force_data_skipping_indices = 'idx_s'" + ${CLIENT} -q "CHECK TABLE $1 SETTINGS check_query_single_value_result = 1" +} + +# Dictionary block size and front coding affect the size of each segment file. +# Use the default dictionary settings and LZ4 so the 20 segments exceed the 16 MiB inline budget. +SEGMENTS="index_granularity = 5, merge_max_block_size = 5, text_index_max_processed_tokens_before_flush = 1, + default_compression_codec = 'LZ4', + max_bytes_to_merge_at_max_space_in_pool = 1, text_index_max_memory_usage_before_flush = '1Gi'" + +# Both counters must come from the successful operation that produced the readable part. +segments() { + ${CLIENT} -q "SYSTEM FLUSH LOGS part_log" + ${CLIENT} -q "SELECT '$1', count() = 1, + max(ProfileEvents['TextIndexTemporarySegmentsWritten']) >= 20, + max(ProfileEvents['CASManifestInlineEntriesSelectedForBlob']) > 0 + FROM system.part_log + WHERE database = currentDatabase() AND table = '$1' AND event_type = '$2' AND error = 0 + AND part_name IN (SELECT name FROM system.parts WHERE database = currentDatabase() AND table = '$1' AND active)" +} + +# A merge that may reduce rows rebuilds the index of the result part. +${CLIENT} -q "CREATE TABLE t_merge (k UInt64, s String, INDEX idx_s (s) TYPE text(tokenizer = 'splitByNonAlpha')) + ENGINE = MergeTree ORDER BY k + SETTINGS disk = $(disk merge), min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, ${SEGMENTS}" +fill t_merge 0 $((ROWS / 2)) +fill t_merge $((ROWS / 2)) $((ROWS / 2)) +${CLIENT} -q "OPTIMIZE TABLE t_merge FINAL DEDUPLICATE" +segments t_merge MergeParts +check t_merge + +# A mutation that materializes the index of a part written before the index existed. +${CLIENT} -q "CREATE TABLE t_mat (k UInt64, s String) + ENGINE = MergeTree ORDER BY k + SETTINGS disk = $(disk mat), min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, ${SEGMENTS}" +fill t_mat 0 ${ROWS} +# One part, so that one mutation builds all the segments. +${CLIENT} -q "OPTIMIZE TABLE t_mat FINAL" +${CLIENT} -q "ALTER TABLE t_mat ADD INDEX idx_s (s) TYPE text(tokenizer = 'splitByNonAlpha')" +${CLIENT} -q "ALTER TABLE t_mat MATERIALIZE INDEX idx_s SETTINGS mutations_sync = 2, max_block_size = 5" +segments t_mat MutatePart +check t_mat + +${CLIENT} -q "DROP TABLE t_merge SYNC" +${CLIENT} -q "DROP TABLE t_mat SYNC"