hawdb 0.41.0

An embedded Rust graph database for local data-plane workloads
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
613
614
615
616
617
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
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
750
751
752
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A single commit larger than the free live-overlay headroom drains first
//! (#1479).

use super::*;

mod interrupted;

/// One py-tpcc district: 3,000 orders of ten lines, about 45% of the default
/// resident-byte envelope at 997 bytes per line.
const DISTRICT_LINES: i64 = 30_000;
/// About 59% of the envelope: two of them never fit together, so every one
/// needs a drain first.
const LARGE_DISTRICT_LINES: i64 = 40_000;
/// Large district commits in the repeated-drain test.
const DISTRICTS: i64 = 2;
/// Small commits that fill the overlay to about 67%, just under the 70%
/// trigger, so no drain is running when the district commit arrives.
const FILL_COMMITS: i64 = 18;

fn order_lines_sql(lines: std::ops::Range<i64>) -> String {
    let values = lines.map(order_line).collect::<Vec<_>>().join(", ");
    format!(
        "INSERT INTO order_line (ol_o_id, ol_d_id, ol_w_id, ol_number, ol_i_id, \
         ol_supply_w_id, ol_delivery_d, ol_quantity, ol_amount, ol_dist_info) VALUES {values}"
    )
}

/// Lines per INSERT statement. One statement of a whole district exceeds the
/// SQL parser's memo limit, and only the commit's size matters to live
/// admission, so a large commit is staged as several statements.
const LINES_PER_STATEMENT: i64 = 5_000;

/// The INSERT statements that stage `lines` in one transaction.
fn order_line_statements(lines: std::ops::Range<i64>) -> impl Iterator<Item = String> {
    let end = lines.end;
    lines
        .step_by(LINES_PER_STATEMENT as usize)
        .map(move |start| order_lines_sql(start..(start + LINES_PER_STATEMENT).min(end)))
}

fn insert_line_range(db: &mut Database, lines: std::ops::Range<i64>) -> Result<()> {
    let mut transaction = db.begin_transaction()?;
    for sql in order_line_statements(lines) {
        transaction.query_sql(&sql)?;
    }
    transaction.commit().map(|_| ())
}

fn completed(db: &Database) -> u64 {
    db.automatic_checkpoint_report()
        .unwrap()
        .unwrap()
        .completed_checkpoints
}

fn row_byte_ratio(db: &Database) -> f64 {
    let live = debt(db).relational_live;
    live.pairs()[1].0 as f64 / DEFAULT_MAX_RELATIONAL_ROW_CHANGE_BYTES as f64
}

/// Fills the serving overlay to just under the drain trigger.
fn fill_below_trigger(db: &mut Database) -> i64 {
    create_order_line(db);
    fill_order_lines(db)
}

/// Schema changes fold the live overlay, so they precede the fill.
fn fill_order_lines(db: &mut Database) -> i64 {
    for commit in 0..FILL_COMMITS {
        insert_order_lines(db, commit).unwrap();
    }
    FILL_COMMITS * ORDER_LINES_PER_COMMIT
}

/// Runs one autocommit statement, retrying only the bounded-wait
/// `BranchBusy` that applies nothing (an unoptimized build can exceed it
/// between builder work units).
fn query_with_busy_retries(db: &mut Database, sql: &str) -> Result<()> {
    for _ in 0..100 {
        match db.query_sql(sql) {
            Err(HawDBError::BranchBusy { .. }) => continue,
            result => return result.map(|_| ()),
        }
    }
    db.query_sql(sql).map(|_| ())
}

/// Commits `lines`, retrying only the bounded-wait `BranchBusy` that applies
/// nothing (an unoptimized build can exceed it between builder work units).
fn commit_with_busy_retries(
    db: &mut Database,
    lines: std::ops::Range<i64>,
    retries: &mut usize,
) -> Result<()> {
    loop {
        match insert_line_range(db, lines.clone()) {
            Err(HawDBError::BranchBusy { .. }) if *retries < 100 => *retries += 1,
            result => return result,
        }
    }
}

