Skip to content

fix: escape control characters in ledger strings on human-readable output - #2710

Merged
robcohen merged 4 commits into
mainfrom
fix/escape-ledger-control-chars
Oct 20, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/escape-ledger-control-chars

Conversation

@robcohen

Copy link
Copy Markdown
Member

What changed

This PR implements the decision on #2538, plus the price fetch-failure follow-up from its second comment.

1. Human-readable output always escapes; data formats keep the value. I reused rustledger_plugin::untrusted (#2525), so \u{1b} shows up visibly instead of acting on the terminal.

  • check text diagnostics:
    • The message and hint are escaped. These can quote a document path, an option value or an include pattern.
    • The miette source snippet is escaped. The new escape_untrusted_source keeps \n, \t and \r (which miette reads as line terminators) and maps byte offsets, so label spans still cover the same characters.
    • The fallback file:line:col lines are escaped, and so are the load-error, option-warning and LINT-XFER lines.
  • Query text tables: every cell and header is escaped, newlines and tabs included (they would break the row). Column widths are computed on the escaped text.
  • report text:
    • sanitize_display used to replace control characters with spaces. It now escapes them, so journal narration and payee, balances lot labels, and budget/returns labels all get the same rule. Budget column widths now use the escaped width.
    • Diagnostic lines (Diagnostic::to_line) are escaped too.
  • Price: Messages::emit_as escapes the terminal line, which covers PRICE_FETCH_FAILED. The plain-format currency from a price source is escaped too. Recorded diagnostics (ag-rledger) keep the raw text.
  • Never escaped: PRINT, query -f beancount and rledger format. They emit ledger text, and beancount strings have no escape syntax for these characters. A test pins that PRINT and format still emit them byte for byte.
  • Raw as data:
    • CSV is untouched. The returns CSV no longer space-replaces its labels.
    • LSP and FFI are untouched.
    • JSON keeps the value but now also escapes DEL, the C1 controls, bidi controls and U+2028/2029 as \uXXXX. serde emitted these raw. The escaped form decodes to the same string, so the value is unchanged.
      • check/query/lint JSON goes through a new cmd::to_json_pretty.
      • report JSON goes through rustledger_core::format::escape_json.
  • The character set is now defined once, in rustledger_core::format::is_display_unsafe, and untrusted::is_unsafe delegates to it.

2. Ingest: extract neutralizes control characters in imported text: CSV cells, OFX fields, and the entries a WASM importer returns. The fields covered are payee, narration, string metadata (directive and posting), note comment and event value.

  • A tab, newline or line separator becomes a space. Any other such character becomes U+FFFD.
  • Each affected row gets a warning naming the row and the field, e.g. Row 1: control characters in narration replaced .... OFX rows are named by their FITID; WASM importer rows read Entry N.

3. rledger lint control-chars (also in ag-rledger lint) reports control characters already in a ledger's strings, with file:line and field. Tab, newline and the \r of a \r\n are not reported. It has text and JSON output. It is a lint, not a check warning, because bean-check accepts these characters (same reasoning as #1446).

Overlap note for the parallel BQL lane: the only query-writer change is in crates/rustledger/src/cmd/query/output.rs (write_text escaping and write_json via to_json_pretty). Nothing in rustledger-query changed.

No CACHE_VERSION bump: parser output is unchanged.

Proposed, not implemented: a parser warning

Should the parser warn on control characters in strings? I propose no:

If you do want one, it should be opt-in, either check --lint control-chars (alongside --lint transfers) or an option.

How tested

  • crates/rustledger/tests/control_chars_output_test.rs (7 tests, end to end through the binary):
    • check text: message and snippet are escaped.
    • check -f json: the value is kept and is valid JSON with no raw C1.
    • Query: the table is escaped, CSV is raw, JSON keeps the value and escapes DEL/C1.
    • report journal: text is escaped, CSV is raw, JSON is valid and keeps the value.
    • PRINT and format emit the characters byte-identically.
    • extract replaces the characters and warns, once per row.
    • lint control-chars finds them.
    • With the render and ingest changes reverted, 5 of the 7 fail. The PRINT/format guard and the new lint pass either way.
  • Unit tests:
    • escape_untrusted_source: offset mapping, line terminators kept, escape lengths.
    • escape_json: DEL/C1/bidi.
    • to_json_pretty: round trip.
    • Importer neutralize_directive.
    • Lint: text, JSON, a clean CRLF ledger.
  • Test suites for cargo test -p rustledger-core -p rustledger-plugin -p rustledger-importer -p rustledger --all-features: 2515 passed. The one failure in the first run was in my own new test, which used the wrong flag; that test passes after the fix.
  • Also passing:
    • cargo clippy --workspace --all-features --all-targets -D warnings
    • the release-config clippy (-p rustledger --no-default-features --features mimalloc,ag-rledger)
    • cargo doc -D warnings for the 4 changed crates
    • cargo fmt

Closes #2538

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…tput

Ledger strings (narrations, payees, metadata, comments, document paths)
reached the terminal raw in check diagnostics (message and miette
snippet), query tables and report text. They are now escaped with
rustledger_plugin::untrusted's rule (#2525), as are price fetch-failure
lines. Data output keeps the value: CSV, PRINT, -f beancount and format
write it as is; JSON escapes DEL, C1, bidi controls and line separators as
\uXXXX, which decode to the same string. extract neutralizes control
characters in imported text (tab/newline to a space, others to U+FFFD)
with a warning naming the row and field, and `rledger lint control-chars`
reports the ones already in a ledger (#2538).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner October 20, 2026 14:51
@github-actions

github-actions Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 31.6ms ± 1.1ms 490.3ms ± 11.8ms 15.5x 51.6 MB / 50.1 MB
investment 52.9ms ± 10.0ms 1634.7ms ± 7.4ms 30.9x 53.6 MB / 58.1 MB
fifo 46.0ms ± 1.1ms 9269.7ms ± 99.6ms 201.6x 55.9 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 29.8ms ± 0.5ms 31.6ms ± 1.1ms +6.3% 🟡 slower 51.7 MB → 51.6 MB (-0.3%)
investment 50.4ms ± 1.9ms 52.9ms ± 10.0ms +4.9% ✅ within noise 53.6 MB → 53.6 MB (+0.1%)
fifo 46.8ms ± 1.4ms 46.0ms ± 1.1ms -1.7% ✅ within noise 55.9 MB → 55.9 MB (-0.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.5ms, investment 4.5ms, fifo 0.8ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 819
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@robcohen

Copy link
Copy Markdown
Member Author

Deep-review rounds (lane V6)

Round Scope Checks Findings
1 The whole diff, re-read adversarially. Covered: snippet offset remapping (spans that start on or end after an escaped character, multi-byte C1, \r\n sources); JSON post-escaping (it must not touch the pretty-printer's newlines); widths of escaped cells; the CSV/PRINT/format/LSP/FFI paths staying raw Fail-without-fix: 5 of the 7 CLI tests fail with the render and ingest changes reverted. Changed-crate suites: 2515 passed. Workspace clippy, release-config clippy, docs An early draft of the JSON helper escaped the pretty-printer's own line breaks; I fixed it to skip C0 (which serde already escapes). One test used check --json where the flag is -f json. Both were fixed before the push
2 Differential fuzz: 300 random ledgers with control characters (ESC, BEL, C1 CSI, DEL, bidi override, NUL, CR, FF, BS, U+2028) at random positions, through check, check -f json and query Looked for panics and for raw control characters in human output. Self-check first: the same detector reports rledger format output (which keeps them) as RAW None

Converged after round 2.

Red non-required checks:

@robcohen
robcohen merged commit 51cf232 into main Oct 20, 2026
53 of 56 checks passed
@robcohen
robcohen deleted the fix/escape-ledger-control-chars branch October 20, 2026 23:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Escape control characters in ledger strings on output

1 participant