reylo-engine-core 0.9.0

What every database's analysis engine shares: the request protocol and its host, the placeholder lexer, the project file, the type model and its JSON Schema, structured parameters, and the WebAssembly ABI each database's artifact exports.
Documentation
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
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! The replay run to its end, for a host that links the engine natively: call a round, answer
//! every need it names, call again, until the engine answers with the analysis. [`run`] does it
//! for an [`Answerer`] that answers as it is called, and [`run_async`] for one whose answers are
//! futures, as a database client's are. Each round runs on the engine's stack, as [`crate::api::call`]
//! runs one.
//!
//! A host keeps the answers it has across statements in an [`AnswerCache`]: every need is named by
//! what it asks (`describe:<sql>`, `query:<sql>|<params>`), so a later statement that asks the same
//! is answered without a round trip, for as long as the answer's [`Scope`] says it stays true.

use crate::api::{Analysis, Answer, Answers, DbError, Need, Response, Scope};
use crate::database::Database;
use serde_json::Value;
use std::collections::HashMap;
use std::future::Future;
use std::time::{Duration, Instant};

/// How many rounds a statement may take before the replay is given up as unsettled. A statement
/// settles in a handful: each round collects every need that does not wait on another's answer. An
/// array of rows nested in another waits a few rounds per level, so three levels take about twenty.
/// It equals the loader's limit, the bound of the replay loop in `src/engine-core.ts`, so a native
/// host never settles a statement the loader gives up on.
pub const ROUNDS: usize = 32;

/// What answers the engine's needs as it is called: a database client that blocks.
pub trait Answerer<D> {
    /// Why the host could not answer at all, such as a lost connection; it ends the replay. A
    /// database's refusal of what it was asked is not one: that is the inner `Err`, an answer the
    /// engine reads (an unknown column in a describe becomes a diagnostic).
    type Error;

    /// The database's describe of `sql`: Postgres's Parse and Describe, MySQL's prepare; never
    /// asked of SQLite, which prepares inside the engine.
    fn describe(&mut self, sql: &str) -> Result<Result<D, DbError>, Self::Error>;

    /// A catalog query's rows, each an array of its values in column order.
    fn query(&mut self, sql: &str, params: &[Value]) -> Result<Result<Vec<Vec<Value>>, DbError>, Self::Error>;
}

/// [`Answerer`] for a client whose answers are futures.
pub trait AsyncAnswerer<D> {
    /// As [`Answerer::Error`].
    type Error;

    /// As [`Answerer::describe`].
    fn describe(&mut self, sql: &str) -> impl Future<Output = Result<Result<D, DbError>, Self::Error>> + Send;

    /// As [`Answerer::query`].
    fn query(&mut self, sql: &str, params: &[Value]) -> impl Future<Output = Result<Result<Vec<Vec<Value>>, DbError>, Self::Error>> + Send;
}

/// [`AsyncAnswerer`] for a client that takes several requests at once, as a tokio-postgres client
/// pipelines the statements it is given together over its one connection. [`run_concurrent`] asks
/// each round's needs together, so a round waits about one round trip to the server rather than one
/// per need, which is most of an analysis's time on a server far from the host.
pub trait ConcurrentAnswerer<D> {
    /// As [`Answerer::Error`].
    type Error;

    /// As [`Answerer::describe`].
    fn describe(&self, sql: &str) -> impl Future<Output = Result<Result<D, DbError>, Self::Error>> + Send;

    /// As [`Answerer::query`].
    fn query(&self, sql: &str, params: &[Value]) -> impl Future<Output = Result<Result<Vec<Vec<Value>>, DbError>, Self::Error>> + Send;

    /// Whether `error` ended the session, or leaves it to the host to give up on, so that nothing else asked on it need finish. A round stops at such an error at once; after any other it lets what it already asked finish, since a request dropped halfway can leave its state on a session the host goes on using.
    fn ends_session(&self, _error: &Self::Error) -> bool {
        true
    }
}

/// Why a replay ended without an analysis.
#[derive(Debug)]
pub enum ReplayError<E> {
    /// The host could not answer.
    Host(E),
    /// The engine failed, with its message.
    Engine(String),
    /// The engine was still asking after [`ROUNDS`] rounds.
    Unsettled,
}

impl<E: std::fmt::Display> std::fmt::Display for ReplayError<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ReplayError::Host(e) => write!(f, "{e}"),
            ReplayError::Engine(message) => write!(f, "{message}"),
            ReplayError::Unsettled => write!(f, "the engine was still asking after {ROUNDS} rounds"),
        }
    }
}

