Skip to content

Commit 87b3563

Browse files
committed
fix(usage): lock the forecast history while a render rewrites it
The renders of every session and profile share session-usage-history.json. A render read the whole file, added its reading and renamed a new file over it, so when two renders overlapped, the later rename put back what it had read: the other render's new reading was lost, or a whole profile it had just added. Unique temp file names only kept the JSON from tearing. A render with something to write now creates session-usage-history.json.lock exclusively, reads the history again under it, writes, and removes the lock. A render that finds the lock held doesn't wait: it forecasts from what it read and leaves the write to its next render, which records the same percent with the same time, since a reading is dated by when its percent was seen. A lock more than 10 seconds old, or dated that far ahead, was left by a render that died holding it, and is taken over. Renders with nothing to write don't take the lock.
1 parent bded3b6 commit 87b3563

4 files changed

Lines changed: 201 additions & 30 deletions

File tree

‎docs/DEVELOPMENT.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ bun run docs
5757
- `~/.cache/ccstatusline/terminal-width.json` - per-session no-width probe results; detected numeric widths are not persisted by the renderer
5858
- `~/.cache/ccstatusline/usage.json` and `~/.cache/ccstatusline/usage.lock` - usage API data cache and fetch backoff lock
5959
- `~/.cache/ccstatusline/usage-credentials.lock` - 30-second backoff after a usage credential lookup finds no OAuth login, tagged with the profile it applies to
60+
- `~/.cache/ccstatusline/session-usage-history.json` and `~/.cache/ccstatusline/session-usage-history.json.lock` - 5-hour usage readings for Block Forecast and Block Limit Timer, per Claude config directory, and the lock a render holds while writing them
6061
- `~/.cache/ccstatusline/claude-status.json` and `~/.cache/ccstatusline/claude-status.lock` - Claude service-status cache and failed-fetch backoff lock
6162
- `~/.cache/ccstatusline/skills/skills-<sessionId>.jsonl` - skill hook records; session IDs must contain only ASCII letters, digits, `-`, or `_`
6263

‎src/utils/__tests__/session-forecast-prefetch.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ function makeDeps(initial?: unknown): SessionUsageHistoryDeps & { files: Map<str
4343
return content;
4444
},
4545
writeFileSync: (p: string, data: string) => { files.set(p, data); },
46+
createFileExclusiveSync: (p: string) => {
47+
if (files.has(p)) {
48+
throw new Error('EEXIST');
49+
}
50+
51+
files.set(p, '');
52+
},
4653
renameSync: (from: string, to: string) => {
4754
files.set(to, files.get(from) ?? '');
4855
files.delete(from);

‎src/utils/__tests__/session-usage-history.test.ts‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
import { getUsageFetchedAtMs } from '../usage';
2020

2121
const CACHE_PATH = '/cache/ccstatusline/session-usage-history.json';
22+
const LOCK_PATH = `${CACHE_PATH}.lock`;
2223
const MINUTE = 60 * 1000;
2324
const NOW = Date.UTC(2026, 9, 8, 13, 17);
2425
const RESET_AT = Date.UTC(2026, 9, 8, 15, 0);
@@ -59,6 +60,14 @@ function makeDeps(initial?: unknown): SessionUsageHistoryDeps & { files: Map<str
5960
files.set(p, data);
6061
mtimes.set(p, deps.now());
6162
},
63+
createFileExclusiveSync: (p: string) => {
64+
if (files.has(p)) {
65+
throw new Error('EEXIST');
66+
}
67+
68+
files.set(p, '');
69+
mtimes.set(p, deps.now());
70+
},
6271
renameSync: (from: string, to: string) => {
6372
const data = files.get(from);
6473
if (data === undefined) {
@@ -333,6 +342,84 @@ describe('recordSessionUsageReading', () => {
333342
expect(recordSessionUsageReading('/p', RESET_AT, -3, makeDeps())).toEqual([[NOW, NOW, 0]]);
334343
});
335344

345+
// Renders of every session and profile share the file, and one could
346+
// otherwise write back what it read before another's write landed
347+
it('reads the history again under its lock, keeping what another render wrote since', () => {
348+
const before = history({ '/work': [{ resetAt: RESET_AT, readings: [[NOW - 5 * MINUTE, NOW - 2 * MINUTE, 30]] }] });
349+
const written = history({ '/work': [{ resetAt: RESET_AT, readings: [[NOW - 5 * MINUTE, NOW - 2 * MINUTE, 30], [NOW, NOW, 31]] }] });
350+
const deps = makeDeps(before);
351+
const read = deps.readFileSync;
352+
deps.readFileSync = (p: string) => {
353+
const content = read(p);
354+
deps.files.set(CACHE_PATH, JSON.stringify(written));
355+
return content;
356+
};
357+
358+
expect(recordSessionUsageReading('/personal', RESET_AT, 42, deps)).toEqual([[NOW, NOW, 42]]);
359+
expect(stored(deps)).toEqual(history({
360+
'/work': [{ resetAt: RESET_AT, readings: [[NOW - 5 * MINUTE, NOW - 2 * MINUTE, 30], [NOW, NOW, 31]] }],
361+
'/personal': [{ resetAt: RESET_AT, readings: [[NOW, NOW, 42]] }]
362+
}));
363+
expect(deps.files.has(LOCK_PATH)).toBe(false);
364+
});
365+
366+
// A later render records the same percent with the same time, as it's
367+
// dated by when it was seen
368+
it('leaves the write to a later render while another holds the lock', () => {
369+
const deps = makeDeps();
370+
deps.files.set(LOCK_PATH, '');
371+
deps.mtimes.set(LOCK_PATH, NOW - 1000);
372+
deps.percentSeenAt = () => NOW - 10_000;
373+
374+
expect(recordSessionUsageReading('/p', RESET_AT, 42, deps)).toEqual([[NOW - 10_000, NOW - 10_000, 42]]);
375+
expect(deps.writes).toBe(0);
376+
expect(deps.files.has(LOCK_PATH)).toBe(true);
377+
378+
deps.files.delete(LOCK_PATH);
379+
deps.now = () => NOW + 5000;
380+
381+
expect(recordSessionUsageReading('/p', RESET_AT, 42, deps)).toEqual([[NOW - 10_000, NOW - 10_000, 42]]);
382+
expect(stored(deps)).toEqual(history({ '/p': [{ resetAt: RESET_AT, readings: [[NOW - 10_000, NOW - 10_000, 42]] }] }));
383+
});
384+
385+
it.each([
386+
['left by a render that died holding it', NOW - 11_000],
387+
['dated ahead by a clock since set back', NOW + 11_000]
388+
])('takes over a lock %s', (_label, lockedAtMs) => {
389+
const deps = makeDeps();
390+
deps.files.set(LOCK_PATH, '');
391+
deps.mtimes.set(LOCK_PATH, lockedAtMs);
392+
393+
recordSessionUsageReading('/p', RESET_AT, 42, deps);
394+
395+
expect(stored(deps)).toEqual(history({ '/p': [{ resetAt: RESET_AT, readings: [[NOW, NOW, 42]] }] }));
396+
expect(deps.files.has(LOCK_PATH)).toBe(false);
397+
});
398+
399+
it('leaves the write when a dead render\'s lock can\'t be removed', () => {
400+
const deps = makeDeps();
401+
deps.files.set(LOCK_PATH, '');
402+
deps.mtimes.set(LOCK_PATH, NOW - 11_000);
403+
deps.unlinkSync = () => {
404+
throw new Error('EPERM');
405+
};
406+
407+
expect(recordSessionUsageReading('/p', RESET_AT, 42, deps)).toEqual([[NOW, NOW, 42]]);
408+
expect(deps.writes).toBe(0);
409+
});
410+
411+
it('doesn\'t take the lock when there\'s nothing to write', () => {
412+
const deps = makeDeps(history({ '/p': [{ resetAt: RESET_AT, readings: [[NOW - 5 * MINUTE, NOW - 30_000, 42]] }] }));
413+
let locks = 0;
414+
deps.createFileExclusiveSync = () => {
415+
locks += 1;
416+
};
417+
418+
recordSessionUsageReading('/p', RESET_AT, 42, deps);
419+
420+
expect(locks).toBe(0);
421+
});
422+
336423
it('still returns the readings when the write fails', () => {
337424
const deps = makeDeps();
338425
deps.writeFileSync = () => {

‎src/utils/session-usage-history.ts‎

Lines changed: 106 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@ const LAST_SEEN_WRITE_INTERVAL_MS = 60 * 1000;
2727
// Another render's temp file this old has been left behind, not still being
2828
// written, so a write removes it
2929
const ORPHANED_TEMP_FILE_AGE_MS = 60 * 1000;
30+
// A render holds the history's lock for a few milliseconds; one this old (or
31+
// dated this far ahead, by a clock since set back) was left by a render that
32+
// died holding it.
33+
const STALE_LOCK_AGE_MS = 10 * 1000;
3034
// The model Claude Code names on the assistant messages it writes itself
3135
const SYNTHETIC_MODEL = '<synthetic>';
3236

@@ -43,6 +47,8 @@ interface SessionUsageHistory {
4347
export interface SessionUsageHistoryDeps {
4448
readFileSync: (path: string) => string;
4549
writeFileSync: (path: string, data: string) => void;
50+
// Creates an empty file, and fails when there is one already
51+
createFileExclusiveSync: (path: string) => void;
4652
renameSync: (from: string, to: string) => void;
4753
unlinkSync: (path: string) => void;
4854
readdirSync: (path: string) => string[];
@@ -101,6 +107,7 @@ export function getDefaultSessionUsageHistoryDeps(payload?: StatusJSON): Session
101107
return {
102108
readFileSync: (p: string) => fs.readFileSync(p, 'utf-8'),
103109
writeFileSync: (p: string, data: string) => { fs.writeFileSync(p, data, 'utf-8'); },
110+
createFileExclusiveSync: (p: string) => { fs.writeFileSync(p, '', { flag: 'wx' }); },
104111
renameSync: (from: string, to: string) => { fs.renameSync(from, to); },
105112
unlinkSync: (p: string) => { fs.unlinkSync(p); },
106113
readdirSync: (p: string) => fs.readdirSync(p),
@@ -227,23 +234,18 @@ function removeOrphanedTempFiles(deps: SessionUsageHistoryDeps, nowMs: number):
227234
}
228235
}
229236

230-
/**
231-
* Records the current session percent in this profile's 5-hour window and
232-
* returns the window's readings for the forecast. Best-effort: a failed write
233-
* still returns the readings, and nothing here throws.
234-
*/
235-
export function recordSessionUsageReading(
237+
// Adds the percent to this profile's window in history, which it changes in
238+
// place. Says whether anything changed, so needs writing.
239+
function addReading(
240+
history: SessionUsageHistory,
236241
profileKey: string,
237242
resetAtMs: number,
238243
percent: number,
239-
deps: SessionUsageHistoryDeps = getDefaultSessionUsageHistoryDeps()
240-
): SessionUsageReading[] {
241-
const nowMs = deps.now();
242-
const clampedPercent = Math.max(0, Math.min(100, percent));
243-
const seenAt = getSeenAtLookup(deps, nowMs);
244-
244+
nowMs: number,
245+
seenAt: () => number | undefined
246+
): { profiles: Record<string, SessionUsageWindow[]>; readings: SessionUsageReading[]; changed: boolean } {
245247
const profiles: Record<string, SessionUsageWindow[]> = {};
246-
for (const [key, windows] of Object.entries(readHistory(deps).profiles)) {
248+
for (const [key, windows] of Object.entries(history.profiles)) {
247249
const kept = pruneWindows(windows, nowMs);
248250
if (kept.length > 0) {
249251
profiles[key] = kept;
@@ -262,31 +264,70 @@ export function recordSessionUsageReading(
262264
const last = readings[readings.length - 1];
263265
// Usage never falls within a window: a lower percent is another session's
264266
// stale payload, and recording it would fake a steep climb later.
265-
if (last !== undefined && clampedPercent < last[2]) {
266-
return readings;
267+
if (last !== undefined && percent < last[2]) {
268+
return { profiles, readings, changed: false };
267269
}
268270

269-
if (last?.[2] !== clampedPercent) {
271+
if (last?.[2] !== percent) {
270272
// A new percent can't have been seen before the last one was
271273
const firstSeenMs = Math.max(seenAt() ?? nowMs, last?.[1] ?? Number.NEGATIVE_INFINITY);
272-
readings.push([firstSeenMs, firstSeenMs, clampedPercent]);
273-
} else if (nowMs - last[1] < LAST_SEEN_WRITE_INTERVAL_MS) {
274-
// Not even now is a minute past the last sighting, so there's no need
275-
// to look up when the percent was seen
276-
return readings;
277-
} else {
278-
// With no time for the percent, the reading's own last sighting stands
279-
const lastSeenMs = seenAt() ?? last[1];
280-
if (lastSeenMs - last[1] < LAST_SEEN_WRITE_INTERVAL_MS) {
281-
return readings;
274+
readings.push([firstSeenMs, firstSeenMs, percent]);
275+
return { profiles, readings, changed: true };
276+
}
277+
278+
// Not even now is a minute past the last sighting, so there's no need to
279+
// look up when the percent was seen
280+
if (nowMs - last[1] < LAST_SEEN_WRITE_INTERVAL_MS) {
281+
return { profiles, readings, changed: false };
282+
}
283+
284+
// With no time for the percent, the reading's own last sighting stands
285+
const lastSeenMs = seenAt() ?? last[1];
286+
if (lastSeenMs - last[1] < LAST_SEEN_WRITE_INTERVAL_MS) {
287+
return { profiles, readings, changed: false };
288+
}
289+
290+
last[1] = lastSeenMs;
291+
return { profiles, readings, changed: true };
292+
}
293+
294+
// Taken before a render reads the history to write it, so that two renders
295+
// can't each write over what the other added. Says whether this render holds
296+
// it now.
297+
function lockHistory(deps: SessionUsageHistoryDeps, nowMs: number): boolean {
298+
const lockPath = `${deps.cachePath}.lock`;
299+
try {
300+
deps.mkdirSync(path.dirname(deps.cachePath));
301+
deps.createFileExclusiveSync(lockPath);
302+
return true;
303+
} catch {
304+
// Held by another render, or left behind by one
305+
}
306+
307+
try {
308+
if (Math.abs(nowMs - deps.statSync(lockPath).mtimeMs) < STALE_LOCK_AGE_MS) {
309+
return false;
282310
}
283311

284-
last[1] = lastSeenMs;
312+
deps.unlinkSync(lockPath);
313+
deps.createFileExclusiveSync(lockPath);
314+
return true;
315+
} catch {
316+
return false;
317+
}
318+
}
319+
320+
function unlockHistory(deps: SessionUsageHistoryDeps): void {
321+
try {
322+
deps.unlinkSync(`${deps.cachePath}.lock`);
323+
} catch {
324+
// Gone already; nothing more to do.
285325
}
326+
}
286327

328+
function writeHistory(deps: SessionUsageHistoryDeps, profiles: Record<string, SessionUsageWindow[]>): void {
287329
const tempPath = `${deps.cachePath}.${process.pid}.tmp`;
288330
try {
289-
deps.mkdirSync(path.dirname(deps.cachePath));
290331
const history: SessionUsageHistory = { version: HISTORY_SCHEMA_VERSION, profiles };
291332
deps.writeFileSync(tempPath, JSON.stringify(history));
292333
deps.renameSync(tempPath, deps.cachePath);
@@ -300,8 +341,43 @@ export function recordSessionUsageReading(
300341
// Never written, or still held; nothing more to do.
301342
}
302343
}
344+
}
345+
346+
/**
347+
* Records the current session percent in this profile's 5-hour window and
348+
* returns the window's readings for the forecast. Best-effort: a failed write
349+
* still returns the readings, and nothing here throws.
350+
*
351+
* A render that finds another holding the history's lock doesn't wait for it:
352+
* it forecasts from what it read and leaves the write to a later render. That
353+
* one records the same percent with the same time, since a reading's time is
354+
* when its percent was seen rather than when it was written.
355+
*/
356+
export function recordSessionUsageReading(
357+
profileKey: string,
358+
resetAtMs: number,
359+
percent: number,
360+
deps: SessionUsageHistoryDeps = getDefaultSessionUsageHistoryDeps()
361+
): SessionUsageReading[] {
362+
const nowMs = deps.now();
363+
const clampedPercent = Math.max(0, Math.min(100, percent));
364+
const seenAt = getSeenAtLookup(deps, nowMs);
365+
366+
const unlocked = addReading(readHistory(deps), profileKey, resetAtMs, clampedPercent, nowMs, seenAt);
367+
if (!unlocked.changed || !lockHistory(deps, nowMs)) {
368+
return unlocked.readings;
369+
}
303370

304-
removeOrphanedTempFiles(deps, nowMs);
371+
try {
372+
// Read again under the lock, in case another render wrote since
373+
const locked = addReading(readHistory(deps), profileKey, resetAtMs, clampedPercent, nowMs, seenAt);
374+
if (locked.changed) {
375+
writeHistory(deps, locked.profiles);
376+
removeOrphanedTempFiles(deps, nowMs);
377+
}
305378

306-
return readings;
379+
return locked.readings;
380+
} finally {
381+
unlockHistory(deps);
382+
}
307383
}

0 commit comments

Comments
 (0)