state.rs 13.5 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::block_manager::{
    block::{registry::BlockRegistationError, BlockState, PrivateBlockExt},
    events::Publisher,
};

use super::*;

impl<S: Storage, M: BlockMetadata> State<S, M> {
    fn new(
        event_manager: Arc<dyn EventManager>,
        return_tx: tokio::sync::mpsc::UnboundedSender<Block<S, M>>,
27
28
        global_registry: GlobalRegistry,
        async_runtime: Handle,
29
        metrics: Arc<PoolMetrics>,
Ryan Olson's avatar
Ryan Olson committed
30
31
32
33
    ) -> Self {
        Self {
            active: ActiveBlockPool::new(),
            inactive: InactiveBlockPool::new(),
34
            registry: BlockRegistry::new(event_manager.clone(), global_registry, async_runtime),
Ryan Olson's avatar
Ryan Olson committed
35
36
            return_tx,
            event_manager,
37
            metrics,
Ryan Olson's avatar
Ryan Olson committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
        }
    }

    async fn handle_priority_request(
        &mut self,
        req: PriorityRequest<S, M>,
        return_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Block<S, M>>,
    ) {
        match req {
            PriorityRequest::AllocateBlocks(req) => {
                let (count, resp_tx) = req.dissolve();
                let blocks = self.allocate_blocks(count);
                if resp_tx.send(blocks).is_err() {
                    tracing::error!("failed to send response to allocate blocks");
                }
            }
            PriorityRequest::RegisterBlocks(req) => {
                let (blocks, resp_tx) = req.dissolve();
                let immutable_blocks = self.register_blocks(blocks, return_rx).await;
                if resp_tx.send(immutable_blocks).is_err() {
                    tracing::error!("failed to send response to register blocks");
                }
            }
            PriorityRequest::MatchSequenceHashes(req) => {
                let (sequence_hashes, resp_tx) = req.dissolve();
                let immutable_blocks = self.match_sequence_hashes(sequence_hashes, return_rx).await;
                if resp_tx.send(immutable_blocks).is_err() {
                    tracing::error!("failed to send response to match sequence hashes");
                }
            }
        }
    }

    fn handle_control_request(&mut self, req: ControlRequest<S, M>) {
        match req {
            ControlRequest::AddBlocks(blocks) => {
                let (blocks, resp_rx) = blocks.dissolve();
                self.inactive.add_blocks(blocks);
                if resp_rx.send(()).is_err() {
                    tracing::error!("failed to send response to add blocks");
                }
            }
        }
    }

    fn handle_return_block(&mut self, block: Block<S, M>) {
        self.return_block(block);
    }

    /// We have a strong guarantee that the block will be returned to the pool in the near future.
    /// The caller must take ownership of the block
    async fn wait_for_returned_block(
        &mut self,
        sequence_hash: SequenceHash,
        return_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Block<S, M>>,
    ) -> Block<S, M> {
        while let Some(block) = return_rx.recv().await {
95
            if matches!(block.state(), BlockState::Registered(handle, _) if handle.sequence_hash() == sequence_hash)
Ryan Olson's avatar
Ryan Olson committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
            {
                return block;
            }
            self.handle_return_block(block);
        }

        unreachable!("this should be unreachable");
    }

    pub fn allocate_blocks(
        &mut self,
        count: usize,
    ) -> Result<Vec<MutableBlock<S, M>>, BlockPoolError> {
        let available_blocks = self.inactive.available_blocks() as usize;

        if available_blocks < count {
            tracing::debug!(
                "not enough blocks available, requested: {}, available: {}",
                count,
                available_blocks
            );
            return Err(BlockPoolError::NotEnoughBlocksAvailable(
                count,
                available_blocks,
            ));
        }

        let mut blocks = Vec::with_capacity(count);

        for _ in 0..count {
            if let Some(block) = self.inactive.acquire_free_block() {
                blocks.push(MutableBlock::new(block, self.return_tx.clone()));
            }
        }

131
132
133
134
        self.metrics
            .counter("blocks_allocated")
            .inc_by(count as u64);

Ryan Olson's avatar
Ryan Olson committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
        Ok(blocks)
    }

    pub async fn register_blocks(
        &mut self,
        blocks: Vec<MutableBlock<S, M>>,
        return_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Block<S, M>>,
    ) -> Result<Vec<ImmutableBlock<S, M>>, BlockPoolError> {
        let expected_len = blocks.len();
        let mut immutable_blocks = Vec::new();

        // raii object that will collect all the publish handles and publish them when the object is dropped
        let mut publish_handles = self.publisher();

        for mut block in blocks.into_iter() {
            let sequence_hash = block.sequence_hash()?;

            // If the block is already registered, acquire a clone of the immutable block
            if let Some(immutable) = self.active.match_sequence_hash(sequence_hash) {
                immutable_blocks.push(immutable);
                continue;
            }

158
159
            let mut offload = true;

Ryan Olson's avatar
Ryan Olson committed
160
161
            let mutable = if let Some(raw_block) = self.inactive.match_sequence_hash(sequence_hash)
            {
162
                assert!(matches!(raw_block.state(), BlockState::Registered(_, _)));
Ryan Olson's avatar
Ryan Olson committed
163
164
165
166
167
168
169
170
171
                MutableBlock::new(raw_block, self.return_tx.clone())
            } else {
                // Attempt to register the block
                // On the very rare chance that the block is registered, but in the process of being returned,
                // we will wait for it to be returned and then register it.
                let result = block.register(&mut self.registry);

                match result {
                    Ok(handle) => {
172
173
174
175
                        // Only create our publish handle if this block is new, and not transfered.
                        if let Some(handle) = handle {
                            publish_handles.take_handle(handle);
                        }
Ryan Olson's avatar
Ryan Olson committed
176
177
178
179
                        block
                    }
                    Err(BlockRegistationError::BlockAlreadyRegistered(_)) => {
                        // Block is already registered, wait for it to be returned
180
                        offload = false;
Ryan Olson's avatar
Ryan Olson committed
181
182
183
184
185
186
187
188
189
190
191
192
                        let raw_block =
                            self.wait_for_returned_block(sequence_hash, return_rx).await;
                        MutableBlock::new(raw_block, self.return_tx.clone())
                    }
                    Err(e) => {
                        return Err(BlockPoolError::FailedToRegisterBlock(e.to_string()));
                    }
                }
            };

            let immutable = self.active.register(mutable)?;

193
            if offload {
194
195
196
                if let Some(priority) = immutable.metadata().offload_priority() {
                    immutable.enqueue_offload(priority).await.unwrap();
                }
197
198
            }

Ryan Olson's avatar
Ryan Olson committed
199
200
201
202
203
            immutable_blocks.push(immutable);
        }

        assert_eq!(immutable_blocks.len(), expected_len);

204
205
206
207
        self.metrics
            .counter("blocks_registered")
            .inc_by(immutable_blocks.len() as u64);

Ryan Olson's avatar
Ryan Olson committed
208
209
210
211
212
213
214
215
216
        Ok(immutable_blocks)
    }

    async fn match_sequence_hashes(
        &mut self,
        sequence_hashes: Vec<SequenceHash>,
        return_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Block<S, M>>,
    ) -> Vec<ImmutableBlock<S, M>> {
        let mut immutable_blocks = Vec::new();
217
218
219
        for sequence_hash in &sequence_hashes {
            if !self.registry.is_registered(*sequence_hash) {
                break;
Ryan Olson's avatar
Ryan Olson committed
220
221
222
223
224
225
226
            }

            // the block is registered, so to get it from either the:
            // 1. active pool
            // 2. inactive pool
            // 3. return channel

227
            if let Some(immutable) = self.active.match_sequence_hash(*sequence_hash) {
Ryan Olson's avatar
Ryan Olson committed
228
229
230
231
232
                immutable_blocks.push(immutable);
                continue;
            }

            let raw_block =
233
                if let Some(raw_block) = self.inactive.match_sequence_hash(*sequence_hash) {
Ryan Olson's avatar
Ryan Olson committed
234
235
                    raw_block
                } else {
236
237
                    self.wait_for_returned_block(*sequence_hash, return_rx)
                        .await
Ryan Olson's avatar
Ryan Olson committed
238
239
240
                };

            // this assert allows us to skip the error checking on the active pool registration step
241
            assert!(matches!(raw_block.state(), BlockState::Registered(_, _)));
Ryan Olson's avatar
Ryan Olson committed
242
243
244
245
246
247
248
249
250
251
252

            let mutable = MutableBlock::new(raw_block, self.return_tx.clone());

            let immutable = self
                .active
                .register(mutable)
                .expect("unable to register block; should ever happen");

            immutable_blocks.push(immutable);
        }

253
254
255
256
257
258
259
        self.metrics
            .counter("cache_hits")
            .inc_by(immutable_blocks.len() as u64);
        self.metrics
            .counter("cache_misses")
            .inc_by(sequence_hashes.len() as u64 - immutable_blocks.len() as u64);

Ryan Olson's avatar
Ryan Olson committed
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
        immutable_blocks
    }

    /// Returns a block to the inactive pool
    pub fn return_block(&mut self, mut block: Block<S, M>) {
        self.active.remove(&mut block);
        self.inactive.return_block(block);
    }

    fn publisher(&self) -> Publisher {
        Publisher::new(self.event_manager.clone())
    }
}

impl<S: Storage, M: BlockMetadata> ProgressEngine<S, M> {
275
    #[allow(clippy::too_many_arguments)]
Ryan Olson's avatar
Ryan Olson committed
276
277
278
279
280
281
    pub fn new(
        event_manager: Arc<dyn EventManager>,
        priority_rx: tokio::sync::mpsc::UnboundedReceiver<PriorityRequest<S, M>>,
        ctrl_rx: tokio::sync::mpsc::UnboundedReceiver<ControlRequest<S, M>>,
        cancel_token: CancellationToken,
        blocks: Vec<Block<S, M>>,
282
283
        global_registry: GlobalRegistry,
        async_runtime: Handle,
284
        metrics: Arc<PoolMetrics>,
Ryan Olson's avatar
Ryan Olson committed
285
286
    ) -> Self {
        let (return_tx, return_rx) = tokio::sync::mpsc::unbounded_channel();
287
288
289
290
291
292
293
        let mut state = State::<S, M>::new(
            event_manager,
            return_tx,
            global_registry,
            async_runtime,
            metrics.clone(),
        );
Ryan Olson's avatar
Ryan Olson committed
294
295
296
297
298
299
300
301
302
303

        tracing::debug!(count = blocks.len(), "adding blocks to inactive pool");
        state.inactive.add_blocks(blocks);

        Self {
            priority_rx,
            ctrl_rx,
            cancel_token,
            state,
            return_rx,
304
            metrics,
Ryan Olson's avatar
Ryan Olson committed
305
306
307
308
309
310
311
312
        }
    }

    pub async fn step(&mut self) -> bool {
        tokio::select! {
            biased;

            Some(priority_req) = self.priority_rx.recv(), if !self.priority_rx.is_closed() => {
313
                self.metrics.gauge("priority_request_queue_size").set(self.priority_rx.len() as i64);
Ryan Olson's avatar
Ryan Olson committed
314
315
316
317
                self.state.handle_priority_request(priority_req, &mut self.return_rx).await;
            }

            Some(req) = self.ctrl_rx.recv(), if !self.ctrl_rx.is_closed() => {
318
                self.metrics.gauge("control_request_queue_size").set(self.ctrl_rx.len() as i64);
Ryan Olson's avatar
Ryan Olson committed
319
320
321
322
                self.state.handle_control_request(req);
            }

            Some(block) = self.return_rx.recv() => {
323
                self.metrics.gauge("return_block_queue_size").set(self.return_rx.len() as i64);
Ryan Olson's avatar
Ryan Olson committed
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
                self.state.handle_return_block(block);
            }

            _ = self.cancel_token.cancelled() => {
                return false;
            }
        }

        true
    }
}
// pub(crate) async fn progress_engine<S: Storage, M: BlockMetadata>(
//     event_manager: Arc<dyn EventManager>,
//     mut priority_rx: tokio::sync::mpsc::UnboundedReceiver<PriorityRequest<S, M>>,
//     mut ctrl_rx: tokio::sync::mpsc::UnboundedReceiver<ControlRequest<S, M>>,
//     cancel_token: CancellationToken,
// ) {
//     let (return_tx, mut return_rx) = tokio::sync::mpsc::unbounded_channel();
//     let mut state = State::<S, M>::new(event_manager, return_tx);

//     loop {
//         tokio::select! {
//             biased;

//             Some(priority_req) = priority_rx.recv(), if !priority_rx.is_closed() => {
//                 state.handle_priority_request(priority_req, &mut return_rx).await;
//             }

//             Some(req) = ctrl_rx.recv(), if !ctrl_rx.is_closed() => {
//                 state.handle_control_request(req);
//             }

//             Some(block) = return_rx.recv() => {
//                 state.handle_return_block(block);
//             }

//             _ = cancel_token.cancelled() => {
//                 break;
//             }
//         }
//     }
// }

// pub(crate) async fn progress_engine_v2<S: Storage, M: BlockMetadata>(
//     event_manager: Arc<dyn EventManager>,
//     priority_rx: tokio::sync::mpsc::UnboundedReceiver<PriorityRequest<S, M>>,
//     ctrl_rx: tokio::sync::mpsc::UnboundedReceiver<ControlRequest<S, M>>,
//     cancel_token: CancellationToken,
// ) {
//     let mut progress_engine =
//         ProgressEngine::<S, M>::new(event_manager, priority_rx, ctrl_rx, cancel_token);

//     while progress_engine.step().await {
//         tracing::trace!("progress engine step");
//     }
// }