queue.rs 28.5 KB
Newer Older
jixx's avatar
jixx committed
1
2
3
4
use crate::block_allocator::{BlockAllocation, BlockAllocator};
use crate::client;
use crate::client::{
    Batch, GrammarType, NextTokenChooserParameters, Request, StoppingCriteriaParameters,
jixx's avatar
init  
jixx committed
5
6
};
use nohash_hasher::{BuildNoHashHasher, IntMap};
jixx's avatar
jixx committed
7
use std::cmp::max;
jixx's avatar
init  
jixx committed
8
use std::collections::VecDeque;
jixx's avatar
jixx committed
9
10
11
12
13
use text_generation_router::infer::InferError;
use text_generation_router::infer::InferStreamResponse;
use text_generation_router::validation::{
    Chunk, ChunksToString, ValidGenerateRequest, ValidGrammar, ValidParameters,
    ValidStoppingParameters,
jixx's avatar
init  
jixx committed
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
};
use tokio::sync::{mpsc, oneshot};
use tokio::time::Instant;
use tracing::{info_span, instrument, Instrument, Span};

/// Queue entry
#[derive(Debug)]
pub(crate) struct Entry {
    /// Request
    pub request: ValidGenerateRequest,
    /// Response sender to communicate between the Infer struct and the batching_task
    pub response_tx: mpsc::UnboundedSender<Result<InferStreamResponse, InferError>>,
    /// Span that will live as long as entry
    pub span: Span,
    /// Temporary span used as a guard when logging inference, wait times...
    pub temp_span: Option<Span>,
    /// Instant when this entry was queued
    pub queue_time: Instant,
    /// Instant when this entry was added to a batch
    pub batch_time: Option<Instant>,
    /// Block Allocation
    pub block_allocation: Option<BlockAllocation>,
}

/// Request Queue
#[derive(Debug, Clone)]
pub(crate) struct Queue {
    /// Channel to communicate with the background queue task
    queue_sender: mpsc::UnboundedSender<QueueCommand>,
}

impl Queue {
    pub(crate) fn new(
        requires_padding: bool,
        block_size: u32,
jixx's avatar
jixx committed
49
        prefix_caching: bool,
jixx's avatar
init  
jixx committed
50
51
52
        window_size: Option<u32>,
        speculate: u32,
        max_batch_total_tokens: u32,
jixx's avatar
jixx committed
53
        support_chunking: bool,
jixx's avatar
init  
jixx committed
54
55
56
57
58
59
60
61
    ) -> Self {
        // Create channel
        let (queue_sender, queue_receiver) = mpsc::unbounded_channel();

        // Launch background queue task
        tokio::spawn(queue_task(
            requires_padding,
            block_size,
jixx's avatar
jixx committed
62
            prefix_caching,
jixx's avatar
init  
jixx committed
63
64
65
            window_size,
            speculate,
            max_batch_total_tokens,
jixx's avatar
jixx committed
66
            support_chunking,
jixx's avatar
init  
jixx committed
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
            queue_receiver,
        ));

        Self { queue_sender }
    }

    /// Append an entry to the queue
    #[instrument(skip_all)]
    pub(crate) fn append(&self, entry: Entry) {
        // Send append command to the background task managing the state
        // Unwrap is safe here
        self.queue_sender
            .send(QueueCommand::Append(Box::new(entry), Span::current()))
            .unwrap();
    }

    // Get the next batch
    #[instrument(skip(self))]
    pub(crate) async fn next_batch(
        &self,
        min_size: Option<usize>,
        max_size: Option<usize>,
        prefill_token_budget: u32,
        token_budget: u32,
    ) -> Option<NextBatch> {
jixx's avatar
jixx committed
92
93
94
95
        if prefill_token_budget == 0 || token_budget == 0 {
            return None;
        };

jixx's avatar
init  
jixx committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        // Create response channel
        let (response_sender, response_receiver) = oneshot::channel();
        // Send next batch command to the background task managing the state
        // Unwrap is safe here
        self.queue_sender
            .send(QueueCommand::NextBatch {
                min_size,
                max_size,
                prefill_token_budget,
                token_budget,
                response_sender,
                span: Span::current(),
            })
            .unwrap();
        // Await on response channel
        // Unwrap is safe here
        response_receiver.await.unwrap()
    }
}

// Background task responsible of the queue state
jixx's avatar
jixx committed
117
#[allow(clippy::too_many_arguments)]
jixx's avatar
init  
jixx committed
118
119
120
async fn queue_task(
    requires_padding: bool,
    block_size: u32,
jixx's avatar
jixx committed
121
    prefix_caching: bool,
jixx's avatar
init  
jixx committed
122
123
124
    window_size: Option<u32>,
    speculate: u32,
    max_batch_total_tokens: u32,
jixx's avatar
jixx committed
125
    support_chunking: bool,
jixx's avatar
init  
jixx committed
126
127
128
129
130
    mut receiver: mpsc::UnboundedReceiver<QueueCommand>,
) {
    let mut state = State::new(
        requires_padding,
        block_size,
jixx's avatar
jixx committed
131
        prefix_caching,
jixx's avatar
init  
jixx committed
132
133
134
        window_size,
        speculate,
        max_batch_total_tokens,
jixx's avatar
jixx committed
135
        support_chunking,
jixx's avatar
init  
jixx committed
136
137
138
139
140
141
    );

    while let Some(cmd) = receiver.recv().await {
        match cmd {
            QueueCommand::Append(entry, span) => {
                span.in_scope(|| state.append(*entry));
jixx's avatar
jixx committed
142
                metrics::gauge!("tgi_queue_size").increment(1.0);
jixx's avatar
init  
jixx committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
            }
            QueueCommand::NextBatch {
                min_size,
                max_size,
                prefill_token_budget,
                token_budget,
                response_sender,
                span,
            } => {
                let next_batch = state
                    .next_batch(min_size, max_size, prefill_token_budget, token_budget)
                    .instrument(span)
                    .await;
                response_sender.send(next_batch).unwrap();
jixx's avatar
jixx committed
157
                metrics::gauge!("tgi_queue_size").set(state.entries.len() as f64);
jixx's avatar
init  
jixx committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
            }
        }
    }
}

/// Queue State
#[derive(Debug)]
struct State {
    /// Queue entries organized in a Vec
    entries: VecDeque<(u64, Entry)>,

    /// Id of the next entry
    next_id: u64,

    /// Id of the next batch
    next_batch_id: u64,

    /// Paged Attention block size
    block_size: u32,

    /// Speculation amount
    speculate: u32,

jixx's avatar
jixx committed
181
182
183
184
185
    /// Whether the model allow the prefill chunking
    /// If it does, the last request in the batch will be split to exactly match the prefill
    /// token budget
    support_chunking: bool,

jixx's avatar
init  
jixx committed
186
187
188
189
190
191
192
193
    /// Paged Attention Block Allocation
    block_allocator: Option<BlockAllocator>,
}

impl State {
    fn new(
        requires_padding: bool,
        block_size: u32,
jixx's avatar
jixx committed
194
        prefix_caching: bool,
jixx's avatar
init  
jixx committed
195
196
197
        window_size: Option<u32>,
        speculate: u32,
        max_batch_total_tokens: u32,
jixx's avatar
jixx committed
198
        support_chunking: bool,
jixx's avatar
init  
jixx committed
199
    ) -> Self {
jixx's avatar
jixx committed
200
201
202
203
204
205
206
207
        let block_allocator = (!requires_padding).then(|| {
            BlockAllocator::new(
                max_batch_total_tokens,
                block_size,
                prefix_caching,
                window_size,
            )
        });
jixx's avatar
init  
jixx committed
208
209
210
211
212
213
214

        Self {
            entries: VecDeque::with_capacity(128),
            next_id: 0,
            next_batch_id: 0,
            block_size,
            speculate,
jixx's avatar
jixx committed
215
            support_chunking,
jixx's avatar
init  
jixx committed
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
            block_allocator,
        }
    }

    /// Append an entry to the queue
    fn append(&mut self, mut entry: Entry) {
        // Create a span that will live as long as the entry is in the queue waiting to be batched
        let queue_span = info_span!(parent: &entry.span, "queued");
        entry.temp_span = Some(queue_span);

        // Push entry in the queue
        self.entries.push_back((self.next_id, entry));
        self.next_id += 1;
    }

