Skip to content

chore: bypass immer for first evaluation, fixed cloneDeep issue and using mutative instead of immer#38993

Merged
vsvamsi1 merged 1 commit intoreleasefrom
test61
Feb 6, 2025
Merged

chore: bypass immer for first evaluation, fixed cloneDeep issue and using mutative instead of immer#38993
vsvamsi1 merged 1 commit intoreleasefrom
test61

Conversation

@vsvamsi1
Copy link
Contributor

@vsvamsi1 vsvamsi1 commented Feb 4, 2025

Description

  • Using mutative instead of immer, this has reduced the main thread scripting by about 1 second.
  • Removed a cloneDeep during table onMount which saves about 70ms in main thread scripting.
  • Bypassed mutative when applying the first tree to reduce the overhead associated to mutative.

Fixes #Issue Number
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.All"

🔍 Cypress test results

Tip

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


Thu, 06 Feb 2025 04:21:41 UTC

Communication

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

  • Yes
  • No

Summary by CodeRabbit

  • New Dependency

    • Integrated a new library to enhance overall state management.
  • Refactor

    • Updated state update mechanisms across interactive components and data flows.
    • Improved table widget processing for more consistent behavior.
  • Chore

    • Removed legacy development-only configuration settings.

@vsvamsi1 vsvamsi1 requested a review from a team February 4, 2025 05:40
@vsvamsi1 vsvamsi1 requested review from a team and KelvinOm as code owners February 4, 2025 05:40
@vsvamsi1 vsvamsi1 requested review from AnaghHegde and removed request for a team February 4, 2025 05:40
@vsvamsi1 vsvamsi1 marked this pull request as draft February 4, 2025 05:40
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 4, 2025

Walkthrough

This pull request refactors state management across the codebase by replacing the immer library’s produce function with the mutative library’s create function. The changes include new dependency addition, import statement updates, and modifications in various reducers, hooks, components, sagas, and test files. Additionally, the autofreeze logic in the main index file has been removed, and a table widget’s column transformation logic has been updated. The overall functionality remains intact with only the underlying state mutation mechanism being altered.

Changes

File(s) Change Summary
app/client/package.json Added dependency "mutative": "^1.1.0".
app/.../WidgetProvider/factory/index.tsx, app/.../ce/pages/Editor/Explorer/hooks.tsx, app/.../ce/reducers/entityReducers/jsActionsReducer.tsx, app/.../ce/reducers/uiReducers/applicationsReducer.tsx, app/.../components/editorComponents/WidgetQueryGeneratorForm/index.tsx, app/.../components/propertyControls/ButtonTabControl.tsx, app/.../sagas/WidgetAdditionSagas.ts Replaced import of produce from immer with { create } from mutative and updated corresponding function calls.
app/client/src/index.tsx Removed setAutoFreeze logic and associated import from immer.
app/.../reducers/entityReducers/datasourceReducer.ts, app/.../reducers/entityReducers/metaReducer/index.ts, app/.../reducers/entityReducers/metaReducer/metaReducerUtils.ts, app/.../utils/ReducerUtils.ts Transitioned state updates from immer to mutative in reducers and utility functions; modified control flow (e.g., conditional update checks).
app/.../widgets/TableWidgetV2/widget/index.tsx Replaced lodash’s cloneDeep with an implementation using objectKeys to transform column properties (changing HTML to TEXT).
app/.../reducers/evaluationReducers/treeReducer.ts Updated payload type and simplified control flow by removing redundant conditionals for new tree state updates.
app/.../workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts, app/.../workers/Evaluation/evalTreeWithChanges.test.ts, app/.../workers/common/DataTreeEvaluator/utils.test.ts Updated test cases to replace immer’s produce with mutative’s create ensuring consistent state handling in tests.

Sequence Diagram(s)

sequenceDiagram
  participant U as User Action
  participant C as Component/Reducer
  participant M as Mutative.create
  participant S as Updated State

  U->>C: Dispatch action (e.g., state update)
  C->>M: Call create(currentState, updater)
  M->>S: Return new state object
  S-->>C: Updated state for render
