Skip to content

refactor: remove a few unnecessary .expect("infallible")#6766

Merged
hanabi1224 merged 2 commits intomainfrom
hm/less-expect
Mar 19, 2026
Merged

refactor: remove a few unnecessary .expect("infallible")#6766
hanabi1224 merged 2 commits intomainfrom
hm/less-expect

Conversation

@hanabi1224
Copy link
Contributor

@hanabi1224 hanabi1224 commented Mar 19, 2026

Summary of changes

Changes introduced in this pull request:

Reference issue to close (if applicable)

Closes

Other information and links

Change checklist

  • I have performed a self-review of my own code,
  • I have made corresponding changes to the documentation. All new code adheres to the team's documentation standards,
  • I have added tests that prove my fix is effective or that my feature works (if possible),
  • I have made sure the CHANGELOG is up-to-date. All user-facing changes should be reflected in this document.

Outside contributions

  • I have read and agree to the CONTRIBUTING document.
  • I have read and agree to the AI Policy document. I understand that failure to comply with the guidelines will lead to rejection of the pull request.

Summary by CodeRabbit

  • Refactor

    • Streamlined internal construction of non-zero numeric values across authentication, chain sync, and RPC areas to use a simpler, non-fallible approach while preserving behavior.
    • Adjusted cache capacity initialization to the same effective size using the new pattern.
  • Tests

    • Simplified test token expiration setup to use non-fallible duration construction.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 19, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5767c4a7-c17a-4997-9c5f-927694519179

📥 Commits

Reviewing files that changed from the base of the PR and between f4dbce4 and 4abd00f.

📒 Files selected for processing (1)
  • src/rpc/methods/f3.rs

Walkthrough

Replaced fallible NonZero and chrono Duration constructors with non-fallible alternatives: nonzero! macro for NonZero types and direct chrono::Duration constructors in JWT test code. Changes are limited to test and internal initialization sites; no public API changes.

Changes

Cohort / File(s) Summary
JWT Test Refactoring
src/auth/mod.rs
Swapped Duration::try_hours/try_seconds(...).expect("Infallible") for direct chrono::Duration::hours(...) and negated durations in JWT test token-expiration setup.
Index cache capacity
src/chain/store/index.rs
Replaced 20480.try_into().expect("infallible") with nonzero!(20480_usize) when initializing SizeTrackingLruCache capacity.
Chain sync NonZero migration
src/chain_sync/network_context.rs
Replaced NonZeroU64::new(...).expect("Infallible") with nonzero!(...) at three handle_chain_exchange_request call sites; added nonzero_ext::nonzero import.
RPC (f3) NonZero and cache changes
src/rpc/methods/f3.rs
Changed blockstore read-cache capacity to NonZeroUsize via nonzero!(65536_usize), removed prior try_into().expect(...) conversions, and replaced 1.try_into().expect("Infallible") with nonzero!(1_u64); added imports for nonzero_ext::nonzero and std::num::NonZeroUsize.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

RPC

Suggested reviewers

  • LesnyRumcajs
  • sudo-shashank
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the primary change: refactoring to remove unnecessary .expect("infallible") calls across multiple files, which is what the entire changeset implements.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch hm/less-expect
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch hm/less-expect
📝 Coding Plan
  • Generate coding plan for human review comments

Comment @coderabbitai help to get the list of available commands and usage tips.

@hanabi1224 hanabi1224 marked this pull request as ready for review March 19, 2026 07:53
@hanabi1224 hanabi1224 requested a review from a team as a code owner March 19, 2026 07:53
@hanabi1224 hanabi1224 requested review from akaladarshi and sudo-shashank and removed request for a team March 19, 2026 07:53
@hanabi1224
Copy link
Contributor Author

@coderabbitai anything similar in the repo?

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 19, 2026

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for .expect("infallible") patterns
rg -n 'expect\("infallible"\)' --type rust -C2

echo "---"
# Also search for similar patterns with different casing or wording
rg -n 'expect\("Infallible"\)' --type rust -C2

echo "---"
# Search for unwrap with infallible comments
rg -n 'infallible' --type rust -C2

Repository: ChainSafe/forest
Length of output: 19394


@hanabi1224 Yes! Here's a summary of similar .expect("infallible") / .expect("Infallible") patterns found across the codebase, grouped by category:


1. ProgressStyle::with_template with hardcoded strings (same pattern as this PR)

