ctb_formats_dcdata/support/
layout.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Schema parser and validator for the global graph layout partition table.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::report::ValidationReport;
30
31pub use ctb_storage_minimal::global_graph_layout::{
32    FORMAT_REGION_END, FORMAT_REGION_START, SHORT_DC_REGION_END,
33    SHORT_DC_REGION_START, UNICODE_REGION_END, UNICODE_REGION_START,
34};
35
36/// A validated row from `global-graph-layout.csv`.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct ParsedLayoutRow {
39    pub first_id: u128,
40    pub last_id: u128,
41    pub count: u128,
42    pub block_name: String,
43    pub description: String,
44    pub line_number: usize,
45}
46
47/// Validates the global graph layout CSV table.
48pub fn validate_layout_table(
49    csv_bytes: &[u8],
50    file_path: &str,
51    report: &mut ValidationReport,
52) -> Vec<ParsedLayoutRow> {
53    let vec_bytes = csv_bytes.to_vec();
54    let table = match csv_tools::parse_csv_reader(
55        &vec_bytes,
56        csv_tools::CsvParseOptions {
57            has_header: true,
58            flexible: true,
59            ..Default::default()
60        },
61    ) {
62        Ok(t) => t,
63        Err(e) => {
64            report.add_error(
65                file_path,
66                None,
67                None,
68                format!("Failed to parse CSV: {e}"),
69                Some("Check CSV syntax and quoting"),
70            );
71            return Vec::new();
72        }
73    };
74
75    let mut rows = Vec::new();
76    let mut expected_next_first: Option<u128> = Some(0);
77
78    if let Some(header) = table.header() {
79        if header.len() != 5 {
80            report.add_error(
81                file_path,
82                Some(1),
83                None,
84                format!(
85                    "CSV header has {} columns, expected 5 columns",
86                    header.len()
87                ),
88                Some("Ensure CSV header has exactly 5 columns matching schema"),
89            );
90        }
91    }
92
93    for i in 0..table.row_count() {
94        let line_no = i.saturating_add(2); // 1-indexed header + data row
95
96        if let Some(row_slice) = table.row(i) {
97            if row_slice.iter().all(|s| s.trim().is_empty()) {
98                continue;
99            }
100            if row_slice.len() != 5 {
101                report.add_error(
102                    file_path,
103                    Some(line_no),
104                    None,
105                    format!(
106                        "Row has {} columns, expected 5 columns (mismatched field count)",
107                        row_slice.len()
108                    ),
109                    Some("Check for unquoted commas, missing commas, or extra columns to avoid misaligned data"),
110                );
111            }
112        }
113
114        let get_str = |col: usize| -> String {
115            match table.cell(i, col) {
116                Some(s) => s.trim().to_string(),
117                None => String::new(),
118            }
119        };
120
121        let first_str = get_str(0);
122        let last_str = get_str(1);
123        let count_str = get_str(2);
124        let block_name = get_str(3);
125        let description = get_str(4);
126
127        if first_str.is_empty() && last_str.is_empty() && block_name.is_empty()
128        {
129            continue;
130        }
131
132        let first_id = if let Ok(val) = first_str.parse::<u128>() {
133            val
134        } else {
135            report.add_error(
136                file_path,
137                Some(line_no),
138                Some("First ID in region"),
139                format!("Invalid integer for First ID: '{first_str}'"),
140                Some("Must be a non-negative integer"),
141            );
142            continue;
143        };
144
145        let last_id = if let Ok(val) = last_str.parse::<u128>() {
146            val
147        } else {
148            report.add_error(
149                file_path,
150                Some(line_no),
151                Some("Last ID in region"),
152                format!("Invalid integer for Last ID: '{last_str}'"),
153                Some("Must be a non-negative integer"),
154            );
155            continue;
156        };
157
158        let count = if let Ok(val) = count_str.parse::<u128>() {
159            val
160        } else {
161            report.add_error(
162                file_path,
163                Some(line_no),
164                Some("Count of IDs in region"),
165                format!("Invalid integer for Count: '{count_str}'"),
166                Some("Must be a positive integer"),
167            );
168            continue;
169        };
170
171        if block_name.is_empty() {
172            report.add_error(
173                file_path,
174                Some(line_no),
175                Some("Block name"),
176                "Block name cannot be empty",
177                Some(
178                    "Provide a descriptive name for the graph partition region",
179                ),
180            );
181        }
182
183        if last_id < first_id {
184            report.add_error(
185                file_path,
186                Some(line_no),
187                Some("Last ID in region"),
188                format!("Last ID ({last_id}) must be >= First ID ({first_id})"),
189                Some("Correct range bounds"),
190            );
191        }
192
193        let computed_count = last_id.saturating_sub(first_id).saturating_add(1);
194        if count != computed_count {
195            report.add_error(
196                file_path,
197                Some(line_no),
198                Some("Count of IDs in region"),
199                format!(
200                    "Region Count ({count}) does not match Last ID - First ID + 1 ({computed_count})"
201                ),
202                Some("Update Count column to match the arithmetic span"),
203            );
204        }
205
206        if let Some(expected_first) = expected_next_first {
207            if first_id != expected_first {
208                report.add_error(
209                    file_path,
210                    Some(line_no),
211                    Some("First ID in region"),
212                    format!(
213                        "Region gap or overlap detected: expected First ID {expected_first}, but found {first_id}"
214                    ),
215                    Some("Ensure regions are contiguous with no gaps or overlaps"),
216                );
217            }
218        }
219
220        expected_next_first = Some(last_id.saturating_add(1));
221
222        rows.push(ParsedLayoutRow {
223            first_id,
224            last_id,
225            count,
226            block_name,
227            description,
228            line_number: line_no,
229        });
230    }
231
232    // Verify key landmark regions
233    if let Some(unicode_row) = rows.first() {
234        if unicode_row.first_id != UNICODE_REGION_START
235            || unicode_row.last_id != UNICODE_REGION_END
236        {
237            report.add_error(
238                file_path,
239                Some(unicode_row.line_number),
240                Some("Block name"),
241                format!(
242                    "Unicode region bounds mismatch: expected 0..={UNICODE_REGION_END}, found {}..={}",
243                    unicode_row.first_id, unicode_row.last_id
244                ),
245                Some("Restore canonical Unicode bounds"),
246            );
247        }
248    }
249
250    if let Some(dc_row) = rows.get(1) {
251        if dc_row.first_id != SHORT_DC_REGION_START
252            || dc_row.last_id != SHORT_DC_REGION_END
253        {
254            report.add_error(
255                file_path,
256                Some(dc_row.line_number),
257                Some("Block name"),
258                format!(
259                    "Dc region bounds mismatch: expected {SHORT_DC_REGION_START}..={SHORT_DC_REGION_END}, found {}..={}",
260                    dc_row.first_id, dc_row.last_id
261                ),
262                Some("Restore canonical Dc region bounds"),
263            );
264        }
265    }
266
267    if let Some(fmt_row) = rows.get(2) {
268        if fmt_row.first_id != FORMAT_REGION_START
269            || fmt_row.last_id != FORMAT_REGION_END
270        {
271            report.add_error(
272                file_path,
273                Some(fmt_row.line_number),
274                Some("Block name"),
275                format!(
276                    "Format region bounds mismatch: expected {FORMAT_REGION_START}..={FORMAT_REGION_END}, found {}..={}",
277                    fmt_row.first_id, fmt_row.last_id
278                ),
279                Some("Restore canonical Formats region bounds"),
280            );
281        }
282    }
283
284    rows
285}