From f2d23ded28e7ff1c5c6a29cb44b96bb2f36c0f47 Mon Sep 17 00:00:00 2001 From: Afloat Date: Tue, 17 Nov 2026 10:53:25 +0800 Subject: [PATCH] fix(skill-tracker): serialize append and retention across processes --- manifests/context-packs/skill-triggers@1.json | 2 +- manifests/install-modules.json | 1 + scripts/lib/skill-evolution/tracker.js | 31 +++-- tests/lib/helpers/skill-runs-worker.js | 42 +++++++ tests/lib/skill-tracker-concurrency.test.js | 118 ++++++++++++++++++ 5 files changed, 185 insertions(+), 9 deletions(-) create mode 100644 tests/lib/helpers/skill-runs-worker.js create mode 100644 tests/lib/skill-tracker-concurrency.test.js diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index 91b727422..527ab8eb4 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -10,7 +10,7 @@ "id": "hand-seeded", "source": "manual-curation-pending-regeneration" }, - "registryDigest": "23bd986cff96ea33424b1a461461a70e3194582ce01927145fd3f956daeebf7f", + "registryDigest": "b867716be5f13f38c8f77613d910304971ad9743d13727440607c565fc0d2087", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ diff --git a/manifests/install-modules.json b/manifests/install-modules.json index d16c7c6b8..6ab0c3bc6 100644 --- a/manifests/install-modules.json +++ b/manifests/install-modules.json @@ -68,6 +68,7 @@ "scripts/harness-audit.js", "scripts/skills-health.js", "scripts/lib/skill-evolution", + "scripts/lib/install/claude-settings-lock.js", "scripts/lib/astra-review", "scripts/ci/validate-skill-host-compat.js", "scripts/ci/validate-skills.js" diff --git a/scripts/lib/skill-evolution/tracker.js b/scripts/lib/skill-evolution/tracker.js index da8005aed..2944ed6bf 100644 --- a/scripts/lib/skill-evolution/tracker.js +++ b/scripts/lib/skill-evolution/tracker.js @@ -4,7 +4,8 @@ const fs = require('fs'); const os = require('os'); const path = require('path'); -const { ensureDir } = require('../utils'); +const { ensureDir, log } = require('../utils'); +const { acquireSettingsLock } = require('../install/claude-settings-lock'); const VALID_OUTCOMES = new Set(['success', 'failure', 'partial']); const VALID_FEEDBACK = new Set(['accepted', 'corrected', 'rejected']); @@ -131,15 +132,29 @@ function appendRunRecord(runsFilePath, record, options = {}) { : MAX_RUN_RECORDS; ensureDir(path.dirname(runsFilePath)); - fs.appendFileSync(runsFilePath, `${JSON.stringify(record)}\n`, { encoding: 'utf8', mode: RUNS_FILE_MODE }); - + // Append and retention must share one critical section. Otherwise a pruner + // can overwrite a run another process appended after its read snapshot. + const release = acquireSettingsLock(runsFilePath, { + label: 'skill run history', timeoutMs: options.lockTimeoutMs ?? 5000, + }); try { - fs.chmodSync(runsFilePath, RUNS_FILE_MODE); - } catch { - // Windows and some mounts do not support POSIX modes; the record still lands. - } + fs.appendFileSync(runsFilePath, `${JSON.stringify(record)}\n`, { encoding: 'utf8', mode: RUNS_FILE_MODE }); - pruneRunRecords(runsFilePath, maxRecords); + try { + fs.chmodSync(runsFilePath, RUNS_FILE_MODE); + } catch { + // Windows and some mounts do not support POSIX modes; the record still lands. + } + + pruneRunRecords(runsFilePath, maxRecords); + } finally { + try { + release(); + } catch (error) { + // Preserve the append result or its original error if cleanup fails. + log(`[SkillTracker] Error releasing run history lock: ${error.message}`); + } + } } // Keep only the newest `maxRecords` lines. Rewrites the whole file, which is diff --git a/tests/lib/helpers/skill-runs-worker.js b/tests/lib/helpers/skill-runs-worker.js new file mode 100644 index 000000000..09cdf1135 --- /dev/null +++ b/tests/lib/helpers/skill-runs-worker.js @@ -0,0 +1,42 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { recordSkillExecution } = require('../../../scripts/lib/skill-evolution/tracker'); + +const [root, role] = process.argv.slice(2); +const runsFilePath = path.join(root, 'runs.jsonl'); +const signal = name => fs.writeFileSync(path.join(root, name), ''); +if (role === 'owner') { + const read = fs.readFileSync; + let paused = false; + fs.readFileSync = function (file, ...args) { + const contents = read.call(this, file, ...args); + if (file === runsFilePath && !paused) { + paused = true; + signal('snapshot-ready'); + const sleeper = new Int32Array(new SharedArrayBuffer(4)); + const deadline = Date.now() + 15000; + while (!fs.existsSync(path.join(root, 'release'))) { + if (Date.now() > deadline) throw new Error('Owner release deadline exceeded'); + Atomics.wait(sleeper, 0, 0, 10); + } + } + return contents; + }; +} else { + const link = fs.linkSync; + fs.linkSync = function (source, target) { + try { return link.call(this, source, target); } + catch (error) { + if (target === `${runsFilePath}.ecc.lock` && error.code === 'EEXIST') signal('contended'); + throw error; + } + }; +} + +recordSkillExecution({ + skill_id: role, skill_version: 'v1', task_description: 'Concurrent run', + outcome: 'success', recorded_at: '2026-03-15T12:00:00.000Z', +}, { runsFilePath, maxRecords: 2 }); +signal(`${role}-finished`); diff --git a/tests/lib/skill-tracker-concurrency.test.js b/tests/lib/skill-tracker-concurrency.test.js new file mode 100644 index 000000000..052b4c649 --- /dev/null +++ b/tests/lib/skill-tracker-concurrency.test.js @@ -0,0 +1,118 @@ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawn } = require('child_process'); +const { acquireSettingsLock } = require('../../scripts/lib/install/claude-settings-lock'); +const { recordSkillExecution, readSkillExecutionRecords } = require('../../scripts/lib/skill-evolution/tracker'); + +const payload = skillId => ({ + skill_id: skillId, skill_version: 'v1', task_description: 'Concurrent run', + outcome: 'success', recorded_at: '2026-03-15T12:00:00.000Z', +}); + +async function waitFor(root, names) { + const deadline = Date.now() + 10000; + while (!names.some(name => fs.existsSync(path.join(root, name)))) { + if (Date.now() > deadline) throw new Error(`Timed out waiting for ${names.join(' or ')}`); + await new Promise(resolve => setTimeout(resolve, 10)); + } +} + +function startWorker(root, role) { + const child = spawn(process.execPath, [path.join(__dirname, 'helpers', 'skill-runs-worker.js'), root, role], { + stdio: ['ignore', 'ignore', 'pipe'], + }); + let stderr = ''; + child.stderr.on('data', chunk => { stderr += chunk; }); + child.done = new Promise((resolve, reject) => { + child.on('error', reject); + child.on('close', (code, signal) => resolve({ code, signal, stderr })); + }); + child.done.catch(() => {}); + return child; +} + +const cases = [ + ['concurrent retention preserves the latest run after another writer has taken a snapshot', async (root, file, children) => { + recordSkillExecution(payload('seed-0'), { runsFilePath: file, maxRecords: 2 }); + recordSkillExecution(payload('seed-1'), { runsFilePath: file, maxRecords: 2 }); + const owner = startWorker(root, 'owner'); + children.push(owner); + await waitFor(root, ['snapshot-ready']); + const contender = startWorker(root, 'contender'); + children.push(contender); + await waitFor(root, ['contender-finished', 'contended']); + fs.writeFileSync(path.join(root, 'release'), ''); + for (const child of children) { + const result = await child.done; + assert.strictEqual(result.code, 0, result.stderr); + } + assert.deepStrictEqual(readSkillExecutionRecords({ runsFilePath: file }).map(row => row.skill_id), ['owner', 'contender']); + assert.ok(!fs.existsSync(`${file}.ecc.lock`), 'both writers release the lock'); + }], + ['a lock timeout preserves the existing sink and never appends outside the lock', (_root, file) => { + recordSkillExecution(payload('seed'), { runsFilePath: file }); + const before = fs.readFileSync(file, 'utf8'); + const release = acquireSettingsLock(file); + try { + assert.throws(() => recordSkillExecution(payload('busy'), { runsFilePath: file, lockTimeoutMs: 20 }), /Another ECC process/); + assert.strictEqual(fs.readFileSync(file, 'utf8'), before); + } finally { + release(); + } + }], + ['an append error releases the lock and a later write succeeds', (_root, file) => { + const append = fs.appendFileSync; + const expected = Object.assign(new Error('Injected append failure'), { code: 'EIO' }); + fs.appendFileSync = (target, ...args) => { + if (target === file) throw expected; + return append(target, ...args); + }; + try { + assert.throws(() => recordSkillExecution(payload('failed'), { runsFilePath: file }), error => error === expected); + } finally { + fs.appendFileSync = append; + } + assert.ok(!fs.existsSync(`${file}.ecc.lock`)); + recordSkillExecution(payload('retry'), { runsFilePath: file }); + assert.deepStrictEqual(readSkillExecutionRecords({ runsFilePath: file }).map(row => row.skill_id), ['retry']); + }], + ['a terminated writer does not permanently block subsequent telemetry', async (root, file, children) => { + const owner = startWorker(root, 'owner'); + children.push(owner); + await waitFor(root, ['snapshot-ready']); + owner.kill('SIGKILL'); + await owner.done; + recordSkillExecution(payload('recovered'), { runsFilePath: file, maxRecords: 2 }); + assert.deepStrictEqual(readSkillExecutionRecords({ runsFilePath: file }).map(row => row.skill_id), ['owner', 'recovered']); + assert.ok(!fs.existsSync(`${file}.ecc.lock`)); + }], +]; + +(async () => { + let passed = 0; + let failed = 0; + for (const [name, run] of cases) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-skill-runs-')); + const children = []; + try { + await run(root, path.join(root, 'runs.jsonl'), children); + passed++; + console.log(` ✓ ${name}`); + } catch (error) { + failed++; + console.error(` ✗ ${name}: ${error.message}`); + } finally { + for (const child of children) { + if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); + await child.done; + } + fs.rmSync(root, { recursive: true, force: true }); + } + } + console.log(`\nPassed: ${passed}, Failed: ${failed}`); + process.exitCode = failed > 0 ? 1 : 0; +})();