active.rs 8.28 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
27
28
29
30
31
32
33
34
35
36
37
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
95
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Active pool for managing blocks that are currently in use (have strong references).
//!
//! This pool provides a layer of abstraction over the BlockRegistry for finding
//! active blocks. Active blocks are those that have been registered and are
//! currently being used, as opposed to inactive blocks which are available
//! for reuse.

use std::sync::Arc;

use super::{BlockMetadata, RegisteredBlock, SequenceHash};
use crate::blocks::RegisteredReturnFn;
use crate::registry::BlockRegistry;

/// Pool for managing active (in-use) blocks.
///
/// This is a simple wrapper around BlockRegistry that encapsulates the logic
/// for finding blocks that are currently active (have strong references).
pub(crate) struct ActivePool<T: BlockMetadata> {
    block_registry: BlockRegistry,
    return_fn: RegisteredReturnFn<T>,
}

impl<T: BlockMetadata> ActivePool<T> {
    /// Create a new ActivePool with the given registry and return function.
    pub(crate) fn new(block_registry: BlockRegistry, return_fn: RegisteredReturnFn<T>) -> Self {
        Self {
            block_registry,
            return_fn,
        }
    }

    /// Find multiple blocks by sequence hashes, stopping on first miss.
    ///
    /// This searches for active blocks in the registry and returns them as
    /// RegisteredBlock guards. If any hash is not found or the block cannot
    /// be retrieved, the search stops and returns only the blocks found so far.
    #[inline]
    pub(crate) fn find_matches(
        &self,
        hashes: &[SequenceHash],
        touch: bool,
    ) -> Vec<Arc<dyn RegisteredBlock<T>>> {
        let mut matches = Vec::with_capacity(hashes.len());

        for hash in hashes {
            if let Some(handle) = self.block_registry.match_sequence_hash(*hash, touch) {
                if let Some(block) = handle.try_get_block::<T>(self.return_fn.clone()) {
                    matches.push(block);
                } else {
                    break; // Stop on first miss
                }
            } else {
                break; // Stop on first miss
            }
        }

        matches
    }

    /// Scan for blocks in the active pool (doesn't stop on miss).
    ///
    /// Unlike `find_matches`, this continues scanning even when a hash is not found.
    /// Returns all found blocks with their corresponding sequence hashes.
    #[inline]
    pub(crate) fn scan_matches(
        &self,
        hashes: &[SequenceHash],
    ) -> Vec<(SequenceHash, Arc<dyn RegisteredBlock<T>>)> {
        hashes
            .iter()
            .filter_map(|hash| {
                self.block_registry
                    .match_sequence_hash(*hash, false)
                    .and_then(|handle| {
                        handle
                            .try_get_block::<T>(self.return_fn.clone())
                            .map(|block| (*hash, block))
                    })
            })
            .collect()
    }

    // /// Find a single block by sequence hash.
    // ///
    // /// Returns the block if found and active, None otherwise.
    // #[inline]
    // pub(crate) fn find_match(&self, seq_hash: SequenceHash) -> Option<Arc<dyn RegisteredBlock<T>>> {
    //     self.block_registry
    //         .match_sequence_hash(seq_hash, true)
    //         .and_then(|handle| handle.try_get_block::<T>(self.return_fn.clone()))
    // }

    // /// Check if a block with the given sequence hash is currently active.
    // pub(crate) fn has_block(&self, seq_hash: SequenceHash) -> bool {
    //     self.find_match(seq_hash).is_some()
    // }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::blocks::{Block, PrimaryBlock, state::Reset};
    use crate::pools::backends::{FifoReusePolicy, HashMapBackend};
    use crate::pools::inactive::InactivePool;
    use crate::pools::reset::ResetPool;
    use crate::testing::{TestMeta, create_staged_block, tokens_for_id};

    fn create_test_setup() -> (
        ActivePool<TestMeta>,
        InactivePool<TestMeta>,
        BlockRegistry,
        ResetPool<TestMeta>,
    ) {
        let registry = BlockRegistry::new();

        let reset_blocks: Vec<Block<TestMeta, Reset>> =
            (0..10_usize).map(|i| Block::new(i, 4)).collect();
        let reset_pool = ResetPool::new(reset_blocks, 4, None);

        let reuse_policy = Box::new(FifoReusePolicy::new());
        let backend = Box::new(HashMapBackend::new(reuse_policy));
        let inactive_pool = InactivePool::new(backend, &reset_pool, None);

        let active_pool = ActivePool::new(registry.clone(), inactive_pool.return_fn());

        (active_pool, inactive_pool, registry, reset_pool)
    }

    /// Register a staged block and hold a strong reference to make it "active".
    fn make_active_block(
        registry: &BlockRegistry,
        return_fn: &RegisteredReturnFn<TestMeta>,
        id: usize,
        tokens: &[u32],
    ) -> (Arc<PrimaryBlock<TestMeta>>, SequenceHash) {
        let staged = create_staged_block::<TestMeta>(id, tokens);
        let seq_hash = staged.sequence_hash();
        let handle = registry.register_sequence_hash(seq_hash);
        let registered = staged.register_with_handle(handle);
        let primary = PrimaryBlock::new_attached(Arc::new(registered), return_fn.clone());
        (primary, seq_hash)
    }

    #[test]
    fn test_find_matches() {
        let (active_pool, inactive_pool, registry, _reset_pool) = create_test_setup();
        let return_fn = inactive_pool.return_fn();

        let (_hold1, hash1) = make_active_block(&registry, &return_fn, 1, &tokens_for_id(1));
        let (_hold2, hash2) = make_active_block(&registry, &return_fn, 2, &tokens_for_id(2));
        let (_hold3, hash3) = make_active_block(&registry, &return_fn, 3, &tokens_for_id(3));

        let found = active_pool.find_matches(&[hash1, hash2, hash3], true);
        assert_eq!(found.len(), 3);
        assert_eq!(found[0].block_id(), 1);
        assert_eq!(found[1].block_id(), 2);
        assert_eq!(found[2].block_id(), 3);
    }

    #[test]
    fn test_find_matches_stops_on_miss() {
        let (active_pool, inactive_pool, registry, _reset_pool) = create_test_setup();
        let return_fn = inactive_pool.return_fn();

        let (_hold1, hash1) = make_active_block(&registry, &return_fn, 1, &tokens_for_id(1));
        let (_hold3, hash3) = make_active_block(&registry, &return_fn, 3, &tokens_for_id(3));

        // Create a hash that's not in the registry
        let missing_hash = {
            let staged = create_staged_block::<TestMeta>(999, &[9999, 9998, 9997, 9996]);
            staged.sequence_hash()
        };

        let found = active_pool.find_matches(&[hash1, missing_hash, hash3], true);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].block_id(), 1);
    }

    #[test]
    fn test_scan_matches() {
        let (active_pool, inactive_pool, registry, _reset_pool) = create_test_setup();
        let return_fn = inactive_pool.return_fn();

        let (_hold1, hash1) = make_active_block(&registry, &return_fn, 1, &tokens_for_id(1));
        let (_hold3, hash3) = make_active_block(&registry, &return_fn, 3, &tokens_for_id(3));

        let missing_hash = {
            let staged = create_staged_block::<TestMeta>(999, &[9999, 9998, 9997, 9996]);
            staged.sequence_hash()
        };

        // scan_matches doesn't stop on miss — should find both 1 and 3
        let found = active_pool.scan_matches(&[hash1, missing_hash, hash3]);
        assert_eq!(found.len(), 2);
        assert_eq!(found[0].0, hash1);
        assert_eq!(found[0].1.block_id(), 1);
        assert_eq!(found[1].0, hash3);
        assert_eq!(found[1].1.block_id(), 3);
    }

    #[test]
    fn test_find_matches_empty() {
        let (active_pool, _inactive_pool, _registry, _reset_pool) = create_test_setup();

        let found = active_pool.find_matches(&[], true);
        assert!(found.is_empty());
    }

    #[test]
    fn test_find_matches_no_active_blocks() {
        let (active_pool, _inactive_pool, _registry, _reset_pool) = create_test_setup();

        let missing_hash = {
            let staged = create_staged_block::<TestMeta>(999, &[9999, 9998, 9997, 9996]);
            staged.sequence_hash()
        };

        let found = active_pool.find_matches(&[missing_hash], true);
        assert!(found.is_empty());
    }
}