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(collections): support indexing #20704

Merged
merged 83 commits into from
Aug 30, 2024
Merged

feat(collections): support indexing #20704

merged 83 commits into from
Aug 30, 2024

Conversation

aaronc
Copy link
Member

@aaronc aaronc commented Jun 17, 2024

Description

Introduces basic schema indexing support to collections without any special handling added to codecs. Better naming of fields and better conversion to schema types will be handled in separate PRs (such as #20538). This PR is intended to demonstrate the high level API for schema/indexing support and default handling.


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

Summary by CodeRabbit

  • New Features

    • Introduced schema indexing capabilities for collections, enhancing codec functionality.
    • Added methods for collections to return schema codecs and indicate secondary indexing.
    • Implemented a new indexing mechanism that allows for better management of deletions in collections.
    • Documented the addition of the ModuleCodec method in the changelog for improved schema management.
  • Chores

    • Updated dependencies to include new libraries for better schema handling and indexing performance.

Copy link
Contributor

coderabbitai bot commented Jun 17, 2024

Walkthrough

Walkthrough

The changes introduce enhancements to the collections framework, focusing on schema indexing capabilities. Key updates include the addition of the ModuleCodec method in the Schema and HasSchemaCodec interfaces, new structures for schema codec management, and modifications to the IndexingOptions struct for handling deletion retention. These developments aim to improve schema validation and data handling within the Cosmos SDK.

Changes

Files Change Summary
collections/.../indexing.go, collections/.../codec/indexing.go Introduced new interfaces and structs for schema codec management, including the ModuleCodec method and IndexingOptions for deletion retention.
collections/go.mod Updated dependency management by adding cosmossdk.io/schema and github.com/tidwall/btree, changing the status of github.com/tidwall/btree from indirect to direct.
collections/CHANGELOG.md Added an entry documenting the new ModuleCodec method in the Schema and HasSchemaCodec interface, enhancing indexing support in the collections module.
x/accounts/defaults/lockup/go.mod Added an indirect dependency on cosmossdk.io/schema v0.2.0 and reformatted the dependency list for improved readability.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SchemaManager
    participant Codec
    participant Collection

    User->>SchemaManager: Request schema codec
    SchemaManager->>Codec: Fetch schema codec
    Codec-->>SchemaManager: Return SchemaCodec
    SchemaManager->>Collection: Apply schema changes
    Collection-->>User: Confirm schema update
Loading

Possibly related issues


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

indexer/base/field.go Fixed Show fixed Hide fixed
indexer/base/kind.go Fixed Show fixed Hide fixed
indexer/base/kind.go Fixed Show fixed Hide fixed
indexer/base/kind.go Fixed Show fixed Hide fixed
indexer/base/field.go Fixed Show fixed Hide fixed
indexer/base/field.go Fixed Show fixed Hide fixed
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

Outside diff range, codebase verification and nitpick comments (1)
collections/CHANGELOG.md (1)

41-41: Simplify changelog entry wording.

Consider simplifying the wording for brevity.

- Add `ModuleCodec` method to `Schema` and `HasSchemaCodec` interface in order to support `cosmossdk.io/schema` compatible indexing.
+ Add `ModuleCodec` method to `Schema` and `HasSchemaCodec` interface to support `cosmossdk.io/schema` compatible indexing.
Tools
LanguageTool

[style] ~41-~41: Consider a shorter alternative to avoid wordiness.
Context: ...Schema and HasSchemaCodec interface in order to support cosmossdk.io/schema compatibl...

(IN_ORDER_TO_PREMIUM)

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9355a04 and 333415f.

Files selected for processing (2)
  • collections/CHANGELOG.md (1 hunks)
  • collections/go.mod (1 hunks)
Additional context used
Path-based instructions (1)
collections/CHANGELOG.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

LanguageTool
collections/CHANGELOG.md

[style] ~41-~41: Consider a shorter alternative to avoid wordiness.
Context: ...Schema and HasSchemaCodec interface in order to support cosmossdk.io/schema compatibl...

(IN_ORDER_TO_PREMIUM)

Additional comments not posted (2)
collections/go.mod (2)

23-23: Verify local replacement directive.

The replacement of cosmossdk.io/schema with a local path ../schema suggests local development or testing. Ensure this change is intentional and correctly set up for local development.


8-8: Verify new dependencies.

Ensure that adding cosmossdk.io/schema v0.1.0 and github.com/tidwall/btree v1.7.0 as direct dependencies is intentional and does not introduce conflicts or issues in the codebase.

Also applies to: 10-10

Verification successful

Dependencies are intentionally added and used.

The dependencies cosmossdk.io/schema v0.1.0 and github.com/tidwall/btree v1.7.0 are intentionally added to the go.mod file and are actively used in the codebase without any apparent conflicts.

  • cosmossdk.io/schema is used in multiple files such as schema/view/object.go and indexer/postgres/internal/testdata/example_schema.go.
  • github.com/tidwall/btree is used extensively across various files, indicating its integration into the project.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify usage of new dependencies in the codebase.

# Test: Search for imports of the new dependencies. Expect: Relevant usage in the codebase.
rg --type go 'import.*(cosmossdk\.io/schema|github\.com/tidwall/btree)'

Length of output: 257


Script:

#!/bin/bash
# Check if github.com/tidwall/btree is listed in the go.mod file
rg 'github\.com/tidwall/btree' collections/go.mod

# Search for any usage of btree in the codebase
rg --type go 'btree'

Length of output: 5105

Copy link
Member

@facundomedica facundomedica left a comment

Choose a reason for hiding this comment

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

utACK

collections/codec/indexing.go Outdated Show resolved Hide resolved
collections/indexing.go Outdated Show resolved Hide resolved
Comment on lines +24 to +27
// isSecondaryIndex indicates that this map represents a secondary index
// on another collection and that it should be skipped when generating
// a user facing schema
isSecondaryIndex bool
Copy link
Member

Choose a reason for hiding this comment

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

q: could it be useful to still generate this optionally? Or is it absolutely unnecessary? (asking out of ignorance)

Copy link
Member Author

Choose a reason for hiding this comment

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

The target database (ex. postgres) should generally be able to produce any secondary index it wants if the primary data is present. So this isn't needed.

aaronc and others added 2 commits August 20, 2024 09:24
Co-authored-by: Facundo Medica <14063057+facundomedica@users.noreply.github.com>
Co-authored-by: Facundo Medica <14063057+facundomedica@users.noreply.github.com>
@aaronc aaronc marked this pull request as draft August 27, 2024 16:05
@aaronc aaronc marked this pull request as ready for review August 28, 2024 17:36
@aaronc aaronc enabled auto-merge August 28, 2024 17:39
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: 3

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 333415f and c4f9251.

Files selected for processing (3)
  • collections/codec/indexing.go (1 hunks)
  • collections/indexing.go (1 hunks)
  • x/accounts/defaults/lockup/go.mod (1 hunks)
Files skipped from review due to trivial changes (1)
  • x/accounts/defaults/lockup/go.mod
Additional context used
Path-based instructions (2)
collections/codec/indexing.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

collections/indexing.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

GitHub Check: tests (03)
collections/indexing.go

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema


[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)

GitHub Check: tests (02)
collections/indexing.go

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema


[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)

GitHub Check: tests (01)
collections/indexing.go

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema


[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)

GitHub Check: tests (00)
collections/indexing.go

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema


[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)

GitHub Check: golangci-lint
collections/indexing.go

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema


[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)) (typecheck)

GitHub Check: dependency-review
collections/indexing.go

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema


[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)

Additional comments not posted (6)
collections/codec/indexing.go (4)

10-22: LGTM!

The HasSchemaCodec interface is well-defined and follows Go conventions.

The code changes are approved.


24-44: LGTM!

The SchemaCodec struct is well-defined and follows Go conventions. The use of func fields for conversion is appropriate.

The code changes are approved.


46-54: LGTM!

The KeySchemaCodec function correctly handles the retrieval of the schema codec, including fallback handling.

The code changes are approved.


56-64: LGTM!

The ValueSchemaCodec function correctly handles the retrieval of the schema codec, including fallback handling.

The code changes are approved.

collections/indexing.go (2)

14-19: LGTM!

The IndexingOptions struct is well-defined and follows Go conventions.

The code changes are approved.


71-89: LGTM!

The decodeKV function is well-structured and handles key-value pair updates correctly.

The code changes are approved.

Comment on lines +66 to +102
// FallbackSchemaCodec returns a fallback schema codec for T when one isn't explicitly
// specified with HasSchemaCodec. It maps all simple types directly to schema kinds
// and converts everything else to JSON.
func FallbackSchemaCodec[T any]() SchemaCodec[T] {
var t T
kind := schema.KindForGoValue(t)
if err := kind.Validate(); err == nil {
return SchemaCodec[T]{
Fields: []schema.Field{{
// we don't set any name so that this can be set to a good default by the caller
Name: "",
Kind: kind,
}},
// these can be nil because T maps directly to a schema value for this kind
ToSchemaType: nil,
FromSchemaType: nil,
}
} else {
// we default to encoding everything to JSON
return SchemaCodec[T]{
Fields: []schema.Field{{Kind: schema.JSONKind}},
ToSchemaType: func(t T) (any, error) {
bz, err := json.Marshal(t)
return json.RawMessage(bz), err
},
FromSchemaType: func(a any) (T, error) {
var t T
bz, ok := a.(json.RawMessage)
if !ok {
return t, fmt.Errorf("expected json.RawMessage, got %T", a)
}
err := json.Unmarshal(bz, &t)
return t, err
},
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Address undefined types and methods.

The function provides a comprehensive fallback mechanism. However, the following issues need to be addressed:

  • schema.Type is undefined.
  • schema.NewModuleSchema is undefined.
  • update.Remove is undefined in schema.KVPairUpdate.

Ensure these types and methods are correctly defined or imported.

Comment on lines 21 to 63
// ModuleCodec returns the ModuleCodec for this schema for the provided options.
func (s Schema) ModuleCodec(opts IndexingOptions) (schema.ModuleCodec, error) {
decoder := moduleDecoder{
collectionLookup: &btree.Map[string, *collectionSchemaCodec]{},
}

retainDeletions := make(map[string]bool)
for _, collName := range opts.RetainDeletionsFor {
retainDeletions[collName] = true
}

var types []schema.Type
for _, collName := range s.collectionsOrdered {
coll := s.collectionsByName[collName]

// skip secondary indexes
if coll.isSecondaryIndex() {
continue
}

cdc, err := coll.schemaCodec()
if err != nil {
return schema.ModuleCodec{}, err
}

if retainDeletions[coll.GetName()] {
cdc.objectType.RetainDeletions = true
}

types = append(types, cdc.objectType)

decoder.collectionLookup.Set(string(coll.GetPrefix()), cdc)
}

modSchema, err := schema.NewModuleSchema(types...)
if err != nil {
return schema.ModuleCodec{}, err
}

return schema.ModuleCodec{
Schema: modSchema,
KVDecoder: decoder.decodeKV,
}, nil
Copy link
Contributor

Choose a reason for hiding this comment

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

Address undefined types and methods.

The function is well-structured and handles options correctly. However, the following issues need to be addressed:

  • schema.Type is undefined.
  • schema.NewModuleSchema is undefined.

Ensure these types and methods are correctly defined or imported.

Tools
GitHub Check: tests (03)

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema

GitHub Check: tests (02)

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema

GitHub Check: tests (01)

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema

GitHub Check: tests (00)

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema

GitHub Check: golangci-lint

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema

GitHub Check: dependency-review

[failure] 32-32:
undefined: schema.Type


[failure] 55-55:
undefined: schema.NewModuleSchema

Comment on lines +91 to +120
func (c collectionSchemaCodec) decodeKVPair(update schema.KVPairUpdate) ([]schema.ObjectUpdate, error) {
// strip prefix
key := update.Key
key = key[len(c.coll.GetPrefix()):]

k, err := c.keyDecoder(key)
if err != nil {
return []schema.ObjectUpdate{
{TypeName: c.coll.GetName()},
}, err

}

if update.Remove {
return []schema.ObjectUpdate{
{TypeName: c.coll.GetName(), Key: k, Delete: true},
}, nil
}

v, err := c.valueDecoder(update.Value)
if err != nil {
return []schema.ObjectUpdate{
{TypeName: c.coll.GetName(), Key: k},
}, err
}

return []schema.ObjectUpdate{
{TypeName: c.coll.GetName(), Key: k, Value: v},
}, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Address undefined field.

The function is well-structured and handles key-value pair updates correctly. However, the field Remove is undefined in schema.KVPairUpdate.

Ensure this field is correctly defined or imported.

Tools
GitHub Check: tests (03)

[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)

GitHub Check: tests (02)

[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)

GitHub Check: tests (01)

[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)

GitHub Check: tests (00)

[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)

GitHub Check: golangci-lint

[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)) (typecheck)

GitHub Check: dependency-review

[failure] 104-104:
update.Remove undefined (type schema.KVPairUpdate has no field or method Remove)

@aaronc
Copy link
Member Author

aaronc commented Aug 28, 2024

Looks like CI is failing here because I'm using a replace for schema in collections, but many places that have collections referenced don't have the replace for schema, but do have a replace for collections.

So I think I will wait until I tag schema again to merge this and not use a replace in collections... Marking draft until that's done.

@aaronc aaronc marked this pull request as draft August 28, 2024 18:05
auto-merge was automatically disabled August 28, 2024 18:05

Pull request was converted to draft

@aaronc aaronc marked this pull request as ready for review August 30, 2024 21:06
@aaronc aaronc enabled auto-merge August 30, 2024 21:06
@aaronc aaronc added this pull request to the merge queue Aug 30, 2024
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

Outside diff range, codebase verification and nitpick comments (1)
collections/go.mod (1)

10-10: Change in dependency status for github.com/tidwall/btree v1.7.0

The shift from an indirect to a direct dependency for github.com/tidwall/btree suggests a more active use of this package in the codebase, likely related to its utility in indexing operations. This change should be reflected in the documentation to clarify its role and importance in the project.

Consider adding documentation or comments in the codebase to explain the specific use cases of btree in the context of indexing, which will help future developers understand the rationale behind this dependency change.

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c4f9251 and b1610ac.

Files ignored due to path filters (1)
  • collections/go.sum is excluded by !**/*.sum
Files selected for processing (3)
  • collections/go.mod (1 hunks)
  • collections/indexing.go (1 hunks)
  • x/accounts/defaults/lockup/go.mod (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • collections/indexing.go
  • x/accounts/defaults/lockup/go.mod
Additional comments not posted (1)
collections/go.mod (1)

8-8: Addition of cosmossdk.io/schema v0.2.0

The addition of this dependency is crucial for the new schema indexing capabilities introduced in this PR. Ensure that the version 0.2.0 aligns with the latest stable release that includes all necessary features for schema management.

Merged via the queue into main with commit f843f1a Aug 30, 2024
76 checks passed
@aaronc aaronc deleted the aaronc/collections-indexable branch August 30, 2024 21:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants