Skip to content

Fix slowdown during historical sync because of tracking reorgs too early#626

Merged
DZakh merged 1 commit into
mainfrom
dz/fix-early-realtime-entry
Jul 7, 2025
Merged

Fix slowdown during historical sync because of tracking reorgs too early#626
DZakh merged 1 commit into
mainfrom
dz/fix-early-realtime-entry

Conversation

@DZakh

@DZakh DZakh commented Jul 7, 2025

Copy link
Copy Markdown
Member

Fixes the bug of entering realtime indexing mode too early for unordered multichain mode. In this mode, we start saving entity history to be able to rollback on reorg, which drastically slows down historical sync if enabled during historical sync.

The issue was caused by invalid logic for checking whether we entered the reorg threshold. For the unordered multichain mode, it checked only the chain we used for batch creation, which became a single chain at a time after https://github.com/enviodev/hyperindex/releases/tag/v2.22.0 - causing the perf regression as soon as one of the chains reaches the head.

In older version the bug also existed, but there was a much slower chance of triggering it - one chain should reach the head and have some events, while all the other chains shouldn't have events to process (fetching).

Summary by CodeRabbit

  • Refactor

    • Simplified internal logic for event selection and reorg threshold checks, leading to more streamlined control flow.
    • Removed or renamed several internal functions and types to reduce complexity and improve clarity.
  • Tests

    • Updated tests to align with renamed and refactored functions, simplifying assertions and improving readability.

@DZakh DZakh requested a review from moose-code July 7, 2025 13:13
@coderabbitai

coderabbitai Bot commented Jul 7, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change refactors event batching and selection logic in the ChainManager module by simplifying the retrieval of the next event and removing unnecessary pattern matching and intermediate functions. The test suite is updated to reflect these changes, and redundant or obsolete code is eliminated for clarity and maintainability.

Changes

File(s) Change Summary
codegenerator/cli/npm/envio/src/FetchState.res Simplified queueItemIsInReorgThreshold by removing unnecessary pattern matching.
codegenerator/cli/templates/static/codegen/src/eventFetching/ChainManager.res Removed priorityQueueComparitor, noActiveChains, and popOrderedBatchItem; replaced determineNextEvent with getOrderedNextItem; updated batching logic to use new function and explicit reorg threshold checks.
scenarios/test_codegen/test/ChainManager_test.res Updated tests to use getOrderedNextItem instead of determineNextEvent; simplified comparator access and result assertions.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ChainManager
    participant FetchState

    Client->>ChainManager: createOrderedBatch()
    ChainManager->>ChainManager: getOrderedNextItem(fetchStatesMap)
    ChainManager->>FetchState: Check reorg threshold for event
    alt Event within threshold
        ChainManager-->>Client: Add event to batch
    else Event outside threshold
        ChainManager-->>Client: Skip event
    end
Loading

Possibly related PRs

Suggested reviewers

  • JonoPrest

Poem

In the warren of code, we hop and we prune,
Old branches removed, new logic in tune.
No more tangled paths for events to be fetched,
The queue is now simple, the code neatly etched.
🐇✨ Onward we bound, with our functions refreshed!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9bb895c and 7f4ff3f.

📒 Files selected for processing (3)
  • codegenerator/cli/npm/envio/src/FetchState.res (1 hunks)
  • codegenerator/cli/templates/static/codegen/src/eventFetching/ChainManager.res (5 hunks)
  • scenarios/test_codegen/test/ChainManager_test.res (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.res`: Never use `[| item |]` to create an array. Use `[ item ]` instead. M...

**/*.res: Never use [| item |] to create an array. Use [ item ] instead.
Must always use = for setting value to a field. Use := only for ref values created using ref function.
It's also possible to define an inline object, it'll have quoted fields in this case.
Never use %raw to access object fields if you know the type.

📄 Source: CodeRabbit Inference Engine (.cursor/rules/rescript.mdc)

List of files the instruction was applied to:

  • scenarios/test_codegen/test/ChainManager_test.res
  • codegenerator/cli/npm/envio/src/FetchState.res
  • codegenerator/cli/templates/static/codegen/src/eventFetching/ChainManager.res
`**/*.{res,resi}`: ReScript has record types which require a type definition bef...

**/*.{res,resi}: ReScript has record types which require a type definition beforehand. You can access record fields by dot like foo.myField.
Use records when working with structured data, and objects to conveniently pass payload data between functions.

📄 Source: CodeRabbit Inference Engine (.cursor/rules/rescript.mdc)

List of files the instruction was applied to:

  • scenarios/test_codegen/test/ChainManager_test.res
  • codegenerator/cli/npm/envio/src/FetchState.res
  • codegenerator/cli/templates/static/codegen/src/eventFetching/ChainManager.res
🧠 Learnings (1)
scenarios/test_codegen/test/ChainManager_test.res (1)
Learnt from: JonoPrest
PR: enviodev/hyperindex#555
File: scenarios/test_codegen/test/lib_tests/EntityHistory_test.res:631-659
Timestamp: 2025-05-27T17:07:12.878Z
Learning: In isolated tests for EntityHistory rollbacks with controlled mock data setup, the ordering of getRollbackDiff results is deterministic and doesn't require sorting before comparison with deepStrictEqual.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build_and_test
🔇 Additional comments (10)
codegenerator/cli/npm/envio/src/FetchState.res (1)

896-906: LGTM! Good simplification of the reorg threshold check.

The removal of unnecessary pattern matching on queueItem improves readability while maintaining the same functionality. The direct return of the comparison result is cleaner and more straightforward.

scenarios/test_codegen/test/ChainManager_test.res (4)

179-180: Test updated correctly for public API access.

The change from ChainManager.ExposedForTesting_Hidden.getComparitorFromItem to ChainManager.getComparitorFromItem reflects that this function is now part of the public API rather than hidden for testing.


230-232: Test name and function call updated for API refactoring.

The test correctly reflects the function rename from determineNextEvent to getOrderedNextItem, maintaining consistency with the refactored ChainManager API.


322-327: Test expectations updated for option return type.

The test correctly expects a direct option type return from getOrderedNextItem_ordered instead of extracting earliestEvent from a result type. The test structure properly validates the new API.


362-367: Consistent test pattern for option type handling.

This test follows the same pattern as the previous one, correctly handling the option return type from getOrderedNextItem_ordered.

codegenerator/cli/templates/static/codegen/src/eventFetching/ChainManager.res (5)

52-73: Excellent simplification of event selection logic.

The new getOrderedNextItem function is much cleaner than the previous determineNextEvent:

  • Returns a simple option type instead of complex result types
  • Directly finds the earliest event among actively indexing chains
  • Eliminates unnecessary complexity while maintaining core functionality
  • Better aligns with the PR objective of fixing reorg threshold logic

This refactoring improves maintainability and readability significantly.


146-146: Function updated correctly for new API.

The nextItemIsNone function correctly uses getOrderedNextItem and checks for None, maintaining the same logical behavior with the simplified API.


154-207: Improved batch creation with explicit reorg threshold handling.

The refactored createOrderedBatch function demonstrates better separation of concerns:

  • Uses getOrderedNextItem for event selection
  • Performs reorg threshold checks explicitly using FetchState.queueItemIsInReorgThreshold
  • Removes embedded tracking logic in favor of clear, explicit checks
  • Maintains the same functionality while improving code clarity

This aligns well with the PR objective of fixing reorg threshold logic during historical sync.


247-252: Explicit reorg threshold check improves clarity.

The reorg threshold check is now explicit and clear, using FetchState.queueItemIsInReorgThreshold directly on the earliestEvent. This removes the previous embedded logic and makes the condition more transparent.


283-296: Correct reorg threshold determination for unordered mode.

The logic correctly determines reorg threshold status by:

  1. Using getOrderedNextItem to find the earliest event across all chains
  2. Checking that specific event's reorg threshold status
  3. Returning false when no chains are actively indexing

This approach ensures the reorg threshold check considers all chains properly, which directly addresses the performance issue described in the PR objectives.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@moose-code moose-code left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

lgtm!!! Really nice find

@DZakh DZakh merged commit 466948a into main Jul 7, 2025
2 checks passed
@DZakh DZakh deleted the dz/fix-early-realtime-entry branch July 7, 2025 13:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants