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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use {
    crate::{
        lock::Lock, top_level_id::TopLevelId, AccessKind, GraphNode, ResourceKey, TransactionId,
    },
    std::{
        cmp::Ordering,
        collections::{hash_map::Entry, BinaryHeap, HashMap, HashSet},
    },
};

/// A directed acyclic graph where edges are only present between nodes if
/// that node is the next-highest priority node for a particular resource.
/// Resources can be either read or write locked with write locks being
/// exclusive.
/// `Transaction`s are inserted into the graph and then popped in time-priority order.
/// Between conflicting transactions, the first to be inserted will always have higher priority.
pub struct PrioGraph<
    Id: TransactionId,
    Rk: ResourceKey,
    Tl: TopLevelId<Id>,
    Pfn: Fn(&Id, &GraphNode<Id>) -> Tl,
> {
    /// Locked resources and which transaction holds them.
    locks: HashMap<Rk, Lock<Id>>,
    /// Graph edges and count of edges into each node. The count is used
    /// to detect joins.
    nodes: HashMap<Id, GraphNode<Id>>,
    /// Main queue - currently unblocked transactions.
    main_queue: BinaryHeap<Tl>,
    /// Priority modification for top-level transactions.
    top_level_prioritization_fn: Pfn,

    /// Used to generate the next distinct chain id.
    next_chain_id: u64,
    /// Map from chain id to joined chain.
    chain_to_joined: HashMap<u64, u64>,
}

impl<
        Id: TransactionId,
        Rk: ResourceKey,
        Tl: TopLevelId<Id>,
        Pfn: Fn(&Id, &GraphNode<Id>) -> Tl,
    > PrioGraph<Id, Rk, Tl, Pfn>
{
    /// Drains all transactions from the primary queue into a batch.
    /// Then, for each transaction in the batch, unblock transactions it was blocking.
    /// If any of those transactions are now unblocked, add them to the main queue.
    /// Repeat until the main queue is empty.
    pub fn natural_batches(
        iter: impl IntoIterator<Item = (Id, impl IntoIterator<Item = (Rk, AccessKind)>)>,
        top_level_prioritization_fn: Pfn,
    ) -> Vec<Vec<Id>> {
        // Insert all transactions into the graph.
        let mut graph = PrioGraph::new(top_level_prioritization_fn);
        for (id, tx) in iter.into_iter() {
            graph.insert_transaction(id, tx);
        }

        // Create natural batches by manually popping without unblocking at each level.
        let mut batches = vec![];

        while !graph.main_queue.is_empty() {
            let mut batch = Vec::new();
            while let Some(id) = graph.pop() {
                batch.push(id);
            }

            for id in &batch {
                graph.unblock(id);
            }

            batches.push(batch);
        }

        batches
    }

    /// Create a new priority graph.
    pub fn new(top_level_prioritization_fn: Pfn) -> Self {
        Self {
            locks: HashMap::new(),
            nodes: HashMap::new(),
            main_queue: BinaryHeap::new(),
            top_level_prioritization_fn,
            next_chain_id: 0,
            chain_to_joined: HashMap::new(),
        }
    }

    /// Insert a transaction into the graph with the given `Id`.
    /// `Transaction`s should be inserted in priority order.
    pub fn insert_transaction(&mut self, id: Id, tx: impl IntoIterator<Item = (Rk, AccessKind)>) {
        let mut node = GraphNode {
            active: true,
            edges: HashSet::new(),
            blocked_by_count: 0,
            chain_id: self.next_chain_id,
        };

        let mut joined_chains = HashSet::new();

        let mut block_tx = |blocking_id: Id| {
            // If the blocking transaction is the same as the current transaction, do nothing.
            // This indicates the transaction has multiple accesses to the same resource.
            if blocking_id == id {
                return;
            }

            let Some(blocking_tx_node) = self.nodes.get_mut(&blocking_id) else {
                panic!("blocking node must exist");
            };

            // If the node isn't active then we only do chain tracking.
            if blocking_tx_node.active {
                // Add edges to the current node.
                // If it is a unique edge, increment the blocked_by_count for the current node.
                if blocking_tx_node.edges.insert(id) {
                    node.blocked_by_count += 1;
                }
            }
            let blocking_chain_id = blocking_tx_node.chain_id;
            let blocking_chain_id = Self::trace_chain(&self.chain_to_joined, blocking_chain_id);

            match node.chain_id.cmp(&blocking_chain_id) {
                Ordering::Less => {
                    joined_chains.insert(blocking_chain_id);
                }
                Ordering::Equal => {}
                Ordering::Greater => {
                    joined_chains.insert(node.chain_id);
                    node.chain_id = blocking_chain_id;
                }
            }
        };

        for (resource_key, access_kind) in tx.into_iter() {
            match self.locks.entry(resource_key) {
                Entry::Vacant(entry) => {
                    entry.insert(match access_kind {
                        AccessKind::Read => Lock::Read(vec![id], None),
                        AccessKind::Write => Lock::Write(id),
                    });
                }
                Entry::Occupied(mut entry) => match access_kind {
                    AccessKind::Read => {
                        if let Some(blocking_tx) = entry.get_mut().add_read(id) {
                            block_tx(blocking_tx);
                        }
                    }
                    AccessKind::Write => {
                        if let Some(blocking_txs) = entry.get_mut().add_write(id) {
                            for blocking_tx in blocking_txs {
                                block_tx(blocking_tx);
                            }
                        }
                    }
                },
            }
        }

        // If this chain id is distinct, then increment the `next_chain_id`.
        if node.chain_id == self.next_chain_id {
            self.next_chain_id += 1;
        }

        // Add all joining chains into the map.
        for joining_chain in joined_chains {
            self.chain_to_joined.insert(joining_chain, node.chain_id);
        }

        self.nodes.insert(id, node);

        // If the node is not blocked, add it to the main queue.
        if self.nodes.get(&id).unwrap().blocked_by_count == 0 {
            self.main_queue.push(self.create_top_level_id(id));
        }
    }

    /// Returns true if the main queue is empty.
    pub fn is_empty(&self) -> bool {
        self.main_queue.is_empty()
    }

    /// Returns the minimum chain id for a given node id.
    ///
    /// Panics:
    ///     - Node does not exist.
    pub fn chain_id(&self, id: &Id) -> u64 {
        Self::trace_chain(&self.chain_to_joined, self.nodes.get(id).unwrap().chain_id)
    }

    /// Combination of `pop` and `unblock`.
    /// Returns None if the queue is empty.
    /// Returns the `Id` of the popped node, and the set of unblocked `Id`s.
    pub fn pop_and_unblock(&mut self) -> Option<(Id, HashSet<Id>)> {
        let id = self.pop()?;
        Some((id, self.unblock(&id)))
    }

    /// Pop the highest priority node id from the main queue.
    /// Returns None if the queue is empty.
    pub fn pop(&mut self) -> Option<Id> {
        self.main_queue.pop().map(|top_level_id| top_level_id.id())
    }

    /// This will unblock transactions that were blocked by this transaction.
    /// Returns the set of `Id`s that were unblocked.
    ///
    /// Panics:
    ///     - Node does not exist.
    ///     - If the node.blocked_by_count != 0
    pub fn unblock(&mut self, id: &Id) -> HashSet<Id> {
        // If the node is already removed, do nothing.
        let Some(node) = self.nodes.get_mut(id) else {
            panic!("node must exist");
        };
        assert_eq!(node.blocked_by_count, 0, "node must be unblocked");

        node.active = false;
        let edges = core::mem::take(&mut node.edges);

        // Unblock transactions that were blocked by this node.
        for blocked_tx in edges.iter() {
            let blocked_tx_node = self
                .nodes
                .get_mut(blocked_tx)
                .expect("blocked_tx must exist");
            blocked_tx_node.blocked_by_count -= 1;

            if blocked_tx_node.blocked_by_count == 0 {
                self.main_queue.push(self.create_top_level_id(*blocked_tx));
            }
        }

        edges
    }

    /// Returns whether the given `Id` is at the top level of the graph, i.e. not blocked.
    /// If the node does not exist, returns false.
    pub fn is_blocked(&self, id: Id) -> bool {
        self.nodes
            .get(&id)
            .map(|node| node.active && node.blocked_by_count != 0)
            .unwrap_or_default()
    }

    fn create_top_level_id(&self, id: Id) -> Tl {
        (self.top_level_prioritization_fn)(&id, self.nodes.get(&id).unwrap())
    }

    fn trace_chain(chain_to_joined: &HashMap<u64, u64>, mut chain_id: u64) -> u64 {
        while let Some(joined_chain) = chain_to_joined.get(&chain_id) {
            chain_id = *joined_chain;
        }
        chain_id
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    pub type TxId = u64;

    pub type Account = u64;

    pub struct Tx {
        read_locked_resources: Vec<Account>,
        write_locked_resources: Vec<Account>,
    }

    impl Tx {
        fn resources(&self) -> impl Iterator<Item = (Account, AccessKind)> + '_ {
            let write_locked_resources = self
                .write_locked_resources
                .iter()
                .cloned()
                .map(|rk| (rk, AccessKind::Write));
            let read_locked_resources = self
                .read_locked_resources
                .iter()
                .cloned()
                .map(|rk| (rk, AccessKind::Read));

            write_locked_resources.chain(read_locked_resources)
        }
    }

    // Take in groups of transactions, where each group is a set of transaction ids,
    // and the read and write locked resources for each transaction.
    fn setup_test(
        transaction_groups: impl IntoIterator<Item = (Vec<TxId>, Vec<Account>, Vec<Account>)>,
    ) -> (HashMap<TxId, Tx>, Vec<TxId>) {
        let mut transaction_lookup_table = HashMap::new();
        let mut priority_ordered_ids = vec![];
        for (ids, read_accounts, write_accounts) in transaction_groups {
            for id in &ids {
                priority_ordered_ids.push(*id);
                transaction_lookup_table.insert(
                    *id,
                    Tx {
                        read_locked_resources: read_accounts.clone(),
                        write_locked_resources: write_accounts.clone(),
                    },
                );
            }
        }

        // Sort in reverse priority order - highest priority first.
        priority_ordered_ids.sort_by(|a, b| b.cmp(a));

        (transaction_lookup_table, priority_ordered_ids)
    }

    fn create_lookup_iterator<'a>(
        transaction_lookup_table: &'a HashMap<TxId, Tx>,
        reverse_priority_order_ids: &'a [TxId],
    ) -> impl Iterator<Item = (TxId, impl IntoIterator<Item = (Account, AccessKind)> + 'a)> + 'a
    {
        reverse_priority_order_ids.iter().map(|id| {
            (
                *id,
                transaction_lookup_table
                    .get(id)
                    .expect("id must exist")
                    .resources(),
            )
        })
    }

    impl TopLevelId<TxId> for TxId {
        fn id(&self) -> TxId {
            *self
        }
    }

    fn test_top_level_priority_fn(id: &TxId, _node: &GraphNode<TxId>) -> TxId {
        *id
    }

    #[test]
    fn test_simple_queue() {
        // Setup:
        // 3 -> 2 -> 1
        // batches: [3], [2], [1]
        let (transaction_lookup_table, transaction_queue) =
            setup_test([(vec![3, 2, 1], vec![], vec![0])]);
        let batches = PrioGraph::natural_batches(
            create_lookup_iterator(&transaction_lookup_table, &transaction_queue),
            test_top_level_priority_fn,
        );
        assert_eq!(batches, [[3], [2], [1]]);
    }

    #[test]
    fn test_multiple_separate_queues() {
        // Setup:
        // 8 -> 4 -> 2 -> 1
        // 7 -> 5 -> 3
        // 6
        // batches: [8, 7, 6], [4, 5], [2, 3], [1]
        let (transaction_lookup_table, transaction_queue) = setup_test([
            (vec![8, 4, 2, 1], vec![], vec![0]),
            (vec![7, 5, 3], vec![], vec![1]),
            (vec![6], vec![], vec![2]),
        ]);
        let batches = PrioGraph::natural_batches(
            create_lookup_iterator(&transaction_lookup_table, &transaction_queue),
            test_top_level_priority_fn,
        );
        assert_eq!(batches, [vec![8, 7, 6], vec![5, 4], vec![3, 2], vec![1]]);
    }

    #[test]
    fn test_joining_queues() {
        // Setup:
        // 6 -> 3
        //        \
        //          -> 2 -> 1
        //        /
        // 5 -> 4
        // batches: [6, 5], [3, 4], [2], [1]
        let (transaction_lookup_table, transaction_queue) = setup_test([
            (vec![6, 3], vec![], vec![0]),
            (vec![5, 4], vec![], vec![1]),
            (vec![2, 1], vec![], vec![0, 1]),
        ]);
        let batches = PrioGraph::natural_batches(
            create_lookup_iterator(&transaction_lookup_table, &transaction_queue),
            test_top_level_priority_fn,
        );
        assert_eq!(batches, [vec![6, 5], vec![4, 3], vec![2], vec![1]]);
    }

    #[test]
    fn test_forking_queues() {
        // Setup:
        //         -> 2 -> 1
        //        /
        // 6 -> 5
        //        \
        //         -> 4 -> 3
        // batches: [6], [5], [4, 2], [3, 1]
        let (transaction_lookup_table, transaction_queue) = setup_test([
            (vec![6, 5], vec![], vec![0, 1]),
            (vec![2, 1], vec![], vec![0]),
            (vec![4, 3], vec![], vec![1]),
        ]);
        let batches = PrioGraph::natural_batches(
            create_lookup_iterator(&transaction_lookup_table, &transaction_queue),
            test_top_level_priority_fn,
        );
        assert_eq!(batches, [vec![6], vec![5], vec![4, 2], vec![3, 1]]);
    }

    #[test]
    fn test_forking_and_joining() {
        // Setup:
        //         -> 5 ----          -> 2 -> 1
        //        /          \      /
        // 9 -> 8              -> 4
        //        \          /      \
        //         -> 7 -> 6          -> 3
        // batches: [9], [8], [7, 5], [6], [4], [3, 2], [1]
        let (transaction_lookup_table, transaction_queue) = setup_test([
            (vec![5, 2, 1], vec![], vec![0]),
            (vec![9, 8, 4], vec![], vec![0, 1]),
            (vec![7, 6, 3], vec![], vec![1]),
        ]);
        let batches = PrioGraph::natural_batches(
            create_lookup_iterator(&transaction_lookup_table, &transaction_queue),
            test_top_level_priority_fn,
        );
        assert_eq!(
            batches,
            [
                vec![9],
                vec![8],
                vec![7, 5],
                vec![6],
                vec![4],
                vec![3, 2],
                vec![1]
            ]
        );
    }

    #[test]
    fn test_shared_read_account_no_conflicts() {
        // Setup:
        //   - all transactions read-lock account 0.
        // 8 -> 6 -> 4 -> 2
        // 7 -> 5 -> 3 -> 1
        // Batches: [8, 7], [6, 5], [4, 3], [2, 1]
        let (transaction_lookup_table, transaction_queue) = setup_test([
            (vec![8, 6, 4, 2], vec![0], vec![1]),
            (vec![7, 5, 3, 1], vec![0], vec![2]),
        ]);
        let batches = PrioGraph::natural_batches(
            create_lookup_iterator(&transaction_lookup_table, &transaction_queue),
            test_top_level_priority_fn,
        );
        assert_eq!(batches, [vec![8, 7], vec![6, 5], vec![4, 3], vec![2, 1]]);
    }

    #[test]
    fn test_self_conflicting() {
        // Setup:
        //   - transaction read and write locks account 0.
        // 1
        // Batches: [1]
        let (transaction_lookup_table, transaction_queue) =
            setup_test([(vec![1], vec![0], vec![0])]);
        let batches = PrioGraph::natural_batches(
            create_lookup_iterator(&transaction_lookup_table, &transaction_queue),
            test_top_level_priority_fn,
        );
        assert_eq!(batches, [vec![1]]);
    }

    #[test]
    fn test_self_conflicting_write_priority() {
        // Setup:
        //   - transaction 2 read and write locks account 0.
        // 2 --> 1
        // Batches: [2, 1]
        let (transaction_lookup_table, transaction_queue) =
            setup_test([(vec![2], vec![0], vec![0]), (vec![1], vec![0], vec![])]);
        let batches = PrioGraph::natural_batches(
            create_lookup_iterator(&transaction_lookup_table, &transaction_queue),
            test_top_level_priority_fn,
        );
        assert_eq!(batches, [vec![2], vec![1]]);
    }

    #[test]
    fn test_write_read_read_conflict() {
        // Setup:
        //  - W --> R
        //      \
        //       -> R
        // - all transactions using same account 0.
        // Batches: [3], [2, 1]
        let (transaction_lookup_table, transaction_queue) =
            setup_test([(vec![3], vec![], vec![0]), (vec![2, 1], vec![0], vec![])]);
        let batches = PrioGraph::natural_batches(
            create_lookup_iterator(&transaction_lookup_table, &transaction_queue),
            test_top_level_priority_fn,
        );
        assert_eq!(batches, [vec![3], vec![2, 1]]);
    }
}