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(math): Implement custom hybrid un-/marshal model #22529

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

alpe
Copy link
Contributor

@alpe alpe commented Nov 14, 2024

Description

Closes: #22525

Implement custom hybrid marshal/ unmarshalling for Dec type.

source scientific hybrid
-1.0000001E+0 -1.0000001
-1.000001E+0 -1.000001
0E+0 0
1.000000E+6 1E+6
1.00000E+5 100000
1.0000E+4 10000
1.000E+3 1000
1.00E+2 100
1.1E+100000 1.1E+100000
1.2345678900E+10 123.456789E+8
1.234567890E+9 123.456789E+7
1.23456789E+8 123.456789E+6
1.2345678E+7 12.345678E+6
1.234567E+6 1.234567E+6
1.23456E+5 123456
1.2345E+4 12345
1.234E+3 1234
1.23E+2 123
1.2E+1 12
1E+0 1
1E+100000 1E+100000
1E-1 0.1
1E-2 0.01
1E-3 0.001
1E-4 0.0001
1E-5 0.00001
1E-6 1E-6
1E-7 1E-7

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

Summary by CodeRabbit

  • New Features

    • Introduced methods for marshaling and unmarshaling decimal values, enhancing data interchange capabilities.
    • Added support for an upstream GDA-based decimal type in the math module.
  • Bug Fixes

    • Updated test cases to ensure accurate validation of marshaled decimal values without trailing zeros and scientific notation.
  • Tests

    • Added new test cases for various decimal representations and modified existing tests to reflect correct expectations.
    • Refined output expectations in example functions for precision handling in decimal arithmetic.

@alpe alpe requested review from testinginprod and a team as code owners November 14, 2024 14:58
Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request enhance the Dec struct in the math package by adding methods for serialization and deserialization. The new Marshal method serializes decimal values into a byte slice, while the Unmarshal method parses a byte slice back into a Dec struct. Additionally, a helper function for formatting decimals has been introduced. The corresponding test file has been updated to remove outdated test cases and add new ones that validate the marshaling and unmarshaling processes.

Changes

File Change Summary
math/dec.go - Added func (x Dec) Marshal() ([]byte, error) for serialization.
- Added func (x *Dec) Unmarshal(data []byte) error for deserialization.
- Added func fmtE(d apd.Decimal, fmt byte) []byte for formatting decimals.
math/dec_test.go - Removed outdated test cases from TestMarshalUnmarshal.
- Added new test cases for marshaling decimals without trailing zeros.
- Modified existing tests to reflect correct expectations for marshaling outputs.
math/CHANGELOG.md - Updated changelog to include new feature related to GDA-based decimal type.
math/dec_examples_test.go - Adjusted expected output in ExampleDec_MulExact to reflect scientific notation.

Assessment against linked issues

Objective Addressed Explanation
Implement a custom model for Marshal/Unmarshal (22525)

Possibly related PRs

Suggested labels

C:CLI, C:x/auth, C:x/tx, backport/v0.52.x

Suggested reviewers

  • kocubinski
  • julienrbrt
  • testinginprod

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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.

This comment has been minimized.

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: 2

🧹 Outside diff range and nitpick comments (3)
math/dec_test.go (2)

1319-1323: Consider adding more descriptive test case names for zero values.

The test cases "Zero value" and "-0" could be more descriptive to better explain the purpose of testing different representations of zero.

Consider renaming to:

-		"Zero value": {
+		"Zero should be normalized to '0'": {
-		"-0": {
+		"Negative zero should be normalized to '0'": {

1325-1339: Group decimal place test cases for better organization.

The test cases for decimal places could be grouped together with a common prefix for better readability and organization.

Consider renaming the test cases:

-		"1 decimal place": {
+		"decimal_places/1_digit": {
-		"2 decimal places": {
+		"decimal_places/2_digits": {
-		"3 decimal places": {
+		"decimal_places/3_digits": {
-		"4 decimal places": {
+		"decimal_places/4_digits": {
math/dec.go (1)

472-477: Function isEmptyExp is currently unused

The function isEmptyExp is not referenced elsewhere in the codebase. Consider removing it to clean up the code, unless it is intended for future use.

🧰 Tools
🪛 golangci-lint (1.61.0)

472-472: func isEmptyExp is unused

(unused)

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4631049 and ac56675.

📒 Files selected for processing (2)
  • math/dec.go (2 hunks)
  • math/dec_test.go (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
math/dec.go (1)

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

math/dec_test.go (2)

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


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

🪛 golangci-lint (1.61.0)
math/dec.go

472-472: func isEmptyExp is unused

(unused)

🔇 Additional comments (5)
math/dec.go (5)

7-7: Import "strconv" correctly included

The strconv package is required for number formatting in the fmtE function.


411-432: Marshal method implemented correctly

The Marshal method correctly serializes the decimal value into a byte slice using the custom fmtE formatter, handling potential errors appropriately.


435-468: Implementation of custom formatter fmtE is acceptable

The fmtE function effectively formats the decimal into hybrid notation based on the exponent value, aligning with the specified requirements.


441-443: Verify adherence to exponent boundary specifications

Ensure that the condition adj > -6 && adj < 6 in the fmtE function correctly implements the intended boundaries at exponents of ±6 for switching between decimal and scientific notation, as specified in the PR objectives. Consider adding unit tests to validate behavior at the boundary values (e.g., adj == -6 and adj == 6).


479-492: Unmarshal method implemented correctly

The Unmarshal method accurately parses the byte slice into the Dec struct, handling errors appropriately and ensuring the decimal is finite.

Comment on lines +1353 to +1396
"1": {
x: must(NewDecFromString("1")),
exp: "1",
},
"12": {
x: must(NewDecFromString("12")),
exp: "12",
},
"123": {
x: must(NewDecFromString("123")),
exp: "123",
},
"1234": {
x: must(NewDecFromString("1234")),
exp: "1234",
},
"12345": {
x: must(NewDecFromString("12345")),
exp: "12345",
},
"123456": {
x: must(NewDecFromString("123456")),
exp: "123456",
},
"1234567": {
x: must(NewDecFromString("1234567")),
exp: "1.234567E+6",
},
"12345678": {
x: must(NewDecFromString("12345678")),
exp: "12.345678E+6",
},
"123456789": {
x: must(NewDecFromString("123456789")),
exp: "123.456789E+6",
},
"1234567890": {
x: must(NewDecFromString("1234567890")),
exp: "123.456789E+7",
},
"12345678900": {
x: must(NewDecFromString("12345678900")),
exp: "123.456789E+8",
},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add boundary test cases for scientific notation transition.

The test cases cover various integer values but could benefit from explicit boundary test cases at the scientific notation transition points.

Add these test cases:

"boundary/decimal_to_scientific_positive": {
    x:   must(NewDecFromString("999999")),  // Last number in decimal
    exp: "999999",
},
"boundary/decimal_to_scientific_positive_next": {
    x:   must(NewDecFromString("1000000")), // First number in scientific
    exp: "1E+6",
},
"boundary/decimal_to_scientific_negative": {
    x:   must(NewDecFromString("0.000001")), // Last number in decimal
    exp: "0.000001",
},
"boundary/decimal_to_scientific_negative_next": {
    x:   must(NewDecFromString("0.0000001")), // First number in scientific
    exp: "1E-7",
},

math/dec_test.go Outdated
Comment on lines 1446 to 1451
assert.Equal(t, spec.exp, string(marshaled))
// and backwards
unmarshalledDec := new(Dec)
require.NoError(t, unmarshalledDec.Unmarshal(marshaled))
assert.Equal(t, spec.x.String(), unmarshalledDec.String())
assert.True(t, spec.x.Equal(*unmarshalledDec))
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add unmarshal error test cases.

The unmarshaling tests only verify successful cases. Consider adding test cases for invalid input.

Add these test cases:

"unmarshal/invalid_format": {
    x:      NewDecFromInt64(0),
    exp:    "invalid",
    expErr: ErrInvalidDec,
},
"unmarshal/empty_input": {
    x:      NewDecFromInt64(0),
    exp:    "",
    expErr: ErrInvalidDec,
},

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

Can we get the changelogs in math now :)

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: 1

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ac56675 and a0a7e30.

📒 Files selected for processing (1)
  • math/CHANGELOG.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
math/CHANGELOG.md (1)

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

🪛 LanguageTool
math/CHANGELOG.md

[uncategorized] ~39-~39: This expression is usually spelled with a hyphen.
Context: ...-sdk/issues/11783) feat(math): Upstream GDA based decimal type ## [math/v1.4.0](https:/...

(BASED_HYPHEN)

Comment on lines +39 to +40
* [#11783](https://github.com/cosmos/cosmos-sdk/issues/11783) feat(math): Upstream GDA based decimal type

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance the changelog entry with more details.

The current entry could be more descriptive. Consider expanding it to include:

  1. Details about the marshaling/unmarshaling feature
  2. The numerical formatting thresholds
  3. Example behavior
  4. Fix the hyphenation of "GDA-based"
-* [#11783](https://github.com/cosmos/cosmos-sdk/issues/11783) feat(math): Upstream GDA based decimal type
+* [#22525](https://github.com/cosmos/cosmos-sdk/issues/22525) feat(math): Implement custom hybrid marshal/unmarshal for GDA-based decimal type. Numbers are displayed in decimal format until they reach exponents of +/-6, then switch to scientific notation (e.g., 1234567 stays decimal, while 0.0000001 becomes 1E-7).

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~39-~39: This expression is usually spelled with a hyphen.
Context: ...-sdk/issues/11783) feat(math): Upstream GDA based decimal type ## [math/v1.4.0](https:/...

(BASED_HYPHEN)

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

nice!

@julienrbrt julienrbrt changed the title feat: Implement custom hybrid un-/marshal model feat(math): Implement custom hybrid un-/marshal model Nov 25, 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: 1

🧹 Outside diff range and nitpick comments (3)
math/dec_examples_test.go (1)

Line range hint 1-311: Add examples for Marshal/Unmarshal functionality

The example tests are missing coverage for the new marshaling functionality. Consider adding an ExampleDec_Marshal and ExampleDec_Unmarshal to demonstrate:

  • Decimal to scientific notation transition at +/-6 exponents
  • Handling of various number formats (regular decimals, scientific notation)
  • Error cases for invalid inputs

Here's a suggested example test:

func ExampleDec_Marshal() {
    examples := []string{
        "1.23",           // Regular decimal
        "1000000",        // At +6 boundary
        "0.000001",       // At -6 boundary
        "1.23E+7",        // Beyond +6
        "1.23E-7",        // Beyond -6
    }
    
    for _, s := range examples {
        d, err := NewDecFromString(s)
        if err != nil {
            panic(err)
        }
        bytes, err := d.Marshal()
        if err != nil {
            panic(err)
        }
        fmt.Printf("%s -> %s\n", s, string(bytes))
    }
    
    // Output:
    // 1.23 -> 1.23
    // 1000000 -> 1000000
    // 0.000001 -> 0.000001
    // 1.23E+7 -> 1.23E+7
    // 1.23E-7 -> 1.23E-7
}
math/dec.go (1)

411-432: Consider enhancing error message specificity

While the implementation is correct, the error message could be more specific about the reduction failure.

Consider this improvement:

-		return nil, ErrInvalidDec.Wrap(err.Error())
+		return nil, ErrInvalidDec.Wrap(fmt.Sprintf("failed to reduce decimal: %v", err))
math/dec_test.go (1)

Line range hint 1320-1452: LGTM! Comprehensive test coverage for marshal/unmarshal functionality.

The test cases thoroughly cover:

  • Zero and negative zero handling
  • Decimal place variations
  • Scientific notation transitions
  • Edge cases and error conditions

Consider grouping related test cases together with descriptive comments to improve readability. For example:

// Basic zero handling
"Zero value": {...},
"-0": {...},

// Decimal places (0.1 to 0.000001)
"1 decimal place": {...},
"2 decimal places": {...},

// Scientific notation transition
"6 decimal places": {...},
"7 decimal places": {...},
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a0a7e30 and c951c71.

📒 Files selected for processing (3)
  • math/dec.go (5 hunks)
  • math/dec_examples_test.go (1 hunks)
  • math/dec_test.go (6 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
math/dec.go (1)

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

math/dec_examples_test.go (2)

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


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

math/dec_test.go (2)

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


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

🔇 Additional comments (7)
math/dec_examples_test.go (1)

311-311: LGTM: Output format aligns with the new marshaling rules

The modified output "0E-35" correctly follows the scientific notation format for numbers with exponents beyond +/-6, which is consistent with the PR's marshaling implementation.

math/dec.go (4)

303-303: LGTM: Appropriate use of Text('f') for decimal notation

The change from String() to Text('f') ensures consistent decimal notation without exponents, which is more appropriate for BigInt conversion.


338-338: LGTM: Consistent with hybrid notation requirements

The implementation correctly uses the new fmtE helper function to provide hybrid notation based on the exponent value.


472-485: LGTM: Robust implementation with proper validation

The implementation correctly handles parsing and validation, ensuring only finite decimals are accepted.


506-506: LGTM: Consistent with other serialization methods

The change appropriately uses the new fmtE helper function, maintaining consistency with other serialization methods.

math/dec_test.go (2)

154-158: LGTM! Expected values updated to match new decimal format.

The updated expected values for max/min int64 correctly reflect the new hybrid decimal format, maintaining 6 decimal places of precision before switching to scientific notation.


1249-1259: LGTM! Comprehensive test coverage for BigInt conversion.

The test implementation properly covers:

  • Successful conversion cases
  • Error handling for non-integral values
  • Proper assertion of results and errors

Comment on lines +434 to +469
// fmtE formats a decimal number into a byte slice in scientific notation or fixed-point notation depending on the exponent.
// If the adjusted exponent is between -6 and 6 inclusive, it uses fixed-point notation, otherwise it uses scientific notation.
func fmtE(d apd.Decimal, fmt byte) []byte {
var scratch, dest [16]byte
buf := dest[:0]
digits := d.Coeff.Append(scratch[:0], 10)
totalDigits := int64(len(digits))
adj := int64(d.Exponent) + totalDigits - 1
if adj > -6 && adj < 6 {
return []byte(d.Text('f'))
}
switch {
case totalDigits > 5:
beforeComma := digits[0 : totalDigits-6]
adj -= int64(len(beforeComma) - 1)
buf = append(buf, beforeComma...)
buf = append(buf, '.')
buf = append(buf, digits[totalDigits-6:]...)
case totalDigits > 1:
buf = append(buf, digits[0])
buf = append(buf, '.')
buf = append(buf, digits[1:]...)
default:
buf = append(buf, digits[0:]...)
}

buf = append(buf, fmt)
var ch byte
if adj < 0 {
ch = '-'
adj = -adj
} else {
ch = '+'
}
buf = append(buf, ch)
return strconv.AppendInt(buf, adj, 10)
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

🛠️ Refactor suggestion

Based on the search results, I can now provide a final response:

Buffer size is sufficient, but input validation is needed

  1. The fixed buffer size of 16 bytes is actually sufficient because:

    • The function handles scientific notation for large numbers by using the exponent format
    • Test cases show numbers with up to 35 decimal places being handled correctly (e.g., "0.12345678901234567890123456789012345")
  2. However, the lack of input validation for non-finite forms (NaN, Infinity) should be addressed as suggested.

🔗 Analysis chain

Verify buffer sizes and add input validation

Two potential issues to consider:

  1. The fixed buffer sizes ([16]byte) might be insufficient for large numbers
  2. The function lacks validation for the input decimal's form (finite, infinite, NaN)

Consider these improvements:

 func fmtE(d apd.Decimal, fmt byte) []byte {
+	if d.Form != apd.Finite {
+		return []byte("NaN")
+	}
 	var scratch, dest [16]byte
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for large number handling in tests
rg -A 2 "NewDecFromString.*9{15,}" 

Length of output: 36


Script:

#!/bin/bash
# Search for tests related to decimal formatting
rg -l "fmtE.*test" 

# Search for large number test cases in decimal-related tests
rg "Test.*Dec.*" -A 5

# Look for any existing decimal formatting tests
ast-grep --pattern 'func Test$_($_) {
  $$$
  fmtE($$$)
  $$$
}'

Length of output: 45683


Script:

#!/bin/bash
# Search for large decimal test cases
rg -A 3 "NewDecFromString.*[0-9]{15,}" math/

# Look for any decimal formatting tests
rg -A 5 "TestFmt.*Dec" math/

# Check if there are any existing panic tests for decimal formatting
rg -A 3 "panic.*fmtE" math/

Length of output: 5618

Copy link
Contributor

@akhilkumarpilli akhilkumarpilli left a comment

Choose a reason for hiding this comment

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

lgtm, nice work!

@alpe
Copy link
Contributor Author

alpe commented Nov 26, 2024

I would keep this open for some more days to give others a chance to 👀

@julienrbrt
Copy link
Member

cc @testinginprod @facundomedica @tac0turtle
could you ACK or comment on this format (that's the one we had discussed in the arch call)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Implement Marshal/Unmarshal
7 participants