Skip to content
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

fix infinite loop during open-ended range query -- CouchDB #1347

Merged
merged 1 commit into from
May 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions core/ledger/kvledger/txmgmt/statedb/statecouchdb/statecouchdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -520,8 +520,14 @@ func (scanner *queryScanner) getNextStateRangeScanResults() error {
return err
}
scanner.resultsInfo.results = queryResult
scanner.queryDefinition.startKey = nextStartKey
scanner.paginationInfo.cursor = 0
if scanner.queryDefinition.endKey == nextStartKey {
Copy link
Contributor

Choose a reason for hiding this comment

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

I would prefer to make this check more explicit by having this either of the following

  1. nextStartKey == ""
  2. if nextStartKey >= endKey || nextStartKey == ""

In the current form, this check appears to be a special case of the (2) above and may cause confusion that why equal check only and why not greater than (imagine someone looking at this code and having a generic key (not an "") as the end key in mind.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The nextStartKey would never be greater than the endKey. The current condition is very generic. When the scanner is exhausted, nextStartKey == endKey would always become true and any condition that we have after this condition would become a deadcode.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

As mentioned in the PR description, the current condition check avoids an additional REST API call once the scanner is exhaused. Let's assume startKey = "marble1" and endKey = "marble5". It is possible that the startKey and endKey would become the same, i.e., marble5. Once it has become the same, there is no need to run an additional REST API call. The current condition takes care of all scenarios.

Copy link
Contributor

@manish-sethi manish-sethi May 29, 2020

Choose a reason for hiding this comment

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

Ah, yes. just looked at the code and found this logic of explicitly returning the end key as next start, deep buried :-) Thanks for the explanation. I feel that the logic of limits and pagination is much spread across functions and needs a refactoring.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks, Manish, for merging this. I agree. It is much spread and complex to read.

// as we always set inclusive_end=false to match the behavior of
// goleveldb iterator, it is safe to mark the scanner as exhausted
scanner.exhausted = true
// we still need to update the startKey as it is returned as bookmark
}
scanner.queryDefinition.startKey = nextStartKey
return nil
}

Expand Down Expand Up @@ -877,6 +883,7 @@ type queryScanner struct {
queryDefinition *queryDefinition
paginationInfo *paginationInfo
resultsInfo *resultsInfo
exhausted bool
}

type queryDefinition struct {
Expand All @@ -899,7 +906,7 @@ type resultsInfo struct {

func newQueryScanner(namespace string, db *couchDatabase, query string, internalQueryLimit,
limit int32, bookmark, startKey, endKey string) (*queryScanner, error) {
scanner := &queryScanner{namespace, db, &queryDefinition{startKey, endKey, query, internalQueryLimit}, &paginationInfo{-1, limit, bookmark}, &resultsInfo{0, nil}}
scanner := &queryScanner{namespace, db, &queryDefinition{startKey, endKey, query, internalQueryLimit}, &paginationInfo{-1, limit, bookmark}, &resultsInfo{0, nil}, false}
var err error
// query is defined, then execute the query and return the records and bookmark
if scanner.queryDefinition.query != "" {
Expand All @@ -924,6 +931,9 @@ func (scanner *queryScanner) Next() (statedb.QueryResult, error) {
// check to see if additional records are needed
// requery if the cursor exceeds the internalQueryLimit
if scanner.paginationInfo.cursor >= scanner.queryDefinition.internalQueryLimit {
if scanner.exhausted {
return nil, nil
}
var err error
// query is defined, then execute the query and return the records and bookmark
if scanner.queryDefinition.query != "" {
Expand Down
142 changes: 142 additions & 0 deletions core/ledger/kvledger/txmgmt/statedb/statecouchdb/statecouchdb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"strings"
"testing"
"time"
"unicode/utf8"

"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/common/ledger/dataformat"
Expand Down Expand Up @@ -1477,3 +1478,144 @@ func TestChannelMetadata_NegativeTests(t *testing.T) {
require.Equal(t, expectedChannelMetadata, savedChannelMetadata)
require.Equal(t, expectedChannelMetadata, vdb.channelMetadata)
}

func TestRangeQueryWithInternalLimitAndPageSize(t *testing.T) {
// generateSampleData returns a slice of KVs. The returned value contains 12 KVs for a namespace ns1
generateSampleData := func() []*statedb.VersionedKV {
sampleData := []*statedb.VersionedKV{}
ver := version.NewHeight(1, 1)
sampleKV := &statedb.VersionedKV{
CompositeKey: statedb.CompositeKey{Namespace: "ns1", Key: string('\u0000')},
VersionedValue: statedb.VersionedValue{Value: []byte("v0"), Version: ver, Metadata: []byte("m0")},
}
sampleData = append(sampleData, sampleKV)
for i := 0; i < 10; i++ {
sampleKV = &statedb.VersionedKV{
CompositeKey: statedb.CompositeKey{
Namespace: "ns1",
Key: fmt.Sprintf("key-%d", i),
},
VersionedValue: statedb.VersionedValue{
Value: []byte(fmt.Sprintf("value-for-key-%d-for-ns1", i)),
Version: ver,
Metadata: []byte(fmt.Sprintf("metadata-for-key-%d-for-ns1", i)),
},
}
sampleData = append(sampleData, sampleKV)
}
sampleKV = &statedb.VersionedKV{
CompositeKey: statedb.CompositeKey{Namespace: "ns1", Key: string(utf8.MaxRune)},
VersionedValue: statedb.VersionedValue{Value: []byte("v1"), Version: ver, Metadata: []byte("m1")},
}
sampleData = append(sampleData, sampleKV)
return sampleData
}

vdbEnv.init(t, nil)
defer vdbEnv.cleanup()
channelName := "ch1"
vdb, err := vdbEnv.DBProvider.GetDBHandle(channelName)
require.NoError(t, err)
db := vdb.(*VersionedDB)

sampleData := generateSampleData()
batch := statedb.NewUpdateBatch()
for _, d := range sampleData {
batch.PutValAndMetadata(d.Namespace, d.Key, d.Value, d.Metadata, d.Version)
}
db.ApplyUpdates(batch, version.NewHeight(1, 1))

defaultLimit := vdbEnv.config.InternalQueryLimit

// Scenario 1: We try to fetch either 11 records or all 12 records. We pass various internalQueryLimits.
// key utf8.MaxRune would not be included as inclusive_end is always set to false
testRangeQueryWithInternalLimit(t, "ns1", db, 2, string('\u0000'), string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithInternalLimit(t, "ns1", db, 5, string('\u0000'), string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithInternalLimit(t, "ns1", db, 2, string('\u0000'), "", sampleData)
testRangeQueryWithInternalLimit(t, "ns1", db, 5, string('\u0000'), "", sampleData)
testRangeQueryWithInternalLimit(t, "ns1", db, 2, "", string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithInternalLimit(t, "ns1", db, 5, "", string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithInternalLimit(t, "ns1", db, 2, "", "", sampleData)
testRangeQueryWithInternalLimit(t, "ns1", db, 5, "", "", sampleData)

// Scenario 2: We try to fetch either 11 records or all 12 records using pagination. We pass various page sizes while
// keeping the internalQueryLimit as the default one, i.e., 1000.
vdbEnv.config.InternalQueryLimit = defaultLimit
testRangeQueryWithPageSize(t, "ns1", db, 2, string('\u0000'), string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithPageSize(t, "ns1", db, 15, string('\u0000'), string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithPageSize(t, "ns1", db, 2, string('\u0000'), "", sampleData)
testRangeQueryWithPageSize(t, "ns1", db, 15, string('\u0000'), "", sampleData)
testRangeQueryWithPageSize(t, "ns1", db, 2, "", string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithPageSize(t, "ns1", db, 15, "", string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithPageSize(t, "ns1", db, 2, "", "", sampleData)
testRangeQueryWithPageSize(t, "ns1", db, 15, "", "", sampleData)

// Scenario 3: We try to fetch either 11 records or all 12 records using pagination. We pass various page sizes while
// keeping the internalQueryLimit to 1.
vdbEnv.config.InternalQueryLimit = 1
testRangeQueryWithPageSize(t, "ns1", db, 2, string('\u0000'), string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithPageSize(t, "ns1", db, 15, string('\u0000'), string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithPageSize(t, "ns1", db, 2, string('\u0000'), "", sampleData)
testRangeQueryWithPageSize(t, "ns1", db, 15, string('\u0000'), "", sampleData)
testRangeQueryWithPageSize(t, "ns1", db, 2, "", string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithPageSize(t, "ns1", db, 15, "", string(utf8.MaxRune), sampleData[:len(sampleData)-1])
testRangeQueryWithPageSize(t, "ns1", db, 2, "", "", sampleData)
testRangeQueryWithPageSize(t, "ns1", db, 15, "", "", sampleData)
}

func testRangeQueryWithInternalLimit(
t *testing.T,
ns string,
db *VersionedDB,
limit int,
startKey, endKey string,
expectedResults []*statedb.VersionedKV,
) {
vdbEnv.config.InternalQueryLimit = limit
require.Equal(t, int32(limit), db.couchInstance.internalQueryLimit())
itr, err := db.GetStateRangeScanIterator(ns, startKey, endKey)
require.NoError(t, err)
require.Equal(t, int32(limit), itr.(*queryScanner).queryDefinition.internalQueryLimit)
results := []*statedb.VersionedKV{}
for {
result, err := itr.Next()
require.NoError(t, err)
if result == nil {
itr.Close()
break
}
kv := result.(*statedb.VersionedKV)
results = append(results, kv)
}
require.Equal(t, expectedResults, results)
}

func testRangeQueryWithPageSize(
t *testing.T,
ns string,
db *VersionedDB,
pageSize int,
startKey, endKey string,
expectedResults []*statedb.VersionedKV,
) {
itr, err := db.GetStateRangeScanIteratorWithPagination(ns, startKey, endKey, int32(pageSize))
require.NoError(t, err)
results := []*statedb.VersionedKV{}
for {
result, err := itr.Next()
require.NoError(t, err)
if result != nil {
kv := result.(*statedb.VersionedKV)
results = append(results, kv)
continue
}
nextStartKey := itr.GetBookmarkAndClose()
if nextStartKey == endKey {
break
}
itr, err = db.GetStateRangeScanIteratorWithPagination(ns, nextStartKey, endKey, int32(pageSize))
require.NoError(t, err)
continue
}
require.Equal(t, expectedResults, results)
}