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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cache-optimizer",
3
- "version": "2.9.3",
3
+ "version": "2.10.0",
4
4
  "description": "Improve Pi prompt/KV cache hit rates with stable prompts, OpenAI-compatible cache keys, proxy compat warnings, and footer cache stats.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -18,9 +18,9 @@ export const CACHE_OPTIMIZER_COMMANDS = [
18
18
  "rollback",
19
19
  ] as const;
20
20
 
21
- export const CACHE_OPTIMIZER_CONFIG_ARGUMENTS = ["footer-mode", "prompt-rewrite", "virtual-rewrite", "skill-compression", "openai-cache-key", "tool-order", "zero-price-warming", "reset"] as const;
21
+ export const CACHE_OPTIMIZER_CONFIG_ARGUMENTS = ["footer-mode", "prompt-rewrite", "virtual-rewrite", "skill-compression", "openai-cache-key", "tool-order", "zero-price-warming", "stats-incremental", "reset"] as const;
22
22
 
23
- export const CACHE_OPTIMIZER_FEATURE_COMMANDS = ["prompt-rewrite", "virtual-rewrite", "skill-compression", "openai-cache-key", "tool-order", "zero-price-warming"] as const;
23
+ export const CACHE_OPTIMIZER_FEATURE_COMMANDS = ["prompt-rewrite", "virtual-rewrite", "skill-compression", "openai-cache-key", "tool-order", "zero-price-warming", "stats-incremental"] as const;
24
24
 
25
25
  export const CACHE_OPTIMIZER_FEATURE_VALUES = ["on", "off"] as const;
26
26
 
@@ -33,6 +33,7 @@ export const FEATURE_COMMAND_MAP: Record<string, PersistedCacheOptimizerFeature>
33
33
  "openai-cache-key": "openAICacheKey",
34
34
  "tool-order": "toolOrder",
35
35
  "zero-price-warming": "zeroPriceWarming",
36
+ "stats-incremental": "statsIncremental",
36
37
  };
37
38
 
38
39
  export const CACHE_OPTIMIZER_STATS_ARGUMENTS = ["all", "contributors"] as const;
package/src/command.ts CHANGED
@@ -173,7 +173,7 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
173
173
  const resolved = resolveFooterStatsMode(persistedFooterStatsMode);
174
174
  cmdCtx.ui.notify(
175
175
  `Usage: /cache-optimizer config footer-mode total|session|process\n` +
176
- ` /cache-optimizer config prompt-rewrite|virtual-rewrite|skill-compression|openai-cache-key|tool-order|zero-price-warming on|off\n` +
176
+ ` /cache-optimizer config prompt-rewrite|virtual-rewrite|skill-compression|openai-cache-key|tool-order|zero-price-warming|stats-incremental on|off\n` +
177
177
  ` /cache-optimizer config reset\n` +
178
178
  `Current footer mode: ${resolved.mode} (${resolved.source})`,
179
179
  "info",
@@ -1007,7 +1007,7 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
1007
1007
  diagnosis.push(" stats all — Show detailed totals for every model across all local sessions");
1008
1008
  diagnosis.push(" stats contributors — Show per-session contributors for the active model");
1009
1009
  diagnosis.push(" compat — Show compat suggestion with edit location");
1010
- diagnosis.push(" config prompt-rewrite|virtual-rewrite|skill-compression|openai-cache-key|tool-order|zero-price-warming on|off — Persist feature settings");
1010
+ diagnosis.push(" config prompt-rewrite|virtual-rewrite|skill-compression|openai-cache-key|tool-order|zero-price-warming|stats-incremental on|off — Persist feature settings");
1011
1011
  diagnosis.push(" config footer-mode total|session|process — Persist the footer stats mode");
1012
1012
  diagnosis.push(" config reset — Remove persistent feature overrides");
1013
1013
  diagnosis.push(" fix — Auto-fix compat issues (writes models.json or extension config, requires UI)");
package/src/config.ts CHANGED
@@ -4,7 +4,7 @@ import { STATE_DIR } from "./paths.ts";
4
4
  import { PI_CACHE_RETENTION_ENV, STARTUP_CACHE_RETENTION_ENV, requestLongCacheRetention, restoreCacheRetentionEnv } from "./retention.ts";
5
5
  import { type Stats, readFileSync } from "node:fs";
6
6
  import { lstat, mkdir, readFile } from "node:fs/promises";
7
- import { dirname, join } from "node:path";
7
+ import { dirname, isAbsolute, join } from "node:path";
8
8
 
9
9
 
10
10
  export const CONFIG_FILE_PATH = join(STATE_DIR, "pi-cache-optimizer-config.json");
@@ -19,6 +19,19 @@ export const NO_ZERO_PRICE_WARMING_ENV = "PI_CACHE_OPTIMIZER_NO_ZERO_PRICE_WARMI
19
19
 
20
20
  export const FOOTER_MODE_ENV = "PI_CACHE_OPTIMIZER_FOOTER_MODE";
21
21
 
22
+ /** Kill switch for the incremental footer refresh (2.10): 0/false/off/no restores the 2.9.3 full scan per refresh. */
23
+ export const STATS_INCREMENTAL_ENV = "PI_CACHE_OPTIMIZER_STATS_INCREMENTAL";
24
+
25
+ /** Opt-in check (1/true/on/yes) that the footer's shard cache never misses a change the file identity hides (see TieredShardIndex.verifyCachedContents). */
26
+ export const STATS_VERIFY_ENV = "PI_CACHE_OPTIMIZER_STATS_VERIFY";
27
+
28
+ export function isStatsVerifyEnabled(env: MutableEnv = process.env): boolean {
29
+ return isEnabledEnv(env[STATS_VERIFY_ENV]);
30
+ }
31
+
32
+ /** Opt-in footer refresh timing log: 1/true/on/yes writes JSON lines to STATS_TIMING_LOG_PATH; an absolute path writes there. */
33
+ export const STATS_TIMING_ENV = "PI_CACHE_OPTIMIZER_STATS_TIMING";
34
+
22
35
  export type FooterStatsMode = "session" | "total" | "process";
23
36
 
24
37
  export type FooterStatsModeSource = "config" | "env" | "default";
@@ -28,7 +41,7 @@ export type PersistedCacheOptimizerConfigV1 = {
28
41
  footerMode?: FooterStatsMode;
29
42
  };
30
43
 
31
- export type PersistedCacheOptimizerFeature = "promptRewrite" | "virtualRewrite" | "skillCompression" | "openAICacheKey" | "toolOrder" | "zeroPriceWarming";
44
+ export type PersistedCacheOptimizerFeature = "promptRewrite" | "virtualRewrite" | "skillCompression" | "openAICacheKey" | "toolOrder" | "zeroPriceWarming" | "statsIncremental";
32
45
 
33
46
  export type PersistedCacheOptimizerConfigV2 = {
34
47
  version: 2;
@@ -71,6 +84,7 @@ export function featureEnabled(
71
84
  if (feature === "promptRewrite" || feature === "skillCompression" || feature === "zeroPriceWarming") {
72
85
  return !isEnabledEnv(env[envName]);
73
86
  }
87
+ if (feature === "statsIncremental") return !isDisabledEnv(env[envName]);
74
88
  return isEnabledEnv(env[envName]) || defaultValue;
75
89
  }
76
90
 
@@ -79,6 +93,35 @@ export function isZeroPriceWarmingEnabled(): boolean {
79
93
  return runtimeOptimizerEnabled && featureEnabled("zeroPriceWarming", NO_ZERO_PRICE_WARMING_ENV, true);
80
94
  }
81
95
 
96
+ /**
97
+ * Incremental footer refresh (tiered shard index). Unlike the optimizer
98
+ * features it does not follow /cache-optimizer disable: it changes how stats
99
+ * are read, not what is sent to providers.
100
+ *
101
+ * Kill switch: `/cache-optimizer config stats-incremental off` (persisted,
102
+ * wins over the environment like every feature setting) or
103
+ * PI_CACHE_OPTIMIZER_STATS_INCREMENTAL=0. Note: versions before 2.10 reject a
104
+ * config file with a feature key they do not know, so while this key is
105
+ * persisted an older Pi sharing the agent directory falls back to its
106
+ * defaults; the README says so.
107
+ */
108
+ export function isStatsIncrementalEnabled(
109
+ env: MutableEnv = process.env,
110
+ config: PersistedCacheOptimizerConfigV3 = persistedCacheOptimizerConfig,
111
+ ): boolean {
112
+ return featureEnabled("statsIncremental", STATS_INCREMENTAL_ENV, true, env, config);
113
+ }
114
+
115
+ export const STATS_TIMING_LOG_PATH = join(STATE_DIR, "pi-cache-optimizer-stats-timing.jsonl");
116
+
117
+ /** Where the opt-in refresh timing log goes, or undefined when it is off. */
118
+ export function statsTimingLogPath(env: MutableEnv = process.env): string | undefined {
119
+ const value = env[STATS_TIMING_ENV]?.trim();
120
+ if (!value || isDisabledEnv(value)) return undefined;
121
+ if (isEnabledEnv(value)) return STATS_TIMING_LOG_PATH;
122
+ return isAbsolute(value) ? value : undefined;
123
+ }
124
+
82
125
  export function isToolOrderEnabled(env: MutableEnv = process.env): boolean {
83
126
  return runtimeOptimizerEnabled && featureEnabled("toolOrder", TOOL_ORDER_ENV, false);
84
127
  }
@@ -101,7 +144,7 @@ export function parsePersistedCacheOptimizerConfig(value: unknown): PersistedCac
101
144
  const rawFeatures = record.version === 3 ? record.features : undefined;
102
145
  if (rawFeatures !== undefined && !asRecord(rawFeatures)) return undefined;
103
146
  const featuresRecord = asRecord(rawFeatures);
104
- const featureNames = new Set<PersistedCacheOptimizerFeature>(["promptRewrite", "virtualRewrite", "skillCompression", "openAICacheKey", "toolOrder", "zeroPriceWarming"]);
147
+ const featureNames = new Set<PersistedCacheOptimizerFeature>(["promptRewrite", "virtualRewrite", "skillCompression", "openAICacheKey", "toolOrder", "zeroPriceWarming", "statsIncremental"]);
105
148
  if (featuresRecord && Object.keys(featuresRecord).some((key) => !featureNames.has(key as PersistedCacheOptimizerFeature) || typeof featuresRecord[key] !== "boolean")) return undefined;
106
149
 
107
150
  const rawPromptCacheKey = record.promptCacheKey;
@@ -362,6 +405,7 @@ export function formatPersistentFeatureConfig(): string {
362
405
  ["OpenAI cache key", "openAICacheKey", NO_OPENAI_CACHE_KEY_ENV, true],
363
406
  ["Tool ordering", "toolOrder", TOOL_ORDER_ENV, false],
364
407
  ["Zero-price cache warming", "zeroPriceWarming", NO_ZERO_PRICE_WARMING_ENV, true],
408
+ ["Incremental footer refresh", "statsIncremental", STATS_INCREMENTAL_ENV, true],
365
409
  ];
366
410
  for (const [label, feature, envName, defaultValue] of entries) {
367
411
  const hasEnv = process.env[envName] !== undefined || (feature === "openAICacheKey" && process.env[OPENAI_CACHE_KEY_ENV] !== undefined);
@@ -66,6 +66,7 @@ import {
66
66
  type ShardAggregate,
67
67
  type ShardAggregator,
68
68
  type ShardContribution,
69
+ type ShardEpochs,
69
70
  SHARD_CLEANUP_MARKER_PATH,
70
71
  SHARD_FILES_DIR,
71
72
  SHARD_IO_CONCURRENCY,
@@ -76,6 +77,7 @@ import {
76
77
  acquireStatsMaintenanceLock,
77
78
  cleanupStatsShardsV7,
78
79
  cloneCacheStats,
80
+ createShardAggregatorSync,
79
81
  createShardAggregatorV7,
80
82
  currentLocalDay,
81
83
  isMaintenanceMarkerDue,
@@ -96,6 +98,7 @@ import {
96
98
  touchStatsMaintenanceLock,
97
99
  writeMaintenanceMarker,
98
100
  } from "./stats-store.ts";
101
+ import { statsReadFs } from "./stats-fs.ts";
99
102
 
100
103
  export const SHARD_ARCHIVE_DIR = join(SHARD_STATE_DIR, "archive");
101
104
  /**
@@ -486,7 +489,7 @@ export type LoadedStatsArchive = {
486
489
  };
487
490
 
488
491
  type BucketGroup = {
489
- /** Position in ReducedArchive.groups. */
492
+ /** Index of the group's first bucket in the archive: groups keep the order of their first appearance. */
490
493
  order: number;
491
494
  globalEpoch: string;
492
495
  sessionHash: string;
@@ -511,17 +514,21 @@ type RoutedGroup = {
511
514
  firstEligibleIndex: number;
512
515
  };
513
516
 
514
- type ReducedArchive = {
515
- /** Buckets folded per (globalEpoch, session, model, modelEpoch), in order of first appearance. */
517
+ /** One session's buckets folded per (globalEpoch, model, modelEpoch), and its routed entries per globalEpoch. */
518
+ type ReducedSession = {
516
519
  groups: BucketGroup[];
517
520
  routed: RoutedGroup[];
518
- /** The same groups per session (each list in archive order). */
519
- groupsBySession: Map<string, BucketGroup[]>;
520
- routedBySession: Map<string, RoutedGroup[]>;
521
- /** Model keys with buckets under each global epoch, sorted. */
522
- keysByGlobalEpoch: Map<string, string[]>;
521
+ /** Model keys with buckets in this session under each global epoch. */
522
+ keysByGlobalEpoch: Map<string, Set<string>>;
523
523
  };
524
524
 
525
+ /** Get (or create) the value for `key` in a nested map level. */
526
+ function slotOf<K, V>(map: Map<K, V>, key: K, create: () => V): V {
527
+ let value = map.get(key);
528
+ if (value === undefined) map.set(key, value = create());
529
+ return value;
530
+ }
531
+
525
532
  /**
526
533
  * One parsed archive snapshot, cached per file identity. Besides the raw
527
534
  * entries it lazily builds what a refresh needs: the per-day synthetic shards
@@ -534,7 +541,8 @@ export class StatsArchiveView implements LoadedStatsArchive {
534
541
  private syntheticShards?: PersistedStatsShardV7[];
535
542
  private dayIndex?: Map<string, { buckets: number[]; routed: number[] }>;
536
543
  private dayShards?: { day: string; shards: readonly PersistedStatsShardV7[] };
537
- private reduced?: ReducedArchive;
544
+ private bySessionIndex?: { buckets: Map<string, number[]>; routed: Map<string, number[]> };
545
+ private readonly reducedSessions = new Map<string, ReducedSession>();
538
546
  private contributionCache?: { fingerprint: string; contribution: ShardContribution };
539
547
 
540
548
  /** Highest generation listed, including unreadable ones above `generation`; the next publish targets newestGeneration + 1. */
@@ -619,16 +627,36 @@ export class StatsArchiveView implements LoadedStatsArchive {
619
627
  return shards;
620
628
  }
621
629
 
622
- private reduce(): ReducedArchive {
623
- if (this.reduced) return this.reduced;
624
- const groups = new Map<string, BucketGroup>();
625
- const keys = new Map<string, Set<string>>();
626
- this.archive.buckets.forEach((bucket, index) => {
627
- const id = JSON.stringify([bucket.globalEpoch, bucket.sessionHash, bucket.modelKey, bucket.modelEpoch]);
628
- const group = groups.get(id);
630
+ /** Bucket and routed indexes per session: one pass, no per-entry key building. */
631
+ private sessionIndex(): { buckets: Map<string, number[]>; routed: Map<string, number[]> } {
632
+ if (this.bySessionIndex) return this.bySessionIndex;
633
+ const buckets = new Map<string, number[]>();
634
+ const routed = new Map<string, number[]>();
635
+ const { buckets: archiveBuckets, routed: archiveRouted } = this.archive;
636
+ for (let index = 0; index < archiveBuckets.length; index++) slotOf(buckets, archiveBuckets[index]!.sessionHash, () => []).push(index);
637
+ for (let index = 0; index < archiveRouted.length; index++) slotOf(routed, archiveRouted[index]!.sessionHash, () => []).push(index);
638
+ return this.bySessionIndex = { buckets, routed };
639
+ }
640
+
641
+ /**
642
+ * One session's reduced form, built on first use. Groups are keyed by
643
+ * nested maps (no JSON.stringify per bucket, no separator that a string
644
+ * could contain), and only the sessions a refresh asks for are reduced.
645
+ */
646
+ private reduceSession(sessionHash: string): ReducedSession {
647
+ const cached = this.reducedSessions.get(sessionHash);
648
+ if (cached) return cached;
649
+ const index = this.sessionIndex();
650
+ const groups: BucketGroup[] = [];
651
+ const groupIndex = new Map<string, Map<string, Map<string, BucketGroup>>>();
652
+ const keysByGlobalEpoch = new Map<string, Set<string>>();
653
+ for (const bucketIndex of index.buckets.get(sessionHash) ?? []) {
654
+ const bucket = this.archive.buckets[bucketIndex]!;
655
+ const byModelEpoch = slotOf(slotOf(groupIndex, bucket.globalEpoch, () => new Map()), bucket.modelKey, () => new Map<string, BucketGroup>());
656
+ const group = byModelEpoch.get(bucket.modelEpoch);
629
657
  if (!group) {
630
- groups.set(id, {
631
- order: groups.size,
658
+ const created: BucketGroup = {
659
+ order: bucketIndex,
632
660
  globalEpoch: bucket.globalEpoch,
633
661
  sessionHash: bucket.sessionHash,
634
662
  key: bucket.modelKey,
@@ -636,57 +664,64 @@ export class StatsArchiveView implements LoadedStatsArchive {
636
664
  stats: bucket.stats,
637
665
  count: 1,
638
666
  bestUpdatedAt: bucket.updatedAt,
639
- bestIndex: index,
640
- firstEligibleIndex: bucket.updatedAt > -1 ? index : Infinity,
641
- });
642
- let set = keys.get(bucket.globalEpoch);
643
- if (!set) keys.set(bucket.globalEpoch, set = new Set());
644
- set.add(bucket.modelKey);
645
- return;
667
+ bestIndex: bucketIndex,
668
+ firstEligibleIndex: bucket.updatedAt > -1 ? bucketIndex : Infinity,
669
+ };
670
+ byModelEpoch.set(bucket.modelEpoch, created);
671
+ groups.push(created);
672
+ slotOf(keysByGlobalEpoch, bucket.globalEpoch, () => new Set()).add(bucket.modelKey);
673
+ continue;
646
674
  }
647
675
  if (group.count === 1) group.stats = cloneCacheStats(group.stats);
648
676
  mergeStatsAcrossDays(group.stats, bucket.stats, null);
649
677
  group.count++;
650
- if (group.firstEligibleIndex === Infinity && bucket.updatedAt > -1) group.firstEligibleIndex = index;
678
+ if (group.firstEligibleIndex === Infinity && bucket.updatedAt > -1) group.firstEligibleIndex = bucketIndex;
651
679
  if (bucket.updatedAt > group.bestUpdatedAt) {
652
680
  group.bestUpdatedAt = bucket.updatedAt;
653
- group.bestIndex = index;
681
+ group.bestIndex = bucketIndex;
654
682
  }
655
- });
656
- const routed = new Map<string, RoutedGroup>();
657
- this.archive.routed.forEach((entry, index) => {
658
- const id = JSON.stringify([entry.globalEpoch, entry.sessionHash]);
659
- const group = routed.get(id);
660
- const eligible = entry.updatedAt > -1 ? index : Infinity;
683
+ }
684
+ const routed: RoutedGroup[] = [];
685
+ const routedIndex = new Map<string, RoutedGroup>();
686
+ for (const entryIndex of index.routed.get(sessionHash) ?? []) {
687
+ const entry = this.archive.routed[entryIndex]!;
688
+ const group = routedIndex.get(entry.globalEpoch);
689
+ const eligible = entry.updatedAt > -1 ? entryIndex : Infinity;
661
690
  if (!group) {
662
- routed.set(id, { globalEpoch: entry.globalEpoch, sessionHash: entry.sessionHash, bestUpdatedAt: entry.updatedAt, model: entry.model, firstEligibleIndex: eligible });
663
- return;
691
+ const created: RoutedGroup = { globalEpoch: entry.globalEpoch, sessionHash: entry.sessionHash, bestUpdatedAt: entry.updatedAt, model: entry.model, firstEligibleIndex: eligible };
692
+ routedIndex.set(entry.globalEpoch, created);
693
+ routed.push(created);
694
+ continue;
664
695
  }
665
696
  if (group.firstEligibleIndex === Infinity) group.firstEligibleIndex = eligible;
666
697
  if (entry.updatedAt > group.bestUpdatedAt) {
667
698
  group.bestUpdatedAt = entry.updatedAt;
668
699
  group.model = entry.model;
669
700
  }
670
- });
671
- const bySession = <T extends { sessionHash: string }>(items: T[]): Map<string, T[]> => {
672
- const map = new Map<string, T[]>();
673
- for (const item of items) {
674
- let list = map.get(item.sessionHash);
675
- if (!list) map.set(item.sessionHash, list = []);
676
- list.push(item);
677
- }
678
- return map;
679
- };
680
- const groupList = Array.from(groups.values());
681
- const routedList = Array.from(routed.values());
682
- this.reduced = {
683
- groups: groupList,
684
- routed: routedList,
685
- groupsBySession: bySession(groupList),
686
- routedBySession: bySession(routedList),
687
- keysByGlobalEpoch: new Map(Array.from(keys, ([epoch, set]) => [epoch, Array.from(set).sort()])),
688
- };
689
- return this.reduced;
701
+ }
702
+ const reduced: ReducedSession = { groups, routed, keysByGlobalEpoch };
703
+ this.reducedSessions.set(sessionHash, reduced);
704
+ return reduced;
705
+ }
706
+
707
+ /** The sessions a contribution covers: `only`, or every archived session. */
708
+ private sessionsFor(only?: ReadonlySet<string>): Iterable<string> {
709
+ if (only) return only;
710
+ const index = this.sessionIndex();
711
+ return new Set([...index.buckets.keys(), ...index.routed.keys()]);
712
+ }
713
+
714
+ /**
715
+ * Every model key the archive's share of an all-days aggregate (of `only`,
716
+ * when given) can look up an epoch for, under any global epoch: what a
717
+ * refresh reads before aggregating synchronously.
718
+ */
719
+ contributionKeys(only?: ReadonlySet<string>): string[] {
720
+ const keys = new Set<string>();
721
+ for (const session of this.sessionsFor(only)) {
722
+ for (const set of this.reduceSession(session).keysByGlobalEpoch.values()) for (const key of set) keys.add(key);
723
+ }
724
+ return Array.from(keys);
690
725
  }
691
726
 
692
727
  /**
@@ -696,22 +731,41 @@ export class StatsArchiveView implements LoadedStatsArchive {
696
731
  * session selection, or the archive changes.
697
732
  */
698
733
  async contribution(aggregator: Pick<ShardAggregator, "globalEpoch" | "modelEpoch">, only?: ReadonlySet<string>): Promise<ShardContribution> {
699
- const reduced = this.reduce();
700
- const globalEpoch = aggregator.globalEpoch;
701
- let groupList = reduced.groups;
702
- let routedList = reduced.routed;
703
- let keys = reduced.keysByGlobalEpoch.get(globalEpoch) ?? [];
704
- if (only) {
705
- groupList = Array.from(only, (session) => reduced.groupsBySession.get(session) ?? []).flat()
706
- .sort((a, b) => a.order - b.order);
707
- routedList = Array.from(only, (session) => reduced.routedBySession.get(session) ?? []).flat();
708
- keys = Array.from(new Set(groupList.filter((group) => group.globalEpoch === globalEpoch).map((group) => group.key))).sort();
709
- }
734
+ const keys = this.keysUnder(aggregator.globalEpoch, only);
710
735
  const epochs = new Map<string, string>();
711
736
  for (const key of keys) epochs.set(key, await aggregator.modelEpoch(key));
737
+ return this.contributionSync({ globalEpoch: aggregator.globalEpoch, modelEpoch: (key) => epochs.get(key)! }, only);
738
+ }
739
+
740
+ /** Model keys of `only` (or all sessions) with buckets under `globalEpoch`, sorted. */
741
+ private keysUnder(globalEpoch: string, only?: ReadonlySet<string>): string[] {
742
+ const keys = new Set<string>();
743
+ for (const session of this.sessionsFor(only)) {
744
+ for (const key of this.reduceSession(session).keysByGlobalEpoch.get(globalEpoch) ?? []) keys.add(key);
745
+ }
746
+ return Array.from(keys).sort();
747
+ }
748
+
749
+ /** contribution() over epochs read beforehand (ShardEpochs must cover contributionKeys). */
750
+ contributionSync(epochSource: ShardEpochs, only?: ReadonlySet<string>): ShardContribution {
751
+ const globalEpoch = epochSource.globalEpoch;
752
+ const keys = this.keysUnder(globalEpoch, only);
753
+ const epochs = new Map<string, string>();
754
+ for (const key of keys) epochs.set(key, epochSource.modelEpoch(key));
712
755
  const fingerprint = JSON.stringify([globalEpoch, ...keys.flatMap((key) => [key, epochs.get(key)]), only ? Array.from(only).sort() : null]);
713
756
  if (this.contributionCache?.fingerprint === fingerprint) return this.contributionCache.contribution;
714
757
 
758
+ const groupList: BucketGroup[] = [];
759
+ const routedList: RoutedGroup[] = [];
760
+ for (const session of this.sessionsFor(only)) {
761
+ const reduced = this.reduceSession(session);
762
+ for (const group of reduced.groups) groupList.push(group);
763
+ for (const group of reduced.routed) routedList.push(group);
764
+ }
765
+ // Groups of several sessions in the order of their first bucket (what a
766
+ // full reduction in archive order produces).
767
+ groupList.sort((a, b) => a.order - b.order);
768
+
715
769
  type SessionOut = { sessionHash: string; instances: number; models: Array<{ key: string; stats: CacheStats; instances: number }> };
716
770
  type ModelOut = { key: string; stats: CacheStats; instances: number; sessions: string[]; refUpdatedAt: number; refIndex: number; firstEligibleIndex: number };
717
771
  const sessions = new Map<string, SessionOut>();
@@ -790,6 +844,48 @@ export async function aggregateStatsWithArchiveV7(
790
844
  return aggregator.finish();
791
845
  }
792
846
 
847
+ /**
848
+ * aggregateStatsWithArchiveV7 over epochs read beforehand, without a single
849
+ * await: a refresh commits it in the same synchronous step that builds its
850
+ * trailing (in-memory) shard, so usage recorded meanwhile is never lost.
851
+ */
852
+ export function aggregateStatsWithArchiveSync(
853
+ leading: readonly PersistedStatsShardV7[],
854
+ archive: StatsArchiveView,
855
+ trailing: readonly PersistedStatsShardV7[],
856
+ day: string | null,
857
+ sessions: ReadonlySet<string> | undefined,
858
+ epochs: ShardEpochs,
859
+ ): ShardAggregate {
860
+ const aggregator = createShardAggregatorSync(day, epochs);
861
+ const include = (shard: PersistedStatsShardV7) => !sessions || sessions.has(shard.sessionHash);
862
+ for (const shard of leading) if (include(shard)) aggregator.add(shard);
863
+ if (day === null) aggregator.addContribution(archive.contributionSync(epochs, sessions));
864
+ else for (const shard of archive.shardsForDay(day)) if (include(shard)) aggregator.add(shard);
865
+ for (const shard of trailing) if (include(shard)) aggregator.add(shard);
866
+ return aggregator.finish();
867
+ }
868
+
869
+ /** Every model key aggregateStatsWithArchiveSync may look up an epoch for (a superset). */
870
+ export function aggregateEpochKeys(
871
+ leading: readonly PersistedStatsShardV7[],
872
+ archive: StatsArchiveView,
873
+ trailing: readonly PersistedStatsShardV7[],
874
+ day: string | null,
875
+ sessions: ReadonlySet<string> | undefined,
876
+ ): Set<string> {
877
+ const keys = new Set<string>();
878
+ const include = (shard: PersistedStatsShardV7) => !sessions || sessions.has(shard.sessionHash);
879
+ const addShard = (shard: PersistedStatsShardV7) => {
880
+ if (include(shard)) for (const key of Object.keys(shard.models)) keys.add(key);
881
+ };
882
+ for (const shard of leading) addShard(shard);
883
+ for (const shard of trailing) addShard(shard);
884
+ if (day === null) for (const key of archive.contributionKeys(sessions)) keys.add(key);
885
+ else for (const shard of archive.shardsForDay(day)) addShard(shard);
886
+ return keys;
887
+ }
888
+
793
889
  /** Test hooks for archive I/O races and faults; production never sets them. */
794
890
  export type StatsArchiveTestHooks = {
795
891
  /** Runs after each directory listing a reader makes (to land a concurrent migration or publish in between). */
@@ -823,7 +919,7 @@ type ArchiveListing = { generations: number[]; placeholders: string[] };
823
919
  async function listArchiveDirectory(archivePath: string): Promise<ArchiveListing> {
824
920
  let names: string[];
825
921
  try {
826
- names = await readdir(dirname(archivePath));
922
+ names = await statsReadFs().readdir(dirname(archivePath));
827
923
  } catch (error) {
828
924
  if (getErrorCode(error) === "ENOENT") return { generations: [], placeholders: [] };
829
925
  throw error;
@@ -853,7 +949,7 @@ async function listArchiveDirectory(archivePath: string): Promise<ArchiveListing
853
949
  async function newestMigrationPlaceholder(placeholders: readonly string[]): Promise<string | undefined> {
854
950
  if (placeholders.length <= 1) return placeholders[0];
855
951
  const keyed = await Promise.all(placeholders.map(async (path) => {
856
- const info = await lstat(path).catch((error) => {
952
+ const info = await statsReadFs().lstat(path).catch((error) => {
857
953
  if (getErrorCode(error) === "ENOENT") return undefined;
858
954
  throw error;
859
955
  });
@@ -1044,7 +1140,7 @@ async function locateAndReadArchive(archivePath: string, options: ReadStatsArchi
1044
1140
  let info: import("node:fs").Stats | undefined;
1045
1141
  try {
1046
1142
  await testHooks.beforeLstat?.(archivePath);
1047
- info = await lstat(archivePath);
1143
+ info = await statsReadFs().lstat(archivePath);
1048
1144
  } catch (error) {
1049
1145
  if (getErrorCode(error) !== "ENOENT") throw error;
1050
1146
  }
@@ -1087,7 +1183,7 @@ async function readArchiveFile(
1087
1183
  let info: import("node:fs").Stats;
1088
1184
  try {
1089
1185
  await testHooks.beforeLstat?.(path);
1090
- info = await lstat(path);
1186
+ info = await statsReadFs().lstat(path);
1091
1187
  } catch (error) {
1092
1188
  return onError(generation, error);
1093
1189
  }
@@ -1103,7 +1199,7 @@ async function readArchiveFile(
1103
1199
  let bytes: Buffer;
1104
1200
  try {
1105
1201
  await testHooks.beforeReadFile?.(path);
1106
- bytes = await readFile(path);
1202
+ bytes = await statsReadFs().readFile(path);
1107
1203
  } catch (error) {
1108
1204
  archiveFileCache.delete(path);
1109
1205
  return onError(generation, error);
@@ -1131,7 +1227,50 @@ export async function readStatsArchiveView(archivePath: string = SHARD_ARCHIVE_P
1131
1227
  return (await readStatsArchiveDetailed(archivePath, options)).view;
1132
1228
  }
1133
1229
 
1134
- export type StatsSnapshot = { rawShards: PersistedStatsShardV7[]; archive: StatsArchiveView };
1230
+ export type StatsSnapshot = { rawShards: readonly PersistedStatsShardV7[]; archive: StatsArchiveView };
1231
+
1232
+ /** A snapshot can reuse its archive without stat-ing it: see readStatsArchiveForRefresh. */
1233
+ function isReusableArchiveView(view: StatsArchiveView): boolean {
1234
+ return view.present && !view.corrupt && view.generation > 0 && view.corruptGenerations.length === 0 &&
1235
+ !view.pendingGeneration && view.newestGeneration === view.generation;
1236
+ }
1237
+
1238
+ /**
1239
+ * readStatsArchiveDetailed for a footer refresh that holds the previous
1240
+ * snapshot's view. Generation files are immutable (published by link or by
1241
+ * an exclusive create that only counts once complete; never rewritten), so
1242
+ * while the newest listed generation is the one `previous` was read from
1243
+ * and that view is a clean read of it, the listing alone confirms it and the
1244
+ * file is not stat-ed again. Every other state goes through the full read
1245
+ * exactly as before: 2.9.0's archive.json (generation 0, rewritten in place
1246
+ * by 2.9.0) and migration placeholders, a newest generation that is still
1247
+ * pending (written in place) or unreadable (the view recovered below it), or
1248
+ * a newer generation.
1249
+ */
1250
+ export async function readStatsArchiveForRefresh(previous: StatsArchiveView | undefined, archivePath: string = SHARD_ARCHIVE_PATH): Promise<StatsArchiveRead & { reused: boolean }> {
1251
+ if (previous && isReusableArchiveView(previous)) {
1252
+ let newest: number | undefined;
1253
+ try {
1254
+ newest = (await listArchiveDirectory(archivePath)).generations.at(-1);
1255
+ await testHooks.afterList?.(archivePath);
1256
+ } catch {
1257
+ newest = undefined;
1258
+ }
1259
+ if (newest !== undefined && newest === previous.generation) return { view: previous, stale: false, reused: true };
1260
+ }
1261
+ return { ...(await readStatsArchiveDetailed(archivePath)), reused: false };
1262
+ }
1263
+
1264
+ export type ReadStatsSnapshotOptions = {
1265
+ /**
1266
+ * The shard phase. Defaults to readValidStatsShardsV7 (stat every file).
1267
+ * Whatever it is, it must have finished every read (listing, lstat and
1268
+ * readFile) before it resolves: the archive is only listed afterwards.
1269
+ */
1270
+ readShards?: () => Promise<readonly PersistedStatsShardV7[]>;
1271
+ /** Confirm an unchanged clean generation by its listing alone (readStatsArchiveForRefresh). */
1272
+ reuseArchive?: boolean;
1273
+ };
1135
1274
 
1136
1275
  /**
1137
1276
  * The raw shards and the archive as one consistent snapshot. Order matters:
@@ -1141,15 +1280,21 @@ export type StatsSnapshot = { rawShards: PersistedStatsShardV7[]; archive: Stats
1141
1280
  * persistent transient error and served the last good snapshot, that
1142
1281
  * snapshot may predate shards deleted since; pairing it with the fresh
1143
1282
  * listing would undercount, so the previous snapshot is reused as a whole
1144
- * (it was consistent when read) when it holds that same archive.
1283
+ * (it was consistent when read) when it holds that same archive. The
1284
+ * previous snapshot's rawShards are the shard contents read then (shared,
1285
+ * immutable objects), not names to look up again.
1145
1286
  */
1146
1287
  export async function readStatsSnapshot(
1147
1288
  previous?: StatsSnapshot,
1148
1289
  directory: string = SHARD_FILES_DIR,
1149
1290
  archivePath: string = SHARD_ARCHIVE_PATH,
1291
+ options: ReadStatsSnapshotOptions = {},
1150
1292
  ): Promise<StatsSnapshot> {
1151
- const rawShards = await readValidStatsShardsV7(directory);
1152
- const { view, stale } = await readStatsArchiveDetailed(archivePath);
1293
+ // Shard phase first, complete (every lstat and readFile), then the archive.
1294
+ const rawShards = options.readShards ? await options.readShards() : await readValidStatsShardsV7(directory);
1295
+ const { view, stale } = options.reuseArchive
1296
+ ? await readStatsArchiveForRefresh(previous?.archive, archivePath)
1297
+ : await readStatsArchiveDetailed(archivePath);
1153
1298
  if (stale && previous && previous.archive === view) {
1154
1299
  // Only a newer generation can have deleted shards this archive misses.
1155
1300
  // While it is still the newest one (highest generations never go back:
@@ -0,0 +1,54 @@
1
+ import fsp from "node:fs/promises";
2
+ import type { Stats } from "node:fs";
3
+
4
+ /**
5
+ * The read-only filesystem calls a footer refresh makes (shard index,
6
+ * archive reader, epoch reads), behind one replaceable facade so tests can
7
+ * count or fault them without monkeypatching node:fs/promises (fragile
8
+ * under jiti's ESM named bindings). Production never replaces it; every
9
+ * call looks up the fs/promises function at call time.
10
+ */
11
+ export type StatsReadFs = {
12
+ readdir(path: string): Promise<string[]>;
13
+ lstat(path: string): Promise<Stats>;
14
+ stat(path: string): Promise<Stats>;
15
+ readFile(path: string): Promise<Buffer>;
16
+ };
17
+
18
+ const realStatsReadFs: StatsReadFs = {
19
+ readdir: (path) => fsp.readdir(path),
20
+ lstat: (path) => fsp.lstat(path),
21
+ stat: (path) => fsp.stat(path),
22
+ readFile: (path) => fsp.readFile(path),
23
+ };
24
+
25
+ let current: StatsReadFs = realStatsReadFs;
26
+
27
+ /** The facade in effect (real fs unless a test replaced it). */
28
+ export function statsReadFs(): StatsReadFs {
29
+ return current;
30
+ }
31
+
32
+ /** Test hook: replace the facade (undefined restores the real filesystem). */
33
+ export function setStatsReadFsForTests(fs: StatsReadFs | undefined): void {
34
+ current = fs ?? realStatsReadFs;
35
+ }
36
+
37
+ export type StatsReadFsCounts = { readdir: number; lstat: number; stat: number; readFile: number; paths: string[] };
38
+
39
+ /** Test helper: a facade over `base` that counts calls (and records paths). */
40
+ export function countingStatsReadFs(base: StatsReadFs = realStatsReadFs): { fs: StatsReadFs; counts: StatsReadFsCounts; reset(): void } {
41
+ const counts: StatsReadFsCounts = { readdir: 0, lstat: 0, stat: 0, readFile: 0, paths: [] };
42
+ const wrap = <K extends keyof StatsReadFs>(name: K): StatsReadFs[K] => (async (path: string) => {
43
+ counts[name]++;
44
+ counts.paths.push(`${name} ${path}`);
45
+ return (base[name] as (path: string) => Promise<unknown>)(path);
46
+ }) as StatsReadFs[K];
47
+ return {
48
+ fs: { readdir: wrap("readdir"), lstat: wrap("lstat"), stat: wrap("stat"), readFile: wrap("readFile") },
49
+ counts,
50
+ reset() {
51
+ counts.readdir = 0; counts.lstat = 0; counts.stat = 0; counts.readFile = 0; counts.paths.length = 0;
52
+ },
53
+ };
54
+ }