hawdb-storage 0.37.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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
// 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.

//! Deterministic copy-on-write mutation planning for relational row pages.

use super::{
    encoding::encoded_row_len, ImmutableRelationalRowPage, RelationalRowPageEntry,
    RelationalRowPageError, RelationalRowPageId, RelationalRowPageLimits,
    RelationalRowPagePublicationConfig, RelationalRowPagePublicationError,
    RelationalRowPageRootDescriptor, RelationalRowPageRootReader, RelationalRowPageTableDelta,
};
use crate::relational::{
    ordered_key::encode_ordered_relational_key, RelationalKey, RelationalRow, RelationalRowChange,
    RelationalRowChangeCaptureLimits,
};
use hawdb_integrity::Sha256Digest;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::num::{NonZeroU32, NonZeroU64};

#[derive(Debug)]
pub enum RelationalRowPageMutationError {
    Admission(String),
    Corrupt(String),
    Publication(RelationalRowPagePublicationError),
    Page(RelationalRowPageError),
}

impl fmt::Display for RelationalRowPageMutationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Admission(message) => {
                write!(
                    formatter,
                    "relational row-page mutation admission failed: {message}"
                )
            }
            Self::Corrupt(message) => {
                write!(formatter, "corrupt relational row-page mutation: {message}")
            }
            Self::Publication(error) => write!(formatter, "{error}"),
            Self::Page(error) => write!(formatter, "{error}"),
        }
    }
}

impl std::error::Error for RelationalRowPageMutationError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Publication(error) => Some(error),
            Self::Page(error) => Some(error),
            Self::Admission(_) | Self::Corrupt(_) => None,
        }
    }
}

impl From<RelationalRowPagePublicationError> for RelationalRowPageMutationError {
    fn from(error: RelationalRowPagePublicationError) -> Self {
        Self::Publication(error)
    }
}

impl From<RelationalRowPageError> for RelationalRowPageMutationError {
    fn from(error: RelationalRowPageError) -> Self {
        Self::Page(error)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RelationalRowPageIdAllocator {
    next_page_id: NonZeroU64,
}

impl RelationalRowPageIdAllocator {
    pub const fn new(next_page_id: NonZeroU64) -> Self {
        Self { next_page_id }
    }

    pub const fn next_page_id(self) -> NonZeroU64 {
        self.next_page_id
    }

    pub fn allocate(&mut self) -> Result<RelationalRowPageId, RelationalRowPageMutationError> {
        let allocated = self.next_page_id;
        let next_page_id = allocated
            .get()
            .checked_add(1)
            .and_then(NonZeroU64::new)
            .ok_or_else(|| {
                RelationalRowPageMutationError::Admission(
                    "relational row-page id allocator is exhausted".to_string(),
                )
            })?;
        self.next_page_id = next_page_id;
        Ok(RelationalRowPageId::new(allocated))
    }

    fn peek(&self) -> RelationalRowPageId {
        RelationalRowPageId::new(self.next_page_id)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelationalRowPageMutationPlan {
    pub delta: RelationalRowPageTableDelta,
    pub distinct_changes: usize,
    pub base_pages_read: usize,
    pub dirty_pages: usize,
    pub deleted_pages: usize,
    pub split_pages: usize,
}

pub struct RelationalRowPageMutationPlanner<'a> {
    base: Option<&'a RelationalRowPageRootReader>,
    generation: u64,
    source_commit_epoch: u64,
    config: RelationalRowPagePublicationConfig,
}

impl<'a> RelationalRowPageMutationPlanner<'a> {
    pub fn new(
        base: Option<&'a RelationalRowPageRootReader>,
        generation: u64,
        source_commit_epoch: u64,
        config: RelationalRowPagePublicationConfig,
    ) -> Result<Self, RelationalRowPageMutationError> {
        if generation == 0 || source_commit_epoch == 0 {
            return Err(RelationalRowPageMutationError::Admission(format!(
                "row-page mutation generation and epoch must be non-zero, got {generation}/{source_commit_epoch}"
            )));
        }
        if let Some(base) = base {
            if generation <= base.manifest().generation {
                return Err(RelationalRowPageMutationError::Admission(format!(
                    "row-page mutation generation {generation} does not follow base generation {}",
                    base.manifest().generation
                )));
            }
            if source_commit_epoch < base.manifest().source_commit_epoch {
                return Err(RelationalRowPageMutationError::Admission(format!(
                    "row-page mutation epoch {source_commit_epoch} precedes base epoch {}",
                    base.manifest().source_commit_epoch
                )));
            }
        }
        Ok(Self {
            base,
            generation,
            source_commit_epoch,
            config,
        })
    }

    pub fn plan_table(
        &self,
        table: &str,
        schema_digest: Sha256Digest,
        column_count: usize,
        changes: impl IntoIterator<Item = RelationalRowChange>,
    ) -> Result<RelationalRowPageMutationPlan, RelationalRowPageMutationError> {
        if table.is_empty() || table.len() > self.config.max_table_name_bytes.get() {
            return Err(RelationalRowPageMutationError::Admission(format!(
                "row-page mutation table name contains {} bytes, outside admitted range",
                table.len()
            )));
        }
        if column_count == 0 || column_count > self.config.page_limits.max_columns.get() {
            return Err(RelationalRowPageMutationError::Admission(format!(
                "row-page mutation column count {column_count} is outside admitted range"
            )));
        }

        let base_table = self.base.and_then(|base| {
            base.manifest()
                .tables
                .binary_search_by(|candidate| candidate.table.as_str().cmp(table))
                .ok()
                .map(|index| &base.manifest().tables[index])
        });
        if let Some(base_table) = base_table
            && base_table.schema_digest != schema_digest
        {
            return Err(RelationalRowPageMutationError::Admission(format!(
                "table {table} schema digest differs from its published row root"
            )));
        }
        let mut allocator = RelationalRowPageIdAllocator::new(base_table.map_or_else(
            || NonZeroU64::new(1).expect("initial row-page id is non-zero"),
            |root| root.next_page_id,
        ));
        let changes = collect_changes(table, changes, self.config)?;
        let distinct_changes = changes.len();
        let mut groups: BTreeMap<Vec<u8>, MutationGroup> = BTreeMap::new();
        let mut bootstrap_changes = BTreeMap::new();

        if base_table.is_some_and(|root| root.page_count > 0) {
            let base = self.base.expect("base table implies a base reader");
            let mut current_descriptor: Option<RelationalRowPageRootDescriptor> = None;
            for (encoded_key, change) in changes {
                let descriptor = match current_descriptor.as_ref().filter(|descriptor| {
                    descriptor.upper_bound.as_slice() >= encoded_key.as_slice()
                }) {
                    Some(descriptor) => descriptor.clone(),
                    None => base
                        .find_table_page_descriptor(table, &change.primary_key)?
                        .ok_or_else(|| {
                            RelationalRowPageMutationError::Corrupt(format!(
                                "table {table} has a non-empty root without a target leaf"
                            ))
                        })?,
                };
                current_descriptor = Some(descriptor.clone());
                groups
                    .entry(descriptor.lower_bound.clone())
                    .or_insert_with(|| MutationGroup {
                        descriptor,
                        changes: BTreeMap::new(),
                    })
                    .changes
                    .insert(encoded_key, change);
            }
        } else {
            bootstrap_changes = changes;
        }

        let mut dirty_pages = Vec::new();
        let mut dirty_bytes = 0u64;
        let mut deleted_page_ids = BTreeSet::new();
        let mut base_pages_read = 0usize;
        let mut split_pages = 0usize;
        for group in groups.into_values() {
            let base = self.base.expect("mutation group implies a base reader");
            let page = base.read_page(&group.descriptor)?;
            base_pages_read = base_pages_read.checked_add(1).ok_or_else(|| {
                RelationalRowPageMutationError::Admission(
                    "row-page mutation read count overflow".to_string(),
                )
            })?;
            validate_base_page(&page, &group.descriptor, schema_digest, column_count)?;
            let original_page_id = page.page_id;
            let (rows, changed) = apply_changes(page.rows, group.changes)?;
            if !changed {
                continue;
            }
            if rows.is_empty() {
                deleted_page_ids.insert(original_page_id);
                continue;
            }
            let first = dirty_pages.len();
            self.pack_rows(
                schema_digest,
                column_count,
                Some(original_page_id),
                &mut allocator,
                rows,
                |page| {
                    let bytes = charge_dirty_page(dirty_bytes, &page, self.config)?;
                    admit_dirty_pages(dirty_pages.len().saturating_add(1), bytes, self.config)?;
                    dirty_bytes = bytes;
                    dirty_pages.push(page);
                    Ok(())
                },
            )?;
            let written = dirty_pages.len() - first;
            split_pages = split_pages
                .checked_add(written.saturating_sub(1))
                .ok_or_else(|| {
                    RelationalRowPageMutationError::Admission(
                        "row-page split count overflow".to_string(),
                    )
                })?;
        }

        if !bootstrap_changes.is_empty() {
            let (rows, _) = apply_changes(Vec::new(), bootstrap_changes)?;
            self.pack_rows(
                schema_digest,
                column_count,
                None,
                &mut allocator,
                rows,
                |page| {
                    let bytes = charge_dirty_page(dirty_bytes, &page, self.config)?;
                    admit_dirty_pages(dirty_pages.len().saturating_add(1), bytes, self.config)?;
                    dirty_bytes = bytes;
                    dirty_pages.push(page);
                    Ok(())
                },
            )?;
            split_pages = dirty_pages.len().saturating_sub(1);
        }

        dirty_pages.sort_by(|left, right| {
            let left = encode_ordered_relational_key(&left.rows[0].primary_key)
                .expect("planned row-page key was validated");
            let right = encode_ordered_relational_key(&right.rows[0].primary_key)
                .expect("planned row-page key was validated");
            left.cmp(&right)
        });
        let deleted_pages = deleted_page_ids.len();
        let dirty_page_count = dirty_pages.len();
        Ok(RelationalRowPageMutationPlan {
            delta: RelationalRowPageTableDelta {
                replaces_base: false,
                last_row_id: self
                    .base
                    .and_then(|base| base.table_root(table).ok())
                    .map_or(0, |root| root.last_row_id),
                table: table.to_string(),
                schema: None,
                schema_digest,
                column_count: NonZeroU32::new(u32::try_from(column_count).map_err(|_| {
                    RelationalRowPageMutationError::Admission(format!(
                        "table {table} column count does not fit u32"
                    ))
                })?)
                .ok_or_else(|| {
                    RelationalRowPageMutationError::Admission(format!(
                        "table {table} has no columns"
                    ))
                })?,
                next_page_id: allocator.next_page_id(),
                dirty_pages,
                deleted_page_ids: deleted_page_ids.into_iter().collect(),
            },
            distinct_changes,
            base_pages_read,
            dirty_pages: dirty_page_count,
            deleted_pages,
            split_pages,
        })
    }

    fn pack_rows(
        &self,
        schema_digest: Sha256Digest,
        column_count: usize,
        first_page_id: Option<RelationalRowPageId>,
        allocator: &mut RelationalRowPageIdAllocator,
        rows: Vec<RelationalRowPageEntry>,
        mut emit: impl FnMut(ImmutableRelationalRowPage) -> Result<(), RelationalRowPageMutationError>,
    ) -> Result<(), RelationalRowPageMutationError> {
        let mut state = PagePackState::new(
            self.generation,
            self.source_commit_epoch,
            schema_digest,
            column_count,
            first_page_id,
            self.config,
        );
        for row in rows {
            state.push(row, allocator, &mut emit)?;
        }
        state.finish(allocator, emit)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelationalRowPageBootstrapReport {
    pub rows: usize,
    pub pages: usize,
    pub peak_buffered_rows: usize,
    pub next_page_id: NonZeroU64,
}

pub struct RelationalRowPageBootstrap {
    state: PagePackState,
    allocator: RelationalRowPageIdAllocator,
    failed: bool,
}

impl RelationalRowPageBootstrap {
    pub fn new(
        generation: u64,
        source_commit_epoch: u64,
        schema_digest: Sha256Digest,
        column_count: usize,
        next_page_id: NonZeroU64,
        config: RelationalRowPagePublicationConfig,
    ) -> Result<Self, RelationalRowPageMutationError> {
        if generation == 0 || source_commit_epoch == 0 {
            return Err(RelationalRowPageMutationError::Admission(format!(
                "row-page bootstrap generation and epoch must be non-zero, got {generation}/{source_commit_epoch}"
            )));
        }
        if column_count == 0 || column_count > config.page_limits.max_columns.get() {
            return Err(RelationalRowPageMutationError::Admission(format!(
                "row-page bootstrap column count {column_count} is outside admitted range"
            )));
        }
        Ok(Self {
            state: PagePackState::new(
                generation,
                source_commit_epoch,
                schema_digest,
                column_count,
                None,
                config,
            ),
            allocator: RelationalRowPageIdAllocator::new(next_page_id),
            failed: false,
        })
    }

    pub fn push(
        &mut self,
        entry: RelationalRowPageEntry,
        emit: impl FnMut(ImmutableRelationalRowPage) -> Result<(), RelationalRowPageMutationError>,
    ) -> Result<(), RelationalRowPageMutationError> {
        if self.failed {
            return Err(RelationalRowPageMutationError::Admission(
                "row-page bootstrap cannot continue after a previous failure".to_string(),
            ));
        }
        self.state
            .push(entry, &mut self.allocator, emit)
            .inspect_err(|_| self.failed = true)
    }

    pub fn finish(
        mut self,
        emit: impl FnMut(ImmutableRelationalRowPage) -> Result<(), RelationalRowPageMutationError>,
    ) -> Result<RelationalRowPageBootstrapReport, RelationalRowPageMutationError> {
        if self.failed {
            return Err(RelationalRowPageMutationError::Admission(
                "row-page bootstrap cannot finish after a previous failure".to_string(),
            ));
        }
        self.state.finish(&mut self.allocator, emit)?;
        Ok(RelationalRowPageBootstrapReport {
            rows: self.state.emitted_rows,
            pages: self.state.emitted_pages,
            peak_buffered_rows: self.state.peak_buffered_rows,
            next_page_id: self.allocator.next_page_id(),
        })
    }
}

#[derive(Debug)]
struct PlannedChange {
    primary_key: RelationalKey,
    row: Option<RelationalRow>,
    charged_bytes: usize,
}

struct MutationGroup {
    descriptor: RelationalRowPageRootDescriptor,
    changes: BTreeMap<Vec<u8>, PlannedChange>,
}

fn collect_changes(
    table: &str,
    changes: impl IntoIterator<Item = RelationalRowChange>,
    config: RelationalRowPagePublicationConfig,
) -> Result<BTreeMap<Vec<u8>, PlannedChange>, RelationalRowPageMutationError> {
    collect_changes_with_limits(
        table,
        changes,
        config,
        RelationalRowChangeCaptureLimits::default(),
    )
}

fn collect_changes_with_limits(
    table: &str,
    changes: impl IntoIterator<Item = RelationalRowChange>,
    config: RelationalRowPagePublicationConfig,
    limits: RelationalRowChangeCaptureLimits,
) -> Result<BTreeMap<Vec<u8>, PlannedChange>, RelationalRowPageMutationError> {
    let mut collected: BTreeMap<Vec<u8>, PlannedChange> = BTreeMap::new();
    let mut charged_bytes = 0usize;
    for change in changes {
        if change.table != table {
            return Err(RelationalRowPageMutationError::Admission(format!(
                "row-page mutation for table {table} contains change for {}",
                change.table
            )));
        }
        let encoded_key = encode_ordered_relational_key(&change.primary_key).map_err(|error| {
            RelationalRowPageMutationError::Admission(format!(
                "row-page mutation primary key cannot be encoded: {error}"
            ))
        })?;
        if encoded_key.len() > config.page_limits.max_key_bytes.get() {
            return Err(RelationalRowPageMutationError::Admission(format!(
                "row-page mutation primary key contains {} bytes, exceeding limit {}",
                encoded_key.len(),
                config.page_limits.max_key_bytes
            )));
        }
        if !collected.contains_key(&encoded_key) && collected.len() >= limits.max_entries.get() {
            return Err(RelationalRowPageMutationError::Admission(format!(
                "row-page mutation exceeds change limit {}",
                limits.max_entries
            )));
        }
        let change_bytes = crate::relational::estimated_row_change_encoding_bytes(&change)
            .ok_or_else(|| {
                RelationalRowPageMutationError::Admission(
                    "row-page mutation change-byte accounting overflow".to_string(),
                )
            })?;
        let replaced_bytes = collected
            .get(&encoded_key)
            .map_or(0, |existing| existing.charged_bytes);
        let next_bytes = charged_bytes
            .checked_sub(replaced_bytes)
            .and_then(|bytes| bytes.checked_add(change_bytes))
            .ok_or_else(|| {
                RelationalRowPageMutationError::Admission(
                    "row-page mutation change-byte accounting overflow".to_string(),
                )
            })?;
        if next_bytes > limits.max_bytes.get() {
            return Err(RelationalRowPageMutationError::Admission(format!(
                "row-page mutation changes use {next_bytes} bytes, exceeding limit {}",
                limits.max_bytes
            )));
        }
        collected.insert(
            encoded_key,
            PlannedChange {
                primary_key: change.primary_key,
                row: change.row,
                charged_bytes: change_bytes,
            },
        );
        charged_bytes = next_bytes;
    }
    Ok(collected)
}

fn apply_changes(
    rows: Vec<RelationalRowPageEntry>,
    changes: BTreeMap<Vec<u8>, PlannedChange>,
) -> Result<(Vec<RelationalRowPageEntry>, bool), RelationalRowPageMutationError> {
    let mut merged = BTreeMap::new();
    for entry in rows {
        let encoded_key = encode_ordered_relational_key(&entry.primary_key).map_err(|error| {
            RelationalRowPageMutationError::Corrupt(format!(
                "published row-page primary key cannot be encoded: {error}"
            ))
        })?;
        if merged.insert(encoded_key, entry).is_some() {
            return Err(RelationalRowPageMutationError::Corrupt(
                "published row page contains duplicate primary keys".to_string(),
            ));
        }
    }
    let mut changed = false;
    for (encoded_key, change) in changes {
        match change.row {
            Some(row) => {
                let entry = RelationalRowPageEntry {
                    primary_key: change.primary_key,
                    row,
                };
                changed |= merged.get(&encoded_key) != Some(&entry);
                merged.insert(encoded_key, entry);
            }
            None => {
                changed |= merged.remove(&encoded_key).is_some();
            }
        }
    }
    Ok((merged.into_values().collect(), changed))
}

fn validate_base_page(
    page: &ImmutableRelationalRowPage,
    descriptor: &RelationalRowPageRootDescriptor,
    schema_digest: Sha256Digest,
    column_count: usize,
) -> Result<(), RelationalRowPageMutationError> {
    if page.page_id != descriptor.logical_page_id
        || page.schema_digest != schema_digest
        || page.column_count != column_count
    {
        return Err(RelationalRowPageMutationError::Corrupt(format!(
            "row-page {} does not match its table mutation contract",
            descriptor.logical_page_id.get()
        )));
    }
    Ok(())
}

/// Admits `pages` dirty pages whose encoded lengths total `bytes`.
///
/// The byte budget charges encoded page bytes, not the fixed slot each v1
/// page occupies in the page artifact (#1593). It bounds the encoded page
/// payload a publication writes before its fsync; it never bounded memory.
/// Until v2 packs pages by length, physical page-artifact writes can exceed
/// the charge by up to the slot size over the encoded length (about 20x for
/// narrow rows).
fn admit_dirty_pages(
    pages: usize,
    bytes: u64,
    config: RelationalRowPagePublicationConfig,
) -> Result<(), RelationalRowPageMutationError> {
    if pages > config.max_dirty_pages.get() {
        return Err(RelationalRowPageMutationError::Admission(format!(
            "row-page mutation emits {pages} dirty pages, exceeding limit {}",
            config.max_dirty_pages
        )));
    }
    if bytes > config.max_dirty_bytes.get() {
        return Err(RelationalRowPageMutationError::Admission(format!(
            "row-page mutation reserves {bytes} encoded dirty bytes, exceeding limit {}",
            config.max_dirty_bytes
        )));
    }
    Ok(())
}

/// Running size of a pending page, mirroring every size check of the page
/// codec. With `n` rows, encoded keys `k_i`, encoded rows `r_i` and running
/// payload totals `K_i`, `R_i`, the codec accepts the page exactly when each
/// row fits the key, row and `u32` offset limits and
/// `header + k_0 + 16 n + max_i (k_i + K_i + R_i) <= max_page_bytes`. The
/// `i = n` term is the final page length; earlier terms are the codec's
/// per-row projections, which use the complete directory length.
#[derive(Debug, Clone, Copy, Default)]
struct PendingPageSize {
    lower_key_bytes: usize,
    key_bytes: usize,
    row_bytes: usize,
    max_row_extent: usize,
}

impl PendingPageSize {
    /// Returns the size after appending one row as row number `rows`, or
    /// `None` when the codec would reject the page or the row, or when a page
    /// that already holds a row would grow past `target_page_bytes`.
    fn with_row(
        self,
        rows: usize,
        key_len: usize,
        row_len: Option<usize>,
        limits: RelationalRowPageLimits,
        target_page_bytes: usize,
    ) -> Option<Self> {
        let row_len = row_len?;
        if rows > limits.max_rows.get()
            || key_len > limits.max_key_bytes.get()
            || row_len > limits.max_row_bytes.get()
            || u32::try_from(rows).is_err()
            || u32::try_from(self.key_bytes).is_err()
            || u32::try_from(key_len).is_err()
            || u32::try_from(self.row_bytes).is_err()
            || u32::try_from(row_len).is_err()
            || limits.max_page_bytes.get() < super::ROW_PAGE_HEADER_BYTES
        {
            return None;
        }
        let lower_key_bytes = if rows == 1 {
            key_len
        } else {
            self.lower_key_bytes
        };
        let key_bytes = self.key_bytes.checked_add(key_len)?;
        let row_bytes = self.row_bytes.checked_add(row_len)?;
        let row_extent = key_len.checked_add(key_bytes)?.checked_add(row_bytes)?;
        let max_row_extent = self.max_row_extent.max(row_extent);
        let directory_bytes = rows.checked_mul(super::ROW_SLOT_BYTES)?;
        u32::try_from(directory_bytes).ok()?;
        let page_bytes = super::ROW_PAGE_HEADER_BYTES
            .checked_add(lower_key_bytes)?
            .checked_add(directory_bytes)?
            .checked_add(max_row_extent)?;
        // The `i = n` projection is the exact encoded page length.
        let encoded_bytes = super::ROW_PAGE_HEADER_BYTES
            .checked_add(lower_key_bytes)?
            .checked_add(directory_bytes)?
            .checked_add(row_extent)?;
        if rows > 1 && encoded_bytes > target_page_bytes {
            return None;
        }
        (page_bytes <= limits.max_page_bytes.get()).then_some(Self {
            lower_key_bytes,
            key_bytes,
            row_bytes,
            max_row_extent,
        })
    }
}

/// Adds one page's encoded length to a running dirty-byte charge.
fn charge_dirty_page(
    charged: u64,
    page: &ImmutableRelationalRowPage,
    config: RelationalRowPagePublicationConfig,
) -> Result<u64, RelationalRowPageMutationError> {
    charged
        .checked_add(page.encoded_len(config.page_limits)?)
        .ok_or_else(|| {
            RelationalRowPageMutationError::Admission(
                "row-page mutation dirty-byte reservation overflow".to_string(),
            )
        })
}

struct PagePackState {
    generation: u64,
    source_commit_epoch: u64,
    schema_digest: Sha256Digest,
    column_count: usize,
    first_page_id: Option<RelationalRowPageId>,
    config: RelationalRowPagePublicationConfig,
    pending: Option<ImmutableRelationalRowPage>,
    pending_size: PendingPageSize,
    previous_key: Option<Vec<u8>>,
    emitted_rows: usize,
    emitted_pages: usize,
    emitted_bytes: u64,
    peak_buffered_rows: usize,
}

impl PagePackState {
    fn new(
        generation: u64,
        source_commit_epoch: u64,
        schema_digest: Sha256Digest,
        column_count: usize,
        first_page_id: Option<RelationalRowPageId>,
        config: RelationalRowPagePublicationConfig,
    ) -> Self {
        Self {
            generation,
            source_commit_epoch,
            schema_digest,
            column_count,
            first_page_id,
            config,
            pending: None,
            pending_size: PendingPageSize::default(),
            previous_key: None,
            emitted_rows: 0,
            emitted_pages: 0,
            emitted_bytes: 0,
            peak_buffered_rows: 0,
        }
    }

    fn push(
        &mut self,
        entry: RelationalRowPageEntry,
        allocator: &mut RelationalRowPageIdAllocator,
        mut emit: impl FnMut(ImmutableRelationalRowPage) -> Result<(), RelationalRowPageMutationError>,
    ) -> Result<(), RelationalRowPageMutationError> {
        let encoded_key = encode_ordered_relational_key(&entry.primary_key).map_err(|error| {
            RelationalRowPageMutationError::Admission(format!(
                "row-page pack key cannot be encoded: {error}"
            ))
        })?;
        if self
            .previous_key
            .as_ref()
            .is_some_and(|previous| previous.as_slice() >= encoded_key.as_slice())
        {
            return Err(RelationalRowPageMutationError::Admission(
                "row-page pack input is not strictly ordered".to_string(),
            ));
        }
        // Size the candidate arithmetically instead of encoding the whole
        // page per row, which made packing quadratic in the rows per page.
        // `PendingPageSize` admits exactly the pages `encode` accepts. A
        // single-row page that does not fit is encoded once so the caller
        // receives the codec's own error.
        let limits = self.config.page_limits;
        let page_admissible = self.generation != 0
            && self.source_commit_epoch != 0
            && self.column_count != 0
            && self.column_count <= limits.max_columns.get();
        let row_len = encoded_row_len(&entry.row, self.column_count, limits)
            .ok()
            .filter(|_| page_admissible);
        if self.pending.is_none() {
            self.pending = Some(self.empty_page(self.peek_page_id(allocator)));
            self.pending_size = PendingPageSize::default();
        }
        let pending = self.pending.as_mut().expect("pending page was initialized");
        pending.rows.push(entry);
        self.peak_buffered_rows = self.peak_buffered_rows.max(pending.rows.len());
        if let Some(size) = self.pending_size.with_row(
            pending.rows.len(),
            encoded_key.len(),
            row_len,
            limits,
            self.config.target_page_bytes.get(),
        ) {
            self.pending_size = size;
            self.previous_key = Some(encoded_key);
            return Ok(());
        }
        if pending.rows.len() == 1 {
            // The codec rejects this row in any page; report its error.
            pending.encode(self.config.page_limits)?;
            return Err(RelationalRowPageMutationError::Corrupt(
                "row-page pack sizing rejected a row the codec accepts".to_string(),
            ));
        }
        let entry = pending
            .rows
            .pop()
            .expect("candidate page contains the pushed row");
        self.emit_pending(allocator, &mut emit)?;
        let mut next = self.empty_page(self.peek_page_id(allocator));
        next.rows.push(entry);
        let Some(size) = PendingPageSize::default().with_row(
            1,
            encoded_key.len(),
            row_len,
            limits,
            self.config.target_page_bytes.get(),
        ) else {
            next.encode(self.config.page_limits)?;
            return Err(RelationalRowPageMutationError::Corrupt(
                "row-page pack sizing rejected a row the codec accepts".to_string(),
            ));
        };
        self.pending = Some(next);
        self.pending_size = size;
        self.previous_key = Some(encoded_key);
        Ok(())
    }

    fn finish(
        &mut self,
        allocator: &mut RelationalRowPageIdAllocator,
        emit: impl FnMut(ImmutableRelationalRowPage) -> Result<(), RelationalRowPageMutationError>,
    ) -> Result<(), RelationalRowPageMutationError> {
        if self.pending.is_some() {
            self.emit_pending(allocator, emit)?;
        }
        Ok(())
    }

    fn emit_pending(
        &mut self,
        allocator: &mut RelationalRowPageIdAllocator,
        mut emit: impl FnMut(ImmutableRelationalRowPage) -> Result<(), RelationalRowPageMutationError>,
    ) -> Result<(), RelationalRowPageMutationError> {
        let page = self.pending.take().expect("pending page exists");
        let mut next_allocator = *allocator;
        let mut next_first_page_id = self.first_page_id;
        let expected_page_id = next_first_page_id
            .take()
            .map_or_else(|| next_allocator.allocate(), Ok)?;
        if page.page_id != expected_page_id {
            return Err(RelationalRowPageMutationError::Corrupt(
                "row-page allocator changed while packing a page".to_string(),
            ));
        }
        let row_count = page.rows.len();
        let emitted_bytes = charge_dirty_page(self.emitted_bytes, &page, self.config)?;
        emit(page)?;
        *allocator = next_allocator;
        self.first_page_id = next_first_page_id;
        self.emitted_pages = self.emitted_pages.checked_add(1).ok_or_else(|| {
            RelationalRowPageMutationError::Admission(
                "row-page bootstrap page count overflow".to_string(),
            )
        })?;
        self.emitted_rows = self.emitted_rows.checked_add(row_count).ok_or_else(|| {
            RelationalRowPageMutationError::Admission(
                "row-page bootstrap row count overflow".to_string(),
            )
        })?;
        self.emitted_bytes = emitted_bytes;
        admit_dirty_pages(self.emitted_pages, self.emitted_bytes, self.config)
    }

    fn peek_page_id(&self, allocator: &RelationalRowPageIdAllocator) -> RelationalRowPageId {
        self.first_page_id.unwrap_or_else(|| allocator.peek())
    }

    fn empty_page(&self, page_id: RelationalRowPageId) -> ImmutableRelationalRowPage {
        ImmutableRelationalRowPage {
            generation: self.generation,
            source_commit_epoch: self.source_commit_epoch,
            page_id,
            schema_digest: self.schema_digest,
            column_count: self.column_count,
            rows: Vec::new(),
        }
    }
}

#[cfg(test)]
#[path = "mutation/tests.rs"]
mod tests;