Skip to content

feat(zetacore)!: ensure cctx list is sorted by creation time #3548

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 12 commits into from
Feb 24, 2025

Conversation

gartnera
Copy link
Member

@gartnera gartnera commented Feb 18, 2025

The CctxAll() RPC is quite useless on live networks since the results are ordered by tss then chainID.

Add an index on the created_timestamp field. Add an counter index which is incremented when a new CCTX is created. When listing all CCTX, use this index so that the CCTX are ordered by when they were created. You do have to specify pagination.reversed=true right now, but I could also invert counter field the sort descending by default.

This allows you to see the most recent CCTXs first.

Without this, it's quite annoying to calculate CCTX latency in the exporter and other places.

TODO:

  • migration. please advise if this is needed.
  • test coverage
  • do we need a new API endpoint? Or put this behind a separate sort_created_timestamp=true parameter.

I could also introduce a ListRecentCctx(lookbackRange) which just uses the nonces to look for recent CCTXs. I'm mostly just interested in having a way lookup recent CCTX. It would look very similar to ListPendingCctx(). Update: you can't do that because it would miss inbounds.

Also:

  • set max page size to 1000 on this endpoint
  • add unordered parameter to get the old behavior

Summary by CodeRabbit

  • New Features

    • Introduced a timestamp-based indexing mechanism for cross-chain transactions to support more efficient and reliable data retrieval and pagination.
  • Refactor

    • Enhanced transaction storage and query handling with improved variable naming and error processing to ensure smoother cross-chain transaction management.

@gartnera gartnera requested a review from a team as a code owner February 18, 2025 18:06
Copy link
Contributor

coderabbitai bot commented Feb 18, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

The pull request introduces timestamp indexing for cross-chain transactions. A new constant (TSIndexKey) is added in the keeper, and the SetCrossChainTx method is enhanced to create and store a timestamp index for each transaction, including error handling. In the gRPC query handler, the CctxAll method is modified to use the new timestamp store (tsStore) with updated variable names and retrieval logic. Additionally, a new constant (StoreKeyCreatedAtIndex) is added in the types package for creation timestamp indexing.

Changes

File(s) Change Summary
x/crosschain/keeper/cctx.go Added TSIndexKey constant; updated SetCrossChainTx to create a timestamp index using a new store prefix, handle errors, and use a variable (cctxIndexPrefix) for storing CCTX data.
x/crosschain/keeper/grpc_query_cctx.go Renamed sendStore to cctxStore and send to cctx; introduced new tsStore for timestamp index-based pagination; modified data retrieval and unmarshalling in the CctxAll method.
x/crosschain/.../types/keys.go Added StoreKeyCreatedAtIndex constant by appending "-createdat" to the ModuleName, expanding timestamp indexing capabilities.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant SetCrossChainTx
    participant Store
    participant TSIndexStore
    participant Logger

    Client->>SetCrossChainTx: Call SetCrossChainTx(tx)
    SetCrossChainTx->>Store: Retrieve CCTX index bytes
    Store-->>SetCrossChainTx: Return cctxIndexBytes
    alt Error in retrieving index bytes
        SetCrossChainTx->>Logger: Log error
        SetCrossChainTx-->>Client: Return error
    else No error
        SetCrossChainTx->>TSIndexStore: Store (cctxIndexBytes + timestamp)
        TSIndexStore-->>SetCrossChainTx: Acknowledge storage
        SetCrossChainTx->>Store: Save CCTX with cctxIndexPrefix
        Store-->>SetCrossChainTx: Confirm storage
    end
Loading
sequenceDiagram
    participant Client
    participant CctxAll
    participant TSStore
    participant CctxStore

    Client->>CctxAll: Request CCTX list with pagination
    CctxAll->>TSStore: Paginate over timestamp index keys
    TSStore-->>CctxAll: Return key list
    loop For each key
        CctxAll->>CctxStore: Retrieve CCTX data using key
        CctxStore-->>CctxAll: Return transaction data
    end
    CctxAll-->>Client: Return aggregated CCTX list
Loading

Possibly related PRs

Suggested labels

breaking:proto, UPGRADE_TESTS, UPGRADE_IMPORT_MAINNET_TESTS

Suggested reviewers

  • fbac
  • kingpinXD
  • ws4charlie
  • lumtis
  • skosito
  • brewmaster012

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @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.

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

🧹 Nitpick comments (4)
x/crosschain/types/keys.go (1)

18-19: Remove duplicate comment.

The comment "StoreKey defines the primary module store key" is duplicated from line 15.

-	// StoreKey defines the primary module store key
	StoreKeyCreatedAtIndex = ModuleName + "-createdat"
x/crosschain/keeper/cctx.go (2)

96-98: Consider moving constant to types package.

The TSIndexKey constant is used for store prefixes, similar to other keys defined in the types package. Consider moving it there for consistency.


115-119: Improve error handling.

The error handling could be more informative by including the CCTX index in the error message.

-		k.Logger(ctx).Error("unable to GetCCTXIndexBytes", "err", err)
+		k.Logger(ctx).Error("unable to GetCCTXIndexBytes", "err", err, "cctx_index", cctx.Index)
x/crosschain/keeper/grpc_query_cctx.go (1)

59-66: Consider adding error handling for missing CCTX.

While the implementation is correct, it might be helpful to log when a CCTX is not found in the store.

 		var cctx types.CrossChainTx
 		cctxBytes := cctxStore.Get(value)
+		if cctxBytes == nil {
+			k.Logger(ctx).Error("cctx not found in store", "index", string(value))
+			return nil
+		}
 		if err := k.cdc.Unmarshal(cctxBytes, &cctx); err != nil {
 			return err
 		}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c080298 and a0ad345.

📒 Files selected for processing (3)
  • x/crosschain/keeper/cctx.go (2 hunks)
  • x/crosschain/keeper/grpc_query_cctx.go (2 hunks)
  • x/crosschain/types/keys.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code, point out issues relative to ...

**/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

  • x/crosschain/types/keys.go
  • x/crosschain/keeper/cctx.go
  • x/crosschain/keeper/grpc_query_cctx.go
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: test-sim-import-export / sim
  • GitHub Check: test-sim-fullappsimulation / sim
  • GitHub Check: test-sim-nondeterminism / sim
  • GitHub Check: test-sim-after-import / sim
  • GitHub Check: lint
  • GitHub Check: build-and-test
  • GitHub Check: gosec
  • GitHub Check: build-zetanode
  • GitHub Check: build
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
x/crosschain/keeper/cctx.go (1)

120-123: LGTM! Well-implemented timestamp indexing.

The use of big-endian encoding for timestamps ensures correct lexicographical sorting, and the comment explains this clearly.

x/crosschain/keeper/grpc_query_cctx.go (1)

48-49: LGTM! Clear and efficient store initialization.

The store initialization is well-structured, with clear variable names that reflect their purpose.

Copy link
Collaborator

@brewmaster012 brewmaster012 left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Member

@lumtis lumtis left a comment

Choose a reason for hiding this comment

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

We already have the timestamp creation in the cctx data, wouldn't be cleaner to use a auto incremental ID instead? Would fix the collision issue

@gartnera
Copy link
Member Author

We already have the timestamp creation in the cctx data, wouldn't be cleaner to use a auto incremental ID instead? Would fix the collision issue

Yeah I think it would be cleaner, it would definitely make pagination easier. But it does make the migration logic a bit harder.

We could also just skip the migration and say this only applies to new data.

@gartnera gartnera marked this pull request as draft February 19, 2025 18:34
Copy link

codecov bot commented Feb 19, 2025

Codecov Report

Attention: Patch coverage is 75.00000% with 19 lines in your changes missing coverage. Please review.

Project coverage is 64.74%. Comparing base (0716d7a) to head (97f1e5d).
Report is 2 commits behind head on develop.

