Skip to content

Conversation

@fatih-acar
Copy link
Contributor

@fatih-acar fatih-acar commented Jul 22, 2025

Fixes #475

Using plain filters() call with a list of ids to fetch is better than sequentially fetching each id.

Using parallel=False we get:

real    0m17.552s
user    0m2.329s
sys     0m0.061s

With parallel=True we get:

real    0m9.379s
user    0m4.515s
sys     0m0.077s

Summary by CodeRabbit

  • Performance Improvements
    • Enhanced data fetching efficiency for relationships by batching requests, resulting in faster loading times when retrieving related items.
  • Bug Fixes
    • Improved test reliability by refining mocked responses to better simulate data fetching scenarios.

@coderabbitai
Copy link

coderabbitai bot commented Jul 22, 2025

"""

Walkthrough

The fetch methods in both RelationshipManager and RelationshipManagerSync were refactored to replace individual peer fetch operations with a batched approach. Peers are now validated for required fields, grouped by type, and fetched in parallel batches using the client's filters method, improving efficiency for high-cardinality relationships.

Changes

File(s) Change Summary
infrahub_sdk/node/relationship.py Refactored fetch methods in RelationshipManager and RelationshipManagerSync to batch-fetch peers by typename and IDs, added input validation, updated imports for Error and Order.
tests/unit/sdk/test_node.py Added an additional mocked HTTP response in test_node_fetch_relationship to simulate intermediate fetch results; reordered existing mocks accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant RelationshipManager
    participant Client

    User->>RelationshipManager: fetch()
    RelationshipManager->>RelationshipManager: Validate each peer (id, typename)
    RelationshipManager->>RelationshipManager: Group peer IDs by typename
    loop for each typename
        RelationshipManager->>Client: filters(kind, ids, populate_store, branch, parallel=True, order=Order())
    end
    RelationshipManager-->>User: return (after batch fetch)
Loading

Estimated code review effort

2 (~15 minutes)
"""


📜 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 519b99b and 95a7150.

📒 Files selected for processing (1)
  • infrahub_sdk/node/relationship.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • infrahub_sdk/node/relationship.py
⏰ 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). (4)
  • GitHub Check: unit-tests (3.13)
  • GitHub Check: unit-tests (3.12)
  • GitHub Check: unit-tests (3.10)
  • GitHub Check: integration-tests-latest-infrahub
✨ Finishing Touches
  • 📝 Generate Docstrings

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

@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 (3)
infrahub_sdk/node/relationship.py (3)

161-173: Excellent performance optimization with robust validation.

The batched fetching approach effectively replaces individual peer fetch operations with grouped client.filters() calls, which should significantly improve performance for high-cardinality relationships as intended.

The implementation correctly:

  • Groups peer IDs by typename to minimize API calls
  • Validates required peer fields before processing
  • Leverages parallel execution and disabled ordering for optimization

Consider enhancing the error message to include peer identification for easier debugging:

-                raise Error("Unable to fetch the peer, id and/or typename are not defined")
+                raise Error(f"Unable to fetch peer at index {self.peers.index(peer)}: id and/or typename are not defined")

277-289: Consistent and well-implemented synchronous counterpart.

The sync implementation mirrors the async version perfectly, maintaining consistency between both execution contexts. The batched fetching logic is identical, ensuring both async and sync users benefit equally from the performance improvements.

The same error message enhancement suggestion applies here for consistency:

-                raise Error("Unable to fetch the peer, id and/or typename are not defined")
+                raise Error(f"Unable to fetch peer at index {self.peers.index(peer)}: id and/or typename are not defined")

146-173: Outstanding refactoring that delivers on performance objectives.

This implementation successfully transforms individual peer fetch operations into efficient batch operations, directly addressing the PR's goal of improving high-cardinality relationship fetching performance.

Key architectural improvements:

  • Batch optimization: Groups API calls by typename, reducing network overhead
  • Parallel execution: Enables concurrent processing with parallel=True
  • Query optimization: Disables unnecessary ordering with Order(disable=True)
  • Consistent implementation: Identical logic across async/sync variants ensures uniform behavior

The refactoring maintains backward compatibility while delivering significant performance gains (17.5s → 9.4s as noted in PR objectives). The validation logic ensures data integrity, and the grouped approach scales much better with relationship cardinality.

Also applies to: 262-289

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d89883 and 6c01aee.

📒 Files selected for processing (1)
  • infrahub_sdk/node/relationship.py (3 hunks)
⏰ 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). (7)
  • GitHub Check: integration-tests-latest-infrahub
  • GitHub Check: unit-tests (3.10)
  • GitHub Check: unit-tests (3.12)
  • GitHub Check: unit-tests (3.13)
  • GitHub Check: unit-tests (3.11)
  • GitHub Check: unit-tests (3.9)
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (1)
infrahub_sdk/node/relationship.py (1)

7-7: LGTM! Import additions support the refactored fetch logic.

The new imports for Error and Order are correctly added and properly used in the updated fetch methods.

Also applies to: 10-10

@codecov
Copy link

codecov bot commented Jul 22, 2025

Codecov Report

Attention: Patch coverage is 75.00000% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
infrahub_sdk/node/relationship.py 75.00% 3 Missing and 3 partials ⚠️
@@            Coverage Diff             @@
##           stable     #476      +/-   ##
==========================================
+ Coverage   75.63%   75.68%   +0.04%     
==========================================
  Files         100      100              
  Lines        8767     8789      +22     
  Branches     1714     1722       +8     
==========================================
+ Hits         6631     6652      +21     
  Misses       1660     1660              
- Partials      476      477       +1     
Flag Coverage Δ
integration-tests 34.86% <37.50%> (+0.19%) ⬆️
python-3.10 47.98% <58.33%> (+0.09%) ⬆️
python-3.11 47.95% <58.33%> (+0.05%) ⬆️
python-3.12 47.95% <58.33%> (+0.09%) ⬆️
python-3.13 47.93% <58.33%> (+0.07%) ⬆️
python-3.9 46.61% <54.16%> (+0.04%) ⬆️
python-filler-3.12 25.22% <8.33%> (-0.05%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
infrahub_sdk/node/relationship.py 71.75% <75.00%> (+0.13%) ⬆️

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@fatih-acar fatih-acar force-pushed the fac-fix-many-rels-fetch branch from 6c01aee to 519b99b Compare July 22, 2025 07:04
@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Jul 22, 2025

Deploying infrahub-sdk-python with  Cloudflare Pages  Cloudflare Pages

Latest commit: 95a7150
Status: ✅  Deploy successful!
Preview URL: https://68d91c11.infrahub-sdk-python.pages.dev
Branch Preview URL: https://fac-fix-many-rels-fetch.infrahub-sdk-python.pages.dev

View logs

Signed-off-by: Fatih Acar <[email protected]>
@fatih-acar fatih-acar merged commit 6465b92 into stable Jul 22, 2025
20 checks passed
@fatih-acar fatih-acar deleted the fac-fix-many-rels-fetch branch July 22, 2025 10:47
await peer.fetch() # type: ignore[misc]
if not peer.id or not peer.typename:
raise Error("Unable to fetch the peer, id and/or typename are not defined")
if peer.typename not in ids_per_kind_map:
Copy link
Contributor

Choose a reason for hiding this comment

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

with the defaultdict you can just do

ids_per_kind_map[peer.typename].append(peer.id)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks 😅 will try to include this in another PR

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.

task: improve fetch of cardinality many relationship

3 participants