@crvouga/homelab 0.23.13 → 0.23.14
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.
|
@@ -275,6 +275,13 @@
|
|
|
275
275
|
"diskGcMemoryMaxMiB": 2048,
|
|
276
276
|
"diskGcGitTempHours": 1,
|
|
277
277
|
"diskGcFetchMaxMiB": 256,
|
|
278
|
+
"wipGuard": {
|
|
279
|
+
"memoryHighMiB": 256,
|
|
280
|
+
"memoryMaxMiB": 1024,
|
|
281
|
+
"tasks": 64,
|
|
282
|
+
"budgetSeconds": 240,
|
|
283
|
+
"randomizedDelaySeconds": 120
|
|
284
|
+
},
|
|
278
285
|
"agentTool": {
|
|
279
286
|
"memoryMiB": 4096,
|
|
280
287
|
"minimumMemoryMiB": 256,
|
|
@@ -78,7 +78,15 @@
|
|
|
78
78
|
CPUWeight=1
|
|
79
79
|
IOWeight=1
|
|
80
80
|
IOSchedulingClass=idle
|
|
81
|
-
|
|
81
|
+
# A run is bounded in time (the budget resumes on the next tick), memory
|
|
82
|
+
# and processes; its page cache is reclaimed at MemoryHigh instead of
|
|
83
|
+
# competing with T3 and the agents.
|
|
84
|
+
MemoryHigh={{ resourceSafety.wipGuard.memoryHighMiB }}M
|
|
85
|
+
MemoryMax={{ resourceSafety.wipGuard.memoryMaxMiB }}M
|
|
86
|
+
MemorySwapMax=0
|
|
87
|
+
TasksMax={{ resourceSafety.wipGuard.tasks }}
|
|
88
|
+
StateDirectory=personal/wip-guard
|
|
89
|
+
ExecStart=/usr/bin/python3 {{ development_source }}/ansible/ubuntu/wip-guard.py --root {{ development_home }}/.t3/worktrees --node %l --budget {{ resourceSafety.wipGuard.budgetSeconds }} --state %S/personal/wip-guard
|
|
82
90
|
TimeoutStartSec=600
|
|
83
91
|
- name: Declare how often work in progress is saved
|
|
84
92
|
ansible.builtin.copy:
|
|
@@ -91,6 +99,8 @@
|
|
|
91
99
|
[Timer]
|
|
92
100
|
OnBootSec=5min
|
|
93
101
|
OnUnitActiveSec=15min
|
|
102
|
+
# Do not line up with the other timers of the worker.
|
|
103
|
+
RandomizedDelaySec={{ resourceSafety.wipGuard.randomizedDelaySeconds }}
|
|
94
104
|
Persistent=true
|
|
95
105
|
[Install]
|
|
96
106
|
WantedBy=timers.target
|
|
@@ -18,18 +18,38 @@ holds the ref, the same ref is set in the repository itself, so the disk GC
|
|
|
18
18
|
can tell that the work is saved without asking the remote. Recover with
|
|
19
19
|
`git fetch origin 'refs/recovery/*:refs/recovery/*'`.
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
A run costs about nothing when nothing changed, however many worktrees exist:
|
|
22
|
+
|
|
23
|
+
- The snapshot is built in a copy of the worktree's own index, so Git's stat
|
|
24
|
+
cache is valid and only files that changed are read and hashed. An empty
|
|
25
|
+
index would make `git add --all` read every tracked file of every worktree.
|
|
26
|
+
- A fingerprint (HEAD, the changed paths and their size and mtime) is kept per
|
|
27
|
+
worktree once its work is saved; a worktree whose fingerprint is unchanged
|
|
28
|
+
is skipped after one `git status`. The fingerprints are a disposable cache,
|
|
29
|
+
and a day old at most: without them every worktree is saved again, which is
|
|
30
|
+
always safe.
|
|
31
|
+
- A run has a time budget. Worktrees are taken in a stable order and the next
|
|
32
|
+
run resumes after the last one that finished, so a busy worker spends a
|
|
33
|
+
bounded amount of work per tick and no worktree starves.
|
|
34
|
+
|
|
35
|
+
Every decision is one JSON line on stdout, and so is the run: its duration,
|
|
36
|
+
the worktrees seen, visited and left for the next run, and its peak memory.
|
|
22
37
|
|
|
23
38
|
Usage: wip-guard.py --root DIR [--root DIR ...] [--node ID] [--remote NAME]
|
|
24
|
-
[--max-depth N] [--
|
|
39
|
+
[--max-depth N] [--budget SECONDS] [--state DIR]
|
|
40
|
+
[--dry-run]
|
|
25
41
|
"""
|
|
26
42
|
import argparse
|
|
43
|
+
import hashlib
|
|
27
44
|
import json
|
|
28
45
|
import os
|
|
29
46
|
import re
|
|
47
|
+
import resource
|
|
48
|
+
import shutil
|
|
30
49
|
import socket
|
|
31
50
|
import subprocess
|
|
32
51
|
import tempfile
|
|
52
|
+
import time
|
|
33
53
|
from pathlib import Path
|
|
34
54
|
|
|
35
55
|
GIT = ['git', '-c', 'safe.directory=*']
|
|
@@ -68,18 +88,45 @@ def ref_part(value):
|
|
|
68
88
|
return part or 'unnamed'
|
|
69
89
|
|
|
70
90
|
|
|
91
|
+
def fingerprint(path, head):
|
|
92
|
+
"""What identifies the worktree's work: HEAD, the paths that differ from it
|
|
93
|
+
and the size and mtime of each. None when Git cannot tell."""
|
|
94
|
+
status = git(path, '--no-optional-locks', 'status', '--porcelain=v1', '-z',
|
|
95
|
+
'--untracked-files=all')
|
|
96
|
+
if status.returncode != 0:
|
|
97
|
+
return None
|
|
98
|
+
digest = hashlib.sha256(head.encode())
|
|
99
|
+
for entry in status.stdout.split('\0'):
|
|
100
|
+
if not entry:
|
|
101
|
+
continue
|
|
102
|
+
digest.update(entry.encode(errors='surrogateescape'))
|
|
103
|
+
try:
|
|
104
|
+
seen = os.lstat(os.path.join(path, entry[3:]))
|
|
105
|
+
digest.update(b'%d:%d' % (seen.st_size, seen.st_mtime_ns))
|
|
106
|
+
except OSError:
|
|
107
|
+
digest.update(b'absent')
|
|
108
|
+
return digest.hexdigest()
|
|
109
|
+
|
|
110
|
+
|
|
71
111
|
def snapshot(path):
|
|
72
112
|
"""The worktree's files as one commit on HEAD, or HEAD when clean."""
|
|
73
113
|
head = git(path, 'rev-parse', '--verify', 'HEAD').stdout.strip()
|
|
74
114
|
if not head:
|
|
75
115
|
return None, None
|
|
76
116
|
with tempfile.TemporaryDirectory() as private:
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
117
|
+
copy = os.path.join(private, 'index')
|
|
118
|
+
env = {'GIT_INDEX_FILE': copy}
|
|
119
|
+
# The worktree's own index knows each file's size and mtime, so `add`
|
|
120
|
+
# hashes only what changed. Without one, start from HEAD.
|
|
121
|
+
real = git(path, 'rev-parse', '--path-format=absolute', '--git-path', 'index').stdout.strip()
|
|
122
|
+
try:
|
|
123
|
+
shutil.copyfile(real, copy)
|
|
124
|
+
except OSError:
|
|
125
|
+
if git(path, 'read-tree', 'HEAD', env=env).returncode != 0:
|
|
126
|
+
return head, None
|
|
127
|
+
if git(path, 'add', '--all', '--', '.', env=env).returncode != 0:
|
|
81
128
|
return head, None
|
|
82
|
-
tree = git(path, 'write-tree', env=
|
|
129
|
+
tree = git(path, 'write-tree', env=env).stdout.strip()
|
|
83
130
|
if tree == git(path, 'rev-parse', 'HEAD^{tree}').stdout.strip():
|
|
84
131
|
return head, head
|
|
85
132
|
commit = git(path, 'commit-tree', tree, '-p', head, '-m',
|
|
@@ -87,13 +134,59 @@ def snapshot(path):
|
|
|
87
134
|
return head, commit.stdout.strip() or None
|
|
88
135
|
|
|
89
136
|
|
|
90
|
-
|
|
137
|
+
class Stamps:
|
|
138
|
+
"""Fingerprints of saved work, one small file per worktree. A cache: losing
|
|
139
|
+
it only costs a full run."""
|
|
140
|
+
|
|
141
|
+
def __init__(self, directory):
|
|
142
|
+
self.directory = Path(directory) if directory else None
|
|
143
|
+
if self.directory:
|
|
144
|
+
try:
|
|
145
|
+
self.directory.mkdir(parents=True, exist_ok=True)
|
|
146
|
+
except OSError:
|
|
147
|
+
self.directory = None
|
|
148
|
+
|
|
149
|
+
def _file(self, name):
|
|
150
|
+
return self.directory / hashlib.sha256(name.encode()).hexdigest()[:32]
|
|
151
|
+
|
|
152
|
+
def get(self, name, max_age=None):
|
|
153
|
+
if not self.directory:
|
|
154
|
+
return None
|
|
155
|
+
try:
|
|
156
|
+
file = self._file(name)
|
|
157
|
+
if max_age is not None and time.time() - file.stat().st_mtime > max_age:
|
|
158
|
+
return None
|
|
159
|
+
return file.read_text().strip()
|
|
160
|
+
except OSError:
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
def set(self, name, value):
|
|
164
|
+
if not self.directory:
|
|
165
|
+
return
|
|
166
|
+
try:
|
|
167
|
+
self._file(name).write_text(value + '\n')
|
|
168
|
+
except OSError:
|
|
169
|
+
pass
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# A saved worktree is saved again after this long even when unchanged, so a
|
|
173
|
+
# recovery ref lost on the remote comes back.
|
|
174
|
+
STAMP_MAX_AGE = 24 * 3600
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def guard(path, node, remote, dry_run, stamps):
|
|
91
178
|
if git(path, 'remote', 'get-url', remote).returncode != 0:
|
|
92
179
|
return log(worktree=str(path), action='skip', reason='no-remote')
|
|
180
|
+
head = git(path, 'rev-parse', '--verify', 'HEAD').stdout.strip()
|
|
181
|
+
seen = '%s %s' % (node, fingerprint(path, head)) if head else None
|
|
182
|
+
if seen and stamps.get(str(path), STAMP_MAX_AGE) == seen:
|
|
183
|
+
return log(worktree=str(path), action='skip', reason='unchanged')
|
|
93
184
|
head, commit = snapshot(path)
|
|
94
185
|
if not commit:
|
|
95
186
|
return log(worktree=str(path), action='skip', reason='no-commit')
|
|
96
187
|
if commit == head and git(path, 'branch', '--remotes', '--contains', head).stdout.strip():
|
|
188
|
+
if seen and not dry_run:
|
|
189
|
+
stamps.set(str(path), seen)
|
|
97
190
|
return log(worktree=str(path), action='skip', reason='clean')
|
|
98
191
|
branch = git(path, 'symbolic-ref', '--quiet', '--short', 'HEAD').stdout.strip()
|
|
99
192
|
ref = 'refs/recovery/%s/%s' % (ref_part(node), ref_part(branch or 'detached-' + head[:12]))
|
|
@@ -105,23 +198,57 @@ def guard(path, node, remote, dry_run):
|
|
|
105
198
|
# a disposable fleet removes a worktree whose work it holds
|
|
106
199
|
# (disk-gc.py, saved_in_recovery_ref).
|
|
107
200
|
git(path, 'update-ref', ref, commit)
|
|
201
|
+
if seen:
|
|
202
|
+
stamps.set(str(path), seen)
|
|
108
203
|
log(worktree=str(path), action='pushed' if pushed.returncode == 0 else 'failed', ref=ref)
|
|
109
204
|
|
|
110
205
|
|
|
206
|
+
def resume(paths, stamps):
|
|
207
|
+
"""The worktrees in a stable order, starting after the last one a run
|
|
208
|
+
finished, so a run cut short by its budget never starves the others."""
|
|
209
|
+
last = stamps.get('cursor')
|
|
210
|
+
if last in paths:
|
|
211
|
+
at = paths.index(last) + 1
|
|
212
|
+
return paths[at:] + paths[:at]
|
|
213
|
+
return paths
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def peak_mib():
|
|
217
|
+
# ru_maxrss is KiB on Linux; the git processes are the children.
|
|
218
|
+
return max(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
|
|
219
|
+
resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss) // 1024
|
|
220
|
+
|
|
221
|
+
|
|
111
222
|
def main():
|
|
112
223
|
parser = argparse.ArgumentParser()
|
|
113
224
|
parser.add_argument('--root', action='append', required=True)
|
|
114
225
|
parser.add_argument('--node', default=socket.gethostname().split('.')[0])
|
|
115
226
|
parser.add_argument('--remote', default='origin')
|
|
116
227
|
parser.add_argument('--max-depth', type=int, default=3)
|
|
228
|
+
parser.add_argument('--budget', type=float, default=0,
|
|
229
|
+
help='seconds of work per run; 0 means no limit')
|
|
230
|
+
parser.add_argument('--state', default=None,
|
|
231
|
+
help='where fingerprints of saved work are kept')
|
|
117
232
|
parser.add_argument('--dry-run', action='store_true')
|
|
118
233
|
options = parser.parse_args()
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
234
|
+
started = time.monotonic()
|
|
235
|
+
stamps = Stamps(None if options.dry_run else options.state)
|
|
236
|
+
paths = [str(path) for root in options.root
|
|
237
|
+
for path in worktrees(Path(root).expanduser(), options.max_depth)]
|
|
238
|
+
visited = 0
|
|
239
|
+
for path in resume(paths, stamps):
|
|
240
|
+
# Every run makes progress: the first worktree is always taken.
|
|
241
|
+
if visited and options.budget and time.monotonic() - started > options.budget:
|
|
242
|
+
break
|
|
243
|
+
try:
|
|
244
|
+
guard(Path(path), options.node, options.remote, options.dry_run, stamps)
|
|
245
|
+
except (OSError, subprocess.SubprocessError):
|
|
246
|
+
log(worktree=path, action='failed', reason='git')
|
|
247
|
+
visited += 1
|
|
248
|
+
if not options.dry_run:
|
|
249
|
+
stamps.set('cursor', path)
|
|
250
|
+
log(event='run', worktrees=len(paths), visited=visited, deferred=len(paths) - visited,
|
|
251
|
+
seconds=round(time.monotonic() - started, 1), peak_mib=peak_mib())
|
|
125
252
|
|
|
126
253
|
|
|
127
254
|
if __name__ == '__main__':
|
package/docs/durability.md
CHANGED
|
@@ -24,3 +24,12 @@ The guard is `ansible/ubuntu/wip-guard.py`, run by the user timer
|
|
|
24
24
|
`personal-worker-wip-guard.timer` that `ansible/ubuntu/tasks/recovery.yml`
|
|
25
25
|
installs. It pushes with the worker's own Git credentials, so a worktree
|
|
26
26
|
whose remote the worker cannot write to is reported and skipped.
|
|
27
|
+
|
|
28
|
+
A run costs about nothing when nothing changed: the guard keeps a fingerprint
|
|
29
|
+
of each worktree it saved (`HEAD`, the changed paths with their size and
|
|
30
|
+
mtime) under `~/.local/state/personal/wip-guard` and skips a worktree whose
|
|
31
|
+
fingerprint is unchanged, for a day at most. The snapshot is built from a copy
|
|
32
|
+
of the worktree's own index, so only files that changed are read. A run has a
|
|
33
|
+
time budget (`resourceSafety.wipGuard` in the Ubuntu policy) and resumes after
|
|
34
|
+
the last worktree it finished; its unit is bounded in memory and processes. The
|
|
35
|
+
last line of a run is a JSON `run` event with its duration and peak memory.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crvouga/homelab",
|
|
3
|
-
"version": "0.23.
|
|
3
|
+
"version": "0.23.14",
|
|
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": "
|
|
77
|
+
"gitHead": "f3f930e13a324adc8c50540dc27818799bd30439"
|
|
78
78
|
}
|