Skip to content

chore: consolidate utility copies (CSV/JSON escaping, account-type checks, quarter math) - #1741

Merged
robcohen merged 5 commits into
mainfrom
chore/utility-consolidation
Jul 10, 2026
Merged

robcohen merged 5 commits into
mainfrom
chore/utility-consolidation

Conversation

@robcohen

@robcohen robcohen commented Jul 9, 2026

Copy link
Copy Markdown
Member

What

The utility-census batch from the Phase-1 sweep (U1/U2/U5): consolidates four families of copy-pasted utility code into the core helpers. Behavior-identical throughout; no user-visible output changes.

Changes

  • CSV escaping (U2): report_cmd::csv_escape and BQL output::escape_csv were byte-identical private copies. Now rustledger_core::format::escape_csv (unit-tested); both CLI sites delegate — report_cmd via a pub(super) use alias so its 26 call sites are untouched.
  • JSON escaping (U2): report_cmd::json_escape hand-chained replace() over exactly the set core's format::escape_string handles (backslash, quote, \n, \r, \t). Aliased to the core fn; hand chain deleted.
  • Account-type checks (U1): four production sites re-derived account types from raw string prefixes; they now use core's ACCOUNT_TYPES/account_type, so a sixth type or a rule change has one home:
    • LSP on_type_formatting + utils::is_account_like — the deliberately colon-less mid-typing heuristics iterate ACCOUNT_TYPES (same matching, single-sourced list);
    • check_drained plugin — six hand-written clauses (three starts_with + three bare-root equalities) collapse to a three-arm match on account_type, which classifies by root component;
    • split_expenses plugin — is_expense via account_type (identical for any parsable account, which always has ≥ 2 components per fix: one canonical account-name rule; validate FFI ingress; warn on bad name_* roots #1739's rule).
  • Quarter math (U5-lite): (month − 1) / 3 appeared twice within query functions/date.rs, diverging only in off-by-one framing (DATE_TRUNC zero-based vs QUARTER() one-based). A single const quarter_index0 now feeds both.

Deliberately out of scope

⚠️ Pre-existing failure found while testing (not from this PR)

test_account_lifecycle_consistency (crates/rustledger/tests/integration_test.rs) fails on clean main: rledger check passes a ledger where Assets:Bank is posted on 2020-01-15 but opened 2020-02-01 — Python rejects it, and rustledger-validate has a unit test for exactly this rule (lifecycle_posting_before_open_errors), so the check is being lost somewhere between the validator and the CLI pipeline. Verified with a manual rledger check on main: ✓ No errors found. Tracking separately — this looks like a real silent-pass correctness bug.

Testing

core/query/plugin/LSP suites green; CLI suite green except the pre-existing failure above (fails identically with this diff stashed). clippy --all-features --all-targets -D warnings, fmt, rustdoc clean.

🤖 Generated with Claude Code

…ecks, quarter math)

Utility-census batch from the Phase-1 sweep (U1/U2/U5). All changes
behavior-identical; no user-visible output changes.

- CSV escaping: report_cmd csv_escape and BQL output escape_csv were
  byte-identical private copies. Hoist to
  rustledger_core::format::escape_csv (with unit tests); both CLI
  sites now delegate (report_cmd via a pub(super) use alias so the 26
  call sites are untouched).
- JSON escaping: report_cmd json_escape hand-chained replace() over
  exactly the escape set core's format::escape_string handles
  (backslash, quote, \n, \r, \t) — aliased to the core fn, hand chain
  deleted.
- Account-type checks: four production sites re-derived the account
  type from raw string prefixes; they now use the core helpers
  (ACCOUNT_TYPES / account_type), so a future sixth type or rule
  change has one home:
  - LSP on_type_formatting + utils is_account_like: the deliberately
    colon-less mid-typing heuristics now iterate core ACCOUNT_TYPES.
  - check_drained plugin: six hand-written clauses (three prefixes +
    three bare-root equalities) collapse to a three-arm match on
    core account_type, which classifies by root component.
  - split_expenses plugin: is_expense via account_type (identical for
    any parsable account, which always has >= 2 components).