Loading

Possibly related PRs

  • chore: Add IDE Tabs state in Focus Retention #38799: The changes in the main PR, which involve replacing the immer library with the mutative library for state management, are related to the retrieved PR as both involve modifications to the handling of focus entities, specifically the renaming of PROPERTY_PANE to WIDGET, indicating a shift in how state is managed across the application.
  • chore: Refactor WDS custom widget #38038: The changes in the main PR, which involve replacing the immer library with the mutative library for state management, are directly related to the modifications in the retrieved PR, where similar transitions from immer to mutative are made across various components and tests.
  • chore: merge updateActionData with an evaluation #38793: The changes in the main PR, which involve replacing the immer library with the mutative library for state management, are related to the retrieved PR as both involve modifications to the evaluation logic and state handling, specifically in how actions are processed and evaluated.

Suggested labels

Performance Pod, Task

Suggested reviewers

  • rajatagrawal
  • ApekshaBhosale
  • dvj1988

Poem

In code we dance with state anew,
Swapping produce for create – the breakthrough!
From reducers to tests, a smooth refactor spree,
With cleaner flows and magic to see.
Cheers to code, refined as can be! 🚀
Happy merging and bug-free harmony!

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@vsvamsi1 vsvamsi1 self-assigned this Feb 4, 2025
@vsvamsi1 vsvamsi1 added the ok-to-test Required label for CI label Feb 4, 2025
@vsvamsi1
Copy link
Contributor Author

vsvamsi1 commented Feb 4, 2025

/build-deploy-preview skip-tests=true

@github-actions
Copy link

github-actions bot commented Feb 4, 2025

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

@github-actions
Copy link

github-actions bot commented Feb 4, 2025

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

rajatagrawal
rajatagrawal previously approved these changes Feb 4, 2025
znamenskii-ilia
znamenskii-ilia previously approved these changes Feb 4, 2025
@vsvamsi1 vsvamsi1 changed the title bypass immer, fixed cloneDeep and using mutative chore: bypass immer for first evaluation, fixed cloneDeep issue and using mutative instead of immer Feb 4, 2025
@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Feb 4, 2025
@vsvamsi1 vsvamsi1 marked this pull request as ready for review February 4, 2025 14:55
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

🧹 Nitpick comments (8)
app/client/src/utils/ReducerUtils.ts (1)

45-47: Rename the reducer to match the “mutative” library
The function is still called createImmerReducer yet it now uses create from mutative. Consider renaming the function or adding clear comments to avoid confusion.

