Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,13 @@ original plan and any signed-in notes stay out of the repository (see `.gitignor
`test/document.test.ts` checks they match. Every text the reader keeps goes through it, table
cells and captions included, and so does every text a renderer prints. Never add a visible
character to it, or a mark that turns text from right to left.
- **The PDF is read a second way only for table cells cut across pages** (`readSplitRows`), and
only after the plain reading failed. A cell left unfinished goes on at the top of the next page,
and of every page after until it is finished: a page that holds none of it is refused, so no
later row is read before it. Every line must be the exact expected text. Never loosen it to
compare words without their order, and never let it take up a cell again on the page it was left
on. A line two cells both hold may be read as either's; the ways tried are counted
(`SPLIT_ROW_TURNS`), and running out refuses the document.
- **A failed check says where, never what.** Verification details hold block IDs, page numbers,
counts and character codes (`charClass`: a letter or digit only as its kind). Never put a piece
of code text into a report, an error message or a log line.
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,14 @@ fit between the margins. One taller than a page is also made smaller, in proport
it is on one page (at most 8.96 inches of the 9.2 between the margins). Printed at full height it
was cut across two pages and the picture count failed.

**A table row taller than a page.** A row with so much text that it does not fit on one page is
cut across pages with its cells side by side: the first part of each cell on one page, the rest of
each on the next. All of the text is there, but page by page it does not come in the order of the
text, where one cell is whole before the next begins, and the PDF check used to refuse such a
document. It now reads such a row cell by cell across the page break. Nothing else passes that
way: a changed word, text left out, cells in the wrong order, or the rest of a cell printed
anywhere but at the top of the next page are refused as before.

**A numbered item inside a numbered item.** Its marker, such as "2.1.", is wider than the column
the documents gave a marker, so the PDF broke it in two with the final period on a line of its own.
When such an item began on the last line of a page, the period went to the next page and the PDF
Expand Down
41 changes: 37 additions & 4 deletions docs/adr/0003-documents.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,43 @@ The marker's column now takes the width of its marker, never less than before
always follows it. An item whose marker fitted prints exactly where it did. Word was never
affected: its items are a hanging indent with a tab.

Still open, found while testing this: a single table row taller than a whole page. Its cells
are split across pages side by side, so the PDF reads part of the first cell, then part of the
second, where the text has the whole first cell first. The check refuses it. No such row has been
met on a live page.
## A table row taller than a page

Added 1 December 2026. Found while testing the list markers. A row that is taller than a whole page
has to be cut, and it is cut with its cells side by side: one page prints the first part of the
first cell and then the first part of the second, and the next page prints the rest of each. Every
character of every cell is printed, in order. But the text has the first cell whole before the
second begins, so the PDF, read page by page, did not read back as the text, and the check refused
a document that was right. A cell that spans several rows and runs over a page reads the same way.

The row is printed as before. Shrinking it to fit a page would make a long cell unreadable, and
printing its cells one under the other would not be the table the page shows. What changed is the
reading (`readSplitRows` in `src/document/verify.ts`), and only as a second reading, after the
plain one has failed, so every document that passed before is judged exactly as it was:

- A table cell may be left unfinished where the next line begins the same table's next cell.
- What is left of it must go on at the top of the next page, before anything else of that page,
and so on every page after until it is finished. A page that holds none of it while it is
unfinished is refused, so no later row is ever read before the rest of an earlier one. (Cells are
set from the top, so the rest of a cut cell is always the first thing of its next page.) It is
never taken up again on the page it was left on, so a table on one page is read only in its own
order.
- Every printed line must be the very text expected at one of those places. Nothing may be left
over at the end, of the pages or of the text.
- The last lines of two cells may stand on one baseline and come back as one line; that is the end
of the one, a space, and the rest of the other.
- Two cells of a row can hold the same line, and such a line can be read as either's. The reader
follows each way, the plainest first, until one reads every page to the end. Every way obeys the
rules above, so this accepts nothing more; it only keeps a correct document from being refused
for the way a line was first read. The ways tried are counted (`SPLIT_ROW_TURNS`), and a document
that runs out of them is refused.

The report then carries `cellsAcrossPages`, a count. The check refuses the same PDF for a text
with a word changed, with text added to a cell, or with the cells the other way round, and
`test/fidelity.electron.cjs` holds it to that.

Rejected: comparing the words of a row without regard to order. That would pass a row whose
cells were printed in the wrong columns.

## Pagination

Expand Down
6 changes: 5 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,11 @@ The hard rules are tested by name. Search the tests for `rule_R` to see each one
than a page is printed smaller, in proportion, so that all of it is on one page
(`pictureScale`); Word follows. The verifier then reads the PDF text and the Word XML back and
compares them with the tree, setting aside only header rows repeated at the top of a
continuation page, and counts the pictures in both.
continuation page, and counts the pictures in both. A table row taller than a page is cut with
its cells side by side, so a page holds parts of several cells: when the plain reading fails,
the PDF is read once more with a cell allowed to be left unfinished and gone on with at the
top of each following page until it is finished, and nothing else allowed (`readSplitRows`;
the report says `cellsAcrossPages`).
- **What a failed check says.** The report names where the documents first differ: the page of
the PDF, the block (`blockAt`), and the two characters, a letter or a digit only as its kind
and anything else as its code point (`charClass`). `explainFailure` turns that into the
Expand Down
175 changes: 174 additions & 1 deletion src/document/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,169 @@ function repeatedHead(lines: string[], heads: string[], expectedRest: string): n
return 0;
}

/**
* What a document prints as one text, with where each table cell's own text lies in it. Nothing
* when the pieces do not add up to `expected` exactly, which no ordinary text does.
*/
export function cellRegions(tree: SectionTree, includeAdoptionTable: boolean, expected: string) {
const regions: { start: number; end: number; table?: string }[] = [];
let text = '';
const add = (piece: string, table?: string) => {
const normal = normalizeForCompare(piece);
if (!normal) return;
if (text) text += ' ';
regions.push({ start: text.length, end: text.length + normal.length, table });
text += normal;
};
add(tree.meta.headerLine);
for (const b of exportBlocks(tree, includeAdoptionTable)) {
if (b.type === 'gap') add('· · ·');
else if (b.type === 'table') {
if (b.caption) add(b.caption);
for (const row of [...b.header, ...b.rows]) for (const c of row) add(c.text, b.id);
} else for (const line of flattenBlock(b)) add(line);
}
return text === expected ? regions : undefined;
}

/** How many times the second reading may go back to a line it could have read another way. */
const SPLIT_ROW_TURNS = 20_000;

/**
* Read the pages again, allowing for one thing the plain reading cannot follow: a table row
* taller than a page. Such a row is cut across pages with its cells side by side, so a page
* prints the first part of one cell and then the first part of the next, and the following page
* prints the rest of each. Every character of every cell is there, in order, but not in the order
* of the text, where a cell is whole before the next begins. The same holds for a cell that spans
* several rows and runs over a page.
*
* So a cell of a table may be left unfinished where the next line begins the table's next cell.
* What is left of it must then go on at the top of the next page, before anything else of that
* page, and so on every page after until it is finished: a page that holds none of it, while it
* is unfinished, is refused, so no later row is ever read before the rest of an earlier one.
* Nothing else is allowed: every printed line must be the very text that is expected at one of
* those places, a cell is never taken up again on the page it was left on, and at the end
* nothing may be left over on either side.
*
* Two cells can hold the same line, and such a line can then be read as either's. Each way is
* followed, the plainest first, until one reads every page to the end; each obeys every rule
* above, so this accepts nothing more, and only stops a correct document being refused for the
* way it was first read. Resolves to how many cells were read across a page break, or to nothing
* when the pages do not read as the text this way either.
*/
export function readSplitRows(
pages: string[][],
heads: string[],
expected: string,
regions: { start: number; end: number; table?: string }[],
): number | undefined {
/** What is left of a cell: the page it was left on or last set aside on, and the last page it had a line of. */
interface Left {
start: number;
end: number;
page: number;
took: number;
}
/** Where the reading stands: the line in hand (or none, and the next to fetch), and what was read. */
interface Standing {
page: number;
index: number;
line: string;
pos: number;
left: Left[];
split: number;
}
/** Where `line` ends if it is the text expected at `at`, within `limit`. A line break may stand for a space. */
const fits = (line: string, at: number, limit: number) => {
const from = at > 0 && expected[at] === ' ' ? at + 1 : at;
return from + line.length <= limit && expected.startsWith(line, from) ? from + line.length : -1;
};
/** The unfinished table cell `pos` is in, and the cell after it when that is of the same table. */
const cellAt = (pos: number) => {
let low = 0,
high = regions.length - 1;
while (low < high) {
const mid = (low + high + 1) >> 1;
if (regions[mid]!.start <= pos) low = mid;
else high = mid - 1;
}
const cell = regions[low];
const following = regions[low + 1];
return cell?.table && cell.start <= pos && pos < cell.end && following?.table === cell.table
? { cell, following }
: undefined;
};
/** Every way to read on from `s`, the plainest first; none when it cannot be; a number at the end. */
const ways = (s: Standing): Standing[] | number => {
let { page, index, line } = s;
while (!line) {
const lines = pages[page];
if (!lines) return s.pos === expected.length && !s.left.length && s.split ? s.split : [];
if (index < lines.length) line = lines[index++]!;
else {
page++;
const next = pages[page];
index = next ? repeatedHead(next, heads, expected.slice(s.pos)) : 0;
}
}
const here = { ...s, page, index, line };
// What an earlier page left of a cell comes first on a later one.
const which = s.left.findIndex((rest) => rest.page < page);
if (which >= 0) {
const rest = s.left[which]!;
const without = s.left.filter((other) => other !== rest);
const instead = (now: Left) => s.left.map((other) => (other === rest ? now : other));
const out: Standing[] = [];
const end = fits(line, rest.start, rest.end);
if (end >= 0) {
const more = end < rest.end;
out.push({
...here,
line: '',
left: more ? instead({ ...rest, start: end, took: page }) : without,
});
} else {
// The last line of two cells can stand on one baseline, and is then read as one line:
// the end of this cell, a space, and what belongs to the next.
const from = expected[rest.start] === ' ' ? rest.start + 1 : rest.start;
const tail = expected.slice(from, rest.end);
if (tail && line.startsWith(tail + ' '))
out.push({ ...here, line: line.slice(tail.length + 1), left: without });
}
// Its part of this page is over, and it is not taken up again here. A cell that has had no
// line of this page is never passed over: nothing is read before the rest of it.
if (rest.took === page) out.push({ ...here, left: instead({ ...rest, page }) });
return out;
}
const out: Standing[] = [];
const end = fits(line, s.pos, expected.length);
if (end >= 0) out.push({ ...here, line: '', pos: end });
// Inside a table cell, the line may begin the table's next cell instead.
const at = cellAt(s.pos);
const begun = at ? fits(line, at.following.start, expected.length) : -1;
if (at && begun >= 0)
out.push({
...here,
line: '',
pos: begun,
split: s.split + 1,
left: [...s.left, { start: s.pos, end: at.cell.end, page, took: page }],
});
return out;
};
const others: Standing[] = [];
let turns = 0;
let standing: Standing | undefined = { page: 0, index: 0, line: '', pos: 0, left: [], split: 0 };
while (standing) {
const next = ways(standing);
if (typeof next === 'number') return next;
for (let i = next.length - 1; i > 0; i--) others.push(next[i]!);
if (!next.length && ++turns > SPLIT_ROW_TURNS) return undefined;
standing = next[0] ?? others.pop();
}
return undefined;
}

export async function verifyPdf(bytes: Buffer, tree: SectionTree, includeAdoptionTable = false) {
const pdfjs = await import('pdfjs-dist/legacy/build/pdf.mjs');
const task = pdfjs.getDocument({ data: new Uint8Array(bytes), useSystemFonts: false, verbosity: 0 });
Expand Down Expand Up @@ -486,7 +649,15 @@ export async function verifyPdf(bytes: Buffer, tree: SectionTree, includeAdoptio
actual += printed;
}
}
const result = checkText(actual, expected);
let result: ReturnType<typeof checkText> = checkText(actual, expected);
// The plain reading failed. A table row taller than a page is printed in another order than
// the text, every character of it all the same: read the pages once more with that allowed.
let cellsAcrossPages: number | undefined;
if (!result.ok) {
const regions = cellRegions(tree, includeAdoptionTable, expected);
cellsAcrossPages = regions && readSplitRows(pages, heads, expected, regions);
if (cellsAcrossPages) result = { ok: true };
}
const images = pictures(tree, includeAdoptionTable);
const imagesOk = painted === images;
const footerOk = !footerPage;
Expand All @@ -502,6 +673,8 @@ export async function verifyPdf(bytes: Buffer, tree: SectionTree, includeAdoptio
footerOk,
...(footerPage && { footerPage }),
...((images || !imagesOk) && { images, imagesPrinted: painted }),
// Cells of a table row taller than a page, read across the page break that cuts them.
...(cellsAcrossPages && { cellsAcrossPages }),
},
pageCount: pdf.numPages,
};
Expand Down
Loading
Loading