Skip to content

feat: Bun Runtime Support. Migrate from Piscina to Tinypool for worker thread management#716

Merged
yamadashy merged 8 commits intomainfrom
feat/tinypool
Jul 4, 2025
Merged

feat: Bun Runtime Support. Migrate from Piscina to Tinypool for worker thread management#716
yamadashy merged 8 commits intomainfrom
feat/tinypool

Conversation

@yamadashy
Copy link
Owner

@yamadashy yamadashy commented Jul 4, 2025

This PR migrates the worker thread pool implementation from Piscina to Tinypool, achieving significant bundle size reduction while maintaining full API compatibility and performance.

Related:

Summary

  • Bundle size reduction: 800KB → 38KB (95% reduction)
  • API compatibility: Maintains existing worker thread functionality
  • Performance: No degradation in parallel processing capabilities
  • Runtime support: Added Bun testing to ensure cross-runtime compatibility

Key Changes

Core Migration

  • Replace piscina dependency with tinypool (^1.1.1)
  • Update all import statements and function calls
  • Rename initTinypool to initWorker for better abstraction

Affected Components

  • File processing: fileCollect.ts, fileProcess.ts
  • Security checks: securityCheck.ts
  • Metrics calculation: calculateAllFileMetrics.ts, calculateOutputMetrics.ts
  • Core abstraction: processConcurrency.ts
  • Tests: Updated mocks and test cases

CI Enhancements

  • Added Bun test jobs (3 OS × 2 versions)
  • Added Bun build-and-run jobs for comprehensive validation
  • Ensures compatibility across Node.js and Bun runtimes

Benefits

  1. Lightweight: Dramatically reduced bundle size from 800KB to 38KB
  2. Future-proof: Abstract API allows easy worker pool library changes
  3. Maintained performance: All 5 worker pipelines retain their speed
  4. Cross-runtime: Validated on both Node.js and Bun environments

Testing

  • ✅ All 685 unit tests pass
  • ✅ Integration tests with actual file processing
  • ✅ Build and CLI functionality verified
  • ✅ Bun runtime compatibility confirmed

Checklist

  • Run npm run test
  • Run npm run lint
  • Verified Bun compatibility
  • Updated CI pipeline
  • Maintained API backward compatibility

🤖 Generated with Claude Code

yamadashy and others added 3 commits July 5, 2025 00:23
Replace Piscina with Tinypool to significantly reduce bundle size (800KB → 38KB) while maintaining full API compatibility and performance. This migration affects all worker thread pools used in file processing, security checks, and metrics calculations.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Updated all references throughout the codebase:
- Import statements in 5 core modules
- Function calls in file processing, metrics, and security modules
- Test mocks and descriptions
- Maintained backward compatibility and functionality

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Add Bun test and build jobs to CI pipeline to ensure compatibility across different JavaScript runtimes. This validates the Tinypool migration works correctly with both Node.js and Bun environments.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings July 4, 2025 15:38
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 4, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes replace the Piscina worker pool library with Tinypool throughout the codebase. All concurrency initialization functions, imports, and related tests are updated accordingly. Additionally, the CI workflow is extended to include jobs for testing and building with the Bun JavaScript runtime on multiple operating systems and Bun versions.

Changes

File(s) Change Summary
.github/workflows/ci.yml Added CI jobs for testing and building with Bun runtime across OS and Bun version matrix.
package.json Removed "piscina" dependency; added "tinypool" dependency.
repomix-instruction.md Updated release note to state Tinypool is used for parallel processing instead of Piscina.
src/core/file/fileCollect.ts
src/core/file/fileProcess.ts
src/core/metrics/calculateAllFileMetrics.ts
src/core/metrics/calculateOutputMetrics.ts
src/core/security/securityCheck.ts
Changed imports and worker pool initialization from Piscina to Tinypool (initPiscinainitWorker).
src/shared/processConcurrency.ts Switched from Piscina to Tinypool; renamed and updated export (initPiscinainitWorker).
tests/core/security/securityCheck.test.ts Updated test mock to use initWorker instead of initPiscina.
tests/shared/processConcurrency.test.ts Updated tests to use Tinypool and initWorker instead of Piscina and initPiscina.

Sequence Diagram(s)

