[bug] Windows CRLF text becomes CRCRLF in persisted corpus
What happened
On Windows, a Markdown/text source with ordinary CRLF line endings is written to full_text.txt with CRCRLF endings. A normal Python text read then sees a blank line inserted between every original line.
This is a production serialization defect, not just a test comparing different platform line endings. In a synthetic two-section setext document, the extractor detects both sections and writes chapters_detected: 2, but the corpus it persists no longer preserves the heading/underline adjacency:
CRLF input LF negative control
Source logical lines 9 9
CLI exit 0 0
CRCRLF sequences in output 8 0
Lines after Python text read 17 9
Sections detected before write 2 2
Sections detected on reread 0 2
Metadata sections 2 2Observed source and output bytes:
source: b'Alpha heading\r\n=============\r\nalpha body ...'
full_text: b'Alpha heading\r\r\n=============\r\r\nalpha body ...'
text reread: 'Alpha heading\n\n=============\n\nalpha body ...'The same CLI and content with LF input does not produce CRCRLF and still detects two sections on reread.
What you expected
Writing the extracted corpus should preserve its logical lines and heading adjacency. Whether the project chooses canonical LF output or preserves source endings, an existing CRLF must not become CRCRLF.
Source document
- Format: Markdown, using the existing plain-text parser; no optional dependencies needed.
- Language: English; entirely synthetic.
- Pages / size: 9 logical lines, 142 UTF-8 bytes with CRLF; the LF control is 133 bytes.
--check: no parser installation is required for this format.
The exact sample is:
Alpha heading
=============
alpha body line one
alpha body line two
Beta heading
============
beta body line one
beta body line twoRepro
Run this from a checkout on Windows. It creates a unique local directory, writes the source bytes explicitly, invokes the unmodified CLI, and compares content-only structure before and after serialization:
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
from book_to_skill.utils import detect_structure
assert os.name == "nt", "This reproduction tests Windows newline translation"
root = Path(tempfile.mkdtemp(prefix="newline-repro-", dir=os.environ.get("BOOK_SKILL_REPRO_DIR", "."))).resolve()
sample = (
"Alpha heading\n=============\n"
"alpha body line one\nalpha body line two\n\n"
"Beta heading\n============\n"
"beta body line one\nbeta body line two\n"
)
for label, ending in [("lf-control", "\n"), ("crlf", "\r\n")]:
source = root / (label + ".md")
original = sample.replace("\n", ending)
source.write_bytes(original.encode("utf-8"))
output = root / (label + "-output")
env = dict(os.environ, BOOK_SKILL_WORKDIR=str(output))
subprocess.run(
[sys.executable, "scripts/extract.py", str(source),
"--mode", "text", "--install-missing", "no"],
env=env, check=True,
)
raw = (output / "full_text.txt").read_bytes()
reread = (output / "full_text.txt").read_text(encoding="utf-8")
content = reread.split("=" * 80, 2)[-1].lstrip("\r\n")
meta = json.loads((output / "metadata.json").read_text(encoding="utf-8"))
print(label, {
"CRCRLF": raw.count(b"\r\r\n"),
"source_lines": len(original.splitlines()),
"reread_lines": len(content.splitlines()),
"before_sections": detect_structure(original)["chapters_detected"],
"reread_sections": detect_structure(content)["chapters_detected"],
"metadata_sections": meta["chapters_detected"],
})
assert b"\r\r\n" not in raw # passes for LF; fails for CRLFBoth CLI calls complete successfully. The LF assertion passes; the CRLF assertion fails with the values in the table above.
Cause and impact
text.py:17-35 reads bytes and decodes them, retaining \r\n. The extractor computes source structure on that string. utils.py:1350-1353 then calls Path.write_text(..., encoding="utf-8") with default newline translation. On Windows, every existing \n is translated to \r\n, so \r\n becomes \r\r\n.
The mismatch exists between extraction metadata and the persisted corpus consumed by Steps 3 and 7. Adjacent lines become separated paragraphs; setext headings cease to be headings when reread normally. The observed chars count also does not catch this: in the CRLF case, it equals the universal-read length even though the line structure changed.
I have not run an LLM conversion or measured an incorrect generated answer. The directly demonstrated loss is the corpus's line structure and its disagreement with pre-write detection.
Smallest correction and acceptance plan
Two bounded approaches are possible:
- Normalize CRLF and standalone CR to LF once, before metadata/structure calculations, and serialize canonical LF without Windows translation. This gives a consistent corpus for future line/character offsets.
- Preserve the extracted string's existing endings and disable output translation. This avoids doubling without changing the parser's input behavior, but the project should define whether mixed endings and normalized character offsets are acceptable.
For the repository's Python 3.9 support, OUTPUT_TEXT.open("w", encoding="utf-8", newline="\n") is available; adding newline= directly to Path.write_text() would require Python 3.10+. A serialization-only adjustment that removes doubling does not by itself define a cross-platform character-offset contract.
Acceptance should cover CRLF, LF, standalone CR and mixed endings; UTF-8, UTF-8 BOM, UTF-16/UTF-32 BOM sources; parser-produced LF strings; and a real CLI round trip. Assert no CRCRLF, preserved logical lines, preserved setext adjacency and unchanged visible text/tab/indentation content. If normalization is chosen, compute metadata from the same canonical string that is written. Keep Unicode sanitization and output-directory security checks intact.
The reproduced failure is Windows-specific. Linux/macOS do not perform this default CRLF translation; a platform-aware test should retain those controls instead of marking all environments as affected.
Environment and validation limits
- Windows 11; Python 3.12.14 from the bundled runtime.
masterc108d25b0cb58e1bdc361f3de02ed9f37075152f; declared package version 1.4.0.- Two real CLI runs, explicit input bytes and output byte inspection; no mocks and no optional parser dependency.
- Independently repeated on the same supported Python 3.12.14 runtime with fresh fixtures: the LF control retained 9 lines and 2 sections; CRLF produced 8 CRCRLF sequences, 17 reread lines and 0 reread sections.
- Existing PRs #253/#255 mention Windows CRLF test failures, and #173 concerns POSIX test guards. The refreshed issue snapshot contains no report of this source-CRLF-to-CRCRLF production behavior.
- No source changes, fix validation, full-suite claim or live-model quality claim.
Source: virgiliojr94/book-to-skill