#[test]
fn district_sized_commits_above_the_free_headroom_drain_first_and_succeed() {
    let fixture = Fixture::new();
    let mut db = Database::open_with_config(&fixture.0, config()).unwrap();
    let mut lines = fill_below_trigger(&mut db);
    let initial = completed(&db);
    let filled = row_byte_ratio(&db);
    assert!(
        (0.6..0.7).contains(&filled),
        "fill must stop just below the trigger: {filled}"
    );
    let mut busy_retries = 0;
    // Each commit needs about 59% of the envelope, below the 70% trigger.
    // The first meets the fill; the second meets the first, so both need a
    // drain before they fit. Two commits cover the repeated case; more only
    // add full checkpoints of a growing table to the CI partition. On main
    // the first one (commit 22) is rejected before WAL append with the
    // live-overlay admission error.
    for district in 0..DISTRICTS {
        let before = completed(&db);
        commit_with_busy_retries(
            &mut db,
            lines..lines + LARGE_DISTRICT_LINES,
            &mut busy_retries,
        )
        .unwrap_or_else(|error| {
            panic!(
                "district {district} failed after {busy_retries} busy retries: {error}; \
                     {:?}; {:?}",
                debt(&db).relational_live,
                db.automatic_checkpoint_report()
            )
        });
        lines += LARGE_DISTRICT_LINES;
        assert!(
            completed(&db) > before,
            "district {district} must be admitted after a drain"
        );
        for (retained, limit) in debt(&db).relational_live.admission_pairs() {
            assert!(limit.is_none_or(|limit| retained <= limit));
        }
    }
    let report = db.automatic_checkpoint_report().unwrap().unwrap();
    assert_eq!(report.failed_attempts, 0, "{report:?}");
    assert!(
        report.completed_checkpoints >= initial + DISTRICTS as u64,
        "{report:?}"
    );
    assert_order_lines(&mut db, lines);
    drop(db);
    let mut reopened = Database::open_with_config(&fixture.0, config()).unwrap();
    assert_order_lines(&mut reopened, lines);
    reopened.checkpoint().unwrap();
    assert_order_line_totals(&mut reopened, lines);
}

/// A district commit above the free headroom whose drain keeps failing is
/// rejected with the retryable `BranchBusy`, never the live-view admission
/// error, and its retries re-arm the stopped circuit (#1618). Without the
/// re-arm, the retry after the third failure returns the non-retryable
/// live-view rejection, and no later retry can clear it on this handle.
#[test]
fn a_district_commit_retries_while_its_drain_fails_and_succeeds_once_the_fault_clears() {
    let fixture = Fixture::new();
    let mut db = Database::open_with_config(&fixture.0, config()).unwrap();
    let lines = fill_below_trigger(&mut db);
    let initial = completed(&db);
    let epoch = db.commit_epoch().unwrap();
    let obstruction = obstruct_next_checkpoint(&mut db);
    let mut busy_retries = 0;
    let mut cleared = false;
    loop {
        match insert_line_range(&mut db, lines..lines + LARGE_DISTRICT_LINES) {
            Ok(()) => break,
            Err(HawDBError::BranchBusy {
                resource: "automatic checkpoint capacity",
            }) if busy_retries < 100 => busy_retries += 1,
            Err(error) => panic!(
                "district failed after {busy_retries} busy retries: {error}; {:?}; {:?}",
                debt(&db).relational_live,
                db.automatic_checkpoint_report()
            ),
        }
        // Every rejected attempt applied nothing.
        assert_eq!(db.commit_epoch().unwrap(), epoch);
        let report = db.automatic_checkpoint_report().unwrap().unwrap();
        assert_eq!(report.completed_checkpoints, initial, "{report:?}");
        if !cleared && report.operation_failures > u64::from(MAX_OPERATION_FAILURES) {
            // The circuit stopped and a retry re-armed it at least once.
            assert!(report.operation_retry_rearms >= 1, "{report:?}");
            std::fs::remove_file(&obstruction).unwrap();
            cleared = true;
        }
    }
    let report = db.automatic_checkpoint_report().unwrap().unwrap();
    eprintln!("district after fault: busy_retries={busy_retries}, report={report:?}");
    assert!(cleared, "{report:?}");
    assert!(report.completed_checkpoints > initial, "{report:?}");
    assert!(!report.operation_retry_exhausted, "{report:?}");
    assert_eq!(db.commit_epoch().unwrap(), epoch + 1);
    let lines = lines + LARGE_DISTRICT_LINES;
    assert_order_lines(&mut db, lines);
    drop(db);
    let mut reopened = Database::open_with_config(&fixture.0, config()).unwrap();
    assert_order_lines(&mut reopened, lines);
    reopened.checkpoint().unwrap();
    assert_order_line_totals(&mut reopened, lines);
}

/// Asserts that the live admission envelope holds.
fn assert_within_envelope(db: &Database) {
    for (retained, limit) in debt(db).relational_live.admission_pairs() {
        assert!(limit.is_none_or(|limit| retained <= limit));
    }
}

/// The owner can drain but its attempt is deferred (a background admission
/// denial, as under memory pressure): the commit that needs that drain gets
/// the retryable `BranchBusy`, not the live-view admission error, applies
/// nothing, and commits once the owner can drain again (#1637).
#[test]
fn a_deferred_drain_returns_retryable_busy_and_applies_nothing() {
    let fixture = Fixture::new();
    let mut db = Database::open_with_config(&fixture.0, config()).unwrap();
    let lines = fill_below_trigger(&mut db);
    let (epoch, checkpoints) = (db.commit_epoch().unwrap(), completed(&db));
    db.set_runtime_governor(governor(1));
    let error = insert_line_range(&mut db, lines..lines + LARGE_DISTRICT_LINES).unwrap_err();
    let report = db.automatic_checkpoint_report().unwrap().unwrap();
    assert!(
        matches!(
            error,
            HawDBError::BranchBusy {
                resource: "automatic checkpoint capacity"
            }
        ),
        "{error}; {report:?}"
    );
    assert!(report.deferred_attempts >= 1, "{report:?}");
    assert!(!report.operation_retry_exhausted, "{report:?}");
    assert!(!db.storage_handle_poisoned().unwrap());
    assert_eq!(db.commit_epoch().unwrap(), epoch);
    assert_eq!(completed(&db), checkpoints);
    assert_within_envelope(&db);
    assert_order_lines(&mut db, lines);
    db.set_runtime_governor(governor(8 * 1024 * 1024 * 1024));
    let mut busy_retries = 0;
    commit_with_busy_retries(
        &mut db,
        lines..lines + LARGE_DISTRICT_LINES,
        &mut busy_retries,
    )
    .unwrap();
    assert!(completed(&db) > checkpoints);
    assert_within_envelope(&db);
    assert_order_lines(&mut db, lines + LARGE_DISTRICT_LINES);
}

/// Holds the owner just before the drain a large commit requested, makes it
/// unable to drain with `disable`, and asserts that the commit keeps the
/// non-retryable pre-WAL live-view rejection rather than `BranchBusy`:
/// waiting cannot help, and the synchronous manual checkpoint then drains
/// the overlay so the same commit succeeds (#1637). `disable` returns a guard
/// that is dropped before that manual checkpoint.
fn assert_unable_owner_keeps_the_rejection<G>(disable: impl FnOnce(&Arc<Control>) -> G) {
    let fixture = Fixture::new();
    let mut db = Database::open_with_config(&fixture.0, config()).unwrap();
    let lines = fill_below_trigger(&mut db);
    let (epoch, checkpoints) = (db.commit_epoch().unwrap(), completed(&db));
    let pause = RequestedDrainPause::install(&db);
    let control = Arc::clone(&pause.control);
    let (error, guard) = std::thread::scope(|scope| {
        let writer =
            scope.spawn(|| insert_line_range(&mut db, lines..lines + LARGE_DISTRICT_LINES));
        pause.wait_until_drain_is_held();
        // The owner re-evaluates its state when released, so it starts no
        // drain; the waiting commit wakes, fails to fit again and returns.
        let guard = disable(&control);
        control.notify_all();
        pause.release();
        (writer.join().unwrap().unwrap_err(), guard)
    });
    let report = db.automatic_checkpoint_report().unwrap().unwrap();
    let message = error.to_string();
    assert!(
        !matches!(error, HawDBError::BranchBusy { .. })
            && message.contains("before WAL append")
            && message.contains("a checkpoint must drain the overlay first"),
        "{message}; {report:?}"
    );
    assert!(!db.storage_handle_poisoned().unwrap());
    assert_eq!(db.commit_epoch().unwrap(), epoch);
    assert_eq!(completed(&db), checkpoints);
    assert_within_envelope(&db);
    assert_order_lines(&mut db, lines);
    drop(guard);
    db.checkpoint().unwrap();
    insert_line_range(&mut db, lines..lines + LARGE_DISTRICT_LINES).unwrap();
    assert_within_envelope(&db);
    assert_order_lines(&mut db, lines + LARGE_DISTRICT_LINES);
}

/// A suspended owner starts no drain, so the waiting commit keeps the
/// live-view rejection.
#[test]
fn a_commit_waiting_on_a_suspended_owner_keeps_the_live_view_rejection() {
    assert_unable_owner_keeps_the_rejection(|control| control.suspend().unwrap());
}

/// A stopped owner (as at shutdown) starts no drain, so the waiting commit
/// keeps the live-view rejection.
#[test]
fn a_commit_waiting_on_a_stopped_owner_keeps_the_live_view_rejection() {
    assert_unable_owner_keeps_the_rejection(|control| {
        control.lock().unwrap().stopping = true;
    });
}

/// A failed owner (an integrity failure while adopting a generation) is
/// terminal for this handle: the waiting commit fails closed with the
/// integrity error, never with the retryable `BranchBusy` and never by
/// re-arming anything, and applies nothing. Reopening recovers exactly the
/// committed rows at the same epoch.
#[test]
fn a_commit_waiting_on_a_failed_owner_fails_closed_and_applies_nothing() {
    let fixture = Fixture::new();
    let mut db = Database::open_with_config(&fixture.0, config()).unwrap();
    let lines = fill_below_trigger(&mut db);
    let (epoch, checkpoints) = (db.commit_epoch().unwrap(), completed(&db));
    let pause = RequestedDrainPause::install(&db);
    let control = Arc::clone(&pause.control);
    let error = std::thread::scope(|scope| {
        let writer =
            scope.spawn(|| insert_line_range(&mut db, lines..lines + LARGE_DISTRICT_LINES));
        pause.wait_until_drain_is_held();
        // As a failed generation adoption leaves it: stopped and failed.
        control.lock().unwrap().stopping = true;
        control.failed.store(true, Ordering::Release);
        control.notify_all();
        pause.release();
        writer.join().unwrap().unwrap_err()
    });
    // The handle refuses every later operation with the integrity error
    // (`ensure_healthy`), so the owner's own report is read directly.
    let report = control.lock().unwrap().report.clone();
    assert!(
        matches!(error, HawDBError::StorageIntegrity(_)),
        "{error}; {report:?}"
    );
    assert_eq!(report.operation_retry_rearms, 0, "{report:?}");
    assert_eq!(report.completed_checkpoints, checkpoints, "{report:?}");
    assert_within_envelope(&db);
    drop(db);
    let mut reopened = Database::open_with_config(&fixture.0, config()).unwrap();
    assert_eq!(reopened.commit_epoch().unwrap(), epoch);
    assert_order_lines(&mut reopened, lines);
}

/// An owner whose operation retries are exhausted starts no drain by itself,
/// but a commit that needs headroom re-arms one attempt once the circuit's
/// backoff expires (#1618). Meanwhile the commit gets at most the retryable
/// `BranchBusy` with nothing applied, and it commits without a manual
/// checkpoint once the re-armed attempt drains. This replaces the
/// live-view rejection #1637 kept for an exhausted owner.
#[test]
fn a_commit_waiting_on_an_exhausted_owner_re_arms_it_and_commits() {
    let fixture = Fixture::new();
    let mut db = Database::open_with_config(&fixture.0, config()).unwrap();
    let lines = fill_below_trigger(&mut db);
    let (epoch, checkpoints) = (db.commit_epoch().unwrap(), completed(&db));
    let pause = RequestedDrainPause::install(&db);
    let control = Arc::clone(&pause.control);
    let result = std::thread::scope(|scope| {
        let writer =
            scope.spawn(|| insert_line_range(&mut db, lines..lines + LARGE_DISTRICT_LINES));
        pause.wait_until_drain_is_held();
        {
            let now = control.frontend_now();
            let fault = HawDBError::Storage("injected operation failure".into());
            let mut state = control.lock().unwrap();
            for _ in 0..MAX_OPERATION_FAILURES {
                record_operation_failure(&mut state, &fault, now);
            }
            assert!(state.report.operation_retry_exhausted);
        }
        control.notify_all();
        pause.release();
        writer.join().unwrap()
    });
    match result {
        Ok(()) => {}
        Err(HawDBError::BranchBusy {
            resource: "automatic checkpoint capacity",
        }) => {
            // Rejected before WAL append: nothing applied, retry is safe.
            assert_eq!(db.commit_epoch().unwrap(), epoch);
            assert_order_lines(&mut db, lines);
            let mut busy_retries = 0;
            commit_with_busy_retries(
                &mut db,
                lines..lines + LARGE_DISTRICT_LINES,
                &mut busy_retries,
            )
            .unwrap();
        }
        Err(error) => panic!("{error}; {:?}", db.automatic_checkpoint_report()),
    }
    let report = db.automatic_checkpoint_report().unwrap().unwrap();
    assert!(report.operation_retry_rearms >= 1, "{report:?}");
    assert!(!report.operation_retry_exhausted, "{report:?}");
    assert!(report.completed_checkpoints > checkpoints, "{report:?}");
    assert_eq!(db.commit_epoch().unwrap(), epoch + 1);
    assert_within_envelope(&db);
    assert_order_lines(&mut db, lines + LARGE_DISTRICT_LINES);
}

const WIDE_COLUMNS: usize = 40;

/// Wide rows per INSERT statement, within the SQL parser's memo limit.
const WIDE_ROWS_PER_STATEMENT: i64 = 1_000;

/// Rows of one primary key and forty BIGINT columns: about 2.7 KB each.
fn wide_rows_sql(rows: std::ops::Range<i64>) -> String {
    let columns = (0..WIDE_COLUMNS)
        .map(|column| format!("c{column}"))
        .collect::<Vec<_>>()
        .join(", ");
    let values = rows
        .map(|id| {
            let row = (0..WIDE_COLUMNS as i64)
                .map(|column| (id * 31 + column).to_string())
                .collect::<Vec<_>>()
                .join(", ");
            format!("({id}, {row})")
        })
        .collect::<Vec<_>>()
        .join(", ");
    format!("INSERT INTO wide (id, {columns}) VALUES {values}")
}