sequenceDiagram
    participant CI as GitHub Actions CI
    participant Bun as Bun Runtime
    participant Node as Node.js Runtime
    participant Repo as Code Repository

    CI->>Repo: Checkout code
    alt For each OS and Bun version
        CI->>Bun: Setup Bun runtime
        CI->>Bun: bun install
        CI->>Bun: bun run test
        CI->>Bun: bun run build
        CI->>Bun: bun install --production
        CI->>Bun: node bin/repomix.cjs (run CLI)
        CI->>CI: Upload build artifact
    end
    alt Node.js jobs (existing)
        CI->>Node: Run tests and build as before
    end
Loading
sequenceDiagram
    participant Main as Main Thread
    participant Tinypool as Tinypool Worker Pool
    participant Worker as Worker Thread

    Main->>Tinypool: initWorker(numOfTasks, workerPath)
    loop For each task
        Main->>Tinypool: run(task)
        Tinypool->>Worker: Execute workerPath with task
        Worker-->>Tinypool: Return result
        Tinypool-->>Main: Return result
    end
Loading
✨ Finishing Touches
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in a Comment
  • Commit Unit Tests in branch feat/tinypool

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 auto-generate unit tests to generate unit tests for 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.

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.

@claude
Copy link
Contributor

claude bot commented Jul 4, 2025

Claude finished @yamadashy's task —— View job


PR Review: Piscina to Tinypool Migration

Review Todo List:

  • Read and analyze core abstraction layer (processConcurrency.ts)
  • Review implementation changes in file processing modules
  • Check security and metrics modules changes
  • Analyze test updates and mock changes
  • Review CI/CD pipeline enhancements
  • Provide comprehensive feedback and recommendations

Overall Assessment: ✅ APPROVED

This is an excellent migration that demonstrates strong architectural principles and attention to detail. The changes are well-executed with proper abstraction, comprehensive testing, and significant bundle size benefits.

Key Strengths

🎯 Excellent Abstraction Layer

The migration is brilliantly abstracted through processConcurrency.ts:23-40, which provides a clean API that completely hides the underlying worker pool implementation. This makes future migrations trivial.

📦 Significant Bundle Size Reduction

  • 95% reduction: 800KB → 38KB is an exceptional improvement
  • Maintained functionality: All worker pool features preserved
  • Performance parity: No degradation in parallel processing

🔧 Consistent Implementation

All modules (fileProcess.ts, securityCheck.ts, calculateAllFileMetrics.ts, etc.) follow the same pattern:

const initTaskRunner = (numOfTasks: number) => {
  const pool = initWorker(numOfTasks, workerPath);
  return (task: Task) => pool.run(task);
};

🧪 Comprehensive Testing Strategy

  • Mock updates: Proper migration in processConcurrency.test.ts:66
  • Cross-runtime support: Added Bun testing (CI lines 136-153, 222-247)
  • Build verification: Both Node.js and Bun build-and-run jobs

Technical Review

Configuration Compatibility

The Tinypool configuration in processConcurrency.ts:30-39 maintains all essential features:

  • ✅ Thread pool sizing (min/max)
  • ✅ Environment variable passing
  • ✅ Idle timeout configuration
  • ✅ Worker path resolution

Error Handling

Proper error handling maintained across all modules with consistent patterns:

  • Logging before worker pool initialization
  • Try-catch blocks around worker execution
  • Performance timing and metrics

API Design

The function rename from initTinypool to initWorker (processConcurrency.ts:23) is a smart abstraction that:

  • Hides implementation details
  • Follows the single responsibility principle
  • Makes future migrations seamless

CI/CD Enhancements

Bun Integration

The CI improvements are well-architected:

  • Test jobs: 3 OS × 2 Bun versions = 6 test combinations
  • Build jobs: Complete build-and-run verification
  • Comprehensive coverage: Ensures cross-runtime compatibility

Job Structure

The parallel job structure is efficient and comprehensive:

  • Separate linting, testing, and build verification
  • Matrix strategy for broad compatibility testing
  • Proper artifact upload for debugging

Minor Suggestions

Documentation

Consider adding a brief comment in processConcurrency.ts explaining why Tinypool was chosen over Piscina (bundle size, performance, etc.).

Type Safety

The current implementation is already well-typed, but consider adding a generic type parameter to initWorker for better type inference:

export const initWorker = <T, R>(
  numOfTasks: number, 
  workerPath: string
): Tinypool<T, R> => { ... }

Performance Monitoring

Consider adding a simple performance comparison comment in the PR description showing before/after metrics for typical workloads.

Security Review

No security concerns identified

  • No credential exposure
  • Proper environment variable handling
  • Safe worker path resolution using import.meta.url

Final Recommendation

