Skip to content

Conversation

keshavsaharia
Copy link
Contributor

@keshavsaharia keshavsaharia commented May 14, 2025

Issues:

Dependencies

  • Upstream: None
  • Downstream: None

Description

Simple fix to improve latency of searching large bundles - thanks to @lucasdellabella's brilliant help, we were able to profile this with 0x and found this performance improvement almost by accident.

It seems like the aggregation of missingReferences was actually the bottleneck - by switching to using a Set, we eliminated some interesting VM behavior and improved performance by around 70x for some large bundles we tested.

Testing

The Set is only being used locally within the function. We tested the performance improvement by loading some large bundles and running the test script (see commits) that counts references.

Screenshot 2025-05-14 at 6 13 56 PM

…rely on regex matching

metriport/metriport-internal#1040

refs. ENG-279

Signed-off-by: Keshav Saharia <keshav@metriport.com>
Copy link

linear bot commented May 14, 2025

Copy link

coderabbitai bot commented May 14, 2025

Walkthrough

The getReferencesFromResources function was updated to use a Set for storing resource IDs, improving lookup efficiency by replacing array includes checks with Set.has. Additionally, a blank line was added in the getReferences function, but this does not affect functionality or control flow.

Changes

File Change Summary
packages/core/src/external/fhir/shared/bundle.ts Updated getReferencesFromResources to use a Set for resource IDs and replaced includes with has; added a blank line in getReferences (no functional impact).

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant BundleUtils

    Caller->>BundleUtils: getReferencesFromResources(resources)
    BundleUtils->>BundleUtils: Store resource IDs in Set
    BundleUtils->>BundleUtils: Check references using Set.has
    BundleUtils-->>Caller: Return missing references
Loading

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c236e5 and 891ca5a.

📒 Files selected for processing (1)
  • packages/core/src/external/fhir/shared/bundle.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/external/fhir/shared/bundle.ts

🪧 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 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.

metriport/metriport-internal#1040

refs. ENG-279

Signed-off-by: Keshav Saharia <keshav@metriport.com>
… data

metriport/metriport-internal#1040

refs. ENG-279

Signed-off-by: Keshav Saharia <keshav@metriport.com>
@keshavsaharia
Copy link
Contributor Author

To check if this is a valid premise (that JSON.stringify + regex is slower than a recursive object search) I added the following test but surprisingly this didn't work for the simple object I tested, likely because there are a lot of references.

a696674

Will try again tomorrow with real data to compare the timing, but it seems like both methods are functionally the same for finding reference strings.

@keshavsaharia keshavsaharia changed the title fix(core): iterate recursively through JavaScript object rather than rely on regex matching fix(core): simple fix for timeout of FHIR reference extraction May 15, 2025
@keshavsaharia
Copy link
Contributor Author

Thanks to @lucasdellabella I learned how to use 0x today - after over a decade of calling myself a Node.js developer, I just ran a Node profiler for the first time 😎

Screenshot 2025-05-14 at 6 13 56 PM

It turns out that the bottleneck wasn't in JSON.stringify at all, but rather by repeatedly calling Array.includes with a large array of strings (~20k - 50k strings for large bundles). This was causing the internal JavaScript VM to start thrashing, which was super interesting.

In any case, this should speed up some resource ID extraction considerably (around 70x when we ran it on my laptop). I left the original JSON.stringify implementation in place so as to make the minimal code change possible to fix the ticket, but also left my deep search algorithm with test cases in case someone wants to optimize it further by incorporating the FHIR schemas for each resource type. That is, only recursively check down the path for a nested object if there is definitely something in the schema along that path which might have a reference string.

@keshavsaharia keshavsaharia marked this pull request as ready for review May 15, 2025 01:17
Copy link

@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

🧹 Nitpick comments (1)
packages/core/src/external/fhir/shared/__tests__/deep-search.test.ts (1)

51-66: Comprehensive edge case testing.

Great job testing the function with various edge cases including empty objects and non-plain objects like Date, Map, Set, Error, RegExp, and Promise. This ensures robustness in production scenarios.

-    expect(deepSearchObjectForString(new RegExp(""), "reference")).toEqual([]);
+    expect(deepSearchObjectForString(/(?:)/, "reference")).toEqual([]);

Use a regular expression literal instead of the RegExp constructor, which avoids some escaping required in string literals and is easier to analyze statically.

🧰 Tools
🪛 Biome (1.9.4)

[error] 57-57: Use a regular expression literal instead of the RegExp constructor.

Regular expression literals avoid some escaping required in a string literal, and are easier to analyze statically.
Safe fix: Use a literal notation instead.

(lint/complexity/useRegexLiterals)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 40cb00e and fd075a0.

📒 Files selected for processing (3)
  • packages/core/src/external/fhir/shared/__tests__/deep-search.test.ts (1 hunks)
  • packages/core/src/external/fhir/shared/bundle.ts (4 hunks)
  • packages/utils/src/fhir-converter/count-bundle-refs.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...

**/*.ts: - Use the Onion Pattern to organize a package's code in layers

  • Try to use immutable code and avoid sharing state across different functions, objects, and systems
  • Try to build code that's idempotent whenever possible
  • Prefer functional programming style functions: small, deterministic, 1 input, 1 output
  • Minimize coupling / dependencies
  • Avoid modifying objects received as parameter
  • Only add comments to code to explain why something was done, not how it works
  • Naming
    • classes, enums: PascalCase
    • constants, variables, functions: camelCase
    • file names: kebab-case
    • table and column names: snake_case
    • Use meaningful names, so whoever is reading the code understands what it means
    • Don’t use negative names, like notEnabled, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any to other types
    • Type predicates: only applicable to narrow down the type, not to force a complete type conversion
    • Prefer deconstructing parameters for functions instead of multiple parameters that might be of
      the same type
    • Don’t use null inside the app, only on code interacting with external interfaces/services,
      like DB and HTTP; convert to undefined before sending inwards into the code
    • Use async/await instead of .then()
    • Use the strict equality operator ===, don’t use abstract equality operator ==
    • When calling a Promise-returning function asynchronously (i.e., not awaiting), use .catch() to
      handle errors (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
  • Avoid creating arrow functions
  • Use truthy syntax instead of in - i.e., if (data.link) not if ('link' in data)
  • Error handling
    • Pass the original error as the new one’s cause so the stack trace is persisted
    • Error messages should have a static message - add dynamic data to MetriportError's additionalInfo prop
    • Avoid sending multiple events to Sentry for a single error
  • Global constants and variables
    • Move literals to constants declared after imports when possible (avoid magic numbers)
    • Avoid shared, global objects
  • Avoid using console.log and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().log()
    • don't create multi-line strings when using JSON.stringify()
  • Use eslint to enforce code style
  • Use prettier to format code
  • max column length is 100 chars
  • multi-line comments use /** */
  • scripts: top-level comments go after the import
  • packages/utils/src/fhir-converter/count-bundle-refs.ts
  • packages/core/src/external/fhir/shared/__tests__/deep-search.test.ts
  • packages/core/src/external/fhir/shared/bundle.ts
🪛 Biome (1.9.4)
packages/core/src/external/fhir/shared/__tests__/deep-search.test.ts

[error] 57-57: Use a regular expression literal instead of the RegExp constructor.

Regular expression literals avoid some escaping required in a string literal, and are easier to analyze statically.
Safe fix: Use a literal notation instead.

(lint/complexity/useRegexLiterals)

🔇 Additional comments (8)
packages/core/src/external/fhir/shared/bundle.ts (5)

78-78: Excellent performance optimization using Set.

Replacing array with Set for resource IDs is a great optimization. Sets have O(1) lookup time for membership checks compared to O(n) for arrays, which will significantly improve performance when checking if references exist in large collections.

Also applies to: 87-87


119-120: LGTM - Clean code refactoring.

Moving the variable initialization to the beginning of the function scope improves code readability and follows good practices.


128-132: Useful documentation of alternative approach.

The commented code provides valuable context about the alternative approach that was considered and tested. This follows the guideline of explaining why something was done, not how it works.


150-184: Well-implemented recursive search function with proper safeguards.

The deepSearchObjectForString function is well-implemented with:

  • Proper type safety using generics
  • Good handling of edge cases (null, Date, Set, Map)
  • Efficient recursion for nested objects and arrays
  • Clear structure following functional programming principles

This follows the coding guideline of building small, deterministic functions with clear inputs and outputs.


186-193: Clean implementation of array search helper.

The deepSearchArrayForString function is clean, concise, and efficiently leverages flatMap for array handling. This complementary function maintains the functional approach and supports the object search function well.

packages/core/src/external/fhir/shared/__tests__/deep-search.test.ts (3)

4-49: Good performance benchmark test.

This test properly validates that both approaches correctly find all references and logs timing information for comparison. This helps validate the performance hypothesis behind the new implementation.

However, consider removing or uncommenting line 48 since leaving commented expectations can be confusing:

-    // expect(jsonStringifyTime).toBeGreaterThanOrEqual(deepSearchTime);
+    // We don't enforce timing constraints in tests as they can be environment-dependent

68-115: Thorough testing of nested object scenarios.

The tests effectively cover multiple levels of nesting and combinations of objects and arrays, ensuring the deep search function correctly finds all references regardless of structure complexity.


117-137: Good coverage of array search scenarios.

These tests validate that the array search function correctly extracts references from various array structures, including arrays of objects and arrays with nested objects.

metriport/metriport-internal#1040

refs. ENG-279

Signed-off-by: Keshav Saharia <keshav@metriport.com>
metriport/metriport-internal#1040

refs. ENG-279

Signed-off-by: Keshav Saharia <keshav@metriport.com>
metriport/metriport-internal#1040

refs. ENG-279

Signed-off-by: Keshav Saharia <keshav@metriport.com>
@lucasdellabella lucasdellabella added this pull request to the merge queue May 16, 2025
Merged via the queue into develop with commit f660b6a May 16, 2025
16 checks passed
@lucasdellabella lucasdellabella deleted the eng-279-rewrite-getreferences-too-slow branch May 16, 2025 01:57
@lucasdellabella lucasdellabella mentioned this pull request May 16, 2025
1 task
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.

3 participants