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

Optimise merge registers for migrations #5522

Merged
merged 5 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Optimise merge registers for migrations
  • Loading branch information
janezpodhostnik committed Mar 25, 2024
commit 6273bbd51330ea19dd09ecd29b8d9b7a145a1872
8 changes: 4 additions & 4 deletions cmd/util/ledger/migrations/atree_register_migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func (m *AtreeRegisterMigrator) MigrateAccount(
m.rw.Write(migrationProblem{
Address: address.Hex(),
Key: "",
Size: len(mr.Snapshot.Payloads),
Size: mr.Snapshot.Len(),
Kind: "more_registers_after_migration",
Msg: fmt.Sprintf("original: %d, new: %d", originalLen, newLen),
})
Expand Down Expand Up @@ -227,7 +227,7 @@ func (m *AtreeRegisterMigrator) convertStorageDomain(

m.rw.Write(migrationProblem{
Address: mr.Address.Hex(),
Size: len(mr.Snapshot.Payloads),
Size: mr.Snapshot.Len(),
Key: string(key),
Kind: "migration_failure",
Msg: err.Error(),
Expand All @@ -245,7 +245,7 @@ func (m *AtreeRegisterMigrator) validateChangesAndCreateNewRegisters(
storageMapIds map[string]struct{},
) ([]*ledger.Payload, error) {
originalPayloadsSnapshot := mr.Snapshot
originalPayloads := originalPayloadsSnapshot.Payloads
originalPayloads := originalPayloadsSnapshot.PayloadMap()
fxamacker marked this conversation as resolved.
Show resolved Hide resolved
newPayloads := make([]*ledger.Payload, 0, len(originalPayloads))

// store state payload so that it can be updated
Expand Down Expand Up @@ -331,7 +331,7 @@ func (m *AtreeRegisterMigrator) validateChangesAndCreateNewRegisters(
m.rw.Write(migrationProblem{
Address: mr.Address.Hex(),
Key: id.String(),
Size: len(mr.Snapshot.Payloads),
Size: mr.Snapshot.Len(),
Kind: "not_migrated",
Msg: fmt.Sprintf("%x", value.Value()),
})
Expand Down
4 changes: 1 addition & 3 deletions cmd/util/ledger/migrations/cadence_values_migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,9 @@ func (m *CadenceBaseMigrator) MigrateAccount(
flow.Address(address): {},
}

newPayloads, err := MergeRegisterChanges(
migrationRuntime.Snapshot.Payloads,
newPayloads, err := migrationRuntime.Snapshot.ApplyChangesAndGetNewPayloads(
result.WriteSet,
expectedAddresses,
expectedAddresses,
m.log,
)
if err != nil {
Expand Down
72 changes: 0 additions & 72 deletions cmd/util/ledger/migrations/merge.go

This file was deleted.

133 changes: 133 additions & 0 deletions cmd/util/ledger/util/payload_shnapshot_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package util_test

import (
"math/rand"
"strconv"
"testing"

"github.com/rs/zerolog"
"github.com/stretchr/testify/require"

"github.com/onflow/flow-go/cmd/util/ledger/util"
"github.com/onflow/flow-go/ledger"
"github.com/onflow/flow-go/ledger/common/convert"
"github.com/onflow/flow-go/model/flow"
)

func Benchmark_Merge(b *testing.B) {

merge := func(b *testing.B, payloadsNum, changesNum int) {
b.Run("merge_"+strconv.Itoa(payloadsNum)+"_"+strconv.Itoa(changesNum), func(b *testing.B) {
benchmarkMerge(b, payloadsNum, changesNum)
})
}

create := func(b *testing.B, payloadsNum int) {
b.Run("create_"+strconv.Itoa(payloadsNum), func(b *testing.B) {
benchmarkCreate(b, payloadsNum)
})
}

create(b, 1000)
create(b, 100000)
create(b, 10000000)
fxamacker marked this conversation as resolved.
Show resolved Hide resolved

merge(b, 1000, 10)
merge(b, 1000, 100)
merge(b, 1000, 1000)

merge(b, 100000, 10)
merge(b, 100000, 1000)
merge(b, 100000, 100000)

merge(b, 10000000, 10)
merge(b, 10000000, 10000)
merge(b, 10000000, 10000000)
janezpodhostnik marked this conversation as resolved.
Show resolved Hide resolved
}

func randomPayload(size int) []byte {
payload := make([]byte, size)
_, _ = rand.Read(payload)
return payload
}

func createPayloads(payloadsNum int) []*ledger.Payload {
// 1kb payloads

payloads := make([]*ledger.Payload, payloadsNum)
for i := 0; i < payloadsNum; i++ {
payloads[i] = ledger.NewPayload(
convert.RegisterIDToLedgerKey(flow.RegisterID{
Owner: flow.EmptyAddress.String(),
Key: strconv.Itoa(i),
}),
randomPayload(1024),
)
}
return payloads
}

func benchmarkMerge(b *testing.B, payloadsNum, changesNum int) {

creatChanges := func(lastIndex, changed, deleted, new int) map[flow.RegisterID]flow.RegisterValue {
janezpodhostnik marked this conversation as resolved.
Show resolved Hide resolved
// half of the changes should be new payloads
changes := make(map[flow.RegisterID]flow.RegisterValue)
for i := 0; i < changed; i++ {

// get random index
index := rand.Intn(lastIndex)

changes[flow.RegisterID{
Owner: flow.EmptyAddress.String(),
Key: strconv.Itoa(index),
}] = randomPayload(1024)
}

for i := 0; i < deleted; i++ {

// get random index
index := rand.Intn(lastIndex)

changes[flow.RegisterID{
Owner: flow.EmptyAddress.String(),
Key: strconv.Itoa(index),
}] = []byte{}
}

for i := 0; i < new; i++ {
changes[flow.RegisterID{
Owner: flow.EmptyAddress.String(),
Key: strconv.Itoa(i + lastIndex),
}] = []byte{}
fxamacker marked this conversation as resolved.
Show resolved Hide resolved
}

return changes
}

payloads := createPayloads(payloadsNum)

for i := 0; i < b.N; i++ {
b.StopTimer()

change, remove, add := changesNum/3, changesNum/3, changesNum/3

// half of the changes should be new payloads
janezpodhostnik marked this conversation as resolved.
Show resolved Hide resolved
changes := creatChanges(len(payloads), change, remove, add)

snapshot, err := util.NewPayloadSnapshot(payloads)
require.NoError(b, err)

b.StartTimer()

_, err = snapshot.ApplyChangesAndGetNewPayloads(changes, nil, zerolog.Nop())
require.NoError(b, err)
}
}

func benchmarkCreate(b *testing.B, payloadsNum int) {
payloads := createPayloads(payloadsNum)
for i := 0; i < b.N; i++ {
_, err := util.NewPayloadSnapshot(payloads)
require.NoError(b, err)
}
}
130 changes: 130 additions & 0 deletions cmd/util/ledger/util/payload_snapshot.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package util

import (
"sort"

"github.com/rs/zerolog"

"github.com/onflow/flow-go/fvm/storage/snapshot"
"github.com/onflow/flow-go/ledger"
"github.com/onflow/flow-go/ledger/common/convert"
"github.com/onflow/flow-go/model/flow"
)

type PayloadSnapshot struct {
reverseMap map[flow.RegisterID]int
payloads []*ledger.Payload
}

var _ snapshot.StorageSnapshot = (*PayloadSnapshot)(nil)

func NewPayloadSnapshot(payloads []*ledger.Payload) (*PayloadSnapshot, error) {
payloadsCopy := make([]*ledger.Payload, len(payloads))
copy(payloadsCopy, payloads)
l := &PayloadSnapshot{
reverseMap: make(map[flow.RegisterID]int, len(payloads)),
payloads: payloadsCopy,
}
for i, payload := range payloadsCopy {
key, err := payload.Key()
if err != nil {
return nil, err
}
id, err := convert.LedgerKeyToRegisterID(key)
if err != nil {
return nil, err
}
l.reverseMap[id] = i
}
return l, nil
}

func (p PayloadSnapshot) Get(id flow.RegisterID) (flow.RegisterValue, error) {
index, exists := p.reverseMap[id]
if !exists {
return nil, nil
}
return p.payloads[index].Value(), nil
}

func (p PayloadSnapshot) Exists(id flow.RegisterID) bool {
_, exists := p.reverseMap[id]
return exists
}

func (p PayloadSnapshot) Len() int {
return len(p.payloads)
}

func (p PayloadSnapshot) PayloadMap() map[flow.RegisterID]*ledger.Payload {
result := make(map[flow.RegisterID]*ledger.Payload, len(p.payloads))
for id, index := range p.reverseMap {
result[id] = p.payloads[index]
}
return result
}

// ApplyChangesAndGetNewPayloads applies the given changes to the snapshot and returns the new payloads.
// the snapshot is destroyed.
func (p PayloadSnapshot) ApplyChangesAndGetNewPayloads(
changes map[flow.RegisterID]flow.RegisterValue,
expectedChangeAddresses map[flow.Address]struct{},
logger zerolog.Logger,
) ([]*ledger.Payload, error) {

// append all new payloads at once at the end
newPayloads := make([]*ledger.Payload, 0, len(changes))
deletedPayloads := make([]int, 0, len(changes))

for id, value := range changes {
if expectedChangeAddresses != nil {
ownerAddress := flow.BytesToAddress([]byte(id.Owner))

if _, ok := expectedChangeAddresses[ownerAddress]; !ok {
// something was changed that does not belong to this account. Log it.
logger.Error().
Str("key", id.String()).
Str("actual_address", ownerAddress.Hex()).
Interface("expected_addresses", expectedChangeAddresses).
Hex("value", value).
Msg("key is part of the change set, but is for a different account")
}
}

existingItemIndex, exists := p.reverseMap[id]
if !exists {
if len(value) == 0 {
// do not add new empty values
continue
}
newPayloads = append(newPayloads, ledger.NewPayload(convert.RegisterIDToLedgerKey(id), value))
} else {
if len(value) == 0 {
// do not add new empty values
deletedPayloads = append(deletedPayloads, existingItemIndex)
continue
}

// update existing payload
p.payloads[existingItemIndex] = ledger.NewPayload(convert.RegisterIDToLedgerKey(id), value)
}
}

// remove deleted payloads by moving the last ones to the deleted positions
// and then re-slicing the array
sort.Ints(deletedPayloads)
for i := len(deletedPayloads) - 1; i >= 0; i-- {
index := deletedPayloads[i]
// take items from the very end of the array
p.payloads[index] = p.payloads[len(p.payloads)-1-(len(deletedPayloads)-1-i)]
}
p.payloads = p.payloads[:len(p.payloads)-len(deletedPayloads)]

result := append(p.payloads, newPayloads...)

// destroy the snapshot to prevent further use
p.payloads = nil
p.reverseMap = nil

return result, nil
}
Loading