Files with missing lines Patch % Lines
x/crosschain/keeper/grpc_query_cctx.go 58.62% 8 Missing and 4 partials ⚠️
x/crosschain/types/cctx.go 0.00% 7 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #3548      +/-   ##
===========================================
+ Coverage    64.72%   64.74%   +0.02%     
===========================================
  Files          461      462       +1     
  Lines        31894    31960      +66     
===========================================
+ Hits         20644    20694      +50     
- Misses       10345    10358      +13     
- Partials       905      908       +3     
Files with missing lines Coverage Δ
x/crosschain/genesis.go 100.00% <100.00%> (ø)
x/crosschain/keeper/cctx.go 100.00% <100.00%> (ø)
x/crosschain/keeper/cctx_counter.go 100.00% <100.00%> (ø)
x/crosschain/types/cctx.go 48.10% <0.00%> (-1.47%) ⬇️
x/crosschain/keeper/grpc_query_cctx.go 86.00% <58.62%> (-4.77%) ⬇️

@gartnera gartnera marked this pull request as ready for review February 19, 2025 22:58
Copy link
Contributor

@kingpinXD kingpinXD left a comment

Choose a reason for hiding this comment

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

The design looks good .
I think this approach is clean and we wont need to migrate old cctxs .

Would need a migration to inititlize the counter , and the import /export of state

@gartnera gartnera force-pushed the cctx-list-createdat branch from 0b80548 to 19cd913 Compare February 20, 2025 17:44
@gartnera gartnera changed the title feat(zeatcore): ensure cctx list is sorted by created_timestamp feat(zeatcore): ensure cctx list is sorted by creation time Feb 20, 2025
@gartnera gartnera changed the title feat(zeatcore): ensure cctx list is sorted by creation time feat(zeatcore)!: ensure cctx list is sorted by creation time Feb 20, 2025
@gartnera gartnera force-pushed the cctx-list-createdat branch 2 times, most recently from 7dbf15d to 933ed00 Compare February 20, 2025 18:14
@gartnera
Copy link
Member Author

Would need a migration to inititlize the counter

Why? It will just be zero when first read? It will then immediately be incremented to 1.

@swift1337
Copy link
Contributor

Would need a migration to inititlize the counter

Why? It will just be zero when first read? It will then immediately be incremented to 1.

Shouldn't it be len(cctx) in genesis migration?

@gartnera
Copy link
Member Author

Would need a migration to inititlize the counter

Why? It will just be zero when first read? It will then immediately be incremented to 1.

Shouldn't it be len(cctx) in genesis migration?

imo no since old CCTX will not be included in this index.

@kingpinXD
Copy link
Contributor

Would need a migration to inititlize the counter

Why? It will just be zero when first read? It will then immediately be incremented to 1.

Okay

	initialCounter := keeper.GetCctxCounter(ctx)
	require.Zero(t, initialCounter)

I think this test is good enough as well to guarantee this

@gartnera gartnera force-pushed the cctx-list-createdat branch from be9cce0 to b43df25 Compare February 24, 2025 17:31
@gartnera gartnera enabled auto-merge February 24, 2025 17:32
@gartnera gartnera changed the title feat(zeatcore)!: ensure cctx list is sorted by creation time feat(zetacore)!: ensure cctx list is sorted by creation time Feb 24, 2025
@gartnera gartnera added this pull request to the merge queue Feb 24, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks Feb 24, 2025
@gartnera gartnera added the CONSENSUS_BREAKING_ACK Acknowledge a consensus breaking change label Feb 24, 2025
@gartnera gartnera added this pull request to the merge queue Feb 24, 2025
Merged via the queue into develop with commit 1a9975c Feb 24, 2025
53 checks passed
@gartnera gartnera deleted the cctx-list-createdat branch February 24, 2025 18:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
breaking:proto CONSENSUS_BREAKING_ACK Acknowledge a consensus breaking change
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants