Skip to content

fix: replace unwrap calls with defensive pattern matching - #7

Merged
robcohen merged 1 commit into
mainfrom
fix/unwrap-calls
Jan 6, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/unwrap-calls

Conversation

@robcohen

@robcohen robcohen commented Jan 6, 2026

Copy link
Copy Markdown
Member

Summary

  • Replaces 3 production unwrap() calls with defensive pattern matching
  • Improves robustness against edge cases and unexpected input
  • Changes in:
    • crates/rustledger-query/src/executor.rs:305 - balance lookup
    • crates/rustledger-query/src/completions.rs:69 - token parsing
    • crates/rustledger-validate/src/lib.rs:480 - account component validation

Test plan

  • All existing tests pass
  • No behavioral changes for valid inputs
  • Code gracefully handles edge cases instead of panicking

@robcohen

robcohen commented Jan 6, 2026

Copy link
Copy Markdown
Member Author

@claude review this PR

@claude

claude Bot commented Jan 6, 2026 •

Copy link
Copy Markdown

Claude finished @robcohen's task in 1m 0s —— View job


Code Review Complete

  • Read repository guidelines (CLAUDE.md)
  • Examine changed files
  • Review pattern matching replacements
  • Analyze error handling approach
  • Provide comprehensive feedback

Review Summary

This PR successfully replaces 3 unwrap() calls with defensive pattern matching. The changes improve code safety without altering behavior for valid inputs. All three changes are well-documented with safety comments explaining the defensive logic.

Detailed Findings

✅ Change 1: completions.rs:177-180 - Token Parsing

Location: crates/rustledger-query/src/completions.rs:177-180

Before:

tokens.push(format!("{}{}", c, chars.next().unwrap()));

After:

// Safety: we just checked peek() == Some(&'='), so next() is guaranteed
if let Some(next_char) = chars.next() {
    tokens.push(format!("{c}{next_char}"));
}

Assessment: ✅ Excellent

  • The safety comment accurately explains why next() will succeed
  • Pattern matching with if let Some is the right approach here
  • Silently continuing without adding the token if None is graceful
  • The logic is protected against future code changes

✅ Change 2: executor.rs:305-308 - Balance Lookup

Location: crates/rustledger-query/src/executor.rs:305-308

Before:

for account in accounts {
    let balance = self.balances.get(account).unwrap();

After:

for account in accounts {
    // Safety: account comes from self.balances.keys(), so it's guaranteed to exist
    let Some(balance) = self.balances.get(account) else {
        continue; // Defensive: skip if somehow the key disappeared
    };

Assessment: ✅ Excellent

  • Uses let-else pattern which is ideal for early-continue scenarios
  • Safety comment explains the invariant while acknowledging defensive nature
  • continue is the appropriate recovery action (skip problematic entries)
  • Protects against potential race conditions or refactoring issues

✅ Change 3: lib.rs:480-485 - Account Component Validation

Location: crates/rustledger-validate/src/lib.rs:480-485

Before:

let first_char = part.chars().next().unwrap();

After:

// Safety: we just checked part.is_empty() above, so this is guaranteed to succeed
let Some(first_char) = part.chars().next() else {
    // This branch is unreachable due to the is_empty check above,
    // but we handle it defensively to avoid unwrap
    return Some(format!("component {} is empty", i + 1));
};

Assessment: ✅ Excellent

  • Very thorough documentation explaining both the invariant and defensive handling
  • Returns a meaningful error message if the unexpected happens
  • Acknowledges the branch is theoretically unreachable while still being defensive
  • Maintains consistency with the validation function's return type

Additional Observations

Formatting Changes

The PR includes several minor formatting improvements (semicolon placement, assert formatting) that were likely auto-applied by rustfmt. These are cosmetic and don't affect functionality.

Test Coverage

All existing tests pass according to the PR description. The changes don't alter behavior for valid inputs, so existing test coverage remains valid.

Recommendations

None - this PR is ready to merge. All changes follow Rust best practices for defensive programming.

Summary

Approval Status: ✅ Approved

This is a well-executed safety improvement. Each unwrap removal:

  1. Has clear documentation explaining the safety invariant
  2. Uses appropriate Rust pattern matching idioms
  3. Handles edge cases gracefully
  4. Maintains code readability

The changes make the codebase more robust against edge cases without introducing performance overhead or complexity.


Replace potentially confusing unwrap() calls with explicit pattern
matching using let-else, even in cases where the unwrap is technically
safe due to prior checks. This improves code clarity and follows
Rust best practices.

Changes:
- validate/lib.rs: Replace unwrap on chars().next() with let-else
- executor.rs: Replace unwrap on HashMap::get() with let-else
- completions.rs: Replace unwrap on chars.next() with if-let

All cases were already safe due to prior checks, but the new code
is more self-documenting about the invariants.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@robcohen
robcohen added this pull request to the merge queue Jan 6, 2026
Merged via the queue into main with commit 2d10918 Jan 6, 2026
@robcohen
robcohen deleted the fix/unwrap-calls branch January 6, 2026 16:41
robcohen added a commit that referenced this pull request Jan 14, 2026
fix: replace unwrap calls with defensive pattern matching
robcohen added a commit that referenced this pull request Jan 14, 2026
fix: replace unwrap calls with defensive pattern matching
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]>
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 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]>
robcohen added a commit that referenced this pull request Aug 11, 2026
* fix(parser): reject transaction headers beancount refuses

Four of the seven constructs in #2008. All four live in the transaction
header, so one rule covers them:

  #3 `* #trip "Money from CC" ^610f`  string after a tag
  #4 `* "Dinner" A:*:B`               junk after the narration
  #6 `* "Mermaid Inn" "Nice dinner" "With Caroline"`
  #7 `* "A" "B" "C"`                  more than two strings

beancount's grammar is `DATE txn txn_strings tags_links eol`, so strings
come first and tags/links follow; more than two strings parses but the
builder rejects it with "Too many strings on transaction description".
Our CST parser is deliberately permissive - it is lossless and recovers
rather than rejecting - and nothing downstream re-imposed that shape.

Case 4 falls out of the same rule rather than needing lexer work: in
`* "Dinner" A:*:B` the `A` lexes as a one-character CURRENCY, which is a
valid flag in the flag position and junk after a string. Scoping the
flag position to "before any string/tag/link" is what catches it.

The rule is written once over `(SyntaxKind, Range)` pairs in a new
`cst::txn_header`, and the red and green walkers differ only in how they
enumerate tokens. The green/red mirrors are the drift source CLAUDE.md
names; the shared rule plus the parity corpus is the defense. Removing
the green call makes `parse_green_eq_red_corpus` fail, verified.

Kind and range are all the rule needs - even the one-character CURRENCY
flag is decided by `range.len() == 1` - so neither walker needs source
access to reach a verdict, only to word the message.

Scope was set by measurement, not by taste. Tallying every token kind
that appears in a transaction header across the 731-file corpus (~30k
transactions) gives DATE, STAR, PENDING_KW, TXN_KW, STRING, TAG, LINK,
WHITESPACE, COMMENT, one-character CURRENCY - and two COLONs, both
inside the case-4 fixture. So the allowlist is evidence, and sweeping
the corpus after the change produces exactly four diagnostics: the four
target fixtures, no false positives.

Deliberately NOT widened past the evidence: `2014-01-01 * * "x"` has two
flags and beancount rejects it, but it is not one of the seven and
guessing at extra strictness is how a compatibility fix starts breaking
real files. The `|` separator keeps its own DeprecatedPipeSymbol
diagnostic instead of being re-reported here.

Requires a cache bump, and this was observed rather than reasoned:
after the parser change the first `rledger check` against the fixtures
still reported only the old downstream E1001s, because the parse cache
held the permissive parse. Loader 24 -> 25, wasm 10 -> 11, the wasm pin
with it, and both archived-layout FIXTURE_VERSION tripwires - which fire
with instructions saying which case applies. This is v15's case: which
errors are emitted changed, how anything is archived did not.

`test_lima_tests_parse` did not catch any of this, and could not have.
Its allowlist branch is a bare `continue`, so listing a fixture only
permits an error and never checks one occurs. TagThenLink,
CostEmptyComponents and CostWithSlashes sat in that list for the
parser's whole life while producing no error at all. A new
LIMA_2008_CASES table replaces that with a two-sided assertion over all
seven cases: the three unfixed rows assert we are STILL permissive, so
finishing #2008 turns the test red and forces the row to flip.

28 allowlisted fixtures are in that same one-sided position today. 22
are `GrammarExceptions*`, whose intended semantics I have not verified,
so they are left alone and noted rather than guessed at.

Effect on compat: all four files now fail to load in `rledger query`
too (#1912), matching bean-query, which is the point - they were
returning rows here and erroring there.

Refs #2008

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG

* chore(baselines): regenerate parser manifest for the four #2008 fixtures

The parser-output baseline gate reported drift on exactly the four
fixtures this branch now rejects, with their SOURCE hashes unchanged -
which is the confirmation, not a surprise: same input, different parser
output, and nothing else in the corpus moved.

Only those four rows are updated. A full `regen-corpus-baselines.sh`
run also wanted to add 17 `interpolation/` rows and rewrite
`donearm-ledger/accounts.beancount`'s SOURCE hash, neither of which
belongs in this commit: the interpolation fixtures are in-tree and
absent from the committed manifest today, which CI tolerates and which
is unrelated to this change, and a differing source hash means my local
corpus copy differs from the one CI fetches. Committing either would be
drift smuggled in under a green checkmark.

The four new hashes are cross-checked: CI's strict run reported the same
16-hex prefixes that the local regeneration produced in full.

Refs #2008

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG

* fix(parser): address #2020 review

Four review comments, all taken.

The one that matters: `test_lima_2008_cases_have_expected_strictness`
skipped itself when the fixture directory was missing. Those 441
fixtures are committed to the repo, so a missing directory is a broken
checkout rather than an unavailable dependency - and a self-skipping
test is the exact failure mode CLAUDE.md warns about under
"Availability-gated tests must fail loudly somewhere". Worse, skipping
would hide the very thing this table exists to pin. Now a hard assert.
I quoted that same rule in the conformance test's module doc while
leaving this skip two files away.

Also:

- `first_header_defect`'s contract said tokens run "through (not past)"
  the terminating NEWLINE, which reads as "include it". Both callers
  exclude it. Says so now, and records that NEWLINE stays in the trivia
  set only so feeding one in cannot change the verdict.
- The `unwrap_or_default()` on a non-char-boundary slice would have
  rendered `unexpected "" in transaction header`, naming nothing. Token
  ranges are always char boundaries so it is unreachable, but the branch
  now falls back to the byte range and defect kind instead of an empty
  quote.
- "three constructs" then listed four cases. Cases 6 and 7 are two
  fixtures of one construct; the doc now says that instead of leaving
  the reader to work it out.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG

---------

Co-authored-by: Claude Opus 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.

1 participant