This PR represents a high-quality migration that:

  • Achieves significant bundle size reduction
  • Maintains backward compatibility
  • Implements proper abstraction patterns
  • Includes comprehensive testing
  • Follows best practices

Recommendation: ✅ APPROVE and MERGE

The migration is production-ready and will provide immediate benefits to users while maintaining the same functionality and performance characteristics.


Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @yamadashy, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly optimizes the application's dependency footprint by replacing the Piscina worker thread management library with Tinypool. This strategic swap not only slashes the bundle size by over 95% but also maintains the existing API and parallel processing performance, ensuring a lightweight yet powerful solution. Furthermore, the change improves the codebase's abstraction for worker pool management and expands CI coverage to include Bun runtime compatibility.

Highlights

  • Core Worker Thread Migration: The primary change in this pull request is the migration of the worker thread pool implementation from the Piscina library to Tinypool.
  • Significant Bundle Size Reduction: This migration has resulted in a dramatic reduction of the application's bundle size, shrinking it from 800KB to just 38KB, representing a 95% decrease.
  • API Compatibility and Performance Preservation: The new Tinypool implementation maintains full API compatibility with existing worker thread functionality and ensures no degradation in parallel processing performance.
  • Improved Abstraction: The worker pool initialization function has been renamed from initPiscina to initWorker, providing a more abstract and future-proof API for managing worker threads.
  • Enhanced Cross-Runtime Compatibility: New CI jobs have been added to specifically test compatibility across Node.js and Bun runtimes, ensuring broader support and stability.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

Major refactoring to replace Piscina with Tinypool for worker thread management, achieving 95% bundle size reduction (800KB → 38KB) while maintaining API compatibility.

  • Renamed initPiscina to initWorker in src/shared/processConcurrency.ts for better abstraction
  • Added comprehensive Bun runtime testing across 3 OS platforms in .github/workflows/ci.yml
  • Updated worker thread implementation in 5 core modules (fileCollect, fileProcess, securityCheck, calculateAllFileMetrics, calculateOutputMetrics)
  • Maintained all 685 unit tests passing and existing performance benchmarks
  • Successfully validated cross-runtime compatibility between Node.js and Bun

11 files reviewed, 1 comment
Edit PR Review Bot Settings | Greptile

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Jul 4, 2025

Deploying repomix with  Cloudflare Pages  Cloudflare Pages

Latest commit: 4e6dfc2
Status: ✅  Deploy successful!
Preview URL: https://354969ab.repomix.pages.dev
Branch Preview URL: https://feat-tinypool.repomix.pages.dev

View logs

@codecov
Copy link

codecov bot commented Jul 4, 2025

Codecov Report

Attention: Patch coverage is 42.85714% with 4 lines in your changes missing coverage. Please review.

Project coverage is 90.36%. Comparing base (1ab51ec) to head (4e6dfc2).
Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
src/core/file/fileCollect.ts 0.00% 1 Missing ⚠️
src/core/file/fileProcess.ts 0.00% 1 Missing ⚠️
src/core/metrics/calculateAllFileMetrics.ts 0.00% 1 Missing ⚠️
src/core/metrics/calculateOutputMetrics.ts 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main     #716   +/-   ##
=======================================
  Coverage   90.36%   90.36%           
=======================================
  Files          99       99           
  Lines        5561     5561           
  Branches     1186     1186           
=======================================
  Hits         5025     5025           
  Misses        536      536           

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

This comment was marked as outdated.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This PR migrates the worker thread pool implementation from Piscina to Tinypool, reducing bundle size. Pay attention to the Node.js version bump and consider a WorkerPool interface for better abstraction.

@yamadashy
Copy link
Owner Author

Response to Review Comments

@greptile-apps[bot] - Bun CLI execution suggestion ✅

Great suggestion! You're absolutely right that running Node.js CLI commands after Bun build may miss Bun-specific runtime issues.

I've updated the workflow to use bun bin/repomix.cjs instead of node bin/repomix.cjs in the build-and-run-bun job. This ensures we're testing the actual Bun runtime execution, providing more comprehensive validation.

Changes made:

  • node bin/repomix.cjsbun bin/repomix.cjs
  • node bin/repomix.cjs --versionbun bin/repomix.cjs --version
  • node bin/repomix.cjs --helpbun bin/repomix.cjs --help

@copilot - Test expectations completeness ✅

The test is already asserting all the necessary configuration parameters:

  • filename, minThreads, maxThreads
  • idleTimeout: 5000
  • env: expect.objectContaining({...process.env, REPOMIX_LOGLEVEL: '2'})