#[test]
fn a_commit_larger_than_the_whole_envelope_is_rejected_with_its_size_and_writes_nothing() {
    let fixture = Fixture::new();
    let mut db = Database::open_with_config(&fixture.0, config()).unwrap();
    create_order_line(&mut db);
    let columns = (0..WIDE_COLUMNS)
        .map(|column| format!("c{column} BIGINT"))
        .collect::<Vec<_>>()
        .join(", ");
    db.query_sql(&format!(
        "CREATE TABLE wide (id BIGINT PRIMARY KEY, {columns})"
    ))
    .unwrap();
    let lines = fill_order_lines(&mut db);
    let epoch = db.commit_epoch().unwrap();
    let checkpoints = completed(&db);
    // 30,000 wide rows need about 80 MB: more than the 64 MiB envelope even
    // when the overlay is empty, so no drain can make room for them.
    let mut transaction = db.begin_transaction().unwrap();
    for start in (0..WIDE_ROWS).step_by(WIDE_ROWS_PER_STATEMENT as usize) {
        transaction
            .query_sql(&wide_rows_sql(start..start + WIDE_ROWS_PER_STATEMENT))
            .unwrap();
    }
    let error = transaction.commit().unwrap_err();
    assert_never_fits(&db, error, epoch, checkpoints);
    let count = db
        .query_sql("SELECT COUNT(*) AS n FROM wide")
        .unwrap()
        .rows
        .into_rows();
    assert_eq!(count[0].get("n"), Some(&Value::Int(0)));
    assert_order_lines(&mut db, lines);
    // The same rows committed in envelope-sized pieces and checkpointed; one
    // autocommit UPDATE of all of them is again larger than the envelope.
    for start in (0..WIDE_ROWS).step_by(WIDE_ROWS_PER_STATEMENT as usize) {
        query_with_busy_retries(
            &mut db,
            &wide_rows_sql(start..start + WIDE_ROWS_PER_STATEMENT),
        )
        .unwrap();
    }
    db.checkpoint().unwrap();
    let wide_sum = |db: &mut Database| {
        db.query_sql("SELECT COUNT(*) AS n, SUM(c0) AS c0 FROM wide")
            .unwrap()
            .rows
            .into_rows()
    };
    let staged = wide_sum(&mut db);
    assert_eq!(staged[0].get("n"), Some(&Value::Int(WIDE_ROWS)));
    let (epoch, checkpoints) = (db.commit_epoch().unwrap(), completed(&db));
    let error = db
        .query_sql(&format!(
            "UPDATE wide SET c0 = c0 + 1 WHERE id >= 0 AND id < {WIDE_ROWS}"
        ))
        .unwrap_err();
    assert_never_fits(&db, error, epoch, checkpoints);
    assert_eq!(wide_sum(&mut db), staged);
    // The handle keeps admitting commits that fit.
    insert_order_lines(&mut db, FILL_COMMITS).unwrap();
    let lines = lines + ORDER_LINES_PER_COMMIT;
    drop(db);
    let mut reopened = Database::open_with_config(&fixture.0, config()).unwrap();
    assert_order_lines(&mut reopened, lines);
    reopened.checkpoint().unwrap();
    assert_order_line_totals(&mut reopened, lines);
}

/// Asserts that `error` is the live-overlay rejection of a commit larger than
/// the whole envelope, and that it applied nothing and forced no drain.
fn assert_never_fits(db: &Database, error: HawDBError, epoch: u64, checkpoints: u64) {
    {
        let message = error.to_string();
        // The limit and the commit size are both named.
        assert!(
            message.contains("before WAL append")
                && message.contains(&format!(
                    "max_entries={DEFAULT_MAX_RELATIONAL_ROW_CHANGES}, \
                     max_bytes={DEFAULT_MAX_RELATIONAL_ROW_CHANGE_BYTES}"
                ))
                && message.contains("a single commit changes at least")
                && message.contains("split it into smaller commits"),
            "{message}"
        );
        assert!(!db.storage_handle_poisoned().unwrap());
        assert_eq!(db.commit_epoch().unwrap(), epoch);
        // A commit that can never fit does not wait for or force a drain.
        assert_eq!(completed(db), checkpoints);
    }
}

const WIDE_ROWS: i64 = 30_000;

/// First line of a district staged and checkpointed before the fill: lines
/// 60,000..90,000 are exactly district 3, which the fill never reaches.
const STAGED_DISTRICT_START: i64 = 60_000;

/// One autocommit statement larger than the free headroom: an UPDATE of a
/// whole checkpointed district. The statement text stays small, so the
/// commit size, not the parser, is what the statement exercises.
#[test]
fn autocommit_statement_above_the_free_headroom_drains_first() {
    let fixture = Fixture::new();
    let mut db = Database::open_with_config(&fixture.0, config()).unwrap();
    create_order_line(&mut db);
    let staged = STAGED_DISTRICT_START..STAGED_DISTRICT_START + DISTRICT_LINES;
    insert_line_range(&mut db, staged.clone()).unwrap();
    db.checkpoint().unwrap();
    let lines = fill_order_lines(&mut db);
    let before = completed(&db);
    query_with_busy_retries(
        &mut db,
        "UPDATE order_line SET ol_quantity = ol_quantity + 1 WHERE ol_w_id = 1 AND ol_d_id = 3",
    )
    .unwrap();
    assert!(completed(&db) > before);
    // A district-wide read merges at most 16,384 live entries (#1480); fold
    // the updated district before reading it back.
    db.checkpoint().unwrap();
    let rows = db
        .query_sql(
            "SELECT COUNT(*) AS n, SUM(ol_quantity) AS quantity FROM order_line \
             WHERE ol_w_id = 1 AND ol_d_id = 3",
        )
        .unwrap()
        .rows
        .into_rows();
    assert_eq!(rows[0].get("n"), Some(&Value::Int(DISTRICT_LINES)));
    assert_eq!(
        rows[0].get("quantity"),
        Some(&Value::Int(DISTRICT_LINES * 6))
    );
    assert_order_lines(&mut db, lines);
}

/// Holds the idle checkpoint owner just before it starts the drain that a
/// waiting commit requested, and reports when that commit starts waiting.
/// Readers are not gated while the owner is idle; writers are.
struct RequestedDrainPause {
    control: Arc<Control>,
    owner_paused: std::sync::mpsc::Receiver<()>,
    resume_owner: std::sync::mpsc::Sender<()>,
    writer_waiting: std::sync::mpsc::Receiver<Phase>,
}

impl RequestedDrainPause {
    /// Install after the fill: below the trigger and the age limit nothing
    /// is due, so the first drain the owner starts is the one the large
    /// commit's declared size requests.
    fn install(db: &Database) -> Self {
        let control = db.runtime.checkpoint_control_for_test();
        // Freeze the frontend policy clock so the writer's bounded drain
        // waits cannot expire into `BranchBusy` while the owner is held.
        control.set_frontend_time(Instant::now());
        let (paused, owner_paused) = std::sync::mpsc::channel();
        let (resume_owner, continuation) = std::sync::mpsc::channel();
        let (waiting, writer_waiting) = std::sync::mpsc::channel();
        {
            let mut state = control.lock().unwrap();
            assert_eq!(state.phase, Phase::Idle);
            state.idle_start_probe = Some(Arc::new(OwnerPauseProbe {
                paused,
                resume: Mutex::new(continuation),
            }));
            state.frontend_wait_probe = Some(waiting);
        }
        Self {
            control,
            owner_paused,
            resume_owner,
            writer_waiting,
        }
    }

    /// Returns once the writer, having passed its task check, waits for the
    /// drain it requested and the owner holds that drain before it starts.
    /// The paused owner gives up after 15 s, so callers release promptly.
    fn wait_until_drain_is_held(&self) {
        // Bounds only a broken run; neither receive is a timing assumption.
        let bound = Duration::from_secs(600);
        self.writer_waiting
            .recv_timeout(bound)
            .expect("the large commit must wait for its drain");
        self.owner_paused
            .recv_timeout(bound)
            .expect("the large commit must make a drain due");
        assert_eq!(self.control.lock().unwrap().phase, Phase::Idle);
    }

    fn release(self) {
        self.resume_owner.send(()).unwrap();
        self.control.lock().unwrap().frontend_wait_probe = None;
        *self.control.frontend_clock.lock().unwrap() = None;
        // A writer that re-evaluated under the frozen clock waits without a
        // timeout; wake it so it sees the real clock (and any backoff).
        self.control.notify_all();
    }
}

