Skip to content

Conversation

@tisnik
Copy link
Contributor

@tisnik tisnik commented Sep 29, 2025

Description

LCORE-731: better docstring for utils module

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library
  • Bump-up library or tool used for development (does not change the final image)
  • CI configuration change
  • Konflux configuration change
  • Unit tests improvement
  • Integration tests improvement
  • End to end tests improvement

Related Tickets & Documents

  • Related Issue #LCORE-731

Summary by CodeRabbit

  • New Features

    • File-based attribute reading now returns referenced file contents (UTF-8) with trailing whitespace trimmed.
  • Bug Fixes

    • More robust validation and explicit error behavior for file path presence and readability.
  • Documentation

    • Expanded docs detailing file-handling behavior and validation/error semantics.
    • Clarified unique ID generation and validation (UUID4 format; accepts strings or bytes).
    • Improved docstrings for utility behaviors and parser/singleton semantics.
  • Chores

    • Minor documentation refinements for consistency.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 29, 2025

Walkthrough

get_attribute_from_file in src/utils/checks.py now reads and returns UTF-8 file contents trimmed of trailing whitespace; several docstrings in src/utils/checks.py, src/utils/suid.py, and src/utils/types.py were expanded or clarified with no functional changes to SUID and types behavior.

Changes

Cohort / File(s) Summary
File attribute retrieval & checks
src/utils/checks.py
get_attribute_from_file now opens the file at data[file_name_key], reads UTF-8 text and returns trimmed contents (returns None only if key missing or None); file_check docstring expanded to document validation semantics and error conditions (runtime behavior still raises on non-file/unreadable).
SUID utilities (docs only)
src/utils/suid.py
Expanded docstrings for get_suid and check_suid describing RFC 4122 UUID4 generation and validation; logic and signatures unchanged.
Type-related docstrings
src/utils/types.py
Expanded docstrings for Singleton.__call__, GraniteToolParser.get_tool_calls, and GraniteToolParser.get_parser; no behavior changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant Checks as utils.checks
  participant FS as File System

  Caller->>Checks: get_attribute_from_file(data, file_name_key)
  alt key missing or value is None
    Checks-->>Caller: return None
  else
    Checks->>FS: open path = data[file_name_key] (read, UTF-8)
    alt file readable
      FS-->>Checks: file contents
      Checks-->>Caller: return contents.rstrip()
    else not a file / unreadable
      Checks-->>Caller: raise InvalidConfigurationError
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I nose through paths with careful cheer,
A whisker-twitch — the file draws near.
I read the lines and trim the end,
UUIDs march by, a curious friend.
A hop, a nibble — changes penned. 🐇

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly references the related issue and concisely describes the primary change, namely improving docstrings in the utils module, which aligns with the PR objectives and the detailed summary of documentation updates across utility functions.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@tisnik tisnik force-pushed the lcore-731-better-docstring-for-utils-module branch from b790f35 to e26cf1a Compare September 29, 2025 07:48
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

🧹 Nitpick comments (2)
src/utils/types.py (1)

37-47: Align docstring with the type hint

The docstring advertises output_message as CompletionMessage | None, but the signature still declares CompletionMessage. Either widen the annotation to accept None or trim the docstring so they stay consistent.

src/utils/suid.py (1)

21-32: Keep annotation and docstring in sync

The docstring now states suid may be str | bytes, but the signature still restricts it to str. Please either update the annotation to str | bytes or narrow the docstring so callers don’t get conflicting guidance.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3fb32cd and e26cf1a.

📒 Files selected for processing (3)
  • src/utils/checks.py (2 hunks)
  • src/utils/suid.py (1 hunks)
  • src/utils/types.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

Use absolute imports for internal modules (e.g., from auth import get_auth_dependency)

Files:

  • src/utils/types.py
  • src/utils/checks.py
  • src/utils/suid.py
**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.py: All modules start with descriptive module-level docstrings explaining purpose
Use logger = logging.getLogger(name) for module logging after import logging
Define type aliases at module level for clarity
All functions require docstrings with brief descriptions
Provide complete type annotations for all function parameters and return types
Use typing_extensions.Self in model validators where appropriate
Use modern union syntax (str | int) and Optional[T] or T | None consistently
Function names use snake_case with descriptive, action-oriented prefixes (get_, validate_, check_)
Avoid in-place parameter modification; return new data structures instead of mutating arguments
Use appropriate logging levels: debug, info, warning, error with clear messages
All classes require descriptive docstrings explaining purpose
Class names use PascalCase with conventional suffixes (Configuration, Error/Exception, Resolver, Interface)
Abstract base classes should use abc.ABC and @AbstractMethod for interfaces
Provide complete type annotations for all class attributes
Follow Google Python docstring style for modules, classes, and functions, including Args, Returns, Raises, Attributes sections as needed

Files:

  • src/utils/types.py
  • src/utils/checks.py
  • src/utils/suid.py
🪛 GitHub Actions: Python linter
src/utils/types.py

[warning] 55-55: Pylint: Line too long (108/100) (C0301)


[warning] 58-58: Pylint: Line too long (150/100) (C0301)


[warning] 61-61: Pylint: Line too long (136/100) (C0301)

⏰ 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-pr
🔇 Additional comments (4)
src/utils/types.py (1)

21-26: Docstring expansion reads well

Clear summary and returns section—no issues spotted here.

src/utils/suid.py (1)

7-15: Docstring clarity appreciated

Thanks for spelling out the RFC 4122 UUID4 details—looks good.

src/utils/checks.py (2)

16-30: Documentation matches behavior

Nice update—this explains the None handling and trimming behavior precisely.


39-53: Docstring clarifies failure modes

Appreciate the explicit Raises section; reads clean.

@tisnik tisnik force-pushed the lcore-731-better-docstring-for-utils-module branch from e26cf1a to 23067db Compare September 29, 2025 07:56
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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e26cf1a and 23067db.

📒 Files selected for processing (2)
  • src/utils/suid.py (1 hunks)
  • src/utils/types.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/utils/types.py
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

Use absolute imports for internal modules (e.g., from auth import get_auth_dependency)

Files:

  • src/utils/suid.py
**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.py: All modules start with descriptive module-level docstrings explaining purpose
Use logger = logging.getLogger(name) for module logging after import logging
Define type aliases at module level for clarity
All functions require docstrings with brief descriptions
Provide complete type annotations for all function parameters and return types
Use typing_extensions.Self in model validators where appropriate
Use modern union syntax (str | int) and Optional[T] or T | None consistently
Function names use snake_case with descriptive, action-oriented prefixes (get_, validate_, check_)
Avoid in-place parameter modification; return new data structures instead of mutating arguments
Use appropriate logging levels: debug, info, warning, error with clear messages
All classes require descriptive docstrings explaining purpose
Class names use PascalCase with conventional suffixes (Configuration, Error/Exception, Resolver, Interface)
Abstract base classes should use abc.ABC and @AbstractMethod for interfaces
Provide complete type annotations for all class attributes
Follow Google Python docstring style for modules, classes, and functions, including Args, Returns, Raises, Attributes sections as needed

Files:

  • src/utils/suid.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). (2)
  • GitHub Check: build-pr
  • GitHub Check: e2e_tests

Comment on lines 19 to +31
def check_suid(suid: str) -> bool:
"""Check if given string is a proper session ID.
Args:
suid: The string to check.
"""
Check if given string is a proper session ID.
Returns True if the string is a valid UUID, False otherwise.
Parameters:
suid (str | bytes): UUID value to validate — accepts a UUID string or
its byte representation.
Notes:
Validation is performed by attempting to construct uuid.UUID(suid);
invalid formats or types result in False.
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Align docstring and signature with declared behavior.

The docstring now promises that check_suid accepts str | bytes, yet the type annotation still restricts the argument to str, which will force callers to fight type checkers. While you are touching the docstring, please update the signature (and the docstring sections) so that the runtime behavior, annotations, and Google-style docs stay consistent. Suggested fix:

-def check_suid(suid: str) -> bool:
+def check_suid(suid: str | bytes) -> bool:
@@
-    Parameters:
-        suid (str | bytes): UUID value to validate — accepts a UUID string or
-        its byte representation.
-
-    Notes:
-        Validation is performed by attempting to construct uuid.UUID(suid);
-        invalid formats or types result in False.
+    Args:
+        suid: UUID value to validate — accepts a UUID string or its byte
+            representation.
+
+    Returns:
+        bool: True if `uuid.UUID(suid)` succeeds, False otherwise.
+
+    Notes:
+        Validation is performed by attempting to construct uuid.UUID(suid);
+        invalid formats or types result in False.

As per coding guidelines.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def check_suid(suid: str) -> bool:
"""Check if given string is a proper session ID.
Args:
suid: The string to check.
"""
Check if given string is a proper session ID.
Returns True if the string is a valid UUID, False otherwise.
Parameters:
suid (str | bytes): UUID value to validateaccepts a UUID string or
its byte representation.
Notes:
Validation is performed by attempting to construct uuid.UUID(suid);
invalid formats or types result in False.
def check_suid(suid: str | bytes) -> bool:
"""
Check if given string is a proper session ID.
Args:
suid: UUID value to validateaccepts a UUID string or its byte
representation.
Returns:
bool: True if `uuid.UUID(suid)` succeeds, False otherwise.
Notes:
Validation is performed by attempting to construct uuid.UUID(suid);
invalid formats or types result in False.
"""
🤖 Prompt for AI Agents
In src/utils/suid.py around lines 19 to 31, the function signature and docstring
disagree: the docstring says the parameter accepts str | bytes but the type
annotation is only str; update the function signature to accept both types
(e.g., suid: str | bytes or Union[str, bytes]) and edit the docstring parameter
type and description to match the annotation (ensure the "Parameters" section
shows "suid (str | bytes): ..." and remove any contradictory wording), keeping
the existing runtime validation logic unchanged and ensuring imports
(typing.Union) are added if needed.

@tisnik tisnik merged commit 42532c0 into lightspeed-core:main Sep 29, 2025
18 of 19 checks passed
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.

1 participant