Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Common/ProfileEvents.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,7 @@ The server successfully detected this situation and will download merged part fr
M(CASRefMove, "Number of CAS committed-reference renames done as one ref-log owner move, with no manifest republication.", ValueType::Number) \
M(CASOwnershipConflict, "Number of CAS operations refused with CAS_OWNERSHIP_CONFLICT: the committed reference the writer had read was moved, dropped or repointed before its change landed.", ValueType::Number) \
M(CASManifestInlineEntriesSelectedForBlob, "Number of staged CAS file entries selected for blob placement because their manifest exceeded the total inline byte budget.", ValueType::Number) \
M(CASInlineWriteMemoryBudgetSpills, "Number of CAS inline-candidate files spilled to local staging because their transaction could not reserve more payload memory.", ValueType::Number) \
M(CASManifestPut, "Number of CAS manifest PUT requests. Grows with manifest creation and indicates metadata write traffic.", ValueType::Number) \
M(CASManifestPutDeduplicated, "Number of CAS deduplicating manifest PUT requests. Grows when existing manifests are reused.", ValueType::Number) \
M(CASManifestOverwrite, "Number of CAS manifest overwrite requests. Growing values indicate repeated manifest replacement.", ValueType::Number) \
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,22 @@
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

namespace DB::Cas
{
class InlineCandidatePayload;
class InlineWriteMemoryBudget;
}