fn assert_line_absent(rows: crate::executor::QueryRows, line: i64) {
    assert!(rows.is_empty(), "line {line} must not be committed");
}

fn line_query(line: i64) -> String {
    let (order, number) = (line / 10, line % 10);
    format!(
        "SELECT ol_i_id FROM order_line WHERE ol_w_id = 1 AND ol_d_id = {} \
         AND ol_o_id = {} AND ol_number = {number}",
        order / 3_000 + 1,
        order % 3_000,
    )
}

/// Stages one district commit in a concurrent transaction, as statements of
/// at most `LINES_PER_STATEMENT` lines.
fn stage_district(
    transaction: &mut crate::ConcurrentDatabaseTransaction,
    lines: std::ops::Range<i64>,
) {
    for sql in order_line_statements(lines) {
        transaction.query_sql(&sql).unwrap();
    }
}

/// Ticks another writer commits on the concurrent handle around the district.
const TICKS: i64 = 20;

/// While a district commit on a concurrent handle waits for the drain it
/// requested, readers keep their published view and another writer queues
/// behind the commit sequencer; both finish once the drain publishes. The
/// owner holds that drain before publication, so the reads provably happen
/// during the wait, without free-running threads competing with the drain.
#[test]
fn concurrent_writer_and_reader_progress_around_a_pre_drained_commit() {
    let fixture = Fixture::new();
    let mut db = Database::open_with_config(&fixture.0, config()).unwrap();
    create_order_line(&mut db);
    db.query_sql("CREATE TABLE ticks (id BIGINT PRIMARY KEY, payload TEXT)")
        .unwrap();
    let lines = fill_order_lines(&mut db);
    let before = completed(&db);
    let pause = RequestedDrainPause::install(&db);
    let db = db.into_concurrent();
    // Readers use the published view; the first read publishes it.
    assert_eq!(db.query_sql(&line_query(0)).unwrap().rows.len(), 1);
    std::thread::scope(|scope| {
        let district = scope.spawn(|| {
            let mut transaction = db
                .begin_transaction(crate::ConcurrentTransactionOptions::default())
                .unwrap();
            stage_district(&mut transaction, lines..lines + DISTRICT_LINES);
            transaction.commit().map(|_| ())
        });
        pause.wait_until_drain_is_held();
        for line in [0, lines - 1] {
            let rows = db.query_sql(&line_query(line)).unwrap().rows.into_rows();
            assert_eq!(rows.len(), 1, "line {line}");
            assert_eq!(
                rows[0].get("ol_i_id"),
                Some(&Value::Int(line * 7_919 % 100_000))
            );
        }
        assert_line_absent(db.query_sql(&line_query(lines)).unwrap().rows, lines);
        let writer = scope.spawn(|| {
            for id in 0..TICKS {
                db.query_sql_with_params(
                    "INSERT INTO ticks (id, payload) VALUES ($1, $2)",
                    &[Value::Int(id), Value::String(format!("tick-{id}"))],
                )
                .unwrap_or_else(|error| panic!("tick {id} failed: {error}"));
            }
        });
        pause.release();
        district
            .join()
            .unwrap()
            .unwrap_or_else(|error| panic!("district commit failed: {error}"));
        writer.join().unwrap();
    });
    let report = db.automatic_checkpoint_report().unwrap().unwrap();
    assert!(report.completed_checkpoints > before, "{report:?}");
    assert_eq!(report.failed_attempts, 0, "{report:?}");
    let count = db
        .query_sql("SELECT COUNT(*) AS n FROM ticks")
        .unwrap()
        .rows
        .into_rows();
    assert_eq!(count[0].get("n"), Some(&Value::Int(TICKS)));
    drop(db);
    let mut reopened = Database::open_with_config(&fixture.0, config()).unwrap();
    let lines = lines + DISTRICT_LINES;
    assert_order_lines(&mut reopened, lines);
    reopened.checkpoint().unwrap();
    assert_order_line_totals(&mut reopened, lines);
}