Skip to content

fix: edge case to ignore parsing very large numbers#37104

Merged
rahulbarwal merged 4 commits intoreleasefrom
rahulbarwal/issue27881
Oct 28, 2024
Merged

fix: edge case to ignore parsing very large numbers#37104
rahulbarwal merged 4 commits intoreleasefrom
rahulbarwal/issue27881

Conversation

@rahulbarwal
Copy link
Contributor

@rahulbarwal rahulbarwal commented Oct 25, 2024

Description

Problem

The defaultOptionValueValidation function in select.ts is not properly handling different input values, resulting in inconsistent behavior.

Root cause

This function does not account for edge cases where the input value is a very large number and is resulting in a rounded off number, leading to incorrect validation results.

Solution

This PR changes the behavior to parsing only when required.

Fixes #27881
or
Fixes Issue URL

Warning

If no issue exists, please create an issue first, and check with the maintainers if the issue is valid.

Automation

/ok-to-test tags="@tag.JSONForm"

🔍 Cypress test results

Tip

🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/11517642696
Commit: d31373a
Cypress dashboard.
Tags: @tag.JSONForm
Spec:


Fri, 25 Oct 2024 12:16:10 UTC

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

  • New Features

    • Enhanced type safety for various functions, improving overall reliability.
    • Streamlined validation logic for option values, allowing for more robust input handling.
  • Bug Fixes

    • Improved test coverage for defaultOptionValueValidation, ensuring accurate handling of both truthy and falsy values.
  • Documentation

    • Added comments indicating areas for future improvements in the codebase.

@rahulbarwal rahulbarwal self-assigned this Oct 25, 2024
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 25, 2024

Walkthrough

The changes in this pull request focus on enhancing type safety within the codebase by updating function parameter types from any to unknown in several functions, including fieldTypeFor, checkIfArrayAndSubDataTypeChanged, and hasNullOrUndefined. Additionally, modifications were made to the defaultOptionValueValidation function to improve its logic and clarity. The test suite for this function was also restructured for better organization. Overall, the changes aim to strengthen type definitions without altering core functionality.

Changes

File Path Change Summary
app/client/src/widgets/JSONFormWidget/schemaParser.ts Updated parameter types from any to unknown for fieldTypeFor, checkIfArrayAndSubDataTypeChanged, and hasNullOrUndefined.
app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/select.ts Renamed parameter inputValue to value, updated logic for handling value, and refined validation conditions.
app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/select.test.ts Restructured test cases for defaultOptionValueValidation into "handling falsey values" and "handling truthy values". Added a new test for long number strings.

Assessment against linked issues

