Skip to content

feat(rpc): impl Filecoin.ChainGetTipSetFinalityStatus#6811

Open
hanabi1224 wants to merge 14 commits intomainfrom
hm/ChainGetTipSetFinalityStatus
Open

feat(rpc): impl Filecoin.ChainGetTipSetFinalityStatus#6811
hanabi1224 wants to merge 14 commits intomainfrom
hm/ChainGetTipSetFinalityStatus

Conversation

@hanabi1224
Copy link
Copy Markdown
Contributor

@hanabi1224 hanabi1224 commented Mar 29, 2026

Summary of changes

Part of #6769

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

  • New Features

    • Added a RPC to report EC finality threshold, finalized tipsets, and current head.
  • Chores

    • Updated test Lotus container image tag to stable.
    • Adjusted default EC finality parameters and made the finality calculator available where needed.
  • Tests

    • Updated tests and added a snapshot to cover the new finality RPC and revised thresholds.
  • Documentation

    • Recorded the new RPC in the changelog.

@hanabi1224 hanabi1224 added the RPC requires calibnet RPC checks to run on CI label Mar 29, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 29, 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: 1cb21d97-a5e3-4299-867f-b005b870bb19

📥 Commits

Reviewing files that changed from the base of the PR and between c60ce45 and b485d60.

⛔ Files ignored due to path filters (1)
  • src/rpc/snapshots/forest__rpc__tests__rpc__v2.snap is excluded by !**/*.snap
📒 Files selected for processing (1)
  • src/rpc/mod.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/rpc/mod.rs

Walkthrough

Adds a new RPC method Filecoin.ChainGetTipSetFinalityStatus (with helpers and an in-function cache), exposes ec_finality/calculator publicly, adjusts EC finality calculator constants and defaults, updates tests and API-compare configuration/snapshots, and registers the RPC in the method registry.

Changes

Cohort / File(s) Summary
Config & API-compare tests
scripts/tests/api_compare/.env, scripts/tests/api_compare/filter-list-gateway, src/tool/subcommands/api_cmd/test_snapshots.txt
Updated LOTUS_IMAGE tag; added Filecoin.ChainGetTipSetFinalityStatus to gateway filter-list; added new API snapshot entry.
EC finality calculator
src/chain/ec_finality/calculator/mod.rs, src/chain/ec_finality/calculator/tests.rs
Raised BISECT_HIGH (200→450), changed DEFAULT_SAFETY_EXPONENT type (i64→i32), removed redundant dead-code attributes, added DEFAULT_GUARANTEE: LazyLock<f64>, and updated tests to use it.
Module exports
src/chain/ec_finality/mod.rs, src/chain/mod.rs
Made calculator and ec_finality modules public (pub mod).
New Chain finality RPC & types
src/rpc/methods/chain.rs, src/rpc/methods/chain/types.rs, src/rpc/mod.rs
Added Filecoin.ChainGetTipSetFinalityStatus RPC, new ChainFinalityStatus response type, EC threshold/finalized-tipset helpers, an in-function mutex cache, and registered the method in RPC registry; adjusted some collection imports.
API compare test harness
src/tool/subcommands/api_cmd/api_compare_tests.rs
chain_tests()chain_tests(offline: bool) and conditional basic/identity test behavior for ChainHead and the new finality RPC.
Changelog
CHANGELOG.md
Added unreleased entry documenting the new Filecoin.ChainGetTipSetFinalityStatus RPC.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RPC as "RPC Handler"
    participant Cache as "In-Function Cache\n(mutex)"
    participant Store as "ChainStore / Blockstore"
    participant Calc as "EC Finality Calculator"

    Client->>RPC: Filecoin.ChainGetTipSetFinalityStatus(request)
    RPC->>Cache: lookup(head)
    alt cache hit
        Cache-->>RPC: cached(ec_threshold, ec_tipset)
    else cache miss
        RPC->>Store: fetch parent epochs (fill null rounds)
        Store-->>RPC: parent_epochs
        RPC->>Calc: find_threshold_depth(parent_epochs)
        Calc-->>RPC: ec_threshold
        RPC->>Store: tipset_by_height(ec_threshold)
        Store-->>RPC: ec_finalized_tipset
        RPC->>Cache: store(head => (ec_threshold, ec_finalized_tipset))
    end
    RPC->>Store: fetch F3 finalized tipset
    Store-->>RPC: f3_finalized_tipset
    RPC->>RPC: choose finalized_tip_set (compare epochs)
    RPC-->>Client: ChainFinalityStatus{ec_threshold, ec_finalized_tipset, f3_finalized_tipset, finalized_tip_set, head}
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • LesnyRumcajs
  • sudo-shashank
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(rpc): impl Filecoin.ChainGetTipSetFinalityStatus' clearly and concisely summarizes the main change: implementing a new RPC method. It accurately reflects the primary objective evident throughout the changeset.

✏️ 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/ChainGetTipSetFinalityStatus
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch hm/ChainGetTipSetFinalityStatus

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

@hanabi1224 hanabi1224 force-pushed the hm/ChainGetTipSetFinalityStatus branch from 50e2ab7 to 00abf12 Compare March 31, 2026 00:07
@hanabi1224 hanabi1224 force-pushed the hm/ChainGetTipSetFinalityStatus branch from 59f3462 to 6db0a02 Compare March 31, 2026 09:26
@hanabi1224 hanabi1224 marked this pull request as ready for review March 31, 2026 09:57
@hanabi1224 hanabi1224 requested a review from a team as a code owner March 31, 2026 09:57
@hanabi1224 hanabi1224 requested review from LesnyRumcajs and sudo-shashank and removed request for a team March 31, 2026 09:57
Copy link
Copy Markdown
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: 2

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

1236-1245: Redundant .clone() on tipset.

The ts is already owned from the Ok(ts) binding, so the .clone() is unnecessary.

Proposed fix
         let finalized = if depth >= 0
             && let Ok(ts) = ctx.chain_index().tipset_by_height(
                 (head.epoch() - depth).max(0),
                 head,
                 ResolveNullTipset::TakeOlder,
             ) {
-            Some(ts.clone())
+            Some(ts)
         } else {
             None
         };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/rpc/methods/chain.rs` around lines 1236 - 1245, The code constructs
`finalized` by matching `let Ok(ts) = ctx.chain_index().tipset_by_height(...)`
but then calls `ts.clone()` even though `ts` is already moved into the `Ok(ts)`
binding; remove the redundant `.clone()` and use `ts` directly when returning
`Some(ts)` in the `finalized` assignment (the change affects the block that
references `finalized`, the `let Ok(ts)` pattern,
`ctx.chain_index().tipset_by_height`, `head`, and
`ResolveNullTipset::TakeOlder`).

1261-1267: Consider async blocking for cache miss path.

On a cache miss, get_finality_status walks ~905 epochs through the blockstore and runs a binary search with floating-point probability calculations via find_threshold_depth. While blockstore lookups are cached and the binary search is bounded (O(log 450)), this synchronous work could briefly block the async runtime on every new block when the cache invalidates.

Cache hits will be frequent in practice since the cache invalidates only when heaviest_tipset changes, which happens infrequently compared to typical RPC request rates. However, if high RPC concurrency is a concern for your load patterns, consider using tokio::task::spawn_blocking for the cache miss path, consistent with similar CPU-bound work like eth.rs::execution_trace.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/rpc/methods/chain.rs` around lines 1261 - 1267, The handler currently
calls get_finality_status synchronously inside handle, which can perform heavy
CPU/blocking work on cache misses; change handle to offload that work to a
blocking thread by invoking tokio::task::spawn_blocking (or equivalent) for
get_finality_status and awaiting its JoinHandle so the async runtime isn't
blocked on the ~905-epoch walk and binary search; update the handle function to
call spawn_blocking(|| Self::get_finality_status(&ctx)) and await the result,
mirroring the pattern used for other CPU-bound work like
eth.rs::execution_trace.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/chain/ec_finality/calculator/mod.rs`:
- Around line 27-29: Update the test comment in the EC finality calculator tests
to reflect the new BISECT_HIGH value (450) instead of 200: locate the comment
above the all-ones chain test in tests.rs (referencing the BISECT/BisectHigh
behavior) and change its text to mention "BisectHigh=450" or "BISECT_HIGH=450"
(e.g., "// All-1s chain is too degraded to achieve 2^-30 within the bisect
search range (BisectHigh=450), so threshold is not found"); no logic changes
needed—the test already references the BISECT_HIGH constant.

In `@src/rpc/methods/chain/types.rs`:
- Around line 14-16: The doc comment block above the type that begins "Describes
how the node is currently determining finality" has a regular comment line ("//
combining probabilistic...") which breaks the doc comment flow; change that line
to a doc comment ("/// combining probabilistic...") so the entire comment block
is contiguous and will appear in generated documentation for the associated
type/enum in types.rs.

---

Nitpick comments:
In `@src/rpc/methods/chain.rs`:
- Around line 1236-1245: The code constructs `finalized` by matching `let Ok(ts)
= ctx.chain_index().tipset_by_height(...)` but then calls `ts.clone()` even
though `ts` is already moved into the `Ok(ts)` binding; remove the redundant
`.clone()` and use `ts` directly when returning `Some(ts)` in the `finalized`
assignment (the change affects the block that references `finalized`, the `let
Ok(ts)` pattern, `ctx.chain_index().tipset_by_height`, `head`, and
`ResolveNullTipset::TakeOlder`).
- Around line 1261-1267: The handler currently calls get_finality_status
synchronously inside handle, which can perform heavy CPU/blocking work on cache
misses; change handle to offload that work to a blocking thread by invoking
tokio::task::spawn_blocking (or equivalent) for get_finality_status and awaiting
its JoinHandle so the async runtime isn't blocked on the ~905-epoch walk and
binary search; update the handle function to call spawn_blocking(||
Self::get_finality_status(&ctx)) and await the result, mirroring the pattern
used for other CPU-bound work like eth.rs::execution_trace.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3713c0e0-a502-4285-a18b-3d12c21fceb8

📥 Commits

Reviewing files that changed from the base of the PR and between d52a294 and 6db0a02.

⛔ Files ignored due to path filters (1)
  • src/rpc/snapshots/forest__rpc__tests__rpc__v2.snap is excluded by !**/*.snap
📒 Files selected for processing (11)
  • scripts/tests/api_compare/.env
  • scripts/tests/api_compare/filter-list-gateway
  • src/chain/ec_finality/calculator/mod.rs
  • src/chain/ec_finality/calculator/tests.rs
  • src/chain/ec_finality/mod.rs
  • src/chain/mod.rs
  • src/rpc/methods/chain.rs
  • src/rpc/methods/chain/types.rs
  • src/rpc/mod.rs
  • src/tool/subcommands/api_cmd/api_compare_tests.rs
  • src/tool/subcommands/api_cmd/test_snapshots.txt

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 31, 2026

Codecov Report

❌ Patch coverage is 82.14286% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.88%. Comparing base (0b7f2b4) to head (b485d60).
⚠️ Report is 6 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/rpc/methods/chain.rs 81.92% 14 Missing and 1 partial ⚠️
Additional details and impacted files
Files with missing lines Coverage Δ
src/chain/ec_finality/calculator/mod.rs 92.19% <100.00%> (+0.03%) ⬆️
src/chain/mod.rs 75.00% <ø> (ø)
src/rpc/mod.rs 88.48% <ø> (ø)
src/rpc/methods/chain.rs 55.49% <81.92%> (+2.31%) ⬆️

... and 3 files with indirect coverage changes


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 0b7f2b4...b485d60. Read the comment docs.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@LesnyRumcajs
Copy link
Copy Markdown
Member

no green checkmark, no review!

@hanabi1224 hanabi1224 mentioned this pull request Apr 3, 2026
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

RPC requires calibnet RPC checks to run on CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants