@vibelord/lanes 1.7.3 → 1.7.5

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.
Files changed (57) hide show
  1. package/README.md +9 -0
  2. package/package.json +1 -1
  3. package/payload/lanes/VERSION +1 -1
  4. package/payload/lanes/bin/lanes +128 -24
  5. package/payload/lanes/bin/lanes-site-serve +15 -0
  6. package/payload/lanes/bin-rs/BINARIES.json +5 -0
  7. package/payload/lanes/container/lane-mcp +108 -5
  8. package/payload/lanes/container/lane_core.py +116 -0
  9. package/payload/lanes/container/throttle-pulse +159 -14
  10. package/payload/lanes/docs/ARCHITECTURE.md +132 -13
  11. package/payload/lanes/docs/DESIGN.md +10 -8
  12. package/payload/lanes/docs/INSTALL.md +1 -1
  13. package/payload/lanes/docs/RUNBOOK.md +436 -8
  14. package/payload/lanes/docs/USERGUIDE.md +82 -9
  15. package/payload/lanes/install/host-install.sh +35 -4
  16. package/payload/lanes/libexec/adopt.py +364 -0
  17. package/payload/lanes/libexec/attach.py +35 -5
  18. package/payload/lanes/libexec/cutover.py +656 -0
  19. package/payload/lanes/libexec/docsd.py +12 -8
  20. package/payload/lanes/libexec/doctor_lanes2.py +284 -0
  21. package/payload/lanes/libexec/economy_poll.py +87 -2
  22. package/payload/lanes/libexec/gc_unregistered.py +407 -0
  23. package/payload/lanes/libexec/lanes_lib.py +474 -2
  24. package/payload/lanes/libexec/native.sh +38 -0
  25. package/payload/lanes/libexec/native_bin.py +670 -0
  26. package/payload/lanes/libexec/session_actions.py +85 -7
  27. package/payload/lanes/libexec/shadow.py +1311 -0
  28. package/payload/lanes/libexec/sidebar.py +252 -30
  29. package/payload/lanes/libexec/sidebar_status.py +373 -25
  30. package/payload/lanes/libexec/statusd.py +67 -3
  31. package/payload/lanes/libexec/tokens.py +99 -131
  32. package/payload/lanes/libexec/tokens.sh +1 -1
  33. package/payload/lanes/libexec/update.py +78 -8
  34. package/payload/lanes/libexec/users.py +282 -0
  35. package/payload/lanes/site/README.md +9 -0
  36. package/payload/lanes/site/conformance.py +280 -0
  37. package/payload/lanes/site/protocol.py +368 -0
  38. package/payload/lanes/site/server.py +314 -0
  39. package/payload/lanes/systemd/lanes-gc.service +1 -1
  40. package/payload/lanes/systemd/lanes-gc.timer +14 -3
  41. package/payload/lanes/tokens/README.md +156 -0
  42. package/payload/lanes/tokens/generate.py +930 -0
  43. package/payload/lanes/tokens/generated/parity.v1.tsv +489 -0
  44. package/payload/lanes/tokens/generated/tokens.resolved.json +835 -0
  45. package/payload/lanes/tokens/tokens.v1.json +763 -0
  46. package/payload/lanes/tokens/tokens.v1.schema.json +143 -0
  47. package/payload/lanes/web/Caddyfile +11 -0
  48. package/payload/lanes/web/README.md +253 -4
  49. package/payload/lanes/web/directory.css +95 -0
  50. package/payload/lanes/web/directory.js +951 -0
  51. package/payload/lanes/web/generated/README.md +107 -0
  52. package/payload/lanes/web/generated/lanes2_protocol.d.mts +1162 -0
  53. package/payload/lanes/web/generated/lanes2_protocol.mjs +2333 -0
  54. package/payload/lanes/web/inbox.js +1140 -0
  55. package/payload/lanes/web/mobile.js +35 -45
  56. package/payload/lanes/web/tokens.css +137 -0
  57. package/payload/manifest.json +7 -4
@@ -0,0 +1,1311 @@
1
+ #!/usr/bin/env python3
2
+ """lanes shadow runner and parity judge (Lanes 2.0 fan-out plan, lane H4; AR 7.4 Observation row, 7.6, D6).
3
+
4
+ The shadow step of a strangler flag (`LANES_RS_STATUSD=shadow` in site.conf) runs a candidate observer beside the live
5
+ one for a window of wall clock (24 h by default) and judges what each wrote. This module is that judge plus the rules
6
+ that keep the candidate harmless:
7
+
8
+ - One writer per host projection: the live writer (a patched statusd, or an owner-mode lanesd) holds
9
+ `flock $LANES_STATE/locks/observer.lock` (AR D6). This runner never takes, tries or probes that lock with a lock call:
10
+ it reads the holders from /proc/locks only (`lock_holders`) and refuses to start while nobody holds it
11
+ (`lock_patch_missing`, unless --no-writer-lock records the exception). At every tick, before and after the
12
+ candidate's cycle, it stops the run when its own pid holds the lock (`shadow_holds_observer_lock`), when the
13
+ candidate or anything in its process group, session or parent chain holds it (`candidate_holds_observer_lock`: a
14
+ shadow-only candidate never takes observer.lock, AR 7.4; the candidate is killed), and, unless --no-writer-lock,
15
+ when nobody holds it any more (`writer_lost`) or another process than at the preflight does (`writer_changed`).
16
+ `hold_observer_lock` is the writer half, for the live writer only.
17
+ - The candidate writes only below `$LANES_STATE/shadow/`: every write and read of the shadow side goes through
18
+ `ShadowTree`, which opens `shadow/` and everything below it with O_NOFOLLOW from the state directory and refuses any
19
+ path that leaves it, and the Python twin runs in its own process with LANES_STATE set to `<state>/shadow` and no
20
+ container slice at all (the guest owner install's LANES_STATUSD_SLICES=off: the shadow compares the host status
21
+ family only, AR 7.6 b).
22
+
23
+ What is compared is the host status family (AR 4.4: `status.json`, `sidebar-status/<board>.json`, `health`,
24
+ `flags/sockets-lost`), each file citing its DM row (`CATALOG`). Two profiles judge a pair of files (`compare`):
25
+
26
+ - `replay` (AR 7.6 a and b, the gate): masked keys none, no unordered set, so any byte that differs is unexplained (U).
27
+ - `drift` (AR 7.6 c, informational, never a gate): the declared mask of volatile keys (`VOLATILE`: sample times and
28
+ producer clocks such as `updated_at`, `stale_since`, `raw_since`, the health `at`, `status_at`, PSI and load values,
29
+ and `state` with a one-cycle tolerance) is lifted; every other byte must still match, the serialisation, the order
30
+ and the shape (object or list) included, so a difference outside the mask is U. A pure reordering of a declared
31
+ unordered set (`UNORDERED`) is E2, reported apart from U. Values each producer samples on its own that AR 7.6 (c)
32
+ does not mask yet (`UNMASKED_SAMPLES`) count as U on a live host until the specification lists them.
33
+
34
+ Only ticks the candidate answered `ok` for, with the live host at the pressure level the candidate was pinned to
35
+ (`ok`; AR 7.6 c: both producers pinned to one pressure level), are judged (`tick_verdict`). A tick under pressure is
36
+ counted `pressure`; a tick whose candidate failed (`err`, `timeout`, `exited`, `protocol`) or, with no candidate
37
+ driven, whose shadow family is stale is a candidate failure, and with --fail-on-unexplained a run with any candidate
38
+ failure, any U, or no judged tick at all exits 1.
39
+
40
+ The deterministic replay of recorded roots through the Python and the Rust producers is `lanes/tests/parity/` (not
41
+ shipped); it uses this module's catalog, masks and `compare`. The live-input replay (AR 7.6 b) needs statusd's teed
42
+ inputs under `shadow/inputs/`, which W18-E adds; until they exist the summary says the gate did not run.
43
+
44
+ Usage (`python3 -S -E <tree>/libexec/shadow.py ...`):
45
+ shadow.py check [--state DIR] [--home DIR] [--no-writer-lock]
46
+ the preflight as one JSON document; exit 3 when it refuses.
47
+ shadow.py run [--state DIR] [--home DIR] [--window SECONDS] [--interval SECONDS] [--warmup SECONDS]
48
+ [--candidate twin|none] [--candidate-cmd ARGV...] [--profile-label NAME] [--fail-on-unexplained]
49
+ [--no-writer-lock]
50
+ the shadow run: every interval, mirror the live inputs into shadow/, ask the candidate for one cycle
51
+ (`lanes2.shadow-candidate/1`: one `cycle <n> <level>` line in, one `ok <n>` or `err <n> <why>` line out), read
52
+ both families and judge them with the drift profile. A candidate is started with a fresh shadow family (the
53
+ previous run's is removed), killed and started again after a timeout or a protocol error, and its stderr is
54
+ drained into shadow/report/candidate.log (about LOG_MAX bytes per flush, rotated past LOG_MAX). No candidate
55
+ cycle is asked while the host's health level is not `ok` (a host under pressure gets fewer spawns). Ticks go
56
+ to shadow/report/ticks.jsonl (rotated past 8 MiB), the result to shadow/report/summary.json. The first --warmup
57
+ seconds (30) count their U apart: a candidate's first rates need two of its own samples. SIGTERM or SIGINT ends
58
+ the window early with a summary; so does a refusal or an I/O error (`shadow_io`).
59
+ Exit 0; 1 with --fail-on-unexplained and U > 0, a candidate failure or no judged tick; 3 refused.
60
+ shadow.py twin-loop
61
+ the Python twin (the candidate `twin` starts it): statusd's observation and projection, run in a process
62
+ whose LANES_STATE is <state>/shadow, pinned to the level each `cycle` line names, with main()'s web origin look
63
+ between two cycles, and without container slices, deliveries, renames or re-arms.
64
+ shadow.py compare LEFT RIGHT [--profile replay|drift]
65
+ judge two state roots' host families once; exit 1 on any U.
66
+
67
+ Refusal codes: owner_undeclared (site.conf LANES_HOST_ROLE is not `owner`: a guest owner install is required),
68
+ flag_not_shadow (LANES_RS_STATUSD is not `shadow`), lock_patch_missing (nobody holds observer.lock),
69
+ shadow_holds_observer_lock, candidate_holds_observer_lock, writer_lost, writer_changed, state_missing,
70
+ shadow_dir_unsafe (shadow/ is a link or not a directory), shadow_io (an I/O error ended the run).
71
+ """
72
+ import argparse
73
+ import contextlib
74
+ import fcntl
75
+ import fnmatch
76
+ import json
77
+ import os
78
+ import select
79
+ import signal
80
+ import subprocess
81
+ import sys
82
+ import time
83
+ from pathlib import Path
84
+
85
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
86
+ import lanes_lib as L # noqa: E402
87
+
88
+ SHADOW_DIR = 'shadow'
89
+ REPORT_DIR = ('report',) # below shadow/
90
+ INPUTS_DIR = ('inputs',) # below shadow/: statusd's live-input tee (AR 7.6 b, W18-E); read only here
91
+ CANDIDATE_LOG = 'report/candidate.log'
92
+ OBSERVER_LOCK = ('locks', 'observer.lock')
93
+ PROC = '/proc' # the REAL /proc (lock holders), never LANES_PROC_ROOT's synthetic tree
94
+ WINDOW_S = 24 * 3600
95
+ INTERVAL_S = 3.0 # statusd's INTERVAL
96
+ HEARTBEAT_S = 15.0 # statusd's HEARTBEAT: a live shadow family's health `at` is never older than
97
+ # one interval plus this (the freshness bound with no candidate driven)
98
+ CANDIDATE_TIMEOUT_S = 25.0 # statusd's cycle deadline (5 + 2 s) plus a 15 s zmx list, plus margin
99
+ WARMUP_S = 30.0 # a rate needs two fleet samples (statusd FLEET_INTERVAL 10 s) on each side
100
+ FILE_MAX = 8 << 20 # a family file bigger than this is not read (reported missing)
101
+ TICKS_MAX = 8 << 20 # ticks.jsonl rotates to ticks.jsonl.1 past this
102
+ LOG_MAX = 1 << 20 # candidate stderr kept per flush; candidate.log rotates to .1 past this
103
+ LINE_MAX = 4096 # one candidate protocol line; a longer one is a protocol error
104
+ LEVELS = ('ok', 'busy', 'critical') # lanes_lib.compute_health's words: the level a candidate is pinned to
105
+ EXAMPLES_MAX = 50 # differences kept verbatim per file in a result, and U examples in a summary
106
+ EXIT_OK, EXIT_UNEXPLAINED, EXIT_USAGE, EXIT_REFUSED = 0, 1, 2, 3
107
+ CANDIDATE_PROTOCOL = 'lanes2.shadow-candidate/1'
108
+ SUMMARY_SCHEMA = 'lanes2.shadow-summary/1'
109
+
110
+ # ------------------------------------------------------------------------------------------------ the DM catalog
111
+ # Every file a Python or Rust observer writes that parity compares: (pattern, DM row, kind, family). Patterns are
112
+ # matched segment by segment (`*` never crosses a `/`) against a path relative to a state root, or, for the container
113
+ # slice, relative to a parity fixture root (the oracle classifies a root-relative path by its location first:
114
+ # `lanes/tests/parity/oracle.py` `catalog_name`). kind: `json` (a v1 document), `line` (key=value tokens, key order is
115
+ # part of the format), `text` (bytes only). A DM row of None is a written file the master data model does not describe
116
+ # yet (a gap the parity report names; containers.json and the per-container pid files, written by statusd's container
117
+ # refresh as well as by `lanes sync`).
118
+ CATALOG = (
119
+ ('status.json', 'DM-LANES-STATUS', 'json', 'host'),
120
+ ('health', 'DM-LANES-HEALTH', 'line', 'host'),
121
+ ('sidebar-status/@directory.json', 'DM-LANES2-C7-DIRECTORY-TWIN', 'json', 'host'),
122
+ ('sidebar-status/*.json', 'DM-LANES-SIDEBAR-STATUS', 'json', 'host'),
123
+ ('flags/sockets-lost', 'DM-LANES-STATUS', 'text', 'host'),
124
+ ('resolve.dynamic/*', 'DM-LANES-STATUS', 'text', 'resolve'),
125
+ ('containers.json', None, 'json', 'containers'),
126
+ ('containers/*.pid', None, 'text', 'containers'),
127
+ ('proc/*/root/home/coder/.lz/status.json', 'DM-LANES-CONTAINER-STATUS', 'json', 'slice'),
128
+ )
129
+ HOST_FAMILY = ('status.json', 'health', 'sidebar-status/*.json', 'flags/sockets-lost') # AR 4.4, the shadow's set
130
+ MIRRORED = ('registry.json', 'containers.json', 'containers/*.pid', 'docs/counts.json') # the twin's live inputs
131
+
132
+ # ---------------------------------------------------------------------------------------- the volatile-key mask
133
+ # AR 7.6 (c), entry by entry: (path pattern, tolerance in cycles, source). A pattern masks the leaf it names and
134
+ # everything below it; `*` stands for one key (a lane id, a board, a container). tolerance 0: always lifted (a sample
135
+ # time, a producer's own clock); 1: a difference may last one cycle, a second consecutive one is U (`state`).
136
+ # Source `AR 7.6 (c)` is the specification's list; `statusd.compared` is the two sample times statusd's own rewrite
137
+ # decision already treats as noise (`fleet.at`, `throttle.at`), which AR 7.6 (c) does not list by name.
138
+ _LANE_CLOCKS = (
139
+ (('lanes', '*', 'activity'), 0, 'AR 7.6 (c)'),
140
+ (('lanes', '*', 'stale_since'), 0, 'AR 7.6 (c)'),
141
+ (('lanes', '*', 'agent', 'since'), 0, 'AR 7.6 (c)'),
142
+ (('lanes', '*', 'agent', 'raw_since'), 0, 'AR 7.6 (c)'),
143
+ (('lanes', '*', 'agent', 'stable_since'), 0, 'AR 7.6 (c)'),
144
+ (('lanes', '*', 'state'), 1, 'AR 7.6 (c)'),
145
+ )
146
+ _SAMPLES = (
147
+ (('fleet', 'at'), 0, 'statusd.compared'),
148
+ (('throttle', 'at'), 0, 'statusd.compared'),
149
+ (('fleet', 'system.pressure'), 0, 'AR 7.6 (c)'),
150
+ (('fleet', 'system.cpu.load_average.1m'), 0, 'AR 7.6 (c)'),
151
+ )
152
+ _PRESSURE = ('mem_some10', 'mem_full10', 'io_some10', 'cpu_some10', 'load1')
153
+ VOLATILE = {
154
+ 'DM-LANES-STATUS': ((('updated_at',), 0, 'AR 7.6 (c)'), (('zmx_listed_at',), 0, 'AR 7.6 (c)'),
155
+ (('health', 'at'), 0, 'AR 7.6 (c)'))
156
+ + tuple((('health', key), 0, 'AR 7.6 (c)') for key in _PRESSURE) + _LANE_CLOCKS + _SAMPLES,
157
+ 'DM-LANES-SIDEBAR-STATUS': _LANE_CLOCKS + _SAMPLES,
158
+ # C7 retains the same compatibility body. No directory field is masked.
159
+ 'DM-LANES2-C7-DIRECTORY-TWIN': _LANE_CLOCKS + _SAMPLES,
160
+ 'DM-LANES-HEALTH': ((('at',), 0, 'AR 7.6 (c)'), (('status_at',), 0, 'AR 7.6 (c)'))
161
+ + tuple(((key,), 0, 'AR 7.6 (c)') for key in _PRESSURE),
162
+ 'DM-LANES-CONTAINER-STATUS': ((('at',), 0, 'AR 7.6 (c)'),) + _LANE_CLOCKS,
163
+ }
164
+ # E2 (AR 7.6 c, "ordering of an unordered set"): the lists whose order no DM row defines — rows keyed by `id`
165
+ # (DM-LANES-STATUS `unregistered{<board>: [row]}` and `zmx{<board>: [row]}`, copied into each board file;
166
+ # DM-LANES-CONTAINER-STATUS `unregistered: [row]`, which the container readers index by `id`) and a ghost's `boards`
167
+ # (board names). Under `drift` a pure reordering of one of them is `reordered` (E2), counted apart from U; under the
168
+ # `replay` gate it is U like every other byte. The sidebar draws a board's lists in their order, so an E2 there is
169
+ # still a difference a person can see.
170
+ UNORDERED = {
171
+ 'DM-LANES-STATUS': (('unregistered', '*'), ('zmx', '*')),
172
+ 'DM-LANES-SIDEBAR-STATUS': (('unregistered', '*'), ('zmx', '*')),
173
+ 'DM-LANES2-C7-DIRECTORY-TWIN': (('unregistered', '*'), ('zmx', '*')),
174
+ 'DM-LANES-CONTAINER-STATUS': (('unregistered',), ('unregistered', '*', 'boards')),
175
+ }
176
+ # Values each producer samples from /proc/cgroups or stamps from its own publication clock that AR 7.6 (c) does not
177
+ # name. C7's content revisions are authority metadata, not a newly authorized volatile-key mask.
178
+ # They are NOT masked here: on a live host they count as U in the drift report until AR 7.6 (c) lists them (open
179
+ # spec-amendment request to the AR owner, beside `fleet.at` and `throttle.at`). A fixture's /proc is static, so the
180
+ # deterministic replay and the smoke never see them move; a 24 h guest run does. The summary names them.
181
+ UNMASKED_SAMPLES = (
182
+ 'status.json fleet.system.cpu.utilization', 'status.json fleet.system.memory.utilization',
183
+ 'status.json fleet.system.memory.usage.used', 'status.json fleet.system.linux.memory.available',
184
+ 'status.json fleet.containers[].container.cpu.percent',
185
+ 'status.json fleet.containers[].container.memory.usage.total',
186
+ 'status.json health.level', 'status.json health.swap_pct', 'status.json health.containers.*',
187
+ 'health swap_pct', 'sidebar-status/<board>.json fleet.* (the same fleet keys)',
188
+ 'sidebar-status/@directory.json directory.directory_revision',
189
+ 'sidebar-status/@directory.json directory.rows[].source.revision',
190
+ 'sidebar-status/@directory.json directory.sources[].{revision,cursor,observed_at_unix_ms}',
191
+ )
192
+ PROFILES = {
193
+ 'replay': {'masks': {}, 'unordered': {}, 'gate': True, 'source': 'AR 7.6 (a) and (b): masked keys none'},
194
+ 'drift': {'masks': VOLATILE, 'unordered': UNORDERED, 'gate': False,
195
+ 'source': 'AR 7.6 (c): informational, never a gate'},
196
+ }
197
+ # The serialisations the Lanes producers use (statusd: compact; the container slice: indent 1, UTF-8; a board
198
+ # projection: sorted keys; C7 directory: sorted keys without separator spaces; containers.json: indent 2).
199
+ # The drift profile requires both sides to be one of these and
200
+ # the SAME one, so a masked comparison can never hide a formatting difference.
201
+ JSON_FORMATS = (
202
+ ('compact', {}), ('indent1', {'indent': 1}), ('indent1-utf8', {'indent': 1, 'ensure_ascii': False}),
203
+ ('indent2', {'indent': 2}), ('sorted', {'sort_keys': True}), ('utf8', {'ensure_ascii': False}),
204
+ ('sorted-utf8', {'sort_keys': True, 'ensure_ascii': False}),
205
+ ('sorted-compact', {'sort_keys': True, 'separators': (',', ':')}),
206
+ )
207
+
208
+
209
+ class Refused(Exception):
210
+ """A machine refusal: `code` plus what a person can do instead."""
211
+
212
+ def __init__(self, code, detail):
213
+ super().__init__(f'{code}: {detail}')
214
+ self.code, self.detail = code, detail
215
+
216
+
217
+ def segments_match(pattern, path):
218
+ """Whether the `/`-separated `path` matches `pattern` segment by segment (`*` never crosses a `/`)."""
219
+ left, right = pattern.split('/'), path.split('/')
220
+ return len(left) == len(right) and all(fnmatch.fnmatchcase(p, q) for q, p in zip(left, right))
221
+
222
+
223
+ def classify(rel):
224
+ """The CATALOG entry of a relative path -> {'dm', 'kind', 'family', 'pattern'}, or None when no entry names it."""
225
+ for pattern, dm, kind, family in CATALOG:
226
+ if segments_match(pattern, rel):
227
+ return {'dm': dm, 'kind': kind, 'family': family, 'pattern': pattern}
228
+ return None
229
+
230
+
231
+ def check_profile(profile):
232
+ """Refuse a profile the judge must not run: a gate with any mask or unordered set (AR 7.6 b: masked keys none,
233
+ byte for byte), a mask or set for a DM row the catalog does not name, a tolerance other than 0 or 1, an entry
234
+ without a source -> the profile."""
235
+ masks = profile.get('masks') or {}
236
+ sets = profile.get('unordered') or {}
237
+ if profile.get('gate') and any(masks.values()):
238
+ raise Refused('mask_in_gate', 'a gate profile masks nothing (AR 7.6 b)')
239
+ if profile.get('gate') and any(sets.values()):
240
+ raise Refused('unordered_in_gate', 'a gate profile compares every list in order (AR 7.6 b)')
241
+ known = {dm for _p, dm, _k, _f in CATALOG if dm}
242
+ for dm, entries in masks.items():
243
+ if dm not in known:
244
+ raise Refused('mask_uncatalogued', f'{dm} is no catalogued DM row')
245
+ for entry in entries:
246
+ if (len(entry) != 3 or not isinstance(entry[0], tuple) or not entry[0] or entry[1] not in (0, 1)
247
+ or not isinstance(entry[2], str) or not entry[2]):
248
+ raise Refused('mask_malformed', f'{dm}: {entry!r}')
249
+ for dm, patterns in sets.items():
250
+ if dm not in known:
251
+ raise Refused('mask_uncatalogued', f'{dm} is no catalogued DM row')
252
+ for pattern in patterns:
253
+ if not isinstance(pattern, tuple) or not pattern:
254
+ raise Refused('mask_malformed', f'{dm}: unordered {pattern!r}')
255
+ return profile
256
+
257
+
258
+ # ------------------------------------------------------------------------------------------- documents and paths
259
+ def walk(value, prefix=()):
260
+ """[(path, kind, leaf)] of a JSON value in document order: one (`object` or `list`, None) entry for every non-empty
261
+ container before its children, one (`leaf`, value) for every leaf (an empty object or list is a leaf of its own).
262
+ A list index and an object key spell the same path segment; the container entries keep them apart."""
263
+ if isinstance(value, dict) and value:
264
+ out = [(prefix, 'object', None)]
265
+ for key, child in value.items():
266
+ out += walk(child, prefix + (str(key),))
267
+ return out
268
+ if isinstance(value, list) and value:
269
+ out = [(prefix, 'list', None)]
270
+ for index, child in enumerate(value):
271
+ out += walk(child, prefix + (str(index),))
272
+ return out
273
+ return [(prefix, 'leaf', value)]
274
+
275
+
276
+ def flatten(value, prefix=()):
277
+ """[(path, leaf)] of a JSON value in document order; an empty object or list is a leaf of its own."""
278
+ return [(path, leaf) for path, kind, leaf in walk(value, prefix) if kind == 'leaf']
279
+
280
+
281
+ def mask_of(masks, path):
282
+ """(matched prefix, tolerance) of the first mask entry covering `path`, else None."""
283
+ for pattern, tolerance, _source in masks:
284
+ if len(pattern) <= len(path) and all(fnmatch.fnmatchcase(path[i], pattern[i]) for i in range(len(pattern))):
285
+ return path[:len(pattern)], tolerance
286
+ return None
287
+
288
+
289
+ def parse(kind, data):
290
+ """(document, format name) of one file's bytes, or (None, None) when it does not parse as its kind."""
291
+ try:
292
+ text = data.decode('utf-8')
293
+ except UnicodeDecodeError:
294
+ return None, None
295
+ if kind == 'json':
296
+ try:
297
+ doc = json.loads(text)
298
+ except (ValueError, RecursionError):
299
+ return None, None
300
+ for name, options in JSON_FORMATS:
301
+ dumped = json.dumps(doc, **options)
302
+ if text == dumped + '\n':
303
+ return doc, name
304
+ if text == dumped:
305
+ return doc, name + '-nonl'
306
+ return doc, None
307
+ if kind == 'line':
308
+ tokens = text.rstrip('\n').split(' ')
309
+ if text.count('\n') != 1 or not text.endswith('\n') or not all('=' in token for token in tokens):
310
+ return None, None
311
+ doc = dict(token.split('=', 1) for token in tokens)
312
+ return doc, 'line' if len(doc) == len(tokens) else None
313
+ return None, None
314
+
315
+
316
+ def view(doc, masks):
317
+ """The document as the drift profile sees it: every unmasked container (its kind: object or list) and leaf (its
318
+ value) in order, and one marker per masked prefix in its place, so neither a reordering, a missing key nor a change
319
+ of shape hides behind a mask."""
320
+ tokens = []
321
+ for path, kind, leaf in walk(doc):
322
+ covered = mask_of(masks, path)
323
+ if covered is None:
324
+ tokens.append((kind, path, json.dumps(leaf, sort_keys=True) if kind == 'leaf' else None))
325
+ elif not tokens or tokens[-1] != ('masked', covered[0]):
326
+ tokens.append(('masked', covered[0]))
327
+ return tokens
328
+
329
+
330
+ def _sorted_at(node, pattern):
331
+ if not pattern:
332
+ return sorted(node, key=lambda item: json.dumps(item, sort_keys=True)) if isinstance(node, list) else node
333
+ head, rest = pattern[0], pattern[1:]
334
+ if isinstance(node, dict):
335
+ return {key: _sorted_at(child, rest) if fnmatch.fnmatchcase(str(key), head) else child
336
+ for key, child in node.items()}
337
+ if isinstance(node, list):
338
+ return [_sorted_at(child, rest) if fnmatch.fnmatchcase(str(index), head) else child
339
+ for index, child in enumerate(node)]
340
+ return node
341
+
342
+
343
+ def unordered_view(doc, sets):
344
+ """`doc` with every list a `sets` pattern names in one canonical order (its items sorted by their JSON), the
345
+ deepest sets first, so two documents that differ only by the order of such lists become equal."""
346
+ for pattern in sorted(sets, key=len, reverse=True):
347
+ doc = _sorted_at(doc, pattern)
348
+ return doc
349
+
350
+
351
+ def leaf_diff(left_doc, right_doc, masks):
352
+ """(unmasked paths that differ, [(masked path, tolerance)] that differ) between two documents, position by
353
+ position, COMPLETE: callers cut what they copy into a report, never what they judge."""
354
+ left, right = dict(flatten(left_doc)), dict(flatten(right_doc))
355
+ plain, lifted = [], []
356
+ for path in list(left) + [p for p in right if p not in left]:
357
+ if path in left and path in right and json.dumps(left[path], sort_keys=True) == json.dumps(right[path], sort_keys=True):
358
+ continue
359
+ covered = mask_of(masks, path)
360
+ if covered is None:
361
+ plain.append('.'.join(path))
362
+ else:
363
+ lifted.append(('.'.join(path), covered[1]))
364
+ return plain, lifted
365
+
366
+
367
+ def compare_one(rel, left, right, profile):
368
+ """One file's verdict under `profile`: `equal`, `masked` (only volatile keys differ: explained), `reordered` (only
369
+ the order of a declared unordered set, and volatile keys, differ: E2), or U — `unexplained`, `missing_left`,
370
+ `missing_right`, `uncatalogued`. -> {path, dm, kind, verdict, paths, masked[, tolerant]}: `paths` and `masked` at
371
+ most EXAMPLES_MAX each, `tolerant` (the tolerance-1 paths that differ, for the Judge) always complete."""
372
+ entry = classify(rel)
373
+ result = {'path': rel, 'dm': entry['dm'] if entry else None, 'kind': entry['kind'] if entry else None,
374
+ 'verdict': 'equal', 'paths': [], 'masked': []}
375
+ if entry is None:
376
+ result['verdict'] = 'uncatalogued'
377
+ return result
378
+ if left is None or right is None:
379
+ result['verdict'] = 'missing_left' if left is None else 'missing_right'
380
+ return result
381
+ if left == right:
382
+ return result
383
+ masks = (profile.get('masks') or {}).get(entry['dm'], ()) if entry['dm'] else ()
384
+ sets = (profile.get('unordered') or {}).get(entry['dm'], ()) if entry['dm'] else ()
385
+ result['verdict'] = 'unexplained'
386
+ if entry['kind'] == 'text':
387
+ result['paths'] = ['<bytes>']
388
+ return result
389
+ (left_doc, left_format), (right_doc, right_format) = parse(entry['kind'], left), parse(entry['kind'], right)
390
+ if left_doc is None or right_doc is None:
391
+ result['paths'] = ['<unparsed>']
392
+ return result
393
+ plain, lifted = leaf_diff(left_doc, right_doc, masks)
394
+ result['masked'] = [path for path, _tolerance in lifted][:EXAMPLES_MAX]
395
+ result['tolerant'] = [path for path, tolerance in lifted if tolerance]
396
+ if left_format is None or right_format is None or left_format != right_format:
397
+ result['paths'] = plain[:EXAMPLES_MAX] + [f'<format {left_format or "unknown"} vs {right_format or "unknown"}>']
398
+ return result
399
+ if not masks and not sets:
400
+ result['paths'] = plain[:EXAMPLES_MAX] or ['<format>']
401
+ return result
402
+ if view(left_doc, masks) == view(right_doc, masks):
403
+ result['verdict'] = 'masked'
404
+ return result
405
+ if sets and view(unordered_view(left_doc, sets), masks) == view(unordered_view(right_doc, sets), masks):
406
+ result['verdict'] = 'reordered'
407
+ result['paths'] = plain[:EXAMPLES_MAX] or ['<order>']
408
+ return result
409
+ result['paths'] = plain[:EXAMPLES_MAX] or ['<order, presence or shape>']
410
+ return result
411
+
412
+
413
+ UNEXPLAINED = ('unexplained', 'missing_left', 'missing_right', 'uncatalogued')
414
+
415
+
416
+ def compare(left, right, profile):
417
+ """Judge two {relative path: bytes or None} maps file by file -> [result] in path order. A path present on one
418
+ side only is U on the other; a file no CATALOG entry names is U (`uncatalogued`), never silently skipped."""
419
+ check_profile(profile)
420
+ return [compare_one(rel, left.get(rel), right.get(rel), profile) for rel in sorted(set(left) | set(right))]
421
+
422
+
423
+ def tally(results):
424
+ """{verdict: count} plus the U total, the E2 total (`reordered`) and, per DM row, the files compared."""
425
+ counts = {}
426
+ rows = {}
427
+ for result in results:
428
+ counts[result['verdict']] = counts.get(result['verdict'], 0) + 1
429
+ rows.setdefault(result['dm'] or 'DM gap', []).append(result['path'])
430
+ return {'verdicts': counts, 'unexplained': sum(counts.get(v, 0) for v in UNEXPLAINED),
431
+ 'reordered': counts.get('reordered', 0), 'dm_rows': rows}
432
+
433
+
434
+ class Judge:
435
+ """The drift profile across judged ticks (AR 7.6 c: `state` with a one-cycle tolerance, E1 sampling skew counted per
436
+ lane transition, not per cycle). A tolerance-1 difference is keyed by its dotted path (`lanes.<id>.state`), so one
437
+ lane's difference that shows in status.json, its board file and its container slice is ONE key, whatever verdict
438
+ each file has for other reasons. A key is explained at the first judged tick it shows; still showing at the next
439
+ judged tick it is U (`tolerance_exceeded`) in every file that shows it, and stays U while it shows. A key resolves
440
+ when every file that showed it was compared again (equal, or its leaves diffed) without it; it then counts one E1
441
+ unless it went U. A key whose file could not be diffed (missing, unparsed) stays open. A tick that is not judged
442
+ is never passed here and changes nothing. A key still open when the window ends is `open`, neither E nor U."""
443
+
444
+ def __init__(self):
445
+ self.pending = {} # key -> {'files': set of file paths that showed it, 'exceeded': bool}
446
+ self.e1 = 0
447
+ self.exceeded = 0
448
+
449
+ def tick(self, results):
450
+ seen, examined = {}, set()
451
+ for result in results:
452
+ if result['verdict'] == 'equal' or 'tolerant' in result:
453
+ examined.add(result['path'])
454
+ for path in result.get('tolerant') or ():
455
+ seen.setdefault(path, []).append(result)
456
+ for key, hits in seen.items():
457
+ entry = self.pending.get(key)
458
+ if entry is None:
459
+ self.pending[key] = {'files': {result['path'] for result in hits}, 'exceeded': False}
460
+ continue
461
+ if not entry['exceeded']:
462
+ entry['exceeded'] = True
463
+ self.exceeded += 1
464
+ entry['files'] |= {result['path'] for result in hits}
465
+ for result in hits:
466
+ if result['verdict'] not in UNEXPLAINED:
467
+ result['verdict'] = 'unexplained'
468
+ result['paths'] = result['paths'] + [f'<tolerance_exceeded {key}>']
469
+ for key in [key for key in self.pending if key not in seen]:
470
+ entry = self.pending[key]
471
+ if entry['files'] <= examined:
472
+ del self.pending[key]
473
+ if not entry['exceeded']:
474
+ self.e1 += 1
475
+ return results
476
+
477
+
478
+ # ---------------------------------------------------------------------------------------- reading the families
479
+ def _safe_parts(rel):
480
+ parts = tuple(rel.split('/'))
481
+ for part in parts:
482
+ L._leaf(part)
483
+ return parts
484
+
485
+
486
+ def read_file(root, rel, limit=FILE_MAX, under=()):
487
+ """The bytes of `root`/<under…>/`rel` read without following a link in any component below `root` (`root` itself
488
+ is trusted), or None."""
489
+ parts = _safe_parts(rel)
490
+ try:
491
+ fd = L.open_real_dir(root, tuple(under) + parts[:-1])
492
+ except (OSError, L.LanesError):
493
+ return None
494
+ try:
495
+ return L.read_regular_at(fd, parts[-1], limit)
496
+ finally:
497
+ os.close(fd)
498
+
499
+
500
+ def expand(root, patterns, under=()):
501
+ """Every relative path under `root`/<under…> that one of `patterns` names (a `*` segment lists that directory
502
+ without following links; a pattern without one is returned as it is)."""
503
+ found = []
504
+ for pattern in patterns:
505
+ parts = pattern.split('/')
506
+ if '*' not in pattern:
507
+ found.append(pattern)
508
+ continue
509
+ try:
510
+ fd = L.open_real_dir(root, tuple(under) + tuple(parts[:-1]))
511
+ except (OSError, L.LanesError):
512
+ continue
513
+ try:
514
+ names = sorted(os.listdir(fd))
515
+ finally:
516
+ os.close(fd)
517
+ found += ['/'.join(parts[:-1] + [name]) for name in names
518
+ if fnmatch.fnmatchcase(name, parts[-1]) and not name.startswith('.')]
519
+ return sorted(set(found))
520
+
521
+
522
+ def read_family(root, patterns=HOST_FAMILY, under=()):
523
+ """{relative path: bytes} of the family files present under `root`/<under…> (absent files are left out)."""
524
+ out = {}
525
+ for rel in expand(root, patterns, under):
526
+ data = read_file(root, rel, under=under)
527
+ if data is not None:
528
+ out[rel] = data
529
+ return out
530
+
531
+
532
+ def health_of(family):
533
+ """The `health` line of a family as a dict of strings, or {} when it is absent or no health line."""
534
+ data = family.get('health')
535
+ doc = parse('line', data)[0] if data is not None else None
536
+ return doc if isinstance(doc, dict) else {}
537
+
538
+
539
+ # --------------------------------------------------------------------------------------------- the observer lock
540
+ def observer_lock_path(state):
541
+ return Path(state, *OBSERVER_LOCK)
542
+
543
+
544
+ def _fd_names(pid, target, proc=PROC):
545
+ try:
546
+ for name in os.listdir(f'{proc}/{pid}/fd'):
547
+ try:
548
+ if os.readlink(f'{proc}/{pid}/fd/{name}') == target:
549
+ return True
550
+ except OSError:
551
+ continue
552
+ except OSError:
553
+ pass
554
+ return False
555
+
556
+
557
+ def lock_holders(path, proc=PROC):
558
+ """Pids holding a flock on `path`, read from /proc/locks (never by trying the lock). A line names the inode as
559
+ `major:minor:inode` (hex device numbers); an overlay filesystem reports a device stat() does not, so an inode match
560
+ on another device counts only when that pid has the file open. Blocked waiters (`->`) hold nothing."""
561
+ try:
562
+ info = os.stat(path, follow_symlinks=False)
563
+ with open(f'{proc}/locks') as handle:
564
+ lines = handle.read().splitlines()
565
+ except OSError:
566
+ return []
567
+ target = os.path.realpath(path)
568
+ holders = []
569
+ for line in lines:
570
+ fields = line.split()
571
+ if len(fields) < 6 or fields[1] != 'FLOCK':
572
+ continue
573
+ try:
574
+ pid = int(fields[4])
575
+ major, minor, inode = fields[5].split(':')
576
+ same_dev = (int(major, 16), int(minor, 16)) == (os.major(info.st_dev), os.minor(info.st_dev))
577
+ inode = int(inode)
578
+ except ValueError:
579
+ continue
580
+ if inode == info.st_ino and pid > 0 and (same_dev or _fd_names(pid, target, proc)) and pid not in holders:
581
+ holders.append(pid)
582
+ return holders
583
+
584
+
585
+ def _stat_fields(pid, proc=PROC):
586
+ """(ppid, process group, session) of `pid` from <proc>/<pid>/stat, or None."""
587
+ try:
588
+ with open(f'{proc}/{pid}/stat') as handle:
589
+ text = handle.read()
590
+ fields = text[text.rindex(')') + 2:].split()
591
+ return int(fields[1]), int(fields[2]), int(fields[3])
592
+ except (OSError, ValueError, IndexError):
593
+ return None
594
+
595
+
596
+ def _belongs(pid, root_pid, proc=PROC):
597
+ """Is `pid` the process `root_pid`, in its process group or session, or below it in the parent chain?"""
598
+ current = pid
599
+ for _ in range(64):
600
+ if current == root_pid:
601
+ return True
602
+ if current <= 1:
603
+ return False
604
+ fields = _stat_fields(current, proc)
605
+ if fields is None:
606
+ return False
607
+ ppid, group, session = fields
608
+ if root_pid in (group, session):
609
+ return True
610
+ current = ppid
611
+ return False
612
+
613
+
614
+ def candidate_holders(holders, root_pid, proc=PROC):
615
+ """The `holders` that are the candidate (`root_pid`) or belong to it: its own process group or session (it runs in
616
+ a session of its own, start_new_session), or a parent chain that reaches it. A process that left the session AND
617
+ lost the candidate as an ancestor is not recognised (best effort beyond the session)."""
618
+ if not root_pid:
619
+ return []
620
+ return [pid for pid in holders if _belongs(pid, root_pid, proc)]
621
+
622
+
623
+ def writer_problem(holders, expected):
624
+ """With a live writer required: {code, detail} when nobody holds observer.lock any more (`writer_lost`: the live
625
+ family is no longer produced, so nothing is left to compare against) or another set of processes than at the
626
+ preflight does (`writer_changed`: the live writer restarted, or something else took the lock), else None."""
627
+ if not holders:
628
+ return {'code': 'writer_lost', 'detail': 'nobody holds locks/observer.lock any more: the live writer is gone '
629
+ '(AR D6); start the shadow run again once it is back'}
630
+ if sorted(holders) != sorted(expected):
631
+ return {'code': 'writer_changed', 'detail': f'observer.lock is held by {sorted(holders)}, at the preflight by '
632
+ f'{sorted(expected)}: start the shadow run again'}
633
+ return None
634
+
635
+
636
+ def lock_watch(state, candidate_pid, expected, allow_unlocked):
637
+ """One look at observer.lock's holders for a tick -> the holders, or Refused: this process holds it
638
+ (`shadow_holds_observer_lock`), the candidate or its child does (`candidate_holds_observer_lock`), or, with a live
639
+ writer required, `writer_problem`."""
640
+ holders = lock_holders(observer_lock_path(state))
641
+ if os.getpid() in holders:
642
+ raise Refused('shadow_holds_observer_lock', 'the shadow side never holds observer.lock (AR D6)')
643
+ owned = candidate_holders(holders, candidate_pid)
644
+ if owned:
645
+ raise Refused('candidate_holds_observer_lock',
646
+ f'the candidate (pid {candidate_pid}) or a process of its session holds observer.lock '
647
+ f'(holders {owned}): a shadow-only candidate never takes it (AR 7.4, D6); it was killed')
648
+ if not allow_unlocked:
649
+ problem = writer_problem(holders, expected)
650
+ if problem:
651
+ raise Refused(problem['code'], problem['detail'])
652
+ return holders
653
+
654
+
655
+ class ObserverLockHeld(Exception):
656
+ def __init__(self, holders):
657
+ super().__init__(f'observer.lock is held by {holders or "another process"}')
658
+ self.holders = holders
659
+
660
+
661
+ @contextlib.contextmanager
662
+ def hold_observer_lock(state):
663
+ """The WRITER half (a patched statusd, an owner-mode lanesd, the parity smoke's live writer): hold
664
+ `locks/observer.lock` for the block, or raise ObserverLockHeld at once. The lock file is opened O_NOFOLLOW, 0600,
665
+ in a `locks/` directory created 0700. The shadow runner never calls this."""
666
+ path = observer_lock_path(state)
667
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
668
+ fd = os.open(str(path), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | getattr(os, 'O_CLOEXEC', 0), 0o600)
669
+ try:
670
+ try:
671
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
672
+ except BlockingIOError:
673
+ raise ObserverLockHeld(lock_holders(path)) from None
674
+ yield fd
675
+ finally:
676
+ os.close(fd)
677
+
678
+
679
+ # ------------------------------------------------------------------------------------------------ the shadow tree
680
+ class ShadowTree:
681
+ """All writes AND reads of the shadow side: below `<state>/shadow/` only, `shadow/` and every component below it a
682
+ real directory opened from the state directory without following a link (created 0700), files replaced
683
+ atomically and only when changed. Before each write it re-reads the observer lock's holders and refuses when this
684
+ process is one of them. A link planted at `shadow/` or below makes a write or removal raise OSError and a read find
685
+ nothing."""
686
+
687
+ def __init__(self, state):
688
+ self.state = Path(state)
689
+ self.root = self.state / SHADOW_DIR
690
+ self.written = set()
691
+
692
+ def guard(self):
693
+ if os.getpid() in lock_holders(observer_lock_path(self.state)):
694
+ raise Refused('shadow_holds_observer_lock', 'the shadow side never holds observer.lock (AR D6)')
695
+
696
+ def _dir(self, parts):
697
+ fd = os.open(str(self.state), os.O_RDONLY | os.O_DIRECTORY | getattr(os, 'O_CLOEXEC', 0))
698
+ try:
699
+ for part in (SHADOW_DIR,) + tuple(parts):
700
+ L._leaf(part)
701
+ try:
702
+ os.mkdir(part, 0o700, dir_fd=fd)
703
+ except FileExistsError:
704
+ pass
705
+ child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, 'O_CLOEXEC', 0),
706
+ dir_fd=fd)
707
+ os.close(fd)
708
+ fd = child
709
+ except BaseException:
710
+ os.close(fd)
711
+ raise
712
+ return fd
713
+
714
+ def write(self, rel, data, mode=0o600):
715
+ """Write `data` at shadow/`rel` -> True when the bytes changed."""
716
+ self.guard()
717
+ parts = _safe_parts(rel)
718
+ fd = self._dir(parts[:-1])
719
+ try:
720
+ changed = L.atomic_write_if_changed_at(fd, parts[-1], data, mode)
721
+ finally:
722
+ os.close(fd)
723
+ self.written.add(rel)
724
+ return changed
725
+
726
+ def remove(self, rel):
727
+ """Remove shadow/`rel` when it is there; OSError when a component below the state directory is a link or no
728
+ directory."""
729
+ self.guard()
730
+ parts = _safe_parts(rel)
731
+ try:
732
+ fd = L.open_real_dir(self.state, (SHADOW_DIR,) + parts[:-1])
733
+ except FileNotFoundError:
734
+ return
735
+ try:
736
+ os.unlink(parts[-1], dir_fd=fd)
737
+ except FileNotFoundError:
738
+ pass
739
+ finally:
740
+ os.close(fd)
741
+
742
+ def ensure(self):
743
+ """Create `shadow/` (0700, never through a link) when it is missing."""
744
+ self.guard()
745
+ os.close(self._dir(()))
746
+
747
+ def expand(self, patterns):
748
+ return expand(self.state, patterns, under=(SHADOW_DIR,))
749
+
750
+ def family(self, patterns=HOST_FAMILY):
751
+ return read_family(self.state, patterns, under=(SHADOW_DIR,))
752
+
753
+ @contextlib.contextmanager
754
+ def append(self, rel, limit):
755
+ """An O_APPEND handle on shadow/`rel`, rotated to `rel`.1 first when it is past `limit` bytes."""
756
+ self.guard()
757
+ parts = _safe_parts(rel)
758
+ fd = self._dir(parts[:-1])
759
+ try:
760
+ try:
761
+ if os.stat(parts[-1], dir_fd=fd, follow_symlinks=False).st_size > limit:
762
+ os.replace(parts[-1], parts[-1] + '.1', src_dir_fd=fd, dst_dir_fd=fd)
763
+ except FileNotFoundError:
764
+ pass
765
+ handle = os.open(parts[-1], os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW
766
+ | getattr(os, 'O_CLOEXEC', 0), 0o600, dir_fd=fd)
767
+ finally:
768
+ os.close(fd)
769
+ self.written.add(rel)
770
+ try:
771
+ yield handle
772
+ finally:
773
+ os.close(handle)
774
+
775
+
776
+ def _write_all(fd, data):
777
+ view_ = memoryview(data)
778
+ while view_:
779
+ view_ = view_[os.write(fd, view_):]
780
+
781
+
782
+ def mirror_inputs(state, tree, patterns=MIRRORED):
783
+ """Copy the twin's live inputs (the registry, the container records, the docs counts) into shadow/, change-only so
784
+ an unchanged registry keeps its mtime (statusd reloads it on an mtime change). An input gone live is removed."""
785
+ state = Path(state)
786
+ present = set(expand(state, patterns))
787
+ for rel in sorted(present):
788
+ data = read_file(state, rel)
789
+ if data is not None:
790
+ tree.write(rel, data)
791
+ for rel in tree.expand(patterns):
792
+ if rel not in present:
793
+ tree.remove(rel)
794
+
795
+
796
+ # ----------------------------------------------------------------------------------------------------- preflight
797
+ def preflight(state, home=None, allow_unlocked=False):
798
+ """-> {'refusals': [{code, detail}], 'warnings': [...], 'site': {...}, 'writer_lock': {...}} for a shadow run on
799
+ this install. A guest owner install (`LANES_HOST_ROLE=owner`) in the STATUSD shadow step, a live writer holding
800
+ observer.lock, a real `shadow/` directory."""
801
+ state = Path(state)
802
+ site = L.site_conf(home)
803
+ refusals, warnings = [], []
804
+ if site.get('LANES_HOST_ROLE') != 'owner':
805
+ refusals.append({'code': 'owner_undeclared',
806
+ 'detail': 'site.conf needs LANES_HOST_ROLE=owner: the shadow runs on a guest owner install'})
807
+ if site.get('LANES_RS_STATUSD') != 'shadow':
808
+ refusals.append({'code': 'flag_not_shadow',
809
+ 'detail': f"site.conf LANES_RS_STATUSD is {site.get('LANES_RS_STATUSD') or 'unset'}, not shadow"})
810
+ if not state.is_dir():
811
+ refusals.append({'code': 'state_missing', 'detail': f'{state} is not a directory'})
812
+ shadow = state / SHADOW_DIR
813
+ if shadow.is_symlink() or (shadow.exists() and not shadow.is_dir()):
814
+ refusals.append({'code': 'shadow_dir_unsafe', 'detail': f'{shadow} is a link or not a directory'})
815
+ holders = lock_holders(observer_lock_path(state))
816
+ if os.getpid() in holders:
817
+ refusals.append({'code': 'shadow_holds_observer_lock', 'detail': 'this process holds observer.lock'})
818
+ if not holders:
819
+ item = {'code': 'lock_patch_missing',
820
+ 'detail': 'nobody holds locks/observer.lock: no single live writer to compare against (AR D6)'}
821
+ (warnings if allow_unlocked else refusals).append(item)
822
+ if not (state / 'status.json').exists():
823
+ warnings.append({'code': 'live_status_absent', 'detail': 'no live status.json yet'})
824
+ return {'refusals': refusals, 'warnings': warnings, 'writer_lock': {'path': str(observer_lock_path(state)),
825
+ 'holders': holders},
826
+ 'site': {key: site.get(key) for key in ('LANES_HOST_ROLE', 'LANES_RS_STATUSD', 'LANES_STATUSD_SLICES')}}
827
+
828
+
829
+ # ----------------------------------------------------------------------------------------------- the candidates
830
+ class Candidate:
831
+ """A long-lived candidate process speaking `lanes2.shadow-candidate/1` on its stdin and stdout. It runs in its own
832
+ session (so a kill takes its tmux and zmx children with it), with LANES_STATE=<state>/shadow and
833
+ LANES_SHADOW_SOURCE=<state>. Its stderr is a pipe this runner drains while it waits for an answer and between
834
+ ticks (`drain`), into shadow/report/candidate.log: at most `log_max` bytes per flush (the excess counted in one
835
+ line), the log rotated to .1 once it is past `log_max`, so neither file grows past about twice `log_max`. A cycle
836
+ is `ok` or `err` when it answers for its own number; no answer within `timeout` seconds is `timeout`, a closed
837
+ pipe `exited`, any other line `protocol`. After `timeout`, `exited` and `protocol` the process is killed and
838
+ started again at the next cycle, so a stray line never answers a later cycle."""
839
+
840
+ def __init__(self, argv, state, tree, timeout=CANDIDATE_TIMEOUT_S, log_max=None):
841
+ self.argv, self.state, self.tree, self.timeout = list(argv), Path(state), tree, timeout
842
+ self.log_max = LOG_MAX if log_max is None else log_max
843
+ self.proc = None
844
+ self.starts = 0
845
+ self.log = bytearray()
846
+ self.dropped = 0
847
+ self.dropped_total = 0
848
+ self.err_open = False
849
+
850
+ @property
851
+ def restarts(self):
852
+ return max(0, self.starts - 1)
853
+
854
+ @property
855
+ def pid(self):
856
+ return self.proc.pid if self.proc is not None else None
857
+
858
+ def start(self):
859
+ env = dict(os.environ, LANES_STATE=str(self.state / SHADOW_DIR), LANES_SHADOW_SOURCE=str(self.state))
860
+ self.proc = subprocess.Popen(self.argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
861
+ env=env, start_new_session=True)
862
+ os.set_blocking(self.proc.stderr.fileno(), False)
863
+ self.err_open = True
864
+ self.starts += 1
865
+
866
+ def _take_stderr(self):
867
+ """Read what the stderr pipe holds now into the pending log (at most `log_max` bytes kept per flush) ->
868
+ False once the pipe is closed."""
869
+ if self.proc is None or not self.err_open:
870
+ return False
871
+ for _ in range(64):
872
+ try:
873
+ chunk = os.read(self.proc.stderr.fileno(), 1 << 16)
874
+ except BlockingIOError:
875
+ return True
876
+ except OSError:
877
+ chunk = b''
878
+ if not chunk:
879
+ self.err_open = False
880
+ return False
881
+ room = max(0, self.log_max - len(self.log))
882
+ self.log += chunk[:room]
883
+ self.dropped += len(chunk) - min(room, len(chunk))
884
+ return True
885
+
886
+ def flush_log(self):
887
+ """Append the pending stderr to shadow/report/candidate.log (rotated to .1 when it is past `log_max`)."""
888
+ if not self.log and not self.dropped:
889
+ return
890
+ data = bytes(self.log)
891
+ if self.dropped:
892
+ data += f'[shadow: {self.dropped} bytes of candidate stderr dropped]\n'.encode()
893
+ self.dropped_total += self.dropped
894
+ self.log.clear()
895
+ self.dropped = 0
896
+ with self.tree.append(CANDIDATE_LOG, self.log_max) as handle:
897
+ _write_all(handle, data)
898
+
899
+ def drain(self, seconds):
900
+ """Wait `seconds`, moving the candidate's stderr into its log as it comes (a chatty candidate never blocks on a
901
+ full pipe between two cycles), then flush it."""
902
+ deadline = time.monotonic() + max(0.0, seconds)
903
+ while True:
904
+ rest = deadline - time.monotonic()
905
+ if rest <= 0:
906
+ break
907
+ if self.proc is None or not self.err_open:
908
+ time.sleep(rest)
909
+ break
910
+ ready, _w, _x = select.select([self.proc.stderr.fileno()], [], [], rest)
911
+ if ready:
912
+ self._take_stderr()
913
+ self.flush_log()
914
+
915
+ def _answer(self, deadline):
916
+ """(the next stdout line, None) before `deadline`, or (None, `timeout` | `exited`); stderr is drained
917
+ meanwhile. A line longer than LINE_MAX comes back cut (a protocol error)."""
918
+ out_fd = self.proc.stdout.fileno()
919
+ line = b''
920
+ while not line.endswith(b'\n') and len(line) <= LINE_MAX:
921
+ rest = deadline - time.monotonic()
922
+ if rest <= 0:
923
+ return None, 'timeout'
924
+ fds = [out_fd] + ([self.proc.stderr.fileno()] if self.err_open else [])
925
+ ready, _w, _x = select.select(fds, [], [], rest)
926
+ if self.err_open and self.proc.stderr.fileno() in ready:
927
+ self._take_stderr()
928
+ if out_fd in ready:
929
+ chunk = os.read(out_fd, 1)
930
+ if not chunk:
931
+ return None, 'exited'
932
+ line += chunk
933
+ return line.decode('utf-8', 'replace').rstrip('\n'), None
934
+
935
+ def _reap(self):
936
+ """The process has ended: what is left on its stderr goes to the log, the pipes are closed."""
937
+ self._take_stderr()
938
+ for pipe in (self.proc.stdin, self.proc.stdout, self.proc.stderr):
939
+ with contextlib.suppress(OSError, ValueError):
940
+ pipe.close()
941
+ self.proc, self.err_open = None, False
942
+ self.flush_log()
943
+
944
+ def kill(self):
945
+ if self.proc is None:
946
+ return
947
+ with contextlib.suppress(OSError):
948
+ os.killpg(self.proc.pid, signal.SIGKILL)
949
+ with contextlib.suppress(subprocess.TimeoutExpired):
950
+ self.proc.wait(timeout=5)
951
+ self._reap()
952
+
953
+ def cycle(self, number, level='ok'):
954
+ if self.proc is not None and self.proc.poll() is not None:
955
+ self._reap() # it exited on its own since the last cycle
956
+ if self.proc is None:
957
+ self.start()
958
+ try:
959
+ self.proc.stdin.write(f'cycle {number} {level}\n'.encode())
960
+ self.proc.stdin.flush()
961
+ except OSError:
962
+ self.kill()
963
+ return 'exited'
964
+ line, failure = self._answer(time.monotonic() + self.timeout)
965
+ if failure is not None:
966
+ self.kill()
967
+ return failure
968
+ words = line.split(' ', 2)
969
+ if words[:2] == ['ok', str(number)]:
970
+ outcome = 'ok'
971
+ elif words[:2] == ['err', str(number)]:
972
+ outcome = 'err'
973
+ else: # its next line would answer this cycle, not the next one: start it again
974
+ self.kill()
975
+ return 'protocol'
976
+ self.flush_log()
977
+ return outcome
978
+
979
+ def stop(self):
980
+ if self.proc is None:
981
+ return
982
+ with contextlib.suppress(OSError, ValueError):
983
+ self.proc.stdin.write(b'stop\n')
984
+ self.proc.stdin.close()
985
+ try:
986
+ self.proc.wait(timeout=5)
987
+ except subprocess.TimeoutExpired:
988
+ self.kill()
989
+ return
990
+ self._reap()
991
+
992
+
993
+ def twin_argv():
994
+ return [sys.executable, '-S', '-E', os.path.abspath(__file__), 'twin-loop']
995
+
996
+
997
+ def pinned_health(health, level):
998
+ """`health` as a candidate pinned to the live pressure `level` reports it (AR 7.6 c: both producers pinned to one
999
+ pressure level): every computed figure kept, the level replaced. Unpinned (None) it is `health` itself."""
1000
+ if level in LEVELS and isinstance(health, dict) and health:
1001
+ return dict(health, level=level)
1002
+ return health
1003
+
1004
+
1005
+ def twin_loop(stdin=None, stdout=None):
1006
+ """The Python twin: statusd's `cycle` (observation and projection; reconcile off, as `--once`) once per
1007
+ `cycle <n> [<level>]` line, pinned to that level, followed by main()'s look for the docs origin
1008
+ (`refresh_origin`, an observation of site.conf and tailscale), in THIS process, whose LANES_STATE must be
1009
+ `$LANES_SHADOW_SOURCE/shadow`. No container slice is written (the shadow compares the host family only), and none of
1010
+ statusd's between-cycle effects runs (re-arms, renames, deliveries, syncs). statusd's journal lines go to stderr;
1011
+ stdout carries only the protocol. The context is kept across cycles like the daemon's, seeded with the mirrored
1012
+ container records so a cycle never asks docker without one of statusd's own reasons."""
1013
+ stdin = stdin or sys.stdin.buffer
1014
+ stdout = stdout or sys.stdout.buffer
1015
+ source = os.environ.get('LANES_SHADOW_SOURCE') or ''
1016
+ if not source or Path(L.STATE) != Path(source) / SHADOW_DIR:
1017
+ raise Refused('twin_not_shadow', f'the twin writes only $LANES_SHADOW_SOURCE/shadow, not {L.STATE}')
1018
+ sys.stdout = sys.stderr
1019
+ import statusd
1020
+ statusd.write_container_status = lambda ctx, payload, now=None: []
1021
+ pin = {'level': None}
1022
+ measured = L.compute_health
1023
+
1024
+ def compute_health(*args, **kwargs):
1025
+ return pinned_health(measured(*args, **kwargs), pin['level'])
1026
+
1027
+ L.compute_health = compute_health
1028
+ ctx = statusd.new_context()
1029
+ recorded = L.read_json(L.STATE / 'containers.json', {}) or {}
1030
+ if isinstance(recorded, dict) and recorded:
1031
+ ctx['containers'] = {name: dict(info) for name, info in recorded.items() if isinstance(info, dict)}
1032
+ ctx['containers_at'] = time.time()
1033
+ for raw in iter(stdin.readline, b''):
1034
+ words = raw.decode('utf-8', 'replace').split()
1035
+ if words[:1] == ['stop']:
1036
+ break
1037
+ if (len(words) not in (2, 3) or words[0] != 'cycle' or not words[1].isdigit()
1038
+ or (len(words) == 3 and words[2] not in LEVELS)):
1039
+ stdout.write(b'err 0 protocol\n')
1040
+ stdout.flush()
1041
+ continue
1042
+ pin['level'] = words[2] if len(words) == 3 else None
1043
+ try:
1044
+ level, _payload = statusd.cycle(ctx, reconcile=False)
1045
+ statusd.refresh_origin(ctx, level) # main()'s between-cycle look, never inside a cycle
1046
+ reply = f'ok {words[1]}\n'
1047
+ except Exception as error: # one failed cycle is reported, never the end of the twin
1048
+ reply = f'err {words[1]} {type(error).__name__}\n'
1049
+ stdout.write(reply.encode())
1050
+ stdout.flush()
1051
+ return 0
1052
+
1053
+
1054
+ # ----------------------------------------------------------------------------------------------------- the runner
1055
+ def inputs_present(state):
1056
+ """How many teed input cycles statusd left under shadow/inputs/ (AR 7.6 b) -> int (0 when none)."""
1057
+ try:
1058
+ fd = L.open_real_dir(Path(state), (SHADOW_DIR,) + INPUTS_DIR)
1059
+ except (OSError, L.LanesError):
1060
+ return 0
1061
+ try:
1062
+ return sum(1 for name in os.listdir(fd) if name.endswith('.json'))
1063
+ finally:
1064
+ os.close(fd)
1065
+
1066
+
1067
+ class Stop:
1068
+ def __init__(self):
1069
+ self.requested = False
1070
+
1071
+ def __call__(self, _signum, _frame):
1072
+ self.requested = True
1073
+
1074
+
1075
+ def tick_verdict(outcome, pinned, live_level, shadow_at, now, interval):
1076
+ """Whether one tick is judged -> None (judge it) or why not: `pressure` (the live host was not at `ok` before the
1077
+ cycle, so the candidate was not asked, or it left the level the candidate was pinned to before the families were
1078
+ read: AR 7.6 c pins both producers to one level), `live_health_absent` (no live health line to read the level
1079
+ from), `candidate_<outcome>` (the candidate did not answer `ok` for THIS cycle, so its shadow family is not this
1080
+ cycle's: `err`, `timeout`, `exited`, `protocol`), `candidate_stale` (no candidate driven, and the shadow family's
1081
+ health `at` is older than one interval plus HEARTBEAT_S, or absent). A `candidate_*` reason is a candidate
1082
+ failure."""
1083
+ if outcome == 'skipped':
1084
+ return 'pressure'
1085
+ if outcome == 'none':
1086
+ if not isinstance(shadow_at, (int, float)) or now - shadow_at > interval + HEARTBEAT_S:
1087
+ return 'candidate_stale'
1088
+ elif outcome != 'ok':
1089
+ return f'candidate_{outcome}'
1090
+ if live_level is None:
1091
+ return 'live_health_absent'
1092
+ if live_level != pinned:
1093
+ return 'pressure'
1094
+ return None
1095
+
1096
+
1097
+ def _number(value):
1098
+ try:
1099
+ return int(value)
1100
+ except (TypeError, ValueError):
1101
+ return None
1102
+
1103
+
1104
+ def run(state, home=None, window=WINDOW_S, interval=INTERVAL_S, candidate_argv=None, label=None,
1105
+ allow_unlocked=False, fail_on_unexplained=False, warmup=WARMUP_S, clock=time.monotonic, sleep=time.sleep,
1106
+ stop=None, candidate_timeout=CANDIDATE_TIMEOUT_S):
1107
+ """The shadow run (module docstring) -> (exit code, summary). Ticks of the first `warmup` seconds are judged and
1108
+ journalled like every other, but their U counts as `warmup_unexplained`, not `unexplained`: each producer's first
1109
+ rate (fleet cpu, container cpu) needs two of its own samples, and a candidate started now has none. A tick that is
1110
+ not judged (`tick_verdict`) is journalled with its reason and counted in `not_judged`."""
1111
+ state = Path(state)
1112
+ pre = preflight(state, home, allow_unlocked)
1113
+ if pre['refusals']:
1114
+ return EXIT_REFUSED, {'schema': SUMMARY_SCHEMA, 'refused': pre['refusals'], 'preflight': pre}
1115
+ tree = ShadowTree(state)
1116
+ judge = Judge()
1117
+ profile = check_profile(PROFILES['drift'])
1118
+ candidate = Candidate(candidate_argv, state, tree, candidate_timeout) if candidate_argv else None
1119
+ expected = pre['writer_lock']['holders']
1120
+ stop = stop or Stop()
1121
+ started_wall, started = time.time(), clock()
1122
+ counts = {'ticks': 0, 'candidate': {}, 'verdicts': {}, 'unexplained': 0, 'warmup_unexplained': 0,
1123
+ 'warmup_ticks': 0, 'ticks_judged': 0, 'not_judged': {}, 'candidate_failures': 0, 'skipped_pressure': 0,
1124
+ 'reordered': 0}
1125
+ files, examples, holders_seen = {}, [], set()
1126
+ refusal = None
1127
+ ticks_rel = '/'.join(REPORT_DIR + ('ticks.jsonl',))
1128
+ try:
1129
+ tree.ensure() # the candidate's LANES_STATE exists before it starts
1130
+ if candidate is not None: # the family a previous run's candidate left is never this run's
1131
+ for rel in tree.expand(HOST_FAMILY):
1132
+ tree.remove(rel)
1133
+ while not stop.requested and clock() - started < window:
1134
+ tick_started = clock()
1135
+ number = counts['ticks'] + 1
1136
+ holders = lock_watch(state, candidate.pid if candidate else None, expected, allow_unlocked)
1137
+ holders_seen.update(holders)
1138
+ tree.guard()
1139
+ level = L.read_health(state).get('level', 'ok')
1140
+ mirror_inputs(state, tree)
1141
+ if level != 'ok':
1142
+ outcome = 'skipped'
1143
+ elif candidate is None:
1144
+ outcome = 'none'
1145
+ else:
1146
+ outcome = candidate.cycle(number, level)
1147
+ holders = lock_watch(state, candidate.pid, expected, allow_unlocked)
1148
+ holders_seen.update(holders)
1149
+ counts['candidate'][outcome] = counts['candidate'].get(outcome, 0) + 1
1150
+ live, shadow_family = read_family(state), tree.family()
1151
+ reason = tick_verdict(outcome, 'ok', health_of(live).get('level'),
1152
+ _number(health_of(shadow_family).get('at')), time.time(), interval)
1153
+ warming = tick_started - started < warmup
1154
+ counts['ticks'] = number
1155
+ record = {'tick': number, 'at': round(time.time(), 3), 'level': level, 'candidate': outcome,
1156
+ 'pinned': level if outcome not in ('skipped', 'none') else None, 'warmup': warming,
1157
+ 'holders': holders, 'judged': reason is None}
1158
+ if reason is None:
1159
+ results = judge.tick(compare(live, shadow_family, profile))
1160
+ summary = tally(results)
1161
+ counts['warmup_ticks' if warming else 'ticks_judged'] += 1
1162
+ counts['warmup_unexplained' if warming else 'unexplained'] += summary['unexplained']
1163
+ counts['reordered'] += summary['reordered']
1164
+ for verdict, n in summary['verdicts'].items():
1165
+ counts['verdicts'][verdict] = counts['verdicts'].get(verdict, 0) + n
1166
+ for result in results:
1167
+ row = files.setdefault(result['path'], {'dm': result['dm'], 'verdicts': {}})
1168
+ row['verdicts'][result['verdict']] = row['verdicts'].get(result['verdict'], 0) + 1
1169
+ if result['verdict'] in UNEXPLAINED and not warming and len(examples) < EXAMPLES_MAX:
1170
+ examples.append({'tick': number, 'path': result['path'], 'dm': result['dm'],
1171
+ 'verdict': result['verdict'], 'paths': result['paths'][:8]})
1172
+ record.update(unexplained=summary['unexplained'], verdicts=summary['verdicts'])
1173
+ else:
1174
+ counts['not_judged'][reason] = counts['not_judged'].get(reason, 0) + 1
1175
+ counts['candidate_failures'] += reason.startswith('candidate_')
1176
+ counts['skipped_pressure'] += reason == 'pressure'
1177
+ record['not_judged'] = reason
1178
+ with tree.append(ticks_rel, TICKS_MAX) as handle:
1179
+ _write_all(handle, (json.dumps(record, sort_keys=True) + '\n').encode())
1180
+ due = tick_started + interval
1181
+ if due - started >= window:
1182
+ break
1183
+ if not stop.requested and due > clock():
1184
+ if candidate is not None and candidate.proc is not None:
1185
+ candidate.drain(due - clock())
1186
+ else:
1187
+ sleep(due - clock())
1188
+ except Refused as error:
1189
+ refusal = {'code': error.code, 'detail': error.detail}
1190
+ except OSError as error: # a full disk, a link planted at shadow/: the run ends with what it has, refused
1191
+ refusal = {'code': 'shadow_io', 'detail': f'{type(error).__name__} (errno {error.errno}): {error}'}
1192
+ finally:
1193
+ if candidate is not None:
1194
+ try:
1195
+ if refusal and refusal['code'] == 'candidate_holds_observer_lock':
1196
+ candidate.kill()
1197
+ else:
1198
+ candidate.stop()
1199
+ except (Refused, OSError) as error:
1200
+ refusal = refusal or {'code': getattr(error, 'code', 'shadow_io'), 'detail': str(error)}
1201
+ teed = inputs_present(state)
1202
+ failed_by = [name for name, failed in (('unexplained', counts['unexplained']),
1203
+ ('candidate_failures', counts['candidate_failures']),
1204
+ ('nothing_judged', not counts['ticks_judged'])) if failed]
1205
+ summary = {
1206
+ 'schema': SUMMARY_SCHEMA, 'profile_label': label, 'state': str(state),
1207
+ 'started_at': round(started_wall, 3), 'ended_at': round(time.time(), 3),
1208
+ 'window_s': window, 'interval_s': interval, 'warmup_s': warmup, 'elapsed_s': round(clock() - started, 3),
1209
+ 'ended_by': 'refusal' if refusal else 'signal' if stop.requested else 'window',
1210
+ 'refused': [refusal] if refusal else [], 'preflight': pre, 'failed_by': failed_by,
1211
+ 'candidate': {'argv': candidate_argv, 'protocol': CANDIDATE_PROTOCOL if candidate_argv else None,
1212
+ 'restarts': candidate.restarts if candidate else 0, 'pinned_level': 'ok',
1213
+ 'log': f'{SHADOW_DIR}/{CANDIDATE_LOG}' if candidate else None,
1214
+ 'log_dropped_bytes': candidate.dropped_total if candidate else 0},
1215
+ 'counts': counts, 'files': files, 'unexplained_examples': examples,
1216
+ 'judge': {'profile': 'drift', 'source': PROFILES['drift']['source'], 'e1_resolved': judge.e1,
1217
+ 'tolerance_exceeded': judge.exceeded, 'open_at_end': len(judge.pending),
1218
+ 'e2_reordered': counts['reordered'],
1219
+ 'unmasked_samples': {'keys': list(UNMASKED_SAMPLES),
1220
+ 'note': 'sampled by each producer at its own instant and not in the AR 7.6 (c) '
1221
+ 'mask: counted as U on a live host until the specification lists them'}},
1222
+ 'writer_lock': {'holders_seen': sorted(holders_seen), 'self': os.getpid(),
1223
+ 'self_held': os.getpid() in holders_seen, 'preflight': expected,
1224
+ 'required': not allow_unlocked},
1225
+ 'writes': sorted(tree.written),
1226
+ 'gates': {
1227
+ '(a) deterministic replay': 'lanes/tests/parity (oracle.py); not run by this runner',
1228
+ '(b) live-input replay': (f'{teed} teed input cycles present; their replay is W18-E' if teed
1229
+ else 'not run: no teed inputs under shadow/inputs/ (W18-E)'),
1230
+ '(c) live sampling diff': 'this run: informational, never a gate',
1231
+ },
1232
+ }
1233
+ try:
1234
+ tree.write('/'.join(REPORT_DIR + ('summary.json',)), json.dumps(summary, indent=1, sort_keys=True) + '\n')
1235
+ except Refused as error: # the runner itself holds observer.lock: nothing more is written, the run is refused
1236
+ refusal = refusal or {'code': error.code, 'detail': error.detail}
1237
+ summary['refused'] = [refusal]
1238
+ summary['ended_by'] = 'refusal'
1239
+ except OSError as error:
1240
+ refusal = refusal or {'code': 'shadow_io', 'detail': f'{type(error).__name__} (errno {error.errno}): {error}'}
1241
+ summary['refused'] = [refusal]
1242
+ summary['ended_by'] = 'refusal'
1243
+ if refusal:
1244
+ return EXIT_REFUSED, summary
1245
+ if fail_on_unexplained and failed_by:
1246
+ return EXIT_UNEXPLAINED, summary
1247
+ return EXIT_OK, summary
1248
+
1249
+
1250
+ def compare_roots(left, right, profile='replay'):
1251
+ """One-shot judgement of two state roots' host families -> (exit code, report)."""
1252
+ results = compare(read_family(Path(left)), read_family(Path(right)), PROFILES[profile])
1253
+ report = dict(tally(results), profile=profile, results=results)
1254
+ return (EXIT_UNEXPLAINED if report['unexplained'] else EXIT_OK), report
1255
+
1256
+
1257
+ def main(argv=None):
1258
+ parser = argparse.ArgumentParser(prog='shadow.py', description=__doc__.split('\n\n')[0])
1259
+ sub = parser.add_subparsers(dest='command', required=True)
1260
+ for name in ('check', 'run'):
1261
+ command = sub.add_parser(name)
1262
+ command.add_argument('--state', default=str(L.STATE))
1263
+ command.add_argument('--home', default=None)
1264
+ command.add_argument('--no-writer-lock', action='store_true')
1265
+ if name == 'run':
1266
+ command.add_argument('--window', type=float, default=WINDOW_S)
1267
+ command.add_argument('--interval', type=float, default=INTERVAL_S)
1268
+ command.add_argument('--warmup', type=float, default=WARMUP_S)
1269
+ command.add_argument('--candidate', choices=('twin', 'none'), default='twin')
1270
+ command.add_argument('--candidate-cmd', nargs=argparse.REMAINDER, default=None)
1271
+ command.add_argument('--profile-label', default=None)
1272
+ command.add_argument('--fail-on-unexplained', action='store_true')
1273
+ sub.add_parser('twin-loop')
1274
+ compare_cmd = sub.add_parser('compare')
1275
+ compare_cmd.add_argument('left')
1276
+ compare_cmd.add_argument('right')
1277
+ compare_cmd.add_argument('--profile', choices=sorted(PROFILES), default='replay')
1278
+ try:
1279
+ args = parser.parse_args(argv)
1280
+ except SystemExit as error:
1281
+ return EXIT_USAGE if error.code else EXIT_OK
1282
+ if args.command == 'twin-loop':
1283
+ try:
1284
+ return twin_loop()
1285
+ except Refused as error:
1286
+ print(json.dumps({'refused': [{'code': error.code, 'detail': error.detail}]}), file=sys.stderr)
1287
+ return EXIT_REFUSED
1288
+ if args.command == 'compare':
1289
+ code, report = compare_roots(args.left, args.right, args.profile)
1290
+ print(json.dumps(report, indent=1, sort_keys=True))
1291
+ return code
1292
+ if args.command == 'check':
1293
+ report = preflight(args.state, args.home, args.no_writer_lock)
1294
+ print(json.dumps(report, indent=1, sort_keys=True))
1295
+ return EXIT_REFUSED if report['refusals'] else EXIT_OK
1296
+ if args.window <= 0 or args.interval <= 0 or args.warmup < 0:
1297
+ print('shadow.py run: --window and --interval must be positive, --warmup not negative', file=sys.stderr)
1298
+ return EXIT_USAGE
1299
+ argv_candidate = args.candidate_cmd or (twin_argv() if args.candidate == 'twin' else None)
1300
+ stop = Stop()
1301
+ signal.signal(signal.SIGTERM, stop)
1302
+ signal.signal(signal.SIGINT, stop)
1303
+ code, summary = run(args.state, args.home, args.window, args.interval, argv_candidate, args.profile_label,
1304
+ args.no_writer_lock, args.fail_on_unexplained, args.warmup, stop=stop)
1305
+ print(json.dumps({key: summary.get(key) for key in ('profile_label', 'ended_by', 'refused', 'failed_by', 'counts',
1306
+ 'judge', 'writer_lock')}, indent=1, sort_keys=True))
1307
+ return code
1308
+
1309
+
1310
+ if __name__ == '__main__':
1311
+ sys.exit(main())