impl<E: std::fmt::Debug + std::fmt::Display> std::error::Error for ReplayError<E> {}

/// The answers a host keeps across statements. A session answer (`Scope::Session`: a server
/// setting, a type the database defines) stays for `session`, any other for `statement`, so a
/// migration shows up within seconds and a statement analyzed again a moment later costs no round
/// trip. A failure is never kept: the next statement asks again.
pub struct AnswerCache<D> {
    entries: HashMap<String, (Instant, Answer<D>)>,
    session: Duration,
    statement: Duration,
}

impl<D> Default for AnswerCache<D> {
    fn default() -> Self {
        AnswerCache::new(Duration::from_secs(60), Duration::from_secs(5))
    }
}

impl<D> AnswerCache<D> {
    pub fn new(session: Duration, statement: Duration) -> Self {
        AnswerCache { entries: HashMap::new(), session, statement }
    }

    /// Answers kept until [`AnswerCache::clear`], for a host that clears them when the schema
    /// changes, or that lives for one run: each catalog fact is then read once.
    pub fn until_cleared() -> Self {
        AnswerCache::new(Duration::MAX, Duration::MAX)
    }

    /// Forgets every answer, as after a change to the schema.
    pub fn clear(&mut self) {
        self.entries.clear();
    }

    fn get(&self, need: &Need) -> Option<&Answer<D>> {
        let ttl = match need {
            Need::Query { scope: Scope::Session, .. } => self.session,
            _ => self.statement,
        };
        self.entries.get(id(need)).filter(|(at, _)| at.elapsed() < ttl).map(|(_, answer)| answer)
    }

    fn put(&mut self, need: &Need, answer: &Answer<D>)
    where
        D: Clone,
    {
        if !matches!(answer, Answer::Error { .. }) {
            self.entries.insert(id(need).to_string(), (Instant::now(), answer.clone()));
        }
    }
}

fn id(need: &Need) -> &str {
    match need {
        Need::Describe { id, .. } | Need::Query { id, .. } => id,
    }
}

/// Where a round left the replay.
enum Round {
    Done(Box<Analysis>),
    Needs(Vec<Need>),
}

/// One round over the answers so far, on the engine's stack.
fn round<Db: Database>(sql: &str, answers: &mut Answers<Db::Describe>) -> Result<Round, String> {
    Db::unbundle(answers);
    let answers: &Answers<Db::Describe> = answers;
    match crate::stack::run(move || Db::round(sql, answers)) {
        Response::Analysis { mut analysis } => {
            analysis.comment = crate::comment::prose(sql, Db::DIALECT);
            Ok(Round::Done(Box::new(analysis)))
        }
        Response::Need { needs } => Ok(Round::Needs(needs)),
        Response::Error { message } => Err(message),
        other => Err(format!("the engine answered a request for an analysis with {other:?}")),
    }
}

fn answer<D, E>(answered: Result<Result<D, DbError>, E>) -> Result<Answer<D>, ReplayError<E>> {
    Ok(match answered.map_err(ReplayError::Host)? {
        Ok(describe) => Answer::Describe { describe },
        Err(error) => Answer::Error { error },
    })
}

fn rows<D, E>(answered: Result<Result<Vec<Vec<Value>>, DbError>, E>) -> Result<Answer<D>, ReplayError<E>> {
    Ok(match answered.map_err(ReplayError::Host)? {
        Ok(rows) => Answer::Rows { rows },
        Err(error) => Answer::Error { error },
    })
}

/// The analysis of `sql`, each need answered from `cache` or by `answerer`.
pub fn run<Db: Database, A: Answerer<Db::Describe>>(sql: &str, answerer: &mut A, cache: &mut AnswerCache<Db::Describe>) -> Result<Analysis, ReplayError<A::Error>> {
    let mut answers: Answers<Db::Describe> = HashMap::new();
    for _ in 0..ROUNDS {
        let needs = match round::<Db>(sql, &mut answers).map_err(ReplayError::Engine)? {
            Round::Done(analysis) => return Ok(*analysis),
            Round::Needs(needs) => needs,
        };
        for need in needs {
            let known = cache.get(&need).cloned();
            let given = match known {
                Some(known) => known,
                None => {
                    let fresh = match &need {
                        Need::Describe { sql, .. } => answer(answerer.describe(sql))?,
                        Need::Query { sql, params, .. } => rows(answerer.query(sql, params))?,
                    };
                    cache.put(&need, &fresh);
                    fresh
                }
            };
            answers.insert(id(&need).to_string(), given);
        }
    }
    Err(ReplayError::Unsettled)
}

/// [`run`] for an [`AsyncAnswerer`].
pub async fn run_async<Db: Database, A: AsyncAnswerer<Db::Describe>>(sql: &str, answerer: &mut A, cache: &mut AnswerCache<Db::Describe>) -> Result<Analysis, ReplayError<A::Error>> {
    let mut answers: Answers<Db::Describe> = HashMap::new();
    for _ in 0..ROUNDS {
        let needs = match round::<Db>(sql, &mut answers).map_err(ReplayError::Engine)? {
            Round::Done(analysis) => return Ok(*analysis),
            Round::Needs(needs) => needs,
        };
        for need in needs {
            let known = cache.get(&need).cloned();
            let given = match known {
                Some(known) => known,
                None => {
                    let fresh = match &need {
                        Need::Describe { sql, .. } => answer(answerer.describe(sql).await)?,
                        Need::Query { sql, params, .. } => rows(answerer.query(sql, params).await)?,
                    };
                    cache.put(&need, &fresh);
                    fresh
                }
            };
            answers.insert(id(&need).to_string(), given);
        }
    }
    Err(ReplayError::Unsettled)
}

/// [`run_async`] for a [`ConcurrentAnswerer`]: the needs of a round that the cache does not answer
/// are asked together, and each is kept in the cache as it would be one at a time.
pub async fn run_concurrent<Db: Database, A: ConcurrentAnswerer<Db::Describe>>(sql: &str, answerer: &A, cache: &mut AnswerCache<Db::Describe>) -> Result<Analysis, ReplayError<A::Error>> {
    let mut answers: Answers<Db::Describe> = HashMap::new();
    for _ in 0..ROUNDS {
        let needs = match round::<Db>(sql, &mut answers).map_err(ReplayError::Engine)? {
            Round::Done(analysis) => return Ok(*analysis),
            Round::Needs(needs) => needs,
        };
        let mut asked: Vec<Need> = Vec::new();
        for need in needs {
            match cache.get(&need).cloned() {
                Some(known) => {
                    answers.insert(id(&need).to_string(), known);
                }
                None if asked.iter().all(|other| id(other) != id(&need)) => asked.push(need),
                None => {}
            }
        }
        let asking = asked.iter().map(|need| async move {
            match need {
                Need::Describe { sql, .. } => answer(answerer.describe(sql).await),
                Need::Query { sql, params, .. } => rows(answerer.query(sql, params).await),
            }
        });
        let fresh = join_to_first_error(asking, |error| matches!(error, ReplayError::Host(host) if answerer.ends_session(host))).await;
        for (need, fresh) in asked.iter().zip(fresh) {
            let fresh = fresh?;
            cache.put(need, &fresh);
            answers.insert(id(need).to_string(), fresh);
        }
    }
    Err(ReplayError::Unsettled)
}

