Skip to content

perf: trivial quick wins bundle (blake3 cache, parking_lot, FxHasher, wasm fat-LTO) - #1076

Merged
robcohen merged 3 commits into
mainfrom
perf/issue-1065-quick-wins
May 11, 2026
Merged

robcohen merged 3 commits into
mainfrom
perf/issue-1065-quick-wins

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Closes #1065.

Four no-architecture, mostly-one-line swaps. Each is too small to merit its own PR; bundled here so they ship together as a single "perf-quick-wins" change.

# Change Files
1 Cache hash: sha2::Sha256 → blake3::Hasher crates/rustledger-loader/src/cache.rs, crates/rustledger-loader/Cargo.toml
2 SyncStringInterner: std::sync::Mutex → parking_lot::Mutex crates/rustledger-core/src/intern.rs, crates/rustledger-core/Cargo.toml
3 BQL hash_row / hash_single_value: DefaultHasher → FxHasher crates/rustledger-query/src/executor/types.rs
4 wasm-release profile: add lto = "fat" override Cargo.toml

Why bundled?

Each item is < 10 lines of meaningful change and uses dependencies already in the workspace (blake3 = "1", parking_lot = "0.12", rustc-hash). Bundling avoids 4 separate PR review cycles for what amounts to "swap the import."

Notes

  • sha2 stays in the workspace because other crates use it for non-cache purposes (synthetic/manifest, ffi-wasi, wasm, plugin). Only rustledger-loader drops the dep.
  • parking_lot::Mutex is non-poisoning, so the call sites simplify from .lock().unwrap() to .lock(). No semantic change — none of the previous unwraps would have triggered (the mutex is short-lived around interner ops).
  • The cache binary format already used a 32-byte hash, so BLAKE3 (also 32 bytes) is a drop-in replacement at the struct level. Any cache file written before this PR will be invalidated on first load (hash mismatch → re-parse), which is the same as any other cache-format change.

Test plan

  • cargo test -p rustledger-core -p rustledger-loader -p rustledger-query --all-features — all green
  • cargo fmt --all -- --check — clean
  • cargo clippy --all-features -- -D warnings — clean
  • CI checks (compatibility, regression, MSRV)

🤖 Generated with Claude Code

Four no-architecture, mostly-one-line swaps consolidated as a single PR
since each is too small to land independently.

1. cache: sha2::Sha256 → blake3::Hasher (~10x faster software hash). The
   blake3 dependency was already pulled in by the workspace; sha2 stays
   in for the other crates that need it (synthetic/manifest, etc.).

2. SyncStringInterner: std::sync::Mutex → parking_lot::Mutex. Avoids
   the OS syscall on lock/unlock, non-poisoning (no .unwrap() at call
   sites). parking_lot was already in workspace deps.

3. BQL hash_row / hash_single_value: DefaultHasher (SipHash 1-3) →
   FxHasher. DISTINCT and GROUP BY keys are internal dedup tokens —
   they need speed, not DoS-resistance. Matches the FxHasher pattern
   used by FxHashMap everywhere else in the workspace.

4. wasm-release profile: add lto = "fat" override. The profile inherits
   from `release` which uses thin LTO to dodge the Apple linker bug;
   WASM doesn't hit that bug so the override is free.

No public API changes. All affected crate test suites pass; fmt and
clippy clean.

Closes #1065

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 11, 2026 02:27
@robcohen
robcohen requested a review from a team as a code owner May 11, 2026 02:27
@github-actions

github-actions Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 30.4ms ± 0.5ms 21.9 MB
beancount 869.4ms ± 6.3ms 50.5 MB
Comparison 28.6x faster 2.3x less

