Skip to content

fix: unexpected null pointer exception due to race condition#217

Merged
JounQin merged 14 commits intoun-ts:mainfrom
fisker:reliability
May 30, 2025
Merged

fix: unexpected null pointer exception due to race condition#217
JounQin merged 14 commits intoun-ts:mainfrom
fisker:reliability

Conversation

@fisker
Copy link
Contributor

@fisker fisker commented Mar 24, 2025

This PR fixes #185 which is related to #184 that introduced possible undefined messages from port to main, we handle it gracefully now, and it also adds a new reliability test case to ensure no such regression anymore, this fix will be cherry picked into 0.9.x/0.10.x also.

cc @jedlikowski


Important

Fixes race condition causing null pointer exception by reverting #156 and adding a reliability test.

  • Fix:
    • Reverts refactor: lazy initialize caches #156 to address race condition causing null pointer exception.
    • Changes globalsCache and syncFnCache to always initialize as Map in helpers.ts and index.ts.
  • Testing:
    • Adds reliability.spec.ts to run 1,000 or 1,000,000 iterations based on environment.
    • Introduces worker-identity.js for identity function testing.
  • Misc:
    • Updates changeset in .changeset/sharp-olives-itch.md to document the fix.

This description was created by Ellipsis for 4fac75c. You can customize this summary. It will automatically update as commits are pushed.

Summary by CodeRabbit

  • Bug Fixes

    • Resolved a rare issue that could cause a null pointer exception due to a race condition, improving reliability.
  • Tests

    • Added a comprehensive reliability test to ensure consistent synchronous function behavior.
    • Updated test imports for improved clarity and maintainability.
  • Chores

    • Adjusted type coverage settings to ignore the "lib" directory instead of all type definition files.
    • Added documentation for the patch update.

@changeset-bot
Copy link

changeset-bot bot commented Mar 24, 2025

🦋 Changeset detected

Latest commit: b701670

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
synckit Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@codesandbox-ci
Copy link

codesandbox-ci bot commented Mar 24, 2025

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Mar 24, 2025

Open in StackBlitz

npm i https://pkg.pr.new/synckit@217

commit: b701670

@codecov
Copy link

codecov bot commented Mar 24, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.82%. Comparing base (27017a0) to head (b701670).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #217      +/-   ##
==========================================
+ Coverage   95.79%   95.82%   +0.02%     
==========================================
  Files           4        4              
  Lines         333      335       +2     
  Branches      153      154       +1     
==========================================
+ Hits          319      321       +2     
+ Misses         14       11       -3     
- Partials        0        3       +3     

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 2, 2025

Walkthrough

The updates introduce a new reliability test that repeatedly calls a synchronous worker function, add a simple worker identity script, and enhance robustness in message handling within the worker communication logic. Additionally, configuration and documentation files are updated to reflect these changes and address a race condition issue.

Changes

File(s) Change Summary
test/reliability.spec.ts, test/worker-identity.js Added a reliability test that invokes a worker identity function 1,000,000 times; added worker script.
src/helpers.ts Improved message handling to safely process undefined or missing messages from worker threads.
.changeset/shiny-kids-check.md Added a changeset documenting a patch for a null pointer exception race condition.
package.json Updated typeCoverage.ignoreFiles to ignore the lib directory instead of **/*.d.ts.
test/types-d.cts Changed synckit import from a relative path to a package import.

Sequence Diagram(s)

sequenceDiagram
    participant TestRunner as test/reliability.spec.ts
    participant MainThread as Main Thread
    participant Worker as worker-identity.js

    TestRunner->>MainThread: createSyncFn(worker-identity.js)
    loop 1,000,000 times
        TestRunner->>MainThread: identityFn(i)
        MainThread->>Worker: Send message with i
        Worker->>MainThread: Return i
        MainThread->>TestRunner: Return i
        TestRunner->>TestRunner: Assert returned value === i
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Handle undefined or missing messages from worker to prevent errors (#185)

Poem

In the warren of code, a bug did appear,
Undefined messages would cause us to fear.
With a hop and a patch, the race is now won,
A million tests later, the fix is done!
🐇✨ Reliable threads, let’s all give a cheer!

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.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/helpers.ts

Oops! Something went wrong! :(

ESLint: 9.27.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@1stg/eslint-config' imported from /eslint.config.js
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:799:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:723:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:706:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:307:38)
at #link (node:internal/modules/esm/module_job:170:49)

test/reliability.spec.ts

Oops! Something went wrong! :(

ESLint: 9.27.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@1stg/eslint-config' imported from /eslint.config.js
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:799:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:723:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:706:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:307:38)
at #link (node:internal/modules/esm/module_job:170:49)

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

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

@sonarqubecloud
Copy link

@JounQin JounQin force-pushed the reliability branch 2 times, most recently from c3ccc24 to 8f2dae7 Compare May 30, 2025 00:01
@JounQin JounQin changed the title test: add "reliability" test fix: unexpected null pointer exception due to race condition May 30, 2025
@JounQin JounQin requested a review from Copilot May 30, 2025 00:04
@JounQin JounQin self-assigned this May 30, 2025
@JounQin JounQin added the bug Something isn't working label May 30, 2025
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR reverts the previous cache initialization change (#156) by eagerly initializing module-level caches and adds a high-iteration reliability test to catch race-condition–related null pointer errors.

  • Initialize syncFnCache and globalsCache as non-undefined Maps to avoid race-condition nulls.
  • Add a new worker-identity.js and reliability.spec.ts to stress-test createSyncFn returns.
  • Ensure the fix is applied to both mainline and 0.9.x/0.10.x branches.

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
test/worker-identity.js Introduces a basic worker identity function test
test/reliability.spec.ts Adds a looped reliability test for createSyncFn
src/index.ts Changes syncFnCache from lazy to eager init
src/helpers.ts Changes globalsCache from lazy to eager init

@JounQin JounQin marked this pull request as ready for review May 30, 2025 00:05
Copy link

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed everything up to 4fac75c in 1 minute and 24 seconds. Click for details.
  • Reviewed 90 lines of code in 5 files
  • Skipped 0 files when reviewing.
  • Skipped posting 5 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. .changeset/sharp-olives-itch.md:1
  • Draft comment:
    Changelog looks clear and the version bump is appropriate.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
2. src/helpers.ts:396
  • Draft comment:
    Pre-initialize globalsCache as a constant to avoid lazy initialization race conditions.
  • Reason this comment was not posted:
    Comment looked like it was already resolved.
3. src/index.ts:29
  • Draft comment:
    Similarly, pre-initializing syncFnCache avoids potential race conditions caused by lazy initialization.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative, explaining why pre-initializing syncFnCache is beneficial. It doesn't suggest a change or ask for confirmation of intent. According to the rules, purely informative comments should be removed.
4. test/reliability.spec.ts:6
  • Draft comment:
    The reliability test is a strong addition; however, verify that 1e6 iterations under CI don’t cause performance issues or CI timeouts.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
5. test/worker-identity.js:1
  • Draft comment:
    Worker identity file is minimal and correct, echoing the input via runAsWorker.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None

Workflow ID: wflow_daYwOxY3KQw0e3Tb

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

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: 0

♻️ Duplicate comments (1)
test/reliability.spec.ts (1)

6-6: Consider adding timeout protection for the reliability test.

While the environment-based iteration count addresses previous feedback about performance, the test lacks timeout protection which could cause indefinite hangs if the race condition being tested manifests as a deadlock.

Consider adding a test timeout or making the iteration count more configurable:

// eslint-disable-next-line @typescript-eslint/no-magic-numbers
-const times = process.env.CI ? 1e6 : 1e3
+const times = process.env.TEST_ITERATIONS 
+  ? parseInt(process.env.TEST_ITERATIONS, 10) 
+  : process.env.CI ? 1e6 : 1e3
🧹 Nitpick comments (1)
test/reliability.spec.ts (1)

8-20: Enhance the reliability test with better error reporting and timeout protection.

The test structure is solid for detecting race conditions, but could benefit from improvements to make debugging easier and prevent indefinite hangs.

Consider these enhancements:

-test(`Reliability (${times} runs)`, async () => {
+test(`Reliability (${times} runs)`, async () => {
   const { createSyncFn } = await import('synckit')
   const identity = createSyncFn(path.resolve(_dirname, `./worker-identity.js`))

   for (let index = 0; index < times; index++) {
     try {
       expect(identity(index)).toBe(index)
     } catch (error) {
-      console.log(`Failed on ${index + 1} run.`)
+      console.error(`Failed on run ${index + 1}/${times}. Input: ${index}, Error:`, error)
       throw error
     }
   }
-})
+}, 60000) // 60 second timeout to prevent indefinite hangs

This adds:

  • More detailed error logging including the error details
  • A reasonable timeout to prevent CI hangs if the race condition causes deadlocks
  • Better context in the error message
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 27017a0 and 4fac75c.

📒 Files selected for processing (5)
  • .changeset/sharp-olives-itch.md (1 hunks)
  • src/helpers.ts (1 hunks)
  • src/index.ts (1 hunks)
  • test/reliability.spec.ts (1 hunks)
  • test/worker-identity.js (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
test/worker-identity.js (1)
src/index.ts (1)
  • runAsWorker (96-149)
test/reliability.spec.ts (2)
src/index.ts (1)
  • createSyncFn (50-78)
test/helpers.ts (1)
  • _dirname (9-9)
src/index.ts (1)
src/types.ts (1)
  • AnyFn (6-6)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Lint and Test with Node.js 24 on windows-latest
  • GitHub Check: Lint and Test with Node.js 24 on macos-latest
  • GitHub Check: Lint and Test with Node.js 24 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 23 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 23 on macos-latest
  • GitHub Check: Lint and Test with Node.js 23 on windows-latest
  • GitHub Check: Lint and Test with Node.js 22 on windows-latest
  • GitHub Check: Lint and Test with Node.js 22 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 20 on windows-latest
  • GitHub Check: Lint and Test with Node.js 20 on macos-latest
  • GitHub Check: Lint and Test with Node.js 20 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 18.18 on windows-latest
  • GitHub Check: Lint and Test with Node.js 18 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 18 on windows-latest
  • GitHub Check: Lint and Test with Node.js 18 on macos-latest
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (5)
src/helpers.ts (1)

399-399: Excellent fix for the race condition!

Eagerly initializing globalsCache as a constant Map eliminates the race condition that could occur when multiple threads attempted to initialize the cache simultaneously using the previous lazy initialization pattern. This directly addresses the null pointer exception issue described in the PR objectives.

.changeset/sharp-olives-itch.md (1)

1-6: Well-documented changeset entry.

The changeset accurately describes the patch addressing the race condition that caused null pointer exceptions. The format and content are appropriate for a patch-level change.

test/worker-identity.js (1)

1-4: Simple and effective reliability test worker.

The identity function implementation is perfect for testing the worker thread mechanism and detecting race conditions without introducing complexity. This complements the reliability tests mentioned in the AI summary.

src/index.ts (1)

32-32: Consistent race condition fix applied.

Eagerly initializing syncFnCache as a constant Map mirrors the same pattern applied in src/helpers.ts and effectively prevents the race condition that could occur during lazy initialization. This change directly contributes to resolving the null pointer exceptions mentioned in the PR objectives.

test/reliability.spec.ts (1)

1-3: LGTM! Clean and appropriate imports.

The imports are well-structured with proper separation between Node.js built-in modules and local helpers.

@JounQin JounQin force-pushed the reliability branch 4 times, most recently from d7ecceb to 6f45612 Compare May 30, 2025 00:52
@sonarqubecloud
Copy link

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: 0

🧹 Nitpick comments (1)
package.json (1)

147-147: Review ignoreFiles pattern: broad directory ignore may hide relevant files
Changing ignoreFiles from "**/*.d.ts" to "lib" will exclude the entire compiled output directory—including any new file types you might unintentionally place there—from type coverage. Consider narrowing the pattern to only ignore declaration files, e.g.:

  "typeCoverage": {
    "ignoreFiles": [
-     "lib"
+     "lib/**/*.d.ts"
    ],
    …
  }