- Quarter math: the (month - 1) / 3 formula appeared twice within
  query functions/date.rs, diverging only in off-by-one framing
  (DATE_TRUNC zero-based vs QUARTER() one-based). Single
  const quarter_index0 helper now feeds both.

Deliberately NOT in this batch:
- report-section routing sites (balsheet/income/networth/holdings)
  are already rewritten config-aware by open PR #1731 — touching
  them here would conflict.
- networth's period bucketing was NOT ported onto query IntervalUnit:
  its buckets are label-string equality (ISO %V weeks) and switching
  machinery risks silent boundary changes for purely cosmetic dedup.
  Reports adopting DisplayContext (U4) is user-visible and belongs in
  its own PR, like #1728.

Note: test_account_lifecycle_consistency (integration_test.rs) fails
on main BEFORE this change — rledger check passes an
account-used-before-open ledger that Python rejects. Pre-existing;
tracked separately.

Co-Authored-By: Claude Fable 5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner July 9, 2026 21:39
Copilot AI review requested due to automatic review settings July 9, 2026 21:39
@github-actions

github-actions Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 31.1ms ± 0.5ms 23.8 MB
beancount 868.9ms ± 6.1ms 50.7 MB
Comparison 27.9x faster 2.1x less

vs main branch (2026-07-10)

Metric main this PR Change
Time 33.7ms 31.1ms -7.7% 🟢
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR consolidates several byte-identical or near-identical utility implementations (CSV/JSON escaping, account-type checks, and quarter math) into single canonical helpers in rustledger-core, then updates the CLI/query/plugins/LSP call sites to delegate to those helpers to reduce drift risk.

Changes:

  • Centralized CSV escaping in rustledger_core::format::escape_csv (with unit test coverage) and updated CLI report + BQL CSV output to use it.
  • Removed the CLI’s hand-rolled JSON escaping chain by aliasing to rustledger_core::format::escape_string.
  • Replaced multiple raw-prefix account-type checks across plugins and LSP handlers with rustledger_core::ACCOUNT_TYPES / rustledger_core::account_type, and deduplicated quarter math via a shared helper in query date functions.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/rustledger/src/cmd/report_cmd/mod.rs Removes local CSV/JSON escaping helpers; aliases to core formatting helpers.
crates/rustledger/src/cmd/query/output.rs Switches BQL CSV escaping to use core’s escape_csv.
crates/rustledger-query/src/executor/functions/date.rs Deduplicates quarter computation via quarter_index0.
crates/rustledger-plugin/src/native/plugins/split_expenses.rs Uses core account_type() instead of a raw "Expenses:" prefix check.
crates/rustledger-plugin/src/native/plugins/check_drained.rs Uses core account_type() to classify balance-sheet accounts.
crates/rustledger-lsp/src/handlers/utils.rs Uses core ACCOUNT_TYPES list for account-like detection.
crates/rustledger-lsp/src/handlers/on_type_formatting.rs Uses core ACCOUNT_TYPES list for posting-line heuristics.
crates/rustledger-core/src/format/mod.rs Re-exports escape_csv and adds a unit test for it.
crates/rustledger-core/src/format/helpers.rs Introduces the canonical escape_csv implementation with docs.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 811
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 2 commits July 10, 2026 02:53
… (review)

- quarter_index0 had been inserted between add_days's doc block and
  its fn, so rustdoc attached the wrong docs; moved above the block,
  plus a debug_assert and a note on the 1-based month contract.
- escape_csv doc said "newline"; only \n triggers quoting (\r does
  not), matching the prior copies byte-for-byte — say so.
- escape_csv import moved to the top import group in query output.

Co-Authored-By: Claude Fable 5 <[email protected]>
Its bucketing is origin- and width-relative months arithmetic, not
calendar-quarter indexing — the doc claimed a third call site that
does not (and could not) exist.

Co-Authored-By: Claude Fable 5 <[email protected]>
@codecov

codecov Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.64516% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...es/rustledger-query/src/executor/functions/date.rs 0.00% 6 Missing ⚠️

📢 Thoughts on this report? Let us know!

@robcohen
robcohen merged commit debe1d4 into main Jul 10, 2026
53 of 55 checks passed
@robcohen
robcohen deleted the chore/utility-consolidation branch July 10, 2026 11:08
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.

2 participants