pi-cache-optimizer 2.9.2 → 2.10.0

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/index.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir } from "node:fs/promises";
3
- import { watch } from "node:fs";
4
- import { join } from "node:path";
2
+ import { appendFile, mkdir } from "node:fs/promises";
3
+ import { basename, join } from "node:path";
5
4
  import {
6
5
  type ExtensionAPI, type ExtensionContext
7
6
  } from "@earendil-works/pi-coding-agent";
@@ -13,9 +12,12 @@ import { atomicCreateTextFileNoReplace, atomicReplaceTextFilePreservingMode, ato
13
12
  import { getAssistantMessageModelTokenValues, getModelIdNameTokenValues, isAdaptiveGenerationModel, isKimiCodingAdaptiveModel } from "./src/model-detect.ts";
14
13
  import { findLastExactModelDefinition, mergeCacheCompat, resolveEffectiveCompatFromConfig } from "./src/compat-config.ts";
15
14
  import { analyzeModelsJsonForMissingEntry, applyModelsJsonFixTransaction, chooseFixPlacement, composeFixInsertion, composeMissingEntryInsertion, composeModelOverrideInsertion, composeModelsJsonReceiptRollback, composeProviderAffinityInsertion, createModelsJsonFixReceipt, createRollbackBackupPath, decideFixPlacement, formatCompatKeysForInsertion, hasExplicitLongRetentionOptInFromConfig, hasReceiptReasoningProtocolChange, isActionableModelsJsonFixReceipt, locateModelInJsonc, markModelsJsonFixReceiptRolledBack, parseModelsJsonFixReceipt, prepareModelsJsonRollback, readModelsJsonFixReceipt, readModelsJsonFixReceiptSnapshot, receiptBackupPath, resolveExplicitCompatValue, selfCheckFix, selfCheckMissingEntryInsertion, validateModelsJsonRollback, writeModelsJsonFixReceipt } from "./src/models-json-fix.ts";
16
- import { ARCHIVE_ABANDONED_ACTIVE_MS, SHARD_ARCHIVE_PATH, isArchivableShard, type StatsSnapshot, aggregateStatsWithArchiveV7, compactStatsShardsV7, encodeStatsArchiveV2, listStatsArchiveGenerations, maybeRunStatsMaintenance, parseStatsArchiveV2, readStatsArchive, readStatsArchiveDetailed, readStatsArchiveView, readStatsSnapshot, setStatsArchiveTestHooks, StatsArchiveView, statsArchiveGenerationPath } from "./src/stats-archive.ts";
17
- import { type CacheProviderId, type CacheStats, LEGACY_STATE_FILE_PATH, acquireStatsMaintenanceLock, isMaintenanceMarkerDue, renameWithRetry, setStatsFsTestHooks, holdsStatsMaintenanceLock, releaseStatsMaintenanceLock, touchStatsMaintenanceLock, type PersistedRoutedModelRef, type PersistedStatsShardV7, SHARD_FILES_DIR, SHARD_GLOBAL_EPOCH_PATH, SHARD_RETENTION_MS, SHARD_STATE_DIR, STATE_FILE_PATH, type ShardAggregate, type UsageSnapshot, addUsageToCacheStats, advanceGlobalStatsEpoch, advanceModelStatsEpoch, aggregateStatsShardsV7, cleanupStatsShardsV7, cloneCacheStats, mapWithConcurrency, currentLocalDay, emptyAllCacheStats, emptyCacheStats, initialEpoch, loadStatsShardAggregateV7, modelEpochPath, parseCacheStats, parsePersistedRoutedModelRef, parsePersistedStatsShardV7, readGlobalStatsEpoch, readModelStatsEpoch, readValidStatsShardsV7, removeLegacyStatsFiles, writeStatsShardV7 } from "./src/stats-store.ts";
15
+ import { ARCHIVE_ABANDONED_ACTIVE_MS, SHARD_ARCHIVE_PATH, isArchivableShard, type StatsSnapshot, aggregateEpochKeys, aggregateStatsWithArchiveSync, aggregateStatsWithArchiveV7, readStatsArchiveForRefresh, compactStatsShardsV7, encodeStatsArchiveV2, listStatsArchiveGenerations, maybeRunStatsMaintenance, parseStatsArchiveV2, readStatsArchive, readStatsArchiveDetailed, readStatsArchiveView, readStatsSnapshot, setStatsArchiveTestHooks, StatsArchiveView, statsArchiveGenerationPath } from "./src/stats-archive.ts";
16
+ import { type CacheProviderId, type CacheStats, LEGACY_STATE_FILE_PATH, acquireStatsMaintenanceLock, isMaintenanceMarkerDue, renameWithRetry, setStatsFsTestHooks, holdsStatsMaintenanceLock, releaseStatsMaintenanceLock, touchStatsMaintenanceLock, type PersistedRoutedModelRef, type PersistedStatsShardV7, SHARD_FILES_DIR, SHARD_GLOBAL_EPOCH_PATH, SHARD_RETENTION_MS, SHARD_STATE_DIR, STATE_FILE_PATH, type ShardAggregate, type UsageSnapshot, addUsageToCacheStats, advanceGlobalStatsEpoch, advanceModelStatsEpoch, aggregateStatsShardsV7, cleanupStatsShardsV7, cloneCacheStats, mapWithConcurrency, currentLocalDay, emptyAllCacheStats, emptyCacheStats, initialEpoch, loadStatsShardAggregateV7, modelEpochPath, parseCacheStats, parsePersistedRoutedModelRef, parsePersistedStatsShardV7, readGlobalStatsEpoch, readModelStatsEpoch, readValidStatsShardsV7, removeLegacyStatsFiles, writeStatsShardV7, type ShardEpochs, readEpochFileResult, readEpochFileWithRetry, createShardAggregatorSync, SHARD_FILE_NAME_PATTERN } from "./src/stats-store.ts";
17
+ import { STATS_FULL_SCAN_INTERVAL_MS, StatsRefreshScheduler, type StatsWatchHandle, createFsShardWatch, TieredShardIndex, getStatsRefreshTestHooks, setStatsRefreshTestHooks } from "./src/stats-refresh.ts";
18
+ import { countingStatsReadFs, setStatsReadFsForTests, statsReadFs } from "./src/stats-fs.ts";
18
19
  import { PI_VIRTUAL_MODEL_API, getCompat, isAnthropicMessagesApi, isKimiCodingEmptySignatureModel, isKnownThirdPartyOpenAIEndpoint, isMistralConversationsApi, isNativeVirtualModel, isOfficialOpenAIBaseUrl, isOpenAICompatibleApi, isOpenAICompatibleProxyApi, isOpenAIFamilyAssistantMessage, isOpenAIFamilyModel, isOpenAIFamilyToken, isPiBuiltInLlamaCppModel, isResponsesPromptRewriteBypassApi, isRoutedFallbackModel, isValidModelsConfigForEffectiveCompat, modelKey, readEffectiveCompatConfig } from "./src/model-identity.ts";
20
+ import { STATS_INCREMENTAL_ENV, STATS_TIMING_ENV, STATS_VERIFY_ENV, isStatsIncrementalEnabled, isStatsVerifyEnabled, statsTimingLogPath } from "./src/config.ts";
19
21
  import { CONFIG_FILE_PATH, VIRTUAL_REWRITE_ENV, FOOTER_MODE_ENV, TOOL_ORDER_ENV, featureEnabled, footerStatsMode, isEnabledEnv, isToolOrderEnabled, parseFooterStatsMode, parsePersistedCacheOptimizerConfig, readPersistedCacheOptimizerConfig, resolveFooterStatsMode, runtimeOptimizerEnabled, setPersistedCacheOptimizerConfig, shouldInjectOpenAIPromptCacheKey, writePersistedCacheOptimizerConfig, writePersistedFeature, writePersistedFooterMode } from "./src/config.ts";
20
22
  import { decideZeroPriceWarming, readCacheWarmingMode } from "./src/cache-warming.ts";
21
23
  import { LONG_CACHE_RETENTION_VALUE, PI_CACHE_RETENTION_BASELINE_SYMBOL, PI_CACHE_RETENTION_ENV, STARTUP_CACHE_RETENTION_ENV, captureCacheRetentionEnv, getOrCaptureCacheRetentionBaseline, decidePromptCacheRetention, recordPromptCacheRetentionDecision, requestLongCacheRetention, restoreCacheRetentionEnv, userRequestedLongCacheRetention } from "./src/retention.ts";
@@ -108,9 +110,36 @@ function notifyCacheCompatIfNeeded(
108
110
  // this module. Tests await it after session_start; runtime code uses the
109
111
  // per-instance promise instead.
110
112
  let latestStatsRestoreForTests: Promise<void> = Promise.resolve();
113
+ /** Per extension instance in this module: resolves once no footer refresh (or its publish) is in flight. */
114
+ const statsRefreshSettledForTests = new Set<() => Promise<void>>();
111
115
 
112
116
  export const __internals_for_tests = {
113
117
  waitForStatsRestore: (): Promise<void> => latestStatsRestoreForTests,
118
+ /**
119
+ * Footer refreshes after tool_execution_end, agent_settled and message_end
120
+ * no longer hold up Pi's handlers (2.10). Tests await this before
121
+ * asserting on what such a refresh publishes.
122
+ */
123
+ statsRefreshSettled: async (): Promise<void> => {
124
+ for (const settled of statsRefreshSettledForTests) await settled();
125
+ },
126
+ setStatsRefreshTestHooks,
127
+ setStatsReadFsForTests,
128
+ countingStatsReadFs,
129
+ TieredShardIndex,
130
+ StatsRefreshScheduler,
131
+ createFsShardWatch,
132
+ aggregateStatsWithArchiveSync,
133
+ aggregateEpochKeys,
134
+ createShardAggregatorSync,
135
+ readStatsArchiveForRefresh,
136
+ readEpochFileResult,
137
+ isStatsIncrementalEnabled,
138
+ statsTimingLogPath,
139
+ STATS_INCREMENTAL_ENV,
140
+ STATS_TIMING_ENV,
141
+ STATS_VERIFY_ENV,
142
+ isStatsVerifyEnabled,
114
143
  getLastSkillCompressionOutcome,
115
144
  decidePromptCacheRetention,
116
145
  userRequestedLongCacheRetention,
@@ -440,7 +469,7 @@ export default function (pi: ExtensionAPI) {
440
469
  let persistenceWarningShown = false;
441
470
  let persistTimer: ReturnType<typeof setTimeout> | null = null;
442
471
  let shardRefreshTimer: ReturnType<typeof setTimeout> | null = null;
443
- let shardWatcher: ReturnType<typeof watch> | undefined;
472
+ let shardWatcher: StatsWatchHandle | undefined;
444
473
  // Historical stats are restored in the background so a large shard
445
474
  // directory never holds up Pi's session_start (issue #28). Handlers that
446
475
  // read or persist aggregated stats await this first.
@@ -630,6 +659,12 @@ export default function (pi: ExtensionAPI) {
630
659
  * own shard was absorbed anyway (see adoptAbsorbedOwnShard).
631
660
  */
632
661
  let persistedOwnShards: PersistedStatsShardV7[] = [];
662
+ /**
663
+ * Which lifetime of the in-memory counters a built shard snapshots: bumped
664
+ * whenever session_start clears them (see adoptAbsorbedOwnShard).
665
+ */
666
+ let countersSession = 0;
667
+ const countersSessionOfShard = new WeakMap<PersistedStatsShardV7, number>();
633
668
  function recordPersistedOwnShard(shard: PersistedStatsShardV7): void {
634
669
  if (shard.instanceId !== instanceId) return;
635
670
  const last = persistedOwnShards.at(-1);
@@ -653,9 +688,17 @@ export default function (pi: ExtensionAPI) {
653
688
  // Not identifiable (clock skew between the processes): assume the
654
689
  // archive holds everything, so nothing is ever counted twice.
655
690
  const absorbed = candidates.at(-1) ?? buildCurrentStatsShard();
691
+ // Session guard: subtract only a version built from the counters held
692
+ // now. session_start clears them (switching to another session, or the
693
+ // same one on reload) but keeps the id, so a version persisted before it
694
+ // counts usage these counters no longer hold: subtracting it would hide
695
+ // this session's usage. Its sessionHash alone cannot tell: a reload keeps
696
+ // it, and it changes without a reset when the session id first becomes
697
+ // known after usage (then the counters still hold that usage).
698
+ const sameSession = countersSessionOfShard.get(absorbed) === countersSession;
656
699
  const remaining: Record<string, CacheStats> = {};
657
700
  for (const [key, stats] of Object.entries(cacheStatsProcessByModel)) {
658
- const entry = absorbed.globalEpoch === currentGlobalEpoch ? absorbed.models[key] : undefined;
701
+ const entry = sameSession && absorbed.globalEpoch === currentGlobalEpoch ? absorbed.models[key] : undefined;
659
702
  const sameEpoch = entry && entry.modelEpoch === (modelEpochByKey.get(key) ?? initialEpoch(`model:${key}`));
660
703
  const delta = cloneCacheStats(stats);
661
704
  if (sameEpoch) {
@@ -678,23 +721,287 @@ export default function (pi: ExtensionAPI) {
678
721
  lastStatusText = undefined;
679
722
  // The new id keeps the old shard's day; the next status update rolls it
680
723
  // over as usual. Persist in the background (the aggregate below already
681
- // counts the in-memory shard).
682
- void persistCacheStats();
724
+ // counts the in-memory shard). Once shutdown began (the refresh gate is
725
+ // closed), never write an active shard: the flush closes this one.
726
+ void persistCacheStats(undefined, refreshScheduler.isClosed ? "closed" : "active");
683
727
  }
684
728
 
685
729
  let lastStatsSnapshot: StatsSnapshot | undefined;
686
730
 
687
- async function refreshShardAggregate(): Promise<ShardAggregate> {
731
+ // ── Epoch reads: one sequence, so a slow read never rolls back a newer one ──
732
+ // Every footer epoch read (refresh, message_end, restore) takes a number
733
+ // when it starts; local resets take one when they wrote. currentGlobalEpoch
734
+ // and each modelEpochByKey entry remember the number of the read that set
735
+ // them, and only a read that started later may change them. Without this a
736
+ // refresh that read E1 before another process reset to E2 could, after
737
+ // message_end already adopted E2 and recorded usage under it, switch back
738
+ // to E1 and clear that usage.
739
+ let epochReadSeq = 0;
740
+ let globalEpochSeq = 0;
741
+ /** Model epoch reads at or below this never set a model epoch (global change, session start, local reset). */
742
+ let modelEpochFloorSeq = 0;
743
+ const modelEpochSeq = new Map<string, number>();
744
+ function nextEpochSeq(): number {
745
+ return ++epochReadSeq;
746
+ }
747
+ /** Whether a global epoch read numbered `seq` may set currentGlobalEpoch (and records it when it may). */
748
+ function acceptGlobalEpochRead(seq: number): boolean {
749
+ if (seq <= globalEpochSeq) return false;
750
+ globalEpochSeq = seq;
751
+ return true;
752
+ }
753
+ function acceptModelEpochRead(seq: number, key: string): boolean {
754
+ if (seq <= modelEpochFloorSeq || seq <= (modelEpochSeq.get(key) ?? 0)) return false;
755
+ modelEpochSeq.set(key, seq);
756
+ return true;
757
+ }
758
+ /**
759
+ * acceptModelEpochRead for the read message_end labels new usage with. A
760
+ * read the floor rejects (a newer read changed the global epoch, or a
761
+ * session started, while it was in flight) is still the newest knowledge
762
+ * of this key's epoch when nothing newer set the key: a global reset never
763
+ * changes model epoch files, and voiding cleared what was known, not what
764
+ * this read saw. Without it the usage is recorded with no model epoch,
765
+ * that is the initial one, which every reader filters out when the model
766
+ * was ever reset, and the next message_end then drops it.
767
+ */
768
+ function acceptModelEpochReadForUsage(seq: number, key: string): boolean {
769
+ if (acceptModelEpochRead(seq, key)) return true;
770
+ if (modelEpochByKey.has(key) || (modelEpochSeq.get(key) ?? 0) > seq) return false;
771
+ modelEpochSeq.set(key, seq);
772
+ return true;
773
+ }
774
+ /** Model epochs known so far are void (they were cleared): older reads must not set them again. */
775
+ function voidModelEpochs(seq: number): void {
776
+ modelEpochSeq.clear();
777
+ modelEpochFloorSeq = Math.max(modelEpochFloorSeq, seq);
778
+ }
779
+
780
+ type EpochSnapshot = { seq: number; global: string; models: Map<string, string> };
781
+
782
+ /** Read the global epoch and `keys` in parallel, once, for one refresh. Throws on a persistent I/O error. */
783
+ async function readEpochSnapshot(keys: Iterable<string>): Promise<EpochSnapshot> {
784
+ const seq = nextEpochSeq();
785
+ const keyList = Array.from(keys);
786
+ const results = await Promise.all([
787
+ readEpochFileWithRetry(SHARD_GLOBAL_EPOCH_PATH, initialEpoch("global")),
788
+ ...keyList.map((key) => readEpochFileWithRetry(modelEpochPath(key), initialEpoch(`model:${key}`))),
789
+ ]);
790
+ const epochs = results.map((result) => {
791
+ if (!result.ok) throw result.error;
792
+ return result.epoch;
793
+ });
794
+ return { seq, global: epochs[0]!, models: new Map(keyList.map((key, index) => [key, epochs[index + 1]!])) };
795
+ }
796
+
797
+ // ── Footer refresh: tiered index + single flight ──
798
+ const fullScanIntervalMs = getStatsRefreshTestHooks().fullScanIntervalMs ?? STATS_FULL_SCAN_INTERVAL_MS;
799
+ const shardIndex = new TieredShardIndex(SHARD_FILES_DIR, {
800
+ freeze: getStatsRefreshTestHooks().freezeShards,
801
+ fullScanIntervalMs,
802
+ });
803
+ /**
804
+ * When the archive was last read in full (its newest generation lstat-ed
805
+ * and its identity checked). Between such reads an unchanged clean
806
+ * generation is confirmed by the listing alone; but a generation number is
807
+ * only unique while the archive directory lives: if the stats directory is
808
+ * deleted and another process compacts from scratch, a new generation 1
809
+ * replaces the old one under the same name. So the identity is re-checked
810
+ * on every full refresh and at least every full scan interval, which
811
+ * bounds that case like a cold shard instead of until the next generation.
812
+ */
813
+ let archiveVerifiedAt = -Infinity;
814
+ const refreshScheduler = new StatsRefreshScheduler<ShardAggregate>((full) => runStatsRefresh(full));
815
+ /** Background refresh chains (and their publish) in flight; shutdown drains them. */
816
+ const backgroundStatsTasks = new Set<Promise<void>>();
817
+ let backgroundRefreshWarned = false;
818
+ /** The context of the latest session_start, for refreshes no handler asked for (watcher, scans). */
819
+ let latestStatsCtx: ExtensionContext | undefined;
820
+
821
+ function trackBackgroundStatsTask(task: Promise<unknown>): void {
822
+ const tracked = task.then(() => undefined, warnBackgroundRefreshOnce);
823
+ backgroundStatsTasks.add(tracked);
824
+ void tracked.then(() => backgroundStatsTasks.delete(tracked));
825
+ }
826
+
827
+ function warnBackgroundRefreshOnce(error: unknown): void {
828
+ if (backgroundRefreshWarned) return;
829
+ backgroundRefreshWarned = true;
830
+ console.warn(`${LOG_PREFIX}: background footer stats refresh failed (further failures are not reported)`, error);
831
+ }
832
+
833
+ /**
834
+ * The one entry point for refreshes Pi does not wait for (tool_execution_end,
835
+ * agent_settled, message_end, the watcher, scans). Never rejects: every
836
+ * failure, including a stale ctx after reload, is caught and warned once.
837
+ * Publishes outside the refresh's critical section (a day rollover inside
838
+ * publishStatus requests refreshes of its own), and not at all once the
839
+ * gate closed or a newer session_start superseded this one.
840
+ */
841
+ function refreshAndPublishInBackground(ctx: ExtensionContext | undefined, pickModel?: () => PiModel | undefined): void {
842
+ if (refreshScheduler.isClosed) return;
843
+ const generation = statsRestoreGeneration;
844
+ trackBackgroundStatsTask((async () => {
845
+ await waitForStatsRestore();
846
+ const aggregate = await refreshScheduler.background(false);
847
+ if (aggregate === undefined || refreshScheduler.isClosed || generation !== statsRestoreGeneration || !ctx) return;
848
+ ensureShardWatcher();
849
+ await publishStatus(ctx, pickModel ? pickModel() : ctx.model);
850
+ })());
851
+ }
852
+
853
+ /**
854
+ * A refresh whose reads start after this call (see StatsRefreshScheduler).
855
+ * `full` (default) stats every shard file: commands, doctor, flush and
856
+ * restore. Lifecycle refreshes use the tiered index.
857
+ */
858
+ function refreshShardAggregate({ full = true }: { full?: boolean } = {}): Promise<ShardAggregate> {
859
+ return refreshScheduler.request(full);
860
+ }
861
+
862
+ function startFullScanIfDue(): void {
863
+ // The shutdown flush's own refreshes run with the gate closed: no new background scan then.
864
+ if (refreshScheduler.isClosed) return;
865
+ const scan = shardIndex.maybeStartFullScan(() => `${instanceId}.json`);
866
+ if (!scan) return;
867
+ trackBackgroundStatsTask(scan.then(async (changed) => {
868
+ await checkShardWatcherDirectory();
869
+ const mismatched = isStatsVerifyEnabled() && !refreshScheduler.isClosed
870
+ ? await shardIndex.verifyCachedContents(`${instanceId}.json`)
871
+ : [];
872
+ noteStatsVerifyResult(mismatched);
873
+ if (changed || mismatched.length > 0) refreshAndPublishInBackground(latestStatsCtx);
874
+ }));
875
+ }
876
+
877
+ // PI_CACHE_OPTIMIZER_STATS_VERIFY: warn (once) when two verifications found
878
+ // shard content that changed behind an unchanged file identity. A check
879
+ // only judges files whose identity was the cached one before and after its
880
+ // read, so a racing writer on a filesystem with real identities is never a
881
+ // verdict; requiring two keeps a single oddity from warning. (Consecutive
882
+ // is not required: the re-read after a verdict makes the next check clean.)
883
+ let statsVerifyMismatches = 0;
884
+ let statsVerifyWarned = false;
885
+ function noteStatsVerifyResult(mismatched: readonly string[]): void {
886
+ if (mismatched.length > 0) statsVerifyMismatches++;
887
+ const timingPath = statsTimingLogPath();
888
+ if (timingPath && mismatched.length > 0) writeStatsTiming(timingPath, { at: new Date().toISOString(), pid: process.pid, verifyMismatched: mismatched.length });
889
+ if (statsVerifyMismatches < 2 || statsVerifyWarned) return;
890
+ statsVerifyWarned = true;
891
+ console.warn(
892
+ `${LOG_PREFIX}: footer stats: ${mismatched.length} shard file(s) changed while their identity (inode, size, timestamps) did not; ` +
893
+ `this filesystem hides changes from the incremental refresh. Set ${STATS_INCREMENTAL_ENV}=0 and please report it.`,
894
+ );
895
+ }
896
+
897
+ async function runStatsRefresh(full: boolean): Promise<ShardAggregate> {
898
+ const startedAt = performance.now();
899
+ const ownName = `${instanceId}.json`;
900
+ const incremental = isStatsIncrementalEnabled();
901
+ let shardPhaseMs = 0;
688
902
  // Order matters (readStatsSnapshot): compaction publishes the archive
689
- // before deleting the shards it absorbed, so reading the directory first
690
- // and the archive second always sees each absorbed shard in at least one
691
- // of them. Reading them concurrently could pair an old archive with a
692
- // post-delete listing and drop those counters (and the last routed model)
693
- // for this refresh. A persistent transient archive read error reuses the
694
- // previous consistent snapshot instead of pairing an old archive with a
695
- // new listing.
696
- const snapshot = await readStatsSnapshot(lastStatsSnapshot);
903
+ // before deleting the shards it absorbed, so the shard phase (listing,
904
+ // every lstat and readFile) completes before the archive is listed.
905
+ // Reading them concurrently could pair an old archive with a post-delete
906
+ // listing and drop those counters. A persistent transient archive read
907
+ // error reuses the previous consistent snapshot (its shard contents, not
908
+ // names) instead of pairing an old archive with a new listing.
909
+ const verifyArchive = full || startedAt - archiveVerifiedAt >= fullScanIntervalMs;
910
+ const snapshot = incremental
911
+ ? await readStatsSnapshot(lastStatsSnapshot, SHARD_FILES_DIR, SHARD_ARCHIVE_PATH, {
912
+ reuseArchive: !verifyArchive,
913
+ readShards: async () => {
914
+ const shards = await shardIndex.refresh({ own: ownName, full });
915
+ await getStatsRefreshTestHooks().afterShardPhase?.();
916
+ shardPhaseMs = performance.now() - startedAt;
917
+ return shards;
918
+ },
919
+ })
920
+ : await readStatsSnapshot(lastStatsSnapshot);
697
921
  lastStatsSnapshot = snapshot;
922
+ if (verifyArchive || !incremental) archiveVerifiedAt = startedAt;
923
+ const snapshotMs = performance.now() - startedAt;
924
+ if (incremental) refreshScheduler.outsideRun(startFullScanIfDue);
925
+ await getStatsRefreshTestHooks().beforeEpochRead?.();
926
+ // Every epoch the aggregation can look up, read once and in parallel,
927
+ // shared by both views and the adoption below.
928
+ const day = currentLocalDay();
929
+ const sessionsAtRead = new Set(currentSessionHashSet ? [currentSessionHash] : []);
930
+ const keys = aggregateEpochKeys(snapshot.rawShards, snapshot.archive, [], day, undefined);
931
+ for (const key of aggregateEpochKeys(snapshot.rawShards, snapshot.archive, [], null, sessionsAtRead)) keys.add(key);
932
+ for (const shard of retiredShards.values()) for (const key of Object.keys(shard.models)) keys.add(key);
933
+ for (const key of Object.keys(cacheStatsProcessByModel)) keys.add(key);
934
+ const epochs = await readEpochSnapshot(keys);
935
+ await getStatsRefreshTestHooks().beforeCommit?.();
936
+ // ── Synchronous commit: no await from here on. ──
937
+ // Usage message_end records meanwhile is in the in-memory counters this
938
+ // step snapshots, so a refresh never overwrites it with older totals.
939
+ const aggregate = commitStatsRefresh(snapshot, epochs, day);
940
+ getStatsRefreshTestHooks().afterCommit?.(aggregate);
941
+ const timingPath = statsTimingLogPath();
942
+ if (timingPath) {
943
+ const totalMs = performance.now() - startedAt;
944
+ writeStatsTiming(timingPath, {
945
+ at: new Date().toISOString(), pid: process.pid, incremental, full,
946
+ totalMs: round(totalMs), shardPhaseMs: round(shardPhaseMs), archivePhaseMs: round(snapshotMs - shardPhaseMs),
947
+ epochAndCommitMs: round(totalMs - snapshotMs), epochKeys: keys.size,
948
+ shards: snapshot.rawShards.length, index: incremental ? shardIndex.lastRefresh : undefined,
949
+ });
950
+ }
951
+ return aggregate;
952
+ }
953
+
954
+ const round = (value: number) => Math.round(value * 100) / 100;
955
+ let timingLinesWritten = 0;
956
+ let timingWrites: Promise<void> = Promise.resolve();
957
+ /** Opt-in (PI_CACHE_OPTIMIZER_STATS_TIMING) JSON lines, serialized, capped, failures ignored. */
958
+ function writeStatsTiming(path: string, record: Record<string, unknown>): void {
959
+ if (timingLinesWritten >= 20_000) return;
960
+ timingLinesWritten++;
961
+ const line = JSON.stringify(record) + "\n";
962
+ timingWrites = timingWrites.then(() => appendFile(path, line, "utf8")).catch(() => undefined);
963
+ }
964
+
965
+ /** The model epoch a refresh's aggregation filters `key` with. */
966
+ function aggregationModelEpoch(key: string, epochs: EpochSnapshot): string {
967
+ // A read (or local reset) newer than this snapshot set our value: it wins.
968
+ if ((modelEpochSeq.get(key) ?? 0) > epochs.seq && modelEpochByKey.has(key)) return modelEpochByKey.get(key)!;
969
+ // Keys first seen after the snapshot (usage recorded meanwhile) use the
970
+ // epoch this process recorded them under.
971
+ return epochs.models.get(key) ?? modelEpochByKey.get(key) ?? initialEpoch(`model:${key}`);
972
+ }
973
+
974
+ function commitStatsRefresh(snapshot: StatsSnapshot, epochs: EpochSnapshot, day: string): ShardAggregate {
975
+ // A reset from another process can advance epochs while this instance is
976
+ // idle. Adopt those epochs during every refresh, not only when a later
977
+ // message_end arrives, so this instance cannot keep an old in-memory
978
+ // process bucket visible in `process` mode or rewrite stale counters during
979
+ // shutdown. Model-scoped resets clear only the affected local bucket. A
980
+ // read older than the one that set the current value is ignored.
981
+ let globalChanged = false;
982
+ if (acceptGlobalEpochRead(epochs.seq) && currentGlobalEpoch !== epochs.global) {
983
+ globalChanged = true;
984
+ currentGlobalEpoch = epochs.global;
985
+ cacheStatsProcessByModel = {};
986
+ modelEpochByKey.clear();
987
+ voidModelEpochs(epochs.seq);
988
+ modelApiByKey.clear();
989
+ modelNameByKey.clear();
990
+ lastActualRoutedModel = undefined;
991
+ }
992
+ if (!globalChanged) {
993
+ for (const key of Object.keys(cacheStatsProcessByModel)) {
994
+ const latestModelEpoch = epochs.models.get(key);
995
+ // A key first recorded after this snapshot was read: message_end read its epoch.
996
+ if (latestModelEpoch === undefined || !acceptModelEpochRead(epochs.seq, key)) continue;
997
+ if ((modelEpochByKey.get(key) ?? initialEpoch(`model:${key}`)) === latestModelEpoch) continue;
998
+ delete cacheStatsProcessByModel[key];
999
+ modelEpochByKey.set(key, latestModelEpoch);
1000
+ modelApiByKey.delete(key);
1001
+ modelNameByKey.delete(key);
1002
+ }
1003
+ }
1004
+
698
1005
  const { rawShards, archive } = snapshot;
699
1006
  const ownAbsorbedAt = archive.archive.absorbed[instanceId];
700
1007
  if (ownAbsorbedAt !== undefined) adoptAbsorbedOwnShard(ownAbsorbedAt);
@@ -703,9 +1010,14 @@ export default function (pi: ExtensionAPI) {
703
1010
  for (const id of archive.absorbedIds) retiredShards.delete(id);
704
1011
  const persistedShards = rawShards.filter((shard) => !archive.absorbedIds.has(shard.instanceId));
705
1012
  for (const shard of persistedShards) retiredShards.delete(shard.instanceId);
1013
+ // This process's own file is not even read by the tiered index (its
1014
+ // in-memory copy, the trailing shard, replaces it); the kill-switch path
1015
+ // reads it and drops it here. If a day rollover changed the id while the
1016
+ // snapshot was read, the previous id's content is its retired copy.
706
1017
  const shards = persistedShards.filter((shard) => shard.instanceId !== instanceId);
707
1018
  shards.push(...retiredShards.values());
708
1019
  const trailing = currentSessionHashSet ? [buildCurrentStatsShard()] : [];
1020
+ const epochSource: ShardEpochs = { globalEpoch: currentGlobalEpoch, modelEpoch: (key) => aggregationModelEpoch(key, epochs) };
709
1021
  // Keep lifetime session footer data separate from daily totals/commands.
710
1022
  // Both equal aggregating [...shards, ...archive.shards, ...trailing]
711
1023
  // (issue #28 review H): the current day only sees archive entries of that
@@ -713,37 +1025,12 @@ export default function (pi: ExtensionAPI) {
713
1025
  // merges the archive's pre-reduced per-(session, model) entries instead
714
1026
  // of re-aggregating every archived bucket. The all-days view is only read
715
1027
  // for the current session (cacheStatsByModel lookups and the last routed
716
- // model), so it is built for that session alone; rebuilding every
717
- // archived session's entries cost more than the rest of the refresh.
718
- const aggregate = await aggregateStatsWithArchiveV7(shards, archive, trailing, currentLocalDay());
719
- const sessionAggregate = await aggregateStatsWithArchiveV7(
720
- shards, archive, trailing, null, new Set(currentSessionHashSet ? [currentSessionHash] : []),
1028
+ // model), so it is built for that session alone.
1029
+ const aggregate = aggregateStatsWithArchiveSync(shards, archive, trailing, day, undefined, epochSource);
1030
+ const sessionAggregate = aggregateStatsWithArchiveSync(
1031
+ shards, archive, trailing, null, new Set(currentSessionHashSet ? [currentSessionHash] : []), epochSource,
721
1032
  );
722
1033
 
723
- // A reset from another process can advance epochs while this instance is
724
- // idle. Adopt those epochs during every aggregate refresh, not only when a
725
- // later message_end arrives, so this instance cannot keep an old in-memory
726
- // process bucket visible in `process` mode or rewrite stale counters during
727
- // shutdown. Model-scoped resets clear only the affected local bucket.
728
- const latestGlobalEpoch = await readGlobalStatsEpoch();
729
- if (currentGlobalEpoch !== latestGlobalEpoch) {
730
- currentGlobalEpoch = latestGlobalEpoch;
731
- cacheStatsProcessByModel = {};
732
- modelEpochByKey.clear();
733
- modelApiByKey.clear();
734
- modelNameByKey.clear();
735
- lastActualRoutedModel = undefined;
736
- } else {
737
- for (const key of Object.keys(cacheStatsProcessByModel)) {
738
- const latestModelEpoch = await readModelStatsEpoch(key);
739
- if ((modelEpochByKey.get(key) ?? initialEpoch(`model:${key}`)) === latestModelEpoch) continue;
740
- delete cacheStatsProcessByModel[key];
741
- modelEpochByKey.set(key, latestModelEpoch);
742
- modelApiByKey.delete(key);
743
- modelNameByKey.delete(key);
744
- }
745
- }
746
-
747
1034
  cacheStatsByModel = {};
748
1035
  for (const [sessionHash, models] of Object.entries(sessionAggregate.bySession)) {
749
1036
  for (const [key, stats] of Object.entries(models)) {
@@ -758,6 +1045,114 @@ export default function (pi: ExtensionAPI) {
758
1045
  return aggregate;
759
1046
  }
760
1047
 
1048
+ // ── TUI shard watcher: an accelerator only (marks names dirty) ──
1049
+ let shardWatcherWanted = false;
1050
+ let shardWatcherDirectory: string | undefined;
1051
+ let shardWatcherRetryAt = 0;
1052
+
1053
+ function closeShardWatcher(): void {
1054
+ const watcher = shardWatcher;
1055
+ shardWatcher = undefined;
1056
+ shardWatcherDirectory = undefined;
1057
+ try {
1058
+ watcher?.close();
1059
+ } catch {}
1060
+ }
1061
+
1062
+ /**
1063
+ * Create the watcher when wanted (TUI, gate open) and missing. Called after
1064
+ * the background restore (which creates the directory) and after
1065
+ * successful background refreshes, so a watcher that failed (the directory
1066
+ * did not exist yet, or an error closed it) is recreated once the
1067
+ * directory can be listed again, at most every STATS_FULL_SCAN_INTERVAL_MS.
1068
+ */
1069
+ function ensureShardWatcher(): void {
1070
+ if (!shardWatcherWanted || shardWatcher || refreshScheduler.isClosed) return;
1071
+ const now = performance.now();
1072
+ if (now < shardWatcherRetryAt) return;
1073
+ shardWatcherRetryAt = now + STATS_FULL_SCAN_INTERVAL_MS;
1074
+ try {
1075
+ const factory = getStatsRefreshTestHooks().watch ?? createFsShardWatch;
1076
+ shardWatcher = factory(SHARD_FILES_DIR, onShardWatchName, onShardWatchError);
1077
+ shardWatcherRetryAt = 0;
1078
+ void statsReadFs().stat(SHARD_FILES_DIR).then((info) => {
1079
+ if (shardWatcher) shardWatcherDirectory = `${String(info.ino)}:${info.birthtimeMs}`;
1080
+ }, () => undefined);
1081
+ } catch {
1082
+ // ENOENT, ENOSPC (inotify watches exhausted), EPERM: lifecycle
1083
+ // refreshes, the hot set and full scans keep the footer correct.
1084
+ shardWatcher = undefined;
1085
+ }
1086
+ }
1087
+
1088
+ function onShardWatchName(name: string | null): void {
1089
+ if (refreshScheduler.isClosed || !shardWatcher) return;
1090
+ const file = name === null ? undefined : basename(name);
1091
+ if (file === undefined) {
1092
+ // Overflow, or a platform that gives no name: re-check everything.
1093
+ shardIndex.requestFullScan();
1094
+ } else if (file.endsWith(".tmp")) {
1095
+ return; // the rename that publishes it reports the target name
1096
+ } else if (file === `${instanceId}.json`) {
1097
+ return; // this process's own writes: its in-memory copy is authoritative
1098
+ } else if (SHARD_FILE_NAME_PATTERN.test(file)) {
1099
+ shardIndex.markDirty(file);
1100
+ } else {
1101
+ shardIndex.requestFullScan();
1102
+ }
1103
+ scheduleShardRefresh(latestStatsCtx);
1104
+ }
1105
+
1106
+ /**
1107
+ * A watcher 'error' (Windows: the watched directory was deleted) would
1108
+ * otherwise be thrown by the EventEmitter and crash Pi. Close the handle
1109
+ * (holding it would keep a deleted directory pending on Windows), fall
1110
+ * back to full scans, and recreate it only once the directory lists again.
1111
+ */
1112
+ function onShardWatchError(): void {
1113
+ closeShardWatcher();
1114
+ shardWatcherRetryAt = performance.now() + STATS_FULL_SCAN_INTERVAL_MS;
1115
+ shardIndex.requestFullScan();
1116
+ }
1117
+
1118
+ /** After a full scan: a watcher whose directory was replaced (Linux keeps it on the old inode, silently) is recreated. */
1119
+ async function checkShardWatcherDirectory(): Promise<void> {
1120
+ if (!shardWatcher || shardWatcherDirectory === undefined) return;
1121
+ const watched = shardWatcherDirectory;
1122
+ let current: string | undefined;
1123
+ try {
1124
+ const info = await statsReadFs().stat(SHARD_FILES_DIR);
1125
+ current = `${String(info.ino)}:${info.birthtimeMs}`;
1126
+ } catch {
1127
+ current = undefined;
1128
+ }
1129
+ if (current !== watched && shardWatcherDirectory === watched) {
1130
+ closeShardWatcher();
1131
+ shardWatcherRetryAt = 0;
1132
+ if (current !== undefined) ensureShardWatcher();
1133
+ }
1134
+ }
1135
+
1136
+ /** session_shutdown, first step: refuse new background work and stop its sources. */
1137
+ function closeStatsRefreshGate(): void {
1138
+ refreshScheduler.close();
1139
+ shardWatcherWanted = false;
1140
+ if (shardRefreshTimer !== null) clearTimeout(shardRefreshTimer);
1141
+ shardRefreshTimer = null;
1142
+ closeShardWatcher();
1143
+ }
1144
+
1145
+ /** Wait for every refresh, publish and scan in flight. */
1146
+ async function drainStatsRefresh(): Promise<void> {
1147
+ for (;;) {
1148
+ await Promise.all(Array.from(backgroundStatsTasks));
1149
+ await refreshScheduler.drain();
1150
+ await shardIndex.settled();
1151
+ if (backgroundStatsTasks.size === 0 && refreshScheduler.idle && !shardIndex.fullScanInFlight) return;
1152
+ }
1153
+ }
1154
+ statsRefreshSettledForTests.add(drainStatsRefresh);
1155
+
761
1156
  function buildCurrentStatsShard(state: "active" | "closed" = "active"): PersistedStatsShardV7 {
762
1157
  const now = Date.now();
763
1158
  const models: PersistedStatsShardV7["models"] = {};
@@ -773,7 +1168,7 @@ export default function (pi: ExtensionAPI) {
773
1168
  stats: cloneCacheStats(stats),
774
1169
  };
775
1170
  }
776
- return {
1171
+ const shard: PersistedStatsShardV7 = {
777
1172
  version: 7,
778
1173
  kind: "pi-cache-optimizer-shard",
779
1174
  instanceId,
@@ -790,16 +1185,16 @@ export default function (pi: ExtensionAPI) {
790
1185
  models,
791
1186
  ...(lastActualRoutedModel ? { lastRoutedModel: { ...lastActualRoutedModel } } : {}),
792
1187
  };
1188
+ countersSessionOfShard.set(shard, countersSession);
1189
+ return shard;
793
1190
  }
794
1191
 
795
- function scheduleShardRefresh(ctx?: ExtensionContext, model?: PiModel): void {
1192
+ function scheduleShardRefresh(ctx?: ExtensionContext): void {
1193
+ if (refreshScheduler.isClosed) return;
796
1194
  if (shardRefreshTimer !== null) clearTimeout(shardRefreshTimer);
797
1195
  shardRefreshTimer = setTimeout(() => {
798
1196
  shardRefreshTimer = null;
799
- void waitForStatsRestore()
800
- .then(() => refreshShardAggregate())
801
- .then(() => publishStatus(ctx as ExtensionContext, model ?? ctx?.model))
802
- .catch(() => undefined);
1197
+ refreshAndPublishInBackground(ctx);
803
1198
  }, SHARD_REFRESH_DEBOUNCE_MS);
804
1199
  shardRefreshTimer.unref?.();
805
1200
  }
@@ -857,6 +1252,7 @@ export default function (pi: ExtensionAPI) {
857
1252
  const displayKey = modelKey(model);
858
1253
  const nextEpoch = await advanceModelStatsEpoch(displayKey);
859
1254
  modelEpochByKey.set(displayKey, nextEpoch);
1255
+ modelEpochSeq.set(displayKey, nextEpochSeq());
860
1256
  delete cacheStatsProcessByModel[displayKey];
861
1257
  delete cacheStatsTotalsByModel[displayKey];
862
1258
  for (const key of Object.keys(cacheStatsByModel)) {
@@ -870,6 +1266,8 @@ export default function (pi: ExtensionAPI) {
870
1266
 
871
1267
  async function resetCurrentSessionStats(): Promise<void> {
872
1268
  currentGlobalEpoch = await advanceGlobalStatsEpoch();
1269
+ globalEpochSeq = nextEpochSeq();
1270
+ voidModelEpochs(globalEpochSeq);
873
1271
  cacheStatsByModel = {};
874
1272
  cacheStatsTotalsByModel = {};
875
1273
  cacheStatsProcessByModel = {};
@@ -907,10 +1305,10 @@ export default function (pi: ExtensionAPI) {
907
1305
  persistTimer = null;
908
1306
  // A persist scheduled while a background restore runs (e.g. a routed
909
1307
  // model change without usage) must not race the restore's own write.
910
- void waitForStatsRestore()
1308
+ trackBackgroundStatsTask(waitForStatsRestore()
911
1309
  .then(() => persistCacheStats(ctx))
912
- .then(() => refreshShardAggregate())
913
- .catch(() => undefined);
1310
+ .then(() => refreshScheduler.background(false))
1311
+ .catch(() => undefined));
914
1312
  }, PERSIST_DEBOUNCE_MS);
915
1313
  persistTimer.unref?.();
916
1314
  }
@@ -924,9 +1322,23 @@ export default function (pi: ExtensionAPI) {
924
1322
  // Adopt resets performed by another Pi process before capturing the shard
925
1323
  // snapshot. Otherwise shutdown/command flush could rewrite stale local
926
1324
  // counters under an old epoch even though aggregation already hid them.
927
- await refreshShardAggregate();
1325
+ // A refresh that fails (a persistent read error) must not cost the
1326
+ // persist: write the counters under the epochs known so far.
1327
+ try {
1328
+ await refreshShardAggregate();
1329
+ } catch (error) {
1330
+ console.warn(`${LOG_PREFIX}: footer stats refresh before persisting failed`, error);
1331
+ }
928
1332
  await persistCacheStats(ctx, lifecycleState);
929
- await refreshShardAggregate();
1333
+ try {
1334
+ await refreshShardAggregate();
1335
+ } catch (error) {
1336
+ console.warn(`${LOG_PREFIX}: footer stats refresh after persisting failed`, error);
1337
+ }
1338
+ // That refresh may have continued an absorbed own shard under a new id
1339
+ // and queued its write: let it land before the flush (and a shutdown)
1340
+ // returns, or interactive mode's process.exit could cut it off.
1341
+ await enqueuePersist(() => Promise.resolve());
930
1342
  }
931
1343
 
932
1344
  async function rollOverStatsIfNeeded(ctx?: ExtensionContext): Promise<void> {
@@ -967,8 +1379,10 @@ export default function (pi: ExtensionAPI) {
967
1379
  syncSessionHash(ctx);
968
1380
  lastStatusText = undefined;
969
1381
  cacheStatsProcessByModel = {};
1382
+ countersSession++;
970
1383
  cacheStatsLegacyFamily = emptyAllCacheStats();
971
1384
  modelEpochByKey.clear();
1385
+ voidModelEpochs(nextEpochSeq());
972
1386
  modelApiByKey.clear();
973
1387
  modelNameByKey.clear();
974
1388
  if (reason === "reload") {
@@ -982,11 +1396,14 @@ export default function (pi: ExtensionAPI) {
982
1396
  // message_end syncs the epoch before recording. If the disk epoch differs
983
1397
  // now, a reset happened after that usage: adopt it and drop the stale
984
1398
  // process bucket instead of re-labelling old counters with the new epoch.
985
- const latestGlobalEpoch = await readGlobalStatsEpoch();
986
- if (latestGlobalEpoch !== currentGlobalEpoch) {
987
- currentGlobalEpoch = latestGlobalEpoch;
1399
+ // A read error keeps the epoch known so far (it is not "no reset").
1400
+ const seq = nextEpochSeq();
1401
+ const latest = await readEpochFileWithRetry(SHARD_GLOBAL_EPOCH_PATH, initialEpoch("global"));
1402
+ if (latest.ok && acceptGlobalEpochRead(seq) && latest.epoch !== currentGlobalEpoch) {
1403
+ currentGlobalEpoch = latest.epoch;
988
1404
  cacheStatsProcessByModel = {};
989
1405
  modelEpochByKey.clear();
1406
+ voidModelEpochs(seq);
990
1407
  modelApiByKey.clear();
991
1408
  modelNameByKey.clear();
992
1409
  }
@@ -1149,6 +1566,11 @@ export default function (pi: ExtensionAPI) {
1149
1566
  // publish a stale footer. Handlers that read or persist stats await
1150
1567
  // waitForStatsRestore() first.
1151
1568
  const generation = ++statsRestoreGeneration;
1569
+ // The same extension instance lives on across session switches
1570
+ // (shutdown, then start): reopen what the shutdown closed.
1571
+ refreshScheduler.open();
1572
+ latestStatsCtx = ctx;
1573
+ const tui = ctx.mode === "tui";
1152
1574
  resetStatsForSessionStart(event.reason, ctx);
1153
1575
  const previousRestore = statsRestorePromise;
1154
1576
  statsRestorePromise = previousRestore
@@ -1160,25 +1582,26 @@ export default function (pi: ExtensionAPI) {
1160
1582
  })
1161
1583
  .catch((error) => {
1162
1584
  console.warn(`${LOG_PREFIX}: failed to restore cache stats`, error);
1585
+ })
1586
+ .then(() => {
1587
+ // TUI only, and only after the restore created the directory (2.9.3
1588
+ // watched it on the startup path and stayed without a watcher for
1589
+ // the whole process when it did not exist yet).
1590
+ if (tui && generation === statsRestoreGeneration && !refreshScheduler.isClosed) {
1591
+ shardWatcherWanted = true;
1592
+ shardWatcherRetryAt = 0;
1593
+ ensureShardWatcher();
1594
+ }
1163
1595
  });
1164
1596
  latestStatsRestoreForTests = statsRestorePromise;
1165
- if (ctx.mode === "tui" && !shardWatcher) {
1166
- try {
1167
- shardWatcher = watch(SHARD_FILES_DIR, () => scheduleShardRefresh(ctx));
1168
- shardWatcher.unref?.();
1169
- } catch {
1170
- // Lifecycle and explicit command refreshes remain authoritative.
1171
- }
1172
- }
1173
1597
  });
1174
1598
 
1175
1599
  pi.on("tool_execution_end", async (event, ctx) => {
1176
1600
  // Pi 0.99+ codemode scripts run nested tool calls in parallel; the calling
1177
1601
  // tool's own end event follows them, so one refresh covers the batch.
1178
1602
  if (isNonEmptyString((event as { parentToolCallId?: unknown } | undefined)?.parentToolCallId)) return;
1179
- await waitForStatsRestore();
1180
- await refreshShardAggregate();
1181
- await publishStatus(ctx);
1603
+ // Pi awaits this handler before the next turn: refresh in the background.
1604
+ refreshAndPublishInBackground(ctx);
1182
1605
  });
1183
1606
 
1184
1607
  // Pi 0.86+ native prompt-cache warming: keep it running for models whose
@@ -1196,20 +1619,20 @@ export default function (pi: ExtensionAPI) {
1196
1619
  // a record consumed out of order) so they cannot be correlated with the
1197
1620
  // next run's messages.
1198
1621
  providerRequestStates.length = 0;
1199
- await waitForStatsRestore();
1200
- await refreshShardAggregate();
1201
- await publishStatus(ctx);
1622
+ refreshAndPublishInBackground(ctx);
1202
1623
  });
1203
1624
 
1204
1625
  pi.on("session_shutdown", async (_event, ctx) => {
1205
1626
  try {
1627
+ // Close the gate first (no new background refresh, watcher event or
1628
+ // scan-triggered publish), then let what is in flight finish, then
1629
+ // flush. The flush's own refreshes are awaited and still run.
1630
+ closeStatsRefreshGate();
1206
1631
  await waitForStatsRestore();
1632
+ await drainStatsRefresh();
1207
1633
  await flushPersistCacheStats(ctx, "closed");
1208
1634
  } finally {
1209
- if (shardRefreshTimer !== null) clearTimeout(shardRefreshTimer);
1210
- shardRefreshTimer = null;
1211
- shardWatcher?.close();
1212
- shardWatcher = undefined;
1635
+ closeStatsRefreshGate();
1213
1636
  latestCacheHint = undefined;
1214
1637
  providerRequestStates.length = 0;
1215
1638
  delete getProtocolGlobal().__piCacheOptimizerCacheKey__;
@@ -1221,7 +1644,7 @@ export default function (pi: ExtensionAPI) {
1221
1644
  pi.on("model_select", async (event, ctx) => {
1222
1645
  if (runtimeOptimizerEnabled) notifyCacheCompatIfNeeded(resolveRouteModel(event.model, ctx) ?? event.model, ctx, warnedModels);
1223
1646
  await waitForStatsRestore();
1224
- await refreshShardAggregate();
1647
+ await refreshShardAggregate({ full: false });
1225
1648
  await publishStatus(ctx, event.model);
1226
1649
  });
1227
1650
 
@@ -1743,16 +2166,23 @@ export default function (pi: ExtensionAPI) {
1743
2166
  // routed model. The process bucket is intentionally never persisted.
1744
2167
  if (statsModel) {
1745
2168
  const key = modelKey(statsModel);
1746
- const latestGlobalEpoch = await readGlobalStatsEpoch();
1747
- const latestModelEpoch = await readModelStatsEpoch(key);
1748
- if (currentGlobalEpoch !== latestGlobalEpoch) {
1749
- currentGlobalEpoch = latestGlobalEpoch;
2169
+ // Fresh reads, numbered like every footer epoch read: a refresh that
2170
+ // read older epochs can no longer switch back and clear this usage. A
2171
+ // read error keeps the epochs known so far.
2172
+ const seq = nextEpochSeq();
2173
+ const [latestGlobal, latestModel] = await Promise.all([
2174
+ readEpochFileWithRetry(SHARD_GLOBAL_EPOCH_PATH, initialEpoch("global")),
2175
+ readEpochFileWithRetry(modelEpochPath(key), initialEpoch(`model:${key}`)),
2176
+ ]);
2177
+ if (latestGlobal.ok && acceptGlobalEpochRead(seq) && currentGlobalEpoch !== latestGlobal.epoch) {
2178
+ currentGlobalEpoch = latestGlobal.epoch;
1750
2179
  cacheStatsProcessByModel = {};
1751
2180
  modelEpochByKey.clear();
2181
+ voidModelEpochs(seq - 1);
1752
2182
  }
1753
- if (modelEpochByKey.get(key) !== latestModelEpoch) {
2183
+ if (latestModel.ok && acceptModelEpochReadForUsage(seq, key) && modelEpochByKey.get(key) !== latestModel.epoch) {
1754
2184
  delete cacheStatsProcessByModel[key];
1755
- modelEpochByKey.set(key, latestModelEpoch);
2185
+ modelEpochByKey.set(key, latestModel.epoch);
1756
2186
  }
1757
2187
  modelApiByKey.set(key, statsModel.api ?? "");
1758
2188
  modelNameByKey.set(key, statsModel.name || statsModel.id);
@@ -1764,20 +2194,19 @@ export default function (pi: ExtensionAPI) {
1764
2194
  addUsageToCacheStats(getStatsForModel(undefined, adapter), usage);
1765
2195
  }
1766
2196
 
1767
- await waitForStatsRestore();
1768
2197
  schedulePersistCacheStats(ctx);
1769
- await refreshShardAggregate();
1770
- // A late response from an older selection must not replace the active
1771
- // footer. Only a routed response that still belongs to the currently
1772
- // selected virtual/router model may publish its physical model directly.
1773
- const responseBelongsToCurrentSelection =
1774
- requestCorrelationForMessage.selectionModelKey !== undefined &&
1775
- ctx.model !== undefined &&
1776
- requestCorrelationForMessage.selectionModelKey === modelKey(ctx.model);
1777
- await publishStatus(
1778
- ctx,
1779
- requestSelectionIsVirtual && responseBelongsToCurrentSelection ? statsModel : ctx.model,
1780
- );
2198
+ // The counters above are already updated in memory; the refresh and the
2199
+ // footer update run in the background (Pi awaits message_end).
2200
+ refreshAndPublishInBackground(ctx, () => {
2201
+ // A late response from an older selection must not replace the active
2202
+ // footer. Only a routed response that still belongs to the currently
2203
+ // selected virtual/router model may publish its physical model directly.
2204
+ const responseBelongsToCurrentSelection =
2205
+ requestCorrelationForMessage.selectionModelKey !== undefined &&
2206
+ ctx.model !== undefined &&
2207
+ requestCorrelationForMessage.selectionModelKey === modelKey(ctx.model);
2208
+ return requestSelectionIsVirtual && responseBelongsToCurrentSelection ? statsModel : ctx.model;
2209
+ });
1781
2210
  });
1782
2211
 
1783
2212
  // ────────────────────────────────────────────────────────────────