This ensures that only .d.ts artifacts are skipped, while still auditing any other files under lib.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 31dbe54 and b701670.

📒 Files selected for processing (5)
  • .changeset/shiny-kids-check.md (1 hunks)
  • package.json (1 hunks)
  • src/helpers.ts (2 hunks)
  • test/reliability.spec.ts (1 hunks)
  • test/types-d.cts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • .changeset/shiny-kids-check.md
  • test/types-d.cts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/helpers.ts
  • test/reliability.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms (18)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Lint and Test with Node.js 24 on windows-latest
  • GitHub Check: Lint and Test with Node.js 24 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 22 on windows-latest
  • GitHub Check: Lint and Test with Node.js 23 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 23 on macos-latest
  • GitHub Check: Lint and Test with Node.js 23 on windows-latest
  • GitHub Check: Lint and Test with Node.js 22 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 22 on macos-latest
  • GitHub Check: Lint and Test with Node.js 18 on macos-latest
  • GitHub Check: Lint and Test with Node.js 18.18 on windows-latest
  • GitHub Check: Lint and Test with Node.js 18.18 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 20 on windows-latest
  • GitHub Check: Lint and Test with Node.js 20 on macos-latest
  • GitHub Check: Lint and Test with Node.js 18 on windows-latest
  • GitHub Check: Lint and Test with Node.js 18 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 18.18 on macos-latest
  • GitHub Check: Lint and Test with Node.js 20 on ubuntu-latest

@JounQin JounQin merged commit 2a3f936 into un-ts:main May 30, 2025
31 checks passed
@fisker fisker deleted the reliability branch May 30, 2025 04:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

random undefined message causes synckit to throw an error

3 participants