vs main branch (2026-05-10)

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR bundles several small, low-touch performance-focused swaps across the workspace (issue #1065), mainly replacing slower default primitives with faster alternatives and tuning the WASM release profile.

Changes:

  • Switch cache hashing in rustledger-loader from SHA-256 to BLAKE3.
  • Switch SyncStringInterner locking in rustledger-core from std::sync::Mutex to parking_lot::Mutex.
  • Switch BQL row/value hashing in rustledger-query from DefaultHasher to rustc_hash::FxHasher, and set WASM release to lto = "fat".
  • Update cargo-vet supply-chain files (remove an exemption and add audits).

Reviewed changes

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

Show a summary per file
File Description
crates/rustledger-loader/src/cache.rs Replaces SHA-256 with BLAKE3 for cache validity hashing.
crates/rustledger-loader/Cargo.toml Swaps optional sha2 dependency/feature wiring to blake3 for cache.
crates/rustledger-core/src/intern.rs Uses parking_lot::Mutex for the sync string interner and simplifies lock calls.
crates/rustledger-core/Cargo.toml Adds parking_lot as a direct dependency.
crates/rustledger-query/src/executor/types.rs Uses FxHasher for hash_row / hash_single_value to speed up executor hashing.
Cargo.toml Sets profile.wasm-release.lto = "fat" override.
Cargo.lock Captures dependency graph updates (blake3, parking_lot).
supply-chain/imports.lock Adds upstream audit entries (cargo-vet).
supply-chain/config.toml Removes an exemption entry (cargo-vet).

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

Comment thread crates/rustledger-loader/src/cache.rs Resolved
@github-actions

github-actions Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

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

Full results available in workflow artifacts

@codecov

codecov Bot commented May 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.90909% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/intern.rs 75.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

Two follow-ups from Copilot review on PR #1076:

1. Bump CACHE_VERSION 3 → 4. The hash algorithm changed (SHA-256 →
   BLAKE3) so old caches will fail the hash compare anyway, but the
   version check at cache.rs:397 fires BEFORE we read+rkyv-deserialize
   the data section. Bumping rejects stale caches at the header,
   skipping the wasted deserialize on every first load after upgrade.
   Documented the rationale in the version-history comment.

2. Drop the redundant `use std::hash::Hasher;` inside hash_row and
   hash_single_value — Hasher is already in scope at module level
   (executor/types.rs:4: `use std::hash::{Hash, Hasher};`).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen

Copy link
Copy Markdown
Member Author

Deep PR review — self + Copilot follow-ups

Pushed 5c4220b6 addressing both Copilot inline findings. Posting my own deep review for the record.

Copilot findings — both addressed

  1. cache.rs:209 — bump CACHE_VERSION. ✅ 3 → 4. Old caches now fail the cheap header version check at cache.rs:397 instead of paying the rkyv deserialize cost only to fail the hash compare. The header layout is unchanged (both SHA-256 and BLAKE3 are 32-byte outputs, so CacheHeader::SIZE == 52 either way), so this is a soft invalidation — old cache files get rejected on first load after upgrade and re-written on save.
  2. types.rs:219,229 — redundant Hasher imports. ✅ Dropped both inner use std::hash::Hasher; — confirmed Hasher is already in scope at types.rs:4 via use std::hash::{Hash, Hasher};.

Self-review findings (all OK)

Correctness

  • ✅ BLAKE3 Hasher::update(&[u8]) differs from sha2's update<T: AsRef<[u8]>> — needed to add & prefix on the to_le_bytes() calls. Done at cache.rs:267-272.
  • ✅ BLAKE3's finalize() returns Hash (not Output<Sha256>). Used *hasher.finalize().as_bytes() to dereference the &[u8; 32] into the owned [u8; 32] return type.
  • ✅ parking_lot::Mutex::lock() returns MutexGuard<T> directly (not LockResult) — non-poisoning. All four call sites in SyncStringInterner simplified from .lock().unwrap().X() to .lock().X(). No semantic change; any code that hit the .unwrap() would have already panicked.
  • ✅ FxHasher produces different hash values than DefaultHasher (SipHash 1-3), but the BQL hashes are internal dedup tokens — not persisted, not cross-process, not part of any wire format. The change is transparent to callers.
  • ✅ wasm-release lto = "fat" override placed after inherits = "release" so it wins.

Cross-platform safety

  • parking_lot works on wasm32 (CI's "Build Package" and "Test (Node.js)" both pass). No new wasm bloat — parking_lot was already a transitive dep via other workspace members; this just makes it a direct dep of rustledger-core.
  • blake3 has a portable software implementation for wasm32. The CI compatibility job passed end-to-end on Linux, and the WASM package builds cleanly.

Scope hygiene

  • ✅ sha2 was kept in the workspace deps — other crates use it for non-cache purposes (synthetic/manifest, ffi-wasi, wasm, plugin). Only rustledger-loader drops the sha2 dep.
  • ✅ Doc comment on SyncStringInterner now explicitly mentions the perf rationale + the non-poisoning consequence at call sites. Useful for future-me wondering why there's no .unwrap().
  • ✅ All four changes are independent and self-contained — bundling them in one PR for review efficiency, but each could be reverted in isolation without affecting the others.

CI

All checks green on the previous commit (35 passed). The fix commit triggers another CI run; nothing in the fix should regress.

Not addressed (won't-do for this PR)

  • Removing sha2 from the workspace — out of scope; other crates legitimately need it.
  • Pre-allocating BLAKE3 hasher state — micro-optimization, not measurable for the cache use case.

Ready for merge once CI re-greens.

@robcohen
robcohen merged commit 0a8663b into main May 11, 2026
44 checks passed
@robcohen
robcohen deleted the perf/issue-1065-quick-wins branch May 11, 2026 03:01
robcohen added a commit that referenced this pull request May 11, 2026
… SyncStringInterner (#1081)

* perf(loader): run reintern_directives on fresh-parse path + drop dead SyncStringInterner (closes #1071)

The cache-hit path already ran reintern_directives after deserializing
to deduplicate InternedStr across files; the fresh-parse path did
not. So multi-file ledgers parsed from source had identical account /
currency / tag strings landing in distinct Arc<str> allocations
(per-file StringInterner), defeating the Arc::ptr_eq fast path in
InternedStr::PartialEq and forcing every cross-file equality through
byte comparison.

Changes:

(1) Extract reintern_directives and reintern_plain_directives from
the feature-gated cache module into a new always-on dedup module.
The dedup walk has no rkyv/cache dependency; gating it behind the
cache feature was incidental. lib.rs now re-exports both functions
unconditionally.

(2) Call dedup::reintern_directives at the end of Loader::load, so
every consumer of LoadResult sees a deduplicated directive list
regardless of whether they came in via cache or fresh parse.

(3) Drop SyncStringInterner from rustledger-core::intern. The type
had zero call sites in the workspace; an audit for #1071 confirmed
it was dead code. Removing it also lets us drop the parking_lot
dependency from rustledger-core (added in #1076 specifically for
this type).

Tests:
* New test_fresh_parse_deduplicates_internedstr_across_files locks
  in the cross-file dedup invariant via VirtualFileSystem (two files
  referencing Assets:Bank; assert the resulting Posting and Open
  share an Arc via InternedStr::ptr_eq).
* Existing reintern unit tests in cache.rs continue to pass against
  the moved implementation.

Closes #1071

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address Copilot review on PR #1081

Three concerns, all valid:

(1) Coverage gap. The pre-Copilot reintern_directive only walked
posting-level account/currency fields. It silently skipped:
  - Transaction.payee
  - Transaction.narration
  - Transaction.tags
  - Transaction.links
  - Document.tags
  - Document.links

Cross-file PartialEq on those fields fell through to byte compare.
Expanded the walk to cover all six. Extracted an intern_vec helper
for the Vec<InternedStr> cases.

(2) Double hash lookup. do_intern called contains() then intern() —
two probes per call. Added StringInterner::intern_with_status which
returns (InternedStr, was_new) from a single probe. Replaces the
existing two-call dance.

(3) Misleading docs. Module docs and Loader::load comment claimed
account/currency/tag coverage, but the implementation skipped the
tag/link/payee/narration cases. Updated both to reflect the actual
(now-correct) full coverage.

Plus a new regression test
test_fresh_parse_deduplicates_transaction_fields_across_files that
references the same payee + tag across two included files and
asserts ptr_eq on both — pre-Copilot fix this would have failed.

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 15, 2026
First of the #1237 static-analysis ratchets, done as a grep ratchet (the
same lightweight named-CI-status pattern as `check-unsafe-invariant.sh`)
rather than a dylint lint — so it needs no extra nightly toolchain.

parking_lot was adopted as a perf quick win in #1076, but nothing prevented
new `std::sync` locks from creeping back in. This adds:
- `scripts/check-sync-primitives.sh` — forbids `std::sync::Mutex`/`RwLock`
  in `crates/*/src/`, with a `// ratchet-allow: std-sync <reason>` escape
  hatch. Verified it passes clean and catches an injected violation.
- a "Sync Primitives" CI job mirroring "Unsafe Invariant".

The single pre-existing usage (`rustledger-query` regex cache) is converted
to `parking_lot::RwLock`. Its std code already recovered from poisoning via
`into_inner()`, which is exactly parking_lot's no-poison behavior, so the
conversion is semantically equivalent and drops the poison-handling arms.

Scope note: the broader #1237 items (dylint lint crate, cargo-public-api
baselines, loom) are intentionally left to follow-ups — see the issue
discussion. public-api/semver overlaps the still-open #1233.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jun 15, 2026
Second of the #1237 ratchets, again as a grep ratchet (no nightly toolchain),
using the marker-based opt-in pattern of `check-unsafe-invariant.sh`.

FxHashMap/FxHashSet were adopted on hot paths in #1076 because std's SipHash
default is much slower for the small-int/short-string keys these paths use.
Nothing prevented a new `std::collections::HashMap` from regressing that.

- `scripts/check-hot-path-collections.sh`: finds files marked
  `// ratchet: fxhash-only`, and fails if their non-test code uses
  `std::collections::HashMap`/`HashSet`. Excludes `#[cfg(test)]` modules and
  leaves `BTreeMap` (deterministic, sorted) untouched. Escape hatch:
  `// ratchet-allow: std-collections <reason>`. Verified it passes clean,
  catches a real (non-test) violation in a marked file, and ignores both
  test modules and unmarked files.
- "Hot-path Collections" CI job (anchored after plugin-test-quality to avoid
  colliding with the sync-primitives job in #1363).
- Marked five genuinely-hot, already-clean modules: booking `book.rs`, core
  `inventory/mod.rs`, loader `process.rs` (the booking pass), validate
  `balance.rs`, query `executor/types.rs`.
- Converted the one std collection in a hot path — `book.rs`'s local
  `booked_indices` dedup set — from `std::collections::HashSet` to
  `FxHashSet` (drop-in: insert/contains/into_iter only).

Modules that use std maps deliberately (e.g. query `aggregation.rs`'s
GROUP BY map with its explicit `key_order`, and the `ShiftSpans` trait impl
for `HashMap<_,_,S>`) are simply left unmarked; the ratchet is opt-in and
extensible.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jun 15, 2026
Second of the #1237 ratchets, again as a grep ratchet (no nightly toolchain),
using the marker-based opt-in pattern of `check-unsafe-invariant.sh`.

FxHashMap/FxHashSet were adopted on hot paths in #1076 because std's SipHash
default is much slower for the small-int/short-string keys these paths use.
Nothing prevented a new `std::collections::HashMap` from regressing that.

- `scripts/check-hot-path-collections.sh`: finds files marked
  `// ratchet: fxhash-only`, and fails if their non-test code uses
  `std::collections::HashMap`/`HashSet`. Excludes `#[cfg(test)]` modules and
  leaves `BTreeMap` (deterministic, sorted) untouched. Escape hatch:
  `// ratchet-allow: std-collections <reason>`. Verified it passes clean,
  catches a real (non-test) violation in a marked file, and ignores both
  test modules and unmarked files.
- "Hot-path Collections" CI job (anchored after plugin-test-quality to avoid
  colliding with the sync-primitives job in #1363).
- Marked five genuinely-hot, already-clean modules: booking `book.rs`, core
  `inventory/mod.rs`, loader `process.rs` (the booking pass), validate
  `balance.rs`, query `executor/types.rs`.
- Converted the one std collection in a hot path — `book.rs`'s local
  `booked_indices` dedup set — from `std::collections::HashSet` to
  `FxHashSet` (drop-in: insert/contains/into_iter only).

Modules that use std maps deliberately (e.g. query `aggregation.rs`'s
GROUP BY map with its explicit `key_order`, and the `ShiftSpans` trait impl
for `HashMap<_,_,S>`) are simply left unmarked; the ratchet is opt-in and
extensible.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Nov 12, 2026
…ponent

CI's Sync Primitives check forbids std::sync locks in non-test library code
(#1076), and `compiled_component` lives in the crate's lib. Switch it to
parking_lot::Mutex (no poisoning, so the PoisonError recovery goes), end
the guard explicitly after the first compile, and split the doc's first
paragraph for clippy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 12, 2026
…heck does (#2946)

* fix(loader)!: validate options in included files as beancount does, and locate every option diagnostic

beancount parses each included file with its own Builder and fresh
options: every value an option's converter rejects is an error at the
included file's line (bean-check exits 1), and only the top-level file's
values are kept. rledger reported every included option as the E7009
warning, valid or not, and exited 0.

set_scoped_inner now reads an included non-accumulating option into a
scratch Options, keeps its diagnostics and drops the value. E7009 is left
for a value the converter accepts. An included name_* root still does
not root that file's own accounts (E1005), a deliberate deviation now
commented and pinned.

Every option diagnostic (E7001 to E7011) carries the option's file and
line: OptionWarning gains `site`, stamped by set_scoped_at, and E7006 /
E7010 are located from the applied values. rledger check (text, JSON, and
ag-rledger check through it), the LSP (diagnostic on the option line, in
the file it is in), WASM option_errors and multi-file Ledger errors read
it. WASM validateMultiFile now reports option diagnostics at all.

Drift guards pin check's JSON and text, the LSP's two paths and WASM's
two multi-file paths to the loader's sites. WASM cache v99; the loader
cache never stores a ledger with option diagnostics, so it stays at v69.

Refs #2925

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(loader): one canonical option-diagnostic mapping, and keep a ledger's options off unrelated LSP buffers

Review round 1 of #2945.

- rustledger_loader::option_warnings_to_errors maps OptionWarning::site to
  LedgerError::location (column 1). rledger check, the LSP and WASM (via
  From<LedgerError>) read it; the WASM helper is a one-argument wrapper
  and single-source entry points drop the file with without_files.
- LSP: a buffer the ledger does not include gets its own options'
  diagnostics, never the ledger's drawn on its lines.
- LSP option range stops before a `; comment`; the live-buffer limitation
  is documented.
- Options::locate is by occurrence, so a repeated documents value is
  located at each of its lines.
- validate_with_filesystem reports option diagnostics beside a fatal load
  error or a processing failure.

Refs #2925

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(ffi): report option errors, and validate file loads as rledger check does

The FFI component never reported a ledger's option diagnostics (E7001 to
E7011): ffi-wasi built `errors` from `ledger.errors` only. They now travel
in a separate, non-gating `option_errors` list on `LoadResult` and
`FileLoad`, mapped by `rustledger_loader::option_warnings_to_errors`, the
canonical function the WASM surface now calls too, and are appended to the
outgoing `errors` last, after the host's plugins and validation have run,
so an invalid option neither skips validation, nor stops session plugins,
nor counts in `parse-error-count`. `valid` and the host-plugin gate go by
severity, which fixes two older bugs: a ledger plugin's warning skipped the
host's plugins, and `valid` was false over a warning alone. Query results
list the option diagnostics, as the WASM query does, and so no longer list
the booking-method refusal beside its E7002 (#2929).

`load-file` reported no validation errors and `validate-file` validated the
entry file's text as one source. Both now validate through the canonical
pipeline (`load_file_with_fs(..., validate: true)`), and the validator's
findings, told apart by the new `LedgerError::is_validation_finding`, are
kept out of the host-plugin gate, so a failed balance does not stop the
host's plugins. Each finding keeps its own file and line. A source-text
finding maps to a line only when its span is in the text (file id 0), as
on WASM; a plugin directive's finding was mapped to an unrelated line
(#2935).

A drift guard pins `rledger check` and the component's `load`,
`load-file`, `validate` and `validate-file` to one list of diagnostics
(codes, messages, files and lines) on a multi-file and a single-file
ledger with a balance failure, a padded cost lot and invalid options, run
natively and through the built wasip2 component.

WIT contract rustledger:[email protected] (behavior only, no shape change).
No cache payload changes.

Closes #2929
Closes #2935

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(ffi)!: WIT 4.0.0 error code and filename, and keep the query refusal

Review round 1 of #2946.

- The WIT `error` record gains `code` and `filename`, filled for every
  error with a location (an included file's own path, the name given to
  `load` for source text, a plugin's placeholder name), so a line can say
  which file it is in. A record change: package rustledger:[email protected],
  `API_VERSION` 4.0, docs cite @4.x.
- Query surfaces (`query`, `query-file`, `batch`, `batch-file`,
  `session.query`) list a rejected booking_method as the refusal again, in
  place of its plain E7002, through one loader canonical,
  `Ledger::query_option_errors`; `load` and `info()` keep the plain E7002.
- Option diagnostics come from #2945's located
  `option_warnings_to_errors` (this branch is rebased onto it), so they
  carry the option's file and line on every surface, and the drift guard
  pins those lines.
- Validation findings leave out the advisory-only E1004 on every surface,
  as `rledger check` does, and are kept beside an unrun plugin's error
  (E8001, E8004, E8005), as `check` keeps them.
- The host-plugin tests assert `check_commodity`'s exact finding, so the
  mutations that put option errors in the plugin gate fail them.
- The file-id span rule cites its WASM twin, and the WASM rule cites it.

No cache payload changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(loader): ignore an included documents option as beancount does, and locate query's option diagnostics

Review round 2 of #2945.

- documents leaves ACCUMULATE_ACROSS_INCLUDES: beancount 3.2.3 keeps only
  the top-level file's (load_file gives documents == [] for an included
  root and bean-check exits 0 with it missing), so an included value is
  read by the scratch converter and ignored with E7009, never scanned or
  checked (no E7006).
- rledger query prints option diagnostics through the canonical mapping,
  with file and line; ag-rledger's query warnings carry them.
- WASM Ledger::from_file_map's processing-error arm keeps the option
  diagnostics, as validate_with_filesystem does.
- LSP option_error_file_id uses SourceFile::id.
- Tests pin site_of's last-line choice (E7010), without_locations
  clearing every site, and included documents.

Refs #2925

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(ffi): locate each parse error and host plugin error, as rledger check does

Review round 2 of #2946.

- A plugin the host asks for (`load-file`, `session.from-file`) reported
  its errors as a bare message: no code, file, line or severity, and its
  text unescaped. The loader's per-error mapping is now the public
  `rustledger_loader::plugin_error_to_ledger_error`, which
  `record_plugin_errors` and ffi-wasi's `apply_plugins` (which gains the
  load's `source_map`) both use. A drift test compares a host-requested
  and a ledger-declared `leafonly`.
- Parse errors were one line-less `parse errors in <path>`, an included
  file's too. `LoadResult::take_parse_errors` (the same method as #2952)
  takes them out before `process`, and the new
  `rustledger_loader::parse_errors_to_ledger_errors` reports each with its
  code, file, line and column, as `check` does. `load(src, name)` names
  the given file on them. New shared case `parse-error-in-include`.
- `batch` and a session from source name their errors `<stdin>`, as their
  entries, not the loader's `<string>`.
- `query_option_errors` shares `query_refusal_error`'s conversion.
- Pin the refusal's site match (an include repeating the main file's bad
  `booking_method` keeps its plain E7002) and the refusal's phase on
  every query surface; both mutation-checked.
- world.wit: both behaviors for a plugin-made directive's finding, line 0
  as the exception to 1-based, and the `version()` example is "4.0".
  Stale comments fixed in ffi-wasi `Error` and the parity cases.
- ffi-component-tests compile the component once per test binary
  (`compiled_component`). Every `parity` / `corpus_parity` test compiled
  the 93 MB debug component on its own `Engine`, the check-parity test once
  per case, many at once on parallel threads: the `parity` binary held
  10-12 GB for 20+ minutes. The crate's tests now take 26 s at 0.9 GB peak.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(ffi-component-tests): use parking_lot for the shared compiled component

CI's Sync Primitives check forbids std::sync locks in non-test library code
(#1076), and `compiled_component` lives in the crate's lib. Switch it to
parking_lot::Mutex (no poisoning, so the PoisonError recovery goes), end
the guard explicitly after the first compile, and split the doc's first
paragraph for clippy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(wasm): list query option errors through the canonical, and pin columns (#2946 review round 3)

- WASM query surfaces (free `query`, `ParsedLedger.query`,
  `queryMultiFile`, `Ledger.query`) list option diagnostics through
  `Ledger::query_option_errors`, as the FFI does: the rejected
  `booking_method`'s E7002 is the refusal. Shared drift guard
  `rustledger-loader/tests/query_option_errors/cases.rs` across the
  loader, the FFI and WASM. WASM cache v105 (both payloads archive
  what a query lists). A source that fails to parse still differs
  (#2960), documented at both sites.
- The check parity rows compare `column`; `load` and `validate` now
  give a validation finding its column, as `check` does. A mid-line
  parse error after a two-byte character pins character columns.
- Paired comments between `parse_errors_to_ledger_errors` and
  `check`'s inline parse-error arm.
- Pin `batch` errors named `<stdin>` and the host-plugin `source_map`
  argument (file names with a tab).
- `session.from-entries` option errors carry code E7002.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(ffi,wasm): locate every finding through one canonical, and count WASM columns in characters (#2946 review round 4)

- loader: `SourceMap::locate(file_id, offset)` replaces the private
  `error_location`; the loader, the FFI component's validation findings and
  the WASM surface all locate through it.
- ffi-component: `semantic_validation_errors` calls `SourceMap::locate`
  instead of re-deriving it.
- check parity: BOM-prefixed cases (LF and CRLF) put a line-1 finding at
  column 2, so a hardcoded column 1 no longer passes.
- wasm: `validateSource`, `ParsedLedger.getErrors`, `parse` and `format`
  counted columns in bytes (4 after a BOM); parse errors now go through the
  loader's `LineIndex` and validation findings through `SourceMap::locate`.
  `LineLookup` keeps lines only. Native and wasm-bindgen tests pin a BOM and
  a multi-byte character before an error.
- WIT: the `error` record's doc says `column` is 1-based in characters and
  0 at a plugin placeholder (doc only).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(ffi,wasm): pin a parse error's refusal, WASM's file-id rule and end positions, and map WASM parse errors once (#2946 review round 5)

- query_option_errors/cases.rs: new refused-by-parse-error-alone case
  (a parse error and no option diagnostic must refuse), run by the
  canonical, the FFI query surfaces and every WASM query surface,
  queryMultiFile included; the component's
  query_short_circuits_on_parse_error gains the same ledger. Moves a
  comment glued to `},` onto its own line.
- wasm: test_a_plugin_directives_finding_maps_to_no_source_line, the
  counterpart of the FFI test; end_line/end_column pinned natively and
  in wasm_error_columns on every surface.
- wasm: parse_error_fields maps a parse error's message, code, phase
  and hint once for parse_error_to_wasm and load_errors_to_errors, with
  paired comments against the loader's parse_errors_to_ledger_errors
  and a drift guard (parse_error_mapping_parity).
- The multi-file path prefix on parse error messages points at #2961.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(wasm,loader): say why WASM keeps its own parse-error mapping (#2946 review round 6)

The paired comments at parse_error_fields and parse_errors_to_ledger_errors
said a LedgerError has no end position. It does: source_span and file_id
carry it; only ErrorLocation is a point. The copy exists because WASM's
single-source surfaces build no LoadError or SourceMap. The multi-file
surfaces report null ends for validation findings only because
From<LedgerError> for Error does not locate them, and that conversion also
drops the hint: both pre-existing, now issue #2964, cited from the
comments, the From impl and wasm_error_columns.rs. The revisit condition
is now "if the single-source surfaces come to build a LoadError".

The load_errors_to_errors comment also names parse_error_mapping_parity
as a test that strips the #2961 path prefix.

Formats the include!d ffi_check_parity/cases.rs with rustfmt (a chain
from the #2952 merge exceeded the chain width).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Dec 1, 2026
…lots

check-sync-primitives.sh forbids std::sync locks in library code (#1076).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Dec 1, 2026
* perf(parser): parse a file of 1 MiB or more on up to 4 threads

`parse_streamed_parallel` runs the loader's streamed parse (ADR-0011) of a
large file in regions of 512 KiB on the rayon pool, at most 4 at a time
(`PARALLEL_PARSE_THREADS`, and never more than the pool has). Each region is
the same builder, recorder and `Conversion::chunk`, started at a likely item
boundary found by a byte scan and stopped at the first boundary past the
next region's start; the results are appended in order and `finish` runs
once. A region's parse is speculative: the merge checks that it starts
where the region before ended and that nothing is carried into it
(`dates_carry`, `no_meta_carried`), and re-parses it from the real boundary
otherwise, so the scan never decides the result. Regions run in waves of
two per thread so peak memory does not hold every region's directives.

The loader uses it by default. `RLEDGER_PARALLEL_PARSE=0` turns it off and
`RLEDGER_PARSE_THREADS=N` changes the cap. Files under two regions, a
one-thread pool, the parser without its `parallel` feature, and wasm
targets keep the sequential streamed parse, whose instruction count is
unchanged: the region stop test is a const generic compiled out of it.

`rledger check`, first run, 16 cores, against `RLEDGER_PARALLEL_PARSE=0`:
29-39% less wall time, 7-26% more CPU time, 2-21% more peak RSS.

The oracle's nesting guard is released while the regions run: a rayon
thread waiting for them can take up another file's whole parse, which
would otherwise see this parse's depth and skip its reconciliation.

`streamed_parse_parity` compares the parallel parse with the whole-tree
parse on pools of 1, 2, 4 and 16 threads; the `compat.yml` job runs it with
`--features parallel` and asserts that regions ran, and
`fuzz_streamed_eq_whole` fuzzes it. ADR-0011 gains a "Parallel regions"
section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(parser): use parking_lot::Mutex for the parallel parse's result slots

check-sync-primitives.sh forbids std::sync locks in library code (#1076).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: trivial quick wins (blake3 cache, parking_lot, FxHasher in BQL, wasm fat-LTO)

2 participants