Skip to content

feat: use datastore directly for state store #66

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 30, 2025
Merged

Conversation

facundomedica
Copy link
Contributor

@facundomedica facundomedica commented Apr 29, 2025

Overview

Now we use datastore.Batching directly and create the rollkit interface internally in order to access Rollkit's data.

Closes #64

Summary by CodeRabbit

  • Refactor
    • Updated internal data storage to use a new datastore interface, improving separation between different storage mechanisms.
    • Enhanced block and blockchain data retrieval by switching to a dedicated store interface for improved consistency.
    • Streamlined state management with a new store wrapper, optimizing state loading and saving processes.
    • Simplified initialization by passing existing datastore instances directly, improving startup efficiency.

Copy link
Contributor

coderabbitai bot commented Apr 29, 2025

"""

Walkthrough

The changes refactor the storage layer in the adapter by replacing the usage of the Rollkit-specific store.Store interface with a new Store type that wraps the ds.Batching interface from the IPFS datastore package with a prefix transform. The Adapter struct now holds both a pointer to this new Store for general state management and a RollkitStore instance for Rollkit-specific operations. Constructors and methods have been updated to use these new types. Calls to fetch blockchain data and height in RPC providers now use RollkitStore instead of the generic store. The server startup code is updated to use the new store setup. The go.mod file was changed to make the go-datastore dependency direct.

Changes

File(s) Change Summary
pkg/adapter/adapter.go Changed Adapter.Store field from store.Store to *Store (new type wrapping ds.Batching), added RollkitStore rstore.Store. Updated NewABCIExecutor to accept ds.Batching and initialize new Store and RollkitStore fields. Removed NewAdapter and LoadState/SaveState methods. Updated methods to use new Store and RollkitStore.
pkg/adapter/store.go Added new Store type embedding ds.Batching with prefix transform. Added NewStore constructor. Converted loadState and saveState functions into methods on Store using ds.Key for access. Changed state key from "abci-s" string to constant "s" key with prefix.
pkg/rpc/provider/blockchain.go, pkg/rpc/provider/provider.go Replaced calls from adapter.Store to adapter.RollkitStore for block data retrieval and height queries. Kept state loading in Validators using adapter.Store.LoadState. No signature changes.
pkg/rpc/provider/info.go Replaced calls to p.adapter.LoadState with p.adapter.Store.LoadState in Status and ConsensusParams methods.
server/start.go Removed creation of new store wrapper, passed existing database directly to NewABCIExecutor. Updated height retrieval to use executor.RollkitStore.Height.
go.mod Made github.com/ipfs/go-datastore dependency direct by removing // indirect comment.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Adapter
    participant Store as *Store (ds.Batching wrapper)
    participant RollkitStore as rstore.Store

    Client->>Adapter: NewABCIExecutor(ds.Batching)
    Adapter->>Store: LoadState / SaveState using ds.Key "s"
    Adapter->>RollkitStore: GetTxs calls Height(ctx)
    RpcProvider->>RollkitStore: Block data & height queries
    RpcProvider->>Store: LoadState for Validators, Status, ConsensusParams
    Server->>Adapter: Start with ds.Batching store
Loading

Assessment against linked issues

Objective Addressed Explanation
Replace Rollkit store interface and metadata hack with raw db and custom interface (#64)

Suggested reviewers

  • tac0turtle

Poem

🐇 In burrows deep where data flows,
The store now swaps, the old one goes!
With keys anew and types aligned,
The rabbit’s code is redefined.
No more hacks, just storage neat,
This change is one that can’t be beat! ✨
Hop along, the code’s complete! 🥕
"""

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b170ffa and 9823886.

📒 Files selected for processing (5)
  • go.mod (1 hunks)
  • pkg/adapter/adapter.go (9 hunks)
  • pkg/adapter/store.go (3 hunks)
  • pkg/rpc/provider/blockchain.go (8 hunks)
  • pkg/rpc/provider/info.go (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • go.mod
🚧 Files skipped from review as they are similar to previous changes (3)
  • pkg/adapter/store.go
  • pkg/rpc/provider/blockchain.go
  • pkg/adapter/adapter.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
pkg/rpc/provider/info.go (1)
pkg/adapter/store.go (1)
  • Store (22-24)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: lint / golangci-lint
🔇 Additional comments (2)
pkg/rpc/provider/info.go (2)

20-20: Correctly adapts to the refactored store architecture

This change properly updates the code to call LoadState on the new Store type field rather than directly on the adapter, which aligns with the refactoring where LoadState was moved to the Store struct that wraps the datastore interface.


112-112: Consistent adaptation to the refactored store architecture

The change correctly updates the ConsensusParams method to use the same pattern as the Status method, calling LoadState on the adapter's Store field. This ensures consistent usage of the refactored storage layer throughout the codebase.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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

Documentation and Community

  • 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.

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: 3

🔭 Outside diff range comments (2)
pkg/adapter/store.go (1)

16-23: ⚠️ Potential issue

Handle ds.ErrNotFound to avoid boot-time failures

ipfs/go-datastore returns ds.ErrNotFound when the key is missing.
Today that bubbles up as an error, so a brand-new node panics instead of starting
with an empty state.

-func loadState(ctx context.Context, s ds.Batching) (*cmtstate.State, error) {
-	data, err := s.Get(ctx, ds.NewKey(stateKey))
-	if err != nil {
-		return nil, fmt.Errorf("failed to get state metadata: %w", err)
-	}
-	if data == nil {
-		return &cmtstate.State{}, nil
-	}
+func loadState(ctx context.Context, s ds.Batching) (*cmtstate.State, error) {
+	data, err := s.Get(ctx, ds.NewKey(stateKey))
+	if errors.Is(err, ds.ErrNotFound) {
+		// first start – return an empty state and let the caller initialise it
+		return &cmtstate.State{}, nil
+	}
+	if err != nil {
+		return nil, fmt.Errorf("failed to get state metadata: %w", err)
+	}

errors must also be imported:

-import (
-    "context"
-    "fmt"
+import (
+    "context"
+    "errors"
+    "fmt"
pkg/adapter/adapter.go (1)

61-70: 🛠️ Refactor suggestion

Extend constructor to receive the Rollkit store

-func NewABCIExecutor(
-    app servertypes.ABCI,
-    store ds.Batching,
-    p2pClient *rollkitp2p.Client,
+func NewABCIExecutor(
+    app servertypes.ABCI,
+    store ds.Batching,
+    rollkitStore store.Store,           // NEW
+    p2pClient *rollkitp2p.Client,
@@
-    a := &Adapter{
-        App:        app,
-        Store:      store,
+    a := &Adapter{
+        App:          app,
+        Store:        store,
+        RollkitStore: rollkitStore,      // NEW

All call-sites must be updated accordingly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 170ec17 and afa7904.

📒 Files selected for processing (2)
  • pkg/adapter/adapter.go (5 hunks)
  • pkg/adapter/store.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: lint / golangci-lint

Comment on lines +396 to 399
currentHeight, err := a.RollkitStore.Height(ctx)
if err != nil {
return nil, err
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Guard against nil RollkitStore before calling Height

Even with the constructor fix, defensive code is advisable:

- currentHeight, err := a.RollkitStore.Height(ctx)
+ if a.RollkitStore == nil {
+     return nil, fmt.Errorf("RollkitStore not initialised")
+ }
+ currentHeight, err := a.RollkitStore.Height(ctx)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
currentHeight, err := a.RollkitStore.Height(ctx)
if err != nil {
return nil, err
}
if a.RollkitStore == nil {
return nil, fmt.Errorf("RollkitStore not initialised")
}
currentHeight, err := a.RollkitStore.Height(ctx)
if err != nil {
return nil, err
}

Copy link
Contributor

@tac0turtle tac0turtle left a comment

Choose a reason for hiding this comment

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

Left one comment but looks good

@facundomedica facundomedica enabled auto-merge (squash) April 30, 2025 13:01
@tac0turtle tac0turtle requested a review from Copilot April 30, 2025 13:59
Copy link

@Copilot Copilot AI left a comment

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 refactors the state storage mechanism to use datastore.Batching directly and creates an internal Rollkit interface to access Rollkit's data.

  • Replace the old store interface with datastore.Batching in server/start.go and propagate changes to retrieve block heights and block data.
  • Update the RPC providers to use the new RollkitStore, ensuring consistency across different RPC endpoints.
  • Refactor the adapter and store packages to create a prefixed store for ABCI data while initializing a separate RollkitStore from the same underlying datastore.

Reviewed Changes

Copilot reviewed 5 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
server/start.go Replaced store reference with executor.RollkitStore for height retrieval and initialization.
pkg/rpc/provider/provider.go Updated block height and data retrieval to use RollkitStore instead of the old store.
pkg/rpc/provider/blockchain.go Switched to RollkitStore for obtaining block data, height, and block search functionality.
pkg/adapter/store.go Converted state load/save functions to use datastore.Batching along with key prefixing.
pkg/adapter/adapter.go Modified adapter initialization to wrap the datastore with a prefixed store and create a separate RollkitStore.
Files not reviewed (1)
  • go.mod: Language not supported
Comments suppressed due to low confidence (1)

pkg/adapter/store.go:18

  • [nitpick] Consider renaming 'stateKey' to a more descriptive name (e.g., 'stateMetadataKey') to enhance code readability.
stateKey = "s"


// Create a prefixed store for ABCI data
prefixedStore := NewPrefixedStore(store)
rollkitStore := rstore.New(store) // do not use prefixedStore for Rollkit
Copy link
Preview

Copilot AI Apr 30, 2025

Choose a reason for hiding this comment

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

[nitpick] Consider adding a brief explanation of why RollkitStore is initialized using the original store rather than the prefixedStore to improve maintainability and clarity.

Suggested change
rollkitStore := rstore.New(store) // do not use prefixedStore for Rollkit
// RollkitStore requires access to the full, unmodified datastore to function correctly.
// Using the prefixedStore would restrict or alter its behavior, which is not desirable.
rollkitStore := rstore.New(store)

Copilot uses AI. Check for mistakes.

Copy link
Contributor

@tac0turtle tac0turtle left a comment

Choose a reason for hiding this comment

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

left two comments, otherwise looks good

Copy link

@alpe alpe left a comment

Choose a reason for hiding this comment

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

👍 The changes look good!
Bonus points would be available for some regression tests.

Mempool mempool.Mempool
MempoolIDs *mempoolIDs
App servertypes.ABCI
Store ds.Batching
Copy link

Choose a reason for hiding this comment

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

personal preference: this is not used somewhere else and can be private

not sure if this is the same idea as @tac0turtle mentioned below but if you would replace batch with a custom state store type, you could encapsulate load/store and avoid the verbose db type.
This may even enable features like caching in the future

@@ -120,7 +120,7 @@ func (p *RpcProvider) BlockResults(ctx context.Context, height *int64) (*coretyp
// Commit implements client.CometRPC.
func (p *RpcProvider) Commit(ctx context.Context, height *int64) (*coretypes.ResultCommit, error) {
heightValue := p.normalizeHeight(height)
header, data, err := p.adapter.Store.GetBlockData(ctx, heightValue)
header, data, err := p.adapter.RollkitStore.GetBlockData(ctx, heightValue)
Copy link
Contributor

Choose a reason for hiding this comment

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

could you open an issue, this block structure is not the one we want to use. the header is not compatible with ibc here

@facundomedica facundomedica merged commit d62bf75 into main Apr 30, 2025
12 checks passed
@facundomedica facundomedica deleted the facu/improve-store branch April 30, 2025 15:57
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.

[chore]: store implementation
3 participants