/// The futures' outputs in their order, the futures polled together, up to and including the first error. An error `stops` says stops the rest returns at once, wherever it falls: a future before it that is still open may be queued behind the same wait on the session, so the outputs end with the first error before it where one has settled, else with it, after the outputs settled before the first open future. After any other error, the rest are polled to their end first.
async fn join_to_first_error<T, E, F: Future<Output = Result<T, E>>>(futures: impl IntoIterator<Item = F>, stops: impl Fn(&E) -> bool) -> Vec<Result<T, E>> {
    let mut futures: Vec<std::pin::Pin<Box<F>>> = futures.into_iter().map(Box::pin).collect();
    let mut outputs: Vec<Option<Result<T, E>>> = futures.iter().map(|_| None).collect();
    std::future::poll_fn(|cx| {
        for (future, output) in futures.iter_mut().zip(outputs.iter_mut()) {
            if output.is_none() {
                if let std::task::Poll::Ready(value) = future.as_mut().poll(cx) {
                    *output = Some(value);
                }
            }
        }
        let done = outputs.iter().all(Option::is_some);
        let stopped = outputs.iter().any(|output| matches!(output, Some(Err(error)) if stops(error)));
        if done || stopped {
            std::task::Poll::Ready(())
        } else {
            std::task::Poll::Pending
        }
    })
    .await;
    let stopping = outputs.iter().position(|output| matches!(output, Some(Err(error)) if stops(error)));
    let mut settled = Vec::with_capacity(outputs.len());
    for i in 0..outputs.len() {
        match outputs[i].take() {
            Some(Ok(value)) => settled.push(Ok(value)),
            Some(Err(error)) => {
                settled.push(Err(error));
                break;
            }
            // Open when a later future's error stopped the round: that error ends it here. Its
            // caller returns at the first error, before reading what it stands beside.
            None => {
                if let Some(Some(Err(error))) = stopping.and_then(|s| outputs.get_mut(s)).map(Option::take) {
                    settled.push(Err(error));
                }
                break;
            }
        }
    }
    settled
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::Diagnostic;
    use crate::dialect::Dialect;
    use crate::host::{Host, Lazy};
    use serde_json::json;

    /// A database that asks, in one round, for the statement's describe and the server's version,
    /// and puts both answers in the analysis's one diagnostic.
    struct Toy;

    impl Database for Toy {
        const DIALECT: Dialect = Dialect::Postgres;
        const FINGERPRINT: &'static str = "toy";
        type Describe = String;

        fn analyze(sql: &str, host: &Host<'_, String>) -> Lazy<Analysis> {
            let described = host.describe(sql);
            let version = host.query("select version()", vec![], Scope::Session);
            let (described, version) = (described?, version?);
            let described = described.unwrap_or_else(|e| e.message);
            let version = version.map(|rows| rows[0][0].to_string()).unwrap_or_else(|e| e.message);
            Some(crate::analysis::bare_of(sql, Dialect::Postgres, vec![Diagnostic { message: format!("{described} | {version}"), start: 0, length: 0, code: 0, server_code: None }]))
        }
    }

    #[derive(Default)]
    struct Counting {
        describes: usize,
        queries: usize,
        lost: bool,
    }

    impl Counting {
        fn describe_now(&mut self, sql: &str) -> Result<Result<String, DbError>, String> {
            self.describes += 1;
            if sql.contains("nope") {
                return Ok(Err(DbError { message: "relation \"nope\" does not exist".into(), code: Some("42P01".into()), position: None }));
            }
            Ok(Ok(format!("described {sql}")))
        }

        fn query_now(&mut self) -> Result<Result<Vec<Vec<Value>>, DbError>, String> {
            self.queries += 1;
            if self.lost {
                return Err("connection lost".into());
            }
            Ok(Ok(vec![vec![json!("18.0")]]))
        }
    }

    impl Answerer<String> for Counting {
        type Error = String;
        fn describe(&mut self, sql: &str) -> Result<Result<String, DbError>, String> {
            self.describe_now(sql)
        }
        fn query(&mut self, _sql: &str, _params: &[Value]) -> Result<Result<Vec<Vec<Value>>, DbError>, String> {
            self.query_now()
        }
    }

    impl AsyncAnswerer<String> for Counting {
        type Error = String;
        fn describe(&mut self, sql: &str) -> impl Future<Output = Result<Result<String, DbError>, String>> + Send {
            let answered = self.describe_now(sql);
            async move { answered }
        }
        fn query(&mut self, _sql: &str, _params: &[Value]) -> impl Future<Output = Result<Result<Vec<Vec<Value>>, DbError>, String>> + Send {
            let answered = self.query_now();
            async move { answered }
        }
    }

    fn said(analysis: &Analysis) -> &str {
        &analysis.diagnostics[0].message
    }

    /// Polls a future whose every await is ready, as the answers above are.
    fn ready<T>(future: impl Future<Output = T>) -> T {
        let mut future = std::pin::pin!(future);
        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
        match future.as_mut().poll(&mut cx) {
            std::task::Poll::Ready(value) => value,
            std::task::Poll::Pending => panic!("an answer was not ready"),
        }
    }

    #[test]
    fn answers_every_need_and_keeps_what_stays_true() {
        let mut host = Counting::default();
        let mut cache = AnswerCache::default();
        let first = run::<Toy, _>("select 1", &mut host, &mut cache).unwrap();
        assert_eq!(said(&first), "described select 1 | \"18.0\"");
        assert_eq!((host.describes, host.queries), (1, 1));
        // The same statement again: both answers from the cache.
        run::<Toy, _>("select 1", &mut host, &mut cache).unwrap();
        assert_eq!((host.describes, host.queries), (1, 1));
        // Another statement: its own describe, the session's version kept.
        let other = run::<Toy, _>("select 2", &mut host, &mut cache).unwrap();
        assert_eq!(said(&other), "described select 2 | \"18.0\"");
        assert_eq!((host.describes, host.queries), (2, 1));
        // A statement answer stays for `statement`, a session one for `session`.
        let mut brief = AnswerCache::new(Duration::from_secs(60), Duration::ZERO);
        run::<Toy, _>("select 3", &mut host, &mut brief).unwrap();
        run::<Toy, _>("select 3", &mut host, &mut brief).unwrap();
        assert_eq!((host.describes, host.queries), (4, 2));
    }

    #[test]
    fn a_refusal_is_an_answer_and_a_lost_host_ends_the_replay() {
        let mut host = Counting::default();
        let mut cache = AnswerCache::default();
        let refused = run::<Toy, _>("select * from nope", &mut host, &mut cache).unwrap();
        assert_eq!(said(&refused), "relation \"nope\" does not exist | \"18.0\"");
        // A refusal is not kept: the next statement that asks asks the database again.
        run::<Toy, _>("select * from nope", &mut host, &mut cache).unwrap();
        assert_eq!(host.describes, 2);
        let mut lost = Counting { lost: true, ..Counting::default() };
        match run::<Toy, _>("select 1", &mut lost, &mut AnswerCache::default()) {
            Err(ReplayError::Host(e)) => assert_eq!(e, "connection lost"),
            other => panic!("expected the host's error, got {:?}", other.map(|a| a.diagnostics)),
        }
    }

    /// Answers that come only once every need of Toy's round, its describe and its query, has been
    /// asked: a host that waits on each answer before it asks the next never gets one.
    #[derive(Default)]
    struct Together {
        asked: std::sync::atomic::AtomicUsize,
        answered: std::sync::atomic::AtomicUsize,
    }

    impl Together {
        fn once_both_asked<'a, T: Send + 'a>(&'a self, value: T) -> impl Future<Output = T> + Send + 'a {
            use std::sync::atomic::Ordering::SeqCst;
            let mut value = Some(value);
            let mut counted = false;
            std::future::poll_fn(move |_| {
                if !counted {
                    counted = true;
                    self.asked.fetch_add(1, SeqCst);
                }
                if self.asked.load(SeqCst) < 2 {
                    return std::task::Poll::Pending;
                }
                self.answered.fetch_add(1, SeqCst);
                std::task::Poll::Ready(value.take().expect("polled after it was ready"))
            })
        }
    }

    impl ConcurrentAnswerer<String> for Together {
        type Error = String;
        fn describe(&self, sql: &str) -> impl Future<Output = Result<Result<String, DbError>, String>> + Send {
            self.once_both_asked(Ok(Ok(format!("described {sql}"))))
        }
        fn query(&self, _sql: &str, _params: &[Value]) -> impl Future<Output = Result<Result<Vec<Vec<Value>>, DbError>, String>> + Send {
            self.once_both_asked(Ok(Ok(vec![vec![json!("18.0")]])))
        }
    }

    /// Polls a future until it is ready, for answers that are ready once others have been asked.
    fn settled<T>(future: impl Future<Output = T>) -> T {
        let mut future = std::pin::pin!(future);
        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
        for _ in 0..8 {
            if let std::task::Poll::Ready(value) = future.as_mut().poll(&mut cx) {
                return value;
            }
        }
        panic!("the replay waited on an answer that comes only once the round's other needs are asked")
    }

    #[test]
    fn the_concurrent_replay_asks_a_rounds_needs_together() {
        let host = Together::default();
        let mut cache = AnswerCache::default();
        let analysis = settled(run_concurrent::<Toy, _>("select 1", &host, &mut cache)).unwrap();
        assert_eq!(said(&analysis), "described select 1 | \"18.0\"");
        assert_eq!(host.answered.load(std::sync::atomic::Ordering::SeqCst), 2);
        // Both answers kept, as the one-at-a-time replay keeps them.
        let mut counting = Counting::default();
        ready(run_async::<Toy, _>("select 1", &mut counting, &mut cache)).unwrap();
        assert_eq!((counting.describes, counting.queries), (0, 0));
    }

    /// A host that loses the connection on one of Toy's two needs: on the describe with the query never answered, or on the query after the describe is answered.
    struct Lost {
        on_describe: bool,
    }

    impl ConcurrentAnswerer<String> for Lost {
        type Error = String;
        fn describe(&self, sql: &str) -> impl Future<Output = Result<Result<String, DbError>, String>> + Send {
            let answered = if self.on_describe { Err("connection lost".to_string()) } else { Ok(Ok(format!("described {sql}"))) };
            async move { answered }
        }
        fn query(&self, _sql: &str, _params: &[Value]) -> impl Future<Output = Result<Result<Vec<Vec<Value>>, DbError>, String>> + Send {
            let on_describe = self.on_describe;
            async move {
                if on_describe {
                    std::future::pending::<()>().await;
                }
                Err("connection lost".to_string())
            }
        }
    }

    #[test]
    fn a_lost_host_ends_the_concurrent_replay_without_waiting_for_the_round() {
        let mut cache = AnswerCache::default();
        match settled(run_concurrent::<Toy, _>("select 1", &Lost { on_describe: true }, &mut cache)) {
            Err(ReplayError::Host(e)) => assert_eq!(e, "connection lost"),
            other => panic!("expected the host's error, got {:?}", other.map(|a| a.diagnostics)),
        }
        // An answer before the lost one is kept.
        let mut cache = AnswerCache::default();
        assert!(matches!(settled(run_concurrent::<Toy, _>("select 1", &Lost { on_describe: false }, &mut cache)), Err(ReplayError::Host(_))));
        let mut counting = Counting::default();
        ready(run_async::<Toy, _>("select 1", &mut counting, &mut cache)).unwrap();
        assert_eq!((counting.describes, counting.queries), (0, 1));
    }

    /// A host whose query gives up on the session while the describe asked before it is still waiting, as a describe queued behind the same lock waits.
    struct Behind;

    impl ConcurrentAnswerer<String> for Behind {
        type Error = String;
        fn describe(&self, _sql: &str) -> impl Future<Output = Result<Result<String, DbError>, String>> + Send {
            async {
                std::future::pending::<()>().await;
                Ok(Ok(String::new()))
            }
        }
        fn query(&self, _sql: &str, _params: &[Value]) -> impl Future<Output = Result<Result<Vec<Vec<Value>>, DbError>, String>> + Send {
            async { Err("locked".to_string()) }
        }
    }

    #[test]
    fn an_error_that_stops_the_round_ends_it_while_a_need_asked_before_it_is_open() {
        match settled(run_concurrent::<Toy, _>("select 1", &Behind, &mut AnswerCache::default())) {
            Err(ReplayError::Host(e)) => assert_eq!(e, "locked"),
            other => panic!("expected the host's error, got {:?}", other.map(|a| a.diagnostics)),
        }
    }

    /// A host whose describe fails with an error the session survives, and whose query is still on its way.
    #[derive(Default)]
    struct Survives {
        finished: std::sync::atomic::AtomicBool,
    }

    impl ConcurrentAnswerer<String> for Survives {
        type Error = String;
        fn describe(&self, _sql: &str) -> impl Future<Output = Result<Result<String, DbError>, String>> + Send {
            async { Err("permission denied".to_string()) }
        }
        fn query(&self, _sql: &str, _params: &[Value]) -> impl Future<Output = Result<Result<Vec<Vec<Value>>, DbError>, String>> + Send {
            let mut polled = false;
            std::future::poll_fn(move |_| {
                if !polled {
                    polled = true;
                    return std::task::Poll::Pending;
                }
                self.finished.store(true, std::sync::atomic::Ordering::SeqCst);
                std::task::Poll::Ready(Ok(Ok(vec![vec![json!("18.0")]])))
            })
        }
        fn ends_session(&self, _error: &String) -> bool {
            false
        }
    }

    #[test]
    fn an_error_the_session_survives_lets_the_round_finish() {
        let host = Survives::default();
        match settled(run_concurrent::<Toy, _>("select 1", &host, &mut AnswerCache::default())) {
            Err(ReplayError::Host(e)) => assert_eq!(e, "permission denied"),
            other => panic!("expected the host's error, got {:?}", other.map(|a| a.diagnostics)),
        }
        assert!(host.finished.load(std::sync::atomic::Ordering::SeqCst));
    }

    #[test]
    fn the_async_replay_answers_as_the_blocking_one() {
        let mut host = Counting::default();
        let mut cache = AnswerCache::default();
        let analysis = ready(run_async::<Toy, _>("select 1", &mut host, &mut cache)).unwrap();
        assert_eq!(said(&analysis), "described select 1 | \"18.0\"");
        ready(run_async::<Toy, _>("select 1", &mut host, &mut cache)).unwrap();
        assert_eq!((host.describes, host.queries), (1, 1));
    }
}