-
Notifications
You must be signed in to change notification settings - Fork 3.7k
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
feat: Optimistic Execution (backport #16581) #18205
Merged
julienrbrt
merged 2 commits into
release/v0.50.x
from
mergify/bp/release/v0.50.x/pr-16581
Oct 23, 2023
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,157 @@ | ||
package oe | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"encoding/hex" | ||
"math/rand" | ||
"sync" | ||
"time" | ||
|
||
abci "github.com/cometbft/cometbft/abci/types" | ||
|
||
"cosmossdk.io/log" | ||
) | ||
|
||
// FinalizeBlockFunc is the function that is called by the OE to finalize the | ||
// block. It is the same as the one in the ABCI app. | ||
type FinalizeBlockFunc func(context.Context, *abci.RequestFinalizeBlock) (*abci.ResponseFinalizeBlock, error) | ||
|
||
// OptimisticExecution is a struct that contains the OE context. It is used to | ||
// run the FinalizeBlock function in a goroutine, and to abort it if needed. | ||
type OptimisticExecution struct { | ||
finalizeBlockFunc FinalizeBlockFunc // ABCI FinalizeBlock function with a context | ||
logger log.Logger | ||
|
||
mtx sync.Mutex | ||
stopCh chan struct{} | ||
request *abci.RequestFinalizeBlock | ||
response *abci.ResponseFinalizeBlock | ||
err error | ||
cancelFunc func() // cancel function for the context | ||
initialized bool // A boolean value indicating whether the struct has been initialized | ||
|
||
// debugging/testing options | ||
abortRate int // number from 0 to 100 that determines the percentage of OE that should be aborted | ||
} | ||
|
||
// NewOptimisticExecution initializes the Optimistic Execution context but does not start it. | ||
func NewOptimisticExecution(logger log.Logger, fn FinalizeBlockFunc, opts ...func(*OptimisticExecution)) *OptimisticExecution { | ||
logger = logger.With(log.ModuleKey, "oe") | ||
oe := &OptimisticExecution{logger: logger, finalizeBlockFunc: fn} | ||
for _, opt := range opts { | ||
opt(oe) | ||
} | ||
return oe | ||
} | ||
|
||
// WithAbortRate sets the abort rate for the OE. The abort rate is a number from | ||
// 0 to 100 that determines the percentage of OE that should be aborted. | ||
// This is for testing purposes only and must not be used in production. | ||
func WithAbortRate(rate int) func(*OptimisticExecution) { | ||
return func(oe *OptimisticExecution) { | ||
oe.abortRate = rate | ||
} | ||
} | ||
|
||
// Reset resets the OE context. Must be called whenever we want to invalidate | ||
// the current OE. | ||
func (oe *OptimisticExecution) Reset() { | ||
oe.mtx.Lock() | ||
defer oe.mtx.Unlock() | ||
oe.request = nil | ||
oe.response = nil | ||
oe.err = nil | ||
oe.initialized = false | ||
} | ||
|
||
func (oe *OptimisticExecution) Enabled() bool { | ||
return oe != nil | ||
} | ||
|
||
// Initialized returns true if the OE was initialized, meaning that it contains | ||
// a request and it was run or it is running. | ||
func (oe *OptimisticExecution) Initialized() bool { | ||
if oe == nil { | ||
return false | ||
} | ||
oe.mtx.Lock() | ||
defer oe.mtx.Unlock() | ||
|
||
return oe.initialized | ||
} | ||
|
||
// Execute initializes the OE and starts it in a goroutine. | ||
func (oe *OptimisticExecution) Execute(req *abci.RequestProcessProposal) { | ||
oe.mtx.Lock() | ||
defer oe.mtx.Unlock() | ||
|
||
oe.stopCh = make(chan struct{}) | ||
oe.request = &abci.RequestFinalizeBlock{ | ||
Txs: req.Txs, | ||
DecidedLastCommit: req.ProposedLastCommit, | ||
Misbehavior: req.Misbehavior, | ||
Hash: req.Hash, | ||
Height: req.Height, | ||
Time: req.Time, | ||
NextValidatorsHash: req.NextValidatorsHash, | ||
ProposerAddress: req.ProposerAddress, | ||
} | ||
|
||
oe.logger.Debug("OE started", "height", req.Height, "hash", hex.EncodeToString(req.Hash), "time", req.Time.String()) | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
oe.cancelFunc = cancel | ||
oe.initialized = true | ||
|
||
go func() { | ||
start := time.Now() | ||
|
||
resp, err := oe.finalizeBlockFunc(ctx, oe.request) | ||
oe.mtx.Lock() | ||
executionTime := time.Since(start) | ||
oe.logger.Debug("OE finished", "duration", executionTime.String(), "height", req.Height, "hash", hex.EncodeToString(req.Hash)) | ||
oe.response, oe.err = resp, err | ||
close(oe.stopCh) | ||
oe.mtx.Unlock() | ||
}() | ||
Comment on lines
+106
to
+115
Check notice Code scanning / CodeQL Spawning a Go routine Note
Spawning a Go routine may be a possible source of non-determinism
|
||
} | ||
|
||
// AbortIfNeeded aborts the OE if the request hash is not the same as the one in | ||
// the running OE. Returns true if the OE was aborted. | ||
func (oe *OptimisticExecution) AbortIfNeeded(reqHash []byte) bool { | ||
if oe == nil { | ||
return false | ||
} | ||
|
||
oe.mtx.Lock() | ||
defer oe.mtx.Unlock() | ||
|
||
if !bytes.Equal(oe.request.Hash, reqHash) { | ||
oe.logger.Error("OE aborted due to hash mismatch", "oe_hash", hex.EncodeToString(oe.request.Hash), "req_hash", hex.EncodeToString(reqHash), "oe_height", oe.request.Height, "req_height", oe.request.Height) | ||
oe.cancelFunc() | ||
return true | ||
} else if oe.abortRate > 0 && rand.Intn(100) < oe.abortRate { | ||
// this is for test purposes only, we can emulate a certain percentage of | ||
// OE needed to be aborted. | ||
oe.cancelFunc() | ||
oe.logger.Error("OE aborted due to test abort rate") | ||
return true | ||
} | ||
|
||
return false | ||
} | ||
|
||
// Abort aborts the OE unconditionally and waits for it to finish. | ||
func (oe *OptimisticExecution) Abort() { | ||
if oe == nil || oe.cancelFunc == nil { | ||
return | ||
} | ||
|
||
oe.cancelFunc() | ||
<-oe.stopCh | ||
} | ||
|
||
// WaitResult waits for the OE to finish and returns the result. | ||
func (oe *OptimisticExecution) WaitResult() (*abci.ResponseFinalizeBlock, error) { | ||
<-oe.stopCh | ||
return oe.response, oe.err | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Change potentially affects state.
Call sequence: