pi-cache-optimizer 2.9.2 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  /**
@@ -185,8 +188,18 @@ export type StatsArchiveV2Document = {
185
188
 
186
189
  const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
187
190
  const GENERATION_FILE_PATTERN = /^archive\.(\d{1,15})\.json$/;
188
- /** 2.9.0's archive.json while it is being migrated (see compactStatsShardsV7). */
191
+ /**
192
+ * 2.9.0's archive.json while it is being migrated (see compactStatsShardsV7):
193
+ * `archive.migrating-<moved-at ms, 13 digits>-<uuid>.json`, or
194
+ * `archive.migrating-<uuid>.json` as 2.9.2 named it. Both match this pattern
195
+ * (2.9.2 reads both).
196
+ */
189
197
  const MIGRATION_PLACEHOLDER_PATTERN = /^archive\.migrating-[0-9a-f-]+\.json$/;
198
+ const MIGRATION_PLACEHOLDER_MOVED_AT_PATTERN = /^archive\.migrating-(\d{13})-[0-9a-f]{8}-[0-9a-f-]+\.json$/;
199
+
200
+ function migrationPlaceholderPath(archivePath: string, movedAt = Date.now()): string {
201
+ return join(dirname(archivePath), `archive.migrating-${String(Math.max(0, Math.floor(movedAt))).padStart(13, "0")}-${randomUUID()}.json`);
202
+ }
190
203
 
191
204
  export function emptyStatsArchive(now = Date.now()): StatsArchiveV1 {
192
205
  return { version: 1, kind: "pi-cache-optimizer-archive", updatedAt: now, absorbed: {}, buckets: [], routed: [] };
@@ -476,7 +489,7 @@ export type LoadedStatsArchive = {
476
489
  };
477
490
 
478
491
  type BucketGroup = {
479
- /** Position in ReducedArchive.groups. */
492
+ /** Index of the group's first bucket in the archive: groups keep the order of their first appearance. */
480
493
  order: number;
481
494
  globalEpoch: string;
482
495
  sessionHash: string;
@@ -501,17 +514,21 @@ type RoutedGroup = {
501
514
  firstEligibleIndex: number;
502
515
  };
503
516
 
504
- type ReducedArchive = {
505
- /** 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 = {
506
519
  groups: BucketGroup[];
507
520
  routed: RoutedGroup[];
508
- /** The same groups per session (each list in archive order). */
509
- groupsBySession: Map<string, BucketGroup[]>;
510
- routedBySession: Map<string, RoutedGroup[]>;
511
- /** Model keys with buckets under each global epoch, sorted. */
512
- keysByGlobalEpoch: Map<string, string[]>;
521
+ /** Model keys with buckets in this session under each global epoch. */
522
+ keysByGlobalEpoch: Map<string, Set<string>>;
513
523
  };
514
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
+
515
532
  /**
516
533
  * One parsed archive snapshot, cached per file identity. Besides the raw
517
534
  * entries it lazily builds what a refresh needs: the per-day synthetic shards
@@ -524,7 +541,8 @@ export class StatsArchiveView implements LoadedStatsArchive {
524
541
  private syntheticShards?: PersistedStatsShardV7[];
525
542
  private dayIndex?: Map<string, { buckets: number[]; routed: number[] }>;
526
543
  private dayShards?: { day: string; shards: readonly PersistedStatsShardV7[] };
527
- private reduced?: ReducedArchive;
544
+ private bySessionIndex?: { buckets: Map<string, number[]>; routed: Map<string, number[]> };
545
+ private readonly reducedSessions = new Map<string, ReducedSession>();
528
546
  private contributionCache?: { fingerprint: string; contribution: ShardContribution };
529
547
 
530
548
  /** Highest generation listed, including unreadable ones above `generation`; the next publish targets newestGeneration + 1. */
@@ -609,16 +627,36 @@ export class StatsArchiveView implements LoadedStatsArchive {
609
627
  return shards;
610
628
  }
611
629
 
612
- private reduce(): ReducedArchive {
613
- if (this.reduced) return this.reduced;
614
- const groups = new Map<string, BucketGroup>();
615
- const keys = new Map<string, Set<string>>();
616
- this.archive.buckets.forEach((bucket, index) => {
617
- const id = JSON.stringify([bucket.globalEpoch, bucket.sessionHash, bucket.modelKey, bucket.modelEpoch]);
618
- 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);
619
657
  if (!group) {
620
- groups.set(id, {
621
- order: groups.size,
658
+ const created: BucketGroup = {
659
+ order: bucketIndex,
622
660
  globalEpoch: bucket.globalEpoch,
623
661
  sessionHash: bucket.sessionHash,
624
662
  key: bucket.modelKey,
@@ -626,57 +664,64 @@ export class StatsArchiveView implements LoadedStatsArchive {
626
664
  stats: bucket.stats,
627
665
  count: 1,
628
666
  bestUpdatedAt: bucket.updatedAt,
629
- bestIndex: index,
630
- firstEligibleIndex: bucket.updatedAt > -1 ? index : Infinity,
631
- });
632
- let set = keys.get(bucket.globalEpoch);
633
- if (!set) keys.set(bucket.globalEpoch, set = new Set());
634
- set.add(bucket.modelKey);
635
- 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;
636
674
  }
637
675
  if (group.count === 1) group.stats = cloneCacheStats(group.stats);
638
676
  mergeStatsAcrossDays(group.stats, bucket.stats, null);
639
677
  group.count++;
640
- if (group.firstEligibleIndex === Infinity && bucket.updatedAt > -1) group.firstEligibleIndex = index;
678
+ if (group.firstEligibleIndex === Infinity && bucket.updatedAt > -1) group.firstEligibleIndex = bucketIndex;
641
679
  if (bucket.updatedAt > group.bestUpdatedAt) {
642
680
  group.bestUpdatedAt = bucket.updatedAt;
643
- group.bestIndex = index;
681
+ group.bestIndex = bucketIndex;
644
682
  }
645
- });
646
- const routed = new Map<string, RoutedGroup>();
647
- this.archive.routed.forEach((entry, index) => {
648
- const id = JSON.stringify([entry.globalEpoch, entry.sessionHash]);
649
- const group = routed.get(id);
650
- 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;
651
690
  if (!group) {
652
- routed.set(id, { globalEpoch: entry.globalEpoch, sessionHash: entry.sessionHash, bestUpdatedAt: entry.updatedAt, model: entry.model, firstEligibleIndex: eligible });
653
- 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;
654
695
  }
655
696
  if (group.firstEligibleIndex === Infinity) group.firstEligibleIndex = eligible;
656
697
  if (entry.updatedAt > group.bestUpdatedAt) {
657
698
  group.bestUpdatedAt = entry.updatedAt;
658
699
  group.model = entry.model;
659
700
  }
660
- });
661
- const bySession = <T extends { sessionHash: string }>(items: T[]): Map<string, T[]> => {
662
- const map = new Map<string, T[]>();
663
- for (const item of items) {
664
- let list = map.get(item.sessionHash);
665
- if (!list) map.set(item.sessionHash, list = []);
666
- list.push(item);
667
- }
668
- return map;
669
- };
670
- const groupList = Array.from(groups.values());
671
- const routedList = Array.from(routed.values());
672
- this.reduced = {
673
- groups: groupList,
674
- routed: routedList,
675
- groupsBySession: bySession(groupList),
676
- routedBySession: bySession(routedList),
677
- keysByGlobalEpoch: new Map(Array.from(keys, ([epoch, set]) => [epoch, Array.from(set).sort()])),
678
- };
679
- 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);
680
725
  }
681
726
 
682
727
  /**
@@ -686,22 +731,41 @@ export class StatsArchiveView implements LoadedStatsArchive {
686
731
  * session selection, or the archive changes.
687
732
  */
688
733
  async contribution(aggregator: Pick<ShardAggregator, "globalEpoch" | "modelEpoch">, only?: ReadonlySet<string>): Promise<ShardContribution> {
689
- const reduced = this.reduce();
690
- const globalEpoch = aggregator.globalEpoch;
691
- let groupList = reduced.groups;
692
- let routedList = reduced.routed;
693
- let keys = reduced.keysByGlobalEpoch.get(globalEpoch) ?? [];
694
- if (only) {
695
- groupList = Array.from(only, (session) => reduced.groupsBySession.get(session) ?? []).flat()
696
- .sort((a, b) => a.order - b.order);
697
- routedList = Array.from(only, (session) => reduced.routedBySession.get(session) ?? []).flat();
698
- keys = Array.from(new Set(groupList.filter((group) => group.globalEpoch === globalEpoch).map((group) => group.key))).sort();
699
- }
734
+ const keys = this.keysUnder(aggregator.globalEpoch, only);
700
735
  const epochs = new Map<string, string>();
701
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));
702
755
  const fingerprint = JSON.stringify([globalEpoch, ...keys.flatMap((key) => [key, epochs.get(key)]), only ? Array.from(only).sort() : null]);
703
756
  if (this.contributionCache?.fingerprint === fingerprint) return this.contributionCache.contribution;
704
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
+
705
769
  type SessionOut = { sessionHash: string; instances: number; models: Array<{ key: string; stats: CacheStats; instances: number }> };
706
770
  type ModelOut = { key: string; stats: CacheStats; instances: number; sessions: string[]; refUpdatedAt: number; refIndex: number; firstEligibleIndex: number };
707
771
  const sessions = new Map<string, SessionOut>();
@@ -780,6 +844,48 @@ export async function aggregateStatsWithArchiveV7(
780
844
  return aggregator.finish();
781
845
  }
782
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
+
783
889
  /** Test hooks for archive I/O races and faults; production never sets them. */
784
890
  export type StatsArchiveTestHooks = {
785
891
  /** Runs after each directory listing a reader makes (to land a concurrent migration or publish in between). */
@@ -792,6 +898,14 @@ export type StatsArchiveTestHooks = {
792
898
  link?: (existingPath: string, newPath: string) => Promise<void>;
793
899
  /** Runs right after the no-hard-link fallback created a generation file exclusively, before writing it. */
794
900
  afterExclusiveCreate?: (target: string) => Promise<void>;
901
+ /**
902
+ * Runs between the steps of moving 2.9.0's archive.json aside (to land a
903
+ * concurrent 2.9.0 write there): "moved-aside" right after archive.json was
904
+ * renamed to its placeholder, before the tombstone directory is made;
905
+ * "undo-removed-tombstone" when undoing, right after the tombstone was
906
+ * removed, before the placeholder is put back.
907
+ */
908
+ afterMigrationStep?: (step: "moved-aside" | "undo-removed-tombstone", archivePath: string, placeholder: string) => Promise<void>;
795
909
  /** Overrides the maintenance heartbeat interval. */
796
910
  heartbeatMs?: number;
797
911
  };
@@ -805,7 +919,7 @@ type ArchiveListing = { generations: number[]; placeholders: string[] };
805
919
  async function listArchiveDirectory(archivePath: string): Promise<ArchiveListing> {
806
920
  let names: string[];
807
921
  try {
808
- names = await readdir(dirname(archivePath));
922
+ names = await statsReadFs().readdir(dirname(archivePath));
809
923
  } catch (error) {
810
924
  if (getErrorCode(error) === "ENOENT") return { generations: [], placeholders: [] };
811
925
  throw error;
@@ -820,6 +934,33 @@ async function listArchiveDirectory(archivePath: string): Promise<ArchiveListing
820
934
  return { generations: generations.sort((a, b) => a - b), placeholders: placeholders.sort() };
821
935
  }
822
936
 
937
+ /**
938
+ * The newest of several migration placeholders, chosen deterministically.
939
+ * Two exist only after a migration kept one for inspection (a 2.9.0 write
940
+ * landed between its move and its mkdir) and a later one was interrupted
941
+ * after its own move: the later one holds what 2.9.0 wrote after the first
942
+ * was moved, so it is the one to read and migrate from (the older one is set
943
+ * aside once a generation exists). Ordered by the time the file was moved
944
+ * aside (in its name), or for 2.9.2's uuid-only names by its mtime (rename
945
+ * keeps it; content 2.9.0 wrote after an earlier move is always newer than
946
+ * that move), then by mtime, then by name. A file that disappeared sorts
947
+ * first; the caller re-lists when it is gone.
948
+ */
949
+ async function newestMigrationPlaceholder(placeholders: readonly string[]): Promise<string | undefined> {
950
+ if (placeholders.length <= 1) return placeholders[0];
951
+ const keyed = await Promise.all(placeholders.map(async (path) => {
952
+ const info = await statsReadFs().lstat(path).catch((error) => {
953
+ if (getErrorCode(error) === "ENOENT") return undefined;
954
+ throw error;
955
+ });
956
+ const mtime = info?.mtimeMs ?? -Infinity;
957
+ const moved = MIGRATION_PLACEHOLDER_MOVED_AT_PATTERN.exec(path.slice(dirname(path).length + 1));
958
+ return { path, time: info ? (moved ? Number(moved[1]) : mtime) : -Infinity, mtime };
959
+ }));
960
+ keyed.sort((a, b) => a.time - b.time || a.mtime - b.mtime || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
961
+ return keyed.at(-1)!.path;
962
+ }
963
+
823
964
  const SOURCE_ATTEMPTS = 6;
824
965
  /** Retries (with these delays) of a transient lstat/read failure before a reader gives up on this refresh. */
825
966
  const TRANSIENT_RETRY_DELAYS_MS = [15, 60, 150];
@@ -883,7 +1024,13 @@ function parseArchiveBytes(kind: "legacy" | "generation", generation: number, pa
883
1024
 
884
1025
  class ArchiveRestart extends Error {}
885
1026
 
886
- const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
1027
+ /**
1028
+ * A retry delay. Deliberately not unref'd: the read is awaited by a Pi
1029
+ * handler (agent_settled, model_select, session_shutdown...), and in print
1030
+ * mode an unref'd delay lets the event loop drain mid-handler, so Pi exits
1031
+ * without session_shutdown (see renameWithRetry).
1032
+ */
1033
+ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
887
1034
 
888
1035
  export type ReadStatsArchiveOptions = {
889
1036
  /** Throw on a transient I/O failure instead of serving the last good snapshot (compaction). */
@@ -993,7 +1140,7 @@ async function locateAndReadArchive(archivePath: string, options: ReadStatsArchi
993
1140
  let info: import("node:fs").Stats | undefined;
994
1141
  try {
995
1142
  await testHooks.beforeLstat?.(archivePath);
996
- info = await lstat(archivePath);
1143
+ info = await statsReadFs().lstat(archivePath);
997
1144
  } catch (error) {
998
1145
  if (getErrorCode(error) !== "ENOENT") throw error;
999
1146
  }
@@ -1005,7 +1152,7 @@ async function locateAndReadArchive(archivePath: string, options: ReadStatsArchi
1005
1152
  return legacyCorruptView(archivePath, parsed.parsed.sha256);
1006
1153
  }
1007
1154
  if (info && !info.isDirectory()) return legacyCorruptView(archivePath, undefined);
1008
- const placeholder = listing.placeholders.at(-1);
1155
+ const placeholder = await newestMigrationPlaceholder(listing.placeholders);
1009
1156
  if (placeholder) {
1010
1157
  const parsed = await readArchiveFile(placeholder, "legacy", 0, options, restartIfNewer);
1011
1158
  if (!parsed) throw new ArchiveRestart();
@@ -1036,7 +1183,7 @@ async function readArchiveFile(
1036
1183
  let info: import("node:fs").Stats;
1037
1184
  try {
1038
1185
  await testHooks.beforeLstat?.(path);
1039
- info = await lstat(path);
1186
+ info = await statsReadFs().lstat(path);
1040
1187
  } catch (error) {
1041
1188
  return onError(generation, error);
1042
1189
  }
@@ -1052,7 +1199,7 @@ async function readArchiveFile(
1052
1199
  let bytes: Buffer;
1053
1200
  try {
1054
1201
  await testHooks.beforeReadFile?.(path);
1055
- bytes = await readFile(path);
1202
+ bytes = await statsReadFs().readFile(path);
1056
1203
  } catch (error) {
1057
1204
  archiveFileCache.delete(path);
1058
1205
  return onError(generation, error);
@@ -1080,7 +1227,50 @@ export async function readStatsArchiveView(archivePath: string = SHARD_ARCHIVE_P
1080
1227
  return (await readStatsArchiveDetailed(archivePath, options)).view;
1081
1228
  }
1082
1229
 
1083
- 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
+ };
1084
1274
 
1085
1275
  /**
1086
1276
  * The raw shards and the archive as one consistent snapshot. Order matters:
@@ -1090,15 +1280,21 @@ export type StatsSnapshot = { rawShards: PersistedStatsShardV7[]; archive: Stats
1090
1280
  * persistent transient error and served the last good snapshot, that
1091
1281
  * snapshot may predate shards deleted since; pairing it with the fresh
1092
1282
  * listing would undercount, so the previous snapshot is reused as a whole
1093
- * (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.
1094
1286
  */
1095
1287
  export async function readStatsSnapshot(
1096
1288
  previous?: StatsSnapshot,
1097
1289
  directory: string = SHARD_FILES_DIR,
1098
1290
  archivePath: string = SHARD_ARCHIVE_PATH,
1291
+ options: ReadStatsSnapshotOptions = {},
1099
1292
  ): Promise<StatsSnapshot> {
1100
- const rawShards = await readValidStatsShardsV7(directory);
1101
- 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);
1102
1298
  if (stale && previous && previous.archive === view) {
1103
1299
  // Only a newer generation can have deleted shards this archive misses.
1104
1300
  // While it is still the newest one (highest generations never go back:
@@ -1349,12 +1545,13 @@ async function moveLegacyArchiveAside(archivePath: string, base: StatsArchiveVie
1349
1545
  const expected = base.legacySourceSha256;
1350
1546
  let placeholder = source;
1351
1547
  if (source === archivePath) {
1352
- placeholder = join(dirname(archivePath), `archive.migrating-${randomUUID()}.json`);
1548
+ placeholder = migrationPlaceholderPath(archivePath);
1353
1549
  try {
1354
1550
  await renameWithRetry(archivePath, placeholder, LEGACY_ARCHIVE_RENAME_BUDGET_MS);
1355
1551
  } catch {
1356
1552
  return false;
1357
1553
  }
1554
+ await testHooks.afterMigrationStep?.("moved-aside", archivePath, placeholder);
1358
1555
  }
1359
1556
  try {
1360
1557
  await createLegacyTombstone(archivePath);
@@ -1374,13 +1571,38 @@ async function moveLegacyArchiveAside(archivePath: string, base: StatsArchiveVie
1374
1571
  // 2.9.0 republished between this pass's read and the move: undo, so the
1375
1572
  // next pass migrates the newer file.
1376
1573
  await rm(archivePath, { recursive: true, force: true }).catch(() => undefined);
1377
- await renameWithRetry(placeholder, archivePath, LEGACY_ARCHIVE_RENAME_BUDGET_MS).catch(() => undefined);
1574
+ await testHooks.afterMigrationStep?.("undo-removed-tombstone", archivePath, placeholder);
1575
+ await restoreLegacyArchive(placeholder, archivePath);
1378
1576
  return false;
1379
1577
  }
1380
1578
  await fsyncDirectory(dirname(archivePath));
1381
1579
  return true;
1382
1580
  }
1383
1581
 
1582
+ /**
1583
+ * Undo a move aside: put the placeholder back as archive.json without ever
1584
+ * replacing a file there. Between removing the tombstone and this step a
1585
+ * 2.9.0 process (holding the lock after a stale takeover) may already have
1586
+ * published archive.json again; a rename would silently overwrite it, losing
1587
+ * what it absorbed (its raw shards are already deleted). link() is a
1588
+ * compare-and-swap: EEXIST keeps 2.9.0's newer file as the archive and keeps
1589
+ * the placeholder for inspection (set aside once a generation exists, never
1590
+ * counted, so nothing is counted twice). Without hard links the rename is
1591
+ * the only way back (the window stays open on such filesystems).
1592
+ */
1593
+ async function restoreLegacyArchive(placeholder: string, archivePath: string): Promise<void> {
1594
+ try {
1595
+ await (testHooks.link ?? link)(placeholder, archivePath);
1596
+ } catch (error) {
1597
+ if (getErrorCode(error) === "EEXIST") return;
1598
+ await renameWithRetry(placeholder, archivePath, LEGACY_ARCHIVE_RENAME_BUDGET_MS).catch(() => undefined);
1599
+ return;
1600
+ }
1601
+ // Both names are the same file now; drop the placeholder. If that fails it
1602
+ // is resolved later (its bytes are the ones the next migration reads).
1603
+ await unlink(placeholder).catch(() => undefined);
1604
+ }
1605
+
1384
1606
  /** Instance ids of every shard-named file in `directory`, readable or not. */
1385
1607
  async function listShardInstanceIds(directory: string): Promise<Set<string>> {
1386
1608
  let names: string[];
@@ -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
+ }