Objective Addressed Explanation
Improve precision handling in JSONForm (#27881) The changes do not directly address the precision issue with large numbers.

Possibly related PRs

Suggested labels

Bug, Enhancement, Task, ok-to-test

Suggested reviewers

  • ApekshaBhosale
  • jsartisan

🎉 In the realm of code where types do play,
any turned unknown, brightening the way.
Functions refined, tests now aligned,
Clarity reigns, and bugs fall behind.
Here's to the changes, both bold and bright,
Enhancing our code, making it right! 🌟


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.

@github-actions github-actions bot added Bug Something isn't working Community Reported issues reported by community members High This issue blocks a user from building or impacts a lot of users JSON Form Issue / features related to the JSON form wiget Needs Triaging Needs attention from maintainers to triage Production Widgets & Accelerators Pod Issues related to widgets & Accelerators Widgets Product This label groups issues related to widgets labels Oct 25, 2024
@rahulbarwal rahulbarwal added the ok-to-test Required label for CI label Oct 25, 2024
@rahulbarwal
Copy link
Contributor Author

/build-deploy-preview skip-tests=true

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

🧹 Outside diff range and nitpick comments (6)
app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/select.test.ts (2)

78-102: Simplify JSON test input

The multiline template literal could be simplified for better readability.

-      const input = `
-      {
-        "label": "green",
-        "value": "green"
-      }
-    `;
+      const input = JSON.stringify({
+        label: "green",
+        value: "green"
+      });

104-120: Document the number precision limitation

This test addresses the core issue from #27881, but would benefit from a comment explaining the JavaScript number precision limitation (2^53 - 1).

+    // JavaScript's Number.MAX_SAFE_INTEGER is 2^53 - 1 (9007199254740991)
+    // Numbers larger than this lose precision when parsed, so we keep them as strings
     it("Edge Case: For very long numbers passed as string, don't parse it as number", () => {
app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/select.ts (2)

Line range hint 18-29: TODO comment needs addressing

There's a TODO comment about fixing ESLint disable. Consider using proper TypeScript types instead of any.

Suggested fix:

- // TODO: Fix this the next time the file is edited
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- obj: any,
+ obj: unknown,

Line range hint 13-73: Consider a comprehensive solution for large number handling

While the current changes improve type safety, a more comprehensive solution might be needed for handling large numbers:

  1. Consider adding a new field type specifically for large numbers
  2. Document the maximum supported number size in the API
  3. Add validation to prevent precision loss
app/client/src/widgets/JSONFormWidget/schemaParser.ts (2)

Line range hint 328-328: Track TODO comments in issue tracker.

Multiple TODO comments indicate future fixes needed for eslint rules. These should be tracked to ensure they don't get forgotten.

Would you like me to create GitHub issues to track these TODOs? I can help create structured issues for:

  1. Fixing eslint disable rules
  2. Updating type definitions

Also applies to: 366-366


Line range hint 229-266: Add validation for large numbers in fieldTypeFor.

Given the PR objectives to fix large number parsing issues, consider adding explicit validation for large numbers in fieldTypeFor.

 export const fieldTypeFor = (value: unknown): FieldType => {
   const dataType = dataTypeFor(value);
+  if (dataType === DataType.NUMBER && typeof value === 'number') {
+    if (!Number.isSafeInteger(value)) {
+      console.warn(`Large number detected: ${value}. Precision may be lost.`);
+    }
+  }
   const potentialFieldType = DATA_TYPE_POTENTIAL_FIELD[dataType];
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 85226f4 and d31373a.

📒 Files selected for processing (3)
  • app/client/src/widgets/JSONFormWidget/schemaParser.ts (1 hunks)
  • app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/select.test.ts (1 hunks)
  • app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/select.ts (3 hunks)
🔇 Additional comments (4)
app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/select.test.ts (1)

7-7: Well-structured test organization!

The separation into "falsey" and "truthy" value handling provides clear test categorization.

Also applies to: 60-60

app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/select.ts (2)

10-10: Type safety improvements look good!

The change from any to LoDashStatic and parameter renaming improves type safety and readability.

Also applies to: 13-15


Line range hint 51-73: Verify validation behavior with large numbers

The validation logic looks good, but let's verify it handles the edge cases correctly.

✅ Verification successful

The previous search was too specific. Let's broaden our search to find relevant test cases and implementations that can help us verify the behavior with large numbers.


Let's examine the test cases specifically related to number handling and the implementation of isFinite validation to verify the behavior with large numbers.


Let's examine the complete test file and the actual implementation of number validation to verify how large numbers are handled.


Large number validation is properly handled

The code correctly handles large numbers through:

  • Explicit test case for very long numbers (60+ digits) ensuring they remain as strings
  • Proper use of _.isFinite() for number validation
  • Fallback to string handling for large numeric values that exceed JavaScript's number precision

The validation logic maintains data integrity by not attempting to parse very large numbers into JavaScript numbers, which could lead to precision loss.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test cases involving large numbers
rg -l "defaultOptionValueValidation.*[0-9]{16,}" --type ts

# Search for related bug reports or issues
rg "large.*number.*validation|precision.*loss" --type ts

Length of output: 119


Script:

#!/bin/bash
# Search for test cases related to select validation
rg -A 5 "defaultOptionValueValidation" --type ts

# Search for test cases with numeric values in select validation
rg -A 5 "isFinite.*value" --type ts

# Look for test files related to select validation
fd "select.*test" -e ts -e js

Length of output: 49957


Script:

#!/bin/bash
# Let's check the test cases in select.test.ts for numeric validation
rg -A 10 "test.*number|test.*large|test.*finite" app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/select.test.ts

# Check implementation of isFinite validation
ast-grep --pattern 'if ($$$isFinite$$$) {
  $$$
}'

Length of output: 189


Script:

#!/bin/bash
# Let's check the test file content for numeric validation cases
cat app/client/src/widgets/JSONFormWidget/widget/propertyConfig/properties/select.test.ts

# Also check the implementation of _.isFinite usage
rg -A 5 "_.isFinite\(value\)" --type ts

Length of output: 11796

app/client/src/widgets/JSONFormWidget/schemaParser.ts (1)

Line range hint 642-644: Consider adding recursion depth limit.

The recursive schema parsing in convertArrayToSchema and convertObjectToSchema could potentially cause stack overflow with deeply nested structures.

Consider adding a depth limit parameter to prevent stack overflow:

 static convertObjectToSchema = ({
   baseSchemaPath,
   currSourceData,
+  depth = 0,
+  maxDepth = 100,
   ...rest
 }: Omit<ParserOptions, "identifier">): Schema => {
+  if (depth >= maxDepth) {
+    console.warn(`Maximum recursion depth ${maxDepth} reached`);
+    return {};
+  }

Also applies to: 699-701

Comment on lines +8 to +57
it("return undefined when input is undefined", () => {
const input = undefined;
const expectedOutput = {
isValid: true,
parsed: undefined,
messages: [{ name: "", message: "" }],
};

it("return null when input is null", () => {
const input = null;
const expectedOutput = {
isValid: true,
parsed: null,
messages: [{ name: "", message: "" }],
};

const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);

expect(response).toEqual(expectedOutput);
});
const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);

it("return empty string with empty string", () => {
const input = "";
const expectedOutput = {
isValid: true,
parsed: "",
messages: [{ name: "", message: "" }],
};

const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);

expect(response).toEqual(expectedOutput);
});
expect(response).toEqual(expectedOutput);
});

it("return null when input is null", () => {
const input = null;
const expectedOutput = {
isValid: true,
parsed: null,
messages: [{ name: "", message: "" }],
};

const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);

expect(response).toEqual(expectedOutput);
});

