Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -510,10 +510,11 @@ disk-level and server-level settings surface.
is committed to the pool (never the object-storage key prefix). Defaults to
`<clickhouse-path>/disks/<disk_name>/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
Expand Down
6 changes: 6 additions & 0 deletions docs/en/antalya/metrics_and_events.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions src/Common/ProfileEvents.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) \
Expand Down

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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<ReadBuffer>
{ return std::make_unique<ReadBufferFromOwnString>(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<const String> bytes_)
: ReadBufferFromString(*bytes_), payload_owner(std::move(bytes_))
{
}

private:
std::shared_ptr<const String> payload_owner;
};
source.open = [owner = std::make_shared<const String>(std::move(bytes))]
{
return std::make_unique<Reader>(owner);
};
return source;
}

Expand Down Expand Up @@ -627,10 +637,10 @@ ManifestId PartWriteTxn::stageManifest(std::vector<ManifestEntry> 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();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
#include <Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasInlineCandidateWriteBuffer.h>

#include <Common/ProfileEvents.h>

#include <algorithm>
#include <cstring>

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<char[]> replacement;
try
{
replacement = std::make_unique_for_overwrite<char[]>(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<InlineWriteMemoryBudget> budget,
CreateLocalWriter create_local_writer_, OnInline on_inline_)
: WriteBufferFromFileBase(0, nullptr, 0)
, path(std::move(path_))
, transfer_size(std::clamp<size_t>(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<InlineCandidatePayload>(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<size_t>(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();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#pragma once

#include <IO/WriteBufferFromFileBase.h>

#include <atomic>
#include <functional>
#include <memory>
#include <string_view>

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<size_t> reserved{0};
};

/// After finalize, hardlinks and in-flight readers share the same allocation and reservation.
class InlineCandidatePayload
{
public:
explicit InlineCandidatePayload(std::shared_ptr<InlineWriteMemoryBudget> 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<InlineWriteMemoryBudget> budget;
std::unique_ptr<char[]> buffer;
size_t length = 0;
size_t capacity = 0;
};

using InlineCandidatePayloadPtr = std::shared_ptr<const InlineCandidatePayload>;

class InlineCandidateWriteBuffer final : public WriteBufferFromFileBase
{
public:
using CreateLocalWriter = std::function<std::unique_ptr<WriteBuffer>()>;
using OnInline = std::function<void(InlineCandidatePayloadPtr)>;

InlineCandidateWriteBuffer(
String path_, size_t buf_size, size_t max_inline_bytes_, std::shared_ptr<InlineWriteMemoryBudget> 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<InlineCandidatePayload> payload;
std::unique_ptr<WriteBuffer> 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;
};

}
3 changes: 2 additions & 1 deletion src/Disks/IO/WriteBufferInlineOrBlob.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading
Loading