#1952·xberg

bug(ocr): one junk cell in a split amount column drops the whole scanned table

Author: tobocop2Created Sep 29, 2026Updated Sep 29, 2026
LabelsbugP1

Description

On a scanned table, a right-aligned amount column still splits into two or three columns by digit width. #1886 was meant to stop this. Its fix keeps left-edge clustering and then folds adjacent tracks whose right edges coincide. The fold runs only when every token below the region's first row reads as a value: a number, or a nil dash, bracket or currency sign on its own.

On a scan, that condition rarely holds for a whole track:

  • One OCR junk token in the track stops the fold: a stray word piece, a letter misread, or a > or + mark.
  • The fold takes only the first row of the region as the header. A scanned header band often has two or three rows, so the header words of the second row count as data and stop the fold too.

The disjoint-column merge (#1649) then gets the split tracks. It correctly refuses to merge a track that holds a cell with a letter. #1950 makes that merge ignore rule marks and read the whole header band as header, and it keeps the letter refusal on purpose.

The leftover track has no header of its own and is mostly empty. The sparse-column check then rejects the whole table. No table is returned for the region, so every value in it is lost as table data; only the region's text remains. Only a debug trace records the rejection; no warning reaches the caller.

This check also stops the shaded-row normalisation from #1785 from helping. With normalize_shaded_rows on, OCR reads the shaded rows, but the fuller grid has the same split tracks with junk in them, and the table is rejected in the same way.

Steps to reproduce

  1. Apply the test patch below on main (92b4f956be). It adds two ignored tests to crates/xberg/src/ocr/processor/execution.rs. Both run an invented OCR word grid through the OCR table route: the region's cleaned grid, then the table cleanup. The grid has a label column (Item 1 to Item 12) and four right-aligned amount columns (Column A to Column D) with long values, short values and nil dashes.
  2. Run cargo test -p xberg --features full --lib -- split_amount_column_ --ignored.
  3. split_amount_column_with_one_junk_cell_keeps_the_table: the clean grid is kept with 5 columns (the control passes). When one nil dash in Column A reads as a, Column A splits into two columns and the table is dropped:
the table is dropped; its grid has 6 columns for 5 on the page: [["Item", "Column A", "", "Column B", "Column C", "Column D"], ["Item 1", "20,118", "", "31,902", "47,260", "58,431"], ..., ["Item 3", "", "85", "85", "85", "85"], ..., ["Item 6", "", "a", "-", "-", "-"], ...]
  1. split_amount_column_under_a_two_row_header_keeps_the_table: with a second header row (Year 1 to Year 4) and no junk, every amount column splits in two and the table is dropped (9 columns for 5). With #1950 applied, this test passes and the junk-cell test still fails.

Relevant files and configuration

  • crates/xberg/src/table_core.rs: column detection, the right-edge fold from #1886 and its value test, and the disjoint-column merge from #1649.
  • crates/xberg/src/pdf/table_reconstruct.rs: the sparse-column check that rejects the table.
  • crates/xberg/src/ocr/processor/execution.rs: the OCR table route, which skips a rejected table.
  • Tesseract OCR with table detection, on any scanned table. ocr.tesseract_config.preprocessing.normalize_shaded_rows makes it more frequent.

How it was found

Measuring a real-world scanned document (not shareable). A replay of the page's OCR words through the table route showed the split tracks, the fold refused on the second header row and on junk tokens, and the sparse-column check as the reason for the rejection.

Fix

The split happens in clustering, not in word-to-column assignment. Assignment stays on the tracks' left edges on purpose (see the #1886 commit) and is correct once the tracks fold. Two directions, not yet decided:

  • Make the fold hold on a scan. Read the header as the band of rows above the first amount row, as #1950 does for the merge. Then decide how many non-value tokens a track can hold and still fold, for example a lone junk token among many amounts with the same right edge.
  • Decide the policy for a sparse column without a header that is left over. Today the check drops the whole table. The alternative is to drop, or fold into its neighbour, only the offending column and keep the rest of the table. The negative controls for #1649 (an unnamed sparse column is rejected) and #1928 (a real sparse integer or amount column is not folded into the labels) pin the current behaviour, so a policy change must restate what those tests protect.

Related: #1886, #1649, #1928, #1950, #1785.

Test patch
diff
diff --git a/crates/xberg/src/ocr/processor/execution.rs b/crates/xberg/src/ocr/processor/execution.rs
index 368dc89f21..0242c1d364 100644
--- a/crates/xberg/src/ocr/processor/execution.rs
+++ b/crates/xberg/src/ocr/processor/execution.rs
@@ -3183,6 +3183,104 @@ mod tests {
         }
     }
 
+    /// An invented scanned table: a label column and four right-aligned amount columns. Each
+    /// amount column holds long values (`12,345`), short values (`85`) and nil dashes, so its
+    /// tokens' left edges fall into two groups by digit width, and the drift fold has to join
+    /// them back into one column. `junk` replaces the nil dash of `Item 6` in `Column A` with an
+    /// OCR misread that holds a letter. `second_header_row` adds a `Year N` label under each column
+    /// header, as a two-row scanned header band has.
+    #[cfg(feature = "pdf")]
+    fn split_amount_table_words(junk: Option<&str>, second_header_row: bool) -> Vec<crate::table_core::HocrWord> {
+        const CHAR_WIDTH: u32 = 15;
+        const HEIGHT: u32 = 25;
+        const RIGHT_EDGES: [u32; 4] = [700, 920, 1140, 1360];
+        let first_data_row = if second_header_row { 2 } else { 1 };
+        let row_top = |row: u32| 200 + row * 45;
+        let right_aligned = |right: u32, row: u32, text: &str| {
+            let width = CHAR_WIDTH * text.chars().count() as u32;
+            word_at(right - width, row_top(row), width, HEIGHT, text)
+        };
+        let mut words = vec![word_at(100, row_top(0), 60, HEIGHT, "Item")];
+        for (column, right) in ["A", "B", "C", "D"].into_iter().zip(RIGHT_EDGES) {
+            words.push(word_at(right - 115, row_top(0), 90, HEIGHT, "Column"));
+            words.push(right_aligned(right, 0, column));
+            if second_header_row {
+                words.push(word_at(right - 90, row_top(1), 60, HEIGHT, "Year"));
+                words.push(right_aligned(right, 1, &(right / 220 - 2).to_string()));
+            }
+        }
+        let long = [
+            "12,345", "20,118", "31,902", "47,260", "58,431", "63,077", "71,594", "86,213",
+        ];
+        for row in 1..=12u32 {
+            let top = row + first_data_row - 1;
+            words.push(word_at(100, row_top(top), 60, HEIGHT, "Item"));
+            words.push(word_at(170, row_top(top), CHAR_WIDTH * 2, HEIGHT, &row.to_string()));
+            for (column, right) in RIGHT_EDGES.into_iter().enumerate() {
+                let text = match row {
+                    3 => "85".to_string(),
+                    9 => "40".to_string(),
+                    6 if column == 0 => junk.unwrap_or("-").to_string(),
+                    6 | 12 => "-".to_string(),
+                    _ => long[(row as usize + column) % long.len()].to_string(),
+                };
+                words.push(right_aligned(right, top, &text));
+            }
+        }
+        words
+    }
+
+    /// The OCR table route on `words`: the region's cleaned grid, then the table cleanup that
+    /// keeps or rejects it.
+    #[cfg(feature = "pdf")]
+    fn ocr_route_table(words: &[crate::table_core::HocrWord]) -> (Vec<Vec<String>>, Option<Vec<Vec<String>>>) {
+        let (grid, _) = reconstruct_cleaned_table(words, &TesseractConfig::default());
+        let kept = post_process_table(grid.clone(), false, false);
+        (grid, kept)
+    }
+
+    #[cfg(feature = "pdf")]
+    #[test]
+    #[ignore = "reproduction: one OCR junk cell with a letter stops the right-aligned fold, the split amount track fails the sparse-column check, and the whole table is dropped"]
+    fn split_amount_column_with_one_junk_cell_keeps_the_table() {
+        let (clean_grid, clean) = ocr_route_table(&split_amount_table_words(None, false));
+        assert_eq!(
+            clean_grid[0].len(),
+            5,
+            "control: the fold joins every amount column: {clean_grid:?}"
+        );
+        assert!(clean.is_some(), "control: the clean table is kept: {clean_grid:?}");
+
+        let (grid, kept) = ocr_route_table(&split_amount_table_words(Some("a"), false));
+        assert_table_kept_with_every_value(&grid, kept);
+    }
+
+    #[cfg(feature = "pdf")]
+    #[test]
+    #[ignore = "reproduction: a second header row stops the right-aligned fold, the split amount track fails the sparse-column check, and the whole table is dropped"]
+    fn split_amount_column_under_a_two_row_header_keeps_the_table() {
+        let (grid, kept) = ocr_route_table(&split_amount_table_words(None, true));
+        assert_table_kept_with_every_value(&grid, kept);
+    }
+
+    #[cfg(feature = "pdf")]
+    fn assert_table_kept_with_every_value(grid: &[Vec<String>], kept: Option<Vec<Vec<String>>>) {
+        let kept = kept.unwrap_or_else(|| {
+            panic!(
+                "the table is dropped; its grid has {} columns for 5 on the page: {grid:?}",
+                grid[0].len()
+            )
+        });
+        for value in [
+            "12,345", "20,118", "31,902", "47,260", "58,431", "63,077", "71,594", "86,213", "85", "40",
+        ] {
+            assert!(
+                kept.iter().flatten().any(|cell| cell.contains(value)),
+                "value {value} is lost: {kept:?}"
+            );
+        }
+    }
+
     /// Builds a grid of `rows * cols` words starting at `(left, top)`, each
     /// cell `40x20` pixels, simulating one table's worth of OCR words.
     fn table_grid_words(left: u32, top: u32, rows: u32, cols: u32) -> Vec<crate::table_core::HocrWord> {