it("return empty string with empty string", () => {
const input = "";
const expectedOutput = {
isValid: true,
parsed: "",
messages: [{ name: "", message: "" }],
};

const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);

it("return value with string", () => {
const input = "green";
const expectedOutput = {
isValid: true,
parsed: "green",
messages: [{ name: "", message: "" }],
};

const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);

expect(response).toEqual(expectedOutput);
expect(response).toEqual(expectedOutput);
});
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

Consider using test.each for falsey value tests

The falsey value tests follow the same pattern and could be more maintainable using test.each.

-  describe("handling falsey values", () => {
-    it("return undefined when input is undefined", () => {
-      const input = undefined;
-      const expectedOutput = {
-        isValid: true,
-        parsed: undefined,
-        messages: [{ name: "", message: "" }],
-      };
-      // ... similar pattern repeats
+  describe("handling falsey values", () => {
+    test.each([
+      ["undefined", undefined],
+      ["null", null],
+      ["empty string", ""]
+    ])("returns correct output for %s", (_, input) => {
+      const expectedOutput = {
+        isValid: true,
+        parsed: input,
+        messages: [{ name: "", message: "" }],
+      };
+      
+      const response = defaultOptionValueValidation(
+        input,
+        {} as JSONFormWidgetProps,
+        _,
+      );
+      
+      expect(response).toEqual(expectedOutput);
+    });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it("return undefined when input is undefined", () => {
const input = undefined;
const expectedOutput = {
isValid: true,
parsed: undefined,
messages: [{ name: "", message: "" }],
};
it("return null when input is null", () => {
const input = null;
const expectedOutput = {
isValid: true,
parsed: null,
messages: [{ name: "", message: "" }],
};
const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);
expect(response).toEqual(expectedOutput);
});
const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);
it("return empty string with empty string", () => {
const input = "";
const expectedOutput = {
isValid: true,
parsed: "",
messages: [{ name: "", message: "" }],
};
const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);
expect(response).toEqual(expectedOutput);
});
expect(response).toEqual(expectedOutput);
});
it("return null when input is null", () => {
const input = null;
const expectedOutput = {
isValid: true,
parsed: null,
messages: [{ name: "", message: "" }],
};
const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);
expect(response).toEqual(expectedOutput);
});
it("return empty string with empty string", () => {
const input = "";
const expectedOutput = {
isValid: true,
parsed: "",
messages: [{ name: "", message: "" }],
};
const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);
it("return value with string", () => {
const input = "green";
const expectedOutput = {
isValid: true,
parsed: "green",
messages: [{ name: "", message: "" }],
};
const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);
expect(response).toEqual(expectedOutput);
expect(response).toEqual(expectedOutput);
});
describe("handling falsey values", () => {
test.each([
["undefined", undefined],
["null", null],
["empty string", ""]
])("returns correct output for %s", (_, input) => {
const expectedOutput = {
isValid: true,
parsed: input,
messages: [{ name: "", message: "" }],
};
const response = defaultOptionValueValidation(
input,
{} as JSONFormWidgetProps,
_,
);
expect(response).toEqual(expectedOutput);
});
});

@github-actions
Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/11517646992.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 37104.
recreate: .

@github-actions
Copy link

Deploy-Preview-URL: https://ce-37104.dp.appsmith.com

@rahulbarwal rahulbarwal merged commit 5e46804 into release Oct 28, 2024
@rahulbarwal rahulbarwal deleted the rahulbarwal/issue27881 branch October 28, 2024 10:06
github-actions bot pushed a commit to Zeral-Zhang/appsmith that referenced this pull request Nov 20, 2024
## Description
<ins>Problem</ins>

The defaultOptionValueValidation function in select.ts is not properly
handling different input values, resulting in inconsistent behavior.


<ins>Root cause</ins>

This function does not account for edge cases where the input value is a
very large number and is resulting in a rounded off number, leading to
incorrect validation results.

<ins>Solution</ins>

This PR changes the behavior to parsing only when required.


Fixes appsmithorg#27881
_or_  
Fixes `Issue URL`
> [!WARNING]  
> _If no issue exists, please create an issue first, and check with the
maintainers if the issue is valid._

## Automation

/ok-to-test tags="@tag.JSONForm"

### 🔍 Cypress test results
<!-- This is an auto-generated comment: Cypress test results  -->
> [!TIP]
> 🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
> Workflow run:
<https://github.com/appsmithorg/appsmith/actions/runs/11517642696>
> Commit: d31373a
> <a
href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=11517642696&attempt=1"
target="_blank">Cypress dashboard</a>.
> Tags: `@tag.JSONForm`
> Spec:
> <hr>Fri, 25 Oct 2024 12:16:10 UTC
<!-- end of auto-generated comment: Cypress test results  -->


## Communication
Should the DevRel and Marketing teams inform users about this change?
- [ ] Yes
- [x] No


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Enhanced type safety for various functions, improving overall
reliability.
- Streamlined validation logic for option values, allowing for more
robust input handling.

- **Bug Fixes**
- Improved test coverage for `defaultOptionValueValidation`, ensuring
accurate handling of both truthy and falsy values.

- **Documentation**
- Added comments indicating areas for future improvements in the
codebase.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Bug Something isn't working Community Reported issues reported by community members High This issue blocks a user from building or impacts a lot of users JSON Form Issue / features related to the JSON form wiget Needs Triaging Needs attention from maintainers to triage ok-to-test Required label for CI Production Widgets & Accelerators Pod Issues related to widgets & Accelerators Widgets Product This label groups issues related to widgets

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Missing precision issue with JSONForm

2 participants