pi-cache-optimizer 2.10.0 → 2.10.2

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.
Files changed (2) hide show
  1. package/index.ts +122 -13
  2. package/package.json +1 -1
package/index.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { appendFile, mkdir } from "node:fs/promises";
2
+ import { appendFile, lstat, mkdir } from "node:fs/promises";
3
3
  import { basename, join } from "node:path";
4
4
  import {
5
5
  type ExtensionAPI, type ExtensionContext
6
6
  } from "@earendil-works/pi-coding-agent";
7
- import { LOG_PREFIX, type PiModel, asRecord, isNonEmptyString } from "./src/common.ts";
7
+ import { LOG_PREFIX, type PiModel, asRecord, getErrorCode, isNonEmptyString } from "./src/common.ts";
8
8
  import { FIX_RECEIPT_FILE_NAME, FIX_RECEIPT_PATH, MODELS_JSON_PATH, STATE_DIR } from "./src/paths.ts";
9
9
  import { type FixSuggestion } from "./src/fix-types.ts";
10
10
  import { deepEqualIgnoringKeys, findExistingCompatKeysInJsonc, locateModelOverrideInJsonc, locateProviderCompatInJsonc, parseJsonc, stripJsoncComments, stripJsoncTrailingCommas } from "./src/jsonc.ts";
@@ -1008,8 +1008,18 @@ export default function (pi: ExtensionAPI) {
1008
1008
  // Shards folded into the archive are counted there. Ignore their raw file
1009
1009
  // (a crash may leave it behind) and this process's in-memory retired copy.
1010
1010
  for (const id of archive.absorbedIds) retiredShards.delete(id);
1011
- const persistedShards = rawShards.filter((shard) => !archive.absorbedIds.has(shard.instanceId));
1012
- for (const shard of persistedShards) retiredShards.delete(shard.instanceId);
1011
+ // A retired copy gives way to its file once the file is at least as new
1012
+ // (its closing write landed). An older file (the id's last active write,
1013
+ // when the closing write failed or is still queued) is ignored instead:
1014
+ // it may hold fewer counters than the retired copy.
1015
+ const persistedShards = rawShards.filter((shard) => {
1016
+ if (archive.absorbedIds.has(shard.instanceId)) return false;
1017
+ const retired = retiredShards.get(shard.instanceId);
1018
+ if (!retired) return true;
1019
+ if (shard.lifecycle.updatedAt < retired.lifecycle.updatedAt) return false;
1020
+ retiredShards.delete(shard.instanceId);
1021
+ return true;
1022
+ });
1013
1023
  // This process's own file is not even read by the tiered index (its
1014
1024
  // in-memory copy, the trailing shard, replaces it); the kill-switch path
1015
1025
  // reads it and drops it here. If a day rollover changed the id while the
@@ -1350,19 +1360,18 @@ export default function (pi: ExtensionAPI) {
1350
1360
  clearTimeout(persistTimer);
1351
1361
  persistTimer = null;
1352
1362
  }
1363
+ // Adopt other processes' epoch resets before the snapshot below.
1364
+ await refreshShardAggregate();
1365
+ // A session_start on this instance may have retired the shard (and
1366
+ // moved to today's day) while that refresh ran: nothing left to roll.
1367
+ if (shardDay === day) return;
1353
1368
  // Preserve yesterday under its original UUID/day before clearing daily
1354
1369
  // counters. Each day owns a new shard so total never includes yesterday.
1355
- await refreshShardAggregate();
1356
- await persistCacheStats(ctx, "closed");
1357
- retiredShards.set(instanceId, buildCurrentStatsShard("closed"));
1358
- instanceId = randomUUID();
1359
- instanceShardPath = join(SHARD_FILES_DIR, `${instanceId}.json`);
1360
- persistedOwnShards = [];
1361
- shardDay = day;
1362
- shardCreatedAt = Date.now();
1370
+ const closing = retireCurrentShard(day, ctx);
1363
1371
  cacheStatsProcessByModel = {};
1364
1372
  cacheStatsLegacyFamily = emptyAllCacheStats();
1365
1373
  lastStatusText = undefined;
1374
+ await closing;
1366
1375
  await persistCacheStats(ctx);
1367
1376
  await refreshShardAggregate();
1368
1377
  })();
@@ -1370,6 +1379,100 @@ export default function (pi: ExtensionAPI) {
1370
1379
  finally { rolloverPromise = undefined; }
1371
1380
  }
1372
1381
 
1382
+ /**
1383
+ * Retired shards whose closing write failed: counted from memory only, so
1384
+ * they would be lost when the process exits. The shutdown flush writes
1385
+ * each one once more (see retryUnpersistedRetiredShards).
1386
+ */
1387
+ const unpersistedRetiredShards = new Map<string, { shard: PersistedStatsShardV7; path: string; landed: boolean }>();
1388
+
1389
+ /**
1390
+ * One more closing write for each retired shard whose write failed, at
1391
+ * shutdown. Skipped once its retired copy is gone: compaction absorbed the
1392
+ * id (the archive counts it), or a file at least as new already landed.
1393
+ * Also skipped when an earlier write of the id had landed but its file is
1394
+ * gone now: compaction folded it into the archive and deleted it (a later
1395
+ * pass then forgets the id, so a refresh that missed the archive in
1396
+ * between still holds the retired copy). Writing it back would count it
1397
+ * twice. A second failure only warns: there is nothing left to retry with.
1398
+ */
1399
+ async function retryUnpersistedRetiredShards(): Promise<void> {
1400
+ for (const [id, { shard, path, landed }] of Array.from(unpersistedRetiredShards)) {
1401
+ unpersistedRetiredShards.delete(id);
1402
+ if (retiredShards.get(id) !== shard) continue;
1403
+ await enqueuePersist(async () => {
1404
+ try {
1405
+ if (landed && await lstat(path).then(() => false, (error) => getErrorCode(error) === "ENOENT")) return;
1406
+ await writeStatsShardV7(path, shard);
1407
+ } catch (error) {
1408
+ console.warn(`${LOG_PREFIX}: failed again to persist a retired stats shard at shutdown; its usage is lost`, error);
1409
+ }
1410
+ });
1411
+ }
1412
+ }
1413
+
1414
+ /**
1415
+ * Retire the current shard: snapshot it closed, keep that snapshot as its
1416
+ * retired copy, continue under a new id on `day`, and queue the snapshot's
1417
+ * write (a failure warns and the retired copy keeps counting it; the
1418
+ * shutdown flush writes it once more). The written and the retired copy
1419
+ * are one object, so once its write lands the file (same updatedAt)
1420
+ * replaces the retired copy. Synchronous up to
1421
+ * the queued write, so usage recorded after this goes to the new id.
1422
+ */
1423
+ function retireCurrentShard(day: string, ctx?: ExtensionContext): Promise<void> {
1424
+ if (persistTimer !== null) {
1425
+ clearTimeout(persistTimer);
1426
+ persistTimer = null;
1427
+ }
1428
+ const closed = buildCurrentStatsShard("closed");
1429
+ const closedPath = instanceShardPath;
1430
+ const landed = persistedOwnShards.length > 0;
1431
+ retiredShards.set(instanceId, closed);
1432
+ instanceId = randomUUID();
1433
+ instanceShardPath = join(SHARD_FILES_DIR, `${instanceId}.json`);
1434
+ persistedOwnShards = [];
1435
+ shardCreatedAt = Date.now();
1436
+ shardDay = day;
1437
+ return enqueuePersist(async () => {
1438
+ try {
1439
+ await writeStatsShardV7(closedPath, closed);
1440
+ } catch (error) {
1441
+ unpersistedRetiredShards.set(closed.instanceId, { shard: closed, path: closedPath, landed });
1442
+ console.warn(`${LOG_PREFIX}: failed to persist a retired stats shard`, error);
1443
+ if (!persistenceWarningShown) {
1444
+ persistenceWarningShown = true;
1445
+ ctx?.ui.notify(
1446
+ `${LOG_PREFIX}: failed to persist footer stats; using in-memory stats for this process.`,
1447
+ "warning",
1448
+ );
1449
+ }
1450
+ }
1451
+ });
1452
+ }
1453
+
1454
+ /**
1455
+ * session_start calls this instance has handled. Pi 1.3 builds a new
1456
+ * extension instance for every session (new/resume/fork/reload), but a
1457
+ * host that keeps one instance across sessions sends it a second
1458
+ * session_start, which clears the in-memory counters.
1459
+ */
1460
+ let sessionStartsHandled = 0;
1461
+
1462
+ /**
1463
+ * Before a second session_start on the same instance clears the counters,
1464
+ * retire the shard holding them and continue under a new id, as the day
1465
+ * rollover does. Without this, the next persist rewrites the old id with
1466
+ * the cleared counters and the earlier session's usage for the day is lost
1467
+ * (the shutdown flush closed it, but the id was reused). See
1468
+ * retireCurrentShard.
1469
+ */
1470
+ function retireShardForSessionStart(): void {
1471
+ // The retired shard keeps its own day; the new id starts on today's, so
1472
+ // the restore does not roll over again into an empty extra shard.
1473
+ void retireCurrentShard(currentLocalDay());
1474
+ }
1475
+
1373
1476
  /**
1374
1477
  * Synchronous part of a session restore: reset in-memory state immediately
1375
1478
  * at session_start, so usage recorded before the background disk restore
@@ -1571,6 +1674,7 @@ export default function (pi: ExtensionAPI) {
1571
1674
  refreshScheduler.open();
1572
1675
  latestStatsCtx = ctx;
1573
1676
  const tui = ctx.mode === "tui";
1677
+ if (sessionStartsHandled++ > 0) retireShardForSessionStart();
1574
1678
  resetStatsForSessionStart(event.reason, ctx);
1575
1679
  const previousRestore = statsRestorePromise;
1576
1680
  statsRestorePromise = previousRestore
@@ -1630,7 +1734,12 @@ export default function (pi: ExtensionAPI) {
1630
1734
  closeStatsRefreshGate();
1631
1735
  await waitForStatsRestore();
1632
1736
  await drainStatsRefresh();
1633
- await flushPersistCacheStats(ctx, "closed");
1737
+ try {
1738
+ await flushPersistCacheStats(ctx, "closed");
1739
+ } finally {
1740
+ // Also when the flush failed (e.g. its rollover's refresh threw).
1741
+ await retryUnpersistedRetiredShards();
1742
+ }
1634
1743
  } finally {
1635
1744
  closeStatsRefreshGate();
1636
1745
  latestCacheHint = undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cache-optimizer",
3
- "version": "2.10.0",
3
+ "version": "2.10.2",
4
4
  "description": "Improve Pi prompt/KV cache hit rates with stable prompts, OpenAI-compatible cache keys, proxy compat warnings, and footer cache stats.",
5
5
  "keywords": [
6
6
  "pi-package",