-export const createImmerReducer = (
+export const createMutativeReducer = (
app/client/src/reducers/evaluationReducers/treeReducer.ts (1)

29-33: Graceful handling of missing or empty update paths
Skipping invalid updates prevents unnecessary crashes. If needed, log or count how many updates are skipped for debugging.

app/client/src/reducers/entityReducers/metaReducer/index.ts (1)

85-110: Maintain consistency in state update patterns.

The reducer uses mutative's create for some cases but falls back to object spread operator for TABLE_PANE_MOVED. Consider using mutative consistently across all cases for better maintainability.

-const next = { ...state };
-// TODO: Fix this the next time the file is edited
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-let widgetMetaProps: Record<string, any> = next[action.payload.widgetId];
+const next = create(state, draft => {
+  let widgetMetaProps = draft[action.payload.widgetId];
+  
+  if (widgetMetaProps === undefined) {
+    draft[action.payload.widgetId] = {
+      isMoved: true,
+      position: { ...action.payload.position },
+    };
+  } else {
+    draft[action.payload.widgetId] = {
+      ...widgetMetaProps,
+      isMoved: true,
+      position: { ...action.payload.position },
+    };
+  }
+});
app/client/src/workers/common/DataTreeEvaluator/utils.test.ts (1)

190-192: Optimize performance by avoiding delete operator.

The static analysis tool correctly flags the use of the delete operator which can impact performance.

-const deletedWidgetNameInAllKeys = create(initialAllKeys, (draft) => {
-  delete draft["WidgetName.name"];
-});
+const deletedWidgetNameInAllKeys = create(initialAllKeys, (draft) => {
+  draft["WidgetName.name"] = undefined;
+});
🧰 Tools
🪛 Biome (1.9.4)

[error] 191-191: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

app/client/src/components/editorComponents/WidgetQueryGeneratorForm/index.tsx (1)

2-2: State update logic looks good but consider adding error handling.

The transition from immer to mutative maintains the same state update logic. However, the create function's error handling could be improved.

Consider wrapping the state update in a try-catch block:

 setConfig(
-  create(config, (draftConfig) => {
+  try {
+    return create(config, (draftConfig) => {
       if (
         property === "datasource" ||
         (typeof property === "object" &&
           Object.keys(property).includes("datasource"))
       ) {
         // ... existing code ...
       }
       // ... rest of the code ...
     }),
+  } catch (error) {
+    console.error("Failed to update config:", error);
+    return config;
+  }
 );

Also applies to: 181-224

app/client/src/ce/pages/Editor/Explorer/hooks.tsx (2)

187-208: Consider optimizing the filtering logic in useActions.

The current implementation iterates through all actions for each page. Consider using a more efficient filtering approach.

-const filteredActions = create(actions, (draft) => {
+const filteredActions = create(actions, (draft) => {
+  const searchKeywordLower = searchKeyword.toLowerCase();
   for (const [key, value] of Object.entries(draft)) {
     if (pageIds.includes(key)) {
       draft[key] = value;
     } else {
-      value.forEach((action, index) => {
-        const searchMatches =
-          action.config.name
-            .toLowerCase()
-            .indexOf(searchKeyword.toLowerCase()) > -1;
-
-        if (searchMatches) {
-          draft[key][index] = action;
-        } else {
-          delete draft[key][index];
-        }
-      });
+      draft[key] = value.filter(action => 
+        action.config.name.toLowerCase().includes(searchKeywordLower)
+      );
     }
-    draft[key] = draft[key].filter(Boolean);
   }
 });

259-270: Optimize page filtering in usePageIds hook.

The current implementation creates unnecessary array copies.

-const filteredPages = create(pages, (draft) => {
-  draft.forEach((page, index) => {
-    const searchMatches =
-      page.pageName.toLowerCase().indexOf(searchKeyword.toLowerCase()) > -1;
-    if (searchMatches) {
-    } else {
-      delete draft[index];
-    }
-  });
-});
+const searchKeywordLower = searchKeyword.toLowerCase();
+const filteredPages = pages.filter(page => 
+  page.pageName.toLowerCase().includes(searchKeywordLower)
+);
app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts (1)

373-374: Consider using undefined assignment instead of delete operator.

Using the delete operator can impact performance. Consider using undefined assignment instead:

-          delete draft.Table1.pageSize;
-          delete draft.Table1.__evaluation__.errors.transientTableData;
+          draft.Table1.pageSize = undefined;
+          draft.Table1.__evaluation__.errors.transientTableData = undefined;

Also applies to: 374-377

🧰 Tools
🪛 Biome (1.9.4)

[error] 373-374: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 84474ae and 0acaede.

⛔ Files ignored due to path filters (1)
  • app/client/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (18)
  • app/client/package.json (1 hunks)
  • app/client/src/WidgetProvider/factory/index.tsx (2 hunks)
  • app/client/src/ce/pages/Editor/Explorer/hooks.tsx (4 hunks)
  • app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx (2 hunks)
  • app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx (2 hunks)
  • app/client/src/components/editorComponents/WidgetQueryGeneratorForm/index.tsx (2 hunks)
  • app/client/src/components/propertyControls/ButtonTabControl.tsx (2 hunks)
  • app/client/src/index.tsx (1 hunks)
  • app/client/src/reducers/entityReducers/datasourceReducer.ts (7 hunks)
  • app/client/src/reducers/entityReducers/metaReducer/index.ts (4 hunks)
  • app/client/src/reducers/entityReducers/metaReducer/metaReducerUtils.ts (2 hunks)
  • app/client/src/reducers/evaluationReducers/treeReducer.ts (3 hunks)
  • app/client/src/sagas/WidgetAdditionSagas.ts (2 hunks)
  • app/client/src/utils/ReducerUtils.ts (2 hunks)
  • app/client/src/widgets/TableWidgetV2/widget/index.tsx (2 hunks)
  • app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts (27 hunks)
  • app/client/src/workers/Evaluation/evalTreeWithChanges.test.ts (9 hunks)
  • app/client/src/workers/common/DataTreeEvaluator/utils.test.ts (5 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
app/client/src/workers/common/DataTreeEvaluator/utils.test.ts

[error] 191-191: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts

[error] 373-374: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 374-377: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (17)
app/client/src/utils/ReducerUtils.ts (2)

35-43: Validate behavior when multiple updates are flagged as "newTree"
Returning after finding the first "newTree" means subsequent "newTree" updates, if any, won't be applied. Confirm this is intentional.


2-2: Double-check “mutative” library version compatibility
It looks fine to import and use create from mutative here. However, kindly ensure that the installed version aligns with project requirements and doesn’t introduce breaking changes.

✅ Verification successful

Verification of mutative version compatibility
The installed version ^1.1.0 (resolved to 1.1.0) is used consistently across the codebase, and there are no apparent compatibility issues with the import of create.

  • Confirmed in app/client/package.json
  • Confirmed in app/client/yarn.lock
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the installed version of 'mutative' in package-lock.json or yarn.lock
rg "mutative" -A 3

Length of output: 7093

app/client/src/reducers/evaluationReducers/treeReducer.ts (2)

3-3: Confirm the import usage for “deep-diff”
Using applyChange is valid, but if performance is a concern for large trees, consider profiling and compare with alternative approaches.


17-17: Switching to generic Diff<DataTree, DataTree>
This type update looks appropriate, given the broader changes. Ensure all references to the older DiffWithNewTreeState are removed or updated.

app/client/src/index.tsx (1)

25-26: Removal of the autofreeze logic aligns with the mutative transition
Dropping setAutoFreeze is consistent with moving away from immer.

app/client/src/reducers/entityReducers/metaReducer/metaReducerUtils.ts (1)

84-91: Verify immutability guarantees with mutative.

The transition from immer to mutative looks correct. However, let's verify that mutative's create function provides the same immutability guarantees as immer's produce.

✅ Verification successful

Immutability Guarantees Verified via Mutative's create()

The investigation confirms that Mutative's create() function maintains the same core immutability guarantees as Immer's produce(). In both approaches, the original state is preserved and only a new state is returned after applying draft modifications. While configuration options and performance optimizations differ, the underlying immutability mechanism works equivalently for typical use cases.

  • Core Guarantee: Both methods use a draft pattern to ensure that the base state remains unchanged.
  • Advanced Options: Mutative offers additional configuration options (e.g., strict mode and patch support) without compromising immutability.
🏁 Scripts executed

The following scripts were executed for the analysis:

Web query:

Does mutative's create function provide the same immutability guarantees as immer's produce function?

Length of output: 6032

app/client/src/ce/pages/Editor/Explorer/hooks.tsx (1)

228-241: Similar optimization needed in useWidgets hook.

The widget filtering logic could be optimized for better performance.

Run this script to check the impact of filtering on large widget trees:

app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx (1)

403-418: LGTM! Efficient state update implementation.

The state update logic using create is well-implemented with efficient lookups using keyBy.

app/client/src/sagas/WidgetAdditionSagas.ts (1)

114-120: LGTM! Good performance optimization.

The switch from immer to mutative for state management is a good optimization, as it reduces scripting time by approximately 50%. The logic for initializing props.children remains correct.

app/client/src/WidgetProvider/factory/index.tsx (1)

421-424: LGTM! Consistent state management update.

The change from immer to mutative is consistent with the codebase-wide optimization effort.

app/client/src/reducers/entityReducers/datasourceReducer.ts (1)

469-477: LGTM! Consistent reducer updates.

The migration from immer to mutative across all action handlers maintains the same state update logic while improving performance.

Also applies to: 659-662, 667-674, 679-686, 688-691, 696-702, 707-713, 715-718, 723-729, 734-740

app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts (1)

113-115: LGTM! Test coverage maintained.

The migration from immer to mutative across all test cases maintains the same test coverage and assertions.

Also applies to: 122-125, 134-136, 148-150, 165-167, 182-184, 185-190, 207-209, 210-215, 247-249, 263-265, 284-287, 305-308, 336-339, 380-386, 387-394, 420-426, 427-430, 446-448, 472-485, 491-493, 507-509, 531-539, 555-557, 572-574, 586-593, 616-623, 631-640, 661-668

app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx (2)

25-25: LGTM! Import statement updated for new state management library.

The change from immer to mutative is consistent with the codebase migration.


533-542: LGTM! State update logic migrated to use mutative.

The state update logic has been correctly migrated from immer's produce to mutative's create while maintaining the same functionality.

app/client/src/widgets/TableWidgetV2/widget/index.tsx (2)

144-144: LGTM! Added utility import for object key iteration.

Using objectKeys from @appsmith/utils is a good practice for consistent key iteration.


934-948: LGTM! Improved column type migration logic.

The implementation efficiently updates column types using objectKeys and reduce, avoiding unnecessary deep cloning.

app/client/package.json (1)

164-164: LGTM! Added mutative dependency.

The addition of mutative@1.1.0 is required for the state management migration from immer.

Comment on lines +65 to 67
const updatedValues: string[] = create(values, (draft: string[]) => {
draft.push(value);
});
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

Simplify array update logic.

Using mutative's create for a simple array push operation is unnecessary overhead. A simpler spread operator would be more efficient here.

-const updatedValues: string[] = create(values, (draft: string[]) => {
-  draft.push(value);
-});
+const updatedValues: string[] = [...values, value];
📝 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
const updatedValues: string[] = create(values, (draft: string[]) => {
draft.push(value);
});
const updatedValues: string[] = [...values, value];

Comment on lines +262 to 265
const updatedLabelUnevalTree = create(unEvalTree, (draft: any) => {
draft.Text1.text = UPDATED_LABEL;
draft.Text1.label = UPDATED_LABEL;
});
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

Fix type casting and improve type safety.

Multiple instances of any type casting should be addressed as noted in the TODO comments.

Consider creating proper types for the draft state:

interface UnEvalTree {
  Text1?: {
    text?: string;
    label?: string;
  };
  [key: string]: any; // for other properties if needed
}

// Then use it in create calls:
const updatedLabelUnevalTree = create(unEvalTree, (draft: UnEvalTree) => {
  if (draft.Text1?.text) {
    draft.Text1.text = UPDATED_LABEL;
  }
});

Also applies to: 314-316, 349-353, 389-393, 429-433, 459-463, 498-502, 536-540

Copy link

@dvj1988 dvj1988 left a comment

Choose a reason for hiding this comment

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

@vsvamsi1 can we remove immer from the dependencies?

@vsvamsi1 vsvamsi1 dismissed stale reviews from znamenskii-ilia and rajatagrawal via 4cb8217 February 5, 2025 19:09
@vsvamsi1 vsvamsi1 added ok-to-test Required label for CI and removed ok-to-test Required label for CI labels Feb 5, 2025
@vsvamsi1 vsvamsi1 requested a review from rajatagrawal February 5, 2025 19:10
@vsvamsi1 vsvamsi1 added ok-to-test Required label for CI and removed ok-to-test Required label for CI labels Feb 5, 2025
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

🧹 Nitpick comments (1)
app/client/src/utils/ReducerUtils.ts (1)

35-43: Consider adding type safety for updates array.

The updates array handling looks correct but could benefit from type safety.

+interface Update {
+  kind: string;
+  rhs: unknown;
+}
+
 if (action?.payload?.updates) {
-  const updates = action?.payload?.updates;
+  const updates = action?.payload?.updates as Update[];

   for (const update of updates) {
     if (update.kind === "newTree") {
       return update.rhs;
     }
   }
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0acaede and 4cb8217.

⛔ Files ignored due to path filters (1)
  • app/client/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (18)
  • app/client/package.json (2 hunks)
  • app/client/src/WidgetProvider/factory/index.tsx (2 hunks)
  • app/client/src/ce/pages/Editor/Explorer/hooks.tsx (4 hunks)
  • app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx (2 hunks)
  • app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx (2 hunks)
  • app/client/src/components/editorComponents/WidgetQueryGeneratorForm/index.tsx (2 hunks)
  • app/client/src/components/propertyControls/ButtonTabControl.tsx (2 hunks)
  • app/client/src/index.tsx (1 hunks)
  • app/client/src/reducers/entityReducers/datasourceReducer.ts (7 hunks)
  • app/client/src/reducers/entityReducers/metaReducer/index.ts (4 hunks)
  • app/client/src/reducers/entityReducers/metaReducer/metaReducerUtils.ts (2 hunks)
  • app/client/src/reducers/evaluationReducers/treeReducer.ts (3 hunks)
  • app/client/src/sagas/WidgetAdditionSagas.ts (2 hunks)
  • app/client/src/utils/ReducerUtils.ts (2 hunks)
  • app/client/src/widgets/TableWidgetV2/widget/index.tsx (2 hunks)
  • app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts (27 hunks)
  • app/client/src/workers/Evaluation/evalTreeWithChanges.test.ts (9 hunks)
  • app/client/src/workers/common/DataTreeEvaluator/utils.test.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (15)
  • app/client/src/ce/pages/Editor/Explorer/hooks.tsx
  • app/client/package.json
  • app/client/src/index.tsx
  • app/client/src/components/editorComponents/WidgetQueryGeneratorForm/index.tsx
  • app/client/src/reducers/entityReducers/datasourceReducer.ts
  • app/client/src/ce/reducers/entityReducers/jsActionsReducer.tsx
  • app/client/src/reducers/evaluationReducers/treeReducer.ts
  • app/client/src/reducers/entityReducers/metaReducer/metaReducerUtils.ts
  • app/client/src/components/propertyControls/ButtonTabControl.tsx
  • app/client/src/sagas/WidgetAdditionSagas.ts
  • app/client/src/WidgetProvider/factory/index.tsx
  • app/client/src/ce/reducers/uiReducers/applicationsReducer.tsx
  • app/client/src/workers/Evaluation/evalTreeWithChanges.test.ts
  • app/client/src/reducers/entityReducers/metaReducer/index.ts
  • app/client/src/widgets/TableWidgetV2/widget/index.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts

[error] 373-374: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 374-377: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

app/client/src/workers/common/DataTreeEvaluator/utils.test.ts

[error] 191-191: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (4)
app/client/src/utils/ReducerUtils.ts (2)

2-2: LGTM: Import change aligns with PR objectives.

The change from immer to mutative library is consistent with the PR's goal of improving performance.


47-47: LGTM: State mutation using mutative's create function.

The replacement of produce with create is correctly implemented.

app/client/src/workers/common/DataTreeEvaluator/utils.test.ts (1)

9-9: LGTM: Consistent replacement of immer with mutative across test cases.

The transition from produce to create is consistently applied across all test cases while maintaining the original test logic and assertions.

Also applies to: 173-174, 190-192, 207-209, 247-249, 263-265, 284-287, 305-308, 323-329, 336-339, 365-371, 372-375, 380-386, 387-394, 420-426, 427-430, 446-448, 475-481, 482-485, 491-493, 507-509, 532-538, 555-557, 572-574, 586-593, 616-623, 631-640, 661-668

app/client/src/workers/Evaluation/__tests__/generateOpimisedUpdates.test.ts (1)

3-3: LGTM: Comprehensive test coverage maintained with mutative.

The transition from produce to create is consistently applied across all test cases while maintaining comprehensive test coverage for optimized updates generation, including edge cases with serialization, moment objects, and large collections.

Also applies to: 113-115, 122-125, 134-136, 148-150, 165-167, 182-190, 207-215, 247-249, 263-265, 284-287, 305-308, 336-339, 365-371, 372-375, 380-386, 387-394, 420-426, 427-430, 446-448, 475-481, 482-485, 491-493, 507-509, 532-538, 555-557, 572-574, 586-593, 616-623, 631-640, 661-668

"eslint-plugin-testing-library": "^6.2.0",
"factory.ts": "^0.5.1",
"husky": "^8.0.0",
"immer": "^9.0.6",
Copy link
Contributor

Choose a reason for hiding this comment

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

@vsvamsi1 Is immer still required in dependencies ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I have left it in the devDependendices not in the dependencies because there were cypress testcases using it. This won't show up on the client prod build. I tried substituting them in the cypress testcases with mutative, however im seeing some errors accessing the mutative packages in cypress commands. I will reach out to @sagar-qa007 to help resolve this and remove them completely. This part of it can be resolved in a separate PR.

Copy link
Contributor

Choose a reason for hiding this comment

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

Sounds good. We can merge the changes for now. I have also added a backlog item for it here

What kind of error are we facing ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The mutative updates were getting ignored and all feature flag interception logic was not working. So all test cases are failing prematurely at the sidebar assertion itself. I thought it was headless chrome running these test cases does not support proxy, however the reducer updates using mutative were working. It seems specific cypress commands.
cc @sagar-qa007

Copy link
Contributor

@rajatagrawal rajatagrawal left a comment

Choose a reason for hiding this comment

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

Left comments

@vsvamsi1 vsvamsi1 requested a review from dvj1988 February 6, 2025 05:12
@vsvamsi1 vsvamsi1 enabled auto-merge (squash) February 6, 2025 05:17
@vsvamsi1 vsvamsi1 merged commit 2b9299e into release Feb 6, 2025
94 of 103 checks passed
@vsvamsi1 vsvamsi1 deleted the test61 branch February 6, 2025 05:50
github-actions bot pushed a commit to Zeral-Zhang/appsmith that referenced this pull request Feb 7, 2025
…sing mutative instead of immer (appsmithorg#38993)

## Description
- Using mutative instead of immer, this has reduced the main thread
scripting by about 1 second.
- Removed a cloneDeep during table onMount which saves about 70ms in
main thread scripting.
- Bypassed mutative when applying the first tree to reduce the overhead
associated to mutative.

Fixes #`Issue Number`  
_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.All"

### 🔍 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/13164792224>
> Commit: 4cb8217
> <a
href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=13164792224&attempt=2"
target="_blank">Cypress dashboard</a>.
> Tags: `@tag.All`
> Spec:
> <hr>Thu, 06 Feb 2025 04:21:41 UTC
<!-- end of auto-generated comment: Cypress test results  -->


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


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

- **New Dependency**
  - Integrated a new library to enhance overall state management.

- **Refactor**
- Updated state update mechanisms across interactive components and data
flows.
  - Improved table widget processing for more consistent behavior.

- **Chore**
  - Removed legacy development-only configuration settings.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@sentry
Copy link

sentry bot commented Feb 7, 2025

Suspect Issues

This pull request was deployed and Sentry observed the following issues:

  • ‼️ TypeError: Cannot set properties of null (setting '0') evaluatedTreeReducer(reducers/evaluationReducer... View Issue
  • ‼️ TypeError: Invalid attempt to iterate non-iterable instance. reducer(utils/ReducerUtils) View Issue
  • ‼️ Error: Only supports setting array indices and the 'length' property. evaluatedTreeReducer(reducers/evaluationReducer... View Issue
  • ‼️ Error: Only supports setting array indices and the 'length' property. proxyHandler.set(src/draft) View Issue
  • ‼️ Error: Only supports setting array indices and the 'length' property. proxyHandler.set(src/draft) View Issue

Did you find this useful? React with a 👍 or 👎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ok-to-test Required label for CI skip-changelog Adding this label to a PR prevents it from being listed in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants