pi-cache-optimizer 2.9.3 → 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.
@@ -692,23 +721,287 @@ 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);
@@ -717,9 +1010,14 @@ export default function (pi: ExtensionAPI) {
717
1010
  for (const id of archive.absorbedIds) retiredShards.delete(id);
718
1011
  const persistedShards = rawShards.filter((shard) => !archive.absorbedIds.has(shard.instanceId));
719
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.
720
1017
  const shards = persistedShards.filter((shard) => shard.instanceId !== instanceId);
721
1018
  shards.push(...retiredShards.values());
722
1019
  const trailing = currentSessionHashSet ? [buildCurrentStatsShard()] : [];
1020
+ const epochSource: ShardEpochs = { globalEpoch: currentGlobalEpoch, modelEpoch: (key) => aggregationModelEpoch(key, epochs) };
723
1021
  // Keep lifetime session footer data separate from daily totals/commands.
724
1022
  // Both equal aggregating [...shards, ...archive.shards, ...trailing]
725
1023
  // (issue #28 review H): the current day only sees archive entries of that
@@ -727,37 +1025,12 @@ export default function (pi: ExtensionAPI) {
727
1025
  // merges the archive's pre-reduced per-(session, model) entries instead
728
1026
  // of re-aggregating every archived bucket. The all-days view is only read
729
1027
  // 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] : []),
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,
735
1032
  );
736
1033
 
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
1034
  cacheStatsByModel = {};
762
1035
  for (const [sessionHash, models] of Object.entries(sessionAggregate.bySession)) {
763
1036
  for (const [key, stats] of Object.entries(models)) {
@@ -772,6 +1045,114 @@ export default function (pi: ExtensionAPI) {
772
1045
  return aggregate;
773
1046
  }
774
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
+
775
1156
  function buildCurrentStatsShard(state: "active" | "closed" = "active"): PersistedStatsShardV7 {
776
1157
  const now = Date.now();
777
1158
  const models: PersistedStatsShardV7["models"] = {};
@@ -808,14 +1189,12 @@ export default function (pi: ExtensionAPI) {
808
1189
  return shard;
809
1190
  }
810
1191
 
811
- function scheduleShardRefresh(ctx?: ExtensionContext, model?: PiModel): void {
1192
+ function scheduleShardRefresh(ctx?: ExtensionContext): void {
1193
+ if (refreshScheduler.isClosed) return;
812
1194
  if (shardRefreshTimer !== null) clearTimeout(shardRefreshTimer);
813
1195
  shardRefreshTimer = setTimeout(() => {
814
1196
  shardRefreshTimer = null;
815
- void waitForStatsRestore()
816
- .then(() => refreshShardAggregate())
817
- .then(() => publishStatus(ctx as ExtensionContext, model ?? ctx?.model))
818
- .catch(() => undefined);
1197
+ refreshAndPublishInBackground(ctx);
819
1198
  }, SHARD_REFRESH_DEBOUNCE_MS);
820
1199
  shardRefreshTimer.unref?.();
821
1200
  }
@@ -873,6 +1252,7 @@ export default function (pi: ExtensionAPI) {
873
1252
  const displayKey = modelKey(model);
874
1253
  const nextEpoch = await advanceModelStatsEpoch(displayKey);
875
1254
  modelEpochByKey.set(displayKey, nextEpoch);
1255
+ modelEpochSeq.set(displayKey, nextEpochSeq());
876
1256
  delete cacheStatsProcessByModel[displayKey];
877
1257
  delete cacheStatsTotalsByModel[displayKey];
878
1258
  for (const key of Object.keys(cacheStatsByModel)) {
@@ -886,6 +1266,8 @@ export default function (pi: ExtensionAPI) {
886
1266
 
887
1267
  async function resetCurrentSessionStats(): Promise<void> {
888
1268
  currentGlobalEpoch = await advanceGlobalStatsEpoch();
1269
+ globalEpochSeq = nextEpochSeq();
1270
+ voidModelEpochs(globalEpochSeq);
889
1271
  cacheStatsByModel = {};
890
1272
  cacheStatsTotalsByModel = {};
891
1273
  cacheStatsProcessByModel = {};
@@ -923,10 +1305,10 @@ export default function (pi: ExtensionAPI) {
923
1305
  persistTimer = null;
924
1306
  // A persist scheduled while a background restore runs (e.g. a routed
925
1307
  // model change without usage) must not race the restore's own write.
926
- void waitForStatsRestore()
1308
+ trackBackgroundStatsTask(waitForStatsRestore()
927
1309
  .then(() => persistCacheStats(ctx))
928
- .then(() => refreshShardAggregate())
929
- .catch(() => undefined);
1310
+ .then(() => refreshScheduler.background(false))
1311
+ .catch(() => undefined));
930
1312
  }, PERSIST_DEBOUNCE_MS);
931
1313
  persistTimer.unref?.();
932
1314
  }
@@ -940,9 +1322,23 @@ export default function (pi: ExtensionAPI) {
940
1322
  // Adopt resets performed by another Pi process before capturing the shard
941
1323
  // snapshot. Otherwise shutdown/command flush could rewrite stale local
942
1324
  // counters under an old epoch even though aggregation already hid them.
943
- 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
+ }
944
1332
  await persistCacheStats(ctx, lifecycleState);
945
- 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());
946
1342
  }
947
1343
 
948
1344
  async function rollOverStatsIfNeeded(ctx?: ExtensionContext): Promise<void> {
@@ -986,6 +1382,7 @@ export default function (pi: ExtensionAPI) {
986
1382
  countersSession++;
987
1383
  cacheStatsLegacyFamily = emptyAllCacheStats();
988
1384
  modelEpochByKey.clear();
1385
+ voidModelEpochs(nextEpochSeq());
989
1386
  modelApiByKey.clear();
990
1387
  modelNameByKey.clear();
991
1388
  if (reason === "reload") {
@@ -999,11 +1396,14 @@ export default function (pi: ExtensionAPI) {
999
1396
  // message_end syncs the epoch before recording. If the disk epoch differs
1000
1397
  // now, a reset happened after that usage: adopt it and drop the stale
1001
1398
  // process bucket instead of re-labelling old counters with the new epoch.
1002
- const latestGlobalEpoch = await readGlobalStatsEpoch();
1003
- if (latestGlobalEpoch !== currentGlobalEpoch) {
1004
- 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;
1005
1404
  cacheStatsProcessByModel = {};
1006
1405
  modelEpochByKey.clear();
1406
+ voidModelEpochs(seq);
1007
1407
  modelApiByKey.clear();
1008
1408
  modelNameByKey.clear();
1009
1409
  }
@@ -1166,6 +1566,11 @@ export default function (pi: ExtensionAPI) {
1166
1566
  // publish a stale footer. Handlers that read or persist stats await
1167
1567
  // waitForStatsRestore() first.
1168
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";
1169
1574
  resetStatsForSessionStart(event.reason, ctx);
1170
1575
  const previousRestore = statsRestorePromise;
1171
1576
  statsRestorePromise = previousRestore
@@ -1177,25 +1582,26 @@ export default function (pi: ExtensionAPI) {
1177
1582
  })
1178
1583
  .catch((error) => {
1179
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
+ }
1180
1595
  });
1181
1596
  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
1597
  });
1191
1598
 
1192
1599
  pi.on("tool_execution_end", async (event, ctx) => {
1193
1600
  // Pi 0.99+ codemode scripts run nested tool calls in parallel; the calling
1194
1601
  // tool's own end event follows them, so one refresh covers the batch.
1195
1602
  if (isNonEmptyString((event as { parentToolCallId?: unknown } | undefined)?.parentToolCallId)) return;
1196
- await waitForStatsRestore();
1197
- await refreshShardAggregate();
1198
- await publishStatus(ctx);
1603
+ // Pi awaits this handler before the next turn: refresh in the background.
1604
+ refreshAndPublishInBackground(ctx);
1199
1605
  });
1200
1606
 
1201
1607
  // Pi 0.86+ native prompt-cache warming: keep it running for models whose
@@ -1213,20 +1619,20 @@ export default function (pi: ExtensionAPI) {
1213
1619
  // a record consumed out of order) so they cannot be correlated with the
1214
1620
  // next run's messages.
1215
1621
  providerRequestStates.length = 0;
1216
- await waitForStatsRestore();
1217
- await refreshShardAggregate();
1218
- await publishStatus(ctx);
1622
+ refreshAndPublishInBackground(ctx);
1219
1623
  });
1220
1624
 
1221
1625
  pi.on("session_shutdown", async (_event, ctx) => {
1222
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();
1223
1631
  await waitForStatsRestore();
1632
+ await drainStatsRefresh();
1224
1633
  await flushPersistCacheStats(ctx, "closed");
1225
1634
  } finally {
1226
- if (shardRefreshTimer !== null) clearTimeout(shardRefreshTimer);
1227
- shardRefreshTimer = null;
1228
- shardWatcher?.close();
1229
- shardWatcher = undefined;
1635
+ closeStatsRefreshGate();
1230
1636
  latestCacheHint = undefined;
1231
1637
  providerRequestStates.length = 0;
1232
1638
  delete getProtocolGlobal().__piCacheOptimizerCacheKey__;
@@ -1238,7 +1644,7 @@ export default function (pi: ExtensionAPI) {
1238
1644
  pi.on("model_select", async (event, ctx) => {
1239
1645
  if (runtimeOptimizerEnabled) notifyCacheCompatIfNeeded(resolveRouteModel(event.model, ctx) ?? event.model, ctx, warnedModels);
1240
1646
  await waitForStatsRestore();
1241
- await refreshShardAggregate();
1647
+ await refreshShardAggregate({ full: false });
1242
1648
  await publishStatus(ctx, event.model);
1243
1649
  });
1244
1650
 
@@ -1760,16 +2166,23 @@ export default function (pi: ExtensionAPI) {
1760
2166
  // routed model. The process bucket is intentionally never persisted.
1761
2167
  if (statsModel) {
1762
2168
  const key = modelKey(statsModel);
1763
- const latestGlobalEpoch = await readGlobalStatsEpoch();
1764
- const latestModelEpoch = await readModelStatsEpoch(key);
1765
- if (currentGlobalEpoch !== latestGlobalEpoch) {
1766
- 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;
1767
2179
  cacheStatsProcessByModel = {};
1768
2180
  modelEpochByKey.clear();
2181
+ voidModelEpochs(seq - 1);
1769
2182
  }
1770
- if (modelEpochByKey.get(key) !== latestModelEpoch) {
2183
+ if (latestModel.ok && acceptModelEpochReadForUsage(seq, key) && modelEpochByKey.get(key) !== latestModel.epoch) {
1771
2184
  delete cacheStatsProcessByModel[key];
1772
- modelEpochByKey.set(key, latestModelEpoch);
2185
+ modelEpochByKey.set(key, latestModel.epoch);
1773
2186
  }
1774
2187
  modelApiByKey.set(key, statsModel.api ?? "");
1775
2188
  modelNameByKey.set(key, statsModel.name || statsModel.id);
@@ -1781,20 +2194,19 @@ export default function (pi: ExtensionAPI) {
1781
2194
  addUsageToCacheStats(getStatsForModel(undefined, adapter), usage);
1782
2195
  }
1783
2196
 
1784
- await waitForStatsRestore();
1785
2197
  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
- );
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
+ });
1798
2210
  });
1799
2211
 
1800
2212
  // ────────────────────────────────────────────────────────────────