@vibelord/lanes 1.7.4 → 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.
@@ -1790,7 +1790,10 @@ Paths, receipts and the log: [RUNBOOK](RUNBOOK.md#messages-inboxes-receipts-and-
1790
1790
  not counted; `shell` stays 0 in practice: a lane whose harness ended into its shell is published under that
1791
1791
  harness's name with the status `shell`); lanes per create-recipe class (`idempotent`, `attach-only`, `null`, `external`, `retired-path`), how many
1792
1792
  create with their identity, where the `lane` contract is installed, zmx-held lanes, the preview renderer, the live
1793
- view sessions, and the pressure summary.
1793
+ view sessions, the unregistered sweep (`gc unregistered: off (LANES_GC_UNREGISTERED unset)`, or `on, idle ≥ 6h,
1794
+ last sweep … : ended N`, `(by hand)` after the time unless the timer ran it; `⚠` for an idle floor it refuses, or a
1795
+ `LANES_GC_` line with a comment, quote or space after its value, named —
1796
+ [Daily cleanup of unregistered terminals](#daily-cleanup-of-unregistered-terminals)), and the pressure summary.
1794
1797
  - Addresses ([Addresses, coordinators and the fleet admin](#addresses-coordinators-and-the-fleet-admin)): `⚠ 2 of 14
1795
1798
  boards without a coordinator: …` (fix: `lanes migrate addresses --write` or `lanes address set-coordinator`),
1796
1799
  `✓ lane addresses unique` (`✗` naming the two lanes of each clash: `lanes sync` refuses the site until one has
@@ -2563,7 +2566,7 @@ All units run in `lanes.slice` and are rendered by the server installer from `la
2563
2566
  | `lanes-statusd.service` | Always on | Server install | Observes every lane; writes `status.json` and `health`; hot-sync; types only `/rename <address>` into an idle Claude lane whose session name is not its address, with no terminal attached (at most two a pass, each lane at most once per 120 s; `LANES_NAMES_AUTO=0` in site.conf turns it off) |
2564
2567
  | `lanes-sync.timer` / `.service` | Every 2 min | Server install | `lanes sync` |
2565
2568
  | `lanes-ensure.timer` / `.service` | Every 1 min | Server install | `lanes ensure`: recreate missing device view sessions; rebuild a view an update left once no client is attached |
2566
- | `lanes-gc.timer` / `.service` | Daily | Server install | `lanes gc`: truncate zmx logs over 5 MB, drop stale dynamic resolve files, prune old npm-staged trees — each folder keeps its 3 newest and every older tree `current`, `current.previous`, a view layout, a running daemon's run record or a process of this account uses; none when `/proc` cannot be read ([INSTALL](INSTALL.md#6-updates-optional-operations-and-removal)) |
2569
+ | `lanes-gc.timer` / `.service` | Daily at midnight, host time (+0–5 min; a midnight the host missed runs once at the next boot) | Server install | `lanes gc`: truncate zmx logs over 5 MB, drop stale dynamic resolve files, prune old npm-staged trees — each folder keeps its 3 newest and every older tree `current`, `current.previous`, a view layout, a running daemon's run record or a process of this account uses; none when `/proc` cannot be read ([INSTALL](INSTALL.md#6-updates-optional-operations-and-removal)); then, only with `LANES_GC_UNREGISTERED=1` in site.conf, end the unregistered sessions in which nothing runs ([Daily cleanup of unregistered terminals](#daily-cleanup-of-unregistered-terminals)) |
2567
2570
  | `lanes-update.timer` / `.service` | 15 min after boot, then every 30 min (+0–5 min) | Server install (the full one: `--update-only` enables nothing — `systemctl --user enable --now lanes-update.timer` on a server set up before 1.2.0) | `lanes update --timer`: install the newest npm release when it is newer ([Update](#update)); a checkout server is left alone; stopped after 1 h |
2568
2571
  | `lanes-enrold.service` | Always on | Server install (enabled and restarted by every one) | Enrolment service on `127.0.0.1:8184`, reached as `https://<host>:8443/enrol/*`: invite redemption, enrolment requests, `/enrol/pending` approvals ([RUNBOOK](RUNBOOK.md#enrolment-service-lanes-enrold-w8-a3)) |
2569
2572
  | `lanes-docsd.service` | Always on | Server install (enabled and restarted by every one) | Docs service on `127.0.0.1:8185`, reached as `https://<host>:8443/lanes-docs/`: login-bound documents, sandboxed artifacts and uploads with receipts; refuses every request until `lanes enrol mode request` is pinned ([RUNBOOK](RUNBOOK.md#docs-service-lanes-docsd-w10-w3)) |
@@ -2640,7 +2643,8 @@ Clients also get `lanes-helper.service` and `lanes-upload.path`/`.service` (Linu
2640
2643
  | Health | `lanes pressure` | Memory / io / cpu pressure, swap, per-container memory and `/tmp`; plain files only; exit 1 unless ok |
2641
2644
  | Health | `lanes invariant save\|check` | Snapshot / verify every live pane's pid and window size |
2642
2645
  | Health | `lanes sockets [check\|repair]` | tmux servers whose socket file was deleted; `repair` sends tmux's SIGUSR1, nothing restarts |
2643
- | Housekeeping | `lanes gc` | What the daily timer runs |
2646
+ | Housekeeping | `lanes gc` | What the daily timer runs (at midnight) |
2647
+ | Housekeeping | `lanes gc --unregistered [--write] [--board B]` | One line per unregistered session: `reap: <why>` only on evidence that nothing runs in it, `keep: <why>` for every other one; `--write` ends the reap lines' sessions ([Daily cleanup of unregistered terminals](#daily-cleanup-of-unregistered-terminals)) |
2644
2648
  | Housekeeping | `lanes tmp scan\|plan\|apply\|reap\|caches [container…] [--approve] [--home]` | What fills the containers' RAM-backed `/tmp`, and removing the dead part ([RUNBOOK](RUNBOOK.md#free-the-ram-lanes-tmp)) |
2645
2649
  | Housekeeping | `lanes guard [--dry-run] [container…]` | One OOM-guard pass by hand |
2646
2650
  | Throttle | `lanes economy --once [--dry-run] [--status-file F --sessions-file F]` | One economy poll (section 8) |
@@ -2671,6 +2675,7 @@ Server (`~/.local/state/lanes/`, `$LANES_STATE`):
2671
2675
  | --- | --- |
2672
2676
  | `registry.json`, `registry.synced`, `resolve/`, `resolve.dynamic/` | The published registry, the last sync time, per-lane targets |
2673
2677
  | `status.json`, `health` | statusd's snapshot and the one-line health record |
2678
+ | `gc-unregistered.json` | The last write run of the unregistered sweep (`lanes gc` with the policy on, or `lanes gc --unregistered --write`): when, by the timer or by hand, the idle floor, and how many sessions it ended, could not end and kept; `lanes doctor` shows it |
2674
2679
  | `run/<name>.tree` | The tree each long-running process started from — `statusd`, `enrold`, `docsd`, `economy`, `notify`, `studio_host` (the enable step its enrolment timer runs) and `sidebar` (the most recently started one): one resolved path, rewritten at every start, so a record that differs from where `~/.local/share/lanes/current` points is a process still running an older version |
2675
2680
  | `containers.json`, `containers/` | Container init pids and home volumes |
2676
2681
  | `devices/<device>.json` | Each known device: layout, viewports, base device, owner, look (colour, theme, glyphs, dim; `device_only` lists the keys `--device-only` kept for this device alone), desktop notifications on/off and the quick-edit editor |
@@ -2727,6 +2732,69 @@ Client: `~/.config/lanes/` (`device`, `install-options`, `ghostty.conf`, `client
2727
2732
  `~/.local/state/lanes-client/` (`launch-<target>.log`, `helper.alive`, `helper-service.log`, `checked` — the time of a
2728
2733
  window's last update question — and `checking/` while one asks), `~/.local/share/lanes/client/`.
2729
2734
 
2735
+ ### Daily cleanup of unregistered terminals
2736
+
2737
+ Ending a lane is a person's call: `x` in the sidebar, one session at a time. A site whose operator wants the
2738
+ unregistered terminals in which nothing runs gone without asking each time can say so once, in the server's
2739
+ `~/.config/lanes/site.conf`:
2740
+
2741
+ ```sh
2742
+ # The daily lanes gc (midnight) ends the unregistered sessions in which nothing runs.
2743
+ LANES_GC_UNREGISTERED=1
2744
+ # Optional: how long a session must have shown no output, in seconds (default 21600 = 6 h, at least 3600).
2745
+ LANES_GC_IDLE_S=21600
2746
+ ```
2747
+
2748
+ Each setting is `KEY=VALUE` alone on its line, with comments on lines of their own: a `LANES_GC_` line with anything
2749
+ after its value (a comment, quotes, a space) is refused rather than read as unset — the sweep then ends nothing, and
2750
+ `lanes doctor` names the line with a `⚠`.
2751
+
2752
+ Only **unregistered** sessions are ever considered: the tmux sessions a board lists under **Unregistered** —
2753
+ unregistered, including a lane a person unregistered while it ran (`u`, `lanes unregister`). A registered lane is
2754
+ never ended, however idle. A session is ended only on **positive evidence that nothing runs in it**:
2755
+
2756
+ - its agent's status is `shell` (the harness ended into its shell), or it has no agent and its pane runs a bare shell
2757
+ (`bash`, `zsh`, `sh`, …), or its pane is dead; and
2758
+ - just before it is ended, a look at every pane of every window of the session finds each one dead, or a bare shell
2759
+ with no process under it; and
2760
+ - it showed no output for at least `LANES_GC_IDLE_S`, no terminal is attached to it, no Studio browser views it,
2761
+ statusd observed it within the last 30 s, and this server reaches its container itself.
2762
+
2763
+ Every other session is kept: an agent that is errored, done, waiting for you (`needs_input`, `needs_approval`),
2764
+ working, or idle at its prompt (every harness prompt stays until a person opens the lane), or a status the sweep does
2765
+ not know; a pane that runs anything but a bare shell (`keep: runs vim`, or `keep: runs claude` for a Claude in another
2766
+ window); a session statusd could not observe (no evidence is never "idle"); a container behind a guest (that guest's
2767
+ own Lanes sweeps it). A session is ended the way the sidebar's `x` ends it, in an unattended mode: the exact session
2768
+ (its tmux id and creation time, checked inside tmux), never while a Studio browser views it, and never a view's own
2769
+ session. An attach statusd has published keeps the session, and the kill itself refuses while a client is attached:
2770
+ tmux checks that inside the same command as the kill, so someone who attaches a second before keeps it too.
2771
+
2772
+ **Look first.** `lanes gc --unregistered` is the dry run, with or without the switch: one line per session, the
2773
+ decision and why, and nothing ended (it also looks at the panes of each session it would end, read-only, so it says
2774
+ what a write would do).
2775
+
2776
+ ```text
2777
+ gc unregistered: off (LANES_GC_UNREGISTERED unset), idle ≥ 6h — dry run: --write ends each reap
2778
+ keep: attached — work--x-scratch-3f2a91c0d4 (work lanes-shells-work/scratch)
2779
+ keep: agent needs_input — work--x-review-8b7e6d5c4a (work lanes-shells-work/review)
2780
+ keep: runs vim — work--x-notes-2c3d4e5f6a (work lanes-shells-work/notes)
2781
+ keep: active 12m ago — work--x-build-1a2b3c4d5e (work lanes-shells-work/build)
2782
+ reap: idle 7h, no agent, no client — work--x-old-9f8e7d6c5b (work lanes-shells-work/old)
2783
+ gc unregistered: 1 to end, 4 kept — lanes gc --unregistered --write ends them
2784
+ ```
2785
+
2786
+ `--board B` looks at one board's sessions. `lanes gc --unregistered --write` ends the `reap` lines' sessions now, by
2787
+ hand. Each is judged again just before closing. A new client, grouped viewer or
2788
+ new output on any window keeps the session even before the status display catches
2789
+ up; cleanup never closes a viewer to make a session eligible. With the switch
2790
+ on, the midnight `lanes gc` does the same after its other housekeeping; its lines are in
2791
+ `journalctl --user -u lanes-gc.service`, and `lanes doctor` names the last run:
2792
+ `gc unregistered: on, idle ≥ 6h, last sweep 2026-11-02 00:03 UTC: ended 1` (with `(by hand)` after the time when a
2793
+ person ran it rather than the timer). Turn it off by removing the line or setting `LANES_GC_UNREGISTERED=0`.
2794
+ [inferred, not measured: on a host whose timer was the earlier boot-relative one, the update that moves it to midnight
2795
+ may run one `lanes gc` at once, because systemd counts a missed calendar run from the timer's last trigger; that sweep
2796
+ ends only what a midnight one would.]
2797
+
2730
2798
  ### NEVER
2731
2799
 
2732
2800
  From the [RUNBOOK](RUNBOOK.md#never):
@@ -172,7 +172,27 @@ check_docs_age
172
172
  export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
173
173
  if [ "$start" = 1 ]; then
174
174
  systemctl --user show-environment >/dev/null
175
- python3 -c 'import subprocess; subprocess.run(["docker", "info", "--format", "{{.ServerVersion}}"], check=True, timeout=15)'
175
+ # An update of an aggregator — a host whose boards all run behind guests (lanes-site/1, docs/RUNBOOK.md
176
+ # "Federation") — needs no docker daemon of its own: when `docker info` is refused and `lanes sync` recorded no
177
+ # local container with a home volume, the update goes on with a warning. A full install, and an update of a host
178
+ # with local containers, still refuse: install-container and the pulse need docker there.
179
+ if ! python3 -c 'import subprocess; subprocess.run(["docker", "info", "--format", "{{.ServerVersion}}"], check=True, timeout=15)'; then
180
+ [ "$update_only" = 1 ] || exit 1
181
+ python3 - "$state/containers.json" <<'PY' || exit 1
182
+ import json, sys
183
+ try:
184
+ recorded = json.load(open(sys.argv[1]))
185
+ except (OSError, ValueError):
186
+ sys.exit(1)
187
+ # A failed inspect has no home either: absence of an answer is not evidence
188
+ # that this host needs no Docker. Malformed records also fail closed (BEY-7140).
189
+ local = sorted(name for name, info in recorded.items()
190
+ if not isinstance(info, dict) or info.get('error') or info.get('home')) \
191
+ if isinstance(recorded, dict) else None
192
+ sys.exit(0 if local == [] else 1)
193
+ PY
194
+ printf 'WARN docker info was refused; no local container is recorded (an aggregator): the update goes on without it\n' >&3
195
+ fi
176
196
  fi
177
197
  if [ "$check" = 1 ]; then
178
198
  echo 'Server prerequisites: ready'
@@ -3,7 +3,8 @@
3
3
  adoption half; P32; BEY-6988). Python 3 stdlib.
4
4
 
5
5
  python3 libexec/adopt.py adopt [--state DIR] [--tree DIR] [--json] adopt every domain; exit 0 every domain adopted,
6
- 3 a domain refused, 1 an I/O failure, 2 usage
6
+ 3 a domain refused, 4 an I/O failure, 2 usage
7
+ (1 is never ours: Python's own crash status)
7
8
  python3 libexec/adopt.py status [--state DIR] [--json] what is adopted, verified on disk; exit 0 every
8
9
  domain verified, 3 otherwise (or none adopted)
9
10
  python3 libexec/adopt.py doctor [--state DIR] `lanes doctor`'s lines (doctor_lines)
@@ -55,7 +56,9 @@ LEGACY_SCHEMA = 1 # the schema epoch the Python owner
55
56
  ADOPTION = Path('lanes2') / 'adoption.json' # under $LANES_STATE
56
57
  STORE_DIR = Path('store') # under $LANES_STATE (AR 4.4)
57
58
  STORE_FILE = 'coordination.sqlite'
58
- EXIT_IO, EXIT_USAGE, EXIT_REFUSED = 1, 2, 3
59
+ # Exit 1 is what Python itself returns for an uncaught exception (an import or syntax failure in a broken tree), so
60
+ # the adopter never uses it: update.py keeps 3 and 4 as warnings and a crash (1) as a failure (WARN_RC).
61
+ EXIT_USAGE, EXIT_REFUSED, EXIT_IO = 2, 3, 4
59
62
  ADOPTION_MAX = 64 * 1024
60
63
  # The Lanes 2.0 state domains (RT 6.2 "the store includes ..." and the Round-2 slices), each with what it holds and
61
64
  # where its 1.x owner keeps it. Order is doctor order.
@@ -187,20 +190,57 @@ def adopt(state, tree=None, now=None):
187
190
  return document
188
191
 
189
192
 
193
+ def _refusal_entry(entry):
194
+ return (isinstance(entry, dict) and set(entry) == {'domain', 'code'}
195
+ and all(isinstance(entry[key], str) for key in ('domain', 'code')))
196
+
197
+
190
198
  def read_adoption(state):
191
- """The adoption record, None when there is none, or raises ValueError when it is not one."""
199
+ """The adoption record, None when there is none, or raises ValueError when it is not one: every field the doctor
200
+ and status read is checked for its type here (kind; domains a list of strings; refused a list of {domain, code}
201
+ strings; adopted_at, release and store strings), so a damaged record is one ✗ line, never a crash."""
192
202
  path = Path(state) / ADOPTION
193
203
  try:
194
- raw = path.read_bytes()
204
+ with path.open('rb') as handle:
205
+ raw = handle.read(ADOPTION_MAX + 1)
195
206
  except FileNotFoundError:
196
207
  return None
197
208
  if len(raw) > ADOPTION_MAX:
198
209
  raise ValueError(f'longer than {ADOPTION_MAX} bytes')
199
- document = json.loads(raw)
200
- domains = document.get('domains') if isinstance(document, dict) else None
201
- if (not isinstance(document, dict) or document.get('kind') != KIND or not isinstance(domains, list)
202
- or not all(isinstance(name, str) for name in domains)):
210
+ try:
211
+ document = json.loads(raw)
212
+ except RecursionError as error:
213
+ raise ValueError('adoption record is nested too deeply') from error
214
+ if (not isinstance(document, dict) or type(document.get('v')) is not int or document['v'] != 1
215
+ or document.get('kind') != KIND):
203
216
  raise ValueError(f'not a {KIND} record')
217
+ # BEY-7110: validate every consumed field before doctor/status use it.
218
+ # Unknown domains remain valid for readers of an older v1 release.
219
+ for field in ('adopted_at', 'release', 'store'):
220
+ value = document.get(field)
221
+ if not isinstance(value, str) or '\x00' in value or (field != 'release' and not value):
222
+ raise ValueError(f'invalid {field}')
223
+ # JSON permits escaped lone surrogates; paths and diagnostic output do not.
224
+ # Refuse inside this reader's ValueError boundary before either consumes it.
225
+ value.encode('utf-8')
226
+ domains = document.get('domains')
227
+ if (not isinstance(domains, list)
228
+ or not all(isinstance(name, str) and cutover.DOMAIN_RE.fullmatch(name) for name in domains)
229
+ or len(domains) != len(set(domains))):
230
+ raise ValueError('invalid domains')
231
+ refused = document.get('refused')
232
+ if not isinstance(refused, list):
233
+ raise ValueError('invalid refused')
234
+ seen = set(domains)
235
+ for entry in refused:
236
+ if not _refusal_entry(entry):
237
+ raise ValueError('invalid refusal')
238
+ domain, code = entry.get('domain'), entry.get('code')
239
+ if (not isinstance(domain, str) or not cutover.DOMAIN_RE.fullmatch(domain) or domain in seen
240
+ or not isinstance(code, str) or not code or '\x00' in code):
241
+ raise ValueError('invalid refusal')
242
+ code.encode('utf-8')
243
+ seen.add(domain)
204
244
  return document
205
245
 
206
246
 
@@ -248,8 +288,7 @@ def doctor_lines(state=None):
248
288
  lines = [('', f"lanes2: adopted {document.get('adopted_at') or '?'} by {release}; {_store_text(state, document)}; "
249
289
  f'{_flags_text(state)}')]
250
290
  listed = set(document['domains'])
251
- refused = {entry.get('domain'): entry.get('code') for entry in document.get('refused') or ()
252
- if isinstance(entry, dict)}
291
+ refused = {entry['domain']: entry['code'] for entry in document.get('refused') or ()}
253
292
  for domain, what, legacy in DOMAINS:
254
293
  record, code = verify_domain(state, domain)
255
294
  if domain not in listed:
@@ -69,6 +69,38 @@ def settings(environ):
69
69
  return limit, age, refused
70
70
 
71
71
 
72
+
73
+ def align_pending(pending):
74
+ """Start retained presentation at ESC within the first CHUNK bytes (BEY-7148).
75
+
76
+ A PTY read boundary can split an escape sequence. Search the bounded
77
+ queued byte stream across chunks, as the Rust relay does for its ring.
78
+ Without an escape in that window, leave plain output unchanged.
79
+ """
80
+ scanned = 0
81
+ discard = None
82
+ for chunk in pending:
83
+ window = min(len(chunk), CHUNK - scanned)
84
+ at = chunk.find(b'\x1b', 0, window)
85
+ if at >= 0:
86
+ discard = scanned + at
87
+ break
88
+ scanned += window
89
+ if scanned == CHUNK:
90
+ break
91
+ if discard is None:
92
+ return 0
93
+ left = discard
94
+ while left:
95
+ chunk = pending.popleft()
96
+ if len(chunk) > left:
97
+ pending.appendleft(chunk[left:])
98
+ left = 0
99
+ else:
100
+ left -= len(chunk)
101
+ return discard
102
+
103
+
72
104
  def relay(command, output_limit=OUTPUT_LIMIT, output_age=OUTPUT_AGE):
73
105
  if not command:
74
106
  raise ValueError('No display command supplied')
@@ -119,11 +151,9 @@ def relay(command, output_limit=OUTPUT_LIMIT, output_age=OUTPUT_AGE):
119
151
  if not dropped: # a limit below two reads: nothing stale to drop, nothing cut
120
152
  return
121
153
  # Start what is kept at its first escape sequence, not inside one (or inside a UTF-8 character).
122
- at = pending[0].find(b'\x1b')
123
- if at > 0:
124
- pending[0] = pending[0][at:]
125
- pending_size -= at
126
- dropped += at
154
+ aligned = align_pending(pending)
155
+ pending_size -= aligned
156
+ dropped += aligned
127
157
  pending.appendleft(CUT)
128
158
  pending_size += len(CUT)
129
159
  shed_bytes += dropped
@@ -2,21 +2,26 @@
2
2
  """`lanes doctor`'s Lanes 2.0 runtime signals (lanes2 Round 2 R2-DOCTOR; RT 16.3, TI 11; BEY-6988). Python 3 stdlib.
3
3
 
4
4
  A Lanes 2.0 host keeps one bounded metrics registry (crates/lanes-runtime/src/signals) and exports it as the snapshot
5
- `$LANES_STATE/signals/lanes2.json` (`lanes2.signals.snapshot/1`, the manifest docs/contracts/lanes2/manifests/
6
- signals.json; DM-LANES2-RT16-SIGNALS). The snapshot is self-describing: every signal carries its doctor phrase, unit,
7
- delay origin, state (ok, warn, alert or unavailable with a reason) and per label its value and the threshold the host
8
- resolved from its resource manifest (lane G2) and benchmark.json (RT 14.1, 15.3). This module only renders it, so the
9
- same text comes out wherever it runs (an installed tree has no docs/), and the Throttle monitor tab reads the same file.
5
+ `$LANES_STATE/signals/lanes2.json` (`lanes2.signals.snapshot/2`, the manifest docs/contracts/lanes2/manifests/
6
+ signals.json revision 2; DM-LANES2-RT16-SIGNALS). The snapshot is self-describing: every signal carries its doctor
7
+ phrase, unit, kind, delay origin, state (ok, warn, alert or unavailable with a reason) and per label its value, its
8
+ increase in the window (a counter) or its rise (a high-water mark), its state and reason, and the threshold the host
9
+ resolved from its resource manifest (lane G2), benchmark.json (RT 14.1, 15.3) or the subsystem's own reported cap.
10
+ This module only renders it, so the same text comes out wherever it runs (an installed tree has no docs/). A Throttle
11
+ monitor tab on the same host may read the same file; none does yet.
10
12
 
11
13
  `doctor_lines(state)` -> [(mark, text)] in `lanes doctor`'s protocol (`✓`/`✗` are checks, `⚠` a warning, `` an
12
14
  information line):
13
15
 
14
16
  - no snapshot file: nothing (no Lanes 2.0 host exports one before integration gate I1);
15
- - a snapshot that cannot be read, is not one, or exceeds MAX_BYTES: one ✗ line and nothing else;
16
- - otherwise a header, ✓ fresh or ✗ stale (older than its own `stale_after_ms`: the host stopped exporting, the values
17
+ - a snapshot that cannot be read, is not one, lacks a field the renderer prints, or exceeds MAX_BYTES: one ✗ line and
18
+ nothing else (never an exception: `lanes doctor` goes on to its later checks);
19
+ - otherwise a header (the host instance, lanes-runtime version, source revision, installed version, profile and
20
+ manifest revisions), ✓ fresh or ✗ stale (older than its own `stale_after_ms`: the host stopped exporting, the values
17
21
  are its last), the delay-origin line (RT 16.3: client rendering, Lanes queueing, storage, holder, network, native
18
- harness), the facet line (resources, custody, owner sources), then exactly one line per signal in snapshot order:
19
- ✗ for an alert, ⚠ for a warning, an information line for ok and unavailable.
22
+ harness; each ok, incomplete when a signal of it is unobserved, warn or alert), the facet line (resources, custody,
23
+ owner sources), then exactly one line per signal in snapshot order: ✗ for an alert, ⚠ for a warning or a signal the
24
+ host did not sample (`not_sampled`), an information line for ok and a declared unavailable reason.
20
25
 
21
26
  Every value is an integer and every line is built from the snapshot and the clock alone, so a snapshot and a `now`
22
27
  render to the same bytes every time.
@@ -30,10 +35,13 @@ import sys
30
35
  import time
31
36
  from pathlib import Path
32
37
 
33
- SCHEMA = 'lanes2.signals.snapshot/1'
38
+ SCHEMA = 'lanes2.signals.snapshot/2'
34
39
  SNAPSHOT = Path('signals') / 'lanes2.json' # under $LANES_STATE: signals.json `snapshot.path`
35
- MAX_BYTES = 65536 # signals.json `snapshot.max_bytes`
40
+ MAX_BYTES = 131072 # signals.json `snapshot.max_bytes`
41
+ NOT_SAMPLED = 'not_sampled' # the registry's own reason: a producer the host did not run
36
42
  STATES = ('ok', 'warn', 'alert', 'unavailable')
43
+ ORIGIN_STATES = ('ok', 'incomplete', 'warn', 'alert')
44
+ KINDS = ('gauge', 'counter', 'high_water', 'age', 'flag')
37
45
  MARK = {'alert': '✗', 'warn': '⚠', 'ok': '', 'unavailable': ''}
38
46
  CMP = {'at_least': '≥', 'above': '>', 'at_most': '≤'}
39
47
  USAGE = 'usage: doctor_lanes2.py [--snapshot PATH] [--now-ms MS]'
@@ -41,7 +49,7 @@ KIB, MIB, GIB = 1 << 10, 1 << 20, 1 << 30
41
49
 
42
50
 
43
51
  class Malformed(ValueError):
44
- """The document is not a `lanes2.signals.snapshot/1` snapshot this renderer can show."""
52
+ """The document is not a `lanes2.signals.snapshot/2` snapshot this renderer can show."""
45
53
 
46
54
 
47
55
  def default_state():
@@ -53,6 +61,12 @@ def is_int(value):
53
61
  return isinstance(value, int) and not isinstance(value, bool) and value >= 0
54
62
 
55
63
 
64
+ def present(mapping, key):
65
+ """Whether `mapping` is an object that carries `key` (null included): every field the renderer prints must be
66
+ there, a missing one is a malformed snapshot, never a KeyError."""
67
+ return isinstance(mapping, dict) and key in mapping
68
+
69
+
56
70
  def tenths(value, unit):
57
71
  """`value / unit` with one decimal, by integer arithmetic (no float formatting)."""
58
72
  scaled = value * 10 // unit
@@ -78,9 +92,15 @@ def fmt(value, unit):
78
92
 
79
93
 
80
94
  def sample_text(sample, unit):
81
- """`[<label> ]<value>[ <threshold note>]`: the bound it crossed for warn/alert, `of <cap>` for a cap it is under."""
95
+ """`[<label> ]<value>[, +<increase>][ <threshold note>]`, or `[<label> ]unavailable (<reason>)`: the bound it
96
+ crossed for warn/alert (a counter's bound applies to its increase), `of <cap>` for a cap it is under."""
82
97
  label = sample['label']
83
- text = (f'{label} ' if label is not None else '') + fmt(sample['value'], unit)
98
+ head = f'{label} ' if label is not None else ''
99
+ if sample['state'] == 'unavailable':
100
+ return f"{head}unavailable ({sample['reason']})"
101
+ text = head + fmt(sample['value'], unit)
102
+ if sample['delta'] is not None:
103
+ text += f", +{fmt(sample['delta'], unit)}"
84
104
  state, cmp = sample['state'], sample['cmp']
85
105
  if state in ('warn', 'alert'):
86
106
  bound = sample[state]
@@ -93,11 +113,13 @@ def sample_text(sample, unit):
93
113
 
94
114
 
95
115
  def signal_line(signal):
96
- """(mark, text) of one signal."""
116
+ """(mark, text) of one signal: ✗ alert, ⚠ warning or not sampled, else information."""
97
117
  head = f"{signal['id']} — {signal['doctor']}: "
98
- if signal['state'] == 'unavailable':
99
- return '', head + f"unavailable ({signal['reason'] or 'no reason given'})"
100
- return MARK[signal['state']], head + '; '.join(sample_text(s, signal['unit']) for s in signal['samples'])
118
+ unsampled = signal['reason'] == NOT_SAMPLED or any(s['reason'] == NOT_SAMPLED for s in signal['samples'])
119
+ mark = MARK[signal['state']] or ('⚠' if unsampled else '')
120
+ if signal['reason'] is not None:
121
+ return mark, head + f"unavailable ({signal['reason']})"
122
+ return mark, head + '; '.join(sample_text(s, signal['unit']) for s in signal['samples'])
101
123
 
102
124
 
103
125
  def origin_text(origin):
@@ -106,36 +128,71 @@ def origin_text(origin):
106
128
 
107
129
 
108
130
  def check_snapshot(doc):
109
- """Raise Malformed unless `doc` has the shape the renderer reads (never trusts a field it then prints)."""
131
+ """Raise Malformed unless `doc` has every field the renderer reads, of the type it reads (never trusts a field it
132
+ then prints, and never meets a missing one)."""
110
133
  def need(ok, what):
111
134
  if not ok:
112
135
  raise Malformed(what)
113
136
 
137
+ def has(mapping, key, test):
138
+ return present(mapping, key) and test(mapping[key])
139
+
140
+ def text(value):
141
+ return isinstance(value, str)
142
+
143
+ def optional_text(value):
144
+ return value is None or isinstance(value, str)
145
+
146
+ def optional_int(value):
147
+ return value is None or is_int(value)
148
+
149
+ def word_of(words):
150
+ # A word of `words`, tested as a string first: an unhashable value (a list, an object) is malformed, never
151
+ # a TypeError from the dict lookup.
152
+ return lambda value: isinstance(value, str) and value in words
153
+
114
154
  need(isinstance(doc, dict), 'not a JSON object')
115
- need(doc.get('schema') == SCHEMA and doc.get('v') == 1, f'not {SCHEMA}')
155
+ need(doc.get('schema') == SCHEMA and doc.get('v') == 2, f'not {SCHEMA}')
116
156
  for key in ('manifest_revision', 'resources_revision', 'written_at_ms', 'refresh_ms', 'stale_after_ms'):
117
- need(is_int(doc.get(key)), f'`{key}` is not a non-negative integer')
157
+ need(has(doc, key, is_int), f'`{key}` is not a non-negative integer')
118
158
  for key in ('profile', 'runtime_version'):
119
- need(isinstance(doc.get(key), str), f'`{key}` is not a string')
120
- need(doc.get('host_instance') is None or isinstance(doc.get('host_instance'), str), '`host_instance`')
121
- need(isinstance(doc.get('attribution'), list) and isinstance(doc.get('signals'), list), 'no attribution or signals')
159
+ need(has(doc, key, text), f'`{key}` is not a string')
160
+ for key in ('host_instance', 'source_revision', 'installed_version'):
161
+ need(has(doc, key, optional_text), f'`{key}` is not a string or null')
162
+ need(has(doc, 'attribution', lambda v: isinstance(v, list)) and has(doc, 'signals', lambda v: isinstance(v, list)),
163
+ 'no attribution or signals')
122
164
  for origin in doc['attribution']:
123
- need(isinstance(origin, dict) and isinstance(origin.get('label'), str) and origin.get('state') in STATES
124
- and isinstance(origin.get('delay'), bool) and isinstance(origin.get('signals'), list)
125
- and all(isinstance(name, str) for name in origin['signals']), 'a malformed attribution entry')
165
+ need(has(origin, 'origin', text) and has(origin, 'label', text)
166
+ and has(origin, 'state', word_of(ORIGIN_STATES))
167
+ and has(origin, 'delay', lambda v: isinstance(v, bool))
168
+ and has(origin, 'signals', lambda v: isinstance(v, list) and all(isinstance(n, str) for n in v)),
169
+ 'a malformed attribution entry')
126
170
  for signal in doc['signals']:
127
171
  need(isinstance(signal, dict), 'a signal is not an object')
128
- need(all(isinstance(signal.get(key), str) for key in ('id', 'doctor', 'unit', 'origin')),
129
- 'a signal without id, doctor, unit or origin')
130
- need(signal.get('state') in STATES, f"{signal.get('id')}: unknown state")
131
- need(signal.get('reason') is None or isinstance(signal.get('reason'), str), f"{signal['id']}: reason")
132
- need(isinstance(signal.get('samples'), list), f"{signal['id']}: no samples")
172
+ need(all(has(signal, key, text) for key in ('id', 'doctor', 'unit', 'kind', 'origin')),
173
+ 'a signal without id, doctor, unit, kind or origin')
174
+ sid = signal['id']
175
+ need(word_of(KINDS)(signal['kind']), f'{sid}: unknown kind')
176
+ need(has(signal, 'state', word_of(STATES)), f'{sid}: unknown state')
177
+ need(has(signal, 'reason', optional_text), f'{sid}: reason')
178
+ need(has(signal, 'samples', lambda v: isinstance(v, list)), f'{sid}: no samples')
179
+ if signal['reason'] is not None:
180
+ need(signal['state'] == 'unavailable' and not signal['samples'],
181
+ f'{sid}: an unavailable signal with samples')
182
+ else:
183
+ need(bool(signal['samples']), f'{sid}: a signal without samples or a reason')
133
184
  for sample in signal['samples']:
134
- need(isinstance(sample, dict) and is_int(sample.get('value')) and sample.get('state') in STATES
135
- and (sample.get('label') is None or isinstance(sample.get('label'), str))
136
- and all(sample.get(key) is None or is_int(sample.get(key)) for key in ('warn', 'alert'))
137
- and (sample.get('cmp') is None or sample.get('cmp') in CMP), f"{signal['id']}: a malformed sample")
138
- need(signal['state'] == 'unavailable' or signal['samples'], f"{signal['id']}: a state without samples")
185
+ need(isinstance(sample, dict)
186
+ and has(sample, 'label', optional_text)
187
+ and has(sample, 'value', optional_int)
188
+ and has(sample, 'delta', optional_int)
189
+ and has(sample, 'state', word_of(STATES))
190
+ and has(sample, 'reason', optional_text)
191
+ and has(sample, 'cmp', lambda v: v is None or word_of(CMP)(v))
192
+ and all(has(sample, key, optional_int) for key in ('warn', 'alert')), f'{sid}: a malformed sample')
193
+ unavailable = sample['state'] == 'unavailable'
194
+ need(unavailable == (sample['value'] is None) == (sample['reason'] is not None),
195
+ f'{sid}: a sample whose value, state and reason disagree')
139
196
 
140
197
 
141
198
  def render(doc, now_ms, path):
@@ -144,6 +201,7 @@ def render(doc, now_ms, path):
144
201
  host = doc['host_instance'] or 'an unnamed host'
145
202
  written, stale = doc['written_at_ms'], doc['stale_after_ms']
146
203
  lines = [('', f"lanes2 runtime signals: {path}, from {host} (lanes-runtime {doc['runtime_version']}, "
204
+ f"source {doc['source_revision'] or 'unknown'}, installed {doc['installed_version'] or 'unknown'}, "
147
205
  f"profile {doc['profile']} r{doc['resources_revision']}, manifest r{doc['manifest_revision']})")]
148
206
  if written > now_ms:
149
207
  lines.append(('⚠', f'lanes2 signals snapshot written {tenths(written - now_ms, 1000)} s in the future: '
@@ -163,6 +221,10 @@ def render(doc, now_ms, path):
163
221
  return lines
164
222
 
165
223
 
224
+ def unreadable(path, why):
225
+ return [('✗', f'lanes2 signals snapshot readable — {why} ({path})')]
226
+
227
+
166
228
  def read_snapshot(path, now_ms=None):
167
229
  """[(mark, text)] of the snapshot file `path` at `now_ms` (Unix ms, default now); [] when the file is absent."""
168
230
  now_ms = int(time.time() * 1000) if now_ms is None else now_ms
@@ -172,18 +234,27 @@ def read_snapshot(path, now_ms=None):
172
234
  except FileNotFoundError:
173
235
  return []
174
236
  except OSError as error:
175
- return [('✗', f'lanes2 signals snapshot readable — {error.strerror or error} ({path})')]
237
+ return unreadable(path, error.strerror or error)
176
238
  if len(data) > MAX_BYTES:
177
- return [('✗', f'lanes2 signals snapshot readable — larger than {MAX_BYTES} bytes ({path})')]
239
+ return unreadable(path, f'larger than {MAX_BYTES} bytes')
178
240
  try:
179
241
  return render(json.loads(data.decode('utf-8')), now_ms, path)
242
+ except RecursionError: # a document nested deeper than the decoder recurses
243
+ return unreadable(path, 'nested too deeply')
180
244
  except (UnicodeDecodeError, ValueError) as error: # json.JSONDecodeError and Malformed are ValueErrors
181
- return [('✗', f'lanes2 signals snapshot readable — {error} ({path})')]
245
+ return unreadable(path, error)
246
+ except (KeyError, TypeError, IndexError) as error: # a field check_snapshot let through: still one problem line
247
+ return unreadable(path, f'{type(error).__name__} {error}')
182
248
 
183
249
 
184
250
  def doctor_lines(state=None, now_ms=None):
185
- """`lanes doctor`'s lines for the snapshot under `state` ($LANES_STATE); [] when there is none."""
186
- return read_snapshot(Path(state if state is not None else default_state()) / SNAPSHOT, now_ms)
251
+ """`lanes doctor`'s lines for the snapshot under `state` ($LANES_STATE); [] when there is none. Never raises: a
252
+ renderer fault is one ✗ line, so `lanes doctor` still prints its later checks."""
253
+ path = Path(state if state is not None else default_state()) / SNAPSHOT
254
+ try:
255
+ return read_snapshot(path, now_ms)
256
+ except Exception as error: # noqa: BLE001 — doctor must survive its own renderer
257
+ return unreadable(path, f'the renderer failed: {type(error).__name__}')
187
258
 
188
259
 
189
260
  def print_lines(lines, out=None):