Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

fix(metrics): address incremental snapshot review

wellkilo1b12e19c6365
diff --git a/scripts/hooks/cost-tracker.js b/scripts/hooks/cost-tracker.js
index 4e491a8e9..63d61170d 100755
--- a/scripts/hooks/cost-tracker.js
+++ b/scripts/hooks/cost-tracker.js
@@ -42,9 +42,12 @@
const fs = require('fs');
const os = require('os');
const path = require('path');
-const { ensureDir, appendFile, getClaudeDir } = require('../lib/utils');
+const { ensureDir, getClaudeDir } = require('../lib/utils');
const { sanitizeSessionId } = require('../lib/session-bridge');
-const { publishAppendedSessionCostSnapshot } = require('../lib/session-cost-snapshot');
+const {
+ appendSessionCostRow,
+ warnSessionCostSnapshotFailure
+} = require('../lib/session-cost-snapshot');
const HARNESS_COST_MAX_AGE_SECONDS = 300;
@@ -245,12 +248,10 @@ process.stdin.on('end', () => {
estimated_cost_usd: estimatedCostUsd
};
- appendFile(path.join(metricsDir, 'costs.jsonl'), `${JSON.stringify(row)}\n`);
try {
- publishAppendedSessionCostSnapshot(metricsDir, sessionId, row);
- } catch {
- // The append-only log remains authoritative. A later bridge read falls
- // back to it when an atomic snapshot cannot be published.
+ appendSessionCostRow(metricsDir, sessionId, row);
+ } catch (error) {
+ warnSessionCostSnapshotFailure('publication', metricsDir, sessionId, error);
}
} catch {
// Non-blocking — never fail the Stop hook.
diff --git a/scripts/hooks/ecc-metrics-bridge.js b/scripts/hooks/ecc-metrics-bridge.js
index 26a677c79..8f10a3a49 100644
--- a/scripts/hooks/ecc-metrics-bridge.js
+++ b/scripts/hooks/ecc-metrics-bridge.js
@@ -15,11 +15,8 @@ const os = require('os');
const path = require('path');
const { sanitizeSessionId, readBridge, writeBridgeAtomic } = require('../lib/session-bridge');
const {
- getCostLogSignature,
- isValidCostRow,
readSessionCostSnapshot,
- repairSessionCostSnapshot,
- signaturesMatch,
+ warnSessionCostSnapshotFailure
} = require('../lib/session-cost-snapshot');
const { getClaudeDir } = require('../lib/utils');
@@ -29,11 +26,6 @@ const RECENT_TOOLS_SIZE = 5;
const HASH_INPUT_LIMIT = 2048;
const WARNING_CACHE_PREFIX = 'ecc-metrics-cost-warnings-';
-function toNumber(value) {
- const n = Number(value);
- return Number.isFinite(n) ? n : 0;
-}
-
function stableStringify(value, depth = 0) {
if (depth > 4) return '[depth-limit]';
if (value === null || typeof value !== 'object') return JSON.stringify(value);
@@ -143,8 +135,9 @@ function writeCostWarningIfChanged(kind, costsPath, signature, message) {
/**
* Read cumulative cost for a session.
*
- * The Stop hook publishes an atomic per-session snapshot, so the normal
- * PostToolUse path reads O(1) data instead of reparsing unbounded history.
+ * The Stop hook publishes an atomic per-session cursor snapshot, so a stable
+ * PostToolUse path reads O(1) metadata and newly appended data is O(delta)
+ * instead of reparsing unbounded history.
* Older ECC installations and damaged/missing snapshots remain compatible:
* they fall back to scanning costs.jsonl for the last cumulative row.
*
@@ -155,77 +148,36 @@ function readSessionCost(sessionId) {
let costsPath = path.join('metrics', 'costs.jsonl');
try {
const metricsDir = path.join(getClaudeDir(), 'metrics');
- const snapshot = readSessionCostSnapshot(metricsDir, sessionId);
- if (snapshot) {
- return {
- totalCost: toNumber(snapshot.estimated_cost_usd),
- totalIn: toNumber(snapshot.input_tokens),
- totalOut: toNumber(snapshot.output_tokens)
- };
- }
-
costsPath = path.join(metricsDir, 'costs.jsonl');
- const sourceBefore = getCostLogSignature(metricsDir);
- const content = fs.readFileSync(costsPath, 'utf8');
- const lines = content.split('\n').filter(Boolean);
-
- let totalCost = 0;
- let totalIn = 0;
- let totalOut = 0;
- let latestRow = null;
- let malformed = 0;
- let invalid = 0;
- const malformedHasher = crypto.createHash('sha256');
- const invalidHasher = crypto.createHash('sha256');
- for (const line of lines) {
- try {
- const row = JSON.parse(line);
- if (row.session_id === sessionId) {
- if (isValidCostRow(row, sessionId)) {
- latestRow = row;
- totalCost = row.estimated_cost_usd;
- totalIn = row.input_tokens;
- totalOut = row.output_tokens;
- } else {
- invalid += 1;
- invalidHasher.update(line).update('\0');
- }
- }
- } catch {
- malformed += 1;
- malformedHasher.update(line).update('\0');
- }
- }
- // One aggregated breadcrumb per call rather than one per bad row, so a
- // log-flooded costs.jsonl stays diagnosable without overwhelming stderr.
- // Suppress repeats for the same malformed-line signature across hook
- // subprocesses, so a persistent bad row should not spam stderr.
- if (malformed > 0) {
+ const snapshotResult = readSessionCostSnapshot(metricsDir, sessionId);
+ if (snapshotResult.malformed > 0) {
writeCostWarningIfChanged(
'malformed',
costsPath,
- `${malformed}:${malformedHasher.digest('hex').slice(0, 16)}`,
- `[ecc-metrics-bridge] skipped ${malformed} malformed line(s) in ${costsPath}\n`
+ `${snapshotResult.malformed}:${snapshotResult.malformedSignature}`,
+ `[ecc-metrics-bridge] skipped ${snapshotResult.malformed} malformed line(s) in ${costsPath}\n`
);
}
- if (invalid > 0) {
+ if (snapshotResult.invalid > 0) {
writeCostWarningIfChanged(
'invalid-row',
costsPath,
- `${invalid}:${invalidHasher.digest('hex').slice(0, 16)}`,
- `[ecc-metrics-bridge] skipped ${invalid} invalid cumulative row(s) for ${sessionId} in ${costsPath}\n`
+ `${snapshotResult.invalid}:${snapshotResult.invalidSignature}`,
+ `[ecc-metrics-bridge] skipped ${snapshotResult.invalid} invalid cumulative row(s) for ${sessionId} in ${costsPath}\n`
);
}
-
- const sourceAfter = getCostLogSignature(metricsDir);
- if (latestRow && signaturesMatch(sourceBefore, sourceAfter)) {
- try {
- repairSessionCostSnapshot(metricsDir, sessionId, latestRow, sourceAfter);
- } catch {
- // Snapshot repair is best effort; the JSONL result remains valid.
- }
+ if (snapshotResult.snapshotError) {
+ warnSessionCostSnapshotFailure(
+ 'repair',
+ metricsDir,
+ sessionId,
+ snapshotResult.snapshotError
+ );
}
- return { totalCost, totalIn, totalOut };
+ const row = snapshotResult.row;
+ return row
+ ? { totalCost: row.estimated_cost_usd, totalIn: row.input_tokens, totalOut: row.output_tokens }
+ : { totalCost: 0, totalIn: 0, totalOut: 0 };
} catch (err) {
// ENOENT is the common case (no Stop event has fired yet this session)
// and is not actually a failure — stay silent on it. Anything else
diff --git a/scripts/lib/session-cost-snapshot.js b/scripts/lib/session-cost-snapshot.js
index 816eae9d3..04a5e45b0 100644
--- a/scripts/lib/session-cost-snapshot.js
+++ b/scripts/lib/session-cost-snapshot.js
@@ -1,6 +1,8 @@
'use strict';
+const crypto = require('crypto');
const fs = require('fs');
+const os = require('os');
const path = require('path');
const { writeFileAtomic } = require('./atomic-write');
const { sanitizeSessionId } = require('./session-bridge');
@@ -8,6 +10,12 @@ const { sanitizeSessionId } = require('./session-bridge');
const COST_SNAPSHOT_SCHEMA_VERSION = 'ecc.cost-snapshot.v1';
const COST_SNAPSHOT_DIRECTORY = 'cost-snapshots';
const COST_LOG_FILENAME = 'costs.jsonl';
+const READ_CHUNK_BYTES = 64 * 1024;
+const FINGERPRINT_WINDOW_BYTES = 256;
+const PRUNE_INTERVAL_MS = 24 * 60 * 60 * 1000;
+const SNAPSHOT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
+const MAX_SNAPSHOTS = 512;
+const WARNING_CACHE_PREFIX = 'ecc-cost-snapshot-warnings-';
function assertSafeSessionId(sessionId) {
if (sanitizeSessionId(sessionId) !== sessionId) {
@@ -15,24 +23,13 @@ function assertSafeSessionId(sessionId) {
}
}
-function getCostSnapshotPath(metricsDir, sessionId) {
- assertSafeSessionId(sessionId);
- // Prefix the filename so Windows device names such as CON/NUL/COM1 never
- // become the basename, even when they are otherwise valid session IDs.
- return path.join(metricsDir, COST_SNAPSHOT_DIRECTORY, `session-${sessionId}.json`);
-}
-
-function getCostLogSignature(metricsDir) {
- const stat = fs.statSync(path.join(metricsDir, COST_LOG_FILENAME));
- return {
- size_bytes: stat.size,
- mtime_ms: stat.mtimeMs
- };
+function getSnapshotDirectory(metricsDir) {
+ return path.join(metricsDir, COST_SNAPSHOT_DIRECTORY);
}
-function signaturesMatch(left, right) {
- return left?.size_bytes === right?.size_bytes
- && left?.mtime_ms === right?.mtime_ms;
+function getCostSnapshotPath(metricsDir, sessionId) {
+ assertSafeSessionId(sessionId);
+ return path.join(getSnapshotDirectory(metricsDir), `session-${sessionId}.json`);
}
function isValidCostRow(row, sessionId) {
@@ -48,89 +45,354 @@ function isValidCostRow(row, sessionId) {
&& row.output_tokens >= 0;
}
-function assertCostLogSignature(source) {
- if (!Number.isSafeInteger(source?.size_bytes) || source.size_bytes < 0) {
- throw new Error('Cost snapshot requires a valid source size');
+function readJsonFile(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ } catch {
+ return null;
}
- if (!Number.isFinite(source?.mtime_ms) || source.mtime_ms < 0) {
- throw new Error('Cost snapshot requires a valid source mtime');
+}
+
+function chooseNewerCumulativeRow(currentRow, nextRow) {
+ if (!currentRow) return nextRow;
+ const nextDominates = nextRow.input_tokens >= currentRow.input_tokens
+ && nextRow.output_tokens >= currentRow.output_tokens
+ && nextRow.estimated_cost_usd >= currentRow.estimated_cost_usd;
+ const currentDominates = currentRow.input_tokens >= nextRow.input_tokens
+ && currentRow.output_tokens >= nextRow.output_tokens
+ && currentRow.estimated_cost_usd >= nextRow.estimated_cost_usd;
+ if (nextDominates && !currentDominates) return nextRow;
+ if (currentDominates && !nextDominates) return currentRow;
+ const nextTimestamp = Date.parse(nextRow.timestamp);
+ const currentTimestamp = Date.parse(currentRow.timestamp);
+ if (Number.isFinite(nextTimestamp) && Number.isFinite(currentTimestamp)) {
+ return nextTimestamp >= currentTimestamp ? nextRow : currentRow;
}
+ return nextRow;
}
-function writeSnapshotForSource(metricsDir, sessionId, row, source) {
- assertSafeSessionId(sessionId);
- if (!isValidCostRow(row, sessionId)) {
- throw new Error('Cost snapshot requires valid non-negative numeric totals for its session');
+function sourceIdentity(stat) {
+ return `${stat.dev}:${stat.ino}`;
+}
+
+function hashWindow(descriptor, position, length) {
+ const buffer = Buffer.alloc(length);
+ if (length > 0) fs.readSync(descriptor, buffer, 0, length, position);
+ return crypto.createHash('sha256').update(buffer).digest('hex');
+}
+
+function fingerprintProcessedPrefix(descriptor, offset) {
+ const windowLength = Math.min(FINGERPRINT_WINDOW_BYTES, offset);
+ const middleStart = Math.max(0, Math.floor((offset - windowLength) / 2));
+ return {
+ start: hashWindow(descriptor, 0, windowLength),
+ middle: hashWindow(descriptor, middleStart, windowLength),
+ end: hashWindow(descriptor, offset - windowLength, windowLength)
+ };
+}
+
+function fingerprintsMatch(left, right) {
+ return left?.start === right?.start
+ && left?.middle === right?.middle
+ && left?.end === right?.end;
+}
+
+function validSnapshotBase(snapshot, descriptor, stat, sessionId) {
+ if (snapshot?.schema_version !== COST_SNAPSHOT_SCHEMA_VERSION) return null;
+ if (snapshot.row !== null && !isValidCostRow(snapshot.row, sessionId)) return null;
+ const source = snapshot.source;
+ if (source?.identity !== sourceIdentity(stat)) return null;
+ if (!Number.isSafeInteger(source.offset_bytes) || source.offset_bytes < 0) return null;
+ if (source.offset_bytes > stat.size) return null;
+ if (source.offset_bytes === stat.size && source.mtime_ms !== stat.mtimeMs) return null;
+ if (!fingerprintsMatch(
+ source.fingerprint,
+ fingerprintProcessedPrefix(descriptor, source.offset_bytes)
+ )) return null;
+ return { row: snapshot.row, offset: source.offset_bytes };
+}
+
+function scanJsonlRange(descriptor, start, end, sessionId, initialRow) {
+ const buffer = Buffer.allocUnsafe(READ_CHUNK_BYTES);
+ let position = start;
+ let processedOffset = start;
+ let pending = Buffer.alloc(0);
+ let latestRow = initialRow;
+ let committedRow = initialRow;
+ let malformed = 0;
+ let invalid = 0;
+ const malformedHasher = crypto.createHash('sha256');
+ const invalidHasher = crypto.createHash('sha256');
+
+ const processLine = (line, committed = true) => {
+ if (!line.trim()) return;
+ try {
+ const row = JSON.parse(line);
+ if (row.session_id !== sessionId) return;
+ if (!isValidCostRow(row, sessionId)) {
+ if (committed) {
+ invalid += 1;
+ invalidHasher.update(line).update('\0');
+ }
+ return;
+ }
+ latestRow = chooseNewerCumulativeRow(latestRow, row);
+ if (committed) committedRow = chooseNewerCumulativeRow(committedRow, row);
+ } catch {
+ if (committed) {
+ malformed += 1;
+ malformedHasher.update(line).update('\0');
+ }
+ }
+ };
+
+ while (position < end) {
+ const bytesRead = fs.readSync(
+ descriptor,
+ buffer,
+ 0,
+ Math.min(buffer.length, end - position),
+ position
+ );
+ if (bytesRead === 0) break;
+ const combined = pending.length > 0
+ ? Buffer.concat([pending, buffer.subarray(0, bytesRead)])
+ : buffer.subarray(0, bytesRead);
+ let lineStart = 0;
+ for (;;) {
+ const newlineIndex = combined.indexOf(0x0a, lineStart);
+ if (newlineIndex < 0) break;
+ processLine(combined.subarray(lineStart, newlineIndex).toString('utf8'));
+ lineStart = newlineIndex + 1;
+ }
+ pending = Buffer.from(combined.subarray(lineStart));
+ position += bytesRead;
+ processedOffset = position - pending.length;
}
+ if (pending.toString('utf8').trim()) processLine(pending.toString('utf8'), false);
+ return {
+ row: latestRow,
+ committedRow,
+ processedOffset,
+ malformed,
+ invalid,
+ malformedSignature: malformed > 0 ? malformedHasher.digest('hex').slice(0, 16) : null,
+ invalidSignature: invalid > 0 ? invalidHasher.digest('hex').slice(0, 16) : null
+ };
+}
- const snapshotPath = getCostSnapshotPath(metricsDir, sessionId);
- assertCostLogSignature(source);
- return writeFileAtomic(
- snapshotPath,
- JSON.stringify({
- schema_version: COST_SNAPSHOT_SCHEMA_VERSION,
- source,
- row
- }),
+function writeSnapshotAtOffset(metricsDir, sessionId, row, descriptor, stat, offset) {
+ if (row !== null && !isValidCostRow(row, sessionId)) return false;
+ const snapshot = {
+ schema_version: COST_SNAPSHOT_SCHEMA_VERSION,
+ source: {
+ identity: sourceIdentity(stat),
+ offset_bytes: offset,
+ mtime_ms: stat.mtimeMs,
+ fingerprint: fingerprintProcessedPrefix(descriptor, offset)
+ },
+ row
+ };
+ writeFileAtomic(
+ getCostSnapshotPath(metricsDir, sessionId),
+ JSON.stringify(snapshot),
{
beforeRename() {
- if (!signaturesMatch(source, getCostLogSignature(metricsDir))) {
- throw new Error('Cost log changed while publishing its session snapshot');
+ const current = fs.fstatSync(descriptor);
+ if (sourceIdentity(current) !== snapshot.source.identity) {
+ throw new Error('Cost log identity changed during snapshot publication');
+ }
+ if (current.size < offset) {
+ throw new Error('Cost log was truncated during snapshot publication');
+ }
+ if (current.size === offset && current.mtimeMs !== snapshot.source.mtime_ms) {
+ throw new Error('Cost log changed during snapshot publication');
+ }
+ if (!fingerprintsMatch(
+ fingerprintProcessedPrefix(descriptor, offset),
+ snapshot.source.fingerprint
+ )) {
+ throw new Error('Cost log prefix changed during snapshot publication');
}
}
}
);
+ return true;
}
-function costLogEndsWithRow(metricsDir, row) {
- const expected = Buffer.from(`${JSON.stringify(row)}\n`, 'utf8');
- const descriptor = fs.openSync(path.join(metricsDir, COST_LOG_FILENAME), 'r');
+function refreshSessionCostSnapshot(metricsDir, sessionId) {
+ assertSafeSessionId(sessionId);
+ const costsPath = path.join(metricsDir, COST_LOG_FILENAME);
+ const descriptor = fs.openSync(costsPath, 'r');
try {
const stat = fs.fstatSync(descriptor);
- if (stat.size < expected.length) return false;
- const actual = Buffer.allocUnsafe(expected.length);
- const bytesRead = fs.readSync(
+ const snapshot = readJsonFile(getCostSnapshotPath(metricsDir, sessionId));
+ const base = validSnapshotBase(snapshot, descriptor, stat, sessionId);
+ if (base?.offset === stat.size) {
+ return {
+ row: base.row,
+ scannedBytes: 0,
+ malformed: 0,
+ invalid: 0,
+ malformedSignature: null,
+ invalidSignature: null,
+ snapshotError: null
+ };
+ }
+ const scan = scanJsonlRange(
descriptor,
- actual,
- 0,
- expected.length,
- stat.size - expected.length
+ base?.offset || 0,
+ stat.size,
+ sessionId,
+ base?.row || null
);
- return bytesRead === expected.length && actual.equals(expected);
+ let snapshotError = null;
+ if (scan.committedRow || scan.processedOffset > 0) {
+ try {
+ writeSnapshotAtOffset(
+ metricsDir,
+ sessionId,
+ scan.committedRow,
+ descriptor,
+ stat,
+ scan.processedOffset
+ );
+ } catch (error) {
+ snapshotError = error;
+ }
+ }
+ return {
+ row: scan.row,
+ scannedBytes: scan.processedOffset - (base?.offset || 0),
+ malformed: scan.malformed,
+ invalid: scan.invalid,
+ malformedSignature: scan.malformedSignature,
+ invalidSignature: scan.invalidSignature,
+ snapshotError
+ };
} finally {
fs.closeSync(descriptor);
}
}
-function publishAppendedSessionCostSnapshot(metricsDir, sessionId, row) {
+function costLogNeedsSeparator(metricsDir) {
+ const costsPath = path.join(metricsDir, COST_LOG_FILENAME);
+ let descriptor;
+ try {
+ descriptor = fs.openSync(costsPath, 'r');
+ const stat = fs.fstatSync(descriptor);
+ if (stat.size === 0) return false;
+ const lastByte = Buffer.alloc(1);
+ return fs.readSync(descriptor, lastByte, 0, 1, stat.size - 1) === 1
+ && lastByte[0] !== 0x0a;
+ } catch (error) {
+ if (error.code === 'ENOENT') return false;
+ throw error;
+ } finally {
+ if (descriptor !== undefined) fs.closeSync(descriptor);
+ }
+}
+
+function appendSessionCostRow(metricsDir, sessionId, row) {
assertSafeSessionId(sessionId);
if (!isValidCostRow(row, sessionId)) {
throw new Error('Cost snapshot requires valid non-negative numeric totals for its session');
}
- const sourceBefore = getCostLogSignature(metricsDir);
- if (!costLogEndsWithRow(metricsDir, row)) return false;
- const sourceAfter = getCostLogSignature(metricsDir);
- if (!signaturesMatch(sourceBefore, sourceAfter)) return false;
- writeSnapshotForSource(metricsDir, sessionId, row, sourceAfter);
- return true;
+ const prefix = costLogNeedsSeparator(metricsDir) ? '\n' : '';
+ fs.appendFileSync(
+ path.join(metricsDir, COST_LOG_FILENAME),
+ `${prefix}${JSON.stringify(row)}\n`,
+ 'utf8'
+ );
+ const result = refreshSessionCostSnapshot(metricsDir, sessionId);
+ if (result.snapshotError) throw result.snapshotError;
+ try {
+ maybePruneSessionCostSnapshots(metricsDir);
+ } catch {
+ // Retention is opportunistic and retried by a later update.
+ }
+ return JSON.stringify(result.row) === JSON.stringify(row);
}
-function repairSessionCostSnapshot(metricsDir, sessionId, row, source) {
- writeSnapshotForSource(metricsDir, sessionId, row, source);
+function readSessionCostSnapshot(metricsDir, sessionId) {
+ try {
+ return refreshSessionCostSnapshot(metricsDir, sessionId);
+ } catch (error) {
+ if (error.code === 'ENOENT') {
+ return { row: null, scannedBytes: 0, malformed: 0, invalid: 0, snapshotError: null };
+ }
+ throw error;
+ }
}
-function readSessionCostSnapshot(metricsDir, sessionId) {
+function maybePruneSessionCostSnapshots(metricsDir, options = {}) {
+ const snapshotDir = getSnapshotDirectory(metricsDir);
+ const now = Number.isFinite(options.now) ? options.now : Date.now();
+ const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : SNAPSHOT_MAX_AGE_MS;
+ const maxSnapshots = Number.isSafeInteger(options.maxSnapshots)
+ ? Math.max(0, options.maxSnapshots)
+ : MAX_SNAPSHOTS;
+ const markerPath = path.join(snapshotDir, '.last-prune');
+
+ fs.mkdirSync(snapshotDir, { recursive: true });
+ const snapshotEntries = fs.readdirSync(snapshotDir, { withFileTypes: true })
+ .filter(entry => entry.isFile() && /^session-.+\.json$/.test(entry.name));
+ if (!options.force) {
+ try {
+ const intervalIsFresh = now - fs.statSync(markerPath).mtimeMs < PRUNE_INTERVAL_MS;
+ if (intervalIsFresh && snapshotEntries.length <= maxSnapshots) return 0;
+ } catch { /* missing marker */ }
+ }
+ fs.writeFileSync(markerPath, String(now), { encoding: 'utf8', mode: 0o600 });
+
+ const snapshots = snapshotEntries
+ .map(entry => {
+ const filePath = path.join(snapshotDir, entry.name);
+ return { filePath, mtimeMs: fs.statSync(filePath).mtimeMs };
+ })
+ .sort((left, right) => right.mtimeMs - left.mtimeMs);
+ const removals = snapshots.filter((entry, index) => (
+ index >= maxSnapshots || now - entry.mtimeMs > maxAgeMs
+ ));
+ let removed = 0;
+ for (const entry of removals) {
+ try {
+ if (fs.statSync(entry.filePath).mtimeMs <= entry.mtimeMs) {
+ fs.rmSync(entry.filePath, { force: true });
+ removed += 1;
+ }
+ } catch { /* already replaced or removed */ }
+ }
+ return removed;
+}
+
+function warningClaimPath(kind, metricsDir, sessionId, signature) {
+ const key = crypto.createHash('sha256')
+ .update(`${path.resolve(metricsDir)}\0${sessionId}\0${kind}\0${signature}`)
+ .digest('hex')
+ .slice(0, 16);
+ return path.join(os.tmpdir(), `${WARNING_CACHE_PREFIX}${key}.claim`);
+}
+
+function warnSessionCostSnapshotFailure(kind, metricsDir, sessionId, error) {
+ const targetPath = getCostSnapshotPath(metricsDir, sessionId);
+ const errorCode = error?.code || error?.name || 'error';
+ const signature = `${kind}:${targetPath}:${errorCode}`;
+ const claimPath = warningClaimPath(kind, metricsDir, sessionId, signature);
+ let claimDescriptor;
try {
- const snapshot = JSON.parse(
- fs.readFileSync(getCostSnapshotPath(metricsDir, sessionId), 'utf8')
- );
- if (snapshot?.schema_version !== COST_SNAPSHOT_SCHEMA_VERSION) return null;
- if (!isValidCostRow(snapshot.row, sessionId)) return null;
- if (!signaturesMatch(snapshot.source, getCostLogSignature(metricsDir))) return null;
- return snapshot.row;
- } catch {
- return null;
+ claimDescriptor = fs.openSync(claimPath, 'wx', 0o600);
+ fs.closeSync(claimDescriptor);
+ claimDescriptor = undefined;
+ } catch (claimError) {
+ if (claimDescriptor !== undefined) fs.closeSync(claimDescriptor);
+ if (claimError.code === 'EEXIST') return;
+ // Warning persistence is best effort. If the claim cannot be created,
+ // still surface the underlying snapshot failure.
}
+ process.stderr.write(
+ `[cost-snapshot] ${kind} failed for session ${sessionId}: ${error?.message || String(error)}\n`
+ );
}
module.exports = {
@@ -138,10 +400,12 @@ module.exports = {
COST_SNAPSHOT_DIRECTORY,
COST_LOG_FILENAME,
getCostSnapshotPath,
- getCostLogSignature,
- signaturesMatch,
isValidCostRow,
- publishAppendedSessionCostSnapshot,
- repairSessionCostSnapshot,
- readSessionCostSnapshot
+ chooseNewerCumulativeRow,
+ appendSessionCostRow,
+ readSessionCostSnapshot,
+ refreshSessionCostSnapshot,
+ costLogNeedsSeparator,
+ maybePruneSessionCostSnapshots,
+ warnSessionCostSnapshotFailure
};
diff --git a/skills/cost-tracking/SKILL.md b/skills/cost-tracking/SKILL.md
index f0f4bfed6..4347ce8f4 100644
--- a/skills/cost-tracking/SKILL.md
+++ b/skills/cost-tracking/SKILL.md
@@ -20,7 +20,10 @@ sum across sessions — summing every row multiply-counts.
ECC also maintains internal per-session files under
`~/.claude/metrics/cost-snapshots/` so runtime hooks can read the current
session total without rescanning all history. Treat those files as a
-rebuildable cache; reports and exports should continue to use `costs.jsonl`.
+rebuildable cache; each snapshot stores a byte cursor so only newly appended
+rows are scanned. Stable reads are O(1), while updates are O(new bytes). Stale
+entries are pruned after 30 days or when the directory exceeds 512 sessions.
+Reports and exports should continue to use `costs.jsonl`.
Row schema:
diff --git a/tests/hooks/cost-tracker.test.js b/tests/hooks/cost-tracker.test.js
index 5946350eb..066c3226d 100644
--- a/tests/hooks/cost-tracker.test.js
+++ b/tests/hooks/cost-tracker.test.js
@@ -119,10 +119,9 @@ function runTests() {
(test('keeps JSONL authoritative when the snapshot path cannot be published', () => {
const tmpHome = makeTempDir();
const metricsDir = path.join(tmpHome, '.claude', 'metrics');
- const blockedSnapshotPath = path.join(
+ const blockedSnapshotPath = getCostSnapshotPath(
metricsDir,
- 'cost-snapshots',
- 'snapshot-failure.json'
+ 'snapshot-failure'
);
fs.mkdirSync(blockedSnapshotPath, { recursive: true });
@@ -137,6 +136,14 @@ function runTests() {
.split('\n')
.map(line => JSON.parse(line));
assert.strictEqual(rows.at(-1).session_id, 'snapshot-failure');
+ assert.match(result.stderr, /cost-snapshot.*publication failed/);
+
+ const second = runScript(
+ { session_id: 'snapshot-failure' },
+ withTempHome(tmpHome)
+ );
+ assert.strictEqual(second.code, 0, second.stderr);
+ assert.strictEqual(second.stderr, '', 'identical persistent failure should warn only once');
} finally {
fs.rmSync(tmpHome, { recursive: true, force: true });
}
diff --git a/tests/hooks/ecc-metrics-bridge.test.js b/tests/hooks/ecc-metrics-bridge.test.js
index 73f440ef1..246301622 100644
--- a/tests/hooks/ecc-metrics-bridge.test.js
+++ b/tests/hooks/ecc-metrics-bridge.test.js
@@ -12,8 +12,8 @@ const path = require('path');
const { run, hashToolCall, extractFilePaths, readSessionCost } = require('../../scripts/hooks/ecc-metrics-bridge');
const {
- getCostSnapshotPath,
- publishAppendedSessionCostSnapshot
+ appendSessionCostRow,
+ getCostSnapshotPath
} = require('../../scripts/lib/session-cost-snapshot');
// Test helper
@@ -242,7 +242,8 @@ function runTests() {
const tmpHome = makeTempHome();
const originalHome = process.env.HOME;
const originalUserProfile = process.env.USERPROFILE;
- const originalReadFileSync = fs.readFileSync;
+ const originalReadSync = fs.readSync;
+ let bytesReadFromCostLog = 0;
try {
process.env.HOME = tmpHome;
process.env.USERPROFILE = tmpHome;
@@ -255,27 +256,18 @@ function runTests() {
input_tokens: 750,
output_tokens: 375
};
- fs.writeFileSync(
- path.join(metricsDir, 'costs.jsonl'),
- `${JSON.stringify(snapshotRow)}\n`,
- 'utf8'
- );
- assert.strictEqual(
- publishAppendedSessionCostSnapshot(metricsDir, 'S1', snapshotRow),
- true
- );
+ appendSessionCostRow(metricsDir, 'S1', snapshotRow);
- fs.readFileSync = function guardedRead(filePath, ...args) {
- if (path.basename(String(filePath)) === 'costs.jsonl') {
- throw new Error('historical JSONL scan should be bypassed on a snapshot hit');
- }
- return originalReadFileSync.call(this, filePath, ...args);
+ fs.readSync = function measuredRead(descriptor, buffer, offset, length, position) {
+ bytesReadFromCostLog += length;
+ return originalReadSync.call(this, descriptor, buffer, offset, length, position);
};
const result = readSessionCost('S1');
assert.deepStrictEqual(result, { totalCost: 0.75, totalIn: 750, totalOut: 375 });
+ assert.ok(bytesReadFromCostLog <= 3 * 256);
} finally {
- fs.readFileSync = originalReadFileSync;
+ fs.readSync = originalReadSync;
if (originalHome === undefined) delete process.env.HOME;
else process.env.HOME = originalHome;
if (originalUserProfile === undefined) delete process.env.USERPROFILE;
@@ -288,7 +280,7 @@ function runTests() {
else failed++;
if (
- test('readSessionCost ignores a stale snapshot after costs.jsonl advances', () => {
+ test('readSessionCost keeps session A on the fast path after session B appends', () => {
const tmpHome = makeTempHome();
const originalHome = process.env.HOME;
const originalUserProfile = process.env.USERPROFILE;
@@ -303,38 +295,24 @@ function runTests() {
input_tokens: 100,
output_tokens: 50
};
- const latest = {
- session_id: 'S1',
+ appendSessionCostRow(metricsDir, 'S1', first);
+ appendSessionCostRow(metricsDir, 'S2', {
+ session_id: 'S2',
estimated_cost_usd: 2,
input_tokens: 200,
output_tokens: 100
- };
- const costsPath = path.join(metricsDir, 'costs.jsonl');
- fs.writeFileSync(costsPath, `${JSON.stringify(first)}\n`, 'utf8');
- publishAppendedSessionCostSnapshot(metricsDir, 'S1', first);
- fs.appendFileSync(costsPath, `${JSON.stringify(latest)}\n`, 'utf8');
-
- assert.deepStrictEqual(readSessionCost('S1'), {
- totalCost: 2,
- totalIn: 200,
- totalOut: 100
});
-
- const originalReadFileSync = fs.readFileSync;
- fs.readFileSync = function guardedRead(filePath, ...args) {
- if (path.basename(String(filePath)) === 'costs.jsonl') {
- throw new Error('fallback should repair the session snapshot');
- }
- return originalReadFileSync.call(this, filePath, ...args);
+ const originalReadSync = fs.readSync;
+ let bytesReadFromCostLog = 0;
+ fs.readSync = function measuredRead(descriptor, buffer, offset, length, position) {
+ bytesReadFromCostLog += length;
+ return originalReadSync.call(this, descriptor, buffer, offset, length, position);
};
try {
- assert.deepStrictEqual(readSessionCost('S1'), {
- totalCost: 2,
- totalIn: 200,
- totalOut: 100
- });
+ assert.deepStrictEqual(readSessionCost('S1'), { totalCost: 1, totalIn: 100, totalOut: 50 });
+ assert.ok(bytesReadFromCostLog <= 2 * 1024);
} finally {
- fs.readFileSync = originalReadFileSync;
+ fs.readSync = originalReadSync;
}
} finally {
if (originalHome === undefined) delete process.env.HOME;
@@ -407,12 +385,12 @@ function runTests() {
};
const costsPath = path.join(metricsDir, 'costs.jsonl');
fs.writeFileSync(costsPath, `${JSON.stringify(valid)}\n`, 'utf8');
- const stat = fs.statSync(costsPath);
+ appendSessionCostRow(metricsDir, 'S1', valid);
+ const snapshot = JSON.parse(fs.readFileSync(getCostSnapshotPath(metricsDir, 'S1'), 'utf8'));
fs.writeFileSync(
getCostSnapshotPath(metricsDir, 'S1'),
JSON.stringify({
- schema_version: 'ecc.cost-snapshot.v1',
- source: { size_bytes: stat.size, mtime_ms: stat.mtimeMs },
+ ...snapshot,
row: { session_id: 'S1' }
}),
'utf8'
diff --git a/tests/lib/session-cost-snapshot.test.js b/tests/lib/session-cost-snapshot.test.js
index de78b2fae..a41165ba4 100644
--- a/tests/lib/session-cost-snapshot.test.js
+++ b/tests/lib/session-cost-snapshot.test.js
@@ -1,16 +1,29 @@
'use strict';
const assert = require('assert');
+const { execFileSync } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const {
- COST_SNAPSHOT_SCHEMA_VERSION,
+ appendSessionCostRow,
getCostSnapshotPath,
- publishAppendedSessionCostSnapshot,
+ maybePruneSessionCostSnapshots,
readSessionCostSnapshot,
+ refreshSessionCostSnapshot,
+ warnSessionCostSnapshotFailure
} = require('../../scripts/lib/session-cost-snapshot');
+function row(sessionId, cost = 1) {
+ return {
+ timestamp: new Date(Date.UTC(2026, 0, 1, 0, 0, cost)).toISOString(),
+ session_id: sessionId,
+ estimated_cost_usd: cost,
+ input_tokens: cost * 100,
+ output_tokens: cost * 50
+ };
+}
+
function test(name, fn) {
try {
fn();
@@ -24,23 +37,16 @@ function test(name, fn) {
}
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-cost-snapshot-'));
-const costLogPath = path.join(root, 'costs.jsonl');
let passed = 0;
let failed = 0;
try {
- if (test('round-trips a versioned cumulative row atomically', () => {
- const row = {
- session_id: 'session-1',
- estimated_cost_usd: 1.25,
- input_tokens: 10,
- output_tokens: 20
- };
- fs.writeFileSync(costLogPath, `${JSON.stringify(row)}\n`, 'utf8');
- assert.strictEqual(publishAppendedSessionCostSnapshot(root, 'session-1', row), true);
+ if (test('appends and atomically publishes a private cumulative snapshot', () => {
+ const current = row('session-1', 1.25);
+ assert.strictEqual(appendSessionCostRow(root, 'session-1', current), true);
const filePath = getCostSnapshotPath(root, 'session-1');
- assert.strictEqual(filePath, getCostSnapshotPath(root, 'session-1'));
- assert.deepStrictEqual(readSessionCostSnapshot(root, 'session-1'), row);
+ assert.deepStrictEqual(readSessionCostSnapshot(root, 'session-1').row, current);
+ assert.strictEqual(fs.statSync(filePath).mode & 0o777, 0o600);
assert.deepStrictEqual(
fs.readdirSync(path.dirname(filePath)).filter(name => name.endsWith('.tmp')),
[]
@@ -48,87 +54,177 @@ try {
})) passed++; else failed++;
if (test('replaces the previous cumulative row for the same session', () => {
- const first = {
- session_id: 'session-update',
- estimated_cost_usd: 1,
- input_tokens: 100,
- output_tokens: 50
- };
- fs.writeFileSync(costLogPath, `${JSON.stringify(first)}\n`, 'utf8');
- assert.strictEqual(publishAppendedSessionCostSnapshot(root, 'session-update', first), true);
- const latest = {
- session_id: 'session-update',
- estimated_cost_usd: 2,
- input_tokens: 200,
- output_tokens: 100
- };
- fs.appendFileSync(costLogPath, `${JSON.stringify(latest)}\n`, 'utf8');
- assert.strictEqual(publishAppendedSessionCostSnapshot(root, 'session-update', latest), true);
- assert.deepStrictEqual(readSessionCostSnapshot(root, 'session-update'), latest);
+ appendSessionCostRow(root, 'session-update', row('session-update', 1));
+ const latest = row('session-update', 2);
+ appendSessionCostRow(root, 'session-update', latest);
+ assert.deepStrictEqual(readSessionCostSnapshot(root, 'session-update').row, latest);
+ })) passed++; else failed++;
+
+ if (test('a delayed older writer cannot lower the latest cumulative total', () => {
+ const older = row('session-order', 1);
+ const newer = row('session-order', 2);
+ older.timestamp = new Date(Date.parse(newer.timestamp) + 1000).toISOString();
+ assert.strictEqual(appendSessionCostRow(root, 'session-order', newer), true);
+ assert.strictEqual(appendSessionCostRow(root, 'session-order', older), false);
+ assert.deepStrictEqual(readSessionCostSnapshot(root, 'session-order').row, newer);
})) passed++; else failed++;
- if (test('invalidates a snapshot when the append-only cost log advances', () => {
- const first = {
- session_id: 'session-stale',
- estimated_cost_usd: 1,
- input_tokens: 100,
- output_tokens: 50
+ if (test('publication failure followed by an older writer still converges to the newer row', () => {
+ const sessionId = 'session-publication-race';
+ const older = row(sessionId, 1);
+ const newer = row(sessionId, 2);
+ older.timestamp = new Date(Date.parse(newer.timestamp) + 1000).toISOString();
+ const snapshotPath = getCostSnapshotPath(root, sessionId);
+ const originalRenameSync = fs.renameSync;
+ let injectedFailure = false;
+ fs.renameSync = function failNewerSnapshot(sourcePath, destinationPath) {
+ if (!injectedFailure && path.resolve(destinationPath) === path.resolve(snapshotPath)) {
+ injectedFailure = true;
+ const error = new Error('injected snapshot publication failure');
+ error.code = 'EIO';
+ throw error;
+ }
+ return originalRenameSync.call(this, sourcePath, destinationPath);
};
- fs.writeFileSync(costLogPath, `${JSON.stringify(first)}\n`, 'utf8');
- assert.strictEqual(publishAppendedSessionCostSnapshot(root, 'session-stale', first), true);
- fs.appendFileSync(
- costLogPath,
- `${JSON.stringify({ session_id: 'session-stale', estimated_cost_usd: 2, input_tokens: 200, output_tokens: 100 })}\n`,
- 'utf8'
- );
- assert.strictEqual(readSessionCostSnapshot(root, 'session-stale'), null);
+ try {
+ assert.throws(() => appendSessionCostRow(root, sessionId, newer), /injected/);
+ } finally {
+ fs.renameSync = originalRenameSync;
+ }
+ assert.strictEqual(appendSessionCostRow(root, sessionId, older), false);
+ assert.deepStrictEqual(readSessionCostSnapshot(root, sessionId).row, newer);
})) passed++; else failed++;
- if (test('a delayed older writer cannot overwrite the newest session row', () => {
- const older = { session_id: 'session-race', estimated_cost_usd: 1, input_tokens: 100, output_tokens: 50 };
- const newer = { session_id: 'session-race', estimated_cost_usd: 2, input_tokens: 200, output_tokens: 100 };
- fs.writeFileSync(costLogPath, `${JSON.stringify(older)}\n`, 'utf8');
- fs.appendFileSync(costLogPath, `${JSON.stringify(newer)}\n`, 'utf8');
- assert.strictEqual(publishAppendedSessionCostSnapshot(root, 'session-race', newer), true);
- assert.strictEqual(publishAppendedSessionCostSnapshot(root, 'session-race', older), false);
- assert.deepStrictEqual(readSessionCostSnapshot(root, 'session-race'), newer);
+ if (test('accepts increasing cumulative totals that share a timestamp', () => {
+ const first = row('session-same-time', 1);
+ const next = row('session-same-time', 2);
+ next.timestamp = first.timestamp;
+ appendSessionCostRow(root, 'session-same-time', first);
+ assert.strictEqual(appendSessionCostRow(root, 'session-same-time', next), true);
+ assert.deepStrictEqual(readSessionCostSnapshot(root, 'session-same-time').row, next);
})) passed++; else failed++;
- if (test('rejects unsafe session IDs instead of escaping the snapshot directory', () => {
- const unsafeId = '../outside';
- const row = { session_id: unsafeId, estimated_cost_usd: 9, input_tokens: 9, output_tokens: 9 };
- fs.writeFileSync(costLogPath, `${JSON.stringify(row)}\n`, 'utf8');
- assert.throws(
- () => publishAppendedSessionCostSnapshot(root, unsafeId, row),
- /safe session ID/
- );
+ if (test('uses timestamps when cumulative dimensions move in opposite directions', () => {
+ const newer = row('session-mixed', 1);
+ newer.input_tokens = 200;
+ newer.output_tokens = 100;
+ newer.timestamp = '2026-01-02T00:00:00.000Z';
+ const delayedOlder = row('session-mixed', 2);
+ delayedOlder.input_tokens = 100;
+ delayedOlder.output_tokens = 50;
+ delayedOlder.timestamp = '2026-01-01T00:00:00.000Z';
+ appendSessionCostRow(root, 'session-mixed', newer);
+ assert.strictEqual(appendSessionCostRow(root, 'session-mixed', delayedOlder), false);
+ assert.deepStrictEqual(readSessionCostSnapshot(root, 'session-mixed').row, newer);
+ })) passed++; else failed++;
+
+ if (test('session B only creates a bounded delta scan for session A', () => {
+ const sessionA = row('session-a', 3);
+ appendSessionCostRow(root, 'session-a', sessionA);
+ const sessionB = row('session-b', 4);
+ appendSessionCostRow(root, 'session-b', sessionB);
+ const refreshed = refreshSessionCostSnapshot(root, 'session-a');
+ assert.deepStrictEqual(refreshed.row, sessionA);
+ assert.ok(refreshed.scannedBytes > 0);
+ assert.ok(refreshed.scannedBytes <= Buffer.byteLength(`${JSON.stringify(sessionB)}\n`));
+ assert.strictEqual(refreshSessionCostSnapshot(root, 'session-a').scannedBytes, 0);
+ })) passed++; else failed++;
+
+ if (test('sessions with no row cache their progress cursor', () => {
+ const caseRoot = path.join(root, 'missing-session');
+ fs.mkdirSync(caseRoot, { recursive: true });
+ const costsPath = path.join(caseRoot, 'costs.jsonl');
+ const other = row('other-only', 1);
+ fs.writeFileSync(costsPath, `${JSON.stringify(other)}\n`.repeat(4000), 'utf8');
+ const first = refreshSessionCostSnapshot(caseRoot, 'missing');
+ const second = refreshSessionCostSnapshot(caseRoot, 'missing');
+ assert.ok(first.scannedBytes > 100000);
+ assert.strictEqual(first.row, null);
+ assert.strictEqual(second.scannedBytes, 0);
+ assert.strictEqual(second.row, null);
+ })) passed++; else failed++;
+
+ if (test('does not advance the cursor past an incomplete trailing row', () => {
+ const caseRoot = path.join(root, 'partial-row');
+ fs.mkdirSync(caseRoot, { recursive: true });
+ const current = row('partial', 6);
+ const serialized = JSON.stringify(current);
+ fs.writeFileSync(path.join(caseRoot, 'costs.jsonl'), serialized, 'utf8');
+ const partial = refreshSessionCostSnapshot(caseRoot, 'partial');
+ assert.deepStrictEqual(partial.row, current);
+ assert.strictEqual(partial.scannedBytes, 0);
+ assert.strictEqual(partial.malformed, 0);
+ fs.appendFileSync(path.join(caseRoot, 'costs.jsonl'), '\n', 'utf8');
+ const complete = refreshSessionCostSnapshot(caseRoot, 'partial');
+ assert.deepStrictEqual(complete.row, current);
+ assert.strictEqual(complete.scannedBytes, Buffer.byteLength(`${serialized}\n`));
+ })) passed++; else failed++;
+
+ if (test('never persists a provisional unterminated row when later bytes corrupt it', () => {
+ const caseRoot = path.join(root, 'partial-corruption');
+ fs.mkdirSync(caseRoot, { recursive: true });
+ const costsPath = path.join(caseRoot, 'costs.jsonl');
+ const provisional = row('partial-corruption', 7);
+ fs.writeFileSync(costsPath, JSON.stringify(provisional), 'utf8');
+ const first = refreshSessionCostSnapshot(caseRoot, 'partial-corruption');
+ assert.deepStrictEqual(first.row, provisional);
+ assert.strictEqual(first.scannedBytes, 0);
+
+ const recovered = row('partial-corruption', 8);
+ appendSessionCostRow(caseRoot, 'partial-corruption', recovered);
+ assert.deepStrictEqual(refreshSessionCostSnapshot(caseRoot, 'partial-corruption').row, recovered);
+ })) passed++; else failed++;
- const escapedPath = path.join(root, 'outside.json');
+ if (test('keeps UTF-8 rows intact across the 64 KiB read boundary', () => {
+ const caseRoot = path.join(root, 'utf8-boundary');
+ fs.mkdirSync(caseRoot, { recursive: true });
+ const current = { ...row('utf8', 7), note: `${'x'.repeat(65520)}数据` };
fs.writeFileSync(
- escapedPath,
- JSON.stringify({ schema_version: COST_SNAPSHOT_SCHEMA_VERSION, row }),
+ path.join(caseRoot, 'costs.jsonl'),
+ `${JSON.stringify(current)}\n`,
'utf8'
);
- assert.strictEqual(readSessionCostSnapshot(root, unsafeId), null);
+ assert.deepStrictEqual(refreshSessionCostSnapshot(caseRoot, 'utf8').row, current);
})) passed++; else failed++;
- if (test('prefixes Windows reserved device names with a safe basename', () => {
- assert.strictEqual(path.basename(getCostSnapshotPath(root, 'CON')), 'session-CON.json');
- assert.strictEqual(path.basename(getCostSnapshotPath(root, 'nul')), 'session-nul.json');
+ if (test('rebuilds after an in-place rewrite or inode rotation', () => {
+ const caseRoot = path.join(root, 'rotation');
+ fs.mkdirSync(caseRoot, { recursive: true });
+ const costsPath = path.join(caseRoot, 'costs.jsonl');
+ const first = row('rotated', 1);
+ const rewritten = row('rotated', 9);
+ appendSessionCostRow(caseRoot, 'rotated', first);
+ fs.writeFileSync(costsPath, `${JSON.stringify(rewritten)}\n`, 'utf8');
+ assert.deepStrictEqual(refreshSessionCostSnapshot(caseRoot, 'rotated').row, rewritten);
+
+ const rotated = row('rotated', 10);
+ fs.renameSync(costsPath, `${costsPath}.old`);
+ fs.writeFileSync(costsPath, `${JSON.stringify(rotated)}\n`, 'utf8');
+ assert.deepStrictEqual(refreshSessionCostSnapshot(caseRoot, 'rotated').row, rotated);
})) passed++; else failed++;
- if (test('rejects a snapshot whose row is bound to another session', () => {
- const filePath = getCostSnapshotPath(root, 'session-2');
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(
- filePath,
- JSON.stringify({
- schema_version: COST_SNAPSHOT_SCHEMA_VERSION,
- row: { session_id: 'session-3', estimated_cost_usd: 3 }
- }),
- 'utf8'
+ if (test('detects same-size in-place changes outside the tail window', () => {
+ const caseRoot = path.join(root, 'same-size-rewrite');
+ fs.mkdirSync(caseRoot, { recursive: true });
+ const costsPath = path.join(caseRoot, 'costs.jsonl');
+ const first = row('same-size', 1);
+ const rewritten = { ...first, estimated_cost_usd: 9 };
+ const filler = `${JSON.stringify(row('filler', 2))}\n`.repeat(20);
+ fs.writeFileSync(costsPath, `${JSON.stringify(first)}\n${filler}`, 'utf8');
+ refreshSessionCostSnapshot(caseRoot, 'same-size');
+ fs.writeFileSync(costsPath, `${JSON.stringify(rewritten)}\n${filler}`, 'utf8');
+ const rebuilt = refreshSessionCostSnapshot(caseRoot, 'same-size');
+ assert.ok(rebuilt.scannedBytes > 0);
+ assert.deepStrictEqual(rebuilt.row, rewritten);
+ })) passed++; else failed++;
+
+ if (test('rejects unsafe session IDs and prefixes Windows device names', () => {
+ assert.throws(
+ () => appendSessionCostRow(root, '../outside', row('../outside', 9)),
+ /safe session ID/
);
- assert.strictEqual(readSessionCostSnapshot(root, 'session-2'), null);
+ assert.strictEqual(path.basename(getCostSnapshotPath(root, 'CON')), 'session-CON.json');
+ assert.strictEqual(path.basename(getCostSnapshotPath(root, 'nul')), 'session-nul.json');
})) passed++; else failed++;
if (test('rejects rows with missing, non-numeric, or negative totals', () => {
@@ -138,33 +234,142 @@ try {
{ session_id: 'invalid-row', estimated_cost_usd: 1, input_tokens: -1, output_tokens: 1 },
{ session_id: 'invalid-row', estimated_cost_usd: 1, input_tokens: 1, output_tokens: Infinity }
];
- for (const row of invalidRows) {
- fs.writeFileSync(costLogPath, `${JSON.stringify(row)}\n`, 'utf8');
+ for (const invalidRow of invalidRows) {
assert.throws(
- () => publishAppendedSessionCostSnapshot(root, 'invalid-row', row),
+ () => appendSessionCostRow(root, 'invalid-row', invalidRow),
/valid non-negative numeric totals/
);
}
})) passed++; else failed++;
- if (test('rejects unknown schemas and malformed JSON', () => {
- const filePath = getCostSnapshotPath(root, 'session-4');
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- fs.writeFileSync(
- filePath,
- JSON.stringify({
- schema_version: 'ecc.cost-snapshot.v999',
- row: { session_id: 'session-4' }
- }),
- 'utf8'
- );
- assert.strictEqual(readSessionCostSnapshot(root, 'session-4'), null);
- fs.writeFileSync(filePath, '{broken', 'utf8');
- assert.strictEqual(readSessionCostSnapshot(root, 'session-4'), null);
+ if (test('malformed snapshots rebuild from the authoritative JSONL', () => {
+ const sessionId = 'session-invalid';
+ const current = row(sessionId, 5);
+ appendSessionCostRow(root, sessionId, current);
+ fs.writeFileSync(getCostSnapshotPath(root, sessionId), '{broken', 'utf8');
+ const rebuilt = refreshSessionCostSnapshot(root, sessionId);
+ assert.deepStrictEqual(rebuilt.row, current);
+ assert.deepStrictEqual(readSessionCostSnapshot(root, sessionId).row, current);
+ })) passed++; else failed++;
+
+ if (test('prunes expired snapshots and enforces the count bound', () => {
+ const now = Date.now();
+ for (let index = 0; index < 4; index += 1) {
+ const sessionId = `prune-${index}`;
+ appendSessionCostRow(root, sessionId, row(sessionId, index + 1));
+ const old = new Date(now - ((index + 1) * 1000));
+ fs.utimesSync(getCostSnapshotPath(root, sessionId), old, old);
+ }
+ const removed = maybePruneSessionCostSnapshots(root, {
+ force: true,
+ now,
+ maxAgeMs: 2500,
+ maxSnapshots: 2
+ });
+ const remaining = fs.readdirSync(path.join(root, 'cost-snapshots'))
+ .filter(name => name.startsWith('session-'));
+ assert.ok(removed >= 2);
+ assert.ok(remaining.length <= 2);
+ })) passed++; else failed++;
+
+ if (test('enforces the count bound while the age-prune marker is fresh', () => {
+ const caseRoot = path.join(root, 'count-bound');
+ fs.mkdirSync(caseRoot, { recursive: true });
+ const now = Date.now();
+ assert.strictEqual(maybePruneSessionCostSnapshots(caseRoot, {
+ force: true,
+ now,
+ maxSnapshots: 2
+ }), 0);
+ for (let index = 0; index < 5; index += 1) {
+ appendSessionCostRow(caseRoot, `count-${index}`, row(`count-${index}`, index + 1));
+ }
+ const removed = maybePruneSessionCostSnapshots(caseRoot, {
+ now: now + 1000,
+ maxSnapshots: 2
+ });
+ const remaining = fs.readdirSync(path.join(caseRoot, 'cost-snapshots'))
+ .filter(name => name.startsWith('session-'));
+ assert.strictEqual(removed, 3);
+ assert.strictEqual(remaining.length, 2);
+ })) passed++; else failed++;
+
+ if (test('deduplicates snapshot warnings independently by failure kind', () => {
+ const caseRoot = path.join(root, 'warning-dedupe');
+ const originalWrite = process.stderr.write.bind(process.stderr);
+ let captured = '';
+ process.stderr.write = chunk => {
+ captured += String(chunk);
+ return true;
+ };
+ try {
+ const error = Object.assign(new Error('persistent failure'), { code: 'EIO' });
+ warnSessionCostSnapshotFailure('publication', caseRoot, 'warn-session', error);
+ warnSessionCostSnapshotFailure('repair', caseRoot, 'warn-session', error);
+ warnSessionCostSnapshotFailure('publication', caseRoot, 'warn-session', error);
+ warnSessionCostSnapshotFailure('repair', caseRoot, 'warn-session', error);
+ const warnings = captured.trim().split('\n');
+ assert.strictEqual(warnings.length, 2);
+ assert.match(warnings[0], /publication failed/);
+ assert.match(warnings[1], /repair failed/);
+ } finally {
+ process.stderr.write = originalWrite;
+ }
+ })) passed++; else failed++;
+
+ if (test('deduplicates the same snapshot warning across concurrent processes', () => {
+ const caseRoot = path.join(root, 'warning-concurrency');
+ fs.mkdirSync(caseRoot, { recursive: true });
+ const modulePath = path.resolve(__dirname, '../../scripts/lib/session-cost-snapshot.js');
+ const workerScript = [
+ "const fs = require('fs');",
+ "const path = require('path');",
+ "const [modulePath, metricsDir, gatePath, index] = process.argv.slice(1);",
+ "fs.writeFileSync(path.join(metricsDir, `ready-${index}`), '');",
+ "const timer = setInterval(() => {",
+ " if (!fs.existsSync(gatePath)) return;",
+ " clearInterval(timer);",
+ " const { warnSessionCostSnapshotFailure } = require(modulePath);",
+ " const error = Object.assign(new Error('persistent failure'), { code: 'EIO' });",
+ " warnSessionCostSnapshotFailure('publication', metricsDir, 'shared-session', error);",
+ "}, 1);"
+ ].join('\n');
+ const orchestratorScript = [
+ "const { spawn } = require('child_process');",
+ "const fs = require('fs');",
+ "const path = require('path');",
+ "const [modulePath, metricsDir] = process.argv.slice(1);",
+ "const gatePath = path.join(metricsDir, 'go');",
+ `const workerScript = ${JSON.stringify(workerScript)};`,
+ "const runs = Array.from({ length: 16 }, (_, index) => new Promise((resolve, reject) => {",
+ " const child = spawn(process.execPath, ['-e', workerScript, modulePath, metricsDir, gatePath, String(index)], { stdio: ['ignore', 'ignore', 'pipe'] });",
+ " let stderr = '';",
+ " child.stderr.on('data', chunk => { stderr += chunk; });",
+ " child.on('error', reject);",
+ " child.on('close', code => resolve({ code, stderr }));",
+ "}));",
+ "const readyTimer = setInterval(() => {",
+ " const ready = fs.readdirSync(metricsDir).filter(name => name.startsWith('ready-'));",
+ " if (ready.length !== runs.length) return;",
+ " clearInterval(readyTimer);",
+ " fs.writeFileSync(gatePath, 'go');",
+ "}, 1);",
+ "Promise.all(runs).then(results => {",
+ " const warnings = results.flatMap(result => result.stderr.split('\\n')).filter(line => line.includes('publication failed'));",
+ " process.stdout.write(JSON.stringify({ codes: results.map(result => result.code), warnings: warnings.length }));",
+ "});"
+ ].join('\n');
+ const result = JSON.parse(execFileSync(
+ process.execPath,
+ ['-e', orchestratorScript, modulePath, caseRoot],
+ { encoding: 'utf8', timeout: 10000 }
+ ));
+ assert.deepStrictEqual(result.codes, Array(16).fill(0));
+ assert.strictEqual(result.warnings, 1);
})) passed++; else failed++;
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
-console.log(`\nResults: ${passed} passed, ${failed} failed`);
+console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
process.exit(failed > 0 ? 1 : 0);