be/src/io/cache/async_cache_write_manager.h
Line | Count | Source |
1 | | // Licensed to the Apache Software Foundation (ASF) under one |
2 | | // or more contributor license agreements. See the NOTICE file |
3 | | // distributed with this work for additional information |
4 | | // regarding copyright ownership. The ASF licenses this file |
5 | | // to you under the Apache License, Version 2.0 (the |
6 | | // "License"); you may not use this file except in compliance |
7 | | // with the License. You may obtain a copy of the License at |
8 | | // |
9 | | // http://www.apache.org/licenses/LICENSE-2.0 |
10 | | // |
11 | | // Unless required by applicable law or agreed to in writing, |
12 | | // software distributed under the License is distributed on an |
13 | | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
14 | | // KIND, either express or implied. See the License for the |
15 | | // specific language governing permissions and limitations |
16 | | // under the License. |
17 | | |
18 | | #pragma once |
19 | | |
20 | | #include <atomic> |
21 | | #include <condition_variable> |
22 | | #include <cstddef> |
23 | | #include <cstdint> |
24 | | #include <deque> |
25 | | #include <functional> |
26 | | #include <memory> |
27 | | #include <mutex> |
28 | | #include <vector> |
29 | | |
30 | | #include "common/atomic_shared_ptr.h" |
31 | | #include "common/status.h" |
32 | | #include "io/cache/file_cache_common.h" |
33 | | #include "runtime/memory/mem_tracker_limiter.h" |
34 | | #include "util/threadpool.h" |
35 | | |
36 | | namespace doris::io { |
37 | | |
38 | | class BlockFileCache; |
39 | | class AsyncCacheWriteEpochRegistry; |
40 | | |
41 | | /// Cache admission attributes captured on the query thread and replayed by a write worker. |
42 | | struct CacheAdmissionContext { |
43 | | /// Query identity used by per-query cache admission and accounting. |
44 | | TUniqueId query_id; |
45 | | FileCacheType cache_type {FileCacheType::NORMAL}; |
46 | | int64_t expiration_time {0}; |
47 | | int64_t tablet_id {0}; |
48 | | bool is_warmup {false}; |
49 | | |
50 | | /// Capture only the cache-admission fields that remain valid after the query thread returns. |
51 | | static CacheAdmissionContext from_cache_context(const CacheContext& context, int64_t tablet_id); |
52 | | |
53 | | /// Recreate the worker-local cache context and attach its temporary statistics sink. |
54 | | CacheContext to_cache_context(ReadStatistics* stats) const; |
55 | | }; |
56 | | |
57 | | /// Reference-counted payload whose allocation is charged to the async-write memory tracker. |
58 | | class AsyncCacheWriteBuffer { |
59 | | public: |
60 | | ~AsyncCacheWriteBuffer(); |
61 | | |
62 | 397 | char* data() { return _data; } |
63 | 0 | const char* data() const { return _data; } |
64 | 1.91k | size_t size() const { return _size; } |
65 | | |
66 | | private: |
67 | | friend class AsyncCacheWriteManager; |
68 | | |
69 | | AsyncCacheWriteBuffer(size_t size, std::shared_ptr<MemTrackerLimiter> tracker); |
70 | | |
71 | | char* _data = nullptr; |
72 | | size_t _size = 0; |
73 | | std::shared_ptr<MemTrackerLimiter> _tracker; |
74 | | }; |
75 | | |
76 | | using AsyncCacheWriteBufferPtr = std::shared_ptr<AsyncCacheWriteBuffer>; |
77 | | |
78 | | /// One live per-file write generation. All async read plans and writes for the same cache key share |
79 | | /// the current token. A key-scoped remove invalidates that token and lets later reads capture a new |
80 | | /// generation without retaining an epoch entry for every historical cache key. |
81 | | class AsyncCacheWriteEpochToken { |
82 | | public: |
83 | | ~AsyncCacheWriteEpochToken(); |
84 | | |
85 | 8 | uint64_t generation() const { return _generation; } |
86 | 310 | bool is_valid() const { return _valid.load(std::memory_order_acquire); } |
87 | | |
88 | | private: |
89 | | friend class AsyncCacheWriteEpochRegistry; |
90 | | |
91 | | AsyncCacheWriteEpochToken(const UInt128Wrapper& cache_hash, uint64_t generation, |
92 | | std::weak_ptr<AsyncCacheWriteEpochRegistry> registry); |
93 | | |
94 | | UInt128Wrapper _cache_hash; |
95 | | uint64_t _generation {0}; |
96 | | std::weak_ptr<AsyncCacheWriteEpochRegistry> _registry; |
97 | | std::atomic<bool> _valid {true}; |
98 | | }; |
99 | | |
100 | | /// Composite persistence fence shared by an async read plan and its derived write tasks. |
101 | | /// `cache_epoch` invalidates all older writes on one cache disk during a full-cache clear, while |
102 | | /// `key_token` lets a single-file removal invalidate only older writes for that cache key. The |
103 | | /// epoch does not govern inflight reads because a cache hash identifies immutable file content. |
104 | | struct AsyncCacheWriteEpoch { |
105 | | uint64_t cache_epoch {0}; |
106 | | std::shared_ptr<AsyncCacheWriteEpochToken> key_token; |
107 | | }; |
108 | | |
109 | | /// One cache-block write. The sole production submitter allocates every `buffer` with exactly |
110 | | /// `file_cache_each_block_size` bytes. `write_size` is the valid prefix starting at `file_offset`; |
111 | | /// only the physical EOF block may use less than the full buffer. `write_epoch` prevents a worker |
112 | | /// from resurrecting data after cache invalidation. |
113 | | struct AsyncCacheWriteTask { |
114 | | using Finalizer = std::function<void(const AsyncCacheWriteTask&)>; |
115 | | |
116 | | UInt128Wrapper cache_hash; |
117 | | size_t file_offset {0}; |
118 | | size_t write_size {0}; |
119 | | AsyncCacheWriteBufferPtr buffer; |
120 | | CacheAdmissionContext admission_ctx; |
121 | | int64_t submit_ts_us {0}; |
122 | | AsyncCacheWriteEpoch write_epoch; |
123 | | Finalizer on_finalized; |
124 | | |
125 | | /// Assert the task contract at the manager boundary. |
126 | | void validate() const; |
127 | | |
128 | | /// Return the full allocation capacity charged to pending-byte accounting. |
129 | | size_t buffer_size() const; |
130 | | |
131 | | /// Run the optional owner cleanup after this task reaches a terminal state. |
132 | | void finalize() const; |
133 | | }; |
134 | | |
135 | | /// Complete per-cache-disk worker and memory settings. The manager receives this value |
136 | | /// explicitly at construction and through update_options(); it never reads global config. |
137 | | struct AsyncCacheWriteManagerOptions { |
138 | | size_t worker_count {1}; |
139 | | // Accepted queued+active buffer capacity. With fixed block-size buffers, any remainder smaller |
140 | | // than one block is intentionally unusable. |
141 | | size_t max_pending_bytes {1}; |
142 | | }; |
143 | | |
144 | | /// Resolve the configured BE-wide pending-byte ownership limit. A positive value is used |
145 | | /// unchanged; -1 selects max(1 GiB, 1% of `be_mem_limit`). Config validation rejects every other |
146 | | /// value. |
147 | | Status resolve_async_file_cache_write_max_pending_bytes(int64_t configured_bytes, |
148 | | int64_t be_mem_limit, |
149 | | size_t* resolved_bytes); |
150 | | |
151 | | /// Owns the bounded async-write queue and workers for one BlockFileCache (one cache disk). |
152 | | /// |
153 | | /// The referenced cache must outlive this manager. Shutdown stops new producers, waits registered |
154 | | /// producers, and drains all accepted tasks before worker resources are released. |
155 | | class AsyncCacheWriteManager { |
156 | | public: |
157 | | /// @param cache Non-owning target cache; it must outlive this manager. |
158 | | /// @param options Initial worker and pending-memory limits. |
159 | | AsyncCacheWriteManager(BlockFileCache* cache, AsyncCacheWriteManagerOptions options); |
160 | | ~AsyncCacheWriteManager(); |
161 | | |
162 | | /// Create the worker pool and schedule the configured long-running workers. Idempotent. |
163 | | Status start(); |
164 | | |
165 | | /// Admit `task` into the memory-bounded FIFO without waiting for disk I/O. Because all tasks |
166 | | /// have one fixed cache-block buffer capacity, a full queue displaces exactly one oldest queued |
167 | | /// task. Active tasks are never displaced. After a runtime limit decrease, submissions continue |
168 | | /// to replace the oldest queued task without increasing pending bytes, even while existing |
169 | | /// pending bytes exceed the new limit. This call can briefly wait for the queue mutex and |
170 | | /// finalizes a displaced task before returning. |
171 | | /// @return true if ownership was transferred to the queue; false when workers have not been |
172 | | /// started, during shutdown, or on backpressure. A rejected task's finalization callback is |
173 | | /// not invoked. |
174 | | bool try_submit(AsyncCacheWriteTask task); |
175 | | |
176 | | /// Allocate `size` payload bytes charged to the manager tracker and return them in `buffer`. |
177 | | Status allocate_tracked_buffer(size_t size, AsyncCacheWriteBufferPtr* buffer); |
178 | | |
179 | | /// Capture the disk-wide epoch and current live generation for `cache_hash`. |
180 | | AsyncCacheWriteEpoch current_write_epoch(const UInt128Wrapper& cache_hash); |
181 | | |
182 | | /// Return the current disk-wide epoch used by cache-clear operations. |
183 | 685 | uint64_t current_cache_epoch() const { return _cache_epoch.load(std::memory_order_acquire); } |
184 | | |
185 | | /// Test whether both levels of `epoch` still accept writes. |
186 | | bool is_current_write_epoch(const AsyncCacheWriteEpoch& epoch) const; |
187 | | |
188 | | /// Test the epoch and record one stale-drop metric when it is no longer current. |
189 | | bool check_write_epoch(const AsyncCacheWriteEpoch& epoch); |
190 | | |
191 | | /// Invalidate only queued/inflight work captured for `cache_hash` before this call. |
192 | | void invalidate_pending_writes(const UInt128Wrapper& cache_hash); |
193 | | |
194 | | /// Advance the disk-wide epoch so every previously captured write becomes stale. |
195 | | /// @return The newly active disk-wide epoch. |
196 | | uint64_t invalidate_all_pending_writes(); |
197 | | |
198 | | /// Return cache keys whose current valid generation is retained by at least one plan or task. |
199 | | /// Invalidated generations are excluded even while stale tasks finish releasing them. |
200 | | size_t active_write_epoch_key_count() const; |
201 | | |
202 | | /// Resize the number of active workers. A shrink waits only for retiring worker loops. |
203 | | /// @param worker_count Positive target worker count for this cache disk. |
204 | | Status resize_workers(size_t worker_count); |
205 | | |
206 | | /// Replace all mutable manager settings with one coherent snapshot. Configuration adapters |
207 | | /// call this method explicitly; the manager itself has no dependency on global config. |
208 | | /// @param options Complete validated settings, including the desired worker count. |
209 | | /// @return OK after the new snapshot is active; InvalidArgument for invalid limits, or a |
210 | | /// worker-resize error when the requested concurrency cannot be applied. |
211 | | Status update_options(const AsyncCacheWriteManagerOptions& options); |
212 | | |
213 | | /// Return the currently active settings as a value snapshot. |
214 | | AsyncCacheWriteManagerOptions options() const; |
215 | | |
216 | | /// Stop submissions, drain all accepted tasks, and join worker loops. Idempotent. |
217 | | void shutdown(); |
218 | | |
219 | | /// Return accepted tasks that have not yet completed finalization. |
220 | 87 | size_t pending_count() const { return _pending_count.load(std::memory_order_relaxed); } |
221 | | |
222 | | /// Return buffer-capacity bytes owned by queued and active tasks. |
223 | 16 | size_t pending_bytes() const { return _pending_bytes.load(std::memory_order_relaxed); } |
224 | | |
225 | | /// Return accepted tasks still waiting in the FIFO queue, excluding active workers. |
226 | | size_t queued_count() const; |
227 | | |
228 | | /// Return buffer-capacity bytes still waiting in the FIFO queue. |
229 | 11 | size_t queued_bytes() const { return _queued_bytes.load(std::memory_order_relaxed); } |
230 | | |
231 | | /// Return tasks currently owned by workers. |
232 | 8 | size_t active_task_count() const { return _active_task_count.load(std::memory_order_relaxed); } |
233 | | |
234 | | /// Return buffer-capacity bytes currently owned by workers. |
235 | 7 | size_t active_bytes() const { return _active_bytes.load(std::memory_order_relaxed); } |
236 | | |
237 | | /// Return worker loops that are currently alive. |
238 | 597 | size_t running_worker_count() const { |
239 | 597 | return _running_worker_count.load(std::memory_order_relaxed); |
240 | 597 | } |
241 | | |
242 | | /// Return bytes currently held by tracked task buffers. |
243 | 602 | int64_t buffer_memory_bytes() const { return _mem_tracker->consumption(); } |
244 | | |
245 | | /// Return tasks displaced by full-queue admission. |
246 | | uint64_t evicted_oldest_count() const; |
247 | | |
248 | | /// Return the current rolling P99 wait to acquire the FIFO mutex. |
249 | | int64_t queue_lock_wait_p99_us() const; |
250 | | |
251 | | /// Return the current rolling P99 FIFO mutex critical-section duration. |
252 | | int64_t queue_lock_hold_p99_us() const; |
253 | | |
254 | | private: |
255 | | class Worker; |
256 | | |
257 | | enum class TaskFinalizationReason : uint8_t { |
258 | | WORKER_FINISHED, |
259 | | EVICTED_OLDEST, |
260 | | }; |
261 | | |
262 | | /// Owns bvar registration and translates manager events into coherent metric updates. |
263 | | class Metrics; |
264 | | |
265 | | /// Resize the owned worker set while `_lifecycle_mutex` is held and `_worker_pool` exists. |
266 | | /// The pool's minimum thread count is kept equal to the long-running Worker task count so a |
267 | | /// task is never accepted without a backing OS thread. |
268 | | Status _resize_workers_locked(size_t worker_count); |
269 | | |
270 | | /// Stop and join workers in `[keep_worker_count, _workers.size())` while the lifecycle mutex is |
271 | | /// held. Stop requests are published under `_queue_mutex` before waking the worker loops. |
272 | | void _stop_workers_locked(size_t keep_worker_count); |
273 | | |
274 | | /// Process one task already moved from queued to active ownership. |
275 | | void _process_task(AsyncCacheWriteTask task); |
276 | | |
277 | | /// Move the oldest queued task to active ownership. |
278 | | bool _try_activate_task(AsyncCacheWriteTask* task); |
279 | | |
280 | | /// Revalidate epoch/cache state and persist the task's still-empty complete blocks. |
281 | | Status _persist_task(const AsyncCacheWriteTask& task); |
282 | | |
283 | | /// Move one active task to its terminal state outside the queue lock. |
284 | | void _complete_active_task(AsyncCacheWriteTask task); |
285 | | |
286 | | /// Record the terminal reason and let the task run its owner cleanup without the queue lock. |
287 | | void _complete_task(AsyncCacheWriteTask task, TaskFinalizationReason reason); |
288 | | |
289 | | BlockFileCache* _cache; |
290 | | atomic_shared_ptr<const AsyncCacheWriteManagerOptions> _options; |
291 | | std::deque<AsyncCacheWriteTask> _queue; |
292 | | mutable std::mutex _queue_mutex; |
293 | | std::condition_variable _queue_cv; |
294 | | // Learned from the first submission and protected by `_queue_mutex`. |
295 | | size_t _task_buffer_size {0}; |
296 | | // Pending covers all accepted tasks, while queued and active are its disjoint ownership states: |
297 | | // pending_count = queue.size() + active_task_count |
298 | | // pending_bytes = queued_bytes + active_bytes |
299 | | // Byte state is maintained directly and is authoritative for memory admission. Production |
300 | | // tasks currently have a fixed cache-block buffer capacity, including a partial EOF write, but |
301 | | // byte accounting deliberately does not depend on deriving bytes from task counts. |
302 | | std::atomic<size_t> _pending_count {0}; |
303 | | std::atomic<size_t> _pending_bytes {0}; |
304 | | std::atomic<size_t> _queued_bytes {0}; |
305 | | std::atomic<size_t> _active_task_count {0}; |
306 | | std::atomic<size_t> _active_bytes {0}; |
307 | | std::atomic<size_t> _running_worker_count {0}; |
308 | | std::atomic<size_t> _active_get_or_set_count {0}; |
309 | | std::atomic<size_t> _active_append_count {0}; |
310 | | std::atomic<size_t> _active_finalize_count {0}; |
311 | | std::atomic<bool> _accepting {true}; |
312 | | std::atomic<size_t> _active_submitters {0}; |
313 | | std::atomic<bool> _started {false}; |
314 | | std::atomic<uint64_t> _cache_epoch {1}; |
315 | | std::shared_ptr<AsyncCacheWriteEpochRegistry> _write_epoch_registry; |
316 | | |
317 | | std::shared_ptr<MemTrackerLimiter> _mem_tracker; |
318 | | std::unique_ptr<Metrics> _metrics; |
319 | | std::unique_ptr<ThreadPool> _worker_pool; |
320 | | std::atomic<size_t> _configured_worker_count {0}; |
321 | | // Serializes start, resize, and shutdown, including all changes to `_workers`. |
322 | | std::mutex _lifecycle_mutex; |
323 | | // Protected by `_lifecycle_mutex`. Worker stop state is owned by each Worker. |
324 | | std::vector<std::shared_ptr<Worker>> _workers; |
325 | | }; |
326 | | |
327 | | } // namespace doris::io |