Repository navigation
chore: update dependencies and fix deny.toml for cargo-deny v0.18 - #2
Merged
Merged
Conversation
- Update wasmtime from 27 to 40 (fixes RUSTSEC-2025-0118, RUSTSEC-2025-0046) - Update rust_decimal from 1.36 to 1.39 - Update rust_decimal_macros from 1.36 to 1.39 - Migrate deny.toml to version 2 format for cargo-deny v0.18 - Update license identifier from GPL-3.0 to GPL-3.0-only (SPDX compliance) - Add ignore for RUSTSEC-2026-0001 (rkyv transitive dep via rust_decimal) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Member
Author
|
@claude review this PR |
|
Claude encountered an error after 34s —— View job PR Review
|
1 task
Member
Author
|
@claude review this PR |
|
Claude encountered an error after 38s —— View job PR Review
|
robcohen
added this pull request to the merge queue
Jan 6, 2026
robcohen
added a commit
that referenced
this pull request
Jan 14, 2026
chore: update dependencies and fix deny.toml for cargo-deny v0.18
robcohen
added a commit
that referenced
this pull request
Jan 14, 2026
chore: update dependencies and fix deny.toml for cargo-deny v0.18
robcohen
added a commit
that referenced
this pull request
Feb 16, 2026
- Sort metadata keys for deterministic output order (#3) - Escape strings in option/include/plugin formatting (#2) - Preserve leading blank lines at file start (#1) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Mar 31, 2026
Fixes several issues identified in PR #624 review: 1. Yahoo f64 precision (issue #3): Use pattern matching with serde_json::Value::Number to preserve decimal precision instead of converting through f64. 2. ECB cross-rate handling (issue #2): Rewrite fetch_price to correctly handle EUR→X, X→EUR, and X→Y cross-rate conversions. 3. --source-cmd early return (issue #4): Move external command handling after symbol discovery so -f flag works with --source-cmd. 4. Hardcoded timeout (issue #7): Use config timeout for --source-cmd instead of hardcoded 30 seconds. 5. External source naming (issue #8): Derive source name from command binary name instead of always returning "external". Add with_name() constructor for configured sources. 6. Unknown sources warning (issue #5): Track and report unknown sources in fallback chains when price fetching fails. 7. Timeout limitation (issue #6): Document that timeout is stored but not enforced due to std::process::Command limitations. Co-Authored-By: Claude Opus 4.5 <[email protected]>
This was referenced Apr 8, 2026
robcohen
added a commit
that referenced
this pull request
Apr 11, 2026
Three inline comments, all about the accuracy of the explanatory
prose in the exclusions-file comment blocks. All legitimate — the
original wording conflated two unrelated things:
1. The account-segment start-character rule (the actual rule
being enforced and documented in these exclusions)
2. Account root-type localization via `name_*` options (a
different feature — issue #572)
Fixes:
1. **Section header was too narrow.** I called the new section
"Unicode-at-account-segment-start exclusions" but the
`Assets:CORP✨` (fava-portfolio-returns) exclusion fails for a
different reason: the emoji `✨` is in Unicode category `So`
(Symbol, Other), not `L` (Letter), so it's rejected *anywhere*
in the segment body, not specifically at the start. Renamed
the section to "Non-ASCII account name exclusions" and split
the explanation into two enumerated rules:
- Rule 1: segment start must be ASCII
- Rule 2: segment body must be ASCII digits, hyphens, or
Unicode letters — no symbols or emoji anywhere
Then documented which of the 4 files exercises which rule.
2. **Intro paragraph mentioned `name_*` as a workaround.** It
doesn't apply: `name_*` options rename the ROOT segment type
(`Assets` → `Activos`), but all 4 exclusions fail on SUB-segments,
not root segments. Replaced the `name_*` suggestion with an
accurate workaround (rename the offending sub-segment to start
with ASCII) and explicitly noted that `name_*` does not help
with sub-segment localization.
3. **`pinto-reports/example.beancount` details suggested `name_*`.**
Same issue as #2, but in the per-file details block. The Swedish
chart of accounts has ASCII root segments (`Liabilities`, `Income`,
`Expenses`) and accented sub-segments (`Årets-resultat` et al.),
so `name_*` renaming does nothing. Replaced with the accurate
workaround.
No code changes. TOML still parses cleanly (8 exclusions total, 4
pre-existing + 4 new). Functional behavior of the exclusions is
unchanged — the compat bot already shows Check Compatibility at
100% and Total Files dropped from 784 to 780, confirming the 4
new patterns match their intended files.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
Apr 12, 2026
- Fix #1: Build SourceMap with buffer content in single-file mode so run_plugins() can preserve directive source locations - Fix #2: Anchor Python plugin warning to the plugin directive span and filter by current_file_id to avoid noise in multi-file mode - Fix #3: Only show plugin errors in the main file (file_id 0) to prevent duplication across open documents - Fix #4: Correct diagnostic message — non-native plugins are skipped in LSP, not "may be slower" (run_plugins only runs native plugins) - Fix #5: Merge fresh buffer plugin declarations with ledger plugins, mirroring the directive overlay approach for unsaved edits Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
Apr 23, 2026
…tability - Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf> to store resolved paths instead of raw values - Add #[non_exhaustive] to ValidationOptions to prevent breaking changes when new fields are added - Resolve document paths against source_map base_dir in run_validation() and build_validation_options_from_loader() to match run_plugins() behavior - Use Path::join() instead of string concatenation for portable paths - Fix test to use doc_subdir.join() instead of format! for path construction Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen
added a commit
that referenced
this pull request
Apr 23, 2026
…tability - Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf> to store resolved paths instead of raw values - Add #[non_exhaustive] to ValidationOptions to prevent breaking changes when new fields are added - Resolve document paths against source_map base_dir in run_validation() and build_validation_options_from_loader() to match run_plugins() behavior - Use Path::join() instead of string concatenation for portable paths - Fix test to use doc_subdir.join() instead of format! for path construction Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen
added a commit
that referenced
this pull request
Apr 23, 2026
…tability - Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf> to store resolved paths instead of raw values - Add #[non_exhaustive] to ValidationOptions to prevent breaking changes when new fields are added - Resolve document paths against source_map base_dir in run_validation() and build_validation_options_from_loader() to match run_plugins() behavior - Use Path::join() instead of string concatenation for portable paths - Fix test to use doc_subdir.join() instead of format! for path construction Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen
added a commit
that referenced
this pull request
Apr 23, 2026
…tability - Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf> to store resolved paths instead of raw values - Add #[non_exhaustive] to ValidationOptions to prevent breaking changes when new fields are added - Resolve document paths against source_map base_dir in run_validation() and build_validation_options_from_loader() to match run_plugins() behavior - Use Path::join() instead of string concatenation for portable paths - Fix test to use doc_subdir.join() instead of format! for path construction Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen
added a commit
that referenced
this pull request
Apr 28, 2026
Five substantive issues raised by the Copilot review on PR #945: 1. **Custom cache directories now created automatically.** `BEANCOUNT_LOAD_CACHE_FILENAME` patterns can resolve to a directory that doesn't exist (e.g. `~/.cache/rledger/{filename}.cache` on a fresh install). `save_cache_entry` now `create_dir_all`s the parent eagerly so caching isn't silently disabled. 2. **`BEANCOUNT_DISABLE_LOAD_CACHE` is now honored at the loader level.** Previously only the CLI checked it, so any external consumer of `rustledger-loader::{load,save}_cache_entry` would silently bypass the kill switch. Both functions now early-return when the env var is set to a non-empty value (matching Python beancount semantics). The CLI check stays as an early-out optimization. 3. **`default_cache_path` exposed as a pure helper.** `cache_path()` reads process env, which makes any test that calls `save_cache_entry`/`invalidate_cache` env-sensitive. `default_cache_path()` returns the dotfile path with no env lookup — useful for tests and library consumers that need determinism. 4. **Doc accuracy.** I had claimed cache invalidation was "content-based" in `docs/commands/check.md` and `docs/reference/architecture.md`, but `compute_hash` actually hashes file path + mtime + size. Reworded both pages to describe the real metadata-based behavior (and noted content-based hashing as a possible future improvement). 5. **Module rustdoc clarified** to state explicitly that the env vars are honored at the loader level, not just by CLI callers. Tests: - New integration test `save_creates_missing_parent_directory` covers the regression in #1. - New integration test `disable_env_makes_load_return_none_and_save_no_op` covers the loader-level enforcement in #2. - In-module roundtrip/invalidate tests now `assert_clean_cache_env()` at the top so a developer with locally-set cache env vars sees a clear failure rather than mysterious behavior. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
Apr 28, 2026
…loses #939) (#945) * fix(cache): hide cache file as dotfile and honor beancount env vars (closes #939) `rledger check` wrote a visible `<file>.cache` next to every ledger, creating clutter that surprised users (#939). Match Python beancount's established convention instead: - Default cache filename is now `.<file>.cache` (hidden dotfile), mirroring beancount's `.{filename}.picklecache`. - Honor `BEANCOUNT_DISABLE_LOAD_CACHE` to opt out persistently. - Honor `BEANCOUNT_LOAD_CACHE_FILENAME` to redirect the cache; supports `{filename}` substitution and resolves relative paths against the source directory, matching beancount semantics. - Empty `BEANCOUNT_LOAD_CACHE_FILENAME` is treated as unset to prevent every ledger's cache from collapsing onto the same file. - After writing the new dotfile cache, opportunistically delete the legacy visible `<file>.cache` (silent on failure) so upgrading users don't have to clean up by hand. The `--no-cache` / `-C` CLI flag continues to work for one-shot opt-out. Tests: - New unit tests for `resolve_cache_pattern` and `legacy_cache_path`. - New `tests/cache_env_var_test.rs` integration test that exercises the env var path end-to-end. Lives in a separate test binary because mutating process env requires `unsafe` since Rust 2024 and the workspace forbids `unsafe_code`. - Updated `test_load_cache_invalid_magic` to write the malformed cache at the new dotfile path so it actually exercises the load path. Docs: - `docs/commands/check.md` — added a Cache File section with naming, env vars, and migration note. - `docs/reference/architecture.md` — refreshed the Binary Cache section with the dotfile location, content-based invalidation note, and env var pointer. - `cache.rs` module-level rustdoc updated. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(cache): refresh remaining stale references to old cache filename Pick up two spots missed in the initial #939 fix: - `.gitignore`: keep matching legacy `<file>.beancount.cache` (gitignored for users upgrading from earlier versions) and add an explicit dotfile pattern with a comment explaining the rationale. The bare `*` pattern already matched dotfiles per gitignore semantics, but the explicit pattern makes the intent clear. - `performance-roadmap.md`: cache location example was still showing the visible filename — updated to the dotfile form with an env-var pointer. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(cache): address Copilot review feedback on #945 Five substantive issues raised by the Copilot review on PR #945: 1. **Custom cache directories now created automatically.** `BEANCOUNT_LOAD_CACHE_FILENAME` patterns can resolve to a directory that doesn't exist (e.g. `~/.cache/rledger/{filename}.cache` on a fresh install). `save_cache_entry` now `create_dir_all`s the parent eagerly so caching isn't silently disabled. 2. **`BEANCOUNT_DISABLE_LOAD_CACHE` is now honored at the loader level.** Previously only the CLI checked it, so any external consumer of `rustledger-loader::{load,save}_cache_entry` would silently bypass the kill switch. Both functions now early-return when the env var is set to a non-empty value (matching Python beancount semantics). The CLI check stays as an early-out optimization. 3. **`default_cache_path` exposed as a pure helper.** `cache_path()` reads process env, which makes any test that calls `save_cache_entry`/`invalidate_cache` env-sensitive. `default_cache_path()` returns the dotfile path with no env lookup — useful for tests and library consumers that need determinism. 4. **Doc accuracy.** I had claimed cache invalidation was "content-based" in `docs/commands/check.md` and `docs/reference/architecture.md`, but `compute_hash` actually hashes file path + mtime + size. Reworded both pages to describe the real metadata-based behavior (and noted content-based hashing as a possible future improvement). 5. **Module rustdoc clarified** to state explicitly that the env vars are honored at the loader level, not just by CLI callers. Tests: - New integration test `save_creates_missing_parent_directory` covers the regression in #1. - New integration test `disable_env_makes_load_return_none_and_save_no_op` covers the loader-level enforcement in #2. - In-module roundtrip/invalidate tests now `assert_clean_cache_env()` at the top so a developer with locally-set cache env vars sees a clear failure rather than mysterious behavior. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(cache): tighten env handling and panic-safe test plumbing (#945 self-review) Self-review of PR #945 surfaced five issues; this commit addresses all of them. 1. **Match Python beancount on `BEANCOUNT_DISABLE_LOAD_CACHE`.** Python's check is `os.getenv(...) is None`, which means *any* presence — empty string included — disables the cache. We required a non-empty value; that's a silent divergence for users who write `EXPORT FOO=` in their shell. Switched to `is_some()` to match. 2. **Normalize the disable check between loader and CLI.** Both now go through the new `cache_disabled_by_env()` helper, exported from the loader so any downstream consumer (LSP, MCP, future tools) gets the same semantics for free. 3. **`invalidate_cache` now also removes the legacy sidecar.** `save_cache_entry` already cleans up the pre-#939 visible file when it writes a new dotfile cache; `invalidate_cache` was missing the same logic, so a `rledger check --invalidate-cache` (hypothetical or programmatic invalidate) would leave the legacy file behind. 4. **`with_env` is now panic-safe.** Replaced the inline save/restore pattern with an `EnvGuard` Drop type. A test that panics mid-body no longer leaks its mutated env into the next test in the binary. 5. **`disable_env_makes_load_return_none_and_save_no_op` was vacuous.** It asserted `load_cache_entry → None`, but the cache file didn't exist (because save was a no-op), so the test would have passed even if `load_cache_entry` ignored the env entirely. Restructured to: (a) write a real cache with the env unset, (b) set the env and verify load returns None despite the cache being on disk, (c) verify save doesn't touch the existing file (mtime invariant). Plus one new test: `empty_disable_env_value_still_disables` locks in the Python-beancount-compatible empty-value semantics from #1. And one new test: `test_invalidate_cache_removes_legacy_sidecar` covers the new behavior in #3. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 1, 2026
…ut trim, refactor Self-review of #965 surfaced six fixable issues: 1. The PR description and docs both claimed `--undeclared` is a 1:1 match for `bean-price --undeclared`. It isn't: bean-price walks transactions (at-cost ∪ converted ∪ priced) with no name filter, while ours walks `commodity` directives with a ticker-shape filter. Different inputs, different outputs. The strict subset is intentional (avoids routing currency codes like `EUR` to stock sources by default), so this PR documents the divergence honestly instead of changing behavior. Closer alignment is tracked as a follow-up under the bean-price audit issue. 2. Whitespace-only `price: " "` now triggers the explicit opt-out, same as `price: ""`. Previously fell through to strict-skip with the same effective result, but inconsistent with the explicit-opt-out intent. 3. Stale doc comment on `DiscoveredCommodity::mapping` — `None` no longer means "name heuristic only"; it can also mean `quote_currency:`-only or CLI-supplied. Updated. 4. Refactored discovery loop to use a `DiscoveryDecision` enum (`OptOut | Discovered | Inherit`). This eliminates the previous double-read of `price:` metadata (once for the opt-out check, once in `build_discovery_info`) and reads the cleaner branch structure off the match arms. 5. Renamed `active_filter_handles_explicit_amounts_on_balance_sheet_side_signature_passthrough` to `discover_inactive_undeclared_combined_matches_legacy_all_commodities` — the previous name implied it was about active-filter behavior, but the test is about combined flag interaction. 6. `--inactive` and `--undeclared` now use clap `requires = "file"` so they error fast when used without `-f`, instead of silently being no-ops. Plus a new test `discover_honors_whitespace_only_price_opt_out` for #2. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 1, 2026
…ve (closes #962) (#965) * fix(price): strict metadata-only discovery, add --undeclared/--inactive (closes #962) `rledger price -f file.beancount` was downloading prices for any ticker-shaped commodity name even without `price:` metadata. Issue #962 flagged this against `bean-price`, where the equivalent flow walks Commodity directives and fetches *only* commodities with explicit `price:` metadata. Verified against upstream `beanprice/price.py::find_currencies_declared`: ```python source_str = entry.meta.get("price", None) if source_str is not None: if source_str == "": # Skip — empty price: opts out continue # parse "<quote>:<source>/<ticker>" and include else: # No price: metadata → ignore the commodity entirely ``` Changes: - Default discovery now requires `price:` or `quote_currency:` metadata. Currency codes like `BAM` and custom commodities like `UKW` no longer collide with stock tickers. - `price: ""` (empty string) is honored as an explicit opt-out, even with `--undeclared`. Matches `bean-price`'s "Skipping ignored currency (with empty price)" behavior. - `--all-commodities` is replaced with two granular flags that match `bean-price`: - `--inactive`: include commodities with zero balance. - `--undeclared`: re-enable the ticker-shape heuristic for commodities without metadata (legacy behavior). Pair with `--inactive` for the pre-#962 "fetch everything" behavior. Tests added in `discovery.rs`: - `discover_skips_no_metadata_commodity_by_default` — the BAM regression. - `discover_honors_empty_price_opt_out` — `price: ""` always skips. - `discover_picks_up_quote_currency_only_commodity` — `quote_currency:` alone is a valid opt-in. CLI tests in `price_cmd.rs` cover the new flag combinations. Docs: `docs/commands/price.md` rewrites the "Discovering Symbols" section to reflect strict-by-default semantics, the new flags, and the `price: ""` opt-out. This is a behavioral break for users who relied on `-f` discovering ticker-shaped names without metadata. Migration: pass `--undeclared` to restore the previous behavior, or annotate the affected commodities with `price:` metadata. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(price): self-review fixes — honest --undeclared divergence, opt-out trim, refactor Self-review of #965 surfaced six fixable issues: 1. The PR description and docs both claimed `--undeclared` is a 1:1 match for `bean-price --undeclared`. It isn't: bean-price walks transactions (at-cost ∪ converted ∪ priced) with no name filter, while ours walks `commodity` directives with a ticker-shape filter. Different inputs, different outputs. The strict subset is intentional (avoids routing currency codes like `EUR` to stock sources by default), so this PR documents the divergence honestly instead of changing behavior. Closer alignment is tracked as a follow-up under the bean-price audit issue. 2. Whitespace-only `price: " "` now triggers the explicit opt-out, same as `price: ""`. Previously fell through to strict-skip with the same effective result, but inconsistent with the explicit-opt-out intent. 3. Stale doc comment on `DiscoveredCommodity::mapping` — `None` no longer means "name heuristic only"; it can also mean `quote_currency:`-only or CLI-supplied. Updated. 4. Refactored discovery loop to use a `DiscoveryDecision` enum (`OptOut | Discovered | Inherit`). This eliminates the previous double-read of `price:` metadata (once for the opt-out check, once in `build_discovery_info`) and reads the cleaner branch structure off the match arms. 5. Renamed `active_filter_handles_explicit_amounts_on_balance_sheet_side_signature_passthrough` to `discover_inactive_undeclared_combined_matches_legacy_all_commodities` — the previous name implied it was about active-filter behavior, but the test is about combined flag interaction. 6. `--inactive` and `--undeclared` now use clap `requires = "file"` so they error fast when used without `-f`, instead of silently being no-ops. Plus a new test `discover_honors_whitespace_only_price_opt_out` for #2. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(price): address Copilot review on PR #965 Three Copilot review comments addressed: 1. **Restored `--all-commodities` as a deprecated, hidden alias** for `--inactive --undeclared`. Existing 0.14.1 scripts and CI invocations no longer break. Emits a deprecation warning to stderr the first time it's used; the flag is hidden from `--help` output. Will be removed in a future release. 2. **Clarified `price: ""` opt-out wording** in `docs/commands/price.md`. The opt-out only suppresses discovery from `-f / --file`; an explicit CLI symbol like `rledger price BAM` is still fetched (CLI args are explicit user intent and override per-commodity discovery rules). The previous "never fetched" wording was misleading. 3. **Warn on malformed `price:` metadata.** A non-empty `price:` value that produces no parseable specs (e.g. typo, wrong format) used to be silently skipped by the strict default. Now we emit a warning to stderr matching `bean-price`'s "Ignoring currency with invalid 'price' source" log, and surface the warning even when the commodity is included via `quote_currency:`. The commodity itself is still skipped under the strict default (matches bean-price); the user sees the typo loudly. Refactor: `classify_commodity_meta` now returns a `Classification` struct carrying both the discovery decision and a `malformed_price` flag, so the caller can log warnings per-symbol with the symbol name in scope. Tests added: - `classify_flags_malformed_price_metadata` — `price: "BOGUS_FORMAT"` flag set, decision = Inherit (skipped under strict default). - `classify_flags_malformed_price_even_when_quote_currency_present` — malformed `price:` paired with valid `quote_currency:` still flags the malformed warning, and the commodity is still discovered. - `classify_does_not_flag_empty_price_as_malformed` — `price: ""` is an opt-out, not malformed (no false-positive warning). - `test_price_args_all_commodities_deprecated_alias_still_parses` — the deprecated flag is accepted by clap. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 7, 2026
…int gate
Copilot flagged four issues on the original commit. All real:
1. **`row_group_keys` desynchronizes after ORDER BY / LIMIT.** The
sidecar is parallel to `rows`, but `sort_results` and the four
`result.rows.truncate(limit)` sites mutated only `rows` — after
sort or pagination, `row_group_keys[i]` no longer corresponded
to row `i`, so currency hints would be applied to the wrong rows.
Fixed by encapsulating the invariant inside `QueryResult`:
- New `QueryResult::truncate(len)` truncates both vectors.
- New `QueryResult::sort_by(F)` pair-sorts both vectors via a
single `mem::take` + `zip` + `sort_by` + push-back, with
`debug_assert_eq!` guarding the lengths.
- `sort.rs` and all four LIMIT sites now go through these helpers.
2. **False-positive currency hint silently STRIPS trailing zeros.**
`DisplayContext::format(n, currency)` falls back to
`n.normalize().to_string()` when the currency has no tracked
precision — `normalize()` strips trailing zeros, turning `0.000`
into `0`. So a heuristic-only currency check ("uppercase, looks
right") would render output WORSE than the pre-fix state for
any unrecognized currency-shaped string in a GROUP BY key.
Fixed by gating on `ctx.get_precision(s).is_some()` in the new
`currency_hint_for_row` helper — only currencies with tracked
precision become hints. Test
`test_currency_hint_for_row_filters_untracked_currencies` pins
the contract end-to-end (USD with samples → hint; MADEUP without
samples → no hint, even though it passes the shape check).
3. **Hint-extraction logic was duplicated** between the width-pass
and the row-print pass in `write_text`. Factored out into the
new `currency_hint_for_row(result, row_idx, ctx)` helper.
4. **(Implicit) `looks_like_currency` docstring overstated safety.**
The original comment claimed false positives were "no-op";
they're not, per #2 above. Rewrote the docstring to call out
the two-step gate (shape check + precision check) and pointer
to the `currency_hint_for_row` site that enforces it.
Net change: +119 / -55 across 4 files. All 131 query tests still
pass; new test pins the precision-gate contract.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 7, 2026
…1022) * fix(query): quantize SUM-aggregate text output via GROUP BY currency `SUM(number) GROUP BY currency` (and equivalent implicit-grouping patterns) emit a `Value::Number` that carries no currency context, so text rendering went through the fallback `format_default` path that preserves rust_decimal's natural scale. When inputs had varying scales (e.g. one 0.00 + one 5.213), the sum kept the wider scale and rendered `0.000` / `5.213` instead of bean-query's `0.00` / `5.21`. Of the ~99 post-#986 BQL compat mismatches, ~15 fell into this bucket. Issue #988 recommended Option A (quantize at aggregation time), but that conflicts with its own AC #4 ("CSV/JSON output of aggregates remains lossless") — quantizing in the aggregator mutates inputs for ALL output paths, not just text. This PR implements Option B as described in the issue body: plumb GROUP BY currency through to the renderer, quantize at text-render time only. Implementation: - `QueryResult` gains `row_group_keys: Vec<Option<Vec<Value>>>` — a parallel sidecar to `rows`. Aggregate path populates it via the new `add_aggregate_row(row, group_key)`; non-aggregate path still calls `add_row(row)` and gets `None` slots. - `cmd/query/output.rs::write_text` looks up the row's sidecar, finds the first currency-shaped string in the GROUP BY key (heuristic: uppercase initial, `[A-Z0-9'._-]`, ≤24 chars), and passes it as a hint to a new `format_value_with_hint`. - `format_value_with_hint` routes `Value::Number` cells through `DisplayContext::format(n, currency)` when a hint is present — per-currency precision via the same path used for `Value::Amount`. - CSV / JSON / beancount renderers still call `format_value` unchanged: lossless preserved, satisfying AC #4. Tests added in cmd::query::output: - `test_looks_like_currency_accepts_typical_currencies` - `test_looks_like_currency_rejects_non_currencies` - `test_format_value_with_hint_routes_number_through_per_currency_ctx` — pins the central dispatch: same Value::Number(0.000) renders as "0.00" with USD hint vs "0.000" without. - `test_format_value_with_hint_unknown_currency_falls_back_safely` — defense-in-depth for false-positive currency detection. All 131 rustledger-query tests still pass; existing rustledger CLI query snapshots unchanged. Closes #988. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(query): address PR #1022 review — sidecar sync + false-positive hint gate Copilot flagged four issues on the original commit. All real: 1. **`row_group_keys` desynchronizes after ORDER BY / LIMIT.** The sidecar is parallel to `rows`, but `sort_results` and the four `result.rows.truncate(limit)` sites mutated only `rows` — after sort or pagination, `row_group_keys[i]` no longer corresponded to row `i`, so currency hints would be applied to the wrong rows. Fixed by encapsulating the invariant inside `QueryResult`: - New `QueryResult::truncate(len)` truncates both vectors. - New `QueryResult::sort_by(F)` pair-sorts both vectors via a single `mem::take` + `zip` + `sort_by` + push-back, with `debug_assert_eq!` guarding the lengths. - `sort.rs` and all four LIMIT sites now go through these helpers. 2. **False-positive currency hint silently STRIPS trailing zeros.** `DisplayContext::format(n, currency)` falls back to `n.normalize().to_string()` when the currency has no tracked precision — `normalize()` strips trailing zeros, turning `0.000` into `0`. So a heuristic-only currency check ("uppercase, looks right") would render output WORSE than the pre-fix state for any unrecognized currency-shaped string in a GROUP BY key. Fixed by gating on `ctx.get_precision(s).is_some()` in the new `currency_hint_for_row` helper — only currencies with tracked precision become hints. Test `test_currency_hint_for_row_filters_untracked_currencies` pins the contract end-to-end (USD with samples → hint; MADEUP without samples → no hint, even though it passes the shape check). 3. **Hint-extraction logic was duplicated** between the width-pass and the row-print pass in `write_text`. Factored out into the new `currency_hint_for_row(result, row_idx, ctx)` helper. 4. **(Implicit) `looks_like_currency` docstring overstated safety.** The original comment claimed false positives were "no-op"; they're not, per #2 above. Rewrote the docstring to call out the two-step gate (shape check + precision check) and pointer to the `currency_hint_for_row` site that enforces it. Net change: +119 / -55 across 4 files. All 131 query tests still pass; new test pins the precision-gate contract. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(query): close test gaps + tighten invariants from deep review Self-review of #1022 surfaced real gaps that Copilot's first pass missed. All addressed in this commit; no production-code behavior change beyond visibility tightening and the `debug_assert!` → `assert!` upgrade in `QueryResult::sort_by`. API hardening: - `QueryResult::row_group_keys` marked `#[doc(hidden)]` and the invariant (parallel to `rows`, never reach in directly) is now in the struct's docstring. New public accessor `group_key(row_idx)` is the canonical read path; the renderer goes through it instead of touching the field. - `sort_by`'s `debug_assert_eq!` is now an unconditional `assert!` with a descriptive message — the lockstep invariant is load-bearing for correctness, not a debug-only sanity check. Test coverage: - `test_sort_by_keeps_row_group_keys_in_lockstep` — pins ORDER BY preserves row↔key alignment. - `test_truncate_keeps_row_group_keys_in_lockstep` — pins LIMIT. - `test_add_row_and_add_aggregate_row_mixed` — pins the invariant across interleaved aggregate/non-aggregate inserts. - `test_add_aggregate_row_empty_key_records_none` — pins the empty-key-becomes-None contract. - `test_csv_aggregate_output_preserves_unquantized_decimal` — pins AC #4 lossless contract for CSV. - `test_json_aggregate_output_preserves_unquantized_decimal` — same for JSON. - `test_beancount_aggregate_output_preserves_unquantized_decimal` — same for beancount output. - `test_text_aggregate_output_quantizes_via_currency_hint` — pins the divergence: text quantizes, the others don't. - `test_e2e_sum_group_by_currency_text_output_matches_per_currency_precision` — full pipeline: real BQL through Executor + write_text. The canary that fires if anyone reverts `add_aggregate_row` to `add_row` in the executor (helper-level tests stay green in that scenario; this one wouldn't). Docs: - Multi-currency-column GROUP BY rare-case behavior now documented on `add_aggregate_row` and the renderer's `currency_hint_for_row`. - Misleading "two `0.00 USD` values sum to `0.000`" example replaced with the real cause (mixed-scale inputs like `0.000` + several `0.00`s). - "Caught by Copilot review on PR #1022" self-references dropped — they would read awkwardly post-merge. 135 query tests + 11 renderer tests pass. Clippy + fmt clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(query): apply remaining deep-review improvements (13 items) Closes the 13 items from the second deep review of #1022. No production-behavior change beyond the visibility tightening, the heuristic narrowing, and the debug-only tripwire — all defensive. Encapsulation: - A: `row_group_keys` demoted from `pub` (with `#[doc(hidden)]`) to `pub(crate)`. External crates now MUST go through `group_key()`, closing the loophole where the renderer (or a future contributor) could violate the parallel-vector invariant by direct field access. Heuristic & perf: - B: `looks_like_currency` lower bound bumped from 1 to 2. Single uppercase letters aren't real currencies; the precision gate would filter them anyway, but tightening the heuristic makes the intent clearer and shrinks the false-positive surface. - C: per-row currency hints now resolved ONCE into a `Vec<Option<&str>>` before the width-calc and print passes, instead of recomputed per pass. Eliminates duplicate work + duplicated extraction code. Safety net: - L: `format_value_with_hint` gains a `debug_assert!` inside the `Value::Number + hint` branch that fires if a caller forgets the precision-gate filter. Discovered (and fixed) a false-fire when width-calc passes the hint to non-Number cells — the assert now scopes correctly to the dispatch branch where the hint is consumed. Test cleanups: - D: vacuous JSON assertion (`A || A`) replaced with a single clean check using raw strings + clearer reasoning comment. - E: dead `let _ = ctx;` in JSON test removed (write_json doesn't take a DisplayContext, so building one is dead code). - F: CSV assertion no longer relies on `\n` substring matching — parses by lines + commas, robust to CRLF on any platform. - G: e2e test asserts on the SUM cell anchored by row position + whitespace tokenization, instead of a global negative substring scan that could false-fire on unrelated `0.0001`-shaped output. - H: dropped the last "Copilot review on PR #1022" self-reference from a test docstring. New coverage: - I: `test_e2e_implicit_group_by_currency_text_output_quantized` — pins the implicit-GROUP-BY path (`SELECT currency, SUM(number)` without `GROUP BY`) also populates `row_group_keys`. Different executor code path (`extract_implicit_group_by_exprs`) that the explicit-GROUP-BY e2e test wouldn't catch. - J: `test_sort_by_panics_on_lockstep_violation` — `#[should_panic]` test that deliberately corrupts the parallel-vector invariant and verifies `sort_by`'s `assert_eq!` actually fires. - K: `test_currency_hint_for_row_finds_currency_in_multi_column_group_by_key` — pins the documented contract that `find_map` over the GROUP BY key correctly skips non-currency-shaped strings (account names) to reach the currency. Docs: - M: `add_row` docstring expanded to explain the sidecar consequence. 136 query tests + 13 renderer tests pass. Clippy + fmt clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(query): apply review #3 fixes (6 items) Items from the third deep review of #1022. All polish; no production behavior change. 1. Multi-currency-key first-wins test The previous test only verified "currency is found in multi-column key" — it would pass under "first match", "last match", or any matching strategy. New test `test_currency_hint_for_row_first_currency_wins_when_multiple` uses a key with TWO currency-shaped + tracked-precision strings (`[EUR, USD]` and reversed `[USD, EUR]`) so the assertion discriminates iteration order. Pins the contract documented on `add_aggregate_row`. 2. `sort_by` pre-allocation `Vec::reserve_exact(n)` on the now-empty `rows` and `row_group_keys` before the push-back loop. Skips incremental-grow allocations. Sub-millisecond at typical N; trivial cleanup. 3. `currency_hints` cache short-circuit Skip the per-row hint Vec allocation entirely when the result has no aggregate rows (the common case for non-aggregate queries). New `QueryResult::has_aggregate_rows()` accessor encapsulates the check (rather than reaching into `pub(crate)` field). Access pattern in the renderer changes to `currency_hints.get(i).copied().flatten()` so the empty-Vec case returns `None` cleanly. 4. Cache-lifetime documentation One-paragraph comment on the `currency_hints` declaration explaining the borrow constraint (`&str` entries borrow from `result`; safe while `result` is `&`-borrowed). Future refactors that mutate `result` mid-stream would break this; the comment makes the constraint visible without reading the borrow checker's mind. 5. Direct `add_row` test `test_add_row_records_none_in_sidecar` standalone (was covered indirectly by the mixed-row test). Pins the contract isolated from other helpers' behavior. 6. `group_key` returns `&[Value]` not `&Vec<Value>` Callers no longer tied to the specific container type. Test assertions updated to use `Some(&[...][..])` for the slice coercion. Also tightens `pub(crate) row_group_keys` access: external consumers MUST go through `group_key()` / `has_aggregate_rows()` accessors. 137 query tests + 14 renderer tests pass. Clippy + fmt clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Merged
4 of 5 tasks
robcohen
added a commit
that referenced
this pull request
Jun 9, 2026
…ve-formatting fixtures (#1292) * test(parser): #1262 phase 4.2 — format-compat suite with 30 destructive-formatting fixtures Phase 4.2 of the CST migration: pin the formatter's promise on every historical destructive-formatting bug class with file-pair golden fixtures (input.bean / expected.bean) and a runtime-walking harness. The file-pair shape complements the inline IDEMPOTENCE_MATRIX in crates/rustledger-parser/src/cst/format.rs::tests: - IDEMPOTENCE_MATRIX pins per-rule canonical-form behavior via property-style tests (idempotence, lexer agreement, round-trip through canonicalize_directives). Hand-edited in code review. - tests/format_compat/cases/ is the user-facing contract surface. Browse the directory to see what rledger format promises on a given input. Reviewers can read input.bean and expected.bean side by side without running the test runner. Both layers are load-bearing. The file-pair layer is the one external users will read when they want to understand what the formatter will do to their file. ## Coverage 30 fixtures across the bug classes that have caused destructive formatting historically: - issue_1252_destructive_repro — full reproducer from lutzky's issue. Pins the trailing-comment, pushtag/poptag, and cross-directive-tag-migration fixes from PR #1284. - trailing_comment_on_directive_header, trailing_comment_eof_no_newline, posting_trailing_comment — the trailing-comment preservation rule from PR #1284 round-7 (Copilot #1). - balance_leading_unary_minus_preserves_sign, balance_leading_parenthesized_expression, price_leading_unary_minus_preserves_sign, posting_arithmetic_with_parens — the sign-preservation rule from PR #1284 round-7 (Copilot #2). - cost_spec_per_unit_plus_total_marker — pins the {# ... } marker preservation (Copilot #3 false-alarm). - cost_spec_with_negative_amount, cost_spec_with_comma_and_date — cost-spec interior canonical form. - pushtag_poptag_pair_preserved, pushmeta_popmeta_pair_preserved — pragma directives survive a round-trip. - transaction_tags_and_links_source_order — source-order rule on transaction headers. - multiline_note_string_preserved, non_latin_account_names — Unicode and multi-line string interior preservation. - section_header_comments_tight, comment_with_unbalanced_quote — inter-directive comment positioning and state-machine agreement on stray quotes. - metadata_unary_minus_value, metadata_arithmetic_value — metadata value canonical form. - multiple_trailing_blank_lines_collapsed, missing_final_newline_added, bom_dropped — file-level whitespace canonicalization. - crlf_outside_strings_folded, crlf_inside_strings_preserved — CRLF line-ending rule. - balance_assertion_with_metadata, transaction_with_pending_flag, custom_directive_with_date_value, document_with_tags_and_links, options_includes_plugins_block — per-directive shape pins. ## Harness tests/format_compat.rs walks tests/format_compat/cases/ at runtime and asserts three properties per fixture: 1. format_source(input) == expected — the byte-exact contract. 2. format_source(expected) == expected — idempotence: re-formatting canonical text is a no-op. 3. parse(expected).errors is empty — the canonical output is itself parseable. Asserts MIN_FIXTURES = 24 as a coverage floor so a future contributor deleting cases by accident fails CI instead of silently dropping the regression net. ## Authoring A new fixture is two files: input.bean (what the user typed) and expected.bean (what the formatter promises). The bootstrap_format_compat example reads input.bean for every case and writes expected.bean by running format_source on it. After the initial bootstrap, expected.bean is the golden contract; the example refuses to overwrite unless BOOTSTRAP_OVERWRITE=1 is set, which keeps a stray re-run from silently re-baselining a fixture whose expected output was hand-edited to pin a deliberate canonical-form choice. ## Verified - cargo test -p rustledger-parser — all 230+ tests pass including the new format_compat test - cargo clippy -p rustledger-parser --all-features --all-targets -- -D warnings — clean - RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser --no-deps — clean Refs #1262. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix: address all 10 findings from the round-1 PR-1292 review 1. Stage-1 mismatch in format_compat.rs no longer `continue`s past the idempotence and parser-clean checks. All three stages run independently per fixture; a malformed expected.bean paired with a non-matching formatter output now surfaces both failures instead of hiding the unparsable golden file. 2. MIN_FIXTURES count floor (24 vs 30 actual) replaced with a REQUIRED_FIXTURES name-set. The count floor was too loose - six load-bearing fixtures could be silently deleted while passing CI. The name-set check forces removal of a critical bug-class fixture to be a deliberate, reviewable edit to the constant, not a silent disappearance from the cases directory. 3. Empty subdirectories no longer count toward the fixture set. The discovery filter requires each entry to actually contain input.bean, so a stray `mkdir` without a `git add` cannot mask coverage loss from a parallel deletion. 4. .gitattributes adds `crates/rustledger-parser/tests/format_compat/ cases/**/*.bean -text` so a Windows contributor with core.autocrlf=true sees the CRLF-bearing fixtures (crlf_outside_strings_folded, crlf_inside_strings_preserved) byte-for-byte as committed. Without this, the literal \r bytes inside the in-string-CR fixture would be silently normalized on checkout and the test would either fail mysteriously or pass for the wrong reason. 5. README "Bump it when you add cases" rewritten to match the harness rustdoc: adding cases is free, only retiring a required fixture changes REQUIRED_FIXTURES. 6. issue_1252_destructive_repro narrative cleaned up. The previous input had load-bearing comments ("Commas should stay", "bean-format does not remove plus signs, neither should rledger format") that became passive-aggressive once the expected.bean pinned the opposite behavior. The fixture now pins ONLY the destructive-bug fixes (trailing comments, pushtag/poptag, cross-directive tag migration). The canonical-form choices on commas and unary `+` move to two dedicated fixtures: - commas_stripped_per_canonical_form - unary_plus_stripped_per_canonical_form These document the PR-4 decision explicitly and link the dispute back to #1252 in their input.bean comments. If the team later flips one of these choices, exactly one fixture's expected.bean changes - the historical destructive-bug pin stays stable. 7. posting_with_interleaved_metadata fixture added to cover the #1142 bug class (per-posting metadata interleaved between postings of the same transaction). The harness rustdoc claimed #1142 coverage but no fixture exercised the shape; balance_assertion_with_metadata only puts metadata on a balance directive, not interleaved between transaction postings. 8. README "what belongs here vs IDEMPOTENCE_MATRIX" section narrowed to acknowledge the overlap. Roughly half of the file-pair fixtures are reviewable mirrors of inline-matrix entries; the other half (issue_1252 repro, BOM, CRLF, pragma blocks, canonical-form-choice fixtures, posting-interleaved- metadata) are genuinely-new coverage shapes that don't fit the inline-string format ergonomically. Both layers are kept, the file-pair layer is the user-facing contract surface. 9. escape_for_diff no longer pass-throughs non-`\n\r\t` control bytes. NUL / BEL / VT / FF / DEL now render via `char::escape_debug` as visible escape sequences, so a fixture mismatch whose only delta is a stray control byte renders visibly in the failure output instead of looking byte-identical to the maintainer. 10. Bootstrap example gains BOOTSTRAP_FIXTURE=<name> for scoped re-baselining. The default (no env vars) skips fixtures with existing expected.bean. BOOTSTRAP_FIXTURE rewrites exactly one named fixture; an unknown name exits non-zero before touching any file. BOOTSTRAP_OVERWRITE=1 still rewrites the whole suite but the summary line warns to review `git diff` carefully before committing. The previous shape made BOOTSTRAP_OVERWRITE=1 the only way to re-baseline ANY fixture, which silently rebaselines unrelated golden files. Verified: cargo test -p rustledger-parser (230+ tests including the new format_compat shape), cargo clippy -p rustledger-parser --all-features --all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser --no-deps. All clean. The harness also passes with a bogus empty subdir present in cases/ (filter confirmed). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix: address Copilot inline review comments on PR #1292 Replace `filter_map(Result::ok)` in the format-compat harness and the bootstrap example with explicit `unwrap_or_else(|e| panic!(...))` on each `read_dir` entry. Per-entry errors now panic with a diagnostic instead of being silently dropped, matching the convention in `tests/baseline_common::walk`. The previous shape was a recall hole. If a permission or filesystem fault hit one fixture directory (e.g. a stale `.partial` upload from a backup tool, an inaccessible sub-tree on a CI runner), the entry would be discarded with no diagnostic. The harness would still pass the count floor and the bootstrap would print "wrote N files" as if the run was complete, hiding the silent coverage drop. Copilot's third comment (about missing `.gitattributes` rule for the CRLF fixtures) was already addressed in the round-1 review fixes (commit 30adb81). The bot's review fired against the pre-fix commit; that finding is moot. Verified: cargo test -p rustledger-parser --test format_compat, cargo clippy -p rustledger-parser --all-features --all-targets -- -D warnings. All clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix: address all 10 findings from the round-2 PR-1292 review 1. escape_for_diff now routes everything outside ASCII-printable through `char::escape_debug`, which renders BOM (U+FEFF), zero- width spaces (U+200B..=U+200D, U+2060), C1 controls (U+0080..=U+009F), and other format-category codepoints as visible `\u{...}` escapes. The previous shape passed those bytes through verbatim, so a regression that stopped stripping the BOM would have rendered `--- expected ---` and `--- got ---` panels byte-identical to the eye - undermining the bom_dropped fixture's whole purpose. Printable non-ASCII Unicode (Cyrillic, CJK, Greek, etc.) still passes through unchanged because escape_debug preserves printable categories. 2. `present_names` is now built via `to_string_lossy().into_owned()` instead of `.to_str().map(String::from)`. The previous shape silently dropped non-UTF-8 directory names from the set, so a present-but-non-UTF-8-named REQUIRED fixture would have been falsely reported as missing. Aligns with the bootstrap example's name-extraction policy. 3. REQUIRED_FIXTURES check now runs against the RAW directory listing (every subdir), not the filtered-for-input.bean set. A required fixture whose directory exists but is missing input.bean now surfaces as `[name] missing input.bean` in the per-fixture failure log, not as the misleading "required fixture missing from cases dir" assert. The two failure shapes correspond to two distinct contributor mistakes (forgot to create the dir vs. forgot to `git add` the input file); the error message now disambiguates them. 4. Bootstrap summary branch order swapped: target_fixture is checked BEFORE overwrite_all, so the combined `BOOTSTRAP_OVERWRITE=1 BOOTSTRAP_FIXTURE=<name>` invocation prints "only the named fixture's expected.bean was rewritten" instead of the previous misleading "rewritten across the whole suite". The actual write behavior was already correct; only the summary line was lying. 5. MIRROR_PAIRS constant added to tests/format_compat.rs listing 17 (file_pair_name, matrix_name) bug-class twins across the file-pair suite and the inline IDEMPOTENCE_MATRIX. The integration test asserts every file_pair_name exists as a directory under cases/. A new inline unit test `idempotence_matrix_mirrors_format_compat_pairs` in cst::format::tests asserts every matrix_name exists in IDEMPOTENCE_MATRIX. A one-sided deletion now requires editing both lists (or fails CI on the unedited side), enforcing the "two audience" coverage coupling the README's split design previously left as documentation-only. 6. REQUIRED_FIXTURES grew from 20 to 25 entries. Promoted from non-required: - multiline_note_string_preserved (string-literal interior preservation, classic destructive-formatting class) - balance_assertion_with_metadata (per-directive metadata attachment, sibling of #1142) - transaction_tags_and_links_source_order (tag/link ordering preservation, sibling of #1252) - metadata_unary_minus_value (sign preservation on metadata values) - non_latin_account_names (Unicode column-alignment correctness) Each was identifiably load-bearing for a regression class but could previously be deleted without tripping the floor check. 7. Stale rustdoc on `canonicalize_directives` in cst/format.rs disambiguated. The reference to "the deleted format_compat test" was ambiguous now that PR #1292 reintroduces a format_compat test in a different crate. Rustdoc now names the OLD test (crates/rustledger/tests/format_compat.rs, deleted in phase 4.1) explicitly and clarifies the new file-pair suite does NOT exercise canonicalize_directives' reparse-error path. 8. Stages 2 and 3 of the harness now run inside `catch_unwind`. A panic in format_source or parse on a pathological expected no longer aborts the entire test and discards the stage-1 failures recorded for earlier fixtures in the same loop. The panic is recorded as a per-fixture failure with a clear message ("format_source is contracted to be total over arbitrary input; this is a bug") so the contributor knows the regression is in the formatter, not the fixture. 9. Bootstrap's BOOTSTRAP_FIXTURE validation now requires the target fixture's input.bean to exist before allowing any I/O. The previous shape exited 0 with "wrote 0, missing input 1" on a BOOTSTRAP_FIXTURE=name where `cases/name/` was an empty directory (no input.bean), which a contributor could misread as "bootstrap succeeded". The new check exits with code 3 and a clear "directory has no input.bean" message. Distinct from the existing code 2 "directory does not exist" path. 10. issue_1252_destructive_repro/input.bean now opens with a cross-reference comment pointing forward to the commas_stripped and unary_plus_stripped sibling fixtures. A reviewer auditing the #1252 fixture no longer reads the `commas_stripped/input.bean` claim that "the dispute is tracked in #1252" and then finds zero comma cases in the #1252 fixture itself. Verified: cargo test -p rustledger-parser (231+ tests; new idempotence_matrix_mirrors_format_compat_pairs unit test green), cargo clippy -p rustledger-parser --all-features --all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser --no-deps. All clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
Jun 10, 2026
Addresses 10 deep-review findings + 5 Copilot inline comments (all converging on the same byte-identity / doc-drift / cache- reach themes). ## Correctness - `format_source_with_parsed` now falls back to `format_source(source)` when `parse_result.errors` is non- empty. Preserves byte-identity for inputs whose CST diverges from what `format_source`'s pre-parse normalization would produce — concretely, bare-`\r` (classic Mac) line terminators that `crlf_to_lf_outside_strings` normalizes but `parse_via_cst` does not. Without this fallback, classic-Mac sources would emit different text on the cached path vs format_source. - Defensive length-check `debug_assert_eq!` catches the most common form of `(parse_result, source)` mismatched pair (different documents have different lengths). Released as `debug_assert_eq!` so release builds pay no cost; debug builds panic on mismatched pair. New test `format_source_with_parsed_panics_on_length_mismatch` pins the debug-build behavior. ## More cache reach - CLI `try_format_source` (the entry that backs `rledger format`) switched from `format_source(source)` to `format_source_with_parsed(&result, source)`. The CLI was the one consumer round-1 missed — same shape as the LSP/FFI/WASM migrations. - `rledger doctor roundtrip` switched similarly. On a project of 200 included files the doctor pass roughly halves its parsing cost. ## Test fixture expansion Added three new fixtures to `format_source_with_parsed_matches_format_source`: - **BOM + CRLF combination** — Windows-authored ledger with a UTF-8 BOM. - **Parse-error file** — exercises the new error-gate fallback. - **Bare-CR line terminators** — classic-Mac source; exercises the fallback (`parse_via_cst` errors out on bare CR). ## Hot-path costs - `assert_eq!` → `debug_assert_eq!` in `format_node_with_alignment` and `format_node_range_with_alignment`. The bare `format_node` / `format_node_range` delegates already validated kind via `SourceFile::cast`, so on the most common call path (bare → with_alignment) the assert was a redundant release-build cost. External direct callers still get a debug-build panic on wrong-kind input. ## Rustdoc fixes (Copilot inline #1 / #3 / #4 / #5) - Three rustdoc cites pointed at non-existent tests: `compute_alignment_matches_parseresult_cache` (lib.rs:309, format.rs:858 in `compute_alignment`, convert.rs:272 inline comment) and `format_node_range_with_alignment_matches_uncached` (format.rs:812). Renamed to point at actual test names (`parse_result_alignment_cache::*` and `format_node_range_matches_format_node_range_with_alignment`). - `compute_alignment(node)` doc claim corrected: the function takes `&SourceFile`, not `&SyntaxNode`. Updated to `compute_alignment(&SourceFile::cast(node).unwrap())` in both occurrence sites. - `syntax_node().cast::<SourceFile>()` invalid turbofish in rustdoc fixed to `SourceFile::cast(syntax_node()).unwrap()`. ## Public API path consistency (Copilot inline #2) `ParseResult::alignment` field type spelled as `crate::format::PostingAlignment` (via the public re-export surface) instead of `crate::cst::format::PostingAlignment` (the internal module path). Matches the documented "sole import path" convention in `crate::format` module rustdoc. ## CHANGELOG naming rationale tightened Cited the live existing `rustledger_core::Alignment` (an unrelated workspace type used by the legacy typed-Directive emitter) as the concrete reason for naming the new type `PostingAlignment` instead of bare `Alignment`. Round-1 only mentioned hypothetical future collisions. ## Stale rustdoc reference `Alignment::default()` → `PostingAlignment::default()` in the `format_node_with_alignment` rustdoc. ## Criterion benchmark New `bench_format_source_vs_with_parsed` group in `benches/parser_bench.rs`. Compares `format_source(s)` against `format_source_with_parsed(&pre_parsed, s)` on 10 / 100 / 1000 transaction synthetic ledgers. Provides an executable witness for the PR's perf claim. ## Verified - `cargo test -p rustledger-parser -p rustledger-lsp -p rustledger-ffi-wasi -p rustledger --all-features` — 224 LSP lib + 263 parser lib + 58 FFI lib + integration suites green (parser: 262 -> 263 with the new debug-build panic test). - `cargo clippy --workspace --all-features --all-targets -- -D warnings` clean. - `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p rustledger-lsp --no-deps` clean. - Baseline manifest unchanged. Refs #1299. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
Jun 10, 2026
…es (#1299) * chore(deps): #1262 unyank aes 0.9.0 -> 0.9.1 cargo deny check surfaced aes 0.9.0 (transitive via zip 8.6.0 -> rustledger-plugin) as a yanked version. cargo update -p aes resolves to 0.9.1, the immediate successor that drops the yank mark. Lockfile-only change, no source diff in the workspace, no semver impact on rustledger-plugin or its consumers. cargo deny check now reports advisories ok, bans ok, licenses ok, sources ok across the workspace. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(parser,lsp): cache formatter alignment on ParseResult Pre-compute the formatter's file-wide alignment columns at parse time and stash them on `ParseResult::alignment`, so hot formatting paths (notably the LSP `range_formatting` fallback shipped in #1298) don't re-walk every posting in the file on every call. ## Background `format_node` and `format_node_range` (in `rustledger-parser/src/cst/format.rs`) run a pre-pass over every Transaction's postings to compute file-wide alignment columns: `number_col` (where the right-justified number field starts) and `number_width` (max rendered width of any number). The pre-pass is `O(N_postings_in_file)` per call. This is fine for the CLI's one-shot `rledger format`, but the LSP `range_formatting` fallback path can be invoked per-keystroke by format-on-type clients while the user is editing through a parse error. A 10k-directive ledger with a typo means we walked 10k directives' postings on every key press. The PR #1298 review flagged this as a real concern (deferred at the time as acceptable). ## What's in this PR ### Parser - `format::Alignment` is now `pub` + `#[non_exhaustive]` + `Copy`, with public `number_col` / `number_width` fields. Construction via `Alignment::default()` is supported externally; the `#[non_exhaustive]` attribute reserves the right to add fields later without breaking downstream `match` arms. - `format::compute_alignment(&SourceFile) -> Alignment` is now `pub` so consumers can pre-compute independently. - `ParseResult::alignment: Alignment` populated by `parse_via_cst` during the existing `walk_descendants_once` pass. Same canonical- payload exclusion pattern as `syntax_root`: bound in the destructure for compiler-enforced exhaustiveness, discarded from the canonical hash. Pinned by `canonical_payload_excludes_alignment`. - Two new `_with_alignment` variants: `format::format_node_with_alignment(node, alignment) -> String` and `format::format_node_range_with_alignment(node, range, alignment)`. The bare `format_node` / `format_node_range` delegate to them after computing alignment internally — no behavior change for existing callers, just a new opt-in fast path. - Equivalence pinned: `format_node_equals_format_node_with_alignment` and `format_node_range_matches_format_node_range_with_alignment` assert byte-identical output across representative fixtures. The cache's freshness vs. a fresh `compute_alignment` call is pinned by `parse_result_alignment_cache::*` (6 fixtures including empty source, open-only, single transaction, multi-transaction with varying widths, arithmetic amounts, and a parse-error file). ### LSP - `fallback_cst_snap_edit` in `range_formatting.rs` now calls `format_node_range_with_alignment(&node, cst_range, parse_result.alignment)` instead of `format_node_range(&node, cst_range)`. The per-call `O(N_postings)` walk is gone; per-fallback cost is now `O(N_cst_nodes covered by the user's range)`, independent of file size. ### Deps - `cargo update -p aes` to unyank the transitive dependency `aes 0.9.0 -> 0.9.1`. Surfaced by `cargo deny check`. Lockfile-only, no source diff anywhere in the workspace. ## Why both in one PR The dependency unyank is a single-line lockfile change that would otherwise sit in its own trivial PR. Keeping it next to the substantive change is a closing housekeeping pass; the two commits are clean (`chore(deps):` + `feat(parser,lsp):`) so they can be split during review if desired. ## Verified - `cargo test -p rustledger-parser -p rustledger-lsp --all-features` (224 LSP lib + 260 parser lib green; parser format module suite went 250 -> 260 with the 10 new tests spread across `cst::format::tests`, `parse_result_alignment_cache`, `canonical_payload_excludes_alignment`). - `cargo clippy --workspace --all-features --all-targets -- -D warnings` clean. - `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p rustledger-lsp --no-deps` clean. - `cargo deny check` now reports `advisories ok, bans ok, licenses ok, sources ok`. - Baseline manifest unchanged (the canonical-payload exclusion works as designed; the new test pins it executably). Refs #1262 (post-completion follow-up flagged in the closing comment). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * chore: regenerate cargo-vet exemptions * fix(parser,lsp,ffi,wasm): #1299 round-1 review findings Addresses 10 deep-review findings on PR #1299. Same root cause for the largest one: the original PR optimized only the rare parse-error LSP fallback path; the much more common Format-on- Save / FFI format.source / WASM ParsedLedger::format paths still re-parsed the source and re-walked every posting, leaving the cache mostly dead code. ## Cache reaches the happy path now - New public entry `format::format_source_with_parsed(&ParseResult, &str)` reuses the cached `syntax_root` AND `alignment`, skipping both the duplicate parse and the duplicate alignment walk. - LSP `handle_formatting` / `format_document` switched to `format_source_with_parsed`. The Format-on-Save / format-on- type-clean-file paths now pay only the per-call emit cost. - FFI `format.source` (rustledger-ffi-wasi/src/jsonrpc/router.rs) switched: it already produced `parse_result` for the error gate; the second parse via `format_source` is gone. - WASM `ParsedLedger::format` (already-cached `parse_result` field) and `api::format_source` (already-produced `parse_result`) both switched. - Byte-identical output pinned by new `format_source_with_parsed_matches_format_source` test across LF / CRLF / BOM-prefixed fixtures. The two paths produce the same canonical text because the canonical form is rebuilt from typed values rather than echoing trivia. ## Type rename: Alignment -> PostingAlignment The public type was just introduced this week (no shipped consumers); the cheapest moment to rename. `Alignment` is too generic for `rustledger_parser::format::Alignment` and would compete with future text-justification or memory-layout helpers. `PostingAlignment` is qualified by its semantic purpose. Re- export, struct definition, field type on `ParseResult::alignment`, all internal `align: Alignment` parameter sites, and the `canonical_payload_excludes_alignment` test all updated. ## Cast cleanup in _with_alignment fns `format_node_with_alignment` and `format_node_range_with_alignment` each replaced their `SourceFile::cast(node.clone()).expect(...)` + misleading `let _ = source_file;` precondition with `assert_eq!(node.kind(), SyntaxKind::SOURCE_FILE)`. Saves the redundant Arc-bump clone on every hot-path call (the bare `format_node` delegate already validated the kind) while keeping the same panic guarantee for direct external callers. The `format_node_with_alignment` body now uses `node.children_with_tokens()` directly instead of `source_file.syntax().children_with_tokens()`. ## Docs - `compute_alignment` rustdoc grew a `Tree-shape precondition` section documenting the must-be-just-parsed contract: hand-built partial trees and ERROR_NODE-wrapped transactions silently fall back to `PostingAlignment::default()`. Behavior pinned by the new `parse_result_alignment_cache::mid_transaction_error_node` test. - `ParseResult::alignment` rustdoc grew a `Producer-only cache invariant` section explaining what happens if a consumer mutates `directives` / `syntax_root` without refreshing the cache, and pointing them at `compute_alignment` for the manual refresh. - CHANGELOG entry rewritten to list the three public entry points (node, node_range, source), document the `PostingAlignment` naming choice, and capture the producer-only invariant. ## Tests - Existing 10 cache-equivalence tests still pass. - 1 new test pins `format_source_with_parsed` byte-identity vs `format_source` across LF / CRLF / BOM fixtures. - 1 new test pins cache equivalence under mid-transaction ERROR_NODE recovery — the scenario the LSP fallback actually traverses during format-on-type. ## Verified - `cargo test -p rustledger-parser -p rustledger-lsp -p rustledger-ffi-wasi --all-features` — 224 LSP lib + 262 parser lib + 58 FFI lib + integration suites green (parser: 260 -> 262 with the 2 new tests). - `cargo clippy --workspace --all-features --all-targets -- -D warnings` clean. - `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p rustledger-lsp -p rustledger-ffi-wasi -p rustledger-wasm --no-deps` clean. - Baseline manifest unchanged. Refs #1299. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(parser,lsp,cli): #1299 round-2 review findings + Copilot inline Addresses 10 deep-review findings + 5 Copilot inline comments (all converging on the same byte-identity / doc-drift / cache- reach themes). ## Correctness - `format_source_with_parsed` now falls back to `format_source(source)` when `parse_result.errors` is non- empty. Preserves byte-identity for inputs whose CST diverges from what `format_source`'s pre-parse normalization would produce — concretely, bare-`\r` (classic Mac) line terminators that `crlf_to_lf_outside_strings` normalizes but `parse_via_cst` does not. Without this fallback, classic-Mac sources would emit different text on the cached path vs format_source. - Defensive length-check `debug_assert_eq!` catches the most common form of `(parse_result, source)` mismatched pair (different documents have different lengths). Released as `debug_assert_eq!` so release builds pay no cost; debug builds panic on mismatched pair. New test `format_source_with_parsed_panics_on_length_mismatch` pins the debug-build behavior. ## More cache reach - CLI `try_format_source` (the entry that backs `rledger format`) switched from `format_source(source)` to `format_source_with_parsed(&result, source)`. The CLI was the one consumer round-1 missed — same shape as the LSP/FFI/WASM migrations. - `rledger doctor roundtrip` switched similarly. On a project of 200 included files the doctor pass roughly halves its parsing cost. ## Test fixture expansion Added three new fixtures to `format_source_with_parsed_matches_format_source`: - **BOM + CRLF combination** — Windows-authored ledger with a UTF-8 BOM. - **Parse-error file** — exercises the new error-gate fallback. - **Bare-CR line terminators** — classic-Mac source; exercises the fallback (`parse_via_cst` errors out on bare CR). ## Hot-path costs - `assert_eq!` → `debug_assert_eq!` in `format_node_with_alignment` and `format_node_range_with_alignment`. The bare `format_node` / `format_node_range` delegates already validated kind via `SourceFile::cast`, so on the most common call path (bare → with_alignment) the assert was a redundant release-build cost. External direct callers still get a debug-build panic on wrong-kind input. ## Rustdoc fixes (Copilot inline #1 / #3 / #4 / #5) - Three rustdoc cites pointed at non-existent tests: `compute_alignment_matches_parseresult_cache` (lib.rs:309, format.rs:858 in `compute_alignment`, convert.rs:272 inline comment) and `format_node_range_with_alignment_matches_uncached` (format.rs:812). Renamed to point at actual test names (`parse_result_alignment_cache::*` and `format_node_range_matches_format_node_range_with_alignment`). - `compute_alignment(node)` doc claim corrected: the function takes `&SourceFile`, not `&SyntaxNode`. Updated to `compute_alignment(&SourceFile::cast(node).unwrap())` in both occurrence sites. - `syntax_node().cast::<SourceFile>()` invalid turbofish in rustdoc fixed to `SourceFile::cast(syntax_node()).unwrap()`. ## Public API path consistency (Copilot inline #2) `ParseResult::alignment` field type spelled as `crate::format::PostingAlignment` (via the public re-export surface) instead of `crate::cst::format::PostingAlignment` (the internal module path). Matches the documented "sole import path" convention in `crate::format` module rustdoc. ## CHANGELOG naming rationale tightened Cited the live existing `rustledger_core::Alignment` (an unrelated workspace type used by the legacy typed-Directive emitter) as the concrete reason for naming the new type `PostingAlignment` instead of bare `Alignment`. Round-1 only mentioned hypothetical future collisions. ## Stale rustdoc reference `Alignment::default()` → `PostingAlignment::default()` in the `format_node_with_alignment` rustdoc. ## Criterion benchmark New `bench_format_source_vs_with_parsed` group in `benches/parser_bench.rs`. Compares `format_source(s)` against `format_source_with_parsed(&pre_parsed, s)` on 10 / 100 / 1000 transaction synthetic ledgers. Provides an executable witness for the PR's perf claim. ## Verified - `cargo test -p rustledger-parser -p rustledger-lsp -p rustledger-ffi-wasi -p rustledger --all-features` — 224 LSP lib + 263 parser lib + 58 FFI lib + integration suites green (parser: 262 -> 263 with the new debug-build panic test). - `cargo clippy --workspace --all-features --all-targets -- -D warnings` clean. - `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p rustledger-lsp --no-deps` clean. - Baseline manifest unchanged. Refs #1299. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> Co-authored-by: rustledger-bot[bot] <257329324+rustledger-bot[bot]@users.noreply.github.com>
robcohen
added a commit
that referenced
this pull request
Jun 19, 2026
Follow-up to the review on #1435. Instead of running the plugin and relabeling the failure by name-shape, detect a bare module-name reference *before* invoking the runtime: - Correctness (#1): the old error-path relabel discarded the real error `e` for any dotted/non-.py name — masking genuine failures such as a corrupt runtime download (`PythonRuntime::new()` fails before module discovery). Now module names are rejected up front, so the `Err(e)` arm only fires for real plugin files and surfaces `e` verbatim (E8002). - Altitude (#2): no runtime is downloaded/compiled (and no "10-100x slower" warning printed) for a request that is rejectable from the name alone. - Reuse/consistency (#3): both E8004 sites now share `module_ref_message`, so the "not supported by module name; reference the file directly" guidance is identical everywhere. - Discriminator (#4): one `is_python_module_name` helper using `eq_ignore_ascii_case`, not the pre-lowercased `ext` (fixes a latent case-sensitivity coupling). - Docs (#5): document E8002/E8004/E8005 in docs/reference/errors.md. - Cleanup (#6,#7): static example path (drops the dead `unwrap_or` and the `./.py` trailing-dot edge); drop the redundant `is_python_available()` guard (`suggest_module_path` already handles a missing interpreter). fmt + clippy (-D warnings, python-plugins) clean; loader suite 64/64. Co-Authored-By: Claude Opus 4.8 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Jun 19, 2026
* fix(loader): actionable error for module-name Python plugin refs A Python plugin declared by module name (beancount's `plugin "pkg.mod"`) is unsupported by design — only file-path references load (see `discover_module_source`). It routes into the Python-plugin branch (the name contains a dot), runs, and fails inside `execute_module`, surfacing as `E8002: Python plugin 'pkg.mod' execution failed: Python plugin module not found: pkg.mod` — doubly misleading, reading as a venv/PYTHONPATH problem the user cannot fix. Detect the bare-module-name case in the error path and emit an actionable `E8004` instead: name the unsupported form and point at the file path, resolving it via system Python (`suggest_module_path`) when possible, else a generic hint that also notes the sandbox cannot see the host venv (the plugin must be self-contained). This also unifies the code with the parallel unknown-plugin branch (both `E8004`). The existing `suggest_module_path`/`E8004` hint was unreachable for real module names because they always contain a dot and were diverted into the Python branch first. Closes #1432 (Gap 1). Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(plugins): document Python plugin file-path + self-contained model Gaps 2-3 of #1432. Document that: - Built-in names resolve to the native Rust plugin regardless of the `beancount.plugins.` prefix (so `plugin "beancount.plugins.auto_accounts"` is unchanged), but a custom Python plugin must be referenced by file path — the module-name form is rejected. - Python plugins run in a CPython-WASI sandbox that never mounts the host venv / site-packages, so they must be self-contained (stdlib + the bundled beancount compat shim); anything heavier needs a native Rust plugin. Adds a "Referencing a Python Plugin" + "Plugin Sandbox" section to docs/reference/plugins.md and a file-path note to docs/migration/from-beancount.md (clarifying that the existing auto_accounts example works because it resolves to a native plugin, not Python). Co-Authored-By: Claude Opus 4.8 <[email protected]> * refactor(loader): reject module-name plugins up front; address review Follow-up to the review on #1435. Instead of running the plugin and relabeling the failure by name-shape, detect a bare module-name reference *before* invoking the runtime: - Correctness (#1): the old error-path relabel discarded the real error `e` for any dotted/non-.py name — masking genuine failures such as a corrupt runtime download (`PythonRuntime::new()` fails before module discovery). Now module names are rejected up front, so the `Err(e)` arm only fires for real plugin files and surfaces `e` verbatim (E8002). - Altitude (#2): no runtime is downloaded/compiled (and no "10-100x slower" warning printed) for a request that is rejectable from the name alone. - Reuse/consistency (#3): both E8004 sites now share `module_ref_message`, so the "not supported by module name; reference the file directly" guidance is identical everywhere. - Discriminator (#4): one `is_python_module_name` helper using `eq_ignore_ascii_case`, not the pre-lowercased `ext` (fixes a latent case-sensitivity coupling). - Docs (#5): document E8002/E8004/E8005 in docs/reference/errors.md. - Cleanup (#6,#7): static example path (drops the dead `unwrap_or` and the `./.py` trailing-dot edge); drop the redundant `is_python_available()` guard (`suggest_module_path` already handles a missing interpreter). fmt + clippy (-D warnings, python-plugins) clean; loader suite 64/64. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(loader): recognize forward-slash plugin paths on Windows + unit tests Addresses the Copilot review note: is_python_module_name checked only std::path::MAIN_SEPARATOR (`\` on Windows), so a forward-slash file ref like "plugins/foo" could be misclassified as a module name there. Check both `/` and the platform separator. Adds direct unit tests for is_python_module_name (module vs .py vs path-separated vs existing-file, case-insensitive ext) and module_ref_message (both the resolved-path and fallback branches — also covering the line codecov flagged). Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
This was referenced Jun 20, 2026
robcohen
added a commit
that referenced
this pull request
Jun 23, 2026
…gs stream (BR8 step 3 final) (#1559) * refactor(query): build_postings_table consumes the shared scan_postings stream (BR8 step 3 final) Extract scan_postings from collect_postings (the single posting scan: iterate + optional FROM/WHERE + accumulate balance/account_balance -> PostingContext); collect_postings becomes a thin wrapper computing the #1080 gates. build_postings_table now drives scan_postings(None, None, all-gates) and reads balance/account_balance from each context instead of its own accumulator loop, and its redundant date-sort is removed (the loader pre-sorts; the other scanners do not re-sort). One iteration, not two -- eliminating the duplicated accumulation that was the source of bug #2. No perf regression; #postings parity test + full query suite unchanged. * query: address review — correct account_balance/FROM comment; assert scan invariants with expect Copilot: (1) account_balance is independent of WHERE, not FROM (the FROM clause is honored) — fix the comment; (2)/(3) scan_postings(None,None,..) is infallible and always sets directive_index, so use expect to assert those invariants instead of silently returning an empty table / attributing rows to directive 0.
robcohen
added a commit
that referenced
this pull request
Jun 25, 2026
dhat profiling (the new profiling data branch) ranked tokenize_inner and lossless_kind_tokens as the #1/#2 allocators -- both grew an unsized Vec via push, reallocating ~17x. Reserve Vec::with_capacity(source.len() / 4) (~4 bytes per beancount token). Measured on a 10k-txn workload: total heap allocated 158.7MB -> 141.6MB (-10.8%); tokenize_inner 17 allocations -> 1. Parser tests + clippy clean; allocation-only, behavior-preserving.
robcohen
added a commit
that referenced
this pull request
Jun 25, 2026
… (-10.8% heap) (#1587) * perf(parser): pre-size lexer token vectors to kill reallocation churn dhat profiling (the new profiling data branch) ranked tokenize_inner and lossless_kind_tokens as the #1/#2 allocators -- both grew an unsized Vec via push, reallocating ~17x. Reserve Vec::with_capacity(source.len() / 4) (~4 bytes per beancount token). Measured on a 10k-txn workload: total heap allocated 158.7MB -> 141.6MB (-10.8%); tokenize_inner 17 allocations -> 1. Parser tests + clippy clean; allocation-only, behavior-preserving. * perf(parser): cap the token-vector reservation (avoid pathological over-reserve)
This was referenced Jun 27, 2026
robcohen
added a commit
that referenced
this pull request
Jul 1, 2026
…p oversell (#1666, #1668) (#1669) #1666 — reducing a labeled cost lot dropped the matched lot's label (single-lot path set label: None while the multi-lot path preserved it), so the reduction didn't net against its augmenting lot and left a phantom unlabeled negative lot in the holdings view. Carry the matched lot's label onto the reduction posting (as the date already was). rustledger-booking/src/book.rs. #1668 #2 — a balance asserted in a currency the account doesn't allow only got a confusing 'Balance failed ... got 0 EUR'. Add a dedicated 'Invalid currency ... for Balance directive' diagnostic (E-code CurrencyNotAllowed) in validate_balance_early, mirroring the transaction currency check; only when the account constrains its currencies. #1668 #1 — an oversell reported 'Not enough units' twice via the FFI: booking (inside load_source) reports it WITH transaction context, and the #1663 validation session re-derived it context-free (its reduce-check is a standalone-validation safety net). Drop the session's copy when a load error already conveys it. The CLI never doubled (it partitions booking-failed txns out before late validation). #1668 #3 — investigated, no change: rustledger already flags duplicate open across includes (E1002 on the CLI), and #1663 made the FFI load path validate too, so it is caught there as well; the report reflects the pre-#1663 non-validating load. Tests: booking reduction-label netting; balance wrong-currency (+ unconstrained no-false-positive); FFI parity oversell-single-error. 94 validate + 106 booking + 19 FFI parity pass; clippy -D warnings + fmt clean. Closes #1666 Co-authored-by: Claude Opus 4.8 <[email protected]>
This was referenced Jul 1, 2026
robcohen
added a commit
that referenced
this pull request
Aug 11, 2026
#2008 cases 1 and 2, stacked on the transaction-header PR. #1 `10 AAPL {, 100.0 USD, , }` beancount: unexpected COMMA, expecting HASH or CAPITAL or CURRENCY #2 `1.1 AAPL {45.23 USD / 2015-07-16 / "blabla"}` beancount: unexpected SLASH, expecting RCURL or COMMA beancount's cost spec is a comma-separated component list where each component is a compound_amount, DATE, STRING or `*`. An empty component is not a component, and CURRENCY completes a compound_amount so nothing but `,` or a closer may follow it. The obvious reading of case 2 - "SLASH is illegal in a cost spec" - is wrong and would have been worse than the bug. `/` is a number_expr operator: `{10.00 * 3 USD}` is valid and archives 30.00 (#1939/#1942), so a token ban would have passed both fixtures and broken every ledger that divides in a cost spec. The defect is positional, which is what beancount's own message says ("expecting RCURL or COMMA"). `*` is left as ordinary content for the same reason - it is both the "any lot" component and multiplication, and reading it as a complete component turns `{10.00 * 3 USD}` into junk. The corpus caught the one I did get wrong. A first draft recognized only `}` as a closer and fired on 42 real `{{total}}` specs across the 731-file sweep. With `{{`/`}}`/`{#` in the brace sets the sweep produces exactly two diagnostics: the two target fixtures, no false positives. That case is now a unit test rather than something the sweep alone covers. No green mirror this time, and that is not an oversight: the check rides the existing whole-tree COST_SPEC scan next to `extract_unclosed_cost_brace_errors`, which sits outside the `use_green` branch and already runs for both paths. One walker, nothing to drift. Case 5 (`{USD}`, `{ # USD}`) is deliberately still accepted. beancount rejects it from the BOOKER - "Too many missing numbers for currency group" - which is a judgment across a currency group, not a property of one spec's tokens, so it cannot be decided here. A unit test asserts it stays clean so the split is explicit rather than an omission. Honest about what this does NOT fix: `rledger check` still reports the downstream `E3001 does not balance` alongside the new parse error, because we continue processing where beancount stops at the syntax error. The real cause is now named first and `rledger query` refuses the file (matching bean-query), but fully removing the invented-cost residual means dropping the directive, which is a booking-layer change and not this PR. Cache 25 -> 26 (wasm 11 -> 12, pins with them) - a separate bump from v25 because a cache written between the two lands carries v25 and is still stale for this change. Refs #2008 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG
robcohen
added a commit
that referenced
this pull request
Aug 11, 2026
#2008 cases 1 and 2, stacked on the transaction-header PR. #1 `10 AAPL {, 100.0 USD, , }` beancount: unexpected COMMA, expecting HASH or CAPITAL or CURRENCY #2 `1.1 AAPL {45.23 USD / 2015-07-16 / "blabla"}` beancount: unexpected SLASH, expecting RCURL or COMMA beancount's cost spec is a comma-separated component list where each component is a compound_amount, DATE, STRING or `*`. An empty component is not a component, and CURRENCY completes a compound_amount so nothing but `,` or a closer may follow it. The obvious reading of case 2 - "SLASH is illegal in a cost spec" - is wrong and would have been worse than the bug. `/` is a number_expr operator: `{10.00 * 3 USD}` is valid and archives 30.00 (#1939/#1942), so a token ban would have passed both fixtures and broken every ledger that divides in a cost spec. The defect is positional, which is what beancount's own message says ("expecting RCURL or COMMA"). `*` is left as ordinary content for the same reason - it is both the "any lot" component and multiplication, and reading it as a complete component turns `{10.00 * 3 USD}` into junk. The corpus caught the one I did get wrong. A first draft recognized only `}` as a closer and fired on 42 real `{{total}}` specs across the 731-file sweep. With `{{`/`}}`/`{#` in the brace sets the sweep produces exactly two diagnostics: the two target fixtures, no false positives. That case is now a unit test rather than something the sweep alone covers. No green mirror this time, and that is not an oversight: the check rides the existing whole-tree COST_SPEC scan next to `extract_unclosed_cost_brace_errors`, which sits outside the `use_green` branch and already runs for both paths. One walker, nothing to drift. Case 5 (`{USD}`, `{ # USD}`) is deliberately still accepted. beancount rejects it from the BOOKER - "Too many missing numbers for currency group" - which is a judgment across a currency group, not a property of one spec's tokens, so it cannot be decided here. A unit test asserts it stays clean so the split is explicit rather than an omission. Honest about what this does NOT fix: `rledger check` still reports the downstream `E3001 does not balance` alongside the new parse error, because we continue processing where beancount stops at the syntax error. The real cause is now named first and `rledger query` refuses the file (matching bean-query), but fully removing the invented-cost residual means dropping the directive, which is a booking-layer change and not this PR. Cache 25 -> 26 (wasm 11 -> 12, pins with them) - a separate bump from v25 because a cache written between the two lands carries v25 and is still stale for this change. Refs #2008 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG
robcohen
added a commit
that referenced
this pull request
Aug 11, 2026
* fix(parser): reject malformed cost-spec component lists #2008 cases 1 and 2, stacked on the transaction-header PR. #1 `10 AAPL {, 100.0 USD, , }` beancount: unexpected COMMA, expecting HASH or CAPITAL or CURRENCY #2 `1.1 AAPL {45.23 USD / 2015-07-16 / "blabla"}` beancount: unexpected SLASH, expecting RCURL or COMMA beancount's cost spec is a comma-separated component list where each component is a compound_amount, DATE, STRING or `*`. An empty component is not a component, and CURRENCY completes a compound_amount so nothing but `,` or a closer may follow it. The obvious reading of case 2 - "SLASH is illegal in a cost spec" - is wrong and would have been worse than the bug. `/` is a number_expr operator: `{10.00 * 3 USD}` is valid and archives 30.00 (#1939/#1942), so a token ban would have passed both fixtures and broken every ledger that divides in a cost spec. The defect is positional, which is what beancount's own message says ("expecting RCURL or COMMA"). `*` is left as ordinary content for the same reason - it is both the "any lot" component and multiplication, and reading it as a complete component turns `{10.00 * 3 USD}` into junk. The corpus caught the one I did get wrong. A first draft recognized only `}` as a closer and fired on 42 real `{{total}}` specs across the 731-file sweep. With `{{`/`}}`/`{#` in the brace sets the sweep produces exactly two diagnostics: the two target fixtures, no false positives. That case is now a unit test rather than something the sweep alone covers. No green mirror this time, and that is not an oversight: the check rides the existing whole-tree COST_SPEC scan next to `extract_unclosed_cost_brace_errors`, which sits outside the `use_green` branch and already runs for both paths. One walker, nothing to drift. Case 5 (`{USD}`, `{ # USD}`) is deliberately still accepted. beancount rejects it from the BOOKER - "Too many missing numbers for currency group" - which is a judgment across a currency group, not a property of one spec's tokens, so it cannot be decided here. A unit test asserts it stays clean so the split is explicit rather than an omission. Honest about what this does NOT fix: `rledger check` still reports the downstream `E3001 does not balance` alongside the new parse error, because we continue processing where beancount stops at the syntax error. The real cause is now named first and `rledger query` refuses the file (matching bean-query), but fully removing the invented-cost residual means dropping the directive, which is a booking-layer change and not this PR. Cache 25 -> 26 (wasm 11 -> 12, pins with them) - a separate bump from v25 because a cache written between the two lands carries v25 and is still stale for this change. Refs #2008 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG * fix(parser): fuse the cost-spec shape check into the existing scan Both #2022 review comments, and the second was more than wording. I documented the check as riding the existing whole-tree COST_SPEC scan and then gave it its own `descendants()` walk - so the doc was false AND the code did the thing the doc was written to avoid. That scan already sits behind a `contains('{')` guard precisely because `descendants()` allocates a red node per node; profiling once flagged it as ~50k wasted allocations on cost-spec-free ledgers. A second identical pass doubles a cost the codebase deliberately profiled down. Now genuinely fused into `extract_unclosed_cost_brace_errors`' loop: one walk, and the module doc describes what the code does. An unclosed spec skips the shape check - reporting a component defect on a truncated spec is noise about the truncation. The other comment: the trailing-junk message hardcoded "only `,` or `}` may follow", but a `{{total}}` spec closes with `}}`. Naming the wrong delimiter in a message about malformed syntax is the same species of misdirection #2008 is about. It says "the closing brace" now. Also gives the cost-spec path the same non-char-boundary fallback the header path got in the #2020 review, instead of an empty-quoted message. Re-swept the 731-file corpus after the restructure: exactly six diagnostics, the six target fixtures, no false positives. Refs #2008 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG * chore(baselines): update CostWithSlashes for the reworded diagnostic The parser-output baseline hashes the diagnostics too, so changing "only `,` or `}` may follow" to "the closing brace" moved this fixture's output hash. One row, source hash unchanged, and the locally regenerated hash matches the prefix CI reported. Refs #2008 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG --------- Co-authored-by: Claude Opus 5 <[email protected]>
1 of 2 tasks
This was referenced Nov 27, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Summary
Test plan
cargo buildpassescargo testpassescargo deny checkpassescargo auditshows only known/documented issues