The test coverage is complete and properly validates the entire configuration object passed to Tinypool constructor.

@gemini-code-assist[bot] - Node.js version requirement ✅

The Node.js version bump from 18.0.0 to 20.0.0 was actually from a previous unrelated change. However, I verified that Tinypool officially requires Node.js 18+ as of 2024, so this version requirement is appropriate and not caused by the Tinypool migration.

The version requirement aligns with Tinypool's ESM-only design and modern Node.js features.

@gemini-code-assist[bot] - WorkerPool abstraction 🤔

I added a WorkerPool interface for better abstraction as suggested. However, I kept the return type as Tinypool to maintain type safety across the codebase without requiring extensive changes to all consumer files.

This provides documentation value and sets up for future abstraction while keeping the migration focused and safe.


All tests pass (685/685) and TypeScript compilation is clean. Thanks for the thorough review! 🙏

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

I see you want me to help update the build-and-run-bun job in the CI workflow to use bun instead of node for running the CLI commands. This change would align with testing the actual Bun runtime execution. Here's how we can modify those lines with the exact same indentation:

      - run: bun bin/repomix.cjs
      - run: bun bin/repomix.cjs --version
      - run: bun bin/repomix.cjs --help

This maintains the exact same indentation as the original (6 spaces before each line) while switching from node to bun for executing the CLI commands. The change ensures we're testing the actual Bun runtime execution rather than Node.js execution of the bundled CJS file.

The changes should verify both basic startup and commonly used CLI flags (--version and --help) under the Bun runtime.

Note that we're only modifying the three lines that execute repomix.cjs - all other parts of the job configuration remain unchanged to maintain the integrity of the build and artifact upload steps.

@gemini-code-assist
Copy link
Contributor

Thanks for the detailed response and for addressing the points raised! Your clarifications are very helpful.

Regarding the Node.js version requirement, it's good to know that the bump was unrelated to the Tinypool migration and that the current version aligns with Tinypool's requirements. This makes perfect sense.

For the WorkerPool abstraction, I appreciate you adding the WorkerPool interface. This is a solid step towards improving the abstraction and maintainability of the codebase, setting it up well for future enhancements. Your pragmatic approach to maintain type safety across consumer files for this migration is completely understandable and a sensible decision. Great work overall! ✨

yamadashy and others added 5 commits July 5, 2025 00:51
Address PR review feedback by switching to native Bun CLI execution in CI and adding WorkerPool interface for better abstraction while maintaining type safety.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Update setup-bun action hash for security and latest features.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Consolidate build process by removing separate clean script and add build-bun alias for consistency with Bun CI workflows.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Reduce CI complexity by testing only the latest Bun version while maintaining comprehensive OS coverage for optimal testing efficiency.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Ensure consistency by applying the same Bun version matrix simplification to the build-and-run-bun job, reducing from 6 to 3 CI combinations.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@yamadashy yamadashy requested a review from Copilot July 4, 2025 16:10
Copy link
Contributor

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 replaces the existing Piscina-based worker pool with Tinypool, renames the initializer to initWorker, and updates all related imports, tests, docs, and CI to use the new implementation.

  • Swap piscina for tinypool and rename initPiscinainitWorker
  • Update all core modules and tests to import and call initWorker
  • Adjust documentation and CI to reflect the new dependency and add Bun support

Reviewed Changes

Copilot reviewed 11 out of 12 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/shared/processConcurrency.ts Replaced Piscina import and initializer with Tinypool
tests/shared/processConcurrency.test.ts Updated test to mock and assert Tinypool initialization
src/core/security/securityCheck.ts Switched pool initializer import to initWorker
tests/core/security/securityCheck.test.ts Updated mock from initPiscina to initWorker
src/core/metrics/*.ts Replaced Piscina with initWorker in metrics modules
src/core/file/*.ts Switched file-processing modules to use initWorker
package.json Removed piscina dependency and added tinypool
repomix-instruction.md Updated documentation to reference Tinypool
.github/workflows/ci.yml Added Bun test and build matrix

@yamadashy yamadashy merged commit c0d8529 into main Jul 4, 2025
54 checks passed
@yamadashy yamadashy deleted the feat/tinypool branch July 4, 2025 16:11
@yamadashy yamadashy changed the title feat: migrate from Piscina to Tinypool for worker thread management feat: Bun Runtime Support. Migrate from Piscina to Tinypool for worker thread management Jul 4, 2025
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.

2 participants