@crvouga/homelab 0.23.10 → 0.23.12

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.
@@ -50,6 +50,16 @@ def reserved(root, budget):
50
50
  return total
51
51
 
52
52
 
53
+ def grant(policy, budget, reserve, headroom, reservations):
54
+ # A shell's maximum is an upper bound, not its minimum working set. Keep
55
+ # small inspection/recovery commands usable without overcommitting memory.
56
+ mib = 1024 * 1024
57
+ minimum = min(budget, policy.get('minimumMemoryMiB', 256) * mib)
58
+ granted = min(budget, max(0, headroom - reservations - reserve))
59
+ granted = granted // mib * mib
60
+ return granted if granted >= minimum else 0
61
+
62
+
53
63
  def main():
54
64
  policy = json.loads(Path(__file__).with_name('agent-tool-policy.json').read_text())
55
65
  runtime = Path(os.environ['XDG_RUNTIME_DIR'])
@@ -67,9 +77,15 @@ def main():
67
77
  # section. Kernel hard caps enforce every granted reservation afterwards.
68
78
  with (runtime / 'homelab-tool-admission.lock').open('a') as lock:
69
79
  fcntl.flock(lock, fcntl.LOCK_EX)
70
- if available(root, Path('/proc')) - reserved(root, budget) < budget + reserve:
80
+ requested = budget
81
+ budget = grant(policy, requested, reserve, available(root, Path('/proc')),
82
+ reserved(root, requested))
83
+ if budget == 0:
71
84
  sys.stderr.write('AGENT_TOOL_REFUSED: insufficient unreserved memory for a bounded shell job. Finish other jobs or move work to another worker, then retry.\n')
72
85
  return 75
86
+ if budget < requested:
87
+ sys.stderr.write('AGENT_TOOL_BUDGET: reduced memory cap to ' +
88
+ str(budget // (1024 * 1024)) + ' MiB; reduce build workers or retry later if this job exceeds it.\n')
73
89
  unit = 'homelab-tool-' + uuid.uuid4().hex + '.scope'
74
90
  env = dict(os.environ)
75
91
  env.pop('BASH_ENV', None)
@@ -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__':
@@ -23,7 +23,7 @@
23
23
  "docker-compose-v2": "2.40.3+ds1-0ubuntu1~24.04.1",
24
24
  "docker-buildx": "0.30.1-0ubuntu1~24.04.1",
25
25
  "build-essential": "12.10ubuntu1",
26
- "ca-certificates": "20260816ubuntu0.24.04.2",
26
+ "ca-certificates": "20261130ubuntu0.24.04.1",
27
27
  "curl": "8.5.0-2ubuntu10.16",
28
28
  "git": "1:2.43.0-1ubuntu7.4",
29
29
  "python3": "3.12.3-0ubuntu2.1",
@@ -66,7 +66,7 @@
66
66
  }
67
67
  }
68
68
  ],
69
- "snapshot": "20261129T000000Z",
69
+ "snapshot": "20261201T000000Z",
70
70
  "packages": {
71
71
  "sudo": "1.9.17p2-1ubuntu3.2",
72
72
  "openssh-server": "1:10.2p1-2ubuntu3.8",
@@ -75,7 +75,7 @@
75
75
  "docker-compose-v2": "2.40.3+ds1-0ubuntu1",
76
76
  "docker-buildx": "0.30.1-0ubuntu1",
77
77
  "build-essential": "12.12ubuntu2.26.04.2",
78
- "ca-certificates": "20260816ubuntu0.26.04.2",
78
+ "ca-certificates": "20261130ubuntu0.26.04.1",
79
79
  "curl": "8.18.0-1ubuntu2.8",
80
80
  "git": "1:2.53.0-1ubuntu1.1",
81
81
  "python3": "3.14.3-0ubuntu2",
@@ -277,6 +277,7 @@
277
277
  "diskGcFetchMaxMiB": 256,
278
278
  "agentTool": {
279
279
  "memoryMiB": 4096,
280
+ "minimumMemoryMiB": 256,
280
281
  "reserveMiB": 2048,
281
282
  "swapMiB": 512,
282
283
  "providerReserveMiB": 1024
@@ -19,14 +19,31 @@ import { configureShellPath } from './shell-path';
19
19
  import { installNativeAws } from './native-aws';
20
20
  import { installNativeT3 } from './native-t3';
21
21
 
22
- function run(args: string[]): void {
23
- const result = spawnSync(args[0]!, args.slice(1), {
24
- cwd: workspaceRoot,
25
- stdio: 'inherit',
26
- });
27
- if (result.error) throw result.error;
28
- if (result.status !== 0)
29
- throw new Error(`${args.join(' ')} failed (${result.status})`);
22
+ /** Pauses before each further try of a download: a registry or release host
23
+ * that answered with an error a moment ago usually answers the next call. */
24
+ const RETRY_PAUSES_SECONDS = [5, 20];
25
+
26
+ /**
27
+ * Runs a command. One that fetches from the network is given `pauses`, the
28
+ * seconds to wait before each further try, so a single failed download does
29
+ * not fail the whole toolchain; the last failure is the one reported.
30
+ */
31
+ export function run(args: string[], pauses: readonly number[] = []): void {
32
+ for (let attempt = 0; ; attempt++) {
33
+ const result = spawnSync(args[0]!, args.slice(1), {
34
+ cwd: workspaceRoot,
35
+ stdio: 'inherit',
36
+ });
37
+ if (result.error) throw result.error;
38
+ if (result.status === 0) return;
39
+ const pause = pauses[attempt];
40
+ if (pause === undefined)
41
+ throw new Error(`${args.join(' ')} failed (${result.status})`);
42
+ console.error(
43
+ `${args[0]} failed (${result.status}); trying again in ${pause}s.`
44
+ );
45
+ spawnSync('sleep', [String(pause)]);
46
+ }
30
47
  }
31
48
 
32
49
  export async function syncTools(
@@ -44,7 +61,7 @@ export async function syncTools(
44
61
  const selected = worker
45
62
  ? Object.keys(workerToolset(config.tools, config.vars, selection))
46
63
  : [];
47
- run(['mise', 'install', '--locked', ...selected]);
64
+ run(['mise', 'install', '--locked', ...selected], RETRY_PAUSES_SECONDS);
48
65
  observe('aws');
49
66
  if (!worker) await installNativeAws();
50
67
  observe('t3');
@@ -77,15 +94,18 @@ if (import.meta.main) {
77
94
  if (!process.argv.includes('--tools-only')) {
78
95
  phase = 'dependencies';
79
96
  report(phase, 'running');
80
- run([
81
- 'mise',
82
- 'exec',
83
- '--locked',
84
- '--',
85
- 'bun',
86
- 'install',
87
- '--frozen-lockfile',
88
- ]);
97
+ run(
98
+ [
99
+ 'mise',
100
+ 'exec',
101
+ '--locked',
102
+ '--',
103
+ 'bun',
104
+ 'install',
105
+ '--frozen-lockfile',
106
+ ],
107
+ RETRY_PAUSES_SECONDS
108
+ );
89
109
  }
90
110
  report(phase, 'passed');
91
111
  } catch (error) {
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.12",
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": "1d754c76bc9281a6df4a4db8f257687e2b390b6e"
78
78
  }
@@ -1,3 +1,4 @@
1
+ import { sshArgs } from '../ssh';
1
2
  import { sshConnectivity } from '../ssh-health';
2
3
  import { managerCustomizations } from '../state/t3-customizations';
3
4
  import { managerClientSettings } from '../state/t3-client-settings';
@@ -421,6 +422,7 @@ function deployWithMonitoring(
421
422
  definition: canonical,
422
423
  verifyConnectivity: (target) => sshConnectivity(target, run),
423
424
  playbook: packagePlaybook(run),
425
+ accountHome: (target) => accountHome(target, run),
424
426
  converge,
425
427
  control: () =>
426
428
  (control ??= fleetTailnetControl(canonical.tailnet, secret)),
@@ -434,6 +436,19 @@ function deployWithMonitoring(
434
436
  };
435
437
  }
436
438
 
439
+ /** The account's home on a worker, as its SSH alias reports it. */
440
+ async function accountHome(
441
+ node: FleetNode,
442
+ run: Runner
443
+ ): Promise<string | null> {
444
+ const result = await run([...sshArgs(node), 'printf "%s" "$HOME"'], {
445
+ timeoutMs: 20_000,
446
+ });
447
+ return result.ok && /^\/[A-Za-z0-9._/-]{1,4000}$/.test(result.stdout)
448
+ ? result.stdout
449
+ : null;
450
+ }
451
+
437
452
  /** One converge of a worker: privilege, Vault, the bootstrap, then what is
438
453
  * verified from the manager and the worker's monitoring.
439
454
  */
@@ -1,5 +1,9 @@
1
1
  import { sshArgs } from '../ssh';
2
- import { playbookAddress } from '../worker-reboot';
2
+ import {
3
+ MANAGED_WORKSPACE,
4
+ playbookAddress,
5
+ workerHome,
6
+ } from '../worker-reboot';
3
7
  import type { FleetDefinition } from '../definition';
4
8
  import {
5
9
  TailnetControlError,
@@ -31,6 +35,10 @@ export interface WorkerDeployment {
31
35
  verifyConnectivity?: (node: FleetNode) => Promise<Check[]>;
32
36
  /** Applies a playbook of the package from the manager. */
33
37
  playbook: PackagePlaybook;
38
+ /** The account's home on the worker, asked over its SSH alias; null when
39
+ * it is not answered. Needed only for a roster entry whose workspace does
40
+ * not name the account home. */
41
+ accountHome?: (node: FleetNode) => Promise<string | null>;
34
42
  /** One converge of the worker; `tailnetKey` is handed to its bootstrap. */
35
43
  converge: (
36
44
  node: FleetNode,
@@ -66,6 +74,11 @@ export async function deployWorker(
66
74
  before.push(...(await keyExpiry(node, deployment)));
67
75
  let target = node;
68
76
  let result = await deployment.converge(target, revision, key);
77
+ // The worker's own home, for the playbooks the manager applies, when the
78
+ // roster workspace does not carry it.
79
+ let managed: Promise<FleetNode> | undefined;
80
+ const playbookNode = (): Promise<FleetNode> =>
81
+ (managed ??= managedWorkspace(target, deployment));
69
82
  const account = await rootOnly(node, result, deployment);
70
83
  if (account) {
71
84
  before.push(account.check);
@@ -77,7 +90,7 @@ export async function deployWorker(
77
90
  const maintenance: Check[] = [];
78
91
  if (deployment.maintenanceReboot && tailscaleUpgradePending(result.checks)) {
79
92
  const upgrade = await upgradeTailscale(
80
- target,
93
+ await playbookNode(),
81
94
  revision,
82
95
  deployment.playbook
83
96
  );
@@ -88,7 +101,7 @@ export async function deployWorker(
88
101
  const reason = rebootReason(node.id, result.checks, deployment);
89
102
  if (reason) {
90
103
  const reboot = await rebootWorker(
91
- target,
104
+ await playbookNode(),
92
105
  {
93
106
  revision,
94
107
  reason,
@@ -108,13 +121,26 @@ export async function deployWorker(
108
121
  (c) => c.id.startsWith('bootstrap:') && c.status === 'fail'
109
122
  )
110
123
  ) {
111
- result.checks.push(await nativeSsh(target, deployment));
124
+ result.checks.push(await nativeSsh(await playbookNode(), deployment));
112
125
  result.checks.push(...(await connectivity(target, deployment)));
113
126
  }
114
127
  result.checks.unshift(...before, ...maintenance);
115
128
  return result;
116
129
  }
117
130
 
131
+ /** The roster entry a playbook is applied to: its own workspace when that is
132
+ * under the account home, else the managed workspace under the home the
133
+ * worker reports for the same SSH alias the converge reached it by.
134
+ */
135
+ async function managedWorkspace(
136
+ node: FleetNode,
137
+ deployment: WorkerDeployment
138
+ ): Promise<FleetNode> {
139
+ if (workerHome(node) || !deployment.accountHome) return node;
140
+ const home = await deployment.accountHome(node);
141
+ return home ? { ...node, workspace: `${home}${MANAGED_WORKSPACE}` } : node;
142
+ }
143
+
118
144
  /** Why this worker is rebooted now, if it is. A worker that converged
119
145
  * before is never rebooted for its first converge; only an explicit
120
146
  * maintenance run reboots it.
@@ -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',
package/src/runner.ts CHANGED
@@ -16,6 +16,58 @@ function terminate(child: ChildProcess): void {
16
16
  } catch {}
17
17
  }
18
18
 
19
+ const pause = (ms: number): Promise<void> =>
20
+ new Promise((done) => setTimeout(done, ms));
21
+
22
+ /** Whether any process of the group still exists, whoever owns it. */
23
+ function groupExists(group: number): boolean {
24
+ try {
25
+ process.kill(-group, 0);
26
+ return true;
27
+ } catch (error) {
28
+ // A group whose members this user may not signal still exists.
29
+ return (error as NodeJS.ErrnoException).code === 'EPERM';
30
+ }
31
+ }
32
+
33
+ /** Ends what a stopped command left in its process group. A process a
34
+ * privileged helper started for it (an Ansible module run through sudo) is
35
+ * not the user's to signal, so it outlives the SIGKILL, keeps the operation
36
+ * lock it inherited and blocks the next converge. It is signalled through
37
+ * sudo, which never asks for a password here and is left alone without it.
38
+ */
39
+ async function reap(
40
+ group: number | undefined,
41
+ privileged: (group: number) => Promise<void> = signalThroughSudo
42
+ ): Promise<void> {
43
+ if (process.platform === 'win32' || !group) return;
44
+ for (let waited = 0; waited < 500; waited += 25) {
45
+ if (!groupExists(group)) return;
46
+ await pause(25);
47
+ }
48
+ await privileged(group);
49
+ for (let waited = 0; waited < 1000 && groupExists(group); waited += 25)
50
+ await pause(25);
51
+ }
52
+
53
+ function signalThroughSudo(group: number): Promise<void> {
54
+ return new Promise((done) => {
55
+ const kill = spawn('sudo', ['-n', 'kill', '-KILL', '--', `-${group}`], {
56
+ stdio: 'ignore',
57
+ });
58
+ const timer = setTimeout(() => {
59
+ kill.kill('SIGKILL');
60
+ done();
61
+ }, 5000);
62
+ const end = (): void => {
63
+ clearTimeout(timer);
64
+ done();
65
+ };
66
+ kill.on('error', end);
67
+ kill.on('close', end);
68
+ });
69
+ }
70
+
19
71
  export function runCommand(
20
72
  command: string[],
21
73
  options: CommandOptions = {}
@@ -47,16 +99,20 @@ export function runCommand(
47
99
  child.stderr.destroy();
48
100
  resolve({ ok, stdout, stderr, reason });
49
101
  };
102
+ let stopping = false;
50
103
  const abort = (cause: CommandResult['reason']): void => {
104
+ if (stopping) return;
105
+ stopping = true;
51
106
  reason = cause;
52
107
  terminate(child);
53
- finish(false);
108
+ // The result waits until nothing of the command is left running.
109
+ void reap(child.pid).then(() => finish(false));
54
110
  };
55
111
  const timer = setTimeout(() => {
56
112
  abort('timeout');
57
113
  }, options.timeoutMs ?? 15_000);
58
114
  const capture = (stream: 'stdout' | 'stderr', chunk: string): void => {
59
- if (finished) return;
115
+ if (finished || stopping) return;
60
116
  bytes += Buffer.byteLength(chunk);
61
117
  if (bytes > MAX_OUTPUT_BYTES) {
62
118
  abort('overflow');
@@ -77,6 +133,7 @@ export function runCommand(
77
133
  abort('missing');
78
134
  });
79
135
  child.on('close', (code) => {
136
+ if (stopping) return;
80
137
  finish(code === 0 && reason === 'exit');
81
138
  });
82
139
  child.stdin.end(options.input);
@@ -59,14 +59,22 @@ export function updatesPending(checks: Check[]): boolean {
59
59
  return rebootNeeded(checks);
60
60
  }
61
61
 
62
+ /** Where a worker keeps what converge manages, under the account home. */
63
+ export const MANAGED_WORKSPACE = '/.local/share/personal/fleet';
64
+
62
65
  /** The home of the account a roster entry converges, from its workspace. */
63
66
  export function workerHome(node: FleetNode): string | null {
64
- const suffix = '/.local/share/personal/fleet';
65
- return node.workspace.endsWith(suffix)
66
- ? node.workspace.slice(0, -suffix.length) || null
67
+ return node.workspace.endsWith(MANAGED_WORKSPACE)
68
+ ? node.workspace.slice(0, -MANAGED_WORKSPACE.length) || null
67
69
  : null;
68
70
  }
69
71
 
72
+ /** Said when no account home is known for a worker: the roster entry names a
73
+ * workspace elsewhere and the worker did not report its home.
74
+ */
75
+ export const HOME_UNKNOWN =
76
+ 'The worker did not report its account home and the roster workspace is not under it, so the playbook was not applied. Check that the SSH alias logs in, or set the roster workspace to <home>/.local/share/personal/fleet, then rerun converge.';
77
+
70
78
  /** How a playbook the manager applies reaches a worker: `user@alias` only
71
79
  * for a worker whose account this run created; a worker reached from
72
80
  * declared data logs in as its declared account. Null without an account
@@ -108,8 +116,7 @@ export async function rebootWorker(
108
116
  status: 'fail',
109
117
  summary: 'WORKER_REBOOT_FAILED',
110
118
  remedy: {
111
- action:
112
- 'The roster names no workspace under the account home, so the worker was not rebooted. Rerun converge once it is enrolled.',
119
+ action: `${HOME_UNKNOWN} The worker was not rebooted.`,
113
120
  },
114
121
  };
115
122
  const result = await playbook(
@@ -1,6 +1,6 @@
1
1
  import type { PackagePlaybook } from './platform/ansible';
2
2
  import type { Check, FleetNode } from './types';
3
- import { playbookAddress } from './worker-reboot';
3
+ import { HOME_UNKNOWN, playbookAddress } from './worker-reboot';
4
4
 
5
5
  /** The worker's converge stopped because its Tailscale is older than the
6
6
  * pin, which a converge never upgrades (ansible/ubuntu/tailscale.yml).
@@ -33,10 +33,7 @@ export async function upgradeTailscale(
33
33
  playbook: PackagePlaybook
34
34
  ): Promise<Check> {
35
35
  const address = playbookAddress(node);
36
- if (!address)
37
- return FAILED(
38
- 'The roster names no workspace under the account home, so Tailscale was not upgraded. Rerun converge --maintenance-reboot once the worker is enrolled.'
39
- );
36
+ if (!address) return FAILED(`${HOME_UNKNOWN} Tailscale was not upgraded.`);
40
37
  const result = await playbook(
41
38
  'ubuntu/tailscale-upgrade.yml',
42
39
  { ...address, revision },