Files
ruflo/tests/unit/utils/npx-isolated-cache.test.js
T
lanemcandClaude 69e93300bc fix: prevent concurrent NPX cache conflicts with isolated cache directories (#215)
* fix: prevent concurrent NPX cache conflicts with lock manager

- Add NPX cache manager utility to serialize NPX operations
- Wrap all NPX commands in withLock() to ensure exclusive access
- Implement automatic retry logic with exponential backoff
- Add lock timeout protection (30s) to prevent deadlocks
- Create manual lock management CLI for debugging
- Add comprehensive troubleshooting documentation

This fix addresses the ENOTEMPTY error that occurs when multiple
claude-flow instances attempt to use NPX simultaneously. The lock
manager ensures only one NPX operation runs at a time, preventing
cache directory rename conflicts.

Fixes the issue where concurrent swarm operations fail with:
npm error code ENOTEMPTY
npm error syscall rename
npm error ENOTEMPTY: directory not empty

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

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: replace complex lock manager with simple per-process cache isolation

- Remove complex NPX lock manager in favor of simpler approach
- Each process now gets isolated NPX cache directory
- Maintains true parallel execution without serialization overhead
- Add comprehensive test suites to verify fix works
- Update documentation with improved solution

Benefits:
- No performance impact (no serialization)
- Simpler implementation (50 lines vs 200+ lines)
- Self-cleaning cache directories
- Cross-platform compatibility
- Zero lock contention

Test Results:
- All 6 unit tests pass
- 18/18 integration tests pass with 0 ENOTEMPTY errors
- Concurrent and stress tests successful

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

Co-Authored-By: Claude <noreply@anthropic.com>

* test: add Jest-compatible tests for NPX cache isolation

- Add comprehensive unit tests for npx-isolated-cache utility
- Add integration tests for init command NPX isolation
- Fix duplicate function declaration in batch-init.js
- All tests pass: 15/15 Jest tests + 6/6 integration tests
- Verify 0 ENOTEMPTY errors in concurrent scenarios

Test Coverage:
- Cache isolation functionality
- Environment variable handling
- Cleanup mechanisms
- Integration with existing code
- Concurrent NPX execution safety

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

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: add comprehensive troubleshooting documentation for NPX cache fix

- Add troubleshooting/README.md with quick diagnosis guide
- Update main troubleshooting.md with NPX cache fix section
- Document test verification steps and version notes
- Link to detailed NPX cache conflicts guide
- Mark issue as FIXED in v2.0.0-alpha.17+

Provides clear guidance for:
- Identifying ENOTEMPTY errors
- Understanding the fix implemented
- Testing concurrent safety
- Version-specific notes

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

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: remove unused imports from batch-init.js

Remove unused imports that were leftover from cleanup:
- getIsolatedNpxEnv (not needed - batch-init doesn't run NPX commands)
- path (removed when duplicate initializeProject function was cleaned up)

The batch-init functionality only creates directories and files with Deno APIs,
so NPX cache isolation is not required there. NPX isolation is only used in
the main init command where create-sparc NPX command is executed.

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

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: maintain Deno environment compatibility in NPX cache isolation

Ensure npx-isolated-cache works in both Deno and Node.js environments:
- Use Deno.env.toObject() when available (Deno environment)
- Fall back to process.env in Node.js environment
- Maintains compatibility with existing Deno-based init command

This preserves the original behavior where Deno.env.toObject() was used
in the init command's environment setup, just with added NPX cache isolation.

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

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-12 23:29:20 -04:00

121 lines
4.0 KiB
JavaScript

/**
* Jest-compatible tests for NPX isolated cache functionality
*/
import { describe, it, expect, beforeEach, afterEach } from '@jest/globals';
import os from 'os';
import path from 'path';
import fs from 'fs/promises';
import { createIsolatedCache, getIsolatedNpxEnv, cleanupAllCaches } from '../../../src/utils/npx-isolated-cache.js';
describe('NPX Isolated Cache', () => {
beforeEach(() => {
// Clean up any existing caches before each test
return cleanupAllCaches();
});
afterEach(() => {
// Clean up caches after each test
return cleanupAllCaches();
});
describe('createIsolatedCache', () => {
it('should create unique cache directories for each call', () => {
const env1 = createIsolatedCache();
const env2 = createIsolatedCache();
expect(env1.NPM_CONFIG_CACHE).toBeDefined();
expect(env2.NPM_CONFIG_CACHE).toBeDefined();
expect(env1.NPM_CONFIG_CACHE).not.toBe(env2.NPM_CONFIG_CACHE);
});
it('should include all process environment variables', () => {
const originalEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'test-value';
const env = createIsolatedCache();
expect(env.NODE_ENV).toBe('test-value');
expect(env.NPM_CONFIG_CACHE).toBeDefined();
expect(env.npm_config_cache).toBeDefined();
process.env.NODE_ENV = originalEnv;
});
it('should create cache directories under temp/.npm-cache', () => {
const env = createIsolatedCache();
const cacheDir = env.NPM_CONFIG_CACHE;
expect(cacheDir).toContain(path.join(os.tmpdir(), '.npm-cache'));
expect(cacheDir).toContain('claude-flow-');
expect(cacheDir).toContain(process.pid.toString());
});
it('should set both NPM_CONFIG_CACHE and npm_config_cache', () => {
const env = createIsolatedCache();
expect(env.NPM_CONFIG_CACHE).toBeDefined();
expect(env.npm_config_cache).toBeDefined();
expect(env.NPM_CONFIG_CACHE).toBe(env.npm_config_cache);
});
});
describe('getIsolatedNpxEnv', () => {
it('should merge additional environment variables', () => {
const env = getIsolatedNpxEnv({
CUSTOM_VAR: 'custom-value',
NODE_ENV: 'override-value'
});
expect(env.CUSTOM_VAR).toBe('custom-value');
expect(env.NODE_ENV).toBe('override-value');
expect(env.NPM_CONFIG_CACHE).toBeDefined();
});
it('should prioritize additional env vars over defaults', () => {
const customCacheDir = '/custom/cache/dir';
const env = getIsolatedNpxEnv({
NPM_CONFIG_CACHE: customCacheDir
});
expect(env.NPM_CONFIG_CACHE).toBe(customCacheDir);
});
});
describe('cache directory structure', () => {
it('should create unique directory names with pid, timestamp, and random', () => {
const env1 = createIsolatedCache();
const env2 = createIsolatedCache();
const cache1 = path.basename(env1.NPM_CONFIG_CACHE);
const cache2 = path.basename(env2.NPM_CONFIG_CACHE);
// Both should start with claude-flow-{pid}
const pidPrefix = `claude-flow-${process.pid}-`;
expect(cache1).toMatch(new RegExp(`^${pidPrefix}\\d+-[a-z0-9]+$`));
expect(cache2).toMatch(new RegExp(`^${pidPrefix}\\d+-[a-z0-9]+$`));
// They should be different
expect(cache1).not.toBe(cache2);
});
});
describe('cleanup functionality', () => {
it('should track cache directories for cleanup', async () => {
const env = createIsolatedCache();
const cacheDir = env.NPM_CONFIG_CACHE;
// Cleanup should not throw even if directory doesn't exist
await expect(cleanupAllCaches()).resolves.not.toThrow();
});
});
describe('environment inheritance', () => {
it('should inherit PATH and other important environment variables', () => {
const env = createIsolatedCache();
expect(env.PATH).toBe(process.env.PATH);
expect(env.HOME || env.USERPROFILE).toBe(process.env.HOME || process.env.USERPROFILE);
});
});
});