These are trivially infallible since the template strings are compile-time constants:

  • src/tool/subcommands/snapshot_cmd.rs:245
  • src/tool/subcommands/benchmark_cmd.rs:323
  • src/tool/subcommands/car_cmd.rs:109

2. Hardcoded literal conversions

  • src/rpc/methods/f3.rs:5341.try_into().expect("Infallible") (converting the literal 1)
  • src/rpc/methods/f3.rs:173BLOCKSTORE_CACHE_CAP.try_into().expect("Infallible") (converting a constant)
  • src/shim/version.rs:89u32::from(other.0).try_into().expect("Infallible")

3. Fixed-size slice-to-array conversions

  • src/db/car/forest.rs:469bytes[8..16].try_into().expect("infallible") — the slice length is structurally guaranteed by [u8; Self::SIZE]

4. Hardcoded valid string parsing

  • src/libp2p/config.rs:42,43"/ip4/0.0.0.0/tcp/0".parse().expect("Infallible") and /udp/0/quic-v1 variant
  • src/blocks/header/test.rs:13,18 — parsing hardcoded CID/hex strings in tests

5. Non-empty iterator .last() after .first() check

  • src/chain_sync/chain_follower.rs:758chain.last().expect("Infallible") immediately after chain.first() succeeds

6. Regex-validated .parse() calls

  • src/cli/subcommands/f3_cmd.rs:334,337 — parsing regex capture groups that are guaranteed to be valid integers

7. signature.bytes() slice ops (may be justified by invariants)

Multiple occurrences in src/eth/homestead_transaction.rs, src/eth/eip_155_transaction.rs, and src/eth/transaction.rs that assume the signature is always a fixed length. These might be better expressed with a length assertion or a typed wrapper, but the "infallible" claim depends on an upstream invariant.


🧠 Learnings used
Learnt from: hanabi1224
Repo: ChainSafe/forest PR: 5930
File: build.rs:64-77
Timestamp: 2025-08-13T09:43:20.301Z
Learning: hanabi1224 prefers hard compile-time errors in build scripts rather than runtime safeguards or collision detection, believing it's better to fail fast and fix root causes of issues like malformed snapshot names.

Learnt from: hanabi1224
Repo: ChainSafe/forest PR: 6057
File: src/cli/subcommands/f3_cmd.rs:0-0
Timestamp: 2025-09-09T10:37:17.947Z
Learning: hanabi1224 prefers having default timeouts (like 10m for --no-progress-timeout) to prevent commands from hanging indefinitely, even when the timeout flag isn't explicitly provided by users. This fail-fast approach is preferred over requiring explicit flag usage.

Learnt from: hanabi1224
Repo: ChainSafe/forest PR: 6644
File: src/rpc/methods/eth/tipset_resolver.rs:168-168
Timestamp: 2026-03-05T01:04:43.904Z
Learning: In the Forest codebase (ChainSafe/forest), `ec` in function names like `get_ec_finalized_tipset` and `get_ec_safe_tipset` stands for "expected-consensus", not "election-confirmation". Doc comments and descriptions referring to these functions should use the term "expected-consensus finality".

akaladarshi
akaladarshi previously approved these changes Mar 19, 2026
@hanabi1224 hanabi1224 enabled auto-merge March 19, 2026 08:01
@hanabi1224 hanabi1224 disabled auto-merge March 19, 2026 08:01
@codecov
Copy link

codecov bot commented Mar 19, 2026

Codecov Report

❌ Patch coverage is 50.00000% with 5 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (main@94a5591). Learn more about missing BASE report.
⚠️ Report is 1 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/chain_sync/network_context.rs 0.00% 3 Missing ⚠️
src/rpc/methods/f3.rs 0.00% 2 Missing ⚠️
Additional details and impacted files
Files with missing lines Coverage Δ
src/auth/mod.rs 100.00% <100.00%> (ø)
src/chain/store/index.rs 87.11% <100.00%> (ø)
src/rpc/methods/f3.rs 2.06% <0.00%> (ø)
src/chain_sync/network_context.rs 30.68% <0.00%> (ø)

Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 94a5591...4abd00f. Read the comment docs.

@hanabi1224 hanabi1224 added this pull request to the merge queue Mar 19, 2026
Merged via the queue into main with commit 8e76961 Mar 19, 2026
35 checks passed
@hanabi1224 hanabi1224 deleted the hm/less-expect branch March 19, 2026 09:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants