Skip to content

Conversation

@gmazoyer
Copy link
Contributor

@gmazoyer gmazoyer commented Jul 29, 2025

This change moves the get_flat_value function to methods of the InfrahubNode and InfrahubNodeSync classes. This allows to handle traversing relationships of cardinality one using a flat notation in addition to attributes.

The extract method has also been moved as it needs to be async for regular nodes now.

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of value lookups using flat notation (e.g., foo__bar__value) for relationships with cardinality one, ensuring correct resolution of nested attributes.
  • New Features

    • Introduced enhanced methods for retrieving and extracting nested values using flat key notation in both asynchronous and synchronous node interfaces.
  • Tests

    • Updated and expanded tests to separately verify flat value retrieval and extraction, including error handling for invalid lookups.
    • Removed outdated tests related to the previous utility function for flat value extraction.

@coderabbitai
Copy link

coderabbitai bot commented Jul 29, 2025

Walkthrough

This change refactors the logic for flat notation value lookups (e.g., foo__bar__value) from a utility function into new recursive methods within both async and sync node classes. The utility function and its protocol interface declaration are removed. Tests are updated and expanded to cover the new class methods and error handling, including separation of flat value retrieval and extraction tests.

Changes

Cohort / File(s) Change Summary
Changelog
changelog/6882.fixed.md
Documents the fix for flat notation value lookups across one-to-one relationships.
Async/Sync Node Refactor
infrahub_sdk/node/node.py
Removes utility-based extract method; adds recursive get_flat_value and extract methods directly in async (InfrahubNode) and sync (InfrahubNodeSync) classes, supporting nested lookups and relationship traversal with proper async/sync fetch handling.
Protocol Cleanup
infrahub_sdk/protocols_base.py
Removes the extract method declaration from the CoreNodeBase protocol interface.
Utility Removal
infrahub_sdk/utils.py
Deletes the get_flat_value utility function, as its logic is now embedded in node classes.
Node Tests Refactor & Expansion
tests/unit/sdk/test_node.py
Splits and expands tests: adds test_get_flat_value for async and sync nodes, covering correct lookups and error cases; refactors test_node_extract to use new methods and fixtures, separating concerns and improving coverage.
Utils Tests Cleanup
tests/unit/sdk/test_utils.py
Removes the test and import for the deleted get_flat_value utility function.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Node (async/sync)
    participant RelatedNode

    Caller->>Node: extract(params)
    loop For each key in params
        Node->>Node: get_flat_value(key)
        alt Key traverses relationship
            Node->>RelatedNode: fetch (awaited or sync)
            RelatedNode->>Node: get_flat_value(remaining_key)
        end
        Node-->>Caller: value
    end
    Node-->>Caller: dict of extracted values
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 136e7ff and e2552e5.

📒 Files selected for processing (1)
  • infrahub_sdk/node/node.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • infrahub_sdk/node/node.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). (8)
  • GitHub Check: unit-tests (3.9)
  • GitHub Check: validate-generated-documentation
  • GitHub Check: unit-tests (3.13)
  • GitHub Check: unit-tests (3.11)
  • GitHub Check: integration-tests-latest-infrahub
  • GitHub Check: unit-tests (3.10)
  • GitHub Check: unit-tests (3.12)
  • GitHub Check: documentation
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch gma-20250729-6882

🪧 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 generate unit tests to generate unit tests for 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.

@cloudflare-workers-and-pages
Copy link

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

Deploying infrahub-sdk-python with  Cloudflare Pages  Cloudflare Pages

Latest commit: e2552e5
Status: ✅  Deploy successful!
Preview URL: https://66ba3368.infrahub-sdk-python.pages.dev
Branch Preview URL: https://gma-20250729-6882.infrahub-sdk-python.pages.dev

View logs

@codecov
Copy link

codecov bot commented Jul 29, 2025

Codecov Report

❌ Patch coverage is 91.48936% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
infrahub_sdk/node/node.py 91.48% 4 Missing ⚠️
@@            Coverage Diff             @@
##           stable     #487      +/-   ##
==========================================
+ Coverage   75.63%   75.75%   +0.11%     
==========================================
  Files         100      100              
  Lines        8767     8821      +54     
  Branches     1714     1727      +13     
==========================================
+ Hits         6631     6682      +51     
- Misses       1660     1664       +4     
+ Partials      476      475       -1     
Flag Coverage Δ
integration-tests 34.72% <0.00%> (+0.05%) ⬆️
python-3.10 48.12% <80.85%> (+0.23%) ⬆️
python-3.11 48.14% <80.85%> (+0.23%) ⬆️
python-3.12 48.10% <80.85%> (+0.23%) ⬆️
python-3.13 48.10% <80.85%> (+0.23%) ⬆️
python-3.9 46.79% <80.85%> (+0.21%) ⬆️
python-filler-3.12 25.16% <10.63%> (-0.10%) ⬇️

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

Files with missing lines Coverage Δ
infrahub_sdk/protocols_base.py 74.21% <ø> (+0.57%) ⬆️
infrahub_sdk/utils.py 85.11% <ø> (+0.36%) ⬆️
infrahub_sdk/node/node.py 75.96% <91.48%> (+1.02%) ⬆️

... and 5 files with indirect coverage changes

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

@gmazoyer gmazoyer marked this pull request as ready for review July 29, 2025 13:03
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 (2)
infrahub_sdk/node/node.py (2)

1031-1062: Consider handling AttributeError in nested attribute access.

The implementation correctly handles flat notation lookups. However, the nested getattr calls in lines 1045-1047 could raise AttributeError if any intermediate attribute doesn't exist. Consider wrapping this in a try-except block for more graceful error handling.

         if first in self._schema.attribute_names:
             attr = getattr(self, first)
-            for part in remaining.split(separator):
-                attr = getattr(attr, part)
-            return attr
+            try:
+                for part in remaining.split(separator):
+                    attr = getattr(attr, part)
+                return attr
+            except AttributeError as exc:
+                raise AttributeError(f"Invalid attribute path: {key}") from exc

1657-1688: Consider consistent error handling with async version.

The sync implementation correctly mirrors the async logic. Similar to the async version, consider adding error handling for the nested getattr calls in lines 1670-1673.

         if first in self._schema.attribute_names:
             attr = getattr(self, first)
-            for part in remaining.split(separator):
-                attr = getattr(attr, part)
-            return attr
+            try:
+                for part in remaining.split(separator):
+                    attr = getattr(attr, part)
+                return attr
+            except AttributeError as exc:
+                raise AttributeError(f"Invalid attribute path: {key}") from exc
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f3bb071 and 45c2bfb.

📒 Files selected for processing (6)
  • changelog/6882.fixed.md (1 hunks)
  • infrahub_sdk/node/node.py (3 hunks)
  • infrahub_sdk/protocols_base.py (0 hunks)
  • infrahub_sdk/utils.py (0 hunks)
  • tests/unit/sdk/test_node.py (1 hunks)
  • tests/unit/sdk/test_utils.py (0 hunks)
💤 Files with no reviewable changes (3)
  • infrahub_sdk/protocols_base.py
  • tests/unit/sdk/test_utils.py
  • infrahub_sdk/utils.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/unit/sdk/test_node.py (2)
tests/unit/sdk/conftest.py (4)
  • clients (37-42)
  • location_schema (140-172)
  • location_data01 (375-412)
  • client (32-33)
infrahub_sdk/node/node.py (6)
  • InfrahubNode (452-1078)
  • get_flat_value (1031-1061)
  • get_flat_value (1657-1687)
  • InfrahubNodeSync (1081-1704)
  • extract (1063-1069)
  • extract (1689-1695)
🔇 Additional comments (6)
changelog/6882.fixed.md (1)

1-1: LGTM!

The changelog entry clearly describes the fix for flat notation value lookups with cardinality-one relationships.

tests/unit/sdk/test_node.py (2)

1950-1976: LGTM!

The test comprehensively covers the get_flat_value method for both async and sync node instances. It properly:

  • Tests attribute access via flat notation (name__value)
  • Tests relationship traversal with cardinality one (primary_tag__display_label)
  • Tests custom separators (. vs __)
  • Validates error handling for many-cardinality relationships
  • Uses appropriate mocking with reusable responses

1978-1996: LGTM!

The test properly validates the extract method functionality for both async and sync node instances. It correctly:

  • Tests multiple key extractions in a single call
  • Uses flat notation for value lookup (name__value, description__value)
  • Verifies the returned dictionary structure and values
  • Follows consistent parametrized testing patterns
infrahub_sdk/node/node.py (3)

11-11: Import cleanup looks good.

The removal of get_flat_value from utils import aligns with moving this functionality into the node classes.


1063-1069: Extract method implementation looks good.

The async extract method correctly iterates through params and awaits the flat value lookups.


1689-1696: Sync extract method implementation is correct.

The method properly implements the synchronous version of extract, maintaining consistency with the async implementation.

@gmazoyer gmazoyer requested a review from a team July 29, 2025 21:03
@gmazoyer gmazoyer merged commit 5daba0e into stable Jul 30, 2025
20 checks passed
@gmazoyer gmazoyer deleted the gma-20250729-6882 branch July 30, 2025 08:19
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