Skip to content

Conversation

@tisnik
Copy link
Contributor

@tisnik tisnik commented Aug 19, 2025

Description

LCORE-463: Added missing error handling

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-463

Summary by CodeRabbit

  • Bug Fixes

    • Improved robustness of feedback submission by handling file I/O errors and logging detailed context, ensuring successful writes are confirmed and failures are surfaced clearly.
  • Tests

    • Added parameterized tests covering permission-denied scenarios for multiple feedback payloads, increasing error-handling coverage and reliability.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 19, 2025

Warning

Rate limit exceeded

@tisnik has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 10 minutes and 34 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between ab75c32 and ffb1c29.

📒 Files selected for processing (1)
  • tests/unit/app/endpoints/test_feedback.py (1 hunks)

Walkthrough

Added try/except around feedback JSON file write to catch and log OSError/IOError, re-raising on failure. Introduced unit tests validating permission-denied behavior using non-writable path and different payload variants. No public API changes.

Changes

Cohort / File(s) Summary
Feedback endpoint error handling
src/app/endpoints/feedback.py
Wrap file write in try/except; on OSError/IOError, log path and re-raise; success log unchanged.
Unit tests for IO error handling
tests/unit/app/endpoints/test_feedback.py
Add parameterized tests asserting OSError on writes to non-writable path for two payload shapes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant Endpoint as store_feedback
  participant FS as FileSystem

  Client->>Endpoint: store_feedback(payload, path)
  rect rgba(220,235,255,0.5)
    note right of Endpoint: Attempt to persist JSON
    Endpoint->>FS: write(path, json)
    alt write succeeds
      FS-->>Endpoint: ok
      Endpoint-->>Client: return success (log info)
    else OSError/IOError
      FS-->>Endpoint: error
      note right of Endpoint: Log error with target path
      Endpoint-->>Client: raise OSError/IOError
    end
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I thump my foot by the feedback log,
Tried to write—denied by the fog!
Catch the squeak, re-raise the plight,
Tests nibble paths that fail to write.
When perms say no, my ears perk high—
Burrow safe code, and hop on by. 🐇

✨ 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
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@tisnik tisnik force-pushed the lcore-463-missing-error-handling branch 2 times, most recently from 783c672 to ab75c32 Compare August 19, 2025 09:43
@tisnik
Copy link
Contributor Author

tisnik commented Aug 19, 2025

@CodeRabbit fullreview

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 19, 2025

@tisnik I'll conduct a full review of the PR changes for LCORE-463: Added missing error handling.

✅ Actions performed

Full review triggered.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/app/endpoints/feedback.py (2)

143-145: Prevent client payload from overriding server-controlled fields (user_id, timestamp).

With the current merge order, user-supplied keys in feedback can override user_id and timestamp, compromising integrity. Ensure server fields win.

Apply this diff:

-    current_time = str(datetime.now(UTC))
-    data_to_store = {"user_id": user_id, "timestamp": current_time, **feedback}
+    current_time = datetime.now(UTC).isoformat()
+    # Server-controlled fields must not be overridden by client input
+    data_to_store = {**feedback, "user_id": user_id, "timestamp": current_time}

110-118: Avoid leaking internal exception details to API clients.

Returning str(e) (which can include filesystem paths, errno, etc.) in the 500 response is an information disclosure risk. Keep details in server logs; return a generic error to clients.

Apply this diff:

-    except Exception as e:
-        logger.error("Error storing user feedback: %s", e)
+    except Exception as e:
+        logger.exception("Error storing user feedback")
         raise HTTPException(
             status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
             detail={
                 "response": "Error storing user feedback",
-                "cause": str(e),
             },
         ) from e
🧹 Nitpick comments (3)
src/app/endpoints/feedback.py (2)

148-153: Good addition; tighten logging and simplify exception type.

Catching OSError is sufficient in Python 3 (IOError aliases to OSError). Also, log the stack trace for easier debugging.

Apply this diff:

-    try:
-        with open(feedback_file_path, "w", encoding="utf-8") as feedback_file:
-            json.dump(data_to_store, feedback_file)
-    except (OSError, IOError) as e:
-        logger.error("Failed to store feedback at %s: %s", feedback_file_path, e)
-        raise
+    try:
+        with open(feedback_file_path, "w", encoding="utf-8") as feedback_file:
+            json.dump(data_to_store, feedback_file)
+    except OSError as e:
+        logger.exception("Failed to store feedback at %s", feedback_file_path)
+        raise

138-142: Also handle directory creation errors with logging context.

mkdir can fail (permissions, read-only FS, invalid path). Mirror the write-path handling so failures are logged with the target directory.

Apply this diff:

-    storage_path.mkdir(parents=True, exist_ok=True)
+    try:
+        storage_path.mkdir(parents=True, exist_ok=True)
+    except OSError as e:
+        logger.exception("Failed to prepare feedback storage directory %s", storage_path)
+        raise
tests/unit/app/endpoints/test_feedback.py (1)

131-155: Optional: Verify server-enforced fields override any client-supplied duplicates.

If you adopt the merge-order fix, add a regression test to ensure a client cannot spoof user_id/timestamp.

Example test to add near this block:

def test_store_feedback_overrides_spoofed_fields(mocker):
    configuration.user_data_collection_configuration.feedback_storage = "fake-path"
    mocker.patch("builtins.open", mocker.mock_open())
    mocker.patch("app.endpoints.feedback.Path", return_value=mocker.MagicMock())
    mocker.patch("app.endpoints.feedback.get_suid", return_value="fake-uuid")
    mock_json = mocker.patch("app.endpoints.feedback.json")

    user_id = "real_user_id"
    payload = {"user_id": "spoofed", "timestamp": "1970-01-01T00:00:00Z"}

    store_feedback(user_id, payload)

    args, kwargs = mock_json.dump.call_args
    stored = args[0]
    assert stored["user_id"] == user_id
    assert stored["timestamp"] != "1970-01-01T00:00:00Z"
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between da067bc and ab75c32.

📒 Files selected for processing (2)
  • src/app/endpoints/feedback.py (1 hunks)
  • tests/unit/app/endpoints/test_feedback.py (1 hunks)

@tisnik tisnik force-pushed the lcore-463-missing-error-handling branch from ab75c32 to ffb1c29 Compare August 19, 2025 10:15
@tisnik tisnik merged commit b0a737b into lightspeed-core:main Aug 19, 2025
18 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