namespace DB
{

Expand All @@ -33,10 +41,9 @@ namespace DB
/// `Cas::PartWriteTxn`, created lazily before the first staged dependency, so the durable manifest
/// edge is established before the pool observes or uploads a new blob.
///
/// File writes stage blobs locally or on S3. During publication the transaction also moves
/// excess inline entries into blobs, uploading them directly from their buffered bytes. The
/// destructor removes the transaction's local and S3 staging and abandons any open part builds;
/// it never publishes an uncommitted ref.
/// Inline-eligible files share a transaction-wide memory budget and spill to local staging
/// when a write exceeds either memory limit. Commit chooses placement per manifest from the
/// final paths and sizes. Readers and uploads can retain the source after publication.
class ContentAddressedTransaction : public IMetadataTransaction
{
public:
Expand Down Expand Up @@ -86,9 +93,8 @@ class ContentAddressedTransaction : public IMetadataTransaction
const std::string & path, size_t buf_size, WriteMode mode,
const WriteSettings & settings, bool autocommit) override;

/// Creates the inner buffer for a content-addressed path. Inline candidates that outgrow
/// the per-file limit stream to local staging. Part blobs are hashed as they are written, and
/// verbatim namespace or mountpoint files are read-modify-written when append is requested.
/// Opens a part-file writer or a verbatim namespace or mountpoint writer. Only verbatim files
/// support append, by reading and rewriting the existing contents.
std::unique_ptr<WriteBufferFromFileBase> writeFile(
const std::string & path,
size_t buf_size,
Expand Down Expand Up @@ -127,6 +133,8 @@ class ContentAddressedTransaction : public IMetadataTransaction
/// Test-only: stages the part file `path` as a blob entry naming `ref` with no pending upload and no copy
/// source, a shape no operation produces.
void stageUnprovenBlobEntryForTest(const std::string & path, const Cas::BlobRef & ref, uint64_t size);
size_t inlineCandidateReservedBytesForTest() const noexcept;
void failNextFileRegistrationForTest() { fail_next_file_registration = true; }
/// Test-only: the copy source shared by this transaction's borrows from the committed part `part_path`, or null.
std::shared_ptr<const Cas::CopySource> borrowedSourceForTest(const std::string & part_path) const;

Expand All @@ -137,20 +145,34 @@ class ContentAddressedTransaction : public IMetadataTransaction
ContentAddressedMetadataStorage & metadata_storage;

private:
/// State for one routed part. The build is opened lazily at the first staged write so every
/// manifest dependency is recorded by the same `Cas::PartWriteTxn`; pending blobs remain in
/// staging until publication.
/// One finalized source shared across paths, readers and uploads. The memory payload
/// owns its reservation until the last holder releases its bytes.
struct StagedPartFilePayload
{
std::shared_ptr<const Cas::InlineCandidatePayload> in_memory_payload;
String staging_path; /// Local filesystem path or the S3 key used by IObjectStorage.
ObjectStoragePtr remote_storage;
String pool_staging_key; /// Pool-relative address for reads through the request engine.
ThrottlerPtr remote_throttler; /// The original writer's bandwidth limiter follows the file through hardlinks and moves.
bool allow_inline_by_name = false; /// Set from the original write path, before any hardlink or rename.
bool registered = false; /// The local writer owns its scratch path until registration succeeds.
mutable std::atomic<bool> publication_attempted{false};

~StagedPartFilePayload();
};
using StagedPartFilePayloadPtr = std::shared_ptr<const StagedPartFilePayload>;

/// 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.
Cas::PartWriteTxnPtr build;
std::vector<Cas::ManifestEntry> entries; /// staged manifest entries (uploads + adoptions)
/// The committed source of each entry in `entries` adopted without reading its body, keyed by entry path.
/// It follows the entry through staged copies and renames; `confirmCopySources` checks it before promote.
/// Written only by `putEntry`, `eraseEntry`, `rekeyEntry` and `clearEntries`, which keep it in step with `entries`,
/// until a successful `commit` clears it.
/// Adding, replacing, renaming or removing an entry keeps this map in step with `entries`. A successful commit clears it.
/// Entries borrowed from one source share one handle (`copy_sources_by_part`).
std::map<std::string, std::shared_ptr<Cas::CopySource>> copy_sources;
std::unordered_map<std::string, std::shared_ptr<Cas::CopySource>> borrowed_blob_sources_by_path;
/// The committed manifest this transaction found under the part's name when it first staged a
/// write to it; a later commit requires exactly that binding. Empty for a part the transaction
/// creates (`tmp_*`), where a committed row at commit time is somebody else's part, not ours,
Expand All @@ -163,25 +185,15 @@ class ContentAddressedTransaction : public IMetadataTransaction
bool published = false; /// set by publishStaging during commit(); the commit
/// loop is idempotent (never re-publishes a staging).

/// `staging_key` is either a private local temp path or an S3 staging object key returned by
/// `CaContentWriteBuffer` at finalize. The backend selects the read-your-writes source; both
/// kinds are removed by this transaction on commit and on abort.
struct PendingBlob
{
Cas::BlobRef ref;
std::string staging_key;
uint64_t size = 0;
Cas::StagingBackend backend = Cas::StagingBackend::Local;
/// The once-only verbatim-copy privilege of the staging object. A hardlink copies this
/// record into another part, and the copy shares the flag, so the parts together copy
/// the staged envelope at most once.
std::shared_ptr<std::atomic<bool>> publication_attempted = std::make_shared<std::atomic<bool>>(false);
/// The `remote_throttler` of the settings the file was written with; a hardlink or a move keeps it.
ThrottlerPtr remote_throttler;
};
std::vector<PendingBlob> pending_blobs; /// Staged blobs uploaded after the manifest edge is precommitted.
/// Each newly written path and its hardlinks retain the original staging source.
std::unordered_map<String, StagedPartFilePayloadPtr> staged_payloads_by_path;
bool has_finalized_file_write = false; /// A build opened only for a transfer cannot replace the temporary segment ref.
};

std::shared_ptr<Cas::InlineWriteMemoryBudget> 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<std::pair<std::string, std::string>, PartStaging> parts;
Expand All @@ -190,6 +202,7 @@ class ContentAddressedTransaction : public IMetadataTransaction
std::unordered_map<String, std::shared_ptr<Cas::CopySource>> 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
Expand All @@ -198,22 +211,32 @@ class ContentAddressedTransaction : public IMetadataTransaction
/// Cleared in `commit()`'s epilogue.
std::unordered_set<String> force_fresh_validated_refs;

/// Stage a content part file as a blob without recording a dependency proof, and add/replace its
/// manifest entry. Successful post-precommit publication later records `Materialized`. Shared by
/// the streaming-blob path
/// (Local or S3-staging, `backend` says which) and the always-Local inline-cap fallback.
void registerFinalizedPartFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size,
const std::shared_ptr<StagedPartFilePayload> & staged_payload);
/// Transfer the writer's private file or S3 object only on successful registration.
void stageBlobPartFile(const ContentAddressedMetadataStorage::Route & route,
const Cas::BlobRef & ref, size_t size, const std::string & staging_key,
Cas::StagingBackend backend, ThrottlerPtr remote_throttler);
ObjectStoragePtr remote_storage, const String & pool_staging_key, ThrottlerPtr remote_throttler);

/// Builds the fixed-length CABL envelope header for a staging blob, with a fresh `incarnation_tag`,
/// so the S3 staging object holds `[header][payload]` and the promote
/// stays a verbatim server-side copy. `build_id` is left 0 (not known at stream time; diagnostic-only).
std::string buildS3StagingBlobHeader(const ContentAddressedMetadataStorage::Route & route) const;

/// Replaces the staged entry at `entry.path`; `source` is its committed source when it was adopted from
/// another part without its bytes, and nullopt when this transaction uploads or inlines the bytes.
static void putEntry(PartStaging & st, Cas::ManifestEntry entry, std::shared_ptr<Cas::CopySource> source);
/// An Inline entry copied from a committed manifest already contains its file bytes.
static void putCopiedInlineEntry(PartStaging & part_staging, Cas::ManifestEntry && entry);

/// A writer finalized the file in this transaction. Keep its bytes in memory or staging for this path and any hardlinks.
static void putEntryWithStagedPayload(PartStaging & part_staging, Cas::ManifestEntry && entry, StagedPartFilePayloadPtr staged_payload);

/// A hardlink reuses a Blob entry from a committed manifest. Keep the source so commit can confirm the borrowed blob.
static void putBorrowedBlobEntry(
PartStaging & part_staging, Cas::ManifestEntry && entry, std::shared_ptr<Cas::CopySource> borrowed_blob_source);

/// Hardlinks and moves carry the original file or copy source to the destination path. An entry can have at most one.
static void putEntryForHardLinkOrMove(
PartStaging & part_staging, Cas::ManifestEntry && entry, std::shared_ptr<Cas::CopySource> borrowed_blob_source, StagedPartFilePayloadPtr staged_payload);

static void eraseEntry(PartStaging & st, const std::string & path);
/// Renames `entry`, an element of `st.entries`, in place; `new_path` must not be staged.
static void rekeyEntry(PartStaging & st, Cas::ManifestEntry & entry, std::string new_path);
Expand Down Expand Up @@ -243,17 +266,26 @@ class ContentAddressedTransaction : public IMetadataTransaction
void discardStagingOf(const ContentAddressedMetadataStorage::Route & r);
/// Finds the staged manifest entry for a routed file without consulting committed storage.
const Cas::ManifestEntry * findStagedEntry(const ContentAddressedMetadataStorage::Route & r) const;
/// Returns the pending (staged but not yet uploaded) blob for `ref`, or nullptr when it has
/// already been uploaded or was never staged.
const PartStaging::PendingBlob * findPendingBlob(const PartStaging & st, const Cas::BlobRef & ref) const;

static StagedPartFilePayloadPtr findStagedPayload(const PartStaging & st, const String & path);

static std::unique_ptr<ReadBuffer> openStagedPayload(const StagedPartFilePayloadPtr & staged_payload, uint64_t size, const Cas::PoolPtr & pool);

Cas::BlobSource stagedUploadSource(const StagedPartFilePayloadPtr & staged_payload, uint64_t size) const;

static void convertInlineEntryToBlob(
Cas::ManifestEntry & entry, Cas::BlobHashAlgo hash_algo, std::vector<Cas::BlobUploadRequest> & blob_upload_requests);
static void convertBlobEntryToInline(Cas::ManifestEntry & entry, PartStaging & part_staging, const Cas::PoolPtr & pool);

std::vector<Cas::BlobUploadRequest> applyManifestInlineBudget(
PartStaging & part_staging, uint64_t inline_bytes_from_unchanged_base_entries) const;
/// Returns the part build, creating it lazily with the routed ref as its intended destination.
Cas::PartWriteTxn & buildFor(const ContentAddressedMetadataStorage::Route & r, PartStaging & st);
/// Parses a disk path and maps a part-file path to its namespace/ref/file route.
std::optional<ContentAddressedMetadataStorage::Route> routeOf(const std::string & path) const;

/// Removes the transaction's staging after commit or abort: local files and S3 staging objects
/// alike. S3 deletes are best-effort; a lost delete leaves debris for the mount-start sweep.
void cleanupPendingTempFiles() noexcept;
/// Release this transaction's ownership. Readers and pending uploads retain their own handles.
void releaseStagedFiles() noexcept;

/// Append sources from local or S3 staging only for blob refs still named by the staged entries.
void appendStagedBlobUploads(const PartStaging & st, std::vector<Cas::BlobUploadRequest> & blob_upload_requests) const;
Expand All @@ -262,21 +294,6 @@ class ContentAddressedTransaction : public IMetadataTransaction
Cas::ManifestId precommitAndUpload(const Cas::RootNamespace & ns, const std::string & ref, PartStaging & st,
const PendingRefs & blob_refs_with_upload_requests, const std::vector<Cas::BlobUploadRequest> & blob_upload_requests);

