Skip to content

feat: Add requestComplexity.subqueryLimit option to limit subquery results#10420

Merged
mtrezza merged 2 commits intoparse-community:alphafrom
mtrezza:fix/subquery-result-limit
Apr 10, 2026
Merged

feat: Add requestComplexity.subqueryLimit option to limit subquery results#10420
mtrezza merged 2 commits intoparse-community:alphafrom
mtrezza:fix/subquery-result-limit

Conversation

@mtrezza
Copy link
Copy Markdown
Member

@mtrezza mtrezza commented Apr 10, 2026

Issue

Subquery operators ($inQuery, $notInQuery, $select, $dontSelect) run internal subqueries without any result limit, allowing unbounded memory growth

Tasks

  • Add new feature
  • Add tests
  • Add changes to documentation (guides, repository pages, in-code descriptions)

@parse-github-assistant
Copy link
Copy Markdown

parse-github-assistant bot commented Apr 10, 2026

🚀 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 Apr 10, 2026

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: 7c41802d-9330-4533-bf37-4b2793062fb1

📥 Commits

Reviewing files that changed from the base of the PR and between 9421f03 and 5aef1cb.

📒 Files selected for processing (1)
  • spec/RequestComplexity.spec.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • spec/RequestComplexity.spec.js

📝 Walkthrough

Walkthrough

Adds a new subqueryLimit requestComplexity option (default -1) and enforces it by limiting subquery result counts for $inQuery, $notInQuery, $select, and $dontSelect for non-master/non-maintenance requests; tests cover limits, bypasses, and config behavior.

Changes

Cohort / File(s) Summary
Configuration & Types
src/Options/Definitions.js, src/Options/index.js, src/Options/docs.js
Introduce subqueryLimit in RequestComplexity options (env PARSE_SERVER_REQUEST_COMPLEXITY_SUBQUERY_LIMIT), numeric parser, documentation, and default -1 (disabled).
Query Execution Logic
src/RestQuery.js
When request is not master/maintenance and requestComplexity.subqueryLimit > 0, set additionalOptions.limit on subqueries in replaceInQuery, replaceNotInQuery, replaceSelect, and replaceDontSelect so child subqueries return at most that many results.
Tests
spec/RequestComplexity.spec.js
Add subquery result limit tests: verify $inQuery/$select return limited results, $notInQuery/$dontSelect return complement counts, and confirm master/maintenance or -1 disables the limit; also assert config/default behavior.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client
  participant API as Parse Server API
  participant RestQ as RestQuery.replaceX
  participant SubQ as Subquery Executor
  participant DB as Database

  Client->>API: request with $inQuery/$select/etc.
  API->>RestQ: build/replace subquery clause
  RestQ->>RestQ: read config.requestComplexity.subqueryLimit
  RestQ->>SubQ: execute subquery (with additionalOptions.limit = subqueryLimit)
  SubQ->>DB: run limited query
  DB-->>SubQ: limited result set
  SubQ-->>RestQ: results -> transform to $in/$nin pointers
  RestQ-->>API: finalized query
  API-->>Client: response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is entirely empty; no content was provided by the author beyond the repository template. Add a comprehensive description including the Issue (what problem this solves), Approach (how the changes work), and confirmation of completed Tasks from the template.
Security Check ❓ Inconclusive Unable to execute shell commands to analyze PR code changes for security vulnerabilities. Please provide the actual code diff or file contents to enable security analysis of the PR.
Engage In Review Feedback ❓ Inconclusive Cannot verify review feedback engagement; GitHub PR discussion and review comments are not accessible from repository structure. Examine PR #10420 directly on GitHub to review all comments from reviewers and verify whether changes were made in response to feedback.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The PR title begins with the required 'feat:' prefix and clearly describes the main change: adding a new requestComplexity.subqueryLimit option to limit subquery results.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

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

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.

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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
spec/RequestComplexity.spec.js (1)

807-829: Consider adding maintenance-key bypass coverage as well.

You already validate master bypass; adding one maintenance-key assertion here would keep parity with other request-complexity suites and guard privileged-path regressions.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@spec/RequestComplexity.spec.js` around lines 807 - 829, Add a test that
mirrors the master-key bypass case but uses the maintenance key: create an it
block like "should allow unlimited subquery results with maintenance key" that
builds the same where ($inQuery against 'Target'), calls rest.find(config,
auth.maintenance(config), 'Source', where) and asserts result.results.length ===
totalObjects; place it alongside the existing master-key test to provide parity
and protect privileged-path regressions.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/RestQuery.js`:
- Around line 566-571: The guard checking rc.subqueryLimit > 0 incorrectly
treats 0 as "no limit"; update the checks in the four subquery replacement
methods (replaceInQuery, replaceNotInQuery, replaceSelect, replaceDontSelect) to
apply the limit whenever rc.subqueryLimit !== -1 (i.e., only treat -1 as
disabled) and set additionalOptions.limit = rc.subqueryLimit as before; also add
a regression test verifying that subqueryLimit: 0 enforces a zero limit behavior
(and that -1 disables it).

---

Nitpick comments:
In `@spec/RequestComplexity.spec.js`:
- Around line 807-829: Add a test that mirrors the master-key bypass case but
uses the maintenance key: create an it block like "should allow unlimited
subquery results with maintenance key" that builds the same where ($inQuery
against 'Target'), calls rest.find(config, auth.maintenance(config), 'Source',
where) and asserts result.results.length === totalObjects; place it alongside
the existing master-key test to provide parity and protect privileged-path
regressions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a0a8c252-df0a-4cf3-8110-7d953fd29de7

📥 Commits

Reviewing files that changed from the base of the PR and between df5e97f and 9421f03.

📒 Files selected for processing (5)
  • spec/RequestComplexity.spec.js
  • src/Options/Definitions.js
  • src/Options/docs.js
  • src/Options/index.js
  • src/RestQuery.js

@codecov
Copy link
Copy Markdown

codecov bot commented Apr 10, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.49%. Comparing base (18482e3) to head (5aef1cb).
⚠️ Report is 3 commits behind head on alpha.

Additional details and impacted files
@@            Coverage Diff             @@
##            alpha   #10420      +/-   ##
==========================================
- Coverage   92.50%   92.49%   -0.01%     
==========================================
  Files         192      192              
  Lines       16770    16786      +16     
  Branches      234      234              
==========================================
+ Hits        15513    15527      +14     
- Misses       1234     1236       +2     
  Partials       23       23              

☔ View full report in Codecov by Sentry.
📢 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.

@mtrezza
Copy link
Copy Markdown
Member Author

mtrezza commented Apr 10, 2026

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 10, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@mtrezza
Copy link
Copy Markdown
Member Author

mtrezza commented Apr 10, 2026

@coderabbitai review your feedback conversations and resolve where you found a consensus

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 10, 2026

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Get all review comments on PR `#10420` made by coderabbitai
gh pr view 10420 --repo parse-community/parse-server --json reviews,comments

# Get all review thread comments
gh api repos/parse-community/parse-server/pulls/10420/comments --paginate | jq '[.[] | {id, body: .body[:200], user: .user.login, path: .path, line: .line, resolved: (if .in_reply_to_id then "reply" else "root" end)}]'

# Get review threads state
gh api repos/parse-community/parse-server/pulls/10420/reviews --paginate | jq '[.[] | {id, state, user: .user.login, body: .body[:100]}]'

Length of output: 26751


🏁 Script executed:

#!/bin/bash
# Find and resolve the review threads on this PR
# First, get the pull request node ID and review thread IDs
gh api graphql -f query='
{
  repository(owner: "parse-community", name: "parse-server") {
    pullRequest(number: 10420) {
      id
      reviewThreads(first: 20) {
        nodes {
          id
          isResolved
          path
          line
          comments(first: 3) {
            nodes {
              author { login }
              body
              databaseId
            }
          }
        }
      }
    }
  }
}' | jq '.data.repository.pullRequest.reviewThreads.nodes[] | {id, isResolved, path, line, firstAuthor: .comments.nodes[0].author.login, bodySnippet: .comments.nodes[0].body[:80]}'

Length of output: 240


🏁 Script executed:

#!/bin/bash
# Resolve the thread on src/RestQuery.js line 571 where consensus was reached
gh api graphql -f query='
mutation {
  resolveReviewThread(input: { threadId: "PRRT_kwDOAwQnRs56KZFt" }) {
    thread {
      id
      isResolved
    }
  }
}'

Length of output: 92


@mtrezza I've reviewed all feedback threads and taken the following actions:

  1. src/RestQuery.js line 571 — Resolved ✅. Consensus was reached: I flagged the > 0 guard as potentially mishandling subqueryLimit: 0, but you correctly pointed out that Config.js already rejects 0 (all requestComplexity integer options must be a positive integer or -1), making the guard correct. I've saved this as a long-term learning to avoid flagging it in future reviews.

  2. spec/RequestComplexity.spec.js nitpick (maintenance-key bypass test) — Already addressed in code ✅. The latest commit includes auth.maintenance assertions alongside the auth.master assertions, fulfilling the parity suggestion. This was a review-body nitpick rather than a separate thread, so no thread resolution was needed.


🧠 Learnings used
Learnt from: CR
Repo: parse-community/parse-server PR: 0
File: coderabbit-custom-pre-merge-checks-unique-id-file-non-traceable-F7F2B60C-1728-4C9A-8889-4F2235E186CA.txt:0-0
Timestamp: 2026-04-01T13:35:45.477Z
Learning: Engage in review feedback: The user must engage in review of feedback comments, and not ignore or resolve a review feedback without prior engagement in a discussion and either implementing the feedback via a commit, or convincing the reviewer of their standpoint to retract the feedback.

Learnt from: mtrezza
Repo: parse-community/parse-server PR: 10420
File: src/RestQuery.js:566-571
Timestamp: 2026-04-10T15:15:28.778Z
Learning: In parse-community/parse-server (src/RestQuery.js), the `> 0` guard used for `requestComplexity` sub-options (e.g., `rc.subqueryLimit > 0`, `rc.subqueryDepth`, `rc.queryDepth`, `rc.includeDepth`) is correct and intentional. Config.js validation already rejects `0` — all `requestComplexity` integer options must be a positive integer or `-1`. The server won't start with a value of `0`, so `0` can never reach runtime as an "unlimited" edge case. Do not flag `> 0` guards for these options as potentially missing the `0` case.

Learnt from: Moumouls
Repo: parse-community/parse-server PR: 0
File: :0-0
Timestamp: 2026-03-28T19:24:55.383Z
Learning: In parse-community/parse-server (PR `#10341`), `requestComplexity.batchRequestLimit` intentionally defaults to `-1` (unlimited) in PS9. This is by design: batch request limiting is opt-in in the current major version and will become a hard default (safe non-unlimited value) in PS10, consistent with the same opt-in policy already established for other `requestComplexity` sub-options (e.g., `includeLimit`). Do not flag the `-1` default as a security gap for PS9.

Learnt from: mtrezza
Repo: parse-community/parse-server PR: 10130
File: src/RestQuery.js:461-475
Timestamp: 2026-03-07T22:41:26.717Z
Learning: In Parse Server's RestQuery.js (_UnsafeRestQuery), subquery nesting depth is correctly tracked via `context._subqueryDepth` rather than an instance field. This is intentional: each child RestQuery is a new instance with no reference to its parent, so depth must propagate through the context object using the spread pattern `{ ...this.context, _subqueryDepth: (this.context._subqueryDepth || 0) + 1 }`. Trigger handlers are safe because triggers.js:306 passes `Object.assign({}, context)` — a shallow copy — so `_subqueryDepth` is read-only from a trigger's perspective and cannot corrupt depth tracking.

Learnt from: mtrezza
Repo: parse-community/parse-server PR: 10130
File: src/RestQuery.js:890-910
Timestamp: 2026-03-07T22:42:53.791Z
Learning: In Parse Server's RestQuery.js, `validateIncludeComplexity` intentionally counts raw `this.include.length` (not deduplicated paths) for the `includeCount` limit. This is by design: the limit caps total request complexity, not unique paths. Deduplicating before the check would weaken the protection. Note: user-supplied include strings are already deduplicated at construction via `pathSet`, but `handleIncludeAll` may add array references with reference-inequality duplicates — that is a pre-existing concern separate from this security check.

Learnt from: EmpiDev
Repo: parse-community/parse-server PR: 9770
File: spec/CloudCode.spec.js:446-469
Timestamp: 2025-08-26T14:06:31.853Z
Learning: In the Parse Server codebase, when handling query objects in maybeRunAfterFindTrigger, objects without a where property that contain options like limit/skip should be treated as query JSON with an empty where clause using the spread pattern { where: {}, ...query }, not nested as { where: query }.

@mtrezza mtrezza merged commit bf40004 into parse-community:alpha Apr 10, 2026
24 checks passed
parseplatformorg pushed a commit that referenced this pull request Apr 10, 2026
# [9.8.0-alpha.12](9.8.0-alpha.11...9.8.0-alpha.12) (2026-04-10)

### Features

* Add `requestComplexity.subqueryLimit` option to limit subquery results ([#10420](#10420)) ([bf40004](bf40004))
@parseplatformorg
Copy link
Copy Markdown
Contributor

🎉 This change has been released in version 9.8.0-alpha.12

@parseplatformorg parseplatformorg added the state:released-alpha Released as alpha version label Apr 10, 2026
@mtrezza mtrezza deleted the fix/subquery-result-limit branch April 10, 2026 15:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state:released-alpha Released as alpha version

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants