pi-cache-optimizer 2.9.3 → 2.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -0
- package/README.zh-CN.md +18 -0
- package/index.ts +588 -107
- package/package.json +1 -1
- package/src/command-completion.ts +3 -2
- package/src/command.ts +2 -2
- package/src/config.ts +47 -3
- package/src/stats-archive.ts +220 -75
- package/src/stats-fs.ts +54 -0
- package/src/stats-refresh.ts +474 -0
- package/src/stats-store.ts +127 -20
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Incremental footer refresh (2.10): a tiered shard index and a
|
|
3
|
+
* single-flight refresh scheduler.
|
|
4
|
+
*
|
|
5
|
+
* Why: a footer refresh used to lstat every raw shard (about 400 on a busy
|
|
6
|
+
* day) and Pi awaited it on every tool call, message and settle. On Windows
|
|
7
|
+
* (antivirus-scanned AppData) that was ~28 ms per refresh on the critical
|
|
8
|
+
* path of the agent loop.
|
|
9
|
+
*
|
|
10
|
+
* TieredShardIndex
|
|
11
|
+
* - Every refresh lists the directory (creations and deletions are seen at
|
|
12
|
+
* once) and lstats only new names and the hot set: shards that are active,
|
|
13
|
+
* were updated within STATS_HOT_WINDOW_MS, are unreadable or not regular
|
|
14
|
+
* files, or were marked dirty (by the TUI watcher, or by a transient
|
|
15
|
+
* error). Content is re-read only when the file identity changed.
|
|
16
|
+
* - Since 2.8.20 only a live process rewrites a shard, and only its own.
|
|
17
|
+
* A closed shard is rewritten only when the same extension instance starts
|
|
18
|
+
* another session under the same id (Pi keeps the extension across
|
|
19
|
+
* /new, /resume and fork: session_shutdown closes the shard, session_start
|
|
20
|
+
* writes it active again). Usually that is within minutes, which the hot
|
|
21
|
+
* window covers; after a longer idle gap it is a cold shard changing, which
|
|
22
|
+
* the full scan below bounds. Cold (closed, older) shards are re-checked by a
|
|
23
|
+
* background full scan at most every STATS_FULL_SCAN_INTERVAL_MS while
|
|
24
|
+
* refreshes are requested, with at most STATS_FULL_SCAN_CONCURRENCY calls
|
|
25
|
+
* in flight. The staleness of a cold shard is bounded by that interval
|
|
26
|
+
* plus the scan time; hot shards and this process's own shard are never
|
|
27
|
+
* stale.
|
|
28
|
+
* - The output is the valid shards in readdir order, exactly what
|
|
29
|
+
* readValidStatsShardsV7 returns for the same listing and contents (minus
|
|
30
|
+
* this process's own name, which callers replace by their in-memory copy).
|
|
31
|
+
* Aggregation is a full in-memory re-aggregation of these cached inputs,
|
|
32
|
+
* so the result equals the reference aggregation by construction.
|
|
33
|
+
* - refresh() resolves only after every read of the shard phase completed,
|
|
34
|
+
* and returns a fresh array of shared, never-mutated shard objects: a
|
|
35
|
+
* snapshot that later index updates cannot change. Callers list the
|
|
36
|
+
* archive only afterwards (see readStatsSnapshot).
|
|
37
|
+
* - Compaction, cleanup and the kill switch keep using
|
|
38
|
+
* readValidStatsShardsV7 (stat every file); they never trust this index.
|
|
39
|
+
*
|
|
40
|
+
* StatsRefreshScheduler
|
|
41
|
+
* - At most one refresh runs; requests made meanwhile share one trailing
|
|
42
|
+
* run that starts after it, so a caller never gets a result read before
|
|
43
|
+
* its call. A run must not request a refresh itself (asserted: that would
|
|
44
|
+
* wait for the trailing run, which waits for the run).
|
|
45
|
+
* - Background requests are refused while the gate is closed (shutdown);
|
|
46
|
+
* drain() waits for everything in flight.
|
|
47
|
+
*/
|
|
48
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
49
|
+
import { join } from "node:path";
|
|
50
|
+
import { type Stats, watch } from "node:fs";
|
|
51
|
+
import { getErrorCode } from "./common.ts";
|
|
52
|
+
import { statsReadFs } from "./stats-fs.ts";
|
|
53
|
+
import {
|
|
54
|
+
type PersistedStatsShardV7,
|
|
55
|
+
type StatsFileIdentity,
|
|
56
|
+
SHARD_FILE_NAME_PATTERN,
|
|
57
|
+
SHARD_IO_CONCURRENCY,
|
|
58
|
+
applyShardStatHook,
|
|
59
|
+
mapWithConcurrency,
|
|
60
|
+
parseShardFileText,
|
|
61
|
+
sameStatsFileIdentity,
|
|
62
|
+
statsFileIdentityOf,
|
|
63
|
+
} from "./stats-store.ts";
|
|
64
|
+
|
|
65
|
+
/** A shard updated this recently (by its lifecycle.updatedAt) is stat-ed on every refresh. */
|
|
66
|
+
export const STATS_HOT_WINDOW_MS = 15 * 60 * 1000;
|
|
67
|
+
/** Cold shards are re-checked by a background full scan at most this often (while refreshes are requested). */
|
|
68
|
+
export const STATS_FULL_SCAN_INTERVAL_MS = 30 * 1000;
|
|
69
|
+
/** Calls a background full scan keeps in flight (libuv has 4 threads; leave room for Pi's own I/O). */
|
|
70
|
+
export const STATS_FULL_SCAN_CONCURRENCY = 2;
|
|
71
|
+
|
|
72
|
+
type IndexEntry = {
|
|
73
|
+
/** Undefined for a name that is not a regular file. */
|
|
74
|
+
identity?: StatsFileIdentity;
|
|
75
|
+
/** Valid shard whose instanceId matches the file name. */
|
|
76
|
+
shard?: PersistedStatsShardV7;
|
|
77
|
+
/** Schema-valid parse regardless of the name. */
|
|
78
|
+
parsed?: PersistedStatsShardV7;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
export type ShardIndexRefreshStats = {
|
|
82
|
+
names: number;
|
|
83
|
+
/** Names lstat-ed in the foreground. */
|
|
84
|
+
statted: number;
|
|
85
|
+
/** Files read and parsed in the foreground. */
|
|
86
|
+
read: number;
|
|
87
|
+
/** Hot names among the statted ones (excluding new names). */
|
|
88
|
+
hot: number;
|
|
89
|
+
full: boolean;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export type ShardIndexOptions = {
|
|
93
|
+
hotWindowMs?: number;
|
|
94
|
+
fullScanIntervalMs?: number;
|
|
95
|
+
fullScanConcurrency?: number;
|
|
96
|
+
/** Monotonic clock (ms) for scan scheduling. */
|
|
97
|
+
monotonicNow?: () => number;
|
|
98
|
+
/** Wall clock (ms) compared with lifecycle.updatedAt. */
|
|
99
|
+
wallNow?: () => number;
|
|
100
|
+
/** Deep-freeze cached shards (tests: any mutation throws). */
|
|
101
|
+
freeze?: boolean;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
function deepFreeze<T>(value: T): T {
|
|
105
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
106
|
+
Object.freeze(value);
|
|
107
|
+
for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child);
|
|
108
|
+
}
|
|
109
|
+
return value;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
type ReadOutcome = "unchanged" | "read" | "removed" | "transient";
|
|
113
|
+
|
|
114
|
+
export class TieredShardIndex {
|
|
115
|
+
private readonly entries = new Map<string, IndexEntry>();
|
|
116
|
+
private readonly dirty = new Set<string>();
|
|
117
|
+
private lastFullScanAt = -Infinity;
|
|
118
|
+
private scan?: Promise<boolean>;
|
|
119
|
+
private readonly hotWindowMs: number;
|
|
120
|
+
private readonly fullScanIntervalMs: number;
|
|
121
|
+
private readonly fullScanConcurrency: number;
|
|
122
|
+
private readonly monotonicNow: () => number;
|
|
123
|
+
private readonly wallNow: () => number;
|
|
124
|
+
private readonly freeze: boolean;
|
|
125
|
+
/** Last foreground refresh's counters (timing logs and tests). */
|
|
126
|
+
lastRefresh?: ShardIndexRefreshStats;
|
|
127
|
+
|
|
128
|
+
constructor(readonly directory: string, options: ShardIndexOptions = {}) {
|
|
129
|
+
this.hotWindowMs = options.hotWindowMs ?? STATS_HOT_WINDOW_MS;
|
|
130
|
+
this.fullScanIntervalMs = options.fullScanIntervalMs ?? STATS_FULL_SCAN_INTERVAL_MS;
|
|
131
|
+
this.fullScanConcurrency = options.fullScanConcurrency ?? STATS_FULL_SCAN_CONCURRENCY;
|
|
132
|
+
this.monotonicNow = options.monotonicNow ?? (() => performance.now());
|
|
133
|
+
this.wallNow = options.wallNow ?? (() => Date.now());
|
|
134
|
+
this.freeze = options.freeze ?? false;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** A watcher saw `name` change: stat it on the next refresh. */
|
|
138
|
+
markDirty(name: string): void {
|
|
139
|
+
if (SHARD_FILE_NAME_PATTERN.test(name)) this.dirty.add(name);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** A watcher lost events (no file name, overflow, error): the next refresh starts a full scan. */
|
|
143
|
+
requestFullScan(): void {
|
|
144
|
+
this.lastFullScanAt = -Infinity;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
get fullScanInFlight(): boolean {
|
|
148
|
+
return this.scan !== undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Resolves when the background scan in flight (if any) finished. */
|
|
152
|
+
async settled(): Promise<void> {
|
|
153
|
+
while (this.scan) await this.scan.catch(() => false);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
private isHot(entry: IndexEntry, now: number): boolean {
|
|
157
|
+
const shard = entry.parsed;
|
|
158
|
+
if (!shard || !entry.identity) return true;
|
|
159
|
+
return shard.lifecycle.state === "active" || now - shard.lifecycle.updatedAt < this.hotWindowMs;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
private async listNames(): Promise<string[]> {
|
|
163
|
+
try {
|
|
164
|
+
return await statsReadFs().readdir(this.directory);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (getErrorCode(error) === "ENOENT") return [];
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* lstat `name` (and read it if its identity changed). `expected` guards a
|
|
173
|
+
* background scan: its result is applied only while the entry is still
|
|
174
|
+
* the one it started from, so a slow scan never replaces content a newer
|
|
175
|
+
* foreground read stored.
|
|
176
|
+
*/
|
|
177
|
+
private async statAndRead(name: string, background: boolean): Promise<ReadOutcome> {
|
|
178
|
+
const path = join(this.directory, name);
|
|
179
|
+
const expected = this.entries.get(name);
|
|
180
|
+
const stale = () => background && this.entries.get(name) !== expected;
|
|
181
|
+
let info: Stats;
|
|
182
|
+
try {
|
|
183
|
+
info = applyShardStatHook(path, await statsReadFs().lstat(path));
|
|
184
|
+
} catch (error) {
|
|
185
|
+
if (stale()) return "unchanged";
|
|
186
|
+
if (getErrorCode(error) === "ENOENT") {
|
|
187
|
+
this.entries.delete(name);
|
|
188
|
+
this.dirty.delete(name);
|
|
189
|
+
return "removed";
|
|
190
|
+
}
|
|
191
|
+
// Transient (Windows EPERM/EBUSY): keep the last known content and retry next refresh.
|
|
192
|
+
this.dirty.add(name);
|
|
193
|
+
return "transient";
|
|
194
|
+
}
|
|
195
|
+
if (stale()) return "unchanged";
|
|
196
|
+
if (!info.isFile() || info.isSymbolicLink()) {
|
|
197
|
+
this.dirty.delete(name);
|
|
198
|
+
// Already known as not a regular file: unchanged (a full scan must not
|
|
199
|
+
// report a change, and trigger another refresh, every time).
|
|
200
|
+
if (expected && !expected.identity) return "unchanged";
|
|
201
|
+
this.entries.set(name, {});
|
|
202
|
+
return "read";
|
|
203
|
+
}
|
|
204
|
+
if (expected?.identity && sameStatsFileIdentity(expected.identity, info)) {
|
|
205
|
+
this.dirty.delete(name);
|
|
206
|
+
return "unchanged";
|
|
207
|
+
}
|
|
208
|
+
let text: string;
|
|
209
|
+
try {
|
|
210
|
+
text = (await statsReadFs().readFile(path)).toString("utf8");
|
|
211
|
+
} catch (error) {
|
|
212
|
+
if (stale()) return "unchanged";
|
|
213
|
+
if (getErrorCode(error) === "ENOENT") {
|
|
214
|
+
this.entries.delete(name);
|
|
215
|
+
this.dirty.delete(name);
|
|
216
|
+
return "removed";
|
|
217
|
+
}
|
|
218
|
+
this.dirty.add(name);
|
|
219
|
+
return "transient";
|
|
220
|
+
}
|
|
221
|
+
if (stale()) return "unchanged";
|
|
222
|
+
let parsed: { shard?: PersistedStatsShardV7; parsed?: PersistedStatsShardV7 };
|
|
223
|
+
try {
|
|
224
|
+
parsed = parseShardFileText(name, text);
|
|
225
|
+
} catch {
|
|
226
|
+
parsed = {};
|
|
227
|
+
}
|
|
228
|
+
if (this.freeze) deepFreeze(parsed.parsed);
|
|
229
|
+
this.entries.set(name, { identity: statsFileIdentityOf(info), shard: parsed.shard, parsed: parsed.parsed });
|
|
230
|
+
this.dirty.delete(name);
|
|
231
|
+
return "read";
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* The shard phase of a refresh. `own` (this process's shard file name) is
|
|
236
|
+
* never stat-ed or read: callers use their in-memory copy. With `full`,
|
|
237
|
+
* every name is stat-ed (what readValidStatsShardsV7 does): commands,
|
|
238
|
+
* flush and restore use it. Resolves only after every read finished.
|
|
239
|
+
*/
|
|
240
|
+
async refresh({ own, full = false }: { own?: string; full?: boolean } = {}): Promise<PersistedStatsShardV7[]> {
|
|
241
|
+
const names = await this.listNames();
|
|
242
|
+
const candidates = names.filter((name) => SHARD_FILE_NAME_PATTERN.test(name) && name !== own);
|
|
243
|
+
const now = this.wallNow();
|
|
244
|
+
let hot = 0;
|
|
245
|
+
const toStat = full ? candidates : candidates.filter((name) => {
|
|
246
|
+
const entry = this.entries.get(name);
|
|
247
|
+
if (!entry || this.dirty.has(name)) return true;
|
|
248
|
+
if (!this.isHot(entry, now)) return false;
|
|
249
|
+
hot++;
|
|
250
|
+
return true;
|
|
251
|
+
});
|
|
252
|
+
let read = 0;
|
|
253
|
+
await mapWithConcurrency(toStat, SHARD_IO_CONCURRENCY, async (name) => {
|
|
254
|
+
if ((await this.statAndRead(name, false)) === "read") read++;
|
|
255
|
+
});
|
|
256
|
+
if (full) this.lastFullScanAt = this.monotonicNow();
|
|
257
|
+
const listed = new Set(candidates);
|
|
258
|
+
for (const name of Array.from(this.entries.keys())) if (!listed.has(name)) this.entries.delete(name);
|
|
259
|
+
for (const name of Array.from(this.dirty)) if (!listed.has(name)) this.dirty.delete(name);
|
|
260
|
+
const shards: PersistedStatsShardV7[] = [];
|
|
261
|
+
for (const name of candidates) {
|
|
262
|
+
const shard = this.entries.get(name)?.shard;
|
|
263
|
+
if (shard) shards.push(shard);
|
|
264
|
+
}
|
|
265
|
+
this.lastRefresh = { names: candidates.length, statted: toStat.length, read, hot, full };
|
|
266
|
+
return this.freeze ? Object.freeze(shards) as PersistedStatsShardV7[] : shards;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Whether a background full scan is due now. */
|
|
270
|
+
fullScanDue(): boolean {
|
|
271
|
+
return this.scan === undefined && this.monotonicNow() - this.lastFullScanAt >= this.fullScanIntervalMs;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Start a background full scan when one is due. Resolves to true when it
|
|
276
|
+
* found a change (callers then refresh again). Never rejects.
|
|
277
|
+
*/
|
|
278
|
+
maybeStartFullScan(own: () => string | undefined): Promise<boolean> | undefined {
|
|
279
|
+
if (!this.fullScanDue()) return undefined;
|
|
280
|
+
this.lastFullScanAt = this.monotonicNow();
|
|
281
|
+
const scan = (async (): Promise<boolean> => {
|
|
282
|
+
const names = await this.listNames();
|
|
283
|
+
const ownName = own();
|
|
284
|
+
const candidates = names.filter((name) => SHARD_FILE_NAME_PATTERN.test(name) && name !== ownName);
|
|
285
|
+
let changed = false;
|
|
286
|
+
await mapWithConcurrency(candidates, this.fullScanConcurrency, async (name) => {
|
|
287
|
+
const outcome = await this.statAndRead(name, true);
|
|
288
|
+
if (outcome === "read" || outcome === "removed") changed = true;
|
|
289
|
+
});
|
|
290
|
+
this.lastFullScanAt = this.monotonicNow();
|
|
291
|
+
return changed;
|
|
292
|
+
})().catch(() => false).finally(() => {
|
|
293
|
+
if (this.scan === scan) this.scan = undefined;
|
|
294
|
+
});
|
|
295
|
+
this.scan = scan;
|
|
296
|
+
return scan;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Opt-in field check of the identity cache (PI_CACHE_OPTIMIZER_STATS_VERIFY):
|
|
301
|
+
* re-read every cached shard whose identity, lstat-ed before and after the
|
|
302
|
+
* read, still equals the cached one, and compare the contents. A
|
|
303
|
+
* difference means the filesystem reports an unchanged identity for
|
|
304
|
+
* changed content (no inode and coarse timestamps: FAT, some SMB servers),
|
|
305
|
+
* which no amount of stat-ing would notice. Files that changed or failed
|
|
306
|
+
* meanwhile are skipped (no verdict), so a racing writer never counts.
|
|
307
|
+
* A mismatched entry keeps its content for output but loses its identity,
|
|
308
|
+
* so the next refresh reads it again. Returns the mismatched names.
|
|
309
|
+
*/
|
|
310
|
+
async verifyCachedContents(own?: string): Promise<string[]> {
|
|
311
|
+
const names = (await this.listNames()).filter((name) => SHARD_FILE_NAME_PATTERN.test(name) && name !== own);
|
|
312
|
+
const mismatched: string[] = [];
|
|
313
|
+
await mapWithConcurrency(names, this.fullScanConcurrency, async (name) => {
|
|
314
|
+
const entry = this.entries.get(name);
|
|
315
|
+
if (!entry?.identity) return;
|
|
316
|
+
const path = join(this.directory, name);
|
|
317
|
+
try {
|
|
318
|
+
if (!sameStatsFileIdentity(entry.identity, applyShardStatHook(path, await statsReadFs().lstat(path)))) return;
|
|
319
|
+
const text = (await statsReadFs().readFile(path)).toString("utf8");
|
|
320
|
+
if (!sameStatsFileIdentity(entry.identity, applyShardStatHook(path, await statsReadFs().lstat(path)))) return;
|
|
321
|
+
if (this.entries.get(name) !== entry) return;
|
|
322
|
+
let parsed: PersistedStatsShardV7 | undefined;
|
|
323
|
+
try {
|
|
324
|
+
parsed = parseShardFileText(name, text).parsed;
|
|
325
|
+
} catch {
|
|
326
|
+
parsed = undefined;
|
|
327
|
+
}
|
|
328
|
+
if (JSON.stringify(parsed) === JSON.stringify(entry.parsed)) return;
|
|
329
|
+
mismatched.push(name);
|
|
330
|
+
this.entries.set(name, { shard: entry.shard, parsed: entry.parsed });
|
|
331
|
+
} catch {
|
|
332
|
+
// Gone or transiently unreadable: not a verdict.
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
return mismatched;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Test helper: the cached entry names. */
|
|
339
|
+
cachedNames(): string[] {
|
|
340
|
+
return Array.from(this.entries.keys());
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export class ReentrantStatsRefreshError extends Error {
|
|
345
|
+
constructor() {
|
|
346
|
+
super("a stats refresh requested another refresh from inside its own run (it would wait for itself)");
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Single-flight refresh with one trailing run, a shutdown gate and drain. */
|
|
351
|
+
export class StatsRefreshScheduler<T> {
|
|
352
|
+
private running?: Promise<T>;
|
|
353
|
+
private trailing?: { promise: Promise<T>; full: boolean; resolve: (value: T) => void; reject: (error: unknown) => void };
|
|
354
|
+
private closed = false;
|
|
355
|
+
private readonly context = new AsyncLocalStorage<object>();
|
|
356
|
+
private readonly token = {};
|
|
357
|
+
|
|
358
|
+
constructor(private readonly run: (full: boolean) => Promise<T>) {}
|
|
359
|
+
|
|
360
|
+
/** True while called from inside a run (directly or from work it started). */
|
|
361
|
+
insideRun(): boolean {
|
|
362
|
+
return this.context.getStore() === this.token;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Run `work` outside the run's async context (for background work a run starts). */
|
|
366
|
+
outsideRun<R>(work: () => R): R {
|
|
367
|
+
return this.context.exit(work);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* A refresh whose reads all start after this call. Runs now when idle;
|
|
372
|
+
* otherwise joins the single trailing run (`full` if any joiner asked).
|
|
373
|
+
*/
|
|
374
|
+
request(full = false): Promise<T> {
|
|
375
|
+
if (this.insideRun()) return Promise.reject(new ReentrantStatsRefreshError());
|
|
376
|
+
if (!this.running) return this.start(full);
|
|
377
|
+
if (this.trailing) {
|
|
378
|
+
this.trailing.full ||= full;
|
|
379
|
+
return this.trailing.promise;
|
|
380
|
+
}
|
|
381
|
+
let resolve!: (value: T) => void;
|
|
382
|
+
let reject!: (error: unknown) => void;
|
|
383
|
+
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
|
|
384
|
+
this.trailing = { promise, full, resolve, reject };
|
|
385
|
+
return promise;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** request() unless the gate is closed (then resolves undefined without refreshing). */
|
|
389
|
+
background(full = false): Promise<T | undefined> {
|
|
390
|
+
return this.closed ? Promise.resolve(undefined) : this.request(full);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private start(full: boolean): Promise<T> {
|
|
394
|
+
const run = this.context.run(this.token, () => this.run(full));
|
|
395
|
+
this.running = run;
|
|
396
|
+
const settle = () => {
|
|
397
|
+
if (this.running === run) this.running = undefined;
|
|
398
|
+
const next = this.trailing;
|
|
399
|
+
this.trailing = undefined;
|
|
400
|
+
if (next) this.start(next.full).then(next.resolve, next.reject);
|
|
401
|
+
};
|
|
402
|
+
run.then(settle, settle);
|
|
403
|
+
return run;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
get isClosed(): boolean {
|
|
407
|
+
return this.closed;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
get idle(): boolean {
|
|
411
|
+
return !this.running && !this.trailing;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
close(): void {
|
|
415
|
+
this.closed = true;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
open(): void {
|
|
419
|
+
this.closed = false;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Wait until no run is in flight or queued (errors are the callers' to handle). */
|
|
423
|
+
async drain(): Promise<void> {
|
|
424
|
+
while (this.running || this.trailing) {
|
|
425
|
+
await (this.trailing?.promise ?? this.running)!.then(() => undefined, () => undefined);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** What a shard directory watcher must provide (the real one wraps fs.watch). */
|
|
431
|
+
export type StatsWatchHandle = { close(): void };
|
|
432
|
+
export type StatsWatchFactory = (
|
|
433
|
+
directory: string,
|
|
434
|
+
onName: (name: string | null) => void,
|
|
435
|
+
onError: (error: unknown) => void,
|
|
436
|
+
) => StatsWatchHandle;
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* The real watcher: fs.watch with an 'error' listener (without one, the
|
|
440
|
+
* EventEmitter throws the error; on Windows deleting the watched directory
|
|
441
|
+
* emits EPERM, which crashed Pi through its uncaughtException handler).
|
|
442
|
+
* unref'd: it never keeps the process alive.
|
|
443
|
+
*/
|
|
444
|
+
export const createFsShardWatch: StatsWatchFactory = (directory, onName, onError) => {
|
|
445
|
+
const watcher = watch(directory, (_type, filename) => onName(filename == null ? null : String(filename)));
|
|
446
|
+
watcher.on("error", onError);
|
|
447
|
+
watcher.unref?.();
|
|
448
|
+
return watcher;
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
/** Test hooks for the incremental refresh; production never sets them. */
|
|
452
|
+
export type StatsRefreshTestHooks = {
|
|
453
|
+
/** Replaces fs.watch for the TUI shard watcher (a fake that tests drive). */
|
|
454
|
+
watch?: StatsWatchFactory;
|
|
455
|
+
/** Deep-freeze every shard the index caches (any mutation then throws). */
|
|
456
|
+
freezeShards?: boolean;
|
|
457
|
+
/** Overrides the full scan interval of indexes created afterwards. */
|
|
458
|
+
fullScanIntervalMs?: number;
|
|
459
|
+
/** Runs inside every refresh after the shard phase, before the archive is listed. */
|
|
460
|
+
afterShardPhase?: () => void | Promise<void>;
|
|
461
|
+
/** Runs inside every refresh after the snapshot, before the epochs are read. */
|
|
462
|
+
beforeEpochRead?: () => void | Promise<void>;
|
|
463
|
+
/** Runs inside every refresh after the epochs were read, right before the synchronous commit. */
|
|
464
|
+
beforeCommit?: () => void | Promise<void>;
|
|
465
|
+
/** Receives every committed (current-day) aggregate, synchronously. */
|
|
466
|
+
afterCommit?: (aggregate: import("./stats-store.ts").ShardAggregate) => void;
|
|
467
|
+
};
|
|
468
|
+
let statsRefreshTestHooks: StatsRefreshTestHooks = {};
|
|
469
|
+
export function setStatsRefreshTestHooks(hooks: StatsRefreshTestHooks | undefined): void {
|
|
470
|
+
statsRefreshTestHooks = hooks ?? {};
|
|
471
|
+
}
|
|
472
|
+
export function getStatsRefreshTestHooks(): StatsRefreshTestHooks {
|
|
473
|
+
return statsRefreshTestHooks;
|
|
474
|
+
}
|
package/src/stats-store.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { lstat, mkdir, readFile, readdir, rename, rm, stat, unlink, utimes, writ
|
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { LOG_PREFIX, asRecord, getErrorCode, getNonNegativeNumber, isNonEmptyString, isProcessAlive } from "./common.ts";
|
|
5
5
|
import { STATE_DIR } from "./paths.ts";
|
|
6
|
+
import { statsReadFs } from "./stats-fs.ts";
|
|
6
7
|
|
|
7
8
|
export type CacheProviderId = "deepseek" | "openai" | "claude" | "gemini";
|
|
8
9
|
|
|
@@ -226,14 +227,56 @@ export function parseEpochRecord(value: unknown): string | undefined {
|
|
|
226
227
|
return record?.version === 1 && isNonEmptyString(record.epoch) ? record.epoch.trim() : undefined;
|
|
227
228
|
}
|
|
228
229
|
|
|
229
|
-
|
|
230
|
+
/** Outcome of a footer epoch read: an epoch, or an I/O error the caller must not mistake for "no reset". */
|
|
231
|
+
export type EpochReadResult = { ok: true; epoch: string } | { ok: false; error: unknown };
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Footer (non-strict) epoch read. A missing file means no reset ever
|
|
235
|
+
* happened (the fallback); so does a file that is not a valid epoch record,
|
|
236
|
+
* which every reader since 2.8.20 treats the same way, so processes of
|
|
237
|
+
* different versions keep agreeing. Any other read failure (a Windows
|
|
238
|
+
* EPERM/EBUSY while a reset renames the file or a scanner holds it) is
|
|
239
|
+
* reported as an error: before 2.10 it fell back to the initial epoch, and a
|
|
240
|
+
* refresh then "adopted" that epoch and wiped this process's unsaved usage.
|
|
241
|
+
*/
|
|
242
|
+
export async function readEpochFileResult(path: string, fallback: string): Promise<EpochReadResult> {
|
|
243
|
+
let text: string;
|
|
230
244
|
try {
|
|
231
|
-
|
|
245
|
+
text = (await statsReadFs().readFile(path)).toString("utf8");
|
|
246
|
+
} catch (error) {
|
|
247
|
+
if (getErrorCode(error) === "ENOENT") return { ok: true, epoch: fallback };
|
|
248
|
+
return { ok: false, error };
|
|
249
|
+
}
|
|
250
|
+
try {
|
|
251
|
+
return { ok: true, epoch: parseEpochRecord(JSON.parse(text)) ?? fallback };
|
|
232
252
|
} catch {
|
|
233
|
-
return fallback;
|
|
253
|
+
return { ok: true, epoch: fallback };
|
|
234
254
|
}
|
|
235
255
|
}
|
|
236
256
|
|
|
257
|
+
const EPOCH_TRANSIENT_CODES = new Set(["EPERM", "EBUSY", "EACCES", "EAGAIN"]);
|
|
258
|
+
const EPOCH_RETRY_DELAYS_MS = [15, 60];
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* readEpochFileResult, retrying a transient Windows error briefly. The
|
|
262
|
+
* delay is deliberately not unref'd (see renameWithRetry): awaited reads
|
|
263
|
+
* must not let print mode exit mid-handler.
|
|
264
|
+
*/
|
|
265
|
+
export async function readEpochFileWithRetry(path: string, fallback: string): Promise<EpochReadResult> {
|
|
266
|
+
for (let attempt = 0; ; attempt++) {
|
|
267
|
+
const result = await readEpochFileResult(path, fallback);
|
|
268
|
+
if (result.ok || attempt >= EPOCH_RETRY_DELAYS_MS.length || !EPOCH_TRANSIENT_CODES.has(getErrorCode(result.error) ?? "")) return result;
|
|
269
|
+
await new Promise<void>((resolve) => setTimeout(resolve, EPOCH_RETRY_DELAYS_MS[attempt]));
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** readEpochFileResult that throws on an I/O error (callers keep their current epoch). */
|
|
274
|
+
export async function readEpochFile(path: string, fallback: string): Promise<string> {
|
|
275
|
+
const result = await readEpochFileResult(path, fallback);
|
|
276
|
+
if (result.ok) return result.epoch;
|
|
277
|
+
throw result.error;
|
|
278
|
+
}
|
|
279
|
+
|
|
237
280
|
/**
|
|
238
281
|
* Like readEpochFile, but only a missing file maps to the fallback. Any other
|
|
239
282
|
* read or parse failure throws, so destructive maintenance (archive
|
|
@@ -492,6 +535,25 @@ function cloneShard(shard: PersistedStatsShardV7): PersistedStatsShardV7 {
|
|
|
492
535
|
return structuredClone(shard);
|
|
493
536
|
}
|
|
494
537
|
|
|
538
|
+
/** File names the shard directory holds shards under (every version since 2.8.20). */
|
|
539
|
+
export const SHARD_FILE_NAME_PATTERN = /^[0-9a-f-]+\.json$/i;
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Parse one shard file's text the way readShardFileCached does: `parsed` is
|
|
543
|
+
* the schema-valid shard, `shard` the same only when its instanceId matches
|
|
544
|
+
* the file name. Throws SyntaxError on malformed JSON.
|
|
545
|
+
*/
|
|
546
|
+
export function parseShardFileText(name: string, text: string): { shard: PersistedStatsShardV7 | undefined; parsed: PersistedStatsShardV7 | undefined } {
|
|
547
|
+
const filenameInstanceId = name.slice(0, -".json".length);
|
|
548
|
+
const parsed = parsePersistedStatsShardV7(JSON.parse(text));
|
|
549
|
+
return { parsed, shard: parsed && parsed.instanceId === filenameInstanceId ? parsed : undefined };
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** The test hook view of a shard lstat (production: the stats unchanged). */
|
|
553
|
+
export function applyShardStatHook(path: string, info: import("node:fs").Stats): import("node:fs").Stats {
|
|
554
|
+
return statsFsTestHooks.shardStat ? statsFsTestHooks.shardStat(path, info) : info;
|
|
555
|
+
}
|
|
556
|
+
|
|
495
557
|
export async function readValidStatsShardsV7(directory: string = SHARD_FILES_DIR): Promise<PersistedStatsShardV7[]> {
|
|
496
558
|
let names: string[];
|
|
497
559
|
try {
|
|
@@ -562,10 +624,31 @@ export type ShardAggregator = {
|
|
|
562
624
|
finish(): ShardAggregate;
|
|
563
625
|
};
|
|
564
626
|
|
|
565
|
-
/**
|
|
566
|
-
export
|
|
567
|
-
|
|
568
|
-
|
|
627
|
+
/** One consistent set of epochs (global plus every model key an aggregation meets), read before aggregating. */
|
|
628
|
+
export type ShardEpochs = {
|
|
629
|
+
readonly globalEpoch: string;
|
|
630
|
+
/** Must cover every model key the aggregation meets (throws otherwise: a missing prefetch is a bug). */
|
|
631
|
+
modelEpoch(key: string): string;
|
|
632
|
+
};
|
|
633
|
+
|
|
634
|
+
/** Synchronous form of the aggregator, over epochs read beforehand: no await between the first add and finish. */
|
|
635
|
+
export type SyncShardAggregator = {
|
|
636
|
+
readonly day: string | null;
|
|
637
|
+
readonly globalEpoch: string;
|
|
638
|
+
add(shard: PersistedStatsShardV7): void;
|
|
639
|
+
addContribution(contribution: ShardContribution): void;
|
|
640
|
+
finish(): ShardAggregate;
|
|
641
|
+
};
|
|
642
|
+
|
|
643
|
+
/** Model keys `add(shard)` would look up an epoch for (none when the shard is filtered out up front). */
|
|
644
|
+
export function shardEpochKeys(shard: PersistedStatsShardV7, day: string | null, globalEpoch: string): string[] {
|
|
645
|
+
if ((day !== null && shard.day !== day) || shard.globalEpoch !== globalEpoch) return [];
|
|
646
|
+
return Object.keys(shard.models);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** The aggregation itself (aggregateStatsShardsV7's semantics), over pre-read epochs. */
|
|
650
|
+
export function createShardAggregatorSync(day: string | null, epochs: ShardEpochs): SyncShardAggregator {
|
|
651
|
+
const globalEpoch = epochs.globalEpoch;
|
|
569
652
|
const result: ShardAggregate = {
|
|
570
653
|
bySession: {},
|
|
571
654
|
totalsByModel: {},
|
|
@@ -579,29 +662,20 @@ export async function createShardAggregatorV7(day: string | null = currentLocalD
|
|
|
579
662
|
const routedUpdatedAt = new Map<string, number>();
|
|
580
663
|
const modelRefUpdatedAt = new Map<string, number>();
|
|
581
664
|
const modelSessions = new Map<string, Set<string>>();
|
|
582
|
-
const modelEpoch = async (key: string): Promise<string> => {
|
|
583
|
-
let epoch = modelEpochs.get(key);
|
|
584
|
-
if (!epoch) {
|
|
585
|
-
epoch = await readModelStatsEpoch(key);
|
|
586
|
-
modelEpochs.set(key, epoch);
|
|
587
|
-
}
|
|
588
|
-
return epoch;
|
|
589
|
-
};
|
|
590
665
|
|
|
591
666
|
return {
|
|
592
667
|
day,
|
|
593
668
|
globalEpoch,
|
|
594
|
-
|
|
595
|
-
async add(shard) {
|
|
669
|
+
add(shard) {
|
|
596
670
|
if ((day !== null && shard.day !== day) || shard.globalEpoch !== globalEpoch) return;
|
|
597
671
|
let contributed = false;
|
|
598
672
|
if (shard.lastRoutedModel && (routedUpdatedAt.get(shard.sessionHash) ?? -1) < shard.lifecycle.updatedAt) {
|
|
599
673
|
routedUpdatedAt.set(shard.sessionHash, shard.lifecycle.updatedAt);
|
|
600
|
-
|
|
674
|
+
// A copy: shards are shared, read-only cache entries (no per-refresh clone).
|
|
675
|
+
result.lastRoutedModelBySession[shard.sessionHash] = { ...shard.lastRoutedModel };
|
|
601
676
|
}
|
|
602
677
|
for (const [key, entry] of Object.entries(shard.models)) {
|
|
603
|
-
|
|
604
|
-
if (entry.modelEpoch !== epoch || (day !== null && entry.stats.day !== day)) continue;
|
|
678
|
+
if (entry.modelEpoch !== epochs.modelEpoch(key) || (day !== null && entry.stats.day !== day)) continue;
|
|
605
679
|
contributed = true;
|
|
606
680
|
const sessionModels = result.bySession[shard.sessionHash] ??= {};
|
|
607
681
|
sessionModels[key] = mergeStatsAcrossDays(sessionModels[key], entry.stats, day);
|
|
@@ -665,6 +739,39 @@ export async function createShardAggregatorV7(day: string | null = currentLocalD
|
|
|
665
739
|
};
|
|
666
740
|
}
|
|
667
741
|
|
|
742
|
+
/** Incremental form of aggregateStatsShardsV7: add shards (and pre-reduced contributions) in order, then finish. */
|
|
743
|
+
export async function createShardAggregatorV7(day: string | null = currentLocalDay()): Promise<ShardAggregator> {
|
|
744
|
+
const globalEpoch = await readGlobalStatsEpoch();
|
|
745
|
+
const modelEpochs = new Map<string, string>();
|
|
746
|
+
const modelEpoch = async (key: string): Promise<string> => {
|
|
747
|
+
let epoch = modelEpochs.get(key);
|
|
748
|
+
if (!epoch) {
|
|
749
|
+
epoch = await readModelStatsEpoch(key);
|
|
750
|
+
modelEpochs.set(key, epoch);
|
|
751
|
+
}
|
|
752
|
+
return epoch;
|
|
753
|
+
};
|
|
754
|
+
const core = createShardAggregatorSync(day, {
|
|
755
|
+
globalEpoch,
|
|
756
|
+
modelEpoch: (key) => {
|
|
757
|
+
const epoch = modelEpochs.get(key);
|
|
758
|
+
if (epoch === undefined) throw new Error(`model epoch of ${key} was not read before aggregating`);
|
|
759
|
+
return epoch;
|
|
760
|
+
},
|
|
761
|
+
});
|
|
762
|
+
return {
|
|
763
|
+
day,
|
|
764
|
+
globalEpoch,
|
|
765
|
+
modelEpoch,
|
|
766
|
+
async add(shard) {
|
|
767
|
+
for (const key of shardEpochKeys(shard, day, globalEpoch)) if (!modelEpochs.has(key)) await modelEpoch(key);
|
|
768
|
+
core.add(shard);
|
|
769
|
+
},
|
|
770
|
+
addContribution: (contribution) => core.addContribution(contribution),
|
|
771
|
+
finish: () => core.finish(),
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
|
|
668
775
|
export async function aggregateStatsShardsV7(
|
|
669
776
|
shards: PersistedStatsShardV7[],
|
|
670
777
|
day: string | null = currentLocalDay(),
|