agent-bios 0.19.4 → 0.20.0
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.
- package/DEPENDENCIES.md +19 -5
- package/README.md +14 -19
- package/claude/agents/frontier.md +1 -1
- package/claude/guides/claude-prompting.md +475 -234
- package/claude/guides/cli-multi-model-workflow.md +4 -3
- package/claude/guides/gpt-prompting.md +235 -136
- package/claude/guides/session-distill-workflow.md +93 -43
- package/claude/guides/tooling-gotchas.md +3 -1
- package/codex/guides/claude-prompting.md +475 -234
- package/codex/guides/cli-multi-model-workflow.md +4 -3
- package/codex/guides/gpt-prompting.md +235 -136
- package/codex/guides/session-distill-workflow.md +93 -43
- package/codex/guides/tooling-gotchas.md +3 -1
- package/compose/assemble.py +4 -1
- package/compose/canary.sh +8 -6
- package/compose/host_platform.py +158 -15
- package/compose/instructions-state.py +183 -41
- package/compose/instructions_install.py +222 -27
- package/compose/instructions_session.py +250 -75
- package/compose/instructions_setup_cli.py +2 -36
- package/compose/instructions_store.py +160 -3
- package/compose/instructions_transaction.py +29 -5
- package/docs/advanced-launch.md +4 -0
- package/docs/releases/0.20.0.md +102 -0
- package/install.sh +42 -14
- package/launch/agent-launch.py +152 -18
- package/launch/agent-launch.toml +17 -7
- package/launch/agent-launch.zsh +104 -13
- package/launch/claude_subcommands.py +179 -0
- package/launch/shell_integration.py +7 -1
- package/learn/collect-learning.py +60 -9
- package/learn/migrate-learnings.py +70 -4
- package/learn/redact.py +2 -1
- package/package.json +36 -3
- package/provenance.json +1 -1
- package/session-cost.py +80 -9
- package/session-distill/coverage.json +6 -0
- package/session-distill/distill.py +2575 -0
- package/session-distill/grammar/__init__.py +0 -0
- package/session-distill/grammar/owner_lines.py +874 -0
- package/session-distill/originators.json +9 -0
- package/session-distill/packets/cross_review.md +31 -0
- package/session-distill/packets/form.md +86 -0
- package/session-distill/packets/judge.md +81 -0
- package/session-distill/packets/placement_contract.md +90 -0
- package/session-distill/packets/propose.md +124 -0
- package/session-distill/packets/read.md +57 -0
- package/session-distill/packets/reconsider.md +53 -0
- package/session-distill/packets/s7b.md +65 -0
- package/session-distill/packets/s9b.md +39 -0
- package/session-distill/packets/stitch.md +35 -0
- package/session-distill/packets/sweep.md +33 -0
- package/session-distill/runlib/__init__.py +0 -0
- package/session-distill/runlib/bound.py +1102 -0
- package/session-distill/runlib/breaker.py +467 -0
- package/session-distill/runlib/census.py +2347 -0
- package/session-distill/runlib/claims.py +420 -0
- package/session-distill/runlib/controls.py +902 -0
- package/session-distill/runlib/coverage.py +881 -0
- package/session-distill/runlib/declare.py +888 -0
- package/session-distill/runlib/delivery_evidence.py +1145 -0
- package/session-distill/runlib/derive.py +812 -0
- package/session-distill/runlib/destinations.py +3072 -0
- package/session-distill/runlib/dispatch.py +7939 -0
- package/session-distill/runlib/drift.py +1077 -0
- package/session-distill/runlib/entry.py +401 -0
- package/session-distill/runlib/evidence.py +890 -0
- package/session-distill/runlib/exposure.py +1162 -0
- package/session-distill/runlib/gate.py +2727 -0
- package/session-distill/runlib/gitread.py +79 -0
- package/session-distill/runlib/inventory.py +19624 -0
- package/session-distill/runlib/journal.py +1919 -0
- package/session-distill/runlib/ledger.py +3210 -0
- package/session-distill/runlib/ledger_compat.py +101 -0
- package/session-distill/runlib/ledger_migration.py +190 -0
- package/session-distill/runlib/lifecycle_intake.py +693 -0
- package/session-distill/runlib/lineage.py +454 -0
- package/session-distill/runlib/measures.py +249 -0
- package/session-distill/runlib/monitor.py +1180 -0
- package/session-distill/runlib/operations.py +522 -0
- package/session-distill/runlib/packet.py +838 -0
- package/session-distill/runlib/placement.py +1769 -0
- package/session-distill/runlib/projection.py +4090 -0
- package/session-distill/runlib/ranking.py +740 -0
- package/session-distill/runlib/receipts.py +200 -0
- package/session-distill/runlib/records.py +1965 -0
- package/session-distill/runlib/search.py +249 -0
- package/session-distill/runlib/sequencing.py +829 -0
- package/session-distill/runlib/sources.py +641 -0
- package/session-distill/runlib/stage_adjudicate.py +845 -0
- package/session-distill/runlib/stage_apply.py +1378 -0
- package/session-distill/runlib/stage_approvals.py +758 -0
- package/session-distill/runlib/stage_close.py +1220 -0
- package/session-distill/runlib/stage_confirm.py +929 -0
- package/session-distill/runlib/stage_delivery.py +3080 -0
- package/session-distill/runlib/stage_form.py +2576 -0
- package/session-distill/runlib/stage_judge.py +4248 -0
- package/session-distill/runlib/stage_propose.py +3307 -0
- package/session-distill/runlib/stage_read.py +5179 -0
- package/session-distill/runlib/stage_render.py +2739 -0
- package/session-distill/runlib/stage_retrieve.py +924 -0
- package/session-distill/runlib/stage_review_korean.py +1002 -0
- package/session-distill/runlib/stage_review_proposals.py +1292 -0
- package/session-distill/runlib/stagelock.py +412 -0
- package/session-distill/runlib/stop.py +1061 -0
- package/session-distill/runlib/targets.py +809 -0
- package/session-distill/runlib/usage.py +280 -0
- package/session-distill/runlib/validate.py +319 -0
- package/session-distill/runlib/views.py +4327 -0
- package/session-distill/schemas/adjudication.schema.json +35 -0
- package/session-distill/schemas/approval.schema.json +35 -0
- package/session-distill/schemas/census.schema.json +128 -0
- package/session-distill/schemas/checks.schema.json +207 -0
- package/session-distill/schemas/claim.schema.json +16 -0
- package/session-distill/schemas/confirmation.schema.json +24 -0
- package/session-distill/schemas/coverage.schema.json +66 -0
- package/session-distill/schemas/cross_review.schema.json +24 -0
- package/session-distill/schemas/event.schema.json +20 -0
- package/session-distill/schemas/evidence.schema.json +20 -0
- package/session-distill/schemas/expected_observation.schema.json +18 -0
- package/session-distill/schemas/form.schema.json +103 -0
- package/session-distill/schemas/intake.schema.json +71 -0
- package/session-distill/schemas/inventory.schema.json +872 -0
- package/session-distill/schemas/judge.schema.json +77 -0
- package/session-distill/schemas/ledger.schema.json +313 -0
- package/session-distill/schemas/observation.schema.json +16 -0
- package/session-distill/schemas/propose.schema.json +555 -0
- package/session-distill/schemas/read.schema.json +76 -0
- package/session-distill/schemas/reconsider.schema.json +122 -0
- package/session-distill/schemas/run.schema.json +150 -0
- package/session-distill/schemas/s7b.schema.json +200 -0
- package/session-distill/schemas/s9b.schema.json +28 -0
- package/session-distill/schemas/stitch.schema.json +25 -0
- package/session-distill/schemas/sweep.schema.json +25 -0
- package/session-distill/seats.json +149 -0
- package/session-distill/tables/allowed_pairs.json +257 -0
- package/session-distill/tables/controls.json +30 -0
- package/session-distill/tables/delivery_evidence.json +36 -0
- package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
- package/session-distill/tables/destinations.json +684 -0
- package/session-distill/tables/drift_layers.json +68 -0
- package/session-distill/tables/exposure_rules.json +192 -0
- package/session-distill/tables/placement_rules.json +148 -0
- package/session-distill/tables/propose_fixtures.json +154 -0
- package/session-distill/tables/ranking.json +194 -0
- package/session-distill/tables/redundancy.json +10 -0
- package/session-distill/tables/structural_rules.json +44 -0
- package/session-distill/tables/transition_fixtures.json +398 -0
- package/session-distill/tables/transitions.json +69 -0
- package/session-distill/tables/unit_outcome.json +67 -0
- package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
- package/wrappers/claude-run.sh +481 -33
- package/wrappers/claude_hermetic_evidence.py +1423 -0
- package/wrappers/codex-helm.sh +38 -7
- package/wrappers/codex-run.sh +183 -20
- package/wrappers/codex_frame_filter.py +1199 -0
- package/wrappers/codex_protocol.py +737 -0
- package/wrappers/jsonl_lines.py +65 -0
|
@@ -0,0 +1,1061 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""The stop at a cap (design §13.2): freeze the process tree, rescan it, sweep its process
|
|
3
|
+
groups, kill, and verify by pid and start time.
|
|
4
|
+
|
|
5
|
+
A model call's process tree is sampled while it runs (`TreeSampler`). At a cap, `stop_tree`
|
|
6
|
+
SIGSTOPs every member the sampler knows, then repeats rounds until one fresh process listing
|
|
7
|
+
shows a stable, fully stopped member set: each round rescans the descendants of the root and of
|
|
8
|
+
every live member, sweeps the process groups of the tree — the root's own among them, even after
|
|
9
|
+
the root exited (a tool shell's background jobs keep its group after their parent dies) — and stops what it found and any member not yet in the
|
|
10
|
+
stopped state. A stopped process cannot fork, so a listing taken after every member stopped
|
|
11
|
+
that shows no new member is the whole tree; a member that forked between a listing and its
|
|
12
|
+
stop signal is found by the next round. That verified instant is the boundary of design §13.2's
|
|
13
|
+
guarantee — no request is sent after the stop takes effect — and it is what the outgoing-request
|
|
14
|
+
check is held against (monitor.boundary). Then every member is SIGKILLed and the kill is verified: a pid counts as
|
|
15
|
+
the same process only while its start time is the one recorded, so a recycled pid is never
|
|
16
|
+
signalled or counted. Detached daemons (setsid and a double fork) leave the tree before it is
|
|
17
|
+
seen and are outside the guarantee.
|
|
18
|
+
|
|
19
|
+
Every signal is sent to a pid only after a fresh process listing shows it with its recorded
|
|
20
|
+
start time; nothing is ever matched by command name. The listing carries no command at all, so
|
|
21
|
+
no process can shape a row of it: a line whose fixed fields cannot be read is counted unreadable.
|
|
22
|
+
|
|
23
|
+
A process listing that failed or lacks this very process is no evidence (ListingFailed), and one
|
|
24
|
+
with an unreadable line is incomplete evidence: the freeze and the kill it would have verified are
|
|
25
|
+
reported unverified, no pid is signalled on account of a failed listing, and the root's process
|
|
26
|
+
group is killed whole beside the runner's own handle; a member in another group is not signalled
|
|
27
|
+
blind and stays named among the unverified survivors.
|
|
28
|
+
|
|
29
|
+
Failures are named STOP_FREEZE_UNVERIFIED and STOP_SURVIVORS (CONTRACT; the self-test holds the
|
|
30
|
+
implemented codes against its copy of §13.2's two verifications).
|
|
31
|
+
|
|
32
|
+
stop.py --self-test
|
|
33
|
+
"""
|
|
34
|
+
import ast
|
|
35
|
+
import os
|
|
36
|
+
import pathlib
|
|
37
|
+
import signal
|
|
38
|
+
import subprocess
|
|
39
|
+
import sys
|
|
40
|
+
import threading
|
|
41
|
+
import time
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
CONTRACT = {"$comment": "design §13.2: freeze the process tree, rescan it, sweep its process groups, kill, and "
|
|
45
|
+
"verify by pid and start time (stop_tree; the freeze verified, then the kill)",
|
|
46
|
+
"predicate": "stop_tree"}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
PS = "/bin/ps" # the self-test's listing controls put a failing one here
|
|
50
|
+
PS_TIMEOUT_S = 10.0
|
|
51
|
+
# How far the wall clock may move apart from the monotonic one across a stop before its stamps are
|
|
52
|
+
# no evidence. The stamps are wall time because the boundary holds them against host wall-clock
|
|
53
|
+
# records; a step (an NTP correction, a manual set) between them makes that comparison meaningless.
|
|
54
|
+
CLOCK_STEP_S = 1.0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ListingFailed(Exception):
|
|
58
|
+
"""A process listing that cannot be evidence of anything."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Listing(dict):
|
|
62
|
+
"""pid -> row, and `unreadable`: how many lines of the listing could not be read."""
|
|
63
|
+
unreadable = 0
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def ps_table():
|
|
67
|
+
"""pid -> {pid, ppid, pgid, stat, start} for every process, from one `ps` listing of fixed
|
|
68
|
+
fields only (a Listing). Raises ListingFailed when the listing is no evidence: ps did not run
|
|
69
|
+
or exited nonzero, or the listing omits this very process, which no complete listing can."""
|
|
70
|
+
try:
|
|
71
|
+
# Under the C locale and UTC, as compose/instructions_setup_cli.py runs it: `lstart` is five words
|
|
72
|
+
# there, and seven under ko_KR, where every row read as unreadable and the listing was refused for
|
|
73
|
+
# omitting this process. UTC keeps a start time the same text in every listing of one process.
|
|
74
|
+
done = subprocess.run([PS, "-axo", "pid=,ppid=,pgid=,stat=,lstart="], capture_output=True, text=True,
|
|
75
|
+
timeout=PS_TIMEOUT_S, env={**os.environ, "LC_ALL": "C", "TZ": "UTC"})
|
|
76
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
77
|
+
raise ListingFailed(f"ps did not run ({exc.__class__.__name__})") from None
|
|
78
|
+
if done.returncode != 0:
|
|
79
|
+
raise ListingFailed(f"ps exited {done.returncode}")
|
|
80
|
+
rows = Listing()
|
|
81
|
+
for line in done.stdout.splitlines():
|
|
82
|
+
if not line.strip():
|
|
83
|
+
continue
|
|
84
|
+
parts = line.split()
|
|
85
|
+
try:
|
|
86
|
+
if len(parts) != 9:
|
|
87
|
+
raise ValueError
|
|
88
|
+
rows[int(parts[0])] = {"pid": int(parts[0]), "ppid": int(parts[1]), "pgid": int(parts[2]), "stat": parts[3],
|
|
89
|
+
"start": " ".join(parts[4:9])}
|
|
90
|
+
except ValueError:
|
|
91
|
+
rows.unreadable += 1
|
|
92
|
+
if os.getpid() not in rows:
|
|
93
|
+
raise ListingFailed(f"the listing ({len(rows)} rows) omits this process")
|
|
94
|
+
return rows
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def descendants(rows, root):
|
|
98
|
+
children = {}
|
|
99
|
+
for row in rows.values():
|
|
100
|
+
children.setdefault(row["ppid"], []).append(row["pid"])
|
|
101
|
+
seen, stack = set(), [root]
|
|
102
|
+
while stack:
|
|
103
|
+
for kid in children.get(stack.pop(), []):
|
|
104
|
+
if kid not in seen:
|
|
105
|
+
seen.add(kid)
|
|
106
|
+
stack.append(kid)
|
|
107
|
+
return seen
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def same(rows, pid, start):
|
|
111
|
+
"""True while `pid` is the process whose start time was recorded."""
|
|
112
|
+
row = rows.get(pid)
|
|
113
|
+
return bool(row and row["start"] == start)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class TreeSampler(threading.Thread):
|
|
117
|
+
"""Every pid the tree of `root` has had, with its start time, sampled every `interval` s."""
|
|
118
|
+
|
|
119
|
+
def __init__(self, root, interval=0.1):
|
|
120
|
+
super().__init__(daemon=True)
|
|
121
|
+
self.root, self.interval = root, interval
|
|
122
|
+
self.known, self.halt = {}, threading.Event()
|
|
123
|
+
self.sample()
|
|
124
|
+
|
|
125
|
+
def sample(self):
|
|
126
|
+
try:
|
|
127
|
+
rows = ps_table()
|
|
128
|
+
except ListingFailed: # nothing is learnt from a listing that is no evidence
|
|
129
|
+
return {}
|
|
130
|
+
for pid in descendants(rows, self.root) | ({self.root} if self.root in rows else set()):
|
|
131
|
+
self.known.setdefault(pid, rows[pid])
|
|
132
|
+
return rows
|
|
133
|
+
|
|
134
|
+
def run(self):
|
|
135
|
+
while not self.halt.wait(self.interval):
|
|
136
|
+
self.sample()
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _signal(rows, members, sig):
|
|
140
|
+
for pid, row in members.items():
|
|
141
|
+
if same(rows, pid, row["start"]):
|
|
142
|
+
try:
|
|
143
|
+
os.kill(pid, sig)
|
|
144
|
+
except ProcessLookupError:
|
|
145
|
+
pass
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def anchored(proc):
|
|
149
|
+
"""True while the runner is unreaped: its pid, and so the id of the group it leads, cannot have
|
|
150
|
+
gone to another process. Observed without reaping it."""
|
|
151
|
+
if proc.returncode is not None:
|
|
152
|
+
return False
|
|
153
|
+
try:
|
|
154
|
+
os.waitid(os.P_PID, proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT)
|
|
155
|
+
except ChildProcessError: # reaped by someone other than its handle
|
|
156
|
+
return False
|
|
157
|
+
return True
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def exited(proc):
|
|
161
|
+
"""True once the runner has exited (or was reaped), observed without reaping it."""
|
|
162
|
+
if proc.returncode is not None:
|
|
163
|
+
return True
|
|
164
|
+
try:
|
|
165
|
+
return os.waitid(os.P_PID, proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) is not None
|
|
166
|
+
except ChildProcessError:
|
|
167
|
+
return True
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _reach(rows, proc, members, alive, new, found_by_rescan, swept, anchor):
|
|
171
|
+
"""Add to `new` what the listed tree reaches from `alive` and `new`: their descendants, then every
|
|
172
|
+
process in their process groups; `members` are already stopped and are not added again. The
|
|
173
|
+
root's own group is swept only while `anchor` (the runner unreaped) proves the id is its."""
|
|
174
|
+
for root in set(alive) | set(new): # the root only while it is the process the sampler recorded
|
|
175
|
+
for pid in descendants(rows, root):
|
|
176
|
+
if pid not in members and pid not in new:
|
|
177
|
+
new[pid] = rows[pid]
|
|
178
|
+
found_by_rescan.add(pid)
|
|
179
|
+
# the root leads its own group (start_new_session), swept even after the root exits: a pid
|
|
180
|
+
# is never reused while a process group of that id has members
|
|
181
|
+
groups = (({proc.pid} if anchor else set()) | {row["pgid"] for row in [*alive.values(), *new.values()]}) - {0, 1, os.getpgrp()}
|
|
182
|
+
for pid, row in rows.items():
|
|
183
|
+
if row["pgid"] in groups and pid not in members and pid not in new and pid != os.getpid():
|
|
184
|
+
new[pid] = row
|
|
185
|
+
swept.add(pid)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _kill_root_group(proc):
|
|
189
|
+
"""SIGKILL the root's process group whole. Only the root's: it leads its own group and is this
|
|
190
|
+
process's unreaped child, so the id cannot have been reused; a member's other group, seen
|
|
191
|
+
earlier, may since have died and its id gone to an unrelated program, so no other group is
|
|
192
|
+
signalled blind (design §13.2 puts members that left the root's group outside the guarantee)."""
|
|
193
|
+
try:
|
|
194
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
195
|
+
except (ProcessLookupError, PermissionError):
|
|
196
|
+
pass
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def stop_tree(proc, sampler, clock=time.time, settle_s=0.3, freeze_wait_s=1.0, _scanned=None, monotonic=time.monotonic):
|
|
200
|
+
"""Freeze until a fresh listing shows a stable, fully stopped tree; kill; verify the kill.
|
|
201
|
+
Returns the record, including `problems` (STOP_FREEZE_UNVERIFIED, STOP_SURVIVORS) when
|
|
202
|
+
either verification fails. `_scanned(rows, new)` exists for the self-test's fork control
|
|
203
|
+
only: it runs after each round's listing, before that round's new members are stopped.
|
|
204
|
+
|
|
205
|
+
The stamps are wall time (`clock`); the freeze deadline runs on `monotonic`, and the record
|
|
206
|
+
keeps the monotonic instant beside each stamp. A wall clock that moved apart from the
|
|
207
|
+
monotonic one by more than CLOCK_STEP_S between the decision and the kill leaves the freeze
|
|
208
|
+
unverified, by name: its instant cannot be held against host records any more."""
|
|
209
|
+
problems = []
|
|
210
|
+
record = {"decided_at": clock()}
|
|
211
|
+
mono = {"decided_at": monotonic()}
|
|
212
|
+
sampler.halt.set()
|
|
213
|
+
members, found_by_rescan, swept = {}, set(), set()
|
|
214
|
+
first = dict(sampler.known)
|
|
215
|
+
deadline, rounds, running, new = mono["decided_at"] + freeze_wait_s, 0, [], {}
|
|
216
|
+
unlisted, unread = None, 0
|
|
217
|
+
anchor = anchored(proc) # the caller reaps the runner only after every stop of the call is done
|
|
218
|
+
while True:
|
|
219
|
+
try:
|
|
220
|
+
rows = ps_table()
|
|
221
|
+
except ListingFailed as exc:
|
|
222
|
+
unlisted = str(exc)
|
|
223
|
+
break
|
|
224
|
+
unread += rows.unreadable
|
|
225
|
+
rounds += 1
|
|
226
|
+
alive = {pid: row for pid, row in members.items() if same(rows, pid, row["start"])}
|
|
227
|
+
new = {pid: rows[pid] for pid, row in first.items() if same(rows, pid, row["start"])}
|
|
228
|
+
first = {}
|
|
229
|
+
_reach(rows, proc, members, alive, new, found_by_rescan, swept, anchor)
|
|
230
|
+
if _scanned is not None:
|
|
231
|
+
_scanned(rows, new)
|
|
232
|
+
running = sorted(pid for pid in alive if "T" not in rows[pid]["stat"] and "Z" not in rows[pid]["stat"])
|
|
233
|
+
if not new and not running:
|
|
234
|
+
break
|
|
235
|
+
if monotonic() > deadline:
|
|
236
|
+
break
|
|
237
|
+
members.update(new)
|
|
238
|
+
_signal(rows, {**new, **{pid: alive[pid] for pid in running}}, signal.SIGSTOP)
|
|
239
|
+
time.sleep(0.005)
|
|
240
|
+
stable = anchor and unlisted is None and not unread and not new and not running
|
|
241
|
+
record["freeze_at"], mono["freeze_at"] = (clock() if stable else None), monotonic()
|
|
242
|
+
if not anchor:
|
|
243
|
+
problems.append(f"STOP_FREEZE_UNVERIFIED the runner {proc.pid} was reaped before the stop, so no group id is "
|
|
244
|
+
f"provably its own: no group was swept or signalled by it ({rounds} rounds)")
|
|
245
|
+
members.update(new)
|
|
246
|
+
elif unlisted is not None:
|
|
247
|
+
problems.append(f"STOP_FREEZE_UNVERIFIED the process listing failed ({unlisted}), so no freeze is evidenced "
|
|
248
|
+
f"({rounds} rounds)")
|
|
249
|
+
elif unread:
|
|
250
|
+
problems.append(f"STOP_FREEZE_UNVERIFIED the process listing had {unread} unreadable lines, so no freeze is "
|
|
251
|
+
f"evidenced ({rounds} rounds)")
|
|
252
|
+
members.update(new)
|
|
253
|
+
elif not stable:
|
|
254
|
+
problems.append(f"STOP_FREEZE_UNVERIFIED pids {sorted(set(running) | set(new))} were not in the stopped state "
|
|
255
|
+
f"before the kill ({rounds} rounds)")
|
|
256
|
+
members.update(new)
|
|
257
|
+
killed_listed = False
|
|
258
|
+
try:
|
|
259
|
+
rows = ps_table()
|
|
260
|
+
if unlisted is not None: # a recovered listing rebuilds the tree from every sampled identity; the freeze stays unverified
|
|
261
|
+
alive = {pid: row for pid, row in members.items() if same(rows, pid, row["start"])}
|
|
262
|
+
new = {pid: rows[pid] for pid, row in sampler.known.items() if pid not in members and same(rows, pid, row["start"])}
|
|
263
|
+
_reach(rows, proc, members, alive, new, found_by_rescan, swept, anchor)
|
|
264
|
+
members.update(new)
|
|
265
|
+
_signal(rows, members, signal.SIGKILL)
|
|
266
|
+
unread, killed_listed = unread + rows.unreadable, True
|
|
267
|
+
except ListingFailed: # no pid is signalled unlisted
|
|
268
|
+
pass
|
|
269
|
+
if anchor and (unlisted is not None or unread or not killed_listed): # the runner unreaped: its group id is its own
|
|
270
|
+
_kill_root_group(proc)
|
|
271
|
+
if anchor and not exited(proc): # this process's own unreaped child dies whatever any listing said
|
|
272
|
+
os.kill(proc.pid, signal.SIGKILL)
|
|
273
|
+
until = time.monotonic() + 10
|
|
274
|
+
while anchor and not exited(proc) and time.monotonic() < until: # waited for, never reaped here
|
|
275
|
+
time.sleep(0.01)
|
|
276
|
+
record["kill_at"], mono["kill_at"] = clock(), monotonic()
|
|
277
|
+
step = (record["kill_at"] - record["decided_at"]) - (mono["kill_at"] - mono["decided_at"])
|
|
278
|
+
if abs(step) > CLOCK_STEP_S:
|
|
279
|
+
problems.append(f"STOP_FREEZE_UNVERIFIED the wall clock moved {step:+.3f} s against the monotonic clock "
|
|
280
|
+
f"between the decision and the kill, so the freeze instant is no evidence ({rounds} rounds)")
|
|
281
|
+
record["freeze_at"] = None
|
|
282
|
+
time.sleep(settle_s)
|
|
283
|
+
try:
|
|
284
|
+
rows = ps_table()
|
|
285
|
+
# every sampled identity is verified beside the reached ones: a listing that failed earlier
|
|
286
|
+
# may have left a sampled member unreached, and it is named if it lives
|
|
287
|
+
survivors = sorted(pid for pid, row in {**sampler.known, **members}.items()
|
|
288
|
+
if same(rows, pid, row["start"]) and "Z" not in rows[pid]["stat"])
|
|
289
|
+
if rows.unreadable:
|
|
290
|
+
problems.append(f"STOP_SURVIVORS the process listing had {rows.unreadable} unreadable lines, so the kill of "
|
|
291
|
+
f"{sorted(members)} is not verified")
|
|
292
|
+
except ListingFailed as exc:
|
|
293
|
+
rows, survivors = None, sorted(set(members) | set(sampler.known))
|
|
294
|
+
problems.append(f"STOP_SURVIVORS the process listing failed ({exc}), so the kill of {survivors} is not verified")
|
|
295
|
+
if rows is not None and survivors:
|
|
296
|
+
problems.append(f"STOP_SURVIVORS pids {survivors} outlived the kill (verified by pid and start time)")
|
|
297
|
+
record.update(monotonic=mono, tree=[{"pid": pid, "start": row["start"]} for pid, row in sorted(members.items())],
|
|
298
|
+
found_by_rescan=sorted(found_by_rescan), swept=sorted(swept), rounds=rounds, survivors=survivors,
|
|
299
|
+
problems=problems)
|
|
300
|
+
return record
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def stop_recorded(identity, settle_s=2.0, freeze_wait_s=1.0):
|
|
304
|
+
"""Stop what a dead driver left running (WP-08 commit 5a): the process group of the runner whose `identity`
|
|
305
|
+
dispatch recorded when it started it (`{pid, start, pgid}`). It is signalled only when a fresh listing shows the
|
|
306
|
+
process at `pid` with the recorded start time, in the recorded group, and leading it, as dispatch starts every
|
|
307
|
+
runner (start_new_session); a pid since reused by another program, a group that is not the runner's, or an identity
|
|
308
|
+
recorded in part is never signalled.
|
|
309
|
+
|
|
310
|
+
The group is frozen before it is killed, as `stop_tree` freezes a tree (W r1): every member a listing shows in the
|
|
311
|
+
group is SIGSTOPped, and the group is listed again until one listing, still showing the leader as recorded, shows
|
|
312
|
+
every member stopped and none new. A member forked after the first listing is found that way, since a stopped
|
|
313
|
+
process cannot fork. Every member is then SIGKILLed, each only while its own start time is the one listed, and the
|
|
314
|
+
kill is verified over the whole group as a fresh listing shows it, not over the members found: a process the group
|
|
315
|
+
still holds is a survivor whether or not it was found. With the leader no longer listed, a group that still has
|
|
316
|
+
members cannot be shown to be the runner's (its id is free once the leader is gone and the group empties), so
|
|
317
|
+
nothing is signalled and the stop is `unverified`.
|
|
318
|
+
|
|
319
|
+
A listing with an unreadable line can hide a member, so none of the three conclusions - the group gone, the freeze
|
|
320
|
+
stable, the kill done - is drawn from one (W r2): the first listing is taken again until it is complete, within
|
|
321
|
+
`freeze_wait_s`; the freeze goes on listing until a complete listing shows it stable, or until its deadline, when
|
|
322
|
+
the members found are killed; and only a complete listing verifies the kill. When none is complete in time the stop
|
|
323
|
+
is `unverified`.
|
|
324
|
+
|
|
325
|
+
Returns `(outcome, detail)`: `stopped`, `survivors`, `gone` (no such process, and no process in its group),
|
|
326
|
+
`identity_mismatch` (named, nothing signalled) or `unverified` (no listing, an identity not recorded whole, a
|
|
327
|
+
group left without its leader, or a leader not listed by any complete listing: nothing signalled; or a kill no
|
|
328
|
+
complete listing verified)."""
|
|
329
|
+
pid, start, pgid = identity.get("pid"), identity.get("start"), identity.get("pgid")
|
|
330
|
+
if not isinstance(pid, int) or not isinstance(pgid, int) or not start or pgid in (0, 1) or pgid == os.getpgrp():
|
|
331
|
+
return "unverified", f"the runner's identity was not recorded whole: {identity}"
|
|
332
|
+
|
|
333
|
+
def in_group(rows):
|
|
334
|
+
return {p: r for p, r in rows.items() if r["pgid"] == pgid and p != os.getpid() and "Z" not in r["stat"]}
|
|
335
|
+
|
|
336
|
+
try:
|
|
337
|
+
rows = ps_table()
|
|
338
|
+
retry_until = time.monotonic() + freeze_wait_s
|
|
339
|
+
while pid not in rows and rows.unreadable and time.monotonic() < retry_until: # absence needs a complete listing
|
|
340
|
+
time.sleep(0.05)
|
|
341
|
+
rows = ps_table()
|
|
342
|
+
except ListingFailed as exc:
|
|
343
|
+
return "unverified", f"no listing to verify the runner against ({exc})"
|
|
344
|
+
row = rows.get(pid)
|
|
345
|
+
if row is None and rows.unreadable:
|
|
346
|
+
return "unverified", (f"pid {pid} is not listed, and no listing within {freeze_wait_s}s read every line (the last "
|
|
347
|
+
f"had {rows.unreadable} unreadable): its group is not shown gone, so none is signalled")
|
|
348
|
+
if row is None:
|
|
349
|
+
held = in_group(rows)
|
|
350
|
+
if held:
|
|
351
|
+
return "unverified", (f"pid {pid} is not listed and its group {pgid} still holds pids {sorted(held)}: with no "
|
|
352
|
+
f"leader to show the group is the runner's, none is signalled")
|
|
353
|
+
return "gone", f"pid {pid} is not listed"
|
|
354
|
+
differs = [name for name, want in (("start", start), ("pgid", pgid)) if row[name] != want]
|
|
355
|
+
if not differs and pid != pgid:
|
|
356
|
+
differs = ["group leader"]
|
|
357
|
+
if differs:
|
|
358
|
+
return "identity_mismatch", f"pid {pid} is listed with another {', '.join(differs)} than the runner recorded"
|
|
359
|
+
members, rounds, frozen = {}, 0, False
|
|
360
|
+
deadline = time.monotonic() + freeze_wait_s
|
|
361
|
+
while True: # the freeze: a member joins only from a listing that shows the leader as recorded
|
|
362
|
+
rounds += 1
|
|
363
|
+
if not same(rows, pid, start) or rows[pid]["pgid"] != pgid:
|
|
364
|
+
break
|
|
365
|
+
new = {p: r for p, r in in_group(rows).items() if p not in members}
|
|
366
|
+
running = [p for p, r in members.items() if same(rows, p, r["start"]) and "T" not in rows[p]["stat"]
|
|
367
|
+
and "Z" not in rows[p]["stat"]]
|
|
368
|
+
if not new and not running and not rows.unreadable: # an unreadable line may hide a member still running
|
|
369
|
+
frozen = True
|
|
370
|
+
break
|
|
371
|
+
if time.monotonic() > deadline:
|
|
372
|
+
break
|
|
373
|
+
members.update(new)
|
|
374
|
+
_signal(rows, {**new, **{p: members[p] for p in running}}, signal.SIGSTOP)
|
|
375
|
+
time.sleep(0.005)
|
|
376
|
+
try:
|
|
377
|
+
rows = ps_table()
|
|
378
|
+
except ListingFailed:
|
|
379
|
+
break
|
|
380
|
+
try:
|
|
381
|
+
rows = ps_table()
|
|
382
|
+
except ListingFailed as exc:
|
|
383
|
+
return "unverified", (f"the kill listing failed ({exc}): pids {sorted(members)} of group {pgid} were stopped "
|
|
384
|
+
f"and none was killed; they stay stopped until the owner checks each pid against the run's "
|
|
385
|
+
f"host and ends it")
|
|
386
|
+
_signal(rows, members, signal.SIGKILL)
|
|
387
|
+
deadline, left, incomplete = time.monotonic() + settle_s, None, 0
|
|
388
|
+
while time.monotonic() < deadline:
|
|
389
|
+
time.sleep(0.05)
|
|
390
|
+
try:
|
|
391
|
+
after = ps_table()
|
|
392
|
+
except ListingFailed:
|
|
393
|
+
continue
|
|
394
|
+
if after.unreadable: # it may hide a process the group still holds: it verifies nothing
|
|
395
|
+
incomplete += 1
|
|
396
|
+
continue
|
|
397
|
+
left = sorted({p for p, r in members.items() if same(after, p, r["start"]) and "Z" not in after[p]["stat"]}
|
|
398
|
+
| set(in_group(after)))
|
|
399
|
+
if not left:
|
|
400
|
+
break
|
|
401
|
+
if left is None:
|
|
402
|
+
return "unverified", (f"no complete listing verified the kill of pids {sorted(members)} of group {pgid}"
|
|
403
|
+
+ (f" ({incomplete} had unreadable lines)" if incomplete else ""))
|
|
404
|
+
if left:
|
|
405
|
+
return "survivors", f"pids {left} of group {pgid} outlived the kill"
|
|
406
|
+
return "stopped", (f"group {pgid}: {len(members)} processes, frozen in {rounds} listings" if frozen else
|
|
407
|
+
f"group {pgid}: {len(members)} processes, the freeze not shown stable in {rounds} listings")
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def problem_codes(source, function=CONTRACT["predicate"], sink="problems"):
|
|
411
|
+
"""The codes `function` can report: the leading word of every f-string it appends to `sink`
|
|
412
|
+
(the implemented branch set, read from code; monitor.py reads its boundary with it too)."""
|
|
413
|
+
fn = next(n for n in ast.parse(source).body if isinstance(n, ast.FunctionDef) and n.name == function)
|
|
414
|
+
codes = set()
|
|
415
|
+
for node in ast.walk(fn):
|
|
416
|
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "append" \
|
|
417
|
+
and isinstance(node.func.value, ast.Name) and node.func.value.id == sink and node.args:
|
|
418
|
+
head = node.args[0].values[0] if isinstance(node.args[0], ast.JoinedStr) and node.args[0].values else node.args[0]
|
|
419
|
+
if isinstance(head, ast.Constant) and isinstance(head.value, str) and head.value.split():
|
|
420
|
+
codes.add(head.value.split()[0])
|
|
421
|
+
return codes
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
# The inline programs this module's self-test runs, as module-level constants: an inline `python -c`
|
|
425
|
+
# program is admitted by DECLARATION (`runlib/dispatch.py` `INLINE_PROGRAMS`, which pins each one's
|
|
426
|
+
# sha256), and a local's text is only visible where it is built, so a local cannot be declared or
|
|
427
|
+
# pinned (r3 S3). These are test fixtures; nothing in this module's own behaviour reads them.
|
|
428
|
+
#
|
|
429
|
+
# A tree of the self-test's own, in its own session: a foreground child, and an orphan whose parent
|
|
430
|
+
# exits at once, so it hangs off init but keeps the tree's process group — only the group sweep can
|
|
431
|
+
# find it, as a tool shell's background job after the shell is gone.
|
|
432
|
+
TREE = ("import subprocess, sys, time\n"
|
|
433
|
+
"kid = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(300)'])\n"
|
|
434
|
+
"subprocess.Popen([sys.executable, '-c', 'import os, time\\nif os.fork() == 0:\\n time.sleep(300)\\nos._exit(0)']).wait()\n"
|
|
435
|
+
"print(kid.pid, flush=True)\n"
|
|
436
|
+
"time.sleep(300)\n")
|
|
437
|
+
TREE_AWAY = ("import subprocess, sys, time\n"
|
|
438
|
+
"subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(300)'])\n"
|
|
439
|
+
"subprocess.Popen([sys.executable, '-c', 'import os, time\\nif os.fork() == 0:\\n time.sleep(300)\\nos._exit(0)']).wait()\n"
|
|
440
|
+
"away = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(300)'], start_new_session=True)\n"
|
|
441
|
+
"print(away.pid, flush=True)\n"
|
|
442
|
+
"time.sleep(300)\n")
|
|
443
|
+
TREE_EXITS = ("import subprocess, sys\n"
|
|
444
|
+
"subprocess.Popen([sys.executable, '-c', 'import os, time\\nif os.fork() == 0:\\n time.sleep(300)\\nos._exit(0)']).wait()\n"
|
|
445
|
+
"print('ready', flush=True)\n")
|
|
446
|
+
# One child that outlives the stop and nothing else: the outsider and the stranger of the identity
|
|
447
|
+
# controls.
|
|
448
|
+
SLEEPS_LONG = "import time; time.sleep(300)\n"
|
|
449
|
+
# A root that forks a member BETWEEN the listing that found it and its stop signal. The four values
|
|
450
|
+
# it needs arrive as its own argv; its text is fixed.
|
|
451
|
+
FORKING_ROOT = ("import subprocess, sys, time\n"
|
|
452
|
+
"FORKER = 'import os, signal, sys, time\\ndef fork(*_):\\n pid = os.fork()\\n if pid == 0:\\n"
|
|
453
|
+
" time.sleep(300)\\n os._exit(0)\\n open(sys.argv[1], \\'w\\').write(str(pid))\\n"
|
|
454
|
+
"signal.signal(signal.SIGUSR1, fork)\\nwhile True:\\n time.sleep(1)\\n'\n"
|
|
455
|
+
"sys.stdin.readline()\n"
|
|
456
|
+
"f = subprocess.Popen([sys.executable, '-c', FORKER, sys.argv[1]])\n"
|
|
457
|
+
"print(f.pid, flush=True)\n"
|
|
458
|
+
"time.sleep(300)\n")
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def self_test():
|
|
462
|
+
# Imported HERE rather than at module scope: this file is the stop-at-a-cap machinery and
|
|
463
|
+
# production loads it with the standard library alone, which a control in `runlib/inventory.py`'s
|
|
464
|
+
# suite asserts. The suite is the only reader of the collected-failure boundary, so the import
|
|
465
|
+
# lives on the suite's path — and so does the path entry it needs: run as a FILE, this module's
|
|
466
|
+
# own directory is `sys.path[0]` and the package above it is not importable.
|
|
467
|
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
|
|
468
|
+
from runlib import entry
|
|
469
|
+
# Set where this suite begins publishing its report. Past that point a control is not in the
|
|
470
|
+
# number the summary published, and the summary has already said OK — which is a conclusion
|
|
471
|
+
# printed before the judging. The helpers below refuse past it rather than trusting placement.
|
|
472
|
+
reporting = []
|
|
473
|
+
failures, ran, spawned = [], [], []
|
|
474
|
+
entry.SELF_TEST_COLLECTED.append(("stop --self-test", failures))
|
|
475
|
+
|
|
476
|
+
def launch(away=False):
|
|
477
|
+
"""The tree; with `away`, also a child in a session of its own, whose pid is returned in place of the kid's."""
|
|
478
|
+
if away:
|
|
479
|
+
proc = subprocess.Popen([sys.executable, "-c", TREE_AWAY], stdout=subprocess.PIPE, text=True, start_new_session=True)
|
|
480
|
+
else:
|
|
481
|
+
proc = subprocess.Popen([sys.executable, "-c", TREE], stdout=subprocess.PIPE, text=True, start_new_session=True)
|
|
482
|
+
spawned.append(proc)
|
|
483
|
+
kid = int(proc.stdout.readline())
|
|
484
|
+
time.sleep(0.2)
|
|
485
|
+
sampler = TreeSampler(proc.pid, interval=0.05)
|
|
486
|
+
sampler.start()
|
|
487
|
+
time.sleep(0.15)
|
|
488
|
+
return proc, kid, sampler
|
|
489
|
+
|
|
490
|
+
def group(root):
|
|
491
|
+
"""The processes of the self-test's own session `root`: its pid is the group id it created."""
|
|
492
|
+
return {pid: row for pid, row in ps_table().items() if row["pgid"] == root}
|
|
493
|
+
|
|
494
|
+
def cleanup(members):
|
|
495
|
+
_signal(ps_table(), members, signal.SIGKILL)
|
|
496
|
+
|
|
497
|
+
def stop_and_reap(proc, sampler, **kwargs):
|
|
498
|
+
"""The stop, then the reap its caller makes once every stop is done (as dispatch does)."""
|
|
499
|
+
record = stop_tree(proc, sampler, **kwargs)
|
|
500
|
+
proc.poll()
|
|
501
|
+
return record
|
|
502
|
+
|
|
503
|
+
def control(name, condition, detail):
|
|
504
|
+
if reporting:
|
|
505
|
+
raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}: this suite has begun publishing its "
|
|
506
|
+
f"report, so `control` is not in the count it published")
|
|
507
|
+
# A boolean-style helper given a problem LIST passed on whatever its needle said, because a
|
|
508
|
+
# non-empty list is truthy: three controls in this package read correctly and asked nothing
|
|
509
|
+
# until S8a found them. The signature is enforced here rather than remembered.
|
|
510
|
+
if not isinstance(condition, bool):
|
|
511
|
+
raise TypeError(f"CONTROL_CONDITION_NOT_BOOL {name}: this file's `control` judges a "
|
|
512
|
+
f"boolean condition and was given {type(condition).__name__}")
|
|
513
|
+
ran.append(name)
|
|
514
|
+
if not condition:
|
|
515
|
+
failures.append(f"{name}: {detail}")
|
|
516
|
+
|
|
517
|
+
def type_refusal(call):
|
|
518
|
+
"""The message a self-test helper raises when it is given the wrong KIND of argument. The
|
|
519
|
+
control below catches it here, so asking the guard does not fail the suite."""
|
|
520
|
+
try:
|
|
521
|
+
call()
|
|
522
|
+
except TypeError as exc:
|
|
523
|
+
return str(exc)
|
|
524
|
+
return ""
|
|
525
|
+
|
|
526
|
+
control("a boolean-style control given a problem list is refused by name",
|
|
527
|
+
"CONTROL_CONDITION_NOT_BOOL" in type_refusal(
|
|
528
|
+
lambda: control("a planted non-boolean", ["a problem"], "")),
|
|
529
|
+
"the guard admitted a non-boolean condition, so a control in the other file's style would pass on a truthy list")
|
|
530
|
+
|
|
531
|
+
# the listing carries fixed fields only: no process can shape a row through its command
|
|
532
|
+
control("listing-rows-carry-fixed-fields-only", all(set(row) == {"pid", "ppid", "pgid", "stat", "start"}
|
|
533
|
+
for row in ps_table().values()), "a row carries more than its fixed fields")
|
|
534
|
+
|
|
535
|
+
# positive control first: freeze, verify, kill, verify — nothing of the tree survives
|
|
536
|
+
proc, kid, sampler = launch()
|
|
537
|
+
orphans = [pid for pid, row in group(proc.pid).items() if row["ppid"] == 1]
|
|
538
|
+
outsider = subprocess.Popen([sys.executable, "-c", SLEEPS_LONG], start_new_session=True)
|
|
539
|
+
spawned.append(outsider)
|
|
540
|
+
outsider_start = ps_table()[outsider.pid]["start"]
|
|
541
|
+
record = stop_and_reap(proc, sampler)
|
|
542
|
+
tree_pids = {m["pid"] for m in record["tree"]}
|
|
543
|
+
control("stop-kills-the-whole-tree", not record["problems"] and not record["survivors"] and not group(proc.pid),
|
|
544
|
+
f"{record['problems']}, left {sorted(group(proc.pid))}")
|
|
545
|
+
control("tree-holds-root-and-child", {proc.pid, kid} <= tree_pids, f"tree {sorted(tree_pids)}")
|
|
546
|
+
control("orphan-found-only-by-the-group-sweep", orphans and set(orphans) <= set(record["swept"]),
|
|
547
|
+
f"orphans {orphans}, swept {record['swept']}")
|
|
548
|
+
control("freeze-verified-before-the-kill",
|
|
549
|
+
record["freeze_at"] is not None and record["decided_at"] <= record["freeze_at"] <= record["kill_at"],
|
|
550
|
+
f"decided {record['decided_at']} freeze {record['freeze_at']} kill {record['kill_at']}")
|
|
551
|
+
control("process-outside-the-tree-untouched", same(ps_table(), outsider.pid, outsider_start), "the outsider was signalled")
|
|
552
|
+
cleanup({outsider.pid: {"start": outsider_start}})
|
|
553
|
+
|
|
554
|
+
# the listing does not depend on the caller's locale: under ko_KR `lstart` is seven words, which read every
|
|
555
|
+
# row as unreadable and refused the listing for omitting this process. The presence term: the planted
|
|
556
|
+
# locale really prints seven words when ps is asked directly.
|
|
557
|
+
seven = subprocess.run(["/bin/ps", "-p", str(os.getpid()), "-o", "lstart="], capture_output=True, text=True,
|
|
558
|
+
env={**os.environ, "LC_ALL": "ko_KR.UTF-8"}).stdout.split()
|
|
559
|
+
saved_lc_all = os.environ.get("LC_ALL")
|
|
560
|
+
os.environ["LC_ALL"] = "ko_KR.UTF-8"
|
|
561
|
+
try:
|
|
562
|
+
localized = ps_table()
|
|
563
|
+
read = (os.getpid() in localized, localized.unreadable)
|
|
564
|
+
except ListingFailed as exc:
|
|
565
|
+
read = (False, str(exc))
|
|
566
|
+
finally:
|
|
567
|
+
if saved_lc_all is None:
|
|
568
|
+
os.environ.pop("LC_ALL", None)
|
|
569
|
+
else:
|
|
570
|
+
os.environ["LC_ALL"] = saved_lc_all
|
|
571
|
+
control("the-listing-reads-the-same-under-a-seven-word-lstart-locale", len(seven) == 7 and read == (True, 0),
|
|
572
|
+
f"ps printed {len(seven)} words under ko_KR; the listing read {read}")
|
|
573
|
+
|
|
574
|
+
# a wall clock that steps between the decision and the kill leaves the freeze unverified, by name, while
|
|
575
|
+
# the stop itself completes; the record keeps the monotonic instant beside each stamp
|
|
576
|
+
proc, kid, sampler = launch()
|
|
577
|
+
calls = []
|
|
578
|
+
|
|
579
|
+
def stepping():
|
|
580
|
+
calls.append(1)
|
|
581
|
+
return time.time() - (3600.0 if len(calls) > 1 else 0.0)
|
|
582
|
+
record = stop_and_reap(proc, sampler, clock=stepping)
|
|
583
|
+
stepped = [p for p in record["problems"] if p.startswith("STOP_FREEZE_UNVERIFIED the wall clock moved -3600.")]
|
|
584
|
+
control("a-wall-clock-step-across-the-stop-leaves-the-freeze-unverified-by-name",
|
|
585
|
+
len(stepped) == 1 and record["freeze_at"] is None and not record["survivors"] and not group(proc.pid)
|
|
586
|
+
and set(record["monotonic"]) == {"decided_at", "freeze_at", "kill_at"},
|
|
587
|
+
f"{record['problems']}, freeze {record['freeze_at']}, monotonic {record.get('monotonic')}")
|
|
588
|
+
|
|
589
|
+
# negative control: killing the root alone leaves the rest of the tree alive (the probe's rootonly)
|
|
590
|
+
proc, kid, sampler = launch()
|
|
591
|
+
sampler.halt.set()
|
|
592
|
+
members = {**dict(sampler.known), **group(proc.pid)}
|
|
593
|
+
os.kill(proc.pid, signal.SIGKILL)
|
|
594
|
+
proc.wait(timeout=10)
|
|
595
|
+
time.sleep(0.3)
|
|
596
|
+
rows = ps_table()
|
|
597
|
+
alive = sorted(pid for pid, row in members.items() if same(rows, pid, row["start"]))
|
|
598
|
+
control("root-only-kill-leaves-survivors", kid in alive and len(alive) >= 2, f"root-only kill left {alive}")
|
|
599
|
+
cleanup(members)
|
|
600
|
+
|
|
601
|
+
# identity: a pid recorded with a start time that is not its own is never signalled, nor counted
|
|
602
|
+
proc, kid, sampler = launch()
|
|
603
|
+
stranger = subprocess.Popen([sys.executable, "-c", SLEEPS_LONG], start_new_session=True)
|
|
604
|
+
spawned.append(stranger)
|
|
605
|
+
stranger_start = ps_table()[stranger.pid]["start"]
|
|
606
|
+
sampler.known[stranger.pid] = {**ps_table()[stranger.pid], "start": "Mon Jan 1 00:00:00 1990"}
|
|
607
|
+
record = stop_and_reap(proc, sampler)
|
|
608
|
+
control("a-recycled-pid-is-never-signalled", same(ps_table(), stranger.pid, stranger_start)
|
|
609
|
+
and "T" not in ps_table()[stranger.pid]["stat"], "a pid recorded with another start time was signalled")
|
|
610
|
+
control("survivors-are-counted-by-identity", not record["survivors"], f"{record['survivors']}")
|
|
611
|
+
cleanup({stranger.pid: {"start": stranger_start}})
|
|
612
|
+
|
|
613
|
+
# each verification fails by name when it cannot hold: a root that keeps running after its
|
|
614
|
+
# stop signal (here: continued at once) is not frozen; a member the kill misses survives
|
|
615
|
+
original_kill = os.kill
|
|
616
|
+
proc, kid, sampler = launch()
|
|
617
|
+
os.kill = lambda pid, sig: original_kill(pid, signal.SIGCONT if sig == signal.SIGSTOP and pid == proc.pid else sig)
|
|
618
|
+
try:
|
|
619
|
+
record = stop_and_reap(proc, sampler, freeze_wait_s=0.2)
|
|
620
|
+
finally:
|
|
621
|
+
os.kill = original_kill
|
|
622
|
+
control("unverified-freeze-is-named", record["freeze_at"] is None
|
|
623
|
+
and any(p.startswith(f"STOP_FREEZE_UNVERIFIED pids [{proc.pid}") for p in record["problems"]), f"{record['problems']}")
|
|
624
|
+
cleanup({m["pid"]: m for m in record["tree"]})
|
|
625
|
+
proc, kid, sampler = launch()
|
|
626
|
+
os.kill = lambda pid, sig: None if sig == signal.SIGKILL and pid == kid else original_kill(pid, sig)
|
|
627
|
+
try:
|
|
628
|
+
record = stop_and_reap(proc, sampler, settle_s=0.1)
|
|
629
|
+
finally:
|
|
630
|
+
os.kill = original_kill
|
|
631
|
+
control("survivor-is-named", any(p.startswith(f"STOP_SURVIVORS pids [{kid}]") for p in record["problems"]), f"{record['problems']}")
|
|
632
|
+
cleanup({m["pid"]: m for m in record["tree"]})
|
|
633
|
+
|
|
634
|
+
# a member forks between the listing that found it and its stop signal: the next round's
|
|
635
|
+
# listing finds the new child, so the freeze covers it and the kill reaches it
|
|
636
|
+
import tempfile
|
|
637
|
+
with tempfile.TemporaryDirectory() as td:
|
|
638
|
+
told = pathlib.Path(td) / "forked"
|
|
639
|
+
proc = subprocess.Popen([sys.executable, "-c", FORKING_ROOT, str(told)], stdin=subprocess.PIPE,
|
|
640
|
+
stdout=subprocess.PIPE, text=True, start_new_session=True)
|
|
641
|
+
spawned.append(proc)
|
|
642
|
+
sampler = TreeSampler(proc.pid) # it knows the root only: the forker starts after it sampled
|
|
643
|
+
proc.stdin.write("go\n")
|
|
644
|
+
proc.stdin.flush()
|
|
645
|
+
forking = int(proc.stdout.readline())
|
|
646
|
+
time.sleep(0.3)
|
|
647
|
+
child = {}
|
|
648
|
+
|
|
649
|
+
def scanned(rows, new):
|
|
650
|
+
if forking in new and not child:
|
|
651
|
+
os.kill(forking, signal.SIGUSR1)
|
|
652
|
+
for _ in range(400):
|
|
653
|
+
if told.is_file() and told.read_text():
|
|
654
|
+
pid = int(told.read_text())
|
|
655
|
+
listed = ps_table().get(pid)
|
|
656
|
+
if listed:
|
|
657
|
+
child.update(pid=pid, start=listed["start"])
|
|
658
|
+
return
|
|
659
|
+
time.sleep(0.005)
|
|
660
|
+
record = stop_and_reap(proc, sampler, _scanned=scanned)
|
|
661
|
+
control("a-child-forked-before-its-parent-stopped-is-frozen-and-killed",
|
|
662
|
+
child and child["pid"] in {m["pid"] for m in record["tree"]} and not same(ps_table(), child["pid"], child["start"])
|
|
663
|
+
and record["freeze_at"] is not None and not record["problems"],
|
|
664
|
+
f"child {child}, tree {[m['pid'] for m in record['tree']]}, problems {record['problems']}")
|
|
665
|
+
if child:
|
|
666
|
+
cleanup({child["pid"]: child})
|
|
667
|
+
cleanup({m["pid"]: m for m in record["tree"]})
|
|
668
|
+
|
|
669
|
+
# a listing that is no evidence verifies nothing (the positive counterpart is the stop above,
|
|
670
|
+
# over the real ps, whose tree holds a child with a newline in its command): a ps that does not
|
|
671
|
+
# run, one that exits nonzero, one that prints nothing — each with the tree alive, each a named
|
|
672
|
+
# unverified freeze and kill and an unverified boundary; no member is signalled on its account,
|
|
673
|
+
# yet the tree's process groups are killed whole, the orphan in the root's group among them.
|
|
674
|
+
# A line that cannot be read (a command's second line, were one printed) is counted, not
|
|
675
|
+
# fatal: the readable rows still stop and kill the tree, and both verifications are unverified.
|
|
676
|
+
import shutil
|
|
677
|
+
import tempfile
|
|
678
|
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
679
|
+
from runlib import monitor
|
|
680
|
+
fakes = pathlib.Path(tempfile.mkdtemp(prefix="stop-ps-"))
|
|
681
|
+
for name, script in (("does-not-run", None), ("exits-nonzero", '/bin/ps "$@"\nexit 1'), ("prints-nothing", "exit 0"),
|
|
682
|
+
("prints-an-unreadable-line", '/bin/ps "$@"\necho "a command\'s second line"')):
|
|
683
|
+
fake = fakes / name
|
|
684
|
+
if script is not None: # a ps that does not run is one that is not there
|
|
685
|
+
fake.write_text("#!/bin/sh\n" + script + "\n")
|
|
686
|
+
fake.chmod(0o755)
|
|
687
|
+
proc, away, sampler = launch(away=True)
|
|
688
|
+
members = group(proc.pid)
|
|
689
|
+
orphans = [pid for pid, row in members.items() if row["ppid"] == 1]
|
|
690
|
+
away_row = ps_table()[away]
|
|
691
|
+
groups_killed, killpg = [], os.killpg
|
|
692
|
+
os.killpg = lambda pgid, sig: (groups_killed.append(pgid), killpg(pgid, sig))[1]
|
|
693
|
+
globals()["PS"] = str(fake)
|
|
694
|
+
try:
|
|
695
|
+
record = stop_and_reap(proc, sampler, settle_s=0.05)
|
|
696
|
+
finally:
|
|
697
|
+
globals()["PS"] = "/bin/ps"
|
|
698
|
+
os.killpg = killpg
|
|
699
|
+
problems, uncertain = monitor.boundary(monitor.Ledger(), record["freeze_at"], record["kill_at"])
|
|
700
|
+
rows = ps_table()
|
|
701
|
+
left = sorted(pid for pid, row in members.items() if same(rows, pid, row["start"]))
|
|
702
|
+
away_alive = same(rows, away, away_row["start"])
|
|
703
|
+
failed = name != "prints-an-unreadable-line"
|
|
704
|
+
how = "failed" if failed else "had"
|
|
705
|
+
control(f"listing-that-{name}-verifies-no-freeze-and-kills-the-root-group", record["freeze_at"] is None
|
|
706
|
+
and any(p.startswith(f"STOP_FREEZE_UNVERIFIED the process listing {how}") for p in record["problems"])
|
|
707
|
+
and any(p.startswith(f"STOP_SURVIVORS the process listing {how}") for p in record["problems"])
|
|
708
|
+
and orphans and not left
|
|
709
|
+
and monitor.boundary_verdict(record["problems"] + problems, uncertain) == "STOP_BOUNDARY_UNVERIFIED",
|
|
710
|
+
f"left {left} of {sorted(members)}, groups killed {groups_killed}, {record}")
|
|
711
|
+
control(f"listing-that-{name}-passes-no-group-but-the-root-s-to-killpg", groups_killed == [proc.pid],
|
|
712
|
+
f"groups killed {groups_killed}, root {proc.pid}, the away member's group {away_row['pgid']}")
|
|
713
|
+
if failed: # unlisted, the member in a session of its own is not signalled, and is named
|
|
714
|
+
control(f"listing-that-{name}-leaves-the-member-outside-the-root-group-unsignalled-and-named",
|
|
715
|
+
away_row["pgid"] != proc.pid and away in sampler.known and away_alive and away in record["survivors"],
|
|
716
|
+
f"away {away} alive {away_alive}, survivors {record['survivors']}")
|
|
717
|
+
cleanup({**members, away: away_row})
|
|
718
|
+
proc.wait()
|
|
719
|
+
|
|
720
|
+
# the runner's group id is its own only while the runner is unreaped. A root that exited and is
|
|
721
|
+
# not yet reaped, its orphan holding the group, a listing that fails: the group is killed by
|
|
722
|
+
# that id (positive). The same root reaped before the stop: no group is signalled or swept by
|
|
723
|
+
# its id, the orphan is untouched and named nowhere, and the stop is unverified by name — with
|
|
724
|
+
# the listing failed and with it sound.
|
|
725
|
+
def launch_exiting():
|
|
726
|
+
proc = subprocess.Popen([sys.executable, "-c", TREE_EXITS], stdout=subprocess.PIPE, text=True, start_new_session=True)
|
|
727
|
+
spawned.append(proc)
|
|
728
|
+
proc.stdout.readline()
|
|
729
|
+
for _ in range(500):
|
|
730
|
+
if exited(proc):
|
|
731
|
+
break
|
|
732
|
+
time.sleep(0.01)
|
|
733
|
+
return proc, TreeSampler(proc.pid)
|
|
734
|
+
absent = fakes / "absent"
|
|
735
|
+
for case, reap_first, listing in (("unreaped-root-with-a-failed-listing", False, str(absent)),
|
|
736
|
+
("reaped-root-with-a-failed-listing", True, str(absent)),
|
|
737
|
+
("reaped-root-with-a-sound-listing", True, "/bin/ps")):
|
|
738
|
+
proc, sampler = launch_exiting()
|
|
739
|
+
orphans = {pid: row for pid, row in group(proc.pid).items() if pid != proc.pid}
|
|
740
|
+
if reap_first:
|
|
741
|
+
proc.wait()
|
|
742
|
+
groups_killed, killpg = [], os.killpg
|
|
743
|
+
os.killpg = lambda pgid, sig: (groups_killed.append(pgid), killpg(pgid, sig))[1]
|
|
744
|
+
globals()["PS"] = listing
|
|
745
|
+
try:
|
|
746
|
+
record = stop_and_reap(proc, sampler, settle_s=0.05)
|
|
747
|
+
finally:
|
|
748
|
+
globals()["PS"] = "/bin/ps"
|
|
749
|
+
os.killpg = killpg
|
|
750
|
+
rows = ps_table()
|
|
751
|
+
left = sorted(pid for pid, row in orphans.items() if same(rows, pid, row["start"]))
|
|
752
|
+
reaped_named = any(p.startswith(f"STOP_FREEZE_UNVERIFIED the runner {proc.pid} was reaped before the stop")
|
|
753
|
+
for p in record["problems"])
|
|
754
|
+
if reap_first:
|
|
755
|
+
control(f"{case}-signals-and-sweeps-no-group-by-its-id", orphans and groups_killed == [] and left == sorted(orphans)
|
|
756
|
+
and not set(orphans) & set(record["swept"]) and reaped_named and record["freeze_at"] is None,
|
|
757
|
+
f"groups killed {groups_killed}, orphans {sorted(orphans)} left {left}, {record}")
|
|
758
|
+
else:
|
|
759
|
+
control(f"{case}-kills-its-group", orphans and groups_killed == [proc.pid] and not left and not reaped_named
|
|
760
|
+
and record["freeze_at"] is None, f"groups killed {groups_killed}, orphans {sorted(orphans)} left {left}, {record}")
|
|
761
|
+
cleanup(orphans)
|
|
762
|
+
shutil.rmtree(fakes, ignore_errors=True) # the fake ps scripts: the last listing that names them is above
|
|
763
|
+
|
|
764
|
+
# the freeze and kill listings fail and the verification listing succeeds: a sampled member in a
|
|
765
|
+
# group of its own, never reached and never signalled, is alive and named among the survivors
|
|
766
|
+
proc, away, sampler = launch(away=True)
|
|
767
|
+
away_row = ps_table()[away]
|
|
768
|
+
members = group(proc.pid)
|
|
769
|
+
sampler.halt.set()
|
|
770
|
+
sampler.join()
|
|
771
|
+
listed, calls = ps_table, []
|
|
772
|
+
|
|
773
|
+
def twice():
|
|
774
|
+
calls.append(True)
|
|
775
|
+
if len(calls) <= 2:
|
|
776
|
+
raise ListingFailed("planted: a stop-time listing")
|
|
777
|
+
return listed()
|
|
778
|
+
globals()["ps_table"] = twice
|
|
779
|
+
try:
|
|
780
|
+
record = stop_and_reap(proc, sampler, settle_s=0.05)
|
|
781
|
+
finally:
|
|
782
|
+
globals()["ps_table"] = listed
|
|
783
|
+
control("sampled-member-outside-the-root-group-is-named-when-only-verification-lists", away in sampler.known
|
|
784
|
+
and away in record["survivors"] and same(ps_table(), away, away_row["start"])
|
|
785
|
+
and any(p.startswith("STOP_SURVIVORS pids") and str(away) in p for p in record["problems"]),
|
|
786
|
+
f"away {away}, {record}")
|
|
787
|
+
cleanup({**members, away: away_row})
|
|
788
|
+
|
|
789
|
+
# the first stop-time listing fails and every later one succeeds: the freeze stays unverified by
|
|
790
|
+
# name, yet the recovered listing rebuilds the tree from what was sampled — the group sweep
|
|
791
|
+
# included — so the kill reaches it and is verified, and the runner dies through its handle
|
|
792
|
+
proc, kid, sampler = launch()
|
|
793
|
+
members = group(proc.pid)
|
|
794
|
+
sampler.halt.set()
|
|
795
|
+
sampler.join() # the sampler is done listing: the next listing is the stop's own
|
|
796
|
+
listed = ps_table
|
|
797
|
+
failed = []
|
|
798
|
+
|
|
799
|
+
def once():
|
|
800
|
+
if not failed:
|
|
801
|
+
failed.append(True)
|
|
802
|
+
raise ListingFailed("planted: the first stop-time listing")
|
|
803
|
+
return listed()
|
|
804
|
+
globals()["ps_table"] = once
|
|
805
|
+
began = time.monotonic()
|
|
806
|
+
try:
|
|
807
|
+
record = stop_and_reap(proc, sampler, settle_s=0.05)
|
|
808
|
+
finally:
|
|
809
|
+
globals()["ps_table"] = listed
|
|
810
|
+
rows = ps_table()
|
|
811
|
+
control("first-stop-listing-failing-then-recovering-kills-the-tree-unverified", proc.poll() is not None
|
|
812
|
+
and time.monotonic() - began < 10 and record["freeze_at"] is None
|
|
813
|
+
and any(p.startswith("STOP_FREEZE_UNVERIFIED the process listing failed (planted") for p in record["problems"])
|
|
814
|
+
and not any(p.startswith("STOP_SURVIVORS") for p in record["problems"]) and not record["survivors"]
|
|
815
|
+
and not any(same(rows, pid, row["start"]) for pid, row in members.items()) and kid in {m["pid"] for m in record["tree"]},
|
|
816
|
+
f"runner {proc.poll()}, {record}, left {[pid for pid, row in members.items() if same(rows, pid, row['start'])]}")
|
|
817
|
+
cleanup(members)
|
|
818
|
+
# the runner dies through its handle even where no listed signal reaches it
|
|
819
|
+
proc, kid, sampler = launch()
|
|
820
|
+
members = group(proc.pid)
|
|
821
|
+
signalled = _signal
|
|
822
|
+
globals()["_signal"] = lambda rows, chosen, sig: signalled(rows, {k: v for k, v in chosen.items() if k != proc.pid}, sig)
|
|
823
|
+
try:
|
|
824
|
+
record = stop_and_reap(proc, sampler, settle_s=0.05)
|
|
825
|
+
finally:
|
|
826
|
+
globals()["_signal"] = signalled
|
|
827
|
+
control("runner-dies-through-its-handle-whatever-the-listings-reach", proc.poll() is not None, f"runner {proc.poll()}, {record}")
|
|
828
|
+
cleanup(members)
|
|
829
|
+
|
|
830
|
+
# contract fidelity: the codes stop_tree reports are design §13.2's two verifications, copied
|
|
831
|
+
# here once: the freeze verified before the kill, and the kill verified by pid and start time
|
|
832
|
+
source = pathlib.Path(__file__).read_text(encoding="utf-8")
|
|
833
|
+
design_13_2 = {"STOP_FREEZE_UNVERIFIED", "STOP_SURVIVORS"}
|
|
834
|
+
control("contract-cites-design-13-2", CONTRACT["$comment"].startswith("design §13.2"), CONTRACT["$comment"])
|
|
835
|
+
control("stop-codes-are-design-13-2", problem_codes(source) == design_13_2, f"{problem_codes(source)}")
|
|
836
|
+
planted = source.replace(' if rows is not None and survivors:\n', ' if not members:\n problems.append(f"STOP_PLANTED {rounds}")\n'
|
|
837
|
+
' if rows is not None and survivors:\n', 1)
|
|
838
|
+
dropped = source.replace('problems.append(f"STOP_SURVIVORS', 'record.setdefault("x", []).append(f"STOP_SURVIVORS')
|
|
839
|
+
control("an-added-stop-code-is-detected", planted != source and problem_codes(planted) - design_13_2 == {"STOP_PLANTED"},
|
|
840
|
+
f"{problem_codes(planted)}")
|
|
841
|
+
control("a-removed-stop-code-is-detected", dropped != source and design_13_2 - problem_codes(dropped) == {"STOP_SURVIVORS"},
|
|
842
|
+
f"{problem_codes(dropped)}")
|
|
843
|
+
|
|
844
|
+
for p in spawned:
|
|
845
|
+
try:
|
|
846
|
+
p.wait(timeout=5)
|
|
847
|
+
except subprocess.TimeoutExpired:
|
|
848
|
+
pass
|
|
849
|
+
|
|
850
|
+
# ---- WP-08 commit 5a: what a dead driver left running is stopped only when it is the runner recorded. Every
|
|
851
|
+
# process here is one this suite started, so a reverted check can only ever signal one of them.
|
|
852
|
+
def identity_of(pid):
|
|
853
|
+
row = ps_table().get(pid)
|
|
854
|
+
return {"pid": pid, "start": row["start"] if row else None, "pgid": row["pgid"] if row else None}
|
|
855
|
+
|
|
856
|
+
run_a, kid_a, sampler_a = launch()
|
|
857
|
+
sampler_a.halt.set()
|
|
858
|
+
time.sleep(1.2) # `ps` lists a start time to the second: B's must not read as A's
|
|
859
|
+
run_b, kid_b, sampler_b = launch()
|
|
860
|
+
sampler_b.halt.set()
|
|
861
|
+
run_c, _kid_c, sampler_c = launch()
|
|
862
|
+
sampler_c.halt.set()
|
|
863
|
+
recorded_a, recorded_b, recorded_c = identity_of(run_a.pid), identity_of(run_b.pid), identity_of(run_c.pid)
|
|
864
|
+
kid_row_a = ps_table().get(kid_a, {})
|
|
865
|
+
# what each runner's group holds, listed while all three are this suite's unreaped children, so each group id is
|
|
866
|
+
# provably theirs: cleanup signals these identities only, and never looks a group up again by a pid it has reaped
|
|
867
|
+
owned = {**group(run_a.pid), **group(run_b.pid), **group(run_c.pid)}
|
|
868
|
+
|
|
869
|
+
def release(procs, members):
|
|
870
|
+
"""Kill what this suite started, by the identities recorded while it was unreaped, and reap its runners."""
|
|
871
|
+
cleanup(members)
|
|
872
|
+
for proc in procs:
|
|
873
|
+
proc.wait(timeout=10)
|
|
874
|
+
control("stop_recorded: the fixture runners have distinct start times", recorded_a["start"] != recorded_b["start"],
|
|
875
|
+
f"{recorded_a} {recorded_b}")
|
|
876
|
+
outcome_a = stop_recorded(recorded_a)
|
|
877
|
+
try: # the runner here is this suite's child, so its zombie is reaped here, as init reaps a dead driver's
|
|
878
|
+
run_a.wait(timeout=5)
|
|
879
|
+
except subprocess.TimeoutExpired:
|
|
880
|
+
pass
|
|
881
|
+
time.sleep(0.2)
|
|
882
|
+
listed = ps_table()
|
|
883
|
+
control("stop_recorded: the runner recorded, at its pid with its start time and group, is stopped with its group",
|
|
884
|
+
outcome_a[0] == "stopped" and not same(listed, run_a.pid, recorded_a["start"])
|
|
885
|
+
and not same(listed, kid_a, kid_row_a.get("start")), f"{outcome_a}")
|
|
886
|
+
# a pid and group no system hands out, so that a reverted check here has nothing it could signal: the stopped
|
|
887
|
+
# runner's own pid may already be another program's
|
|
888
|
+
nobody = {"pid": 2 ** 30 + 7, "start": recorded_a["start"], "pgid": 2 ** 30 + 7}
|
|
889
|
+
gone = stop_recorded(nobody)
|
|
890
|
+
control("stop_recorded: a runner no longer listed is named gone", gone[0] == "gone", f"{gone}")
|
|
891
|
+
for label, planted in (("another start time at its pid", {**recorded_b, "start": recorded_a["start"]}),
|
|
892
|
+
("another process group", {**recorded_b, "pgid": recorded_c["pgid"]}),
|
|
893
|
+
# its recorded group is its own pid, so it reads as leading it: only the listed group differs
|
|
894
|
+
("a process listed in another group than the one recorded", {**identity_of(kid_b), "pgid": kid_b}),
|
|
895
|
+
("a member that does not lead its group", {**identity_of(kid_b), "pgid": recorded_b["pgid"]})):
|
|
896
|
+
outcome = stop_recorded(planted)
|
|
897
|
+
listed = ps_table()
|
|
898
|
+
control(f"stop_recorded: {label} is named and nothing is signalled",
|
|
899
|
+
outcome[0] == "identity_mismatch" and same(listed, run_b.pid, recorded_b["start"])
|
|
900
|
+
and same(listed, run_c.pid, recorded_c["start"]), f"{outcome}")
|
|
901
|
+
outcome = stop_recorded({**recorded_b, "start": None})
|
|
902
|
+
control("stop_recorded: an identity recorded in part is unverified and nothing is signalled",
|
|
903
|
+
outcome[0] == "unverified" and same(ps_table(), run_b.pid, recorded_b["start"]), f"{outcome}")
|
|
904
|
+
|
|
905
|
+
# W r1: the group as the listings show it over time, driven deterministically (mocked: no real signal is sent).
|
|
906
|
+
# SIGSTOP stops a listed process and SIGKILL removes it. `arrive` adds a process before the n-th listing (a fork
|
|
907
|
+
# between the first listing and the kill); `after_kill` adds one to the first listing after a SIGKILL was sent (a
|
|
908
|
+
# process the group holds once the kill is done), whatever number that listing has.
|
|
909
|
+
class Table:
|
|
910
|
+
"""A mocked process table. `hidden` maps a pid to how many listings show it only as an unreadable line."""
|
|
911
|
+
|
|
912
|
+
def __init__(self, procs, arrive=None, after_kill=(), hidden=None):
|
|
913
|
+
self.procs, self.arrive, self.after_kill = {r["pid"]: dict(r) for r in procs}, arrive or {}, list(after_kill)
|
|
914
|
+
self.listings, self.sent, self.hidden = 0, [], hidden or {}
|
|
915
|
+
|
|
916
|
+
def list(self):
|
|
917
|
+
self.listings += 1
|
|
918
|
+
for r in self.arrive.get(self.listings, ()):
|
|
919
|
+
self.procs[r["pid"]] = dict(r)
|
|
920
|
+
if self.after_kill and any(sig == signal.SIGKILL for _pid, sig in self.sent):
|
|
921
|
+
self.procs.update((r["pid"], dict(r)) for r in self.after_kill)
|
|
922
|
+
self.after_kill = []
|
|
923
|
+
rows = Listing({p: dict(r) for p, r in self.procs.items() if self.hidden.get(p, 0) < self.listings})
|
|
924
|
+
rows.unreadable = sum(1 for p in self.procs if self.hidden.get(p, 0) >= self.listings)
|
|
925
|
+
rows[os.getpid()] = {"pid": os.getpid(), "ppid": 1, "pgid": os.getpgrp(), "stat": "R", "start": "now"}
|
|
926
|
+
return rows
|
|
927
|
+
|
|
928
|
+
def kill(self, target, sig):
|
|
929
|
+
self.sent.append((target, sig))
|
|
930
|
+
if target not in self.procs:
|
|
931
|
+
raise ProcessLookupError(target)
|
|
932
|
+
if sig == signal.SIGSTOP:
|
|
933
|
+
self.procs[target]["stat"] = "T"
|
|
934
|
+
elif sig == signal.SIGKILL:
|
|
935
|
+
del self.procs[target]
|
|
936
|
+
|
|
937
|
+
def driven(table, recorded):
|
|
938
|
+
real_kill, real_table = os.kill, ps_table
|
|
939
|
+
os.kill, globals()["ps_table"] = table.kill, table.list
|
|
940
|
+
try:
|
|
941
|
+
return stop_recorded(recorded, settle_s=0.2)
|
|
942
|
+
finally:
|
|
943
|
+
os.kill, globals()["ps_table"] = real_kill, real_table
|
|
944
|
+
|
|
945
|
+
lead = 2 ** 30 + 21
|
|
946
|
+
|
|
947
|
+
def proc_row(n, stat="S"):
|
|
948
|
+
return {"pid": lead + n, "ppid": lead if n else 1, "pgid": lead, "stat": stat, "start": f"Mon Jan 1 00:00:0{n} 2001"}
|
|
949
|
+
leader = {"pid": lead, "start": proc_row(0)["start"], "pgid": lead}
|
|
950
|
+
forked = Table([proc_row(0), proc_row(1)], arrive={2: [proc_row(2)]})
|
|
951
|
+
outcome = driven(forked, leader)
|
|
952
|
+
control("W r1: stop_recorded freezes the group and kills a member forked after its first listing",
|
|
953
|
+
outcome[0] == "stopped" and (lead + 2, signal.SIGKILL) in forked.sent and not forked.procs, f"{outcome} {forked.sent}")
|
|
954
|
+
late = Table([proc_row(0), proc_row(1)], after_kill=[proc_row(3)])
|
|
955
|
+
outcome = driven(late, leader)
|
|
956
|
+
control("W r1: stop_recorded verifies the whole group, so a process it holds after the kill is a survivor",
|
|
957
|
+
outcome[0] == "survivors" and str(lead + 3) in outcome[1], f"{outcome} {late.sent}")
|
|
958
|
+
leaderless = Table([proc_row(1), proc_row(2)])
|
|
959
|
+
outcome = driven(leaderless, leader)
|
|
960
|
+
control("W r1: a group still holding processes after its leader is gone is unverified and nothing is signalled",
|
|
961
|
+
outcome[0] == "unverified" and leaderless.sent == [] and str(lead + 1) in outcome[1], f"{outcome} {leaderless.sent}")
|
|
962
|
+
emptied = Table([])
|
|
963
|
+
outcome = driven(emptied, leader)
|
|
964
|
+
control("W r1: a leader gone with its group empty is gone, and nothing is signalled",
|
|
965
|
+
outcome[0] == "gone" and emptied.sent == [], f"{outcome} {emptied.sent}")
|
|
966
|
+
# W r2: a live member shown only as an unreadable line - the listing is incomplete, never evidence of absence
|
|
967
|
+
always = float("inf")
|
|
968
|
+
masked = Table([proc_row(1)], hidden={lead + 1: always})
|
|
969
|
+
outcome = driven(masked, leader)
|
|
970
|
+
control("W r2: a leader unlisted beside an unreadable line is unverified, never gone, and nothing is signalled",
|
|
971
|
+
outcome[0] == "unverified" and masked.sent == [] and masked.listings > 1, f"{outcome} {masked.sent}")
|
|
972
|
+
late_leader = Table([proc_row(0), proc_row(1)], hidden={lead: 1})
|
|
973
|
+
outcome = driven(late_leader, leader)
|
|
974
|
+
control("W r2: a first listing hiding the leader is taken again, and the complete one decides",
|
|
975
|
+
outcome[0] == "stopped" and (lead, signal.SIGKILL) in late_leader.sent
|
|
976
|
+
and (lead + 1, signal.SIGKILL) in late_leader.sent and not late_leader.procs, f"{outcome} {late_leader.sent}")
|
|
977
|
+
unseen = Table([proc_row(0), proc_row(1)], hidden={lead + 1: 2})
|
|
978
|
+
outcome = driven(unseen, leader)
|
|
979
|
+
control("W r2: a member an unreadable line hid from the first listings is frozen and killed once a complete "
|
|
980
|
+
"listing shows it",
|
|
981
|
+
outcome[0] == "stopped" and (lead + 1, signal.SIGSTOP) in unseen.sent
|
|
982
|
+
and (lead + 1, signal.SIGKILL) in unseen.sent and not unseen.procs, f"{outcome} {unseen.sent}")
|
|
983
|
+
never = Table([proc_row(0), proc_row(1)], hidden={lead + 1: always})
|
|
984
|
+
outcome = driven(never, leader)
|
|
985
|
+
control("W r2: a kill no complete listing verifies is unverified, not stopped",
|
|
986
|
+
outcome[0] == "unverified" and "no complete listing verified the kill" in outcome[1]
|
|
987
|
+
and never.procs.get(lead + 1, {}).get("stat") == "S", f"{outcome} {never.sent}")
|
|
988
|
+
# W r1: the reaped runner's pid, recycled as the leader of an unrelated group (mocked: no real signal is sent).
|
|
989
|
+
# Cleanup by the recorded identities signals nothing of it; looking the group up again by the pid would.
|
|
990
|
+
recycled, real_kill, real_table = [], os.kill, ps_table
|
|
991
|
+
stranger_row = {"pid": run_a.pid, "ppid": 1, "pgid": run_a.pid, "stat": "S", "start": "Mon Jan 1 00:00:00 2001"}
|
|
992
|
+
member_row = {"pid": 2 ** 30 + 11, "ppid": run_a.pid, "pgid": run_a.pid, "stat": "S", "start": "Mon Jan 1 00:00:00 2001"}
|
|
993
|
+
|
|
994
|
+
def recycled_table():
|
|
995
|
+
rows = Listing({os.getpid(): {"pid": os.getpid(), "ppid": 1, "pgid": os.getpgrp(), "stat": "R", "start": "now"},
|
|
996
|
+
run_a.pid: dict(stranger_row), member_row["pid"]: dict(member_row)})
|
|
997
|
+
return rows
|
|
998
|
+
os.kill = lambda target, sig: recycled.append((target, sig))
|
|
999
|
+
globals()["ps_table"] = recycled_table
|
|
1000
|
+
try:
|
|
1001
|
+
release([run_a], {pid: row for pid, row in owned.items() if row["pgid"] == recorded_a["pgid"]})
|
|
1002
|
+
finally:
|
|
1003
|
+
os.kill, globals()["ps_table"] = real_kill, real_table
|
|
1004
|
+
control("W r1: cleanup after the reap signals nothing of a group a recycled pid now leads", recycled == [],
|
|
1005
|
+
f"signalled {recycled}")
|
|
1006
|
+
release([run_b, run_c], owned)
|
|
1007
|
+
|
|
1008
|
+
# ---- r4 R1: this runner's own `__main__` boundary, DRIVEN rather than read out of the source.
|
|
1009
|
+
# It was a `try` inside the `if __name__` block that no control could enter.
|
|
1010
|
+
boundary_published = []
|
|
1011
|
+
planted_row = ("a planted suite --self-test", ["a failure an abort must not swallow"])
|
|
1012
|
+
entry.SELF_TEST_COLLECTED.append(planted_row)
|
|
1013
|
+
aborted_with = ""
|
|
1014
|
+
try:
|
|
1015
|
+
main_boundary(run=lambda: (_ for _ in ()).throw(RuntimeError("a planted abort")),
|
|
1016
|
+
publish=boundary_published.append)
|
|
1017
|
+
except RuntimeError as exc:
|
|
1018
|
+
aborted_with = str(exc)
|
|
1019
|
+
finally:
|
|
1020
|
+
entry.SELF_TEST_COLLECTED.remove(planted_row)
|
|
1021
|
+
control("the main boundary publishes what the suite collected before an abort leaves",
|
|
1022
|
+
"a planted suite --self-test [FAIL] a failure an abort must not swallow" in boundary_published
|
|
1023
|
+
and aborted_with == "a planted abort",
|
|
1024
|
+
f"{boundary_published} raised={aborted_with!r}")
|
|
1025
|
+
clean_published = []
|
|
1026
|
+
entry.SELF_TEST_COLLECTED.append(planted_row)
|
|
1027
|
+
try:
|
|
1028
|
+
returned_code = main_boundary(run=lambda: 0, publish=clean_published.append)
|
|
1029
|
+
finally:
|
|
1030
|
+
entry.SELF_TEST_COLLECTED.remove(planted_row)
|
|
1031
|
+
control("and a run that returns normally through it publishes nothing and keeps its code",
|
|
1032
|
+
clean_published == [] and returned_code == 0, f"{clean_published} code={returned_code}")
|
|
1033
|
+
reporting.append("the report begins here")
|
|
1034
|
+
entry.SELF_TEST_COLLECTED.remove(("stop --self-test", failures))
|
|
1035
|
+
for failure in failures:
|
|
1036
|
+
print(f"stop --self-test [FAIL] {failure}")
|
|
1037
|
+
if failures:
|
|
1038
|
+
return 1
|
|
1039
|
+
print(f"stop --self-test: OK ({len(ran)} controls: " + ", ".join(ran) + ")")
|
|
1040
|
+
return 0
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def main_boundary(run=None, publish=print):
|
|
1044
|
+
"""This module's `__main__` boundary, as a FUNCTION so a control can drive it (r4 R1).
|
|
1045
|
+
|
|
1046
|
+
The import stays the suite's path only, as `self_test` explains: this module's production use
|
|
1047
|
+
imports nothing of `runlib` beyond the standard library."""
|
|
1048
|
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
|
|
1049
|
+
from runlib import entry # the suite's path only; see `self_test`
|
|
1050
|
+
try:
|
|
1051
|
+
return (run or self_test)()
|
|
1052
|
+
except BaseException:
|
|
1053
|
+
# What the suite had collected, before the abort leaves with its own non-zero exit.
|
|
1054
|
+
entry.publish_collected(publish)
|
|
1055
|
+
raise
|
|
1056
|
+
|
|
1057
|
+
|
|
1058
|
+
if __name__ == "__main__":
|
|
1059
|
+
if "--self-test" not in sys.argv[1:]:
|
|
1060
|
+
sys.exit("usage: stop.py --self-test")
|
|
1061
|
+
sys.exit(main_boundary())
|