|
| 1 | +/** |
| 2 | + * Regression tests for the SIGUSR1 throttle-counter race in observe.sh (#2296) |
| 3 | + * |
| 4 | + * observe.sh runs on every tool call and bumps a throttle counter in |
| 5 | + * ${PROJECT_DIR}/.observer-signal-counter so the observer is signaled only |
| 6 | + * every N observations (#521). The bump used a plain read-modify-write with no |
| 7 | + * locking, so concurrent hook invocations could read the same value, both |
| 8 | + * increment, and lose a write — the observer then fired at unpredictable |
| 9 | + * intervals. The fix serializes the read-modify-write with an atomic mkdir |
| 10 | + * lock. |
| 11 | + * |
| 12 | + * These tests drive the real observe.sh (reusing the stub harness from |
| 13 | + * observer-memory.test.js) and assert the lock's invariant: with the reset |
| 14 | + * threshold set high enough that no reset fires, the final counter must equal |
| 15 | + * the number of invocations — i.e. no increment is ever lost, even under heavy |
| 16 | + * concurrency. |
| 17 | + * |
| 18 | + * Run with: node tests/hooks/observe-signal-counter-race.test.js |
| 19 | + */ |
| 20 | + |
| 21 | +const assert = require('assert'); |
| 22 | +const path = require('path'); |
| 23 | +const fs = require('fs'); |
| 24 | +const os = require('os'); |
| 25 | +const { spawn, spawnSync } = require('child_process'); |
| 26 | + |
| 27 | +let passed = 0; |
| 28 | +let failed = 0; |
| 29 | + |
| 30 | +function test(name, fn) { |
| 31 | + try { |
| 32 | + fn(); |
| 33 | + console.log(` ✓ ${name}`); |
| 34 | + passed++; |
| 35 | + } catch (err) { |
| 36 | + console.log(` ✗ ${name}`); |
| 37 | + console.log(` Error: ${err.message}`); |
| 38 | + failed++; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +async function asyncTest(name, fn) { |
| 43 | + try { |
| 44 | + await fn(); |
| 45 | + console.log(` ✓ ${name}`); |
| 46 | + passed++; |
| 47 | + } catch (err) { |
| 48 | + console.log(` ✗ ${name}`); |
| 49 | + console.log(` Error: ${err.message}`); |
| 50 | + failed++; |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +function createTempDir() { |
| 55 | + return fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-signal-race-')); |
| 56 | +} |
| 57 | + |
| 58 | +function cleanupDir(dir) { |
| 59 | + try { |
| 60 | + fs.rmSync(dir, { recursive: true, force: true }); |
| 61 | + } catch { |
| 62 | + // ignore cleanup errors |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +const repoRoot = path.resolve(__dirname, '..', '..'); |
| 67 | +const observeShPath = path.join(repoRoot, 'skills', 'continuous-learning-v2', 'hooks', 'observe.sh'); |
| 68 | + |
| 69 | +const isWindows = process.platform === 'win32'; |
| 70 | +const hasPython = !isWindows && spawnSync('python3', ['--version']).status === 0; |
| 71 | +// When the runner has flock the lock is exact (blocking, kernel auto-release); |
| 72 | +// without it observe.sh uses a best-effort mkdir spin that may drop at most one |
| 73 | +// increment under pathological contention. |
| 74 | +const hasFlock = !isWindows && spawnSync('bash', ['-c', 'command -v flock']).status === 0; |
| 75 | + |
| 76 | +// Build a self-contained observe.sh sandbox (stub detect-project.sh + |
| 77 | +// homunculus-dir.sh, SKILL_ROOT patched to the sandbox) and return its paths. |
| 78 | +function buildSandbox() { |
| 79 | + const testDir = createTempDir(); |
| 80 | + const projectDir = path.join(testDir, 'project'); |
| 81 | + fs.mkdirSync(projectDir, { recursive: true }); |
| 82 | + |
| 83 | + const skillRoot = path.join(testDir, 'skill'); |
| 84 | + const scriptsDir = path.join(skillRoot, 'scripts'); |
| 85 | + const scriptsLibDir = path.join(scriptsDir, 'lib'); |
| 86 | + const hooksDir = path.join(skillRoot, 'hooks'); |
| 87 | + fs.mkdirSync(scriptsDir, { recursive: true }); |
| 88 | + fs.mkdirSync(scriptsLibDir, { recursive: true }); |
| 89 | + fs.mkdirSync(hooksDir, { recursive: true }); |
| 90 | + |
| 91 | + fs.writeFileSync( |
| 92 | + path.join(scriptsDir, 'detect-project.sh'), |
| 93 | + [ |
| 94 | + '#!/bin/bash', |
| 95 | + 'PROJECT_ID="test-project"', |
| 96 | + 'PROJECT_NAME="test-project"', |
| 97 | + `PROJECT_ROOT="${projectDir}"`, |
| 98 | + `PROJECT_DIR="${projectDir}"`, |
| 99 | + 'CLV2_PYTHON_CMD="python3"', |
| 100 | + '' |
| 101 | + ].join('\n') |
| 102 | + ); |
| 103 | + fs.writeFileSync( |
| 104 | + path.join(scriptsLibDir, 'homunculus-dir.sh'), |
| 105 | + [ |
| 106 | + '#!/bin/bash', |
| 107 | + '_ecc_resolve_homunculus_dir() { printf "%s\\n" "$HOME/.local/share/ecc-homunculus"; }', |
| 108 | + '' |
| 109 | + ].join('\n') |
| 110 | + ); |
| 111 | + |
| 112 | + let observeContent = fs.readFileSync(observeShPath, 'utf8'); |
| 113 | + observeContent = observeContent.replace( |
| 114 | + 'SKILL_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"', |
| 115 | + `SKILL_ROOT="${skillRoot}"` |
| 116 | + ); |
| 117 | + const testObserve = path.join(hooksDir, 'observe.sh'); |
| 118 | + fs.writeFileSync(testObserve, observeContent, { mode: 0o755 }); |
| 119 | + |
| 120 | + return { testDir, projectDir, testObserve }; |
| 121 | +} |
| 122 | + |
| 123 | +// Run observe.sh once against the sandbox. Resolves when the process exits. |
| 124 | +function runObserve(testObserve, projectDir) { |
| 125 | + const input = JSON.stringify({ |
| 126 | + tool_name: 'Read', |
| 127 | + tool_input: { file_path: '/tmp/test.txt' }, |
| 128 | + session_id: 'test-session', |
| 129 | + cwd: projectDir |
| 130 | + }); |
| 131 | + return new Promise((resolve, reject) => { |
| 132 | + const child = spawn('bash', [testObserve, 'post'], { |
| 133 | + env: { |
| 134 | + ...process.env, |
| 135 | + HOME: projectDir, |
| 136 | + CLAUDE_CODE_ENTRYPOINT: 'cli', |
| 137 | + ECC_HOOK_PROFILE: 'standard', |
| 138 | + ECC_SKIP_OBSERVE: '0', |
| 139 | + CLAUDE_PROJECT_DIR: projectDir, |
| 140 | + // Reset threshold far above the invocation count, so no reset fires and |
| 141 | + // the final counter equals the number of invocations. |
| 142 | + ECC_OBSERVER_SIGNAL_EVERY_N: '100000' |
| 143 | + }, |
| 144 | + stdio: ['pipe', 'ignore', 'pipe'] |
| 145 | + }); |
| 146 | + let stderr = ''; |
| 147 | + // Fail the test on a hung hook rather than waiting forever. |
| 148 | + const timer = setTimeout(() => { |
| 149 | + child.kill('SIGKILL'); |
| 150 | + reject(new Error('observe.sh timed out')); |
| 151 | + }, 20000); |
| 152 | + child.stderr.on('data', (chunk) => { stderr += chunk; }); |
| 153 | + // A broken observe.sh must fail the test, not be silently swallowed. |
| 154 | + child.on('close', (code, signal) => { |
| 155 | + clearTimeout(timer); |
| 156 | + if (code === 0 && signal === null) { |
| 157 | + resolve(); |
| 158 | + } else { |
| 159 | + reject(new Error(`observe.sh failed code=${code} signal=${signal}: ${stderr.trim()}`)); |
| 160 | + } |
| 161 | + }); |
| 162 | + child.on('error', (err) => { |
| 163 | + clearTimeout(timer); |
| 164 | + reject(err); |
| 165 | + }); |
| 166 | + child.stdin.end(input); |
| 167 | + }); |
| 168 | +} |
| 169 | + |
| 170 | +function readCounter(projectDir) { |
| 171 | + const counterFile = path.join(projectDir, '.observer-signal-counter'); |
| 172 | + if (!fs.existsSync(counterFile)) { |
| 173 | + return null; |
| 174 | + } |
| 175 | + return parseInt(fs.readFileSync(counterFile, 'utf8').trim(), 10); |
| 176 | +} |
| 177 | + |
| 178 | +console.log('\n=== observe.sh signal-counter race regression (#2296) ===\n'); |
| 179 | + |
| 180 | +test('observe.sh uses a lock around the throttle-counter update', () => { |
| 181 | + const content = fs.readFileSync(observeShPath, 'utf8'); |
| 182 | + assert.ok( |
| 183 | + content.includes('SIGNAL_COUNTER_LOCK'), |
| 184 | + 'observe.sh should define a lock for the signal counter' |
| 185 | + ); |
| 186 | + assert.ok( |
| 187 | + /flock 8\b/.test(content) || /mkdir "\$SIGNAL_COUNTER_LOCK"/.test(content), |
| 188 | + 'observe.sh should acquire the counter lock via flock or an atomic mkdir' |
| 189 | + ); |
| 190 | +}); |
| 191 | + |
| 192 | +test('observe.sh guards against a corrupt (non-integer) counter file', () => { |
| 193 | + const content = fs.readFileSync(observeShPath, 'utf8'); |
| 194 | + assert.ok( |
| 195 | + /''\|\*\[!0-9\]\*\) counter=0/.test(content), |
| 196 | + 'observe.sh should reset a non-integer counter to 0 before incrementing' |
| 197 | + ); |
| 198 | +}); |
| 199 | + |
| 200 | +async function runSequential() { |
| 201 | + const { testDir, projectDir, testObserve } = buildSandbox(); |
| 202 | + try { |
| 203 | + const N = 5; |
| 204 | + for (let i = 0; i < N; i++) { |
| 205 | + await runObserve(testObserve, projectDir); |
| 206 | + } |
| 207 | + const counter = readCounter(projectDir); |
| 208 | + assert.notStrictEqual(counter, null, 'counter file should exist after runs'); |
| 209 | + assert.strictEqual(counter, N, `sequential counter should be ${N}, got ${counter}`); |
| 210 | + } finally { |
| 211 | + cleanupDir(testDir); |
| 212 | + } |
| 213 | +} |
| 214 | + |
| 215 | +async function runConcurrent() { |
| 216 | + const { testDir, projectDir, testObserve } = buildSandbox(); |
| 217 | + try { |
| 218 | + const K = 20; |
| 219 | + // Spawn all K before awaiting any, so they genuinely contend on the counter. |
| 220 | + const runs = []; |
| 221 | + for (let i = 0; i < K; i++) { |
| 222 | + runs.push(runObserve(testObserve, projectDir)); |
| 223 | + } |
| 224 | + await Promise.all(runs); |
| 225 | + const counter = readCounter(projectDir); |
| 226 | + assert.notStrictEqual(counter, null, 'counter file should exist after concurrent runs'); |
| 227 | + if (hasFlock) { |
| 228 | + // flock serializes every invocation, so no increment is ever lost. The |
| 229 | + // pre-fix unlocked code drops increments under this same contention. |
| 230 | + assert.strictEqual( |
| 231 | + counter, |
| 232 | + K, |
| 233 | + `with flock the counter must be exactly ${K}, got ${counter}` |
| 234 | + ); |
| 235 | + } else { |
| 236 | + // mkdir fallback is best-effort: it may drop at most one increment if its |
| 237 | + // bounded spin is exhausted, but never the multi-increment loss the |
| 238 | + // unlocked code exhibited. |
| 239 | + assert.ok( |
| 240 | + counter >= K - 1, |
| 241 | + `mkdir fallback should keep the counter >= ${K - 1}, got ${counter}` |
| 242 | + ); |
| 243 | + } |
| 244 | + } finally { |
| 245 | + cleanupDir(testDir); |
| 246 | + } |
| 247 | +} |
| 248 | + |
| 249 | +(async () => { |
| 250 | + if (!isWindows && hasPython) { |
| 251 | + await asyncTest('sequential invocations increment the counter exactly once each', runSequential); |
| 252 | + await asyncTest('concurrent invocations never lose a counter increment', runConcurrent); |
| 253 | + } else { |
| 254 | + console.log(' - skipping shell-execution tests (requires non-Windows + python3)'); |
| 255 | + } |
| 256 | + |
| 257 | + console.log('\n=== Test Results ==='); |
| 258 | + console.log(`Passed: ${passed}`); |
| 259 | + console.log(`Failed: ${failed}`); |
| 260 | + console.log(`Total: ${passed + failed}`); |
| 261 | + |
| 262 | + process.exit(failed > 0 ? 1 : 0); |
| 263 | +})(); |
0 commit comments