Skip to content

fix: Return INVALID_QUERY for invalid MongoDB hints#10497

Open
Fhatu12 wants to merge 1 commit into
parse-community:alphafrom
Fhatu12:fix/invalid-hint-error
Open

fix: Return INVALID_QUERY for invalid MongoDB hints#10497
Fhatu12 wants to merge 1 commit into
parse-community:alphafrom
Fhatu12:fix/invalid-hint-error

Conversation

@Fhatu12
Copy link
Copy Markdown

@Fhatu12 Fhatu12 commented Jun 5, 2026

Summary

Map invalid MongoDB hint errors to a clean Parse INVALID_QUERY response instead of surfacing them as internal server errors.

Changes

  • add narrow invalid-hint detection in MongoStorageAdapter.handleError()
  • convert matching Mongo hint/index errors to Parse.Error.INVALID_QUERY
  • add regression coverage for invalid hint usage in spec/ParseQuery.hint.spec.js

Testing

  • npm test -- spec/ParseQuery.hint.spec.js

Fixes #8288

Summary by CodeRabbit

  • Bug Fixes

    • Queries using a missing or invalid index hint now return a clear INVALID_QUERY error with a message referencing the hint/index instead of a generic internal server error.
  • Tests

    • Added a test ensuring invalid-hint queries produce the proper INVALID_QUERY error and a descriptive message mentioning the hint.

@parse-github-assistant
Copy link
Copy Markdown

I will reformat the title to use the proper commit message syntax.

@parse-github-assistant parse-github-assistant Bot changed the title fix: return INVALID_QUERY for invalid MongoDB hints fix: Return INVALID_QUERY for invalid MongoDB hints Jun 5, 2026
@parse-github-assistant
Copy link
Copy Markdown

🚀 Thanks for opening this pull request! We appreciate your effort in improving the project. Please let us know once your pull request is ready for review.

Tip

  • Keep pull requests small. Large PRs will be rejected. Break complex features into smaller, incremental PRs.
  • Use Test Driven Development. Write failing tests before implementing functionality. Ensure tests pass.
  • Group code into logical blocks. Add a short comment before each block to explain its purpose.
  • We offer conceptual guidance. Coding is up to you. PRs must be merge-ready for human review.
  • Our review focuses on concept, not quality. PRs with code issues will be rejected. Use an AI agent.
  • Human review time is precious. Avoid review ping-pong. Inspect and test your AI-generated code.

Note

Please respond to review comments from AI agents just like you would to comments from a human reviewer. Let the reviewer resolve their own comments, unless they have reviewed and accepted your commit, or agreed with your explanation for why the feedback was incorrect.

Caution

Pull requests must be written using an AI agent with human supervision. Pull requests written entirely by a human will likely be rejected, because of lower code quality, higher review effort and the higher risk of introducing bugs. Please note that AI review comments on this pull request alone do not satisfy this requirement. Our CI and AI review are safeguards, not development tools. If many issues are flagged, rethink your development approach. Invest more effort in planning and design rather than using review cycles to fix low-quality code.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 5, 2026

Need an answer fast? Review this PR in Change Stack to ask focused questions about the PR or a changed range.

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 79e10363-f94d-4aa0-a777-5e43aaf1d5a6

📥 Commits

Reviewing files that changed from the base of the PR and between 86e05e4 and 64a8c0b.

📒 Files selected for processing (2)
  • spec/ParseQuery.hint.spec.js
  • src/Adapters/Storage/Mongo/MongoStorageAdapter.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • spec/ParseQuery.hint.spec.js
  • src/Adapters/Storage/Mongo/MongoStorageAdapter.js

📝 Walkthrough

Walkthrough

Classifies MongoDB errors caused by invalid query hints and maps them to Parse.Error.INVALID_QUERY in the Mongo storage adapter; adds a test verifying a query using a missing hint returns INVALID_QUERY and includes "hint" in the message.

Changes

Invalid Hint Error Handling

Layer / File(s) Summary
Invalid hint error detection and handler integration
src/Adapters/Storage/Mongo/MongoStorageAdapter.js
Adds isInvalidHintError() to classify MongoDB errors whose messages or codes indicate invalid hints and updates handleError() to throw Parse.Error.INVALID_QUERY with the original error message when detected.
Invalid hint error behavior test
spec/ParseQuery.hint.spec.js
Adds a test that constructs a Parse.Query with a non-existent hint (missing_index) and asserts find() throws Parse.Error.INVALID_QUERY and that the error message contains "hint".

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • mtrezza
🚥 Pre-merge checks | ✅ 5 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Security Check ⚠️ Warning Error message exposes raw MongoDB database errors to clients via ${error.message}, violating CWE-209 and inconsistent with codebase patterns using generic messages for INVALID_QUERY. Change Invalid hint: ${error.message} to generic Invalid hint message to match codebase conventions and prevent database error message disclosure.
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed PR title starts with 'fix:' prefix and clearly summarizes the main change: mapping invalid MongoDB hints to INVALID_QUERY errors.
Description check ✅ Passed PR description provides summary, changes, and testing instructions. Missing the 'Issue' section reference and some template tasks are unchecked, but core content is present.
Linked Issues check ✅ Passed Changes directly address issue #8288 objectives: invalid hint detection is implemented in MongoStorageAdapter.handleError() to convert MongoDB errors to Parse.Error.INVALID_QUERY with regression test coverage.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing invalid hint error handling: test file addition, helper function, and error handler logic remain focused on the stated objective.
Engage In Review Feedback ✅ Passed No actionable review feedback was raised on this PR per PR objectives (CodeRabbit found no issues; maintainer review pending). Review engagement requirement is inapplicable.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 OpenGrep (1.22.0)

OpenGrep fatal error (exit code 2): [00.12][ERROR]: Error: exception Unix_error: No such file or directory stat spec/ParseQuery.hint.spec.js
Raised by primitive operation at UTmp.replace_named_pipe_by_regular_file_if_needed in file "libs/commons/UTmp.ml", line 145, characters 8-27
Called from Scan_CLI.replace_target_roots_by_regular_files_where_needed.(fun) in file "src/osemgrep/cli_scan/Scan_CLI.ml", lines 1086-1087, characters 19-65
Called from List_.fast_map in file "libs/commons/List_.ml", line 81, characters 17-20
Called from


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.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 5, 2026
@Fhatu12
Copy link
Copy Markdown
Author

Fhatu12 commented Jun 5, 2026

Thanks for the feedback.

This PR is ready for review from my side. I used AI assistance to help inspect the code path and prepare the fix, but I reviewed the changes myself and ran the targeted regression test locally.

Validation run:

  • npm test -- spec/ParseQuery.hint.spec.js

CodeRabbit did not raise any actionable comments, so I will wait for the maintainer review.

Comment thread spec/ParseQuery.hint.spec.js Outdated
expect(explain.queryPlanner.winningPlan.inputStage.inputStage.indexName).toBe('_id_');
});

it_only_mongodb_version('<5.1 || >=6')('query find with invalid hint returns invalid query error', async () => {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why is this gated on mongodb versions?

@codecov
Copy link
Copy Markdown

codecov Bot commented Jun 5, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.61%. Comparing base (78859a9) to head (64a8c0b).
⚠️ Report is 2 commits behind head on alpha.

Additional details and impacted files
@@            Coverage Diff             @@
##            alpha   #10497      +/-   ##
==========================================
+ Coverage   92.60%   92.61%   +0.01%     
==========================================
  Files         193      193              
  Lines       16919    16927       +8     
  Branches      234      234              
==========================================
+ Hits        15667    15677      +10     
+ Misses       1229     1227       -2     
  Partials       23       23              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

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

🧹 Nitpick comments (1)
spec/ParseQuery.hint.spec.js (1)

169-170: ⚡ Quick win

Reduce backend-message coupling in this assertion.

The toContain('index') check is brittle because MongoDB/driver wording can vary by version while still correctly mapping to INVALID_QUERY. Keep the behavior contract assertion on error code (and optionally hint) and drop the strict index token requirement.

Suggested test adjustment
-      expect(error.message.toLowerCase()).toContain('index');
+      // Avoid coupling to MongoDB version-specific phrasing.
+      expect(error.message.toLowerCase()).toContain('hint');
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@spec/ParseQuery.hint.spec.js` around lines 169 - 170, Remove the brittle
"index" substring assertion in the test; update the assertion block in
spec/ParseQuery.hint.spec.js so it asserts the error.code equals 'INVALID_QUERY'
(and may still assert the error.message contains 'hint' if desired) and drop the
expect(error.message.toLowerCase()).toContain('index') check to avoid coupling
to driver wording.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@spec/ParseQuery.hint.spec.js`:
- Around line 169-170: Remove the brittle "index" substring assertion in the
test; update the assertion block in spec/ParseQuery.hint.spec.js so it asserts
the error.code equals 'INVALID_QUERY' (and may still assert the error.message
contains 'hint' if desired) and drop the
expect(error.message.toLowerCase()).toContain('index') check to avoid coupling
to driver wording.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d0ec53c4-622a-44b3-91e6-d2fcff173be1

📥 Commits

Reviewing files that changed from the base of the PR and between 4870f4c and 86e05e4.

📒 Files selected for processing (2)
  • spec/ParseQuery.hint.spec.js
  • src/Adapters/Storage/Mongo/MongoStorageAdapter.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Adapters/Storage/Mongo/MongoStorageAdapter.js

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 5, 2026
@Fhatu12
Copy link
Copy Markdown
Author

Fhatu12 commented Jun 5, 2026

Thanks for the feedback.

I’ve updated the test to keep it focused on the actual behaviour we want to protect.

Changes made:

  • removed the MongoDB version gate from the new regression test
  • removed the index wording check, as that wording can vary between MongoDB versions
  • kept the important checks for Parse.Error.INVALID_QUERY and a hint-related error message

I also reran the targeted test locally:

  • npm test -- spec/ParseQuery.hint.spec.js

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.

Hint with invalid index returns internal server error

2 participants