@crvouga/homelab 0.23.10 → 0.23.11

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.
@@ -776,29 +776,71 @@ def expire_entries(directory, hours, busy, now, dry_run):
776
776
  return freed
777
777
 
778
778
 
779
- def footprint(paths):
780
- """What the files under paths hold: their bytes, the bytes of the ones
781
- that have more than one link, and their share of the disk, where a file
782
- with N links is charged a 1/N share to each of them. Nothing is
783
- remembered per file: a node may hold millions."""
779
+ # Inventory is optional. Keep the deadline well below the service timeout.
780
+ INVENTORY_SECONDS = 60
781
+ INVENTORY_IO_FULL_PERCENT = 20
782
+
783
+
784
+ class InventoryDeferred(Exception):
785
+ pass
786
+
787
+
788
+ def inventory_checkpoint(proc):
789
+ deadline = time.monotonic() + INVENTORY_SECONDS
790
+ next_sample = 0
791
+
792
+ def check():
793
+ nonlocal next_sample
794
+ now = time.monotonic()
795
+ if now >= deadline:
796
+ raise InventoryDeferred('deadline')
797
+ if proc is None or now < next_sample:
798
+ return
799
+ next_sample = now + 1
800
+ try:
801
+ for line in (Path(proc) / 'pressure/io').read_text().splitlines():
802
+ if line.startswith('full '):
803
+ fields = dict(field.split('=', 1) for field in line.split()[1:])
804
+ if float(fields['avg10']) >= INVENTORY_IO_FULL_PERCENT:
805
+ raise InventoryDeferred('io-pressure')
806
+ break
807
+ except (OSError, ValueError, KeyError):
808
+ pass # The monotonic budget also applies without PSI.
809
+
810
+ return check
811
+
812
+
813
+ def footprint(paths, check):
814
+ """Measure allocated blocks, charging each hardlink its share."""
784
815
  total = linked = charged = 0
816
+
817
+ def files(path):
818
+ check()
819
+ try:
820
+ with os.scandir(path) as entries:
821
+ for entry in entries:
822
+ check()
823
+ try:
824
+ metadata = entry.stat(follow_symlinks=False)
825
+ except FileNotFoundError:
826
+ continue
827
+ if stat.S_ISDIR(metadata.st_mode):
828
+ yield from files(entry.path)
829
+ elif stat.S_ISREG(metadata.st_mode):
830
+ yield metadata
831
+ except FileNotFoundError:
832
+ return # A build may remove a path during inventory.
833
+
785
834
  for top in paths:
835
+ check()
786
836
  if not is_real_dir(top):
787
837
  continue
788
- for current, dirs, files in os.walk(top):
789
- dirs[:] = [d for d in dirs if not os.path.islink(os.path.join(current, d))]
790
- for name in files:
791
- try:
792
- st = os.lstat(os.path.join(current, name))
793
- except OSError:
794
- continue
795
- if not stat.S_ISREG(st.st_mode):
796
- continue
797
- size = st.st_blocks * 512
798
- total += size
799
- charged += size / max(1, st.st_nlink)
800
- if st.st_nlink > 1:
801
- linked += size
838
+ for st in files(top):
839
+ size = st.st_blocks * 512
840
+ total += size
841
+ charged += size / max(1, st.st_nlink)
842
+ if st.st_nlink > 1:
843
+ linked += size
802
844
  return total, linked, int(charged)
803
845
 
804
846
 
@@ -806,7 +848,7 @@ def footprint(paths):
806
848
  LINKED_STORES = ('pnpm', 'bun')
807
849
 
808
850
 
809
- def measure(home, worktree_roots):
851
+ def measure(home, worktree_roots, check):
810
852
  """What the worktrees, the package stores and the tool installs take on
811
853
  disk, the share of the worktrees' and stores' bytes that is hardlinked,
812
854
  and whether every store is on the filesystem of every worktree root:
@@ -814,12 +856,13 @@ def measure(home, worktree_roots):
814
856
  worktrees = [os.path.join(home, root) for root in worktree_roots]
815
857
  stores = [os.path.join(home, STORES[name][0]) for name in LINKED_STORES]
816
858
  tools = [os.path.join(home, '.local', 'share', 'mise', 'installs')]
817
- worktree_total, worktree_linked, worktree_bytes = footprint(worktrees)
818
- store_total, store_linked, store_bytes = footprint(stores)
819
- _, _, tool_bytes = footprint(tools)
859
+ worktree_total, worktree_linked, worktree_bytes = footprint(worktrees, check)
860
+ store_total, store_linked, store_bytes = footprint(stores, check)
861
+ _, _, tool_bytes = footprint(tools, check)
820
862
  total = worktree_total + store_total
821
863
  devices = {}
822
864
  for path in worktrees + stores:
865
+ check()
823
866
  try:
824
867
  devices[path] = os.stat(path).st_dev
825
868
  except OSError:
@@ -849,6 +892,28 @@ def write_report(path, report):
849
892
  os.replace(temporary, path)
850
893
 
851
894
 
895
+ def report_collection(path, outcome, home, roots, proc):
896
+ started = int(time.time())
897
+ inventory = {'status': 'pending', 'started': started}
898
+ write_report(path, {**outcome, 'inventory': inventory})
899
+ check = inventory_checkpoint(proc)
900
+ measured = {}
901
+ try:
902
+ check()
903
+ measured = measure(home, roots, check)
904
+ check()
905
+ except InventoryDeferred as error:
906
+ inventory.update(status='deferred', reason=str(error))
907
+ measured = {}
908
+ except OSError:
909
+ inventory.update(status='deferred', reason='unavailable')
910
+ measured = {}
911
+ else:
912
+ inventory.update(status='complete')
913
+ inventory['finished'] = int(time.time())
914
+ write_report(path, {**outcome, **measured, 'inventory': inventory})
915
+
916
+
852
917
  def pair(text, kind):
853
918
  name, _, value = text.rpartition('=')
854
919
  if not name:
@@ -1413,7 +1478,7 @@ def main(argv):
1413
1478
  free_mib={p: v // MIB for p, v in after.items()})
1414
1479
  if args.report and not args.dry_run:
1415
1480
  final_used = max(used_percent(p) for p in paths) if target else None
1416
- write_report(os.path.join(home, args.report), {
1481
+ report_collection(os.path.join(home, args.report), {
1417
1482
  'version': 1,
1418
1483
  'operationFailures': OPERATION_FAILURES,
1419
1484
  'finished': int(time.time()),
@@ -1424,8 +1489,7 @@ def main(argv):
1424
1489
  'pnpmStores': generations,
1425
1490
  **({'targetUsedPercent': target, 'usedPercentBefore': initial_used,
1426
1491
  'usedPercentAfter': final_used, 'targetReached': final_used <= target} if target else {}),
1427
- **measure(home, args.worktree_root),
1428
- })
1492
+ }, home, args.worktree_root, None if args.lsof else args.proc)
1429
1493
 
1430
1494
 
1431
1495
  if __name__ == '__main__':
package/docs/runbooks.md CHANGED
@@ -14,7 +14,7 @@ It reads a code by where it stands, never by the word it ends with. The CLI
14
14
  proxy documents the codes of its own commands in
15
15
  [its README](../cliproxy/README.md); the ones converge reports are here.
16
16
 
17
- There are 509 codes; 111 need a person.
17
+ There are 510 codes; 111 need a person.
18
18
 
19
19
  ## Bootstrap of a new or returning worker
20
20
 
@@ -104,6 +104,7 @@ There are 509 codes; 111 need a person.
104
104
  - `DISK_GC_TIMER_MISSING`: the disk GC timer is missing, stopped or disabled.
105
105
  - `DISK_GC_MEMORY_POLICY_STALE`: the effective collector memory limit differs from the bounded Git-maintenance budget in the Ubuntu policy. Run `homelab converge` and inspect service drop-ins if it remains different; the old 512 MiB limit cannot complete representative large-repository maintenance.
106
106
  - `DISK_GC_RUN_STALE`: the disk GC failed or its timer has not fired for two hours.
107
+ - `DISK_GC_INVENTORY_STALE`: cleanup reported its result, but footprint inventory has been pending for over a minute. Inspect the collector service and storage I/O pressure. The reported reclaimed space and cleanup failure count remain available.
107
108
  - `DISK_GC_NOT_REPORTED`: the disk GC has left no report (`resourceSafety.diskGcReport` in `ansible/ubuntu/policy.json`) since converge installed it, so `ubuntu:disk-gc` is skipped. It reports after its next run, within the hour; one that never does fails `DISK_GC_RUN_STALE`.
108
109
  - `PACKAGE_STORE_OTHER_FILESYSTEM`: a package store (`~/.local/share/pnpm/store`, `~/.bun/install/cache`) is on another filesystem than the agent worktrees (`~/.t3/worktrees`), so every install copies its packages instead of linking them, and the disk fills faster. `ubuntu:disk-gc` and `manager:disk-gc` warn. Put the store and the worktrees on one filesystem, or unset an override of `pnpm_config_store_dir` or `BUN_INSTALL_CACHE_DIR`. **Needs a person.**
109
110
  - `SERVICE_NOT_ENABLED`: service not enabled.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crvouga/homelab",
3
- "version": "0.23.10",
3
+ "version": "0.23.11",
4
4
  "description": "Keeps a set of development machines in sync: one manager and many workers",
5
5
  "license": "MIT",
6
6
  "repository": "github:crvouga/homelab",
@@ -74,5 +74,5 @@
74
74
  "engines": {
75
75
  "node": ">=22"
76
76
  },
77
- "gitHead": "d4be50a9b98a213dcbd5d228d92440fa885b0a54"
77
+ "gitHead": "9be01ec43800a7b1ab2a4e0de570807c8ceefcc1"
78
78
  }
@@ -12,15 +12,22 @@ export interface DiskGcReport {
12
12
  disposable: boolean;
13
13
  reclaimedMiB: number;
14
14
  categoriesMiB: Record<string, number>;
15
+ inventory: Inventory;
16
+ }
17
+
18
+ interface Footprint {
15
19
  worktreesMiB: number;
16
20
  storesMiB: number;
17
21
  toolsMiB: number;
18
22
  hardlinkedPercent: number;
19
- /** Whether every package store is on the filesystem of the worktrees;
20
- * null when there is no store or no worktree root yet. */
21
23
  sameFilesystem: boolean | null;
22
24
  }
23
25
 
26
+ type Inventory =
27
+ | { status: 'pending'; started: number }
28
+ | { status: 'deferred' }
29
+ | { status: 'complete'; footprint: Footprint };
30
+
24
31
  const number = (value: unknown): value is number =>
25
32
  typeof value === 'number' && Number.isFinite(value) && value >= 0;
26
33
 
@@ -49,27 +56,12 @@ export async function readDiskGcReport(
49
56
  }
50
57
  if (typeof value !== 'object' || value === null || value['version'] !== 1)
51
58
  return null;
52
- const categories =
53
- typeof value['categoriesMiB'] === 'object' &&
54
- value['categoriesMiB'] !== null
55
- ? Object.fromEntries(
56
- Object.entries(value['categoriesMiB'] as Record<string, unknown>)
57
- .filter(([name, mib]) => /^[a-z_]{1,32}$/.test(name) && number(mib))
58
- .map(([name, mib]) => [name, mib as number])
59
- )
60
- : {};
61
- const fields = [
62
- 'finished',
63
- 'reclaimedMiB',
64
- 'worktreesMiB',
65
- 'storesMiB',
66
- 'toolsMiB',
67
- 'hardlinkedPercent',
68
- ] as const;
69
- if (!fields.every((field) => number(value[field]))) return null;
70
- const same = value['sameFilesystem'];
59
+ const finished = value['finished'];
60
+ const reclaimedMiB = value['reclaimedMiB'];
61
+ const inventory = readInventory(value);
62
+ if (!number(finished) || !number(reclaimedMiB) || !inventory) return null;
71
63
  return {
72
- finished: value['finished'] as number,
64
+ finished,
73
65
  ...operationFailures(value),
74
66
  ...(number(value['usedPercentAfter']) && number(value['targetUsedPercent'])
75
67
  ? {
@@ -78,13 +70,63 @@ export async function readDiskGcReport(
78
70
  }
79
71
  : {}),
80
72
  disposable: value['disposable'] === true,
81
- reclaimedMiB: value['reclaimedMiB'] as number,
82
- categoriesMiB: categories,
83
- worktreesMiB: value['worktreesMiB'] as number,
84
- storesMiB: value['storesMiB'] as number,
85
- toolsMiB: value['toolsMiB'] as number,
86
- hardlinkedPercent: value['hardlinkedPercent'] as number,
87
- sameFilesystem: typeof same === 'boolean' ? same : null,
73
+ reclaimedMiB,
74
+ categoriesMiB: readCategories(value),
75
+ inventory,
76
+ };
77
+ }
78
+
79
+ function readCategories(
80
+ value: Record<string, unknown>
81
+ ): Record<string, number> {
82
+ return typeof value['categoriesMiB'] === 'object' &&
83
+ value['categoriesMiB'] !== null
84
+ ? Object.fromEntries(
85
+ Object.entries(value['categoriesMiB'] as Record<string, unknown>)
86
+ .filter(([name, mib]) => /^[a-z_]{1,32}$/.test(name) && number(mib))
87
+ .map(([name, mib]) => [name, mib as number])
88
+ )
89
+ : {};
90
+ }
91
+
92
+ function readInventory(value: Record<string, unknown>): Inventory | null {
93
+ const metadata = value['inventory'];
94
+ if (metadata !== undefined) {
95
+ if (!metadata || typeof metadata !== 'object') return null;
96
+ const { status, started } = metadata as Record<string, unknown>;
97
+ if (status === 'pending' && number(started)) return { status, started };
98
+ if (status === 'deferred') return { status };
99
+ if (status !== 'complete') return null;
100
+ }
101
+ return readFootprint(value);
102
+ }
103
+
104
+ function readFootprint(value: Record<string, unknown>): Inventory | null {
105
+ // Reports predating the inventory phase already include a full footprint.
106
+ const {
107
+ worktreesMiB,
108
+ storesMiB,
109
+ toolsMiB,
110
+ hardlinkedPercent,
111
+ sameFilesystem,
112
+ } = value;
113
+ if (
114
+ !number(worktreesMiB) ||
115
+ !number(storesMiB) ||
116
+ !number(toolsMiB) ||
117
+ !number(hardlinkedPercent)
118
+ )
119
+ return null;
120
+ return {
121
+ status: 'complete',
122
+ footprint: {
123
+ worktreesMiB,
124
+ storesMiB,
125
+ toolsMiB,
126
+ hardlinkedPercent,
127
+ sameFilesystem:
128
+ typeof sameFilesystem === 'boolean' ? sameFilesystem : null,
129
+ },
88
130
  };
89
131
  }
90
132
 
@@ -100,10 +142,26 @@ export function describeDiskGc(report: DiskGcReport, now: number): string {
100
142
  .join(', ');
101
143
  return [
102
144
  `The disk GC${report.disposable ? ' (disposable storage)' : ''} last ran ${minutes} min ago and reclaimed ${report.reclaimedMiB} MiB${categories ? ` (${categories})` : ''}`,
103
- `worktrees hold ${gib(report.worktreesMiB)}, package stores ${gib(report.storesMiB)}, tool installs ${gib(report.toolsMiB)}; ${report.hardlinkedPercent}% of the worktrees' and stores' bytes are hardlinked.`,
145
+ describeInventory(report.inventory, now),
104
146
  ].join('; ');
105
147
  }
106
148
 
149
+ function inventoryOverdue(inventory: Inventory, now: number): boolean {
150
+ return inventory.status === 'pending' && now - inventory.started > 60;
151
+ }
152
+
153
+ function describeInventory(inventory: Inventory, now: number): string {
154
+ if (inventory.status === 'pending')
155
+ return inventoryOverdue(inventory, now)
156
+ ? 'DISK_GC_INVENTORY_STALE: footprint inventory is overdue.'
157
+ : 'footprint inventory is in progress.';
158
+ if (inventory.status === 'deferred')
159
+ return 'footprint inventory was deferred.';
160
+ const { worktreesMiB, storesMiB, toolsMiB, hardlinkedPercent } =
161
+ inventory.footprint;
162
+ return `worktrees hold ${gib(worktreesMiB)}, package stores ${gib(storesMiB)}, tool installs ${gib(toolsMiB)}; ${hardlinkedPercent}% of the worktrees' and stores' bytes are hardlinked.`;
163
+ }
164
+
107
165
  export const STORE_FILESYSTEM_REMEDY =
108
166
  'Hardlinks cannot cross filesystems, so every install copies its packages instead of linking them from the shared store. Keep the package stores (~/.local/share/pnpm/store, ~/.bun/install/cache) on the filesystem of the agent worktrees (~/.t3/worktrees): move whichever is mounted elsewhere, or unset an override of pnpm_config_store_dir or BUN_INSTALL_CACHE_DIR.';
109
167
 
@@ -115,6 +173,9 @@ export function diskGcReportCheck(
115
173
  now: number
116
174
  ): Check {
117
175
  const summary = describeDiskGc(report, now);
176
+ const otherFilesystem =
177
+ report.inventory.status === 'complete' &&
178
+ report.inventory.footprint.sameFilesystem === false;
118
179
  if (report.operationFailures)
119
180
  return {
120
181
  id,
@@ -137,12 +198,20 @@ export function diskGcReportCheck(
137
198
  remedy: {
138
199
  action:
139
200
  'Inspect the remaining protected data and the GC service result. Add disk capacity if live data exceeds the target.' +
140
- (report.sameFilesystem === false
141
- ? ' ' + STORE_FILESYSTEM_REMEDY
142
- : ''),
201
+ (otherFilesystem ? ' ' + STORE_FILESYSTEM_REMEDY : ''),
202
+ },
203
+ };
204
+ if (inventoryOverdue(report.inventory, now))
205
+ return {
206
+ id,
207
+ status: 'warn',
208
+ summary,
209
+ remedy: {
210
+ action:
211
+ 'Inspect the collector service and storage I/O pressure. Cleanup reported its outcome before inventory began.',
143
212
  },
144
213
  };
145
- return report.sameFilesystem === false
214
+ return otherFilesystem
146
215
  ? {
147
216
  id,
148
217
  status: 'warn',