Skip to content

fix: error computing state for a null epoch#6018

Merged
hanabi1224 merged 1 commit intomainfrom
hm/fix-state-compute-for-null-epoch
Sep 1, 2025
Merged

fix: error computing state for a null epoch#6018
hanabi1224 merged 1 commit intomainfrom
hm/fix-state-compute-for-null-epoch

Conversation

@hanabi1224
Copy link
Contributor

@hanabi1224 hanabi1224 commented Sep 1, 2025

Summary of changes

This PR fixes an error in forest-cli state compute --epoch {EPOCH} when {EPOCH} is a null epoch. It now calculates the state root of its closest non-null ancestor tipset.

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.

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability of state computations over short or null ranges, preventing incorrect starting points and edge-case failures.
    • Ensures backward iteration starts correctly when the requested start height meets or exceeds the end height, leading to consistent results for single-epoch queries and scenarios with null rounds.
    • No changes to public APIs or user-facing interfaces.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 1, 2025

Walkthrough

Adjusts ForestStateCompute’s range selection: when from_epoch is at or beyond to_ts.epoch(), it clamps from_ts to to_ts; otherwise resolves from_ts via tipset_by_height with TakeOlder. Iteration and computation logic remain unchanged.

Changes

Cohort / File(s) Summary of modifications
State compute range clamp
src/rpc/methods/state.rs
Added conditional to clamp from_ts to to_ts when from_epoch >= to_ts.epoch(); otherwise fetch from_ts via tipset_by_height(from_epoch, to_ts, TakeOlder). No interface changes; rest of iteration/computation unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant RPC as StateCompute
  participant CS as ChainStore

  C->>RPC: state_compute(from_epoch, to_ts, n_epochs)
  alt from_epoch >= to_ts.epoch()
    note over RPC: Clamp start\nfrom_ts = to_ts
  else
    RPC->>CS: tipset_by_height(from_epoch, to_ts, TakeOlder)
    CS-->>RPC: from_ts
  end
  loop iterate epochs backward
    RPC->>CS: load tipset / state for epoch
    CS-->>RPC: tipset/state
    RPC->>RPC: compute state
  end
  RPC-->>C: results
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • LesnyRumcajs
  • akaladarshi
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch hm/fix-state-compute-for-null-epoch

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@hanabi1224
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 1, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@hanabi1224 hanabi1224 marked this pull request as ready for review September 1, 2025 10:57
@hanabi1224 hanabi1224 requested a review from a team as a code owner September 1, 2025 10:57
@hanabi1224 hanabi1224 requested review from LesnyRumcajs and sudo-shashank and removed request for a team September 1, 2025 10:57
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/rpc/methods/state.rs (2)

1441-1451: Simplify by clamping the height and using a single tipset_by_height call.

Functionally equivalent but a bit simpler and keeps all paths going through the same API.

-        let from_ts = if from_epoch >= to_ts.epoch() {
-            // When `from_epoch` is a null epoch or `n_epochs` is 1,
-            // `to_ts.epoch()` could be less than or equal to `from_epoch`
-            to_ts.clone()
-        } else {
-            ctx.chain_index().tipset_by_height(
-                from_epoch,
-                to_ts.clone(),
-                ResolveNullTipset::TakeOlder,
-            )?
-        };
+        // Clamp start height to the anchor tipset's epoch to avoid requesting above the anchor.
+        let from_epoch_clamped = std::cmp::min(from_epoch, to_ts.epoch());
+        let from_ts = ctx.chain_index().tipset_by_height(
+            from_epoch_clamped,
+            to_ts.clone(),
+            ResolveNullTipset::TakeOlder,
+        )?;

1435-1435: Nit: use saturating_add to be defensive.

Extremely unlikely to matter in practice, but avoids theoretical overflow on pathological inputs.

-        let to_epoch = from_epoch + n_epochs - 1;
+        let to_epoch = from_epoch.saturating_add(n_epochs - 1);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 903c521 and 88a0640.

📒 Files selected for processing (1)
  • src/rpc/methods/state.rs (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: hanabi1224
PR: ChainSafe/forest#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.
📚 Learning: 2025-08-25T13:35:24.230Z
Learnt from: hanabi1224
PR: ChainSafe/forest#5969
File: src/tool/subcommands/snapshot_cmd.rs:412-412
Timestamp: 2025-08-25T13:35:24.230Z
Learning: In src/tool/subcommands/snapshot_cmd.rs, the +1 in `last_epoch = ts.epoch() - epochs as i64 + 1` fixes an off-by-1 bug where specifying --check-stateroots=N would validate N+1 epochs instead of N epochs, causing out-of-bounds errors when the snapshot contains only N recent state roots.

Applied to files:

  • src/rpc/methods/state.rs
📚 Learning: 2025-08-18T03:09:47.932Z
Learnt from: hanabi1224
PR: ChainSafe/forest#5944
File: src/chain/store/index.rs:0-0
Timestamp: 2025-08-18T03:09:47.932Z
Learning: In Forest's tipset_by_height caching implementation, hanabi1224 prefers performance-conscious solutions that leverage finality guarantees rather than expensive chain walking for fork detection. The approach of constraining cache lookups to finalized epochs (using CHECKPOINT_INTERVAL >= CHAIN_FINALITY) provides fork safety without the performance cost of ancestry verification.

Applied to files:

  • src/rpc/methods/state.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (20)
  • GitHub Check: Calibnet kademlia checks
  • GitHub Check: Snapshot unordered export checks
  • GitHub Check: Bootstrap checks - Lotus
  • GitHub Check: Snapshot export checks v2 with F3 data
  • GitHub Check: Bootstrap checks - Forest
  • GitHub Check: db-migration-checks
  • GitHub Check: Calibnet api test-stateful check
  • GitHub Check: Snapshot export checks
  • GitHub Check: State migrations
  • GitHub Check: Wallet tests
  • GitHub Check: Calibnet eth mapping check
  • GitHub Check: Devnet checks
  • GitHub Check: Calibnet no discovery checks
  • GitHub Check: Calibnet stateless RPC check
  • GitHub Check: Calibnet stateless mode check
  • GitHub Check: Calibnet check
  • GitHub Check: Forest CLI checks
  • GitHub Check: All lint checks
  • GitHub Check: Analyze (rust)
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
src/rpc/methods/state.rs (1)

1441-1451: Null-epoch clamp is correct and fixes the edge case.

Clamping from_ts to to_ts when from_epoch >= to_ts.epoch() prevents requesting a tipset above the anchor and handles null-epoch ranges cleanly. LGTM.

@hanabi1224 hanabi1224 added this pull request to the merge queue Sep 1, 2025
Merged via the queue into main with commit 80e16b8 Sep 1, 2025
50 checks passed
@hanabi1224 hanabi1224 deleted the hm/fix-state-compute-for-null-epoch branch September 1, 2025 13:32
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.

3 participants