Skip to content

Commit 65d7abe

Browse files
committed
fix(clv2): serialize observer signal-counter to stop dropped increments
observe.sh bumps the SIGUSR1 throttle counter in ${PROJECT_DIR}/.observer-signal-counter with an unlocked read-modify-write. The hook runs on every tool call, so concurrent invocations read the same value, both increment, and lose a write, signaling the observer at unpredictable intervals and defeating the #521 throttle. Serialize the read-modify-write under a lock, and only ever bump the counter while that lock is held: - Prefer flock with a bounded -w wait (the OS auto-releases it when the fd closes or the process dies, so there is no stale lock and no lost increment); on a timeout the tick is skipped rather than bumped unlocked. - Fall back to an atomic mkdir lock on platforms without flock, with a bounded spin. An EXIT trap cleans up on normal completion; INT/TERM traps release the lock and exit, so a signal cannot drop the lock and then continue the read-modify-write without ownership. If the lock cannot be acquired in the budget the tick is skipped rather than raced. No hand-rolled PID stale-reclaim (which is racy and can delete a live re-acquirer's lock). - Guard the counter read against a corrupt (non-integer) file that would abort the hook under set -e. Add tests/hooks/observe-signal-counter-race.test.js: 20 concurrent observe.sh invocations must not lose increments (exact under flock; at most one dropped on the best-effort mkdir fallback), the runner rejects on any hook execution failure or hang, plus content guards for the lock and the corrupt-counter handling. Fixes #2296
1 parent 2bc924f commit 65d7abe

2 files changed

Lines changed: 340 additions & 8 deletions

File tree

‎skills/continuous-learning-v2/hooks/observe.sh‎

Lines changed: 69 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -477,21 +477,82 @@ fi
477477
# which caused runaway parallel Claude analysis processes.
478478
SIGNAL_EVERY_N="${ECC_OBSERVER_SIGNAL_EVERY_N:-20}"
479479
SIGNAL_COUNTER_FILE="${PROJECT_DIR}/.observer-signal-counter"
480+
SIGNAL_COUNTER_LOCK="${SIGNAL_COUNTER_FILE}.lock"
480481
ACTIVITY_FILE="${PROJECT_DIR}/.observer-last-activity"
481482

482483
touch "$ACTIVITY_FILE" 2>/dev/null || true
483484

485+
# Serialize the throttle-counter read-modify-write. observe.sh runs on every
486+
# tool call (which can fire every second), so concurrent invocations previously
487+
# raced on this counter: both read the same value, both incremented, and one
488+
# write was lost, signaling the observer at unpredictable intervals (#2296).
489+
# Prefer flock (a kernel advisory lock the OS releases automatically if the hook
490+
# is killed); fall back to the atomic mkdir lock this script already uses for
491+
# the lazy-start path above. Both wrap the same read-modify-write below.
484492
should_signal=0
485-
if [ -f "$SIGNAL_COUNTER_FILE" ]; then
486-
counter=$(cat "$SIGNAL_COUNTER_FILE" 2>/dev/null || echo 0)
487-
counter=$((counter + 1))
488-
if [ "$counter" -ge "$SIGNAL_EVERY_N" ]; then
489-
should_signal=1
490-
counter=0
493+
494+
_ecc_bump_signal_counter() {
495+
if [ -f "$SIGNAL_COUNTER_FILE" ]; then
496+
counter=$(cat "$SIGNAL_COUNTER_FILE" 2>/dev/null || echo 0)
497+
# Guard against a corrupt counter file: a non-integer value would abort the
498+
# hook under `set -e` at the arithmetic below.
499+
case "$counter" in
500+
''|*[!0-9]*) counter=0 ;;
501+
esac
502+
counter=$((counter + 1))
503+
if [ "$counter" -ge "$SIGNAL_EVERY_N" ]; then
504+
should_signal=1
505+
counter=0
506+
fi
507+
echo "$counter" > "$SIGNAL_COUNTER_FILE"
508+
else
509+
echo "1" > "$SIGNAL_COUNTER_FILE"
510+
fi
511+
}
512+
513+
if command -v flock >/dev/null 2>&1 && exec 8>"$SIGNAL_COUNTER_LOCK" 2>/dev/null; then
514+
# flock is auto-released when fd 8 closes or the process dies, so there is no
515+
# stale lock and no lost increment. Use a bounded -w wait so the hook never
516+
# blocks indefinitely, and only bump the counter while the lock is held -- on
517+
# a timeout we skip the tick rather than doing an unlocked read-modify-write.
518+
if flock -w 2 8 2>/dev/null; then
519+
_ecc_bump_signal_counter
520+
flock -u 8 2>/dev/null || true
491521
fi
492-
echo "$counter" > "$SIGNAL_COUNTER_FILE"
522+
exec 8>&- 2>/dev/null || true
493523
else
494-
echo "1" > "$SIGNAL_COUNTER_FILE"
524+
# No flock (e.g. macOS): atomic mkdir lock with a bounded spin so the hook
525+
# never blocks indefinitely. A trap releases the lock on every exit path --
526+
# including the async-timeout SIGTERM -- so a killed hook does not strand the
527+
# directory. We deliberately do NOT hand-roll PID-based stale reclaim:
528+
# re-verifying then removing another process's lock is racy and can delete a
529+
# live re-acquirer's directory, reintroducing the very race this fixes.
530+
_signal_lock_held=0
531+
_signal_lock_spins=0
532+
while [ "$_signal_lock_spins" -lt 100 ]; do
533+
if mkdir "$SIGNAL_COUNTER_LOCK" 2>/dev/null; then
534+
# EXIT cleans up on normal completion. INT/TERM must release AND exit:
535+
# a signal trap that only released the lock would otherwise fall through
536+
# and continue the read-modify-write without ownership.
537+
trap 'rmdir "$SIGNAL_COUNTER_LOCK" 2>/dev/null || true' EXIT
538+
trap 'rmdir "$SIGNAL_COUNTER_LOCK" 2>/dev/null || true; exit 130' INT
539+
trap 'rmdir "$SIGNAL_COUNTER_LOCK" 2>/dev/null || true; exit 143' TERM
540+
_signal_lock_held=1
541+
break
542+
fi
543+
_signal_lock_spins=$((_signal_lock_spins + 1))
544+
sleep 0.02
545+
done
546+
if [ "$_signal_lock_held" -eq 1 ]; then
547+
# Bump only under the held lock -- never an unlocked read-modify-write.
548+
_ecc_bump_signal_counter
549+
rmdir "$SIGNAL_COUNTER_LOCK" 2>/dev/null || true
550+
trap - EXIT INT TERM
551+
fi
552+
# If the lock could not be acquired within the spin budget we skip this tick
553+
# rather than racing on an unlocked counter. Dropping one throttle tick under
554+
# extreme contention only delays the next observer signal slightly; it never
555+
# corrupts the counter or signals spuriously.
495556
fi
496557

497558
# Signal observer if running and throttle allows (check both project-scoped and global observer, deduplicate)
Lines changed: 271 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
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+
const skillRootMarker = 'SKILL_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"';
114+
// Fail fast if observe.sh's SKILL_ROOT definition drifts; otherwise the
115+
// no-op replace would leave the sandbox pointing at the real skill tree and
116+
// the test could pass spuriously.
117+
assert.ok(
118+
observeContent.includes(skillRootMarker),
119+
'observe.sh SKILL_ROOT definition changed; update the sandbox rewrite'
120+
);
121+
observeContent = observeContent.replace(
122+
skillRootMarker,
123+
`SKILL_ROOT="${skillRoot}"`
124+
);
125+
const testObserve = path.join(hooksDir, 'observe.sh');
126+
fs.writeFileSync(testObserve, observeContent, { mode: 0o755 });
127+
128+
return { testDir, projectDir, testObserve };
129+
}
130+
131+
// Run observe.sh once against the sandbox. Resolves when the process exits.
132+
function runObserve(testObserve, projectDir) {
133+
const input = JSON.stringify({
134+
tool_name: 'Read',
135+
tool_input: { file_path: '/tmp/test.txt' },
136+
session_id: 'test-session',
137+
cwd: projectDir
138+
});
139+
return new Promise((resolve, reject) => {
140+
const child = spawn('bash', [testObserve, 'post'], {
141+
env: {
142+
...process.env,
143+
HOME: projectDir,
144+
CLAUDE_CODE_ENTRYPOINT: 'cli',
145+
ECC_HOOK_PROFILE: 'standard',
146+
ECC_SKIP_OBSERVE: '0',
147+
CLAUDE_PROJECT_DIR: projectDir,
148+
// Reset threshold far above the invocation count, so no reset fires and
149+
// the final counter equals the number of invocations.
150+
ECC_OBSERVER_SIGNAL_EVERY_N: '100000'
151+
},
152+
stdio: ['pipe', 'ignore', 'pipe']
153+
});
154+
let stderr = '';
155+
// Fail the test on a hung hook rather than waiting forever.
156+
const timer = setTimeout(() => {
157+
child.kill('SIGKILL');
158+
reject(new Error('observe.sh timed out'));
159+
}, 20000);
160+
child.stderr.on('data', (chunk) => { stderr += chunk; });
161+
// A broken observe.sh must fail the test, not be silently swallowed.
162+
child.on('close', (code, signal) => {
163+
clearTimeout(timer);
164+
if (code === 0 && signal === null) {
165+
resolve();
166+
} else {
167+
reject(new Error(`observe.sh failed code=${code} signal=${signal}: ${stderr.trim()}`));
168+
}
169+
});
170+
child.on('error', (err) => {
171+
clearTimeout(timer);
172+
reject(err);
173+
});
174+
child.stdin.end(input);
175+
});
176+
}
177+
178+
function readCounter(projectDir) {
179+
const counterFile = path.join(projectDir, '.observer-signal-counter');
180+
if (!fs.existsSync(counterFile)) {
181+
return null;
182+
}
183+
return parseInt(fs.readFileSync(counterFile, 'utf8').trim(), 10);
184+
}
185+
186+
console.log('\n=== observe.sh signal-counter race regression (#2296) ===\n');
187+
188+
test('observe.sh uses a lock around the throttle-counter update', () => {
189+
const content = fs.readFileSync(observeShPath, 'utf8');
190+
assert.ok(
191+
content.includes('SIGNAL_COUNTER_LOCK'),
192+
'observe.sh should define a lock for the signal counter'
193+
);
194+
assert.ok(
195+
/flock 8\b/.test(content) || /mkdir "\$SIGNAL_COUNTER_LOCK"/.test(content),
196+
'observe.sh should acquire the counter lock via flock or an atomic mkdir'
197+
);
198+
});
199+
200+
test('observe.sh guards against a corrupt (non-integer) counter file', () => {
201+
const content = fs.readFileSync(observeShPath, 'utf8');
202+
assert.ok(
203+
/''\|\*\[!0-9\]\*\) counter=0/.test(content),
204+
'observe.sh should reset a non-integer counter to 0 before incrementing'
205+
);
206+
});
207+
208+
async function runSequential() {
209+
const { testDir, projectDir, testObserve } = buildSandbox();
210+
try {
211+
const N = 5;
212+
for (let i = 0; i < N; i++) {
213+
await runObserve(testObserve, projectDir);
214+
}
215+
const counter = readCounter(projectDir);
216+
assert.notStrictEqual(counter, null, 'counter file should exist after runs');
217+
assert.strictEqual(counter, N, `sequential counter should be ${N}, got ${counter}`);
218+
} finally {
219+
cleanupDir(testDir);
220+
}
221+
}
222+
223+
async function runConcurrent() {
224+
const { testDir, projectDir, testObserve } = buildSandbox();
225+
try {
226+
const K = 20;
227+
// Spawn all K before awaiting any, so they genuinely contend on the counter.
228+
const runs = [];
229+
for (let i = 0; i < K; i++) {
230+
runs.push(runObserve(testObserve, projectDir));
231+
}
232+
await Promise.all(runs);
233+
const counter = readCounter(projectDir);
234+
assert.notStrictEqual(counter, null, 'counter file should exist after concurrent runs');
235+
if (hasFlock) {
236+
// flock serializes every invocation, so no increment is ever lost. The
237+
// pre-fix unlocked code drops increments under this same contention.
238+
assert.strictEqual(
239+
counter,
240+
K,
241+
`with flock the counter must be exactly ${K}, got ${counter}`
242+
);
243+
} else {
244+
// mkdir fallback is best-effort: it may drop at most one increment if its
245+
// bounded spin is exhausted, but never the multi-increment loss the
246+
// unlocked code exhibited.
247+
assert.ok(
248+
counter >= K - 1,
249+
`mkdir fallback should keep the counter >= ${K - 1}, got ${counter}`
250+
);
251+
}
252+
} finally {
253+
cleanupDir(testDir);
254+
}
255+
}
256+
257+
(async () => {
258+
if (!isWindows && hasPython) {
259+
await asyncTest('sequential invocations increment the counter exactly once each', runSequential);
260+
await asyncTest('concurrent invocations never lose a counter increment', runConcurrent);
261+
} else {
262+
console.log(' - skipping shell-execution tests (requires non-Windows + python3)');
263+
}
264+
265+
console.log('\n=== Test Results ===');
266+
console.log(`Passed: ${passed}`);
267+
console.log(`Failed: ${failed}`);
268+
console.log(`Total: ${passed + failed}`);
269+
270+
process.exit(failed > 0 ? 1 : 0);
271+
})();

0 commit comments

Comments
 (0)