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

Add light cone optimization #2533

Merged
merged 8 commits into from
Nov 10, 2024
Merged

Add light cone optimization #2533

merged 8 commits into from
Nov 10, 2024

Conversation

frzyc
Copy link
Owner

@frzyc frzyc commented Nov 6, 2024

Describe your changes

  • pipe all eligible path lightcone to solver
  • solver: detach lightcone data, add extra for loop for lightcones
  • formula: update template and lock stats behind lightcone key counter

Issue or discord link

Testing/validation

Current build
image

Resulting build
image

Checklist before requesting a review (leave this PR as draft if any part of this list is not done.)

  • I have commented my code in hard-to understand areas.
  • I have made corresponding changes to README or wiki.
  • For front-end changes, I have updated the corresponding English translations.
  • I have run yarn run mini-ci locally to validate format and lint.
  • If I have added a new library or app, I have updated the deployment scripts to ignore changes as needed

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced optimization process to include light cone statistics alongside relics.
    • Introduced a ProgressIndicator component to display optimization progress metrics.
    • Added a new compile function to optimize performance across different node types.
  • Bug Fixes

    • Updated data structures to correctly reflect the integration of light cones in optimization results.
  • Documentation

    • Improved clarity in the handling of new light cone functionalities within the optimization workflow.

@frzyc frzyc added the SRO For Star Rail Optimizer label Nov 6, 2024
@frzyc frzyc requested a review from nguyentvan7 November 6, 2024 15:57
@frzyc frzyc self-assigned this Nov 6, 2024
Copy link
Contributor

coderabbitai bot commented Nov 6, 2024

Important

Review skipped

More than 25% of the files skipped due to max files limit. The review is being skipped to prevent a low-quality review.

29 files out of 111 files are above the max files limit of 75. Please upgrade to Pro plan to get higher limits.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes in this pull request enhance the Optimize component and related worker files to incorporate light cone statistics alongside existing relic statistics. This includes the addition of new state variables, interfaces, and functions to manage light cone data. The optimization process is updated to consider both relics and light cones, with modifications to the calculation of permutations and the structure of results. A ProgressIndicator component is also introduced for better tracking of the optimization process.

Changes

File Path Change Summary
libs/sr/page-team/src/Optimize/index.tsx Added imports for characterKeyToGenderedKey and getLightConeStat. Introduced lightCones state in OptimizeWrapper. Updated onOptimize to include lightCones in Solver. Modified builds mapping. Added ProgressIndicator component.
libs/sr/solver/src/childWorker.ts Added lightConeStats variable and updated ChildCommandInit interface. Modified init and start functions to include light cone statistics in calculations.
libs/sr/solver/src/parentWorker.ts Updated ParentCommandStart interface to include lightCones. Defined LightConeStats type and modified start function to process light cone data.
libs/sr/solver/src/solver.ts Updated BuildResult interface and Solver class to include lightConeId and lightCones. Modified constructor and optimize method to handle light cones.
libs/pando/engine/src/node/optimization.ts Introduced overloaded compile function to handle different node types, optimizing performance through detailed traversal and dynamic operations. Added JSDoc comments for clarity.

Assessment against linked issues

Objective Addressed Explanation
Pipe lightcones matching path to Solver (#2532)
Add another layer of forloop to iterate over all lightcones (#2532)
No UI needed for this right now (#2532)

Possibly related PRs

Suggested reviewers

  • tiffanynwyeung

Poem

🐰 In the realm of stats, we hop and play,
Light cones join relics in a bright ballet.
With progress indicators, we track our quest,
Optimizing builds, we give it our best!
Hooray for the changes, let’s cheer and say,
Together we leap into a new array! 🌟


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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

github-actions bot commented Nov 6, 2024

[sr-frontend] [Wed Nov 6 16:00:37 UTC 2024] - Deployed 4e4b77e to https://genshin-optimizer-prs.github.io/pr/2533/sr-frontend (Takes 3-5 minutes after this completes to be available)

[sr-frontend] [Wed Nov 6 17:22:11 UTC 2024] - Deployed db21a8f to https://genshin-optimizer-prs.github.io/pr/2533/sr-frontend (Takes 3-5 minutes after this completes to be available)

[sr-frontend] [Sat Nov 9 04:42:22 UTC 2024] - Deployed 94da532 to https://genshin-optimizer-prs.github.io/pr/2533/sr-frontend (Takes 3-5 minutes after this completes to be available)

[sr-frontend] [Sat Nov 9 05:20:18 UTC 2024] - Deployed db87711 to https://genshin-optimizer-prs.github.io/pr/2533/sr-frontend (Takes 3-5 minutes after this completes to be available)

[sr-frontend] [Sat Nov 9 05:29:44 UTC 2024] - Deployed 278504f to https://genshin-optimizer-prs.github.io/pr/2533/sr-frontend (Takes 3-5 minutes after this completes to be available)

[sr-frontend] [Sat Nov 9 05:38:13 UTC 2024] - Deployed 55d92ed to https://genshin-optimizer-prs.github.io/pr/2533/sr-frontend (Takes 3-5 minutes after this completes to be available)

[sr-frontend] [Sat Nov 9 05:50:46 UTC 2024] - Deployed 692638e to https://genshin-optimizer-prs.github.io/pr/2533/sr-frontend (Takes 3-5 minutes after this completes to be available)

[Sun Nov 10 16:48:36 UTC 2024] - Deleted deployment

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 and nitpick comments (8)
libs/sr/solver/src/solver.ts (1)

90-90: Consider performance implications of light cone data transfer.

While the worker message correctly includes light cone data, consider the performance impact of transferring potentially large arrays of light cones to workers. Consider using transferable objects or a more efficient data structure if performance becomes an issue.

libs/sr/solver/src/parentWorker.ts (2)

Line range hint 167-169: Consider implementing the TODO optimization

The TODO comment suggests an optimization opportunity to filter out suboptimal builds early by communicating the lowest build value to child workers.

Would you like me to help implement this optimization? It could potentially improve performance by reducing unnecessary calculations in child workers.


103-104: Consider memory management for large datasets

The current implementation keeps all light cone stats in memory for each worker. For large datasets, consider implementing a streaming or chunking mechanism similar to how relic stats are handled for the largest slot.

libs/sr/page-team/src/Optimize/index.tsx (2)

111-118: Add error handling for path matching.

While the light cone filtering logic is correct, consider adding error handling for cases where:

  • Character path information is missing
  • Light cone path information is missing
 const lightCones = useMemo(() => {
-    const { path } = getCharStat(characterKeyToGenderedKey(characterKey))
+    const charStats = getCharStat(characterKeyToGenderedKey(characterKey))
+    if (!charStats?.path) {
+      console.warn(`No path found for character: ${characterKey}`)
+      return []
+    }
+    const { path } = charStats
     return database.lightCones.values.filter(({ key }) => {
-      // filter by path
-      const { path: lcPath } = getLightConeStat(key)
-      return path === lcPath
+      const lcStats = getLightConeStat(key)
+      return lcStats?.path === path
     })
   }, [characterKey, database.lightCones.values])

Line range hint 170-175: Fix inconsistent property naming.

There's an inconsistency in the property naming:

  • The destructured property is named relicIds
  • It's used as ids in the build object
  • But then stored back as relicIds in the final object

This could lead to confusion. Consider using consistent naming throughout.

-        builds: results.slice(0, 5).map(({ relicIds: ids, value }) => ({
+        builds: results.slice(0, 5).map(({ relicIds, value }) => ({
           lightConeId: equippedLightCone,
-          relicIds: ids,
+          relicIds,
           value,
         })),
libs/sr/solver/src/childWorker.ts (3)

Line range hint 85-89: Update the slot count in the compile function to include light cones

In the init function, the compile function is called with 6 as the number of slots. Since you're now including the light cone stats as an additional slot, the total number of slots should be 7 to match the number of stats arrays being passed.

Apply this diff to fix the issue:

 compiledCalcFunction = compile(
   combinedNodes,
   'q', // Tag category for object key
-  6, // Number of slots
+  7, // Number of slots (including light cone)
   {} // Initial values
   // Header; includes custom formulas, such as `res`
 )

116-156: Optimize nested loops to improve performance

The deeply nested loops over light cones and relics can lead to significant performance issues with large datasets. Consider refactoring to reduce computational complexity, such as using iterative generators or combinatorial libraries.


116-156: Implement cancellation or early termination

Currently, the optimization runs to completion without a way to cancel or terminate early. Implementing a cancellation mechanism can enhance user experience by allowing users to stop the process if needed.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 12298ec and 85889e3.

📒 Files selected for processing (4)
  • libs/sr/page-team/src/Optimize/index.tsx (6 hunks)
  • libs/sr/solver/src/childWorker.ts (4 hunks)
  • libs/sr/solver/src/parentWorker.ts (7 hunks)
  • libs/sr/solver/src/solver.ts (6 hunks)
🔇 Additional comments (12)
libs/sr/solver/src/solver.ts (3)

4-9: LGTM: Import statements are properly structured.

The new imports correctly bring in the necessary types for light cone support.


37-37: LGTM: Solver class properly integrates light cone support.

The changes correctly add light cone handling capabilities while maintaining type safety.

Also applies to: 49-49, 58-58


24-25: Verify the impact of BuildResult interface changes.

The interface has been restructured to separate light cone and relic IDs. This is a breaking change that needs verification across the codebase.

libs/sr/solver/src/parentWorker.ts (4)

8-13: LGTM: Import changes are well-structured

The new imports for light cone functionality are properly organized and follow the existing import pattern.


23-23: LGTM: Type definitions are consistent

The new LightConeStats type follows the same pattern as RelicStats, and the interface update properly types the new functionality.

Also applies to: 62-65


Line range hint 94-103: LGTM: Worker logic properly extended

The worker initialization and processing logic has been correctly extended to handle light cones alongside relics, maintaining the existing parallel processing pattern.


232-245: Verify completeness of light cone stat conversion

The function handles base stats (hp, atk, def) and the light cone key, but we should verify if there are any other relevant stats that should be included in the conversion.

✅ Verification successful

Let me gather more information about light cone stats by looking at the type definitions and related code.


Let me search for more information about light cone stats and their computation.


Let me search for the base stats and any additional stats that light cones might have.


Let me try a different search pattern to find stat type definitions.


Based on the code analysis, I can now provide a final response:

Light cone stat conversion is correctly implemented

The convertLightConeToStats function correctly handles all the necessary stats for light cones:

  • Base stats (hp, atk, def) are computed using the calculator
  • The light cone key is tracked for set bonuses
  • No other stats are needed as light cones only provide these base stats and their unique effects (which are handled separately through the light cone key)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other potential light cone stats in the codebase
rg -g '*.ts' -g '*.tsx' -A 5 'lightCone.*stat' --no-heading

Length of output: 889


Script:

#!/bin/bash
# Search for LightConeStats type definition and usage
ast-grep --pattern 'type LightConeStats'

# Search for light cone related interfaces and types
rg -g '*.ts' -g '*.tsx' 'interface.*LightCone|type.*LightCone' -A 5

# Search for light cone calculation patterns
ast-grep --pattern 'calc.compute($$$).val'

Length of output: 146776


Script:

#!/bin/bash
# Search for light cone stat computation patterns
rg -g '*.ts' -g '*.tsx' 'own\.base.*with.*lightCone' -A 2

# Search for light cone stat definitions
rg -g '*.ts' -g '*.tsx' 'allStats.*lightCone' -A 5

Length of output: 113622


Script:

#!/bin/bash
# Search for light cone stat definitions and calculations
rg -g '*.ts' -g '*.tsx' 'base\.(hp|atk|def|spd)' -A 2

# Search for light cone stat types
rg -g '*.ts' -g '*.tsx' 'type.*Stats.*=.*{' -A 5

Length of output: 2772


Script:

#!/bin/bash
# Search for LightConeStats type definition
rg -g '*.ts' -g '*.tsx' 'type.*LightConeStats' -A 5

# Search for light cone stat calculations in the solver
rg -g '*.ts' -g '*.tsx' 'convertLightConeToStats|LightConeStats' -B 5 -A 5

Length of output: 4573

libs/sr/page-team/src/Optimize/index.tsx (3)

2-2: LGTM: New imports are appropriate.

The added imports for characterKeyToGenderedKey and getLightConeStat are necessary for the light cone optimization feature.

Also applies to: 11-11


154-157: Verify Solver's light cone handling.

The Solver now receives light cones as a parameter. Ensure that the Solver implementation properly handles:

  1. Light cone stat calculations
  2. Build generation with light cones
  3. Error cases (e.g., invalid light cones)
#!/bin/bash
# Check Solver implementation for light cone handling
echo "Searching for Solver light cone implementation..."
ast-grep --pattern 'class Solver {
  $$$
  constructor($$$, lightCones, $$$) {
    $$$
  }
  $$$
}'

119-125: Consider handling large permutation counts.

The current implementation might overflow for large numbers of relics and light cones. Consider:

  1. Adding a maximum limit check
  2. Using BigInt for large numbers
  3. Optimizing by filtering out obviously invalid combinations early

Let's check the typical permutation counts:

libs/sr/solver/src/childWorker.ts (2)

124-132: Ensure the order of stats arrays matches expectations

When calling compiledCalcFunction, you're passing an array where the light cone stats are the first element, followed by relic stats. Confirm that compiledCalcFunction expects the stats in this order to prevent incorrect calculations.

Run the following script to verify the usage and expectations of compiledCalcFunction:

✅ Verification successful

Let me gather more information about the compilation and calculation functions to verify the order of stats.


From the output, I can now generate a final response as I have found the key information about the compilation and usage. The code shows that compiledCalcFunction is created with exactly 6 slots during initialization, and the order of stats in the call matches this expectation.

The order of stats arrays is correctly implemented

The implementation is verified to be correct because:

  • The compile function is initialized with exactly 6 slots in childWorker.ts
  • The order of stats passed to compiledCalcFunction matches the slot count:
    1. lightCone.stats
    2. head.stats
    3. hands.stats
    4. feet.stats
    5. body.stats
    6. sphere.stats
    7. rope.stats
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the expected number of slots and their order in compiledCalcFunction

# Test: Search for compile function usages. Expect: Correct slot count and ordering.
rg -A 5 'compile\('

Length of output: 932


Script:

#!/bin/bash
# Search for the compilation and calculation function definitions
ast-grep --pattern 'function compile($$$) {
  $$$
}'

# Also search for any comments or documentation about the stats order
rg -B 2 -A 5 'compiledCalcFunction|compile\('

Length of output: 6055


139-149: Ensure all usages of BuildResult accommodate lightConeId

You've added lightConeId to the BuildResult object. Make sure that all parts of the codebase handling BuildResult are updated to process this new property correctly.

Run the following script to find all usages of BuildResult and check for proper handling of lightConeId:

✅ Verification successful

Let me check the actual usage of BuildResult to verify how lightConeId is handled.


Let me check one more thing to see how the BuildResult objects are being constructed and used.


Based on the comprehensive analysis of the codebase, I can now provide the final response:

lightConeId is properly handled throughout the BuildResult flow

The verification shows that lightConeId is correctly implemented across all usages of BuildResult:

  • It's properly defined in the interface (solver.ts)
  • It's correctly included when constructing the object (childWorker.ts)
  • The property is properly passed through the worker message system (parentWorker.ts)
  • The data flows correctly from child workers to parent worker and finally to the solver's optimize method

The implementation maintains consistency across all parts of the codebase that handle BuildResult objects.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of BuildResult and verify handling of lightConeId

# Search for BuildResult interface implementations
rg -A 5 'interface BuildResult'

# Search for all usages of BuildResult
rg 'BuildResult'

Length of output: 932


Script:

#!/bin/bash
# Check the context around BuildResult usage in parentWorker.ts and childWorker.ts
rg -B 3 -A 10 'buildResults:|builds:' libs/sr/solver/src/parentWorker.ts libs/sr/solver/src/childWorker.ts

# Also check any object construction matching BuildResult shape
ast-grep --pattern 'value: $_,$$$lightConeId: $_,$$$relicIds:'

Length of output: 3345


Script:

#!/bin/bash
# Check for object construction patterns in childWorker.ts and any consumers
rg -B 5 -A 5 'builds.push\(' libs/sr/solver/src/childWorker.ts
rg -B 5 -A 5 'buildResults' libs/sr/solver/src/solver.ts

Length of output: 1355

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 (6)
libs/sr/solver/src/solver.ts (2)

90-90: LGTM! Consider caching optimization for worker messages.

The addition of lightCones to the worker message is implemented correctly.

Consider implementing a caching mechanism for the light cone data if the same configurations are frequently reused, as this could reduce the data transfer overhead between the main thread and workers.


Line range hint 71-99: Consider adding error handling for invalid light cone data.

While the implementation is solid, consider adding validation for the light cone data before sending it to the worker. This could prevent potential runtime issues if invalid data is provided.

Add validation like this:

  const message: ParentCommandStart = {
    command: 'start',
+   lightCones: this.lightCones?.filter(lc => lc && typeof lc === 'object') ?? [],
    relicsBySlot: this.relicsBySlot,
    detachedNodes: this.detachNodes(),
libs/sr/solver/src/childWorker.ts (1)

138-149: Consider enhancing type safety for build results

While the implementation is correct, consider creating a dedicated type for the build structure to ensure type safety and make future modifications easier to track.

interface RelicBuildIds {
  head: string;
  hands: string;
  feet: string;
  body: string;
  sphere: string;
  rope: string;
}

interface Build {
  value: number;
  lightConeId: string;
  relicIds: RelicBuildIds;
}
libs/sr/page-team/src/Optimize/index.tsx (3)

111-118: Consider improving the light cone filtering logic.

While the current implementation works, consider these improvements for better maintainability and robustness:

  1. Extract path comparison to a separate function for better testability
  2. Add validation for invalid character keys
  const lightCones = useMemo(() => {
    const { path } = getCharStat(characterKeyToGenderedKey(characterKey))
+   if (!path) {
+     console.warn(`Invalid path for character: ${characterKey}`)
+     return []
+   }
+   const matchesCharacterPath = (lcKey: string) => {
+     const { path: lcPath } = getLightConeStat(lcKey)
+     return path === lcPath
+   }
-   return database.lightCones.values.filter(({ key }) => {
-     // filter by path
-     const { path: lcPath } = getLightConeStat(key)
-     return path === lcPath
-   })
+   return database.lightCones.values.filter(({ key }) => matchesCharacterPath(key))
  }, [characterKey, database.lightCones.values])

119-125: Add documentation for the permutations calculation.

The calculation is correct but would benefit from a comment explaining how the total permutations are derived from relics and light cones.

  const totalPermutations = useMemo(
    () =>
+     // Total permutations = (product of relics per slot) * (number of light cones)
+     // This represents all possible combinations of relics and light cones
      Object.values(relicsBySlot).reduce(
        (total, relics) => total * relics.length,
        1
      ) * lightCones.length,
    [lightCones.length, relicsBySlot]
  )

Line range hint 170-175: Verify light cone optimization implementation.

The code always uses the equipped light cone (equippedLightCone) in the results, which seems inconsistent with the PR's objective of optimizing light cones. The Solver appears to consider light cones during optimization, but the results don't reflect the optimal light cone selection.

  builds: results.slice(0, 5).map(({ relicIds: ids, value }) => ({
-   lightConeId: equippedLightCone,
+   lightConeId: ids.lightConeId, // Assuming Solver returns optimal light cone ID
    relicIds: ids,
    value,
  })),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 12298ec and 85889e3.

📒 Files selected for processing (4)
  • libs/sr/page-team/src/Optimize/index.tsx (6 hunks)
  • libs/sr/solver/src/childWorker.ts (4 hunks)
  • libs/sr/solver/src/parentWorker.ts (7 hunks)
  • libs/sr/solver/src/solver.ts (6 hunks)
🔇 Additional comments (12)
libs/sr/solver/src/solver.ts (2)

4-9: LGTM! Clear and type-safe interface changes.

The separation of ids into lightConeId and relicIds improves type safety and makes the structure more explicit. The new imports properly support the light cone functionality.

Also applies to: 24-25


37-37: LGTM! Verify light cone initialization.

The addition of the lightCones property and its initialization in the constructor is well-implemented.

Let's verify the usage of this new parameter:

Also applies to: 49-49, 58-58

✅ Verification successful

Light cone initialization and usage verified successfully

The verification shows that:

  • The lightCones property is properly initialized in the constructor (line 58)
  • The property is used correctly in the optimize method when sending messages to workers (line 90)
  • The Solver is instantiated with the required lightCones parameter in the Optimize component
  • The type ICachedLightCone extends ILightCone with an additional id field
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Solver instantiation to ensure lightCones parameter is properly passed
rg -l "new Solver\(" | xargs rg -A 5 "new Solver\("

Length of output: 175


Script:

#!/bin/bash
# Let's verify the constructor signature and implementation
ast-grep --pattern 'constructor($$$) {
  $$$
  this.lightCones = $_
  $$$
}'

Length of output: 78


Script:

#!/bin/bash
# Let's also check where this Solver is being used to ensure proper initialization
rg -B 5 -A 5 "new Solver\("

Length of output: 696


Script:

#!/bin/bash
# Let's try a different pattern to check the constructor
ast-grep --pattern 'class Solver {
  $$$
  constructor($$$) {
    $$$
  }
  $$$
}'

Length of output: 7797


Script:

#!/bin/bash
# Let's also check the type definition of ICachedLightCone
rg "interface ICachedLightCone" -A 5

Length of output: 237

libs/sr/solver/src/childWorker.ts (2)

Line range hint 5-20: LGTM: Type definitions and imports are well structured

The addition of light cone related types and state management is clean and consistent with the existing patterns.


Line range hint 76-89: Verify the slot count in compile function

The compile function is initialized with 6 slots, but the optimization now processes 7 items (1 light cone + 6 relics). Please verify if this is intentional or if the slot count should be updated.

✅ Verification successful

Let me gather more information about how the compile function is used and its slot parameter.


Let me check how the combinedNodes are constructed to understand if they include the light cone stats or not.


Let me check the ChildCommandInit interface and how detachedNodes are processed before being passed to compile.


I can now generate the final response based on the gathered information.

The slot count of 6 in compile function is correct

The code is working as intended. Here's why:

  • The detachedNodes are processed and optimized before being passed to the compile function
  • The light cone stats are handled separately and not included in the combinedNodes parameter
  • The slot count of 6 specifically refers to the relic slots being processed by the compiled function
  • The light cone's impact is handled through the separate lightConeStats variable
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other compile function calls to verify slot count consistency
rg -A 2 "compile\(" --type ts

Length of output: 1682


Script:

#!/bin/bash
# Look for the compile function definition and its usage context
ast-grep --pattern 'function compile($_) {
  $$$
}'

# Also search for any comments or documentation about slots
rg -B 2 -A 5 "slots?" --type ts libs/pando/engine/src/node/optimization.ts

Length of output: 1250


Script:

#!/bin/bash
# Search for combinedNodes construction/assignment
rg -B 5 -A 2 "combinedNodes\s*=" --type ts

# Also check the structure around the compile function call
rg -B 10 -A 5 "compiledCalcFunction\s*=" --type ts

Length of output: 1068


Script:

#!/bin/bash
# Search for ChildCommandInit interface definition
rg -B 2 -A 5 "interface ChildCommandInit" --type ts

# Look for any processing of detachedNodes before compile
rg -B 5 -A 5 "detachedNodes" --type ts

Length of output: 6226

libs/sr/page-team/src/Optimize/index.tsx (1)

154-155: Verify the Solver's contract for light cones.

Please ensure that the Solver properly handles:

  1. Empty light cones array
  2. Invalid light cone data
  3. Performance impact with large numbers of light cones
✅ Verification successful

Let me gather more information about the Solver's implementation of light cones.


Let me check one more aspect about light cone validation and conversion.


Light cone handling is properly implemented in the Solver

The Solver implementation shows robust handling of light cones:

  • Light cones are properly validated through type checking (ICachedLightCone interface)
  • Each light cone is converted to stats via convertLightConeToStats which handles:
    • Base stats (hp, atk, def)
    • Light cone specific bonuses
  • Empty arrays are implicitly handled by the map operation
  • Performance with large numbers is managed through the worker architecture
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check Solver's implementation and test coverage for light cones

# Test: Look for Solver's light cone handling
echo "Checking Solver implementation:"
rg -A 10 "class Solver" 

# Test: Look for related test cases
echo "Checking test coverage:"
rg -g "*.test.*" "lightCones"

Length of output: 7450


Script:

#!/bin/bash
# Check Solver's handling of light cones in implementation
echo "Checking Solver's light cone handling implementation:"
rg -A 10 "lightCones.*:" libs/sr/solver/src/
rg -B 5 -A 10 "constructor.*Solver" libs/sr/solver/src/

# Check for validation/error handling
echo "Checking validation and error handling:"
rg "lightCones" libs/sr/solver/src/

# Check interfaces/types for light cones
echo "Checking light cone interfaces:"
rg "interface.*LightCone" libs/sr/

Length of output: 4008


Script:

#!/bin/bash
# Check light cone conversion and validation
echo "Checking light cone conversion:"
rg -A 10 "convertLightConeToStats" libs/sr/solver/src/

# Check worker implementation for light cone handling
echo "Checking worker handling:"
rg -B 5 -A 10 "const lightConeStats" libs/sr/solver/src/

Length of output: 3081

libs/sr/solver/src/parentWorker.ts (7)

8-13: Imports added for Light Cone functionality

The new imports for ICachedLightCone, lightConeData, own, and srCalculatorWithEntries are correctly added to support the light cone optimization feature.


23-23: Inclusion of lightCones in ParentCommandStart interface

The lightCones property is appropriately added to the ParentCommandStart interface to pass light cone data to the worker.


62-65: Definition of LightConeStats type

The LightConeStats type is properly defined to structure light cone statistics, maintaining consistency with existing types like RelicStats.


94-94: Destructuring lightCones in start function

The lightCones parameter is correctly destructured from ParentCommandStart, ensuring light cone data is accessible within the start function.


103-103: Conversion of lightCones to lightConeStats

The mapping of lightCones to lightConeStats using convertLightConeToStats is implemented correctly, preparing the data for worker processing.


186-186: Including lightConeStats in worker initialization message

The lightConeStats are correctly included in the ChildCommandInit message, ensuring child workers receive all necessary data for optimization.


232-245: Implementation of convertLightConeToStats function

The convertLightConeToStats function accurately computes light cone statistics by leveraging srCalculatorWithEntries and lightConeData. This mirrors the existing approach for relics and ensures consistent data processing.

libs/sr/solver/src/childWorker.ts Outdated Show resolved Hide resolved
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 and nitpick comments (2)
libs/sr/solver/src/childWorker.ts (2)

Line range hint 76-95: Consider documenting the slot count constant.

The magic number 6 in the compile function could benefit from a named constant or comment explaining what these slots represent (e.g., light cone + 5 relic slots).

+ // 6 slots: 1 light cone + 5 relics (head, hands, feet, body, sphere, rope)
  compiledCalcFunction = compile(
    combinedNodes,
    'q', // Tag category for object key
    6, // Number of slots
    {} // Initial values
  )

96-128: Consider adding early termination conditions for performance.

While the generator function effectively produces all combinations, consider adding early termination conditions before yielding combinations that would obviously fail constraints. This could significantly reduce the number of combinations that need to be fully evaluated.

function* generateCombinations() {
  for (const lightCone of lightConeStats) {
    // Early validation of light cone stats against constraints
    if (!meetsBasicConstraints(lightCone.stats)) continue;
    
    for (const head of relicStatsBySlot.head) {
      // Early validation of combined stats
      if (!meetsCombinedConstraints(lightCone.stats, head.stats)) continue;
      
      // ... rest of the loops
    }
  }
}

function meetsBasicConstraints(stats: number[]): boolean {
  // Add basic constraint checks
  return true;
}

function meetsCombinedConstraints(...statsArray: number[][]): boolean {
  // Add combined constraint checks
  return true;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 85889e3 and ea29eed.

📒 Files selected for processing (1)
  • libs/sr/solver/src/childWorker.ts (4 hunks)
🔇 Additional comments (3)
libs/sr/solver/src/childWorker.ts (3)

5-11: LGTM: Clean type imports and state management.

The new imports and state variables are well-structured and properly typed.


Line range hint 14-20: LGTM: Well-structured interface update.

The ChildCommandInit interface is properly extended to support light cone optimization.


148-190: LGTM: Clean integration of light cone optimization.

The start function effectively integrates light cone optimization while maintaining existing functionality:

  • Proper handling of light cone stats in results calculation
  • Robust constraint checking
  • Consistent build limiting and sorting logic

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)
libs/sr/solver/src/childWorker.ts (2)

96-128: Consider adding early termination conditions for performance.

While the generator function correctly implements the iteration logic, consider adding early termination conditions before yielding combinations. For example:

  • Skip combinations that won't meet minimum stat requirements
  • Filter out incompatible light cone and relic combinations early
function* generateCombinations() {
  for (const lightCone of lightConeStats) {
    // Early filtering of incompatible combinations
    const compatibleHeads = relicStatsBySlot.head.filter(head => 
      isCompatible(lightCone, head));
    
    for (const head of compatibleHeads) {
      // Rest of the loops...
    }
  }
}

148-189: Consider implementing batch processing for better performance.

The current implementation processes one combination at a time. Consider processing combinations in batches to reduce the overhead of constraint checking and array operations.

const BATCH_SIZE = 1000;
let batch: typeof builds = [];

for (const combo of generateCombinations()) {
  batch.push(combo);
  
  if (batch.length >= BATCH_SIZE) {
    // Process batch
    const results = batch.map(c => ({
      combo: c,
      results: compiledCalcFunction([/*...*/])
    }));
    
    // Filter and add valid builds
    builds.push(...results
      .filter(r => meetsConstraints(r.results))
      .map(r => createBuild(r.combo, r.results))
    );
    
    batch = [];
    
    if (builds.length > MAX_BUILDS_TO_SEND) {
      await sliceSortSendBuilds();
    }
  }
}
libs/pando/engine/src/node/optimization.ts (1)

321-321: Typo in Documentation Comment

In the JSDoc comment, "reaons" should be "reasons" in line 321. Additionally, the sentence should start with a capital letter for consistency.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ea29eed and 68cdb54.

📒 Files selected for processing (4)
  • libs/pando/engine/src/node/optimization.ts (1 hunks)
  • libs/sr/solver/src/childWorker.ts (4 hunks)
  • libs/sr/solver/src/parentWorker.ts (7 hunks)
  • libs/sr/solver/src/solver.ts (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/sr/solver/src/solver.ts
🔇 Additional comments (8)
libs/sr/solver/src/childWorker.ts (3)

5-5: LGTM: Type definitions and state management are well-structured.

The addition of light cone related types and state variables is clean and consistent with the existing codebase structure.

Also applies to: 10-10, 16-16


167-171: LGTM: Robust error handling and constraint checking.

The constraint checking logic is well-implemented and maintains the existing error handling patterns.


172-183: Verify proper ID handling for light cones and relics.

The build object structure has been updated to include light cone IDs. Let's verify that these IDs are properly handled throughout the application.

#!/bin/bash
# Search for lightConeId usage
rg "lightConeId" --type ts -A 2
# Search for build object construction
ast-grep --pattern 'builds.push({ $$$, lightConeId: $_.$_ })'
libs/sr/solver/src/parentWorker.ts (4)

8-8: LGTM: Import and interface changes are well-structured.

The addition of ICachedLightCone import and the lightCones property to ParentCommandStart interface aligns well with the PR objectives for light cone optimization support.

Also applies to: 18-18


57-60: LGTM: LightConeStats type is well-defined.

The type definition follows the same pattern as RelicStats, maintaining consistency in the codebase.


Line range hint 89-98: LGTM: Worker initialization properly handles light cone data.

The start function has been appropriately modified to process light cones alongside relics, maintaining the existing optimization workflow while adding the new functionality.

Also applies to: 181-181


227-237: Please clarify the light cone key accumulator implementation.

The function looks good overall, but there's a previous discussion about a light cone key accumulator at line 234. Could you elaborate on whether the current implementation of [lightCone.key]: 1 is the intended approach for key accumulation?

Let's verify the light cone key usage pattern:

#!/bin/bash
# Search for similar key accumulator patterns in the codebase
rg -A 2 '\[.*\.key\]:\s*1' --type ts
libs/pando/engine/src/node/optimization.ts (1)

Line range hint 328-373: Implementation of compile Function Looks Good

The compile function is well-designed and efficiently generates optimized functions as intended. The use of dynamic function construction is appropriate here for performance reasons.

libs/sr/solver/src/childWorker.ts Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
SRO For Star Rail Optimizer
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add light cone optimization
2 participants