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

feat(store/v2): Removing old store keys by pruning #20927

Merged
merged 10 commits into from
Jul 24, 2024

Conversation

cool-develope
Copy link
Contributor

@cool-develope cool-develope commented Jul 10, 2024

Description

ref: #19784 #20453

In the original PR, we removed old store keys instantly when upgrading store keys. It will break the GetProof for the history on IBC.
The new design removes old store keys by pruning rather than instant deleting.


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

@cool-develope cool-develope requested a review from a team as a code owner July 10, 2024 00:19
Copy link
Contributor

coderabbitai bot commented Jul 10, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Base branches to auto review (1)
  • main

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.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

@cool-develope your pull request is missing a changelog!

@cool-develope cool-develope changed the title feat (store/v2): removing old store keys by pruning feat (store/v2): Removing old store keys by pruning Jul 10, 2024
@cool-develope cool-develope changed the title feat (store/v2): Removing old store keys by pruning feat(store/v2): Removing old store keys by pruning Jul 10, 2024
Copy link
Contributor

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

Up, this are a lot of changes. I skipped the tests in this iteration, sorry.

@@ -107,6 +108,7 @@ func (t *IavlTree) SetInitialVersion(version uint64) error {

// Prune prunes all versions up to and including the provided version.
func (t *IavlTree) Prune(version uint64) error {
// latestVersion := t.tree.Version()
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: dead code, please remove

store/v2/commitment/mem/tree.go Show resolved Hide resolved
}
}()

end := []byte(fmt.Sprintf("%s%020d/", removedStoreKeyPrefix, version+1))
Copy link
Contributor

Choose a reason for hiding this comment

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

personal preference: "%s%020d/", is used in multiple places. Would it make sense to introduce a helper method like buildRemovedStoreKeysPrefix(key, version)[]byte

Copy link
Contributor

Choose a reason for hiding this comment

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

The version element is encoded into a 20 byte representation. Why not use big endian encoding instead so that you have only 8 bytes?

}()

for ; iter.Valid(); iter.Next() {
storeKey := string(iter.Key()[len(end):])
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: move len(end) before the loop

}
}()

for ; iter.Valid(); iter.Next() {
Copy link
Contributor

Choose a reason for hiding this comment

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

🤔 surprised to see this. Is it more efficient to iterate over the DB than to use the storeKeys and version parameter?


var storeKeys []string
for storeKeyIter.First(); storeKeyIter.Valid(); storeKeyIter.Next() {
storeKey := string(storeKeyIter.Key()[len(end):])
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: move len() before the loop

store/v2/storage/pebbledb/db.go Show resolved Hide resolved
);
`

if _, err = tx.Exec(pruneRemovedStoreKeysStmt, reservedStoreKey, keyRemovedStore, version); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

keyRemovedStore is not set in PruneStoreKeys

`

for _, key := range storeKeys {
_, err = tx.Exec(flushRemovedStoreKeysStmt, reservedStoreKey, key, version)
Copy link
Contributor

Choose a reason for hiding this comment

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

you are passing only 3 parameters to the statement


// prune removed store keys
pruneRemovedStoreKeysStmt := `DELETE FROM state_storage
WHERE store_key in (
Copy link
Contributor

Choose a reason for hiding this comment

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

not fully sure if I understood the DB schema but I think that you also have to define the version to not delete all for a storage key

Copy link
Contributor Author

Choose a reason for hiding this comment

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

good catch, I've fixed and added the testcases to ensure that.

@cool-develope cool-develope requested a review from alpe July 15, 2024 20:03
@kocubinski
Copy link
Member

In the original PR, we removed old store keys instantly when upgrading store keys. It will break the GetProof for the history on IBC.

store/v1 shares this behavior right? i.e.

for sk := range rs.removalMap {
if _, ok := rs.stores[sk]; ok {
delete(rs.stores, sk)
delete(rs.storesParams, sk)
delete(rs.keysByName, sk.Name())
}
}
// reset the removalMap
rs.removalMap = make(map[types.StoreKey]bool)

Ostensibly light clients (like used in IBC) have been accounting for this across store key removals, but it does seem like a long standing bug, is there an issue for it?

@cool-develope
Copy link
Contributor Author

In the original PR, we removed old store keys instantly when upgrading store keys. It will break the GetProof for the history on IBC.

store/v1 shares this behavior right? i.e.

for sk := range rs.removalMap {
if _, ok := rs.stores[sk]; ok {
delete(rs.stores, sk)
delete(rs.storesParams, sk)
delete(rs.keysByName, sk.Name())
}
}
// reset the removalMap
rs.removalMap = make(map[types.StoreKey]bool)

Ostensibly light clients (like used in IBC) have been accounting for this across store key removals, but it does seem like a long standing bug, is there an issue for it?

yes exactly, but not able to find the related issue, maybe removing storekey is not used or at least not frequently

}()

for _, storeKey := range storeKeys {
key := []byte(fmt.Sprintf("%s%s", buildRemovedStoreKeyPrefix(version), storeKey))
Copy link
Contributor

Choose a reason for hiding this comment

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

here and others: let's move away from strings:

Suggested change
key := []byte(fmt.Sprintf("%s%s", buildRemovedStoreKeyPrefix(version), storeKey))
key := append(buildRemovedStoreKeyPrefix(version), storeKey...)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

you mentioned, fmt.Sprintf is more safe in terms of array expanding 🤔

func buildRemovedStoreKeyPrefix(version uint64) []byte {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, version)
return []byte(fmt.Sprintf("%s%x/", removedStoreKeyPrefix, buf))
Copy link
Contributor

Choose a reason for hiding this comment

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

The %x would encode it into hex representation which is 4 chars per byte. Why not work with bytes only, like:

const separator byte = '/'
func buildRemovedStoreKeyPrefix(version uint64) []byte {
	n := len(removedStoreKeyPrefix)
	buf := make([]byte, n+8+1)
	copy(buf[0:], removedStoreKeyPrefix)
	binary.BigEndian.PutUint64(buf[n:], version)
	buf[n+8]=separator
	return buf
}

(untested)

@@ -109,8 +116,7 @@ func (c *CommitStore) LoadVersionAndUpgrade(targetVersion uint64, upgrades *core
for storeKey := range c.multiTrees {
storeKeys = append(storeKeys, storeKey)
}
// deterministic iteration order for upgrades
// (as the underlying store may change and
// deterministic iteration order for upgrades (as the underlying store may change and
Copy link
Contributor

Choose a reason for hiding this comment

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

It was not stdlib but x/exp for maps. My mistake. 🙈
Feel free to revert to avoid the dependency if you prefer.

@@ -203,36 +195,30 @@ func (db *Database) Prune(version uint64) error {
t2.version <= ?
) AND store_key != ?;
`

if _, err = tx.Exec(pruneStmt, version, reservedStoreKey); err != nil {
if err := db.executeTx(pruneStmt, version, reservedStoreKey); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

With executeTx you split the DB transaction into multiple smaller ones. Unless there is a technical reason, it should be avoided. DB transactions should cover the whole (business) process instead to have atomic behaviour.

VALUES(?, ?, ?, ?);
`
flushRemovedStoreKeysStmt := fmt.Sprintf(`INSERT INTO state_storage(store_key, key, value, version)
VALUES %s`, strings.Repeat("(?, ?, ?, ?),", len(storeKeys)))
Copy link
Contributor

Choose a reason for hiding this comment

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

🤔 I have never seen an insert with repeated placeholders. What are the benefits? With dynamic values possible, the DB can not optimize internally for the prepared statement AFAIK.
You also need to check for empty storeKeys slice or the statement would be incorrect.

The old version looks more common and trustworthy ;-)

WHERE store_key in (
SELECT value FROM state_storage
WHERE store_key = ? AND key = ? AND version <= ?
WHERE store_key IN (
Copy link
Contributor

Choose a reason for hiding this comment

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

Would it make sense to limit the delete to version <= ? ?
I think about odd edge cases where store foo is renamed to bar and back?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

so we are checking version <= ? in SELECT, do you think it is not fully covered?

Copy link
Contributor

Choose a reason for hiding this comment

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

The when the delete does not contain a version condition as well, it will delete everything with a matching store key.
For example

height 10: add store foo + some data
height 20: delete store foo
height 30: add store foo + some data

When prune is is run on height 31, it would find the store marked for delete (at height 20) and deletes everything although it is in use again.

This opens another question, if the store is not pruned, would it contain dirty data?

@kocubinski
Copy link
Member

yes exactly, but not able to find the related issue, maybe removing storekey is not used or at least not frequently

Given the adoption of IBC and light clients generally, I'd say this is not a problem, perhaps just expected behavior. This PR adds a lot of complicated code to metadata store and the pruning process, which is already quite complex.

What led you to address removed store keys at this level, were there user complaints?

@cool-develope
Copy link
Contributor Author

cool-develope commented Jul 17, 2024

What led you to address removed store keys at this level, were there user complaints?

I agree it introduces the extra complexity, one violated case is the archive node if remove old keys instantly.
There may be another solutions, still I like the metadata storing approach, it makes clear to track the storage changes.

return batch.WriteSync()
}

func (m *MetadataStore) deleteRemovedStoreKeys(version uint64, fn func(storeKey []byte) error) (err error) {
Copy link
Member

Choose a reason for hiding this comment

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

nit: is fn a filter function? if so can it have a more descriptive name? kind of hard to read

)

type MountTreeFn func(storeKey string) (Tree, error)
Copy link
Member

Choose a reason for hiding this comment

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

needs a godoc if to be included

Copy link
Member

Choose a reason for hiding this comment

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

is there an example usage of this in tests? trying to wrap my head around how it will work in GetProof. would multiple different SC still be supported? the current has a homogenous mounTreeFn for heterogeneous map[string]Tree

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes, it is tested in store_test_suite.go

Copy link
Member

@kocubinski kocubinski left a comment

Choose a reason for hiding this comment

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

we've decided to no longer support store key renaming, so it shouldn't be merged

Copy link
Member

@kocubinski kocubinski left a comment

Choose a reason for hiding this comment

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

rename deprecation will be handled in #20453

realStoreKeys := []string{"renamedStore1", storeKey2, "newStore1", "newStore2"}
commitStore, err = s.NewStore(commitDB, newStoreKeys, log.NewNopLogger())
s.Require().NoError(err)
err = commitStore.LoadVersionAndUpgrade(latestVersion, upgrades)
s.Require().NoError(err)

// verify removed stores
// GetProof should work for the old stores
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@kocubinski MountFn is being tested here

Copy link
Contributor

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

Good progress. 💪


for _, tc := range testcases {
got := BuildPrefixWithVersion(tc.prefix, tc.version)
if len(got) != len(tc.want) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Good test cases.
You can simplify the assert with:

		if !bytes.Equal(tc.want, got) {
			t.Fatalf("expected %X, got %X", tc.want, got)
		}

store/v2/internal/encoding/prefix.go Show resolved Hide resolved
WHERE store_key in (
SELECT value FROM state_storage
WHERE store_key = ? AND key = ? AND version <= ?
WHERE store_key IN (
Copy link
Contributor

Choose a reason for hiding this comment

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

The when the delete does not contain a version condition as well, it will delete everything with a matching store key.
For example

height 10: add store foo + some data
height 20: delete store foo
height 30: add store foo + some data

When prune is is run on height 31, it would find the store marked for delete (at height 20) and deletes everything although it is in use again.

This opens another question, if the store is not pruned, would it contain dirty data?

@@ -329,6 +327,25 @@ func (db *Database) PrintRowsDebug() {
fmt.Println(strings.TrimSpace(sb.String()))
}

func (db *Database) executeTx(stmt string, args ...interface{}) (err error) {
Copy link
Contributor

Choose a reason for hiding this comment

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

personal preference: It is called by one place only. You can inline the method or add some docs please that it is used for a single operation TX only. should be avoided for atomic behaviour on multiple statements

Copy link
Contributor

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

I did some manual testing 👍

if err := batch.Delete(storeKeyIter.Key(), nil); err != nil {
return err
}
}

for _, key := range storeKeys {
for _, s := range storeKeys {
Copy link
Contributor

Choose a reason for hiding this comment

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

would it make sense to search for max version per storeKey?

itr, err := db.storage.NewIter(&pebble.IterOptions{LowerBound: storePrefix(storeKey), UpperBound: storePrefix(util.CopyIncr(storeKey))})
if err != nil {
return err
}
defer itr.Close()

for itr.First(); itr.Valid(); itr.Next() {
itrKey := itr.Key()
_, verBz, _ := SplitMVCCKey(itrKey)
Copy link
Contributor

Choose a reason for hiding this comment

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

Why skipping the sanity check on ok result?

if err != nil {
return err
}
if keyVersion > s.version {
Copy link
Contributor

Choose a reason for hiding this comment

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

👍

WHERE store_key = ? AND value = ? AND version <= ?
GROUP BY key
) AS t
WHERE s.store_key = t.key AND s.version <= t.max_version
Copy link
Contributor

Choose a reason for hiding this comment

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

I have tested this locally. The EXISTS operator feels a bit strange but it works with the where clause 👍

@cool-develope cool-develope merged commit 0b11f85 into store/upgrade Jul 24, 2024
61 of 64 checks passed
@cool-develope cool-develope deleted the store/upgrade_pruning branch July 24, 2024 14:56
store/v2/storage/pebbledb/db.go Dismissed Show dismissed Hide dismissed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants