Skip to content

fix: Server crash from unhandled promise rejection when multiple Cloud Code validator fields fail#10540

Open
dblythy wants to merge 2 commits into
parse-community:alphafrom
dblythy:fix/validator-multiple-field-crash
Open

fix: Server crash from unhandled promise rejection when multiple Cloud Code validator fields fail#10540
dblythy wants to merge 2 commits into
parse-community:alphafrom
dblythy:fix/validator-multiple-field-crash

Conversation

@dblythy

@dblythy dblythy commented Jul 4, 2026

Copy link
Copy Markdown
Member

Closes #8826

Summary by CodeRabbit

  • Bug Fixes
    • Fixed an issue where validation failures involving multiple fields could trigger an unhandled rejection.
    • Invalid input now reliably returns a validation error without leaving behind unexpected async errors.

@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

coderabbitai Bot commented Jul 4, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Fixes a server crash caused by an unhandled promise rejection when multiple Cloud Code validated fields fail simultaneously. Refactors field validation in builtInTriggerValidator to collect validation inputs before invoking Promise.all, and adds a regression test verifying no unhandled rejection occurs.

Changes

Validation rejection fix

Layer / File(s) Summary
Refactor field validation scheduling
src/triggers.js
Replaces immediate validateOptions promise creation with collection of [opt, key, val] tuples into optionValidations, then runs Promise.all(optionValidations.map(...)) after the loop.
Regression test for unhandled rejection
spec/CloudCode.Validator.spec.js
Adds a test that attaches an unhandledRejection listener, triggers a function with multiple invalid fields, asserts the rejection is a Parse.Error.VALIDATION_ERROR, verifies no unhandled rejections were captured, and removes the listener in finally.

Estimated code review effort: 2 (Simple) | ~10 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CloudFunction
  participant builtInTriggerValidator
  participant validateOptions

  CloudFunction->>builtInTriggerValidator: invoke with multiple invalid fields
  loop for each field in options.fields
    builtInTriggerValidator->>builtInTriggerValidator: collect [opt, key, val] into optionValidations
  end
  builtInTriggerValidator->>validateOptions: Promise.all(optionValidations.map(validateOptions))
  validateOptions-->>builtInTriggerValidator: rejection reasons
  builtInTriggerValidator-->>CloudFunction: reject with VALIDATION_ERROR (no unhandled rejection)
Loading
🚥 Pre-merge checks | ✅ 5 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description only says "Closes #8826" and omits the required Issue, Approach, and Tasks sections. Fill in the template sections for Issue, Approach, and Tasks, and note the test/documentation/security checklist status as applicable.
Engage In Review Feedback ❓ Inconclusive Repo diff shows the fix and tests, but no review-thread history is available to verify discussion before resolving feedback. Provide the PR review comments or discussion history showing feedback was discussed and either implemented in a commit or retracted by the reviewer.
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title starts with the required "fix:" prefix and accurately describes the server crash fix.
Linked Issues check ✅ Passed The changes address #8826 by preventing unhandled rejections in multi-field validation failures and adding a regression test.
Out of Scope Changes check ✅ Passed The diff stays focused on the reported validation crash and its regression test with no unrelated code changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Security Check ✅ Passed Patch only changes validation scheduling and adds a regression test; no new auth, injection, or sensitive-data paths, and it reduces an unhandled-rejection crash risk.
✨ 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.

🔧 Biome (2.5.1)
src/triggers.js

File contains syntax errors that prevent linting: Line 230: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax.; Line 230: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax.; Line 230: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax.; Line 230: return types can only be used in TypeScript files


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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/triggers.js (1)

903-912: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Same latent pattern remains in the requireUserKeys branch.

This block still invokes validateOptions(...) immediately inside the loop before Promise.all, the same pattern that caused #8826 in the options.fields branch. It's not currently exploitable here since no other statement in this loop throws synchronously, but it's structurally fragile — any future addition of a synchronous check (e.g. a required validation) in this loop would reintroduce the same unhandled-rejection risk. Consider applying the same input-deferral pattern here for consistency.

♻️ Suggested consistency fix
   } else if (typeof userKeys === 'object') {
-    const optionPromises = [];
+    const optionValidations = [];
     for (const key in options.requireUserKeys) {
       const opt = options.requireUserKeys[key];
       if (opt.options) {
-        optionPromises.push(validateOptions(opt, key, reqUser.get(key)));
+        optionValidations.push([opt, key, reqUser.get(key)]);
       }
     }
-    await Promise.all(optionPromises);
+    await Promise.all(optionValidations.map(([o, k, v]) => validateOptions(o, k, v)));
   }
🤖 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 `@src/triggers.js` around lines 903 - 912, The `requireUserKeys` branch in
`src/triggers.js` has the same eager-promise pattern as the earlier
`options.fields` fix: `validateOptions(...)` is being invoked directly inside
the loop before `Promise.all`, which can reintroduce unhandled-rejection risk if
a future synchronous check is added. Update the logic in this branch to defer
execution the same way as the `options.fields` path, collecting functions/thunks
(or equivalent deferred work) and only invoking `validateOptions` during the
`Promise.all` phase, keeping `userKeys` handling consistent and safe.
🤖 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 `@src/triggers.js`:
- Around line 903-912: The `requireUserKeys` branch in `src/triggers.js` has the
same eager-promise pattern as the earlier `options.fields` fix:
`validateOptions(...)` is being invoked directly inside the loop before
`Promise.all`, which can reintroduce unhandled-rejection risk if a future
synchronous check is added. Update the logic in this branch to defer execution
the same way as the `options.fields` path, collecting functions/thunks (or
equivalent deferred work) and only invoking `validateOptions` during the
`Promise.all` phase, keeping `userKeys` handling consistent and safe.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4d4e34ea-7b2f-4ebd-a9aa-6101770f1c21

📥 Commits

Reviewing files that changed from the base of the PR and between 7e9d53a and 6a047b4.

📒 Files selected for processing (2)
  • spec/CloudCode.Validator.spec.js
  • src/triggers.js

@dblythy dblythy requested review from a team and mtrezza July 4, 2026 16:33
@codecov

codecov Bot commented Jul 4, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.66%. Comparing base (459786f) to head (a12c773).
⚠️ Report is 1 commits behind head on alpha.

Additional details and impacted files
@@           Coverage Diff           @@
##            alpha   #10540   +/-   ##
=======================================
  Coverage   92.66%   92.66%           
=======================================
  Files         193      193           
  Lines       16981    16981           
  Branches      248      248           
=======================================
  Hits        15736    15736           
  Misses       1224     1224           
  Partials       21       21           

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

@Moumouls

Moumouls commented Jul 6, 2026

Copy link
Copy Markdown
Member

@coderabbitai what is the practical use case where the server crashed ?

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd triggers.js src
echo "---"
ast-grep run --pattern 'function builtInTriggerValidator($$$) { $$$ }' --lang js src/triggers.js | head -100

Length of output: 5201


@Moumouls Good question — let me walk through the exact mechanics of the crash.

In src/triggers.js, inside builtInTriggerValidator, when options.fields is a plain object (not an array), the code loops over each field key (around Line 819 onward). For each field:

  • If the field has opt.required set, it calls requiredParam(key) (Line 774-779), which throws synchronously (a plain string) if the value is missing.
  • If the field has opt.type/opt.options, it calls validateOptions(opt, key, val) (Line 781-807), which is an async function. Calling an async function immediately starts executing it and returns a Promise right away — even before anyone awaits it.

Before the fix, the code did:

optionPromises.push(validateOptions(opt, key, val)); // called immediately, inside the loop

and only after the entire for...in loop finished did it call await Promise.all(optionPromises).

Here's the crash scenario matching #8826: imagine a fields config like

fields: {
  type: { type: String, options: ['a', 'b'] }, // validated first
  project: { required: true }                   // validated second
}
  1. The loop first hits type. Since an invalid type value was sent, validateOptions() is invoked immediately — this creates a Promise that will eventually reject (because the value isn't in opts). This rejected promise is pushed into optionPromises, but nothing has "handled" it yet.
  2. The loop then hits project. Since project is missing, requiredParam('project') throws synchronously, right there inside the for...in loop body.
  3. That synchronous throw immediately unwinds the loop — execution never reaches the await Promise.all(optionPromises) line.
  4. The type validation promise created in step 1 is now orphaned: it rejects on its own (asynchronously, on a later microtask tick) with no .catch() or Promise.all() ever attached to it.
  5. Node.js detects this as an unhandled promise rejection, which (depending on the Node version/flags, e.g., --unhandled-rejections=strict, or if there's no global handler) can crash the whole server process.

So the practical trigger is: a Cloud Code validator with a fields object containing more than one field where at least one fails via a synchronous throw (e.g., a missing required field) and another fails via the async validateOptions path (e.g., an invalid type/options value) in the same request. If both fail simultaneously, the async one's promise gets abandoned instead of aggregated, producing the unhandled rejection.

The fix defers invocation of validateOptions() — it now just collects [opt, key, val] tuples during the loop and only creates/awaits the promises together via Promise.all(optionValidations.map(...)) after the loop (and any synchronous throws) complete. This ensures no async validation promise is ever created without being immediately covered by Promise.all.

@Moumouls

Moumouls commented Jul 6, 2026

Copy link
Copy Markdown
Member

@coderabbitai does the test correctly cover the issue, with a try/catch system within the test any chance of a false positive test even in case of a crash ?

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd "CloudCode.Validator.spec.js" spec
echo "---"
rg -n "unhandled rejection when multiple fields" -A 40 spec/CloudCode.Validator.spec.js | head -80

Length of output: 1836


@Moumouls Good instinct to double-check this — let me be precise about what the test actually does, because "try/catch masking a crash" is a real anti-pattern I'd also be wary of, but that's not what's happening here.

There is no try/catch in this test — it's try/finally.

try {
  Parse.Cloud.define('hello', () => 'Hello world!', {
    fields: {
      type: { type: String, options: ['Option A', 'Option B'] },
      project: { required: true },
    },
  });
  await expectAsync(Parse.Cloud.run('hello', { type: 'Invalid' })).toBeRejectedWith(
    jasmine.objectContaining({ code: Parse.Error.VALIDATION_ERROR })
  );
  await new Promise(resolve => setTimeout(resolve, 100));
  expect(rejections).toEqual([]);
} finally {
  process.removeListener('unhandledRejection', onUnhandledRejection);
}

The finally block only detaches the process.on('unhandledRejection', ...) listener for cleanup — it does not catch or swallow any thrown error. If expectAsync(...).toBeRejectedWith(...) fails, or if expect(rejections).toEqual([]) fails, that assertion error propagates normally and Jasmine will mark the test as failed. So there's no risk of the test silently passing due to an exception being swallowed.

Why the unhandledRejection listener approach is actually the correct way to catch this, not a source of false positives:

Node.js only terminates the process on an unhandled rejection when there are zero listeners registered for the 'unhandledRejection' event at the time it fires. By registering onUnhandledRejection before triggering the bug, the test:

  1. Prevents the crash from actually taking down the whole test process (which would otherwise abort the suite non-deterministically).
  2. Captures the rejection reason into the rejections array instead.
  3. Asserts rejections is empty afterward.

So if the pre-fix code path in src/triggers.js were still in place — where validateOptions('type', ...) creates a promise before the synchronous requiredParam('project') throw aborts the loop — the orphaned rejection from type validation would land in rejections, and expect(rejections).toEqual([]) would correctly fail. This is a standard and reliable pattern for testing "does this code path produce an unhandled rejection" without letting it actually crash your test runner.

Field ordering also matches the exact repro from #8826: type (async validateOptions path) is declared before project (sync requiredParam throw), so the loop hits the async path first, then throws synchronously on project — exactly the sequence needed to orphan the first promise before the fix.

One caveat worth noting: the setTimeout(resolve, 100) delay is a timing heuristic to give the orphaned rejection's microtask a chance to surface as an unhandledRejection event (Node needs at least one macrotask tick to fire the event) before the assertion runs. 100ms is generous and should be reliable in CI, but it is technically a heuristic rather than a deterministic guarantee. If you want to eliminate that heuristic entirely, an alternative is to use setImmediate/process.nextTick chaining instead of a fixed timeout, but in practice 100ms is a safe margin and shouldn't cause flakiness.

So to directly answer: yes, the test correctly reproduces and covers the crash scenario, and no, there's no try/catch masking a failure — a real crash-triggering regression would cause this test to fail, not silently pass.

Comment thread src/triggers.js

@mtrezza mtrezza left a comment

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.

Please resolve any open discussions

@Moumouls

Moumouls commented Jul 7, 2026

Copy link
Copy Markdown
Member

@mtrezza For an unknown reason, I can't resolve my comment, really weird.

image

@mtrezza

mtrezza commented Jul 7, 2026

Copy link
Copy Markdown
Member

Resolved, rebased branch

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.

Multiple Validation failures causes server crash

3 participants