    // Get the next batch
    async fn next_batch(
        &mut self,
        min_size: Option<usize>,
        max_size: Option<usize>,
        prefill_token_budget: u32,
        token_budget: u32,
    ) -> Option<NextBatch> {
        if self.entries.is_empty() {
            tracing::debug!("No queue");
            return None;
        }

        // Check if we have enough entries
        if let Some(min_size) = min_size {
            if self.entries.len() < min_size {
                tracing::debug!("Not enough entries");
                return None;
            }
        }

jixx's avatar
jixx committed
252
253
254
255
256
257
258
        if let Some(max_size) = max_size {
            if max_size == 0 {
                tracing::debug!("No capacity");
                return None;
            }
        }

jixx's avatar
init  
jixx committed
259
260
261
262
263
264
        // Pad prefill_token_budget to be a multiple of block size
        let prefill_token_budget =
            ((prefill_token_budget + self.block_size - 1) / self.block_size) * self.block_size;

        // Create span for this batch to add context to inference calls
        let next_batch_span = info_span!(parent: None, "batch", batch_size = tracing::field::Empty);
jixx's avatar
jixx committed
265
        next_batch_span.follows_from(Span::current());
jixx's avatar
init  
jixx committed
266

jixx's avatar
jixx committed
267
        let mut batch = Vec::with_capacity(self.entries.len());
jixx's avatar
init  
jixx committed
268
269
270
271
272
273
        let mut max_input_length = 0;
        let mut prefill_tokens: u32 = 0;
        let mut decode_tokens: u32 = 0;
        let mut max_blocks = 0;

        // Pop entries starting from the front of the queue
jixx's avatar
jixx committed
274
        'entry_loop: while let Some((id, entry)) = self.entries.pop_front() {
jixx's avatar
init  
jixx committed
275
276
277
            // Filter entries where the response receiver was dropped (== entries where the request
            // was dropped by the client)
            if entry.response_tx.is_closed() {
jixx's avatar
jixx committed
278
                metrics::counter!("tgi_request_failure", "err" => "dropped").increment(1);
jixx's avatar
init  
jixx committed
279
280
281
282
283
284
285
286
287
                tracing::debug!("Dropping entry");
                continue;
            }

            let block_allocation = match &self.block_allocator {
                None => {
                    // We pad to max input length in the Python shards
                    // We need to take these padding tokens into the equation
                    max_input_length = max_input_length.max(entry.request.input_length);
jixx's avatar
jixx committed
288
                    prefill_tokens = (batch.len() + 1) as u32 * max_input_length;
jixx's avatar
init  
jixx committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302

                    decode_tokens += entry.request.stopping_parameters.max_new_tokens;
                    let total_tokens = prefill_tokens + decode_tokens + self.speculate;

                    if prefill_tokens > prefill_token_budget || total_tokens > token_budget {
                        // Entry is over budget
                        // Add it back to the front
                        tracing::debug!("Over budget: prefill_tokens={prefill_tokens} > {prefill_token_budget} || {prefill_tokens} + {decode_tokens} + {} > {token_budget}", self.speculate);
                        self.entries.push_front((id, entry));
                        break 'entry_loop;
                    }
                    None
                }
                Some(block_allocator) => {
jixx's avatar
jixx committed
303
304
305
306
307
308
                    // If users wants the prefill logprobs, we cannot reuse the cache.
                    // So no input_ids for the radix tree.
                    let input_ids = if entry.request.decoder_input_details {
                        None
                    } else {
                        entry.request.input_ids.clone()
jixx's avatar
init  
jixx committed
309
310
311
312
313
314
                    };

                    let tokens = entry.request.input_length
                        + entry.request.stopping_parameters.max_new_tokens
                        + self.speculate
                        - 1;
jixx's avatar
jixx committed
315
                    tracing::debug!("Allocating {tokens} with {input_ids:?}");
jixx's avatar
init  
jixx committed
316

jixx's avatar
jixx committed
317
                    let block_allocation = match block_allocator.allocate(tokens, input_ids).await {
jixx's avatar
init  
jixx committed
318
319
320
321
322
323
324
                        None => {
                            // Entry is over budget
                            // Add it back to the front
                            tracing::debug!("Over budget: not enough free blocks");
                            self.entries.push_front((id, entry));
                            break 'entry_loop;
                        }
jixx's avatar
jixx committed
325
                        Some(mut block_allocation) => {
jixx's avatar
init  
jixx committed
326
327
                            tracing::debug!("Allocation: {block_allocation:?}");
                            max_blocks = max(max_blocks, block_allocation.blocks.len() as u32);
jixx's avatar
jixx committed
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

                            if block_allocation.prefix_len == entry.request.input_length {
                                // The whole request was found in the radix trie
                                // However, for the transformer forward to work, we need to
                                // have at least one token of postfix.
                                block_allocation.prefix_len -= 1;
                            }

                            block_allocation
                        }
                    };

                    let postfix_len = entry.request.input_length - block_allocation.prefix_len;

                    if prefill_tokens + postfix_len > prefill_token_budget {
                        // Entry is over budget
                        if self.support_chunking {
                            // We support chunking, just set postfix_len to exactly match prefill_token_budget
                            let chunk_len = prefill_token_budget.saturating_sub(prefill_tokens);
                            if chunk_len > 0 {
                                // Push this entry inside the batch
                                batch.push((id, entry, Some(block_allocation), Some(chunk_len)));
                            } else {
                                // We cannot prefill even one token for this entry
                                // Add it back to the queue
                                self.entries.push_front((id, entry));
                            }
                            tracing::debug!(
                                "Matched budget: prefill_tokens={} == {prefill_token_budget}",
                                prefill_tokens + postfix_len
                            );
                            break 'entry_loop;
                        } else {
                            // We don't support chunking, this entry needs to go back to the buffer
                            // Add it back to the front
                            tracing::debug!(
                                "Over budget: prefill_tokens={} > {prefill_token_budget}",
                                prefill_tokens + postfix_len
                            );
                            self.entries.push_front((id, entry));
                            break 'entry_loop;
jixx's avatar
init  
jixx committed
369
370
                        }
                    }
jixx's avatar
jixx committed
371
372
373
374

                    prefill_tokens += postfix_len;

                    Some(block_allocation)
jixx's avatar
init  
jixx committed
375
376
                }
            };
jixx's avatar
jixx committed
377
378
379
380
381
            batch.push((id, entry, block_allocation, None));
            if Some(batch.len()) == max_size {
                break;
            }
        }
jixx's avatar
init  
jixx committed
382

jixx's avatar
jixx committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
        // Empty batch
        if batch.is_empty() {
            tracing::debug!("Filterered out all entries");
            return None;
        }

        // XXX We haven't allocated yet, so we're allowed to ditch the results.
        // Check if our batch is big enough
        if let Some(min_size) = min_size {
            // Batch is too small
            if batch.len() < min_size {
                // Add back entries to the queue in the correct order
                for (id, entry, _, _) in batch.into_iter().rev() {
                    self.entries.push_front((id, entry));
                }
                return None;
            }
        }

        let mut batch_requests = Vec::with_capacity(self.entries.len());
        let mut batch_entries =
            IntMap::with_capacity_and_hasher(self.entries.len(), BuildNoHashHasher::default());

        for (id, mut entry, block_allocation, chunk_len) in batch {
jixx's avatar
init  
jixx committed
407
408
409
410
411
412
413
414
            // Create a new span to link the batch back to this entry
            let entry_batch_span = info_span!(parent: &entry.span, "infer");
            // Add relationships
            next_batch_span.follows_from(&entry_batch_span);
            entry_batch_span.follows_from(&next_batch_span);
            // Update entry
            entry.temp_span = Some(entry_batch_span);

jixx's avatar
jixx committed
415
416
            let (blocks, slots, prefix_len) = match &block_allocation {
                None => (Vec::new(), Vec::new(), 0),
jixx's avatar
init  
jixx committed
417
418
419
                Some(block_allocation) => (
                    block_allocation.blocks.clone(),
                    block_allocation.slots.clone(),
jixx's avatar
jixx committed
420
                    block_allocation.prefix_len,
jixx's avatar
init  
jixx committed
421
422
423
424
425
426
427
428
                ),
            };

            entry.block_allocation = block_allocation;

            batch_requests.push(Request {
                id,
                prefill_logprobs: entry.request.decoder_input_details,
jixx's avatar
jixx committed
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
                input_chunks: Some(client::Input {
                    chunks: entry
                        .request
                        .inputs
                        .clone()
                        .into_iter()
                        .map(|c| client::InputChunk {
                            chunk: Some(match c {
                                Chunk::Text(text) => client::Chunk::Text(text),
                                Chunk::Image(image) => client::Chunk::Image(client::Image {
                                    data: image.data,
                                    mimetype: image.mimetype,
                                }),
                            }),
                        })
                        .collect(),
jixx's avatar
init  
jixx committed
445
446
447
                }),
                inputs: entry.request.inputs.chunks_to_string(),
                truncate: entry.request.truncate,
jixx's avatar
jixx committed
448
                add_special_tokens: entry.request.add_special_tokens,
jixx's avatar
init  
jixx committed
449
450
451
452
453
454
455
456
457
                parameters: Some(NextTokenChooserParameters::from(
                    entry.request.parameters.clone(),
                )),
                stopping_parameters: Some(StoppingCriteriaParameters::from(
                    entry.request.stopping_parameters.clone(),
                )),
                top_n_tokens: entry.request.top_n_tokens,
                blocks,
                slots,
jixx's avatar
jixx committed
458
                cache_len: prefix_len,
jixx's avatar
init  
jixx committed
459
                adapter_id: entry.request.adapter_id.clone(),
jixx's avatar
jixx committed
460
                chunk_len,
jixx's avatar
init  
jixx committed
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
            });
            // Set batch_time
            entry.batch_time = Some(Instant::now());
            // Insert in batch_entries IntMap
            batch_entries.insert(id, entry);
        }

        // Final batch size
        let size = batch_requests.len() as u32;
        next_batch_span.record("batch_size", size);

        let batch = Batch {
            id: self.next_batch_id,
            requests: batch_requests,
            size,
            max_tokens: (prefill_tokens + decode_tokens),
            max_blocks,
        };
        // Increment batch id
        self.next_batch_id += 1;

jixx's avatar
jixx committed
482
        metrics::histogram!("tgi_batch_next_size").record(batch.size as f64);
jixx's avatar
init  
jixx committed
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541

        Some((batch_entries, batch, next_batch_span))
    }
}

type NextBatch = (IntMap<u64, Entry>, Batch, Span);

#[derive(Debug)]
enum QueueCommand {
    Append(Box<Entry>, Span),
    NextBatch {
        min_size: Option<usize>,
        max_size: Option<usize>,
        prefill_token_budget: u32,
        token_budget: u32,
        response_sender: oneshot::Sender<Option<NextBatch>>,
        span: Span,
    },
}

impl From<ValidParameters> for NextTokenChooserParameters {
    fn from(value: ValidParameters) -> Self {
        let (grammar, grammar_type) = match value.grammar {
            None => (String::new(), GrammarType::None),

            Some(grammar) => match grammar {
                ValidGrammar::Json(grammar_string) => (grammar_string, GrammarType::Json),
                ValidGrammar::Regex(grammar_string) => (grammar_string, GrammarType::Regex),
            },
        };

        Self {
            temperature: value.temperature,
            top_k: value.top_k,
            top_p: value.top_p,
            typical_p: value.typical_p,
            do_sample: value.do_sample,
            seed: value.seed,
            repetition_penalty: value.repetition_penalty,
            frequency_penalty: value.frequency_penalty,
            watermark: value.watermark,
            grammar,
            grammar_type: grammar_type.into(),
        }
    }
}

impl From<ValidStoppingParameters> for StoppingCriteriaParameters {
    fn from(value: ValidStoppingParameters) -> Self {
        Self {
            max_new_tokens: value.max_new_tokens,
            stop_sequences: value.stop_sequences,
            ignore_eos_token: value.ignore_eos_token,
        }
    }
}

#[cfg(test)]
mod tests {
jixx's avatar
jixx committed
542
543
    use std::sync::Arc;

jixx's avatar
init  
jixx committed
544
545
546
547
548
549
550
551
552
553
554
555
    use super::*;
    use tracing::info_span;

    fn default_entry() -> (
        Entry,
        mpsc::UnboundedReceiver<Result<InferStreamResponse, InferError>>,
    ) {
        let (response_tx, receiver_tx) = mpsc::unbounded_channel();

        let entry = Entry {
            request: ValidGenerateRequest {
                inputs: vec![],
jixx's avatar
jixx committed
556
557
558
                input_ids: Some(Arc::new(vec![])),
                input_length: 1,
                add_special_tokens: true,
jixx's avatar
init  
jixx committed
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
                truncate: 0,
                decoder_input_details: false,
                parameters: ValidParameters {
                    temperature: 0.0,
                    top_k: 0,
                    top_p: 0.0,
                    typical_p: 0.0,
                    do_sample: false,
                    seed: 0,
                    repetition_penalty: 0.0,
                    frequency_penalty: 0.0,
                    watermark: false,
                    grammar: None,
                },
                stopping_parameters: ValidStoppingParameters {
                    ignore_eos_token: false,
                    max_new_tokens: 1,
                    stop_sequences: vec![],
                },
                top_n_tokens: 0,
                adapter_id: None,
            },
            response_tx,
            span: info_span!("entry"),
            temp_span: None,
            queue_time: Instant::now(),
            batch_time: None,
            block_allocation: None,
        };
        (entry, receiver_tx)
    }

    #[tokio::test]
    async fn test_append() {
jixx's avatar
jixx committed
593
        let mut state = State::new(false, 1, false, None, 0, 16, false);
jixx's avatar
init  
jixx committed
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
        let (entry, _guard) = default_entry();

        assert_eq!(state.next_id, 0);
        assert_eq!(state.entries.len(), 0);

        state.append(entry);

        assert_eq!(state.next_id, 1);
        assert_eq!(state.entries.len(), 1);
        let (id, _) = state.entries.remove(0).unwrap();
        assert_eq!(id, 0);
    }

    #[tokio::test]
    async fn test_next_batch_empty() {
jixx's avatar
jixx committed
609
        let mut state = State::new(false, 1, false, None, 0, 16, false);
jixx's avatar
init  
jixx committed
610
611
612
613
614
615
616

        assert!(state.next_batch(None, None, 1, 1).await.is_none());
        assert!(state.next_batch(Some(1), None, 1, 1).await.is_none());
    }

    #[tokio::test]
    async fn test_next_batch_min_size() {
jixx's avatar
jixx committed
617
        let mut state = State::new(false, 1, false, None, 0, 16, false);
jixx's avatar
init  
jixx committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        state.append(entry1);
        state.append(entry2);

        let (entries, batch, _) = state.next_batch(None, None, 2, 2).await.unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key(&0));
        assert!(entries.contains_key(&1));
        assert!(entries.get(&0).unwrap().batch_time.is_some());
        assert!(entries.get(&1).unwrap().batch_time.is_some());
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 2);

        assert_eq!(state.next_id, 2);
        assert_eq!(state.entries.len(), 0);
        assert_eq!(state.next_batch_id, 1);

        let (entry3, _guard3) = default_entry();
        state.append(entry3);

        assert!(state.next_batch(Some(2), None, 2, 2).await.is_none());

        assert_eq!(state.next_id, 3);
        assert_eq!(state.entries.len(), 1);
        let (id, _) = state.entries.remove(0).unwrap();
        assert_eq!(id, 2);
    }

    #[tokio::test]
    async fn test_next_batch_max_size() {
jixx's avatar
jixx committed
649
        let mut state = State::new(false, 1, false, None, 0, 16, false);
jixx's avatar
init  
jixx committed
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        state.append(entry1);
        state.append(entry2);

        let (entries, batch, _) = state.next_batch(None, Some(1), 2, 2).await.unwrap();
        assert_eq!(entries.len(), 1);
        assert!(entries.contains_key(&0));
        assert!(entries.get(&0).unwrap().batch_time.is_some());
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 1);

        assert_eq!(state.next_id, 2);
        assert_eq!(state.entries.len(), 1);
        assert_eq!(state.next_batch_id, 1);
    }

    #[tokio::test]
    async fn test_next_batch_token_budget() {
jixx's avatar
jixx committed
669
        let mut state = State::new(false, 1, false, None, 0, 16, false);
jixx's avatar
init  
jixx committed
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        state.append(entry1);
        state.append(entry2);

        let (entries, batch, _) = state.next_batch(None, None, 1, 1).await.unwrap();
        assert_eq!(entries.len(), 1);
        assert!(entries.contains_key(&0));
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 1);

        assert_eq!(state.next_id, 2);
        assert_eq!(state.entries.len(), 1);
        assert_eq!(state.next_batch_id, 1);

        let (entry3, _guard3) = default_entry();
        state.append(entry3);

        let (entries, batch, _) = state.next_batch(None, None, 3, 3).await.unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key(&1));
        assert!(entries.contains_key(&2));
        assert_eq!(batch.id, 1);
        assert_eq!(batch.size, 2);

        assert_eq!(state.next_id, 3);
        assert_eq!(state.entries.len(), 0);
        assert_eq!(state.next_batch_id, 2);
    }

    #[tokio::test]
    async fn test_queue_append() {
jixx's avatar
jixx committed
702
        let queue = Queue::new(false, 1, false, None, 0, 16, false);
jixx's avatar
init  
jixx committed
703
704
705
706
707
708
        let (entry, _guard) = default_entry();
        queue.append(entry);
    }

    #[tokio::test]
    async fn test_queue_next_batch_empty() {
jixx's avatar
jixx committed
709
        let queue = Queue::new(false, 1, false, None, 0, 16, false);
jixx's avatar
init  
jixx committed
710
711
712
713
714
715
716

        assert!(queue.next_batch(None, None, 1, 1).await.is_none());
        assert!(queue.next_batch(Some(1), None, 1, 1).await.is_none());
    }

    #[tokio::test]
    async fn test_queue_next_batch_min_size() {
jixx's avatar
jixx committed
717
        let queue = Queue::new(false, 1, false, None, 0, 16, false);
jixx's avatar
init  
jixx committed
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        queue.append(entry1);
        queue.append(entry2);

        let (entries, batch, _) = queue.next_batch(None, None, 2, 2).await.unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key(&0));
        assert!(entries.contains_key(&1));
        assert!(entries.get(&0).unwrap().batch_time.is_some());
        assert!(entries.get(&1).unwrap().batch_time.is_some());
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 2);

        let (entry3, _guard3) = default_entry();
        queue.append(entry3);

        // Not enough requests pending
        assert!(queue.next_batch(Some(2), None, 2, 2).await.is_none());
        // Not enough token budget
        assert!(queue.next_batch(Some(1), None, 0, 0).await.is_none());
        // Ok
        let (entries2, batch2, _) = queue.next_batch(Some(1), None, 2, 2).await.unwrap();
        assert_eq!(entries2.len(), 1);
        assert!(entries2.contains_key(&2));
        assert!(entries2.get(&2).unwrap().batch_time.is_some());
        assert_eq!(batch2.id, 1);
        assert_eq!(batch2.size, 1);
    }

    #[tokio::test]
    async fn test_queue_next_batch_max_size() {
jixx's avatar
jixx committed
750
        let queue = Queue::new(false, 1, false, None, 0, 16, false);
jixx's avatar
init  
jixx committed
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        queue.append(entry1);
        queue.append(entry2);

        let (entries, batch, _) = queue.next_batch(None, Some(1), 2, 2).await.unwrap();
        assert_eq!(entries.len(), 1);
        assert!(entries.contains_key(&0));
        assert!(entries.get(&0).unwrap().batch_time.is_some());
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 1);
    }

    #[tokio::test]
    async fn test_queue_next_batch_token_budget() {
jixx's avatar
jixx committed
766
        let queue = Queue::new(false, 1, false, None, 0, 16, false);
jixx's avatar
init  
jixx committed
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        queue.append(entry1);
        queue.append(entry2);

        let (entries, batch, _) = queue.next_batch(None, None, 1, 1).await.unwrap();
        assert_eq!(entries.len(), 1);
        assert!(entries.contains_key(&0));
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 1);

        let (entry3, _guard3) = default_entry();
        queue.append(entry3);

        let (entries, batch, _) = queue.next_batch(None, None, 3, 3).await.unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key(&1));
        assert!(entries.contains_key(&2));
        assert_eq!(batch.id, 1);
        assert_eq!(batch.size, 2);
    }

    #[tokio::test]
    async fn test_queue_next_batch_token_speculate() {
jixx's avatar
jixx committed
791
        let queue = Queue::new(true, 1, false, None, 2, 16, false);
jixx's avatar
init  
jixx committed
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        queue.append(entry1);
        queue.append(entry2);

        // Budget of 1 is not enough
        assert!(queue.next_batch(None, None, 1, 1).await.is_none());

        let (entries, batch, _) = queue.next_batch(None, None, 6, 6).await.unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key(&0));
        assert!(entries.contains_key(&1));
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 2);
    }

    #[tokio::test]
    async fn test_queue_next_batch_dropped_receiver() {
jixx's avatar
jixx committed
810
        let queue = Queue::new(false, 1, false, None, 0, 16, false);
jixx's avatar
init  
jixx committed
811
812
813
814
815
816
        let (entry, _) = default_entry();
        queue.append(entry);

        assert!(queue.next_batch(None, None, 1, 1).await.is_none());
    }
}