/// Adopts a manifest entry into another part while preserving its storage state. For a pending
/// blob, `copy_pending` controls whether the staging record is copied (hardlink semantics) or
/// has already been moved by the caller; no dependency exists until its upload succeeds. For
/// an uploaded or committed blob, the destination records trusted-manifest evidence and does not
/// perform a pool read before precommit.
///
/// `pb != nullptr` (pending, not yet uploaded):
/// - `copy_pending=true` → push a copy of *pb into dst_st.pending_blobs (hardlink semantics:
/// both src and dst upload independently; src's copy is left in place by the caller).
/// - `copy_pending=false` → the pb record is already in dst_st (moved or already there).
/// In both cases the later successful upload records `Materialized` in the destination build.
///
void adoptStagedBlob(const PartStaging::PendingBlob * pb, const Cas::ManifestEntry & entry,
PartStaging & dst_st, Cas::PartWriteTxn & dst_build, bool copy_pending);

/// Publishes one staged part, either by promoting a newly staged manifest or by repointing an
/// existing ref after carrying its unchanged entries forward. It is idempotent within the commit
/// loop and marks the staging as published. Writes the exact `Cas::CommitOutcome` into `out_slot`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,9 @@ EntryPlacement entryPlacementFromWireWord(std::string_view w)
return kEntryPlacementWords.fromWord(w, "PartManifest: EntryPlacement");
}

String encodePartManifest(const PartManifest & m)
namespace
{
String encodePartManifestWithDigest(const PartManifest & m, const UInt128 & payload_digest)
{
/// Canonical path order plus duplicate-path rejection makes the encoded record sequence
/// deterministic and establishes the ordering required by the lookup helpers.
Expand Down Expand Up @@ -144,7 +146,7 @@ String encodePartManifest(const PartManifest & m)
bool first = true;
writeManifestRefFields(out, first, kBareManifestRefKeys, m.ref);
writeStringField(out, PartManifestWire::ns, m.root_namespace_id.string(), first);
writeHex128Field(out, PartManifestWire::payload_digest, m.payload_digest, first);
writeHex128Field(out, PartManifestWire::payload_digest, payload_digest, first);
closeObject(out, first);
check_line_bytes(out.size() - line_start, "descriptor");
writeChar('\n', out);
Expand Down Expand Up @@ -176,6 +178,13 @@ String encodePartManifest(const PartManifest & m)
return std::move(out).take();
}

}

String encodePartManifest(const PartManifest & m)
{
return encodePartManifestWithDigest(m, m.payload_digest);
}

PartManifest decodePartManifest(std::string_view data)
{
ReadBufferFromMemory in(data.data(), data.size());
Expand Down Expand Up @@ -321,9 +330,7 @@ PartManifest decodePartManifest(std::string_view data)
throw Exception(ErrorCodes::CORRUPTED_DATA, "PartManifest: trailing bytes after the payload zone");

/// Recompute and verify `payload_digest` last, over the fully-decoded body. `computePayloadDigest`
/// builds its own probe copy with payload_digest zeroed before hashing (see below), so calling it
/// directly here on `m` (whose payload_digest is whatever was read off the wire) is safe and
/// matches encode's own computation exactly.
/// encodes a zero digest in the descriptor regardless of the value read from the wire.
///
/// The decoder accepts strings the encoder would escape longer (a raw control byte), so a line that fit
/// the cap as stored can exceed it once re-encoded: these bytes are corrupt, not a writer's limit.
Expand Down Expand Up @@ -353,9 +360,7 @@ UInt128 computePayloadDigest(const PartManifest & m)
/// itself (it would be circular otherwise) and is stable for identical bodies, changing whenever
/// ref / namespace / entries change. Uses the CAS content-hash primitive (CityHash128) over the
/// deterministic encodePartManifest bytes - the same primitive blob/tree hashing uses.
PartManifest probe = m;
probe.payload_digest = UInt128{};
const String bytes = encodePartManifest(probe);
const String bytes = encodePartManifestWithDigest(m, UInt128{});
const auto h = CityHash_v1_0_2::CityHash128(bytes.data(), bytes.size());
return (static_cast<UInt128>(h.high64) << 64) | static_cast<UInt128>(h.low64);
}
Expand Down
Loading
Loading