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/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.
@@ -692,34 +721,313 @@ export default function (pi: ExtensionAPI) {
692
721
  lastStatusText = undefined;
693
722
  // The new id keeps the old shard's day; the next status update rolls it
694
723
  // over as usual. Persist in the background (the aggregate below already
695
- // counts the in-memory shard).
696
- 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");
697
727
  }
698
728
 
699
729
  let lastStatsSnapshot: StatsSnapshot | undefined;
700
730
 
701
- 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;
702
902
  // Order matters (readStatsSnapshot): compaction publishes the archive
703
- // before deleting the shards it absorbed, so reading the directory first
704
- // and the archive second always sees each absorbed shard in at least one
705
- // of them. Reading them concurrently could pair an old archive with a
706
- // post-delete listing and drop those counters (and the last routed model)
707
- // for this refresh. A persistent transient archive read error reuses the
708
- // previous consistent snapshot instead of pairing an old archive with a
709
- // new listing.
710
- 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);
711
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
+
712
1005
  const { rawShards, archive } = snapshot;
713
1006
  const ownAbsorbedAt = archive.archive.absorbed[instanceId];
714
1007
  if (ownAbsorbedAt !== undefined) adoptAbsorbedOwnShard(ownAbsorbedAt);
715
1008
  // Shards folded into the archive are counted there. Ignore their raw file
716
1009
  // (a crash may leave it behind) and this process's in-memory retired copy.
717
1010
  for (const id of archive.absorbedIds) retiredShards.delete(id);
718
- const persistedShards = rawShards.filter((shard) => !archive.absorbedIds.has(shard.instanceId));
719
- 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
+ });
1023
+ // This process's own file is not even read by the tiered index (its
1024
+ // in-memory copy, the trailing shard, replaces it); the kill-switch path
1025
+ // reads it and drops it here. If a day rollover changed the id while the
1026
+ // snapshot was read, the previous id's content is its retired copy.
720
1027
  const shards = persistedShards.filter((shard) => shard.instanceId !== instanceId);
721
1028
  shards.push(...retiredShards.values());
722
1029
  const trailing = currentSessionHashSet ? [buildCurrentStatsShard()] : [];
1030
+ const epochSource: ShardEpochs = { globalEpoch: currentGlobalEpoch, modelEpoch: (key) => aggregationModelEpoch(key, epochs) };
723
1031
  // Keep lifetime session footer data separate from daily totals/commands.
724
1032
  // Both equal aggregating [...shards, ...archive.shards, ...trailing]
725
1033
  // (issue #28 review H): the current day only sees archive entries of that
@@ -727,37 +1035,12 @@ export default function (pi: ExtensionAPI) {
727
1035
  // merges the archive's pre-reduced per-(session, model) entries instead
728
1036
  // of re-aggregating every archived bucket. The all-days view is only read
729
1037
  // for the current session (cacheStatsByModel lookups and the last routed
730
- // model), so it is built for that session alone; rebuilding every
731
- // archived session's entries cost more than the rest of the refresh.
732
- const aggregate = await aggregateStatsWithArchiveV7(shards, archive, trailing, currentLocalDay());
733
- const sessionAggregate = await aggregateStatsWithArchiveV7(
734
- shards, archive, trailing, null, new Set(currentSessionHashSet ? [currentSessionHash] : []),
1038
+ // model), so it is built for that session alone.
1039
+ const aggregate = aggregateStatsWithArchiveSync(shards, archive, trailing, day, undefined, epochSource);
1040
+ const sessionAggregate = aggregateStatsWithArchiveSync(
1041
+ shards, archive, trailing, null, new Set(currentSessionHashSet ? [currentSessionHash] : []), epochSource,
735
1042
  );
736
1043
 
737
- // A reset from another process can advance epochs while this instance is
738
- // idle. Adopt those epochs during every aggregate refresh, not only when a
739
- // later message_end arrives, so this instance cannot keep an old in-memory
740
- // process bucket visible in `process` mode or rewrite stale counters during
741
- // shutdown. Model-scoped resets clear only the affected local bucket.
742
- const latestGlobalEpoch = await readGlobalStatsEpoch();
743
- if (currentGlobalEpoch !== latestGlobalEpoch) {
744
- currentGlobalEpoch = latestGlobalEpoch;
745
- cacheStatsProcessByModel = {};
746
- modelEpochByKey.clear();
747
- modelApiByKey.clear();
748
- modelNameByKey.clear();
749
- lastActualRoutedModel = undefined;
750
- } else {
751
- for (const key of Object.keys(cacheStatsProcessByModel)) {
752
- const latestModelEpoch = await readModelStatsEpoch(key);
753
- if ((modelEpochByKey.get(key) ?? initialEpoch(`model:${key}`)) === latestModelEpoch) continue;
754
- delete cacheStatsProcessByModel[key];
755
- modelEpochByKey.set(key, latestModelEpoch);
756
- modelApiByKey.delete(key);
757
- modelNameByKey.delete(key);
758
- }
759
- }
760
-
761
1044
  cacheStatsByModel = {};
762
1045
  for (const [sessionHash, models] of Object.entries(sessionAggregate.bySession)) {
763
1046
  for (const [key, stats] of Object.entries(models)) {
@@ -772,6 +1055,114 @@ export default function (pi: ExtensionAPI) {
772
1055
  return aggregate;
773
1056
  }
774
1057
 
1058
+ // ── TUI shard watcher: an accelerator only (marks names dirty) ──
1059
+ let shardWatcherWanted = false;
1060
+ let shardWatcherDirectory: string | undefined;
1061
+ let shardWatcherRetryAt = 0;
1062
+
1063
+ function closeShardWatcher(): void {
1064
+ const watcher = shardWatcher;
1065
+ shardWatcher = undefined;
1066
+ shardWatcherDirectory = undefined;
1067
+ try {
1068
+ watcher?.close();
1069
+ } catch {}
1070
+ }
1071
+
1072
+ /**
1073
+ * Create the watcher when wanted (TUI, gate open) and missing. Called after
1074
+ * the background restore (which creates the directory) and after
1075
+ * successful background refreshes, so a watcher that failed (the directory
1076
+ * did not exist yet, or an error closed it) is recreated once the
1077
+ * directory can be listed again, at most every STATS_FULL_SCAN_INTERVAL_MS.
1078
+ */
1079
+ function ensureShardWatcher(): void {
1080
+ if (!shardWatcherWanted || shardWatcher || refreshScheduler.isClosed) return;
1081
+ const now = performance.now();
1082
+ if (now < shardWatcherRetryAt) return;
1083
+ shardWatcherRetryAt = now + STATS_FULL_SCAN_INTERVAL_MS;
1084
+ try {
1085
+ const factory = getStatsRefreshTestHooks().watch ?? createFsShardWatch;
1086
+ shardWatcher = factory(SHARD_FILES_DIR, onShardWatchName, onShardWatchError);
1087
+ shardWatcherRetryAt = 0;
1088
+ void statsReadFs().stat(SHARD_FILES_DIR).then((info) => {
1089
+ if (shardWatcher) shardWatcherDirectory = `${String(info.ino)}:${info.birthtimeMs}`;
1090
+ }, () => undefined);
1091
+ } catch {
1092
+ // ENOENT, ENOSPC (inotify watches exhausted), EPERM: lifecycle
1093
+ // refreshes, the hot set and full scans keep the footer correct.
1094
+ shardWatcher = undefined;
1095
+ }
1096
+ }
1097
+
1098
+ function onShardWatchName(name: string | null): void {
1099
+ if (refreshScheduler.isClosed || !shardWatcher) return;
1100
+ const file = name === null ? undefined : basename(name);
1101
+ if (file === undefined) {
1102
+ // Overflow, or a platform that gives no name: re-check everything.
1103
+ shardIndex.requestFullScan();
1104
+ } else if (file.endsWith(".tmp")) {
1105
+ return; // the rename that publishes it reports the target name
1106
+ } else if (file === `${instanceId}.json`) {
1107
+ return; // this process's own writes: its in-memory copy is authoritative
1108
+ } else if (SHARD_FILE_NAME_PATTERN.test(file)) {
1109
+ shardIndex.markDirty(file);
1110
+ } else {
1111
+ shardIndex.requestFullScan();
1112
+ }
1113
+ scheduleShardRefresh(latestStatsCtx);
1114
+ }
1115
+
1116
+ /**
1117
+ * A watcher 'error' (Windows: the watched directory was deleted) would
1118
+ * otherwise be thrown by the EventEmitter and crash Pi. Close the handle
1119
+ * (holding it would keep a deleted directory pending on Windows), fall
1120
+ * back to full scans, and recreate it only once the directory lists again.
1121
+ */
1122
+ function onShardWatchError(): void {
1123
+ closeShardWatcher();
1124
+ shardWatcherRetryAt = performance.now() + STATS_FULL_SCAN_INTERVAL_MS;
1125
+ shardIndex.requestFullScan();
1126
+ }
1127
+
1128
+ /** After a full scan: a watcher whose directory was replaced (Linux keeps it on the old inode, silently) is recreated. */
1129
+ async function checkShardWatcherDirectory(): Promise<void> {
1130
+ if (!shardWatcher || shardWatcherDirectory === undefined) return;
1131
+ const watched = shardWatcherDirectory;
1132
+ let current: string | undefined;
1133
+ try {
1134
+ const info = await statsReadFs().stat(SHARD_FILES_DIR);
1135
+ current = `${String(info.ino)}:${info.birthtimeMs}`;
1136
+ } catch {
1137
+ current = undefined;
1138
+ }
1139
+ if (current !== watched && shardWatcherDirectory === watched) {
1140
+ closeShardWatcher();
1141
+ shardWatcherRetryAt = 0;
1142
+ if (current !== undefined) ensureShardWatcher();
1143
+ }
1144
+ }
1145
+
1146
+ /** session_shutdown, first step: refuse new background work and stop its sources. */
1147
+ function closeStatsRefreshGate(): void {
1148
+ refreshScheduler.close();
1149
+ shardWatcherWanted = false;
1150
+ if (shardRefreshTimer !== null) clearTimeout(shardRefreshTimer);
1151
+ shardRefreshTimer = null;
1152
+ closeShardWatcher();
1153
+ }
1154
+
1155
+ /** Wait for every refresh, publish and scan in flight. */
1156
+ async function drainStatsRefresh(): Promise<void> {
1157
+ for (;;) {
1158
+ await Promise.all(Array.from(backgroundStatsTasks));
1159
+ await refreshScheduler.drain();
1160
+ await shardIndex.settled();
1161
+ if (backgroundStatsTasks.size === 0 && refreshScheduler.idle && !shardIndex.fullScanInFlight) return;
1162
+ }
1163
+ }
1164
+ statsRefreshSettledForTests.add(drainStatsRefresh);
1165
+
775
1166
  function buildCurrentStatsShard(state: "active" | "closed" = "active"): PersistedStatsShardV7 {
776
1167
  const now = Date.now();
777
1168
  const models: PersistedStatsShardV7["models"] = {};
@@ -808,14 +1199,12 @@ export default function (pi: ExtensionAPI) {
808
1199
  return shard;
809
1200
  }
810
1201
 
811
- function scheduleShardRefresh(ctx?: ExtensionContext, model?: PiModel): void {
1202
+ function scheduleShardRefresh(ctx?: ExtensionContext): void {
1203
+ if (refreshScheduler.isClosed) return;
812
1204
  if (shardRefreshTimer !== null) clearTimeout(shardRefreshTimer);
813
1205
  shardRefreshTimer = setTimeout(() => {
814
1206
  shardRefreshTimer = null;
815
- void waitForStatsRestore()
816
- .then(() => refreshShardAggregate())
817
- .then(() => publishStatus(ctx as ExtensionContext, model ?? ctx?.model))
818
- .catch(() => undefined);
1207
+ refreshAndPublishInBackground(ctx);
819
1208
  }, SHARD_REFRESH_DEBOUNCE_MS);
820
1209
  shardRefreshTimer.unref?.();
821
1210
  }
@@ -873,6 +1262,7 @@ export default function (pi: ExtensionAPI) {
873
1262
  const displayKey = modelKey(model);
874
1263
  const nextEpoch = await advanceModelStatsEpoch(displayKey);
875
1264
  modelEpochByKey.set(displayKey, nextEpoch);
1265
+ modelEpochSeq.set(displayKey, nextEpochSeq());
876
1266
  delete cacheStatsProcessByModel[displayKey];
877
1267
  delete cacheStatsTotalsByModel[displayKey];
878
1268
  for (const key of Object.keys(cacheStatsByModel)) {
@@ -886,6 +1276,8 @@ export default function (pi: ExtensionAPI) {
886
1276
 
887
1277
  async function resetCurrentSessionStats(): Promise<void> {
888
1278
  currentGlobalEpoch = await advanceGlobalStatsEpoch();
1279
+ globalEpochSeq = nextEpochSeq();
1280
+ voidModelEpochs(globalEpochSeq);
889
1281
  cacheStatsByModel = {};
890
1282
  cacheStatsTotalsByModel = {};
891
1283
  cacheStatsProcessByModel = {};
@@ -923,10 +1315,10 @@ export default function (pi: ExtensionAPI) {
923
1315
  persistTimer = null;
924
1316
  // A persist scheduled while a background restore runs (e.g. a routed
925
1317
  // model change without usage) must not race the restore's own write.
926
- void waitForStatsRestore()
1318
+ trackBackgroundStatsTask(waitForStatsRestore()
927
1319
  .then(() => persistCacheStats(ctx))
928
- .then(() => refreshShardAggregate())
929
- .catch(() => undefined);
1320
+ .then(() => refreshScheduler.background(false))
1321
+ .catch(() => undefined));
930
1322
  }, PERSIST_DEBOUNCE_MS);
931
1323
  persistTimer.unref?.();
932
1324
  }
@@ -940,9 +1332,23 @@ export default function (pi: ExtensionAPI) {
940
1332
  // Adopt resets performed by another Pi process before capturing the shard
941
1333
  // snapshot. Otherwise shutdown/command flush could rewrite stale local
942
1334
  // counters under an old epoch even though aggregation already hid them.
943
- await refreshShardAggregate();
1335
+ // A refresh that fails (a persistent read error) must not cost the
1336
+ // persist: write the counters under the epochs known so far.
1337
+ try {
1338
+ await refreshShardAggregate();
1339
+ } catch (error) {
1340
+ console.warn(`${LOG_PREFIX}: footer stats refresh before persisting failed`, error);
1341
+ }
944
1342
  await persistCacheStats(ctx, lifecycleState);
945
- await refreshShardAggregate();
1343
+ try {
1344
+ await refreshShardAggregate();
1345
+ } catch (error) {
1346
+ console.warn(`${LOG_PREFIX}: footer stats refresh after persisting failed`, error);
1347
+ }
1348
+ // That refresh may have continued an absorbed own shard under a new id
1349
+ // and queued its write: let it land before the flush (and a shutdown)
1350
+ // returns, or interactive mode's process.exit could cut it off.
1351
+ await enqueuePersist(() => Promise.resolve());
946
1352
  }
947
1353
 
948
1354
  async function rollOverStatsIfNeeded(ctx?: ExtensionContext): Promise<void> {
@@ -954,19 +1360,18 @@ export default function (pi: ExtensionAPI) {
954
1360
  clearTimeout(persistTimer);
955
1361
  persistTimer = null;
956
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;
957
1368
  // Preserve yesterday under its original UUID/day before clearing daily
958
1369
  // counters. Each day owns a new shard so total never includes yesterday.
959
- await refreshShardAggregate();
960
- await persistCacheStats(ctx, "closed");
961
- retiredShards.set(instanceId, buildCurrentStatsShard("closed"));
962
- instanceId = randomUUID();
963
- instanceShardPath = join(SHARD_FILES_DIR, `${instanceId}.json`);
964
- persistedOwnShards = [];
965
- shardDay = day;
966
- shardCreatedAt = Date.now();
1370
+ const closing = retireCurrentShard(day, ctx);
967
1371
  cacheStatsProcessByModel = {};
968
1372
  cacheStatsLegacyFamily = emptyAllCacheStats();
969
1373
  lastStatusText = undefined;
1374
+ await closing;
970
1375
  await persistCacheStats(ctx);
971
1376
  await refreshShardAggregate();
972
1377
  })();
@@ -974,6 +1379,65 @@ export default function (pi: ExtensionAPI) {
974
1379
  finally { rolloverPromise = undefined; }
975
1380
  }
976
1381
 
1382
+ /**
1383
+ * Retire the current shard: snapshot it closed, keep that snapshot as its
1384
+ * retired copy, continue under a new id on `day`, and queue the snapshot's
1385
+ * write (a failure only warns: the retired copy keeps counting it). The
1386
+ * written and the retired copy are one object, so once its write lands
1387
+ * the file (same updatedAt) replaces the retired copy. Synchronous up to
1388
+ * the queued write, so usage recorded after this goes to the new id.
1389
+ */
1390
+ function retireCurrentShard(day: string, ctx?: ExtensionContext): Promise<void> {
1391
+ if (persistTimer !== null) {
1392
+ clearTimeout(persistTimer);
1393
+ persistTimer = null;
1394
+ }
1395
+ const closed = buildCurrentStatsShard("closed");
1396
+ const closedPath = instanceShardPath;
1397
+ retiredShards.set(instanceId, closed);
1398
+ instanceId = randomUUID();
1399
+ instanceShardPath = join(SHARD_FILES_DIR, `${instanceId}.json`);
1400
+ persistedOwnShards = [];
1401
+ shardCreatedAt = Date.now();
1402
+ shardDay = day;
1403
+ return enqueuePersist(async () => {
1404
+ try {
1405
+ await writeStatsShardV7(closedPath, closed);
1406
+ } catch (error) {
1407
+ console.warn(`${LOG_PREFIX}: failed to persist a retired stats shard`, error);
1408
+ if (!persistenceWarningShown) {
1409
+ persistenceWarningShown = true;
1410
+ ctx?.ui.notify(
1411
+ `${LOG_PREFIX}: failed to persist footer stats; using in-memory stats for this process.`,
1412
+ "warning",
1413
+ );
1414
+ }
1415
+ }
1416
+ });
1417
+ }
1418
+
1419
+ /**
1420
+ * session_start calls this instance has handled. Pi 1.3 builds a new
1421
+ * extension instance for every session (new/resume/fork/reload), but a
1422
+ * host that keeps one instance across sessions sends it a second
1423
+ * session_start, which clears the in-memory counters.
1424
+ */
1425
+ let sessionStartsHandled = 0;
1426
+
1427
+ /**
1428
+ * Before a second session_start on the same instance clears the counters,
1429
+ * retire the shard holding them and continue under a new id, as the day
1430
+ * rollover does. Without this, the next persist rewrites the old id with
1431
+ * the cleared counters and the earlier session's usage for the day is lost
1432
+ * (the shutdown flush closed it, but the id was reused). See
1433
+ * retireCurrentShard.
1434
+ */
1435
+ function retireShardForSessionStart(): void {
1436
+ // The retired shard keeps its own day; the new id starts on today's, so
1437
+ // the restore does not roll over again into an empty extra shard.
1438
+ void retireCurrentShard(currentLocalDay());
1439
+ }
1440
+
977
1441
  /**
978
1442
  * Synchronous part of a session restore: reset in-memory state immediately
979
1443
  * at session_start, so usage recorded before the background disk restore
@@ -986,6 +1450,7 @@ export default function (pi: ExtensionAPI) {
986
1450
  countersSession++;
987
1451
  cacheStatsLegacyFamily = emptyAllCacheStats();
988
1452
  modelEpochByKey.clear();
1453
+ voidModelEpochs(nextEpochSeq());
989
1454
  modelApiByKey.clear();
990
1455
  modelNameByKey.clear();
991
1456
  if (reason === "reload") {
@@ -999,11 +1464,14 @@ export default function (pi: ExtensionAPI) {
999
1464
  // message_end syncs the epoch before recording. If the disk epoch differs
1000
1465
  // now, a reset happened after that usage: adopt it and drop the stale
1001
1466
  // process bucket instead of re-labelling old counters with the new epoch.
1002
- const latestGlobalEpoch = await readGlobalStatsEpoch();
1003
- if (latestGlobalEpoch !== currentGlobalEpoch) {
1004
- currentGlobalEpoch = latestGlobalEpoch;
1467
+ // A read error keeps the epoch known so far (it is not "no reset").
1468
+ const seq = nextEpochSeq();
1469
+ const latest = await readEpochFileWithRetry(SHARD_GLOBAL_EPOCH_PATH, initialEpoch("global"));
1470
+ if (latest.ok && acceptGlobalEpochRead(seq) && latest.epoch !== currentGlobalEpoch) {
1471
+ currentGlobalEpoch = latest.epoch;
1005
1472
  cacheStatsProcessByModel = {};
1006
1473
  modelEpochByKey.clear();
1474
+ voidModelEpochs(seq);
1007
1475
  modelApiByKey.clear();
1008
1476
  modelNameByKey.clear();
1009
1477
  }
@@ -1166,6 +1634,12 @@ export default function (pi: ExtensionAPI) {
1166
1634
  // publish a stale footer. Handlers that read or persist stats await
1167
1635
  // waitForStatsRestore() first.
1168
1636
  const generation = ++statsRestoreGeneration;
1637
+ // The same extension instance lives on across session switches
1638
+ // (shutdown, then start): reopen what the shutdown closed.
1639
+ refreshScheduler.open();
1640
+ latestStatsCtx = ctx;
1641
+ const tui = ctx.mode === "tui";
1642
+ if (sessionStartsHandled++ > 0) retireShardForSessionStart();
1169
1643
  resetStatsForSessionStart(event.reason, ctx);
1170
1644
  const previousRestore = statsRestorePromise;
1171
1645
  statsRestorePromise = previousRestore
@@ -1177,25 +1651,26 @@ export default function (pi: ExtensionAPI) {
1177
1651
  })
1178
1652
  .catch((error) => {
1179
1653
  console.warn(`${LOG_PREFIX}: failed to restore cache stats`, error);
1654
+ })
1655
+ .then(() => {
1656
+ // TUI only, and only after the restore created the directory (2.9.3
1657
+ // watched it on the startup path and stayed without a watcher for
1658
+ // the whole process when it did not exist yet).
1659
+ if (tui && generation === statsRestoreGeneration && !refreshScheduler.isClosed) {
1660
+ shardWatcherWanted = true;
1661
+ shardWatcherRetryAt = 0;
1662
+ ensureShardWatcher();
1663
+ }
1180
1664
  });
1181
1665
  latestStatsRestoreForTests = statsRestorePromise;
1182
- if (ctx.mode === "tui" && !shardWatcher) {
1183
- try {
1184
- shardWatcher = watch(SHARD_FILES_DIR, () => scheduleShardRefresh(ctx));
1185
- shardWatcher.unref?.();
1186
- } catch {
1187
- // Lifecycle and explicit command refreshes remain authoritative.
1188
- }
1189
- }
1190
1666
  });
1191
1667
 
1192
1668
  pi.on("tool_execution_end", async (event, ctx) => {
1193
1669
  // Pi 0.99+ codemode scripts run nested tool calls in parallel; the calling
1194
1670
  // tool's own end event follows them, so one refresh covers the batch.
1195
1671
  if (isNonEmptyString((event as { parentToolCallId?: unknown } | undefined)?.parentToolCallId)) return;
1196
- await waitForStatsRestore();
1197
- await refreshShardAggregate();
1198
- await publishStatus(ctx);
1672
+ // Pi awaits this handler before the next turn: refresh in the background.
1673
+ refreshAndPublishInBackground(ctx);
1199
1674
  });
1200
1675
 
1201
1676
  // Pi 0.86+ native prompt-cache warming: keep it running for models whose
@@ -1213,20 +1688,20 @@ export default function (pi: ExtensionAPI) {
1213
1688
  // a record consumed out of order) so they cannot be correlated with the
1214
1689
  // next run's messages.
1215
1690
  providerRequestStates.length = 0;
1216
- await waitForStatsRestore();
1217
- await refreshShardAggregate();
1218
- await publishStatus(ctx);
1691
+ refreshAndPublishInBackground(ctx);
1219
1692
  });
1220
1693
 
1221
1694
  pi.on("session_shutdown", async (_event, ctx) => {
1222
1695
  try {
1696
+ // Close the gate first (no new background refresh, watcher event or
1697
+ // scan-triggered publish), then let what is in flight finish, then
1698
+ // flush. The flush's own refreshes are awaited and still run.
1699
+ closeStatsRefreshGate();
1223
1700
  await waitForStatsRestore();
1701
+ await drainStatsRefresh();
1224
1702
  await flushPersistCacheStats(ctx, "closed");
1225
1703
  } finally {
1226
- if (shardRefreshTimer !== null) clearTimeout(shardRefreshTimer);
1227
- shardRefreshTimer = null;
1228
- shardWatcher?.close();
1229
- shardWatcher = undefined;
1704
+ closeStatsRefreshGate();
1230
1705
  latestCacheHint = undefined;
1231
1706
  providerRequestStates.length = 0;
1232
1707
  delete getProtocolGlobal().__piCacheOptimizerCacheKey__;
@@ -1238,7 +1713,7 @@ export default function (pi: ExtensionAPI) {
1238
1713
  pi.on("model_select", async (event, ctx) => {
1239
1714
  if (runtimeOptimizerEnabled) notifyCacheCompatIfNeeded(resolveRouteModel(event.model, ctx) ?? event.model, ctx, warnedModels);
1240
1715
  await waitForStatsRestore();
1241
- await refreshShardAggregate();
1716
+ await refreshShardAggregate({ full: false });
1242
1717
  await publishStatus(ctx, event.model);
1243
1718
  });
1244
1719
 
@@ -1760,16 +2235,23 @@ export default function (pi: ExtensionAPI) {
1760
2235
  // routed model. The process bucket is intentionally never persisted.
1761
2236
  if (statsModel) {
1762
2237
  const key = modelKey(statsModel);
1763
- const latestGlobalEpoch = await readGlobalStatsEpoch();
1764
- const latestModelEpoch = await readModelStatsEpoch(key);
1765
- if (currentGlobalEpoch !== latestGlobalEpoch) {
1766
- currentGlobalEpoch = latestGlobalEpoch;
2238
+ // Fresh reads, numbered like every footer epoch read: a refresh that
2239
+ // read older epochs can no longer switch back and clear this usage. A
2240
+ // read error keeps the epochs known so far.
2241
+ const seq = nextEpochSeq();
2242
+ const [latestGlobal, latestModel] = await Promise.all([
2243
+ readEpochFileWithRetry(SHARD_GLOBAL_EPOCH_PATH, initialEpoch("global")),
2244
+ readEpochFileWithRetry(modelEpochPath(key), initialEpoch(`model:${key}`)),
2245
+ ]);
2246
+ if (latestGlobal.ok && acceptGlobalEpochRead(seq) && currentGlobalEpoch !== latestGlobal.epoch) {
2247
+ currentGlobalEpoch = latestGlobal.epoch;
1767
2248
  cacheStatsProcessByModel = {};
1768
2249
  modelEpochByKey.clear();
2250
+ voidModelEpochs(seq - 1);
1769
2251
  }
1770
- if (modelEpochByKey.get(key) !== latestModelEpoch) {
2252
+ if (latestModel.ok && acceptModelEpochReadForUsage(seq, key) && modelEpochByKey.get(key) !== latestModel.epoch) {
1771
2253
  delete cacheStatsProcessByModel[key];
1772
- modelEpochByKey.set(key, latestModelEpoch);
2254
+ modelEpochByKey.set(key, latestModel.epoch);
1773
2255
  }
1774
2256
  modelApiByKey.set(key, statsModel.api ?? "");
1775
2257
  modelNameByKey.set(key, statsModel.name || statsModel.id);
@@ -1781,20 +2263,19 @@ export default function (pi: ExtensionAPI) {
1781
2263
  addUsageToCacheStats(getStatsForModel(undefined, adapter), usage);
1782
2264
  }
1783
2265
 
1784
- await waitForStatsRestore();
1785
2266
  schedulePersistCacheStats(ctx);
1786
- await refreshShardAggregate();
1787
- // A late response from an older selection must not replace the active
1788
- // footer. Only a routed response that still belongs to the currently
1789
- // selected virtual/router model may publish its physical model directly.
1790
- const responseBelongsToCurrentSelection =
1791
- requestCorrelationForMessage.selectionModelKey !== undefined &&
1792
- ctx.model !== undefined &&
1793
- requestCorrelationForMessage.selectionModelKey === modelKey(ctx.model);
1794
- await publishStatus(
1795
- ctx,
1796
- requestSelectionIsVirtual && responseBelongsToCurrentSelection ? statsModel : ctx.model,
1797
- );
2267
+ // The counters above are already updated in memory; the refresh and the
2268
+ // footer update run in the background (Pi awaits message_end).
2269
+ refreshAndPublishInBackground(ctx, () => {
2270
+ // A late response from an older selection must not replace the active
2271
+ // footer. Only a routed response that still belongs to the currently
2272
+ // selected virtual/router model may publish its physical model directly.
2273
+ const responseBelongsToCurrentSelection =
2274
+ requestCorrelationForMessage.selectionModelKey !== undefined &&
2275
+ ctx.model !== undefined &&
2276
+ requestCorrelationForMessage.selectionModelKey === modelKey(ctx.model);
2277
+ return requestSelectionIsVirtual && responseBelongsToCurrentSelection ? statsModel : ctx.model;
2278
+ });
1798
2279
  });
1799
2280
 
1800
2281
  // ────────────────────────────────────────────────────────────────