summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--core/replica.zig28
-rw-r--r--test/daemon.py105
2 files changed, 115 insertions, 18 deletions
diff --git a/core/replica.zig b/core/replica.zig
index f4a3284c..9067a12a 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -2815,7 +2815,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
sameBuild(gpa, (dial(gpa, path, session, why, have, null) orelse
// Handed to the session as it upgraded, or cut by its exec with
// its dump on the way: it is there again soon.
- if (std.mem.eql(u8, std.mem.sliceTo(why, 0), upgrading) or cutListed(why, session, have != null)) redial(gpa, path, session, why, have, true, null) else null) orelse return null, why)) orelse return null;
+ if (std.mem.eql(u8, std.mem.sliceTo(why, 0), upgrading) or cutListed(why, session, have != null)) redial(gpa, path, session, why, have, true, null) else null) orelse return null, why, false)) orelse return null;
defer {
if (have) |h| h.store(gpa, j) else gpa.free(j.dump);
j.dump = &.{};
@@ -2892,7 +2892,7 @@ fn ownBoot(gpa: Allocator, j: *Joined, fd: c_int, o: pardes.Options, why: *[600]
pub fn confirmBoot(gpa: Allocator, j: *Joined, r: *Replica, o: pardes.Options, why: *[600]u8) ?*Replica {
const t0 = nowNs();
const digest = j.digest;
- j.* = sameBuild(gpa, joinOn(gpa, j.fd, null, why, null, null, digest) orelse return null, why) orelse return null;
+ j.* = sameBuild(gpa, joinOn(gpa, j.fd, null, why, null, null, digest) orelse return null, why, false) orelse return null;
if (j.dump.len == 0) {
r.id = j.client;
r.view = j.view;
@@ -2909,10 +2909,14 @@ pub fn confirmBoot(gpa: Allocator, j: *Joined, r: *Replica, o: pardes.Options, w
/// `j`, when its session runs this build; else its link let go, and why in
/// `why`: the daemon judged the hello by what the session last said, which
-/// an upgrade under way may not have said yet.
-fn sameBuild(gpa: Allocator, j: Joined, why: []u8) ?Joined {
+/// an upgrade under way may not have said yet. `again`: it was a rejoin for
+/// the view the session kept, which the welcome gave it: kept again for it
+/// (its bye's `again`), for the build at its start path, exec'd, to come
+/// back to (client.zig `execAgain`); closed, it came back in a new view,
+/// its own lost (1 in 4 Upgrades on one CPU, 2026-11-22).
+fn sameBuild(gpa: Allocator, j: Joined, why: []u8, again: bool) ?Joined {
if (j.semantics == wire.semantics) return j;
- bye(j.fd, .{});
+ bye(j.fd, .{ .again = again });
_ = libc.close(j.fd);
var jj = j;
jj.rest.deinit(gpa);
@@ -2923,7 +2927,10 @@ fn sameBuild(gpa: Allocator, j: Joined, why: []u8) ?Joined {
/// The session again, after a divergence or an upgrade: an upgrade's
/// takes the time its exec and load take, and its daemon's, so it is
-/// dialled every 100 ms for 20 s. Null, and why in `why`.
+/// dialled every 100 ms for 20 s. Null, and why in `why`. The session's
+/// own word that it is upgrading (`Peers.refuseAll`, until its exec) is
+/// not a try: it is there, writing its dump for as long as that takes (a
+/// 24 s write let every client go for good, 2026-11-22).
/// `patient`: after an Upgrade's `refused` alone, while the session is
/// away a moment; after a divergence a session that will not answer is
/// gone, and the client says so at once (it froze 20 s, 2026-10-30).
@@ -2931,9 +2938,9 @@ fn sameBuild(gpa: Allocator, j: Joined, why: []u8) ?Joined {
/// none for a first join that met an Upgrade.
fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8, have: ?*Have, patient: bool, view: ?u8) ?Joined {
var tries: u32 = 0;
- while (true) : (tries += 1) {
+ while (true) {
why.* = @splat(0);
- if (dial(gpa, path, session, why, have, view)) |j| return sameBuild(gpa, j, why);
+ if (dial(gpa, path, session, why, have, view)) |j| return sameBuild(gpa, j, why, view != null);
// Another build, or another protocol (the daemon moved with its
// session): no dial again will do.
const words = std.mem.sliceTo(why, 0);
@@ -2944,7 +2951,10 @@ fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8,
// Its daemon lists no such session: it is gone, not away a moment
// (an Upgrade keeps it listed throughout).
if (std.mem.startsWith(u8, words, "no session called ")) return null;
- if (!patient or tries > 200) return null;
+ if (!std.mem.eql(u8, words, upgrading)) {
+ if (!patient or tries > 200) return null;
+ tries += 1;
+ }
const ts: libc.timespec = .{ .sec = 0, .nsec = 100 * std.time.ns_per_ms };
_ = libc.nanosleep(&ts, null);
}
diff --git a/test/daemon.py b/test/daemon.py
index 9c0252e5..d1406ae1 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -1321,8 +1321,12 @@ def far_exec(old, new):
wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
nine = reconnect(sock)
wait_for('the far client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30)
- assert b'PARDES_REPLICA_FAR=1' in open(f'/proc/{c.pid}/environ', 'rb').read().split(b'\0') if procfs else True
wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30)
+ # Its environment read once the new image runs (it entered the
+ # screen): an exec names the new file in /proc/PID/exe before it has
+ # written where the environment is, and a read between gets nothing
+ # (two CPUs: 170 execs of 200 read so).
+ assert b'PARDES_REPLICA_FAR=1' in open(f'/proc/{c.pid}/environ', 'rb').read().split(b'\0') if procfs else True
seen = len(checks(check))
key(b'j')
wait_for('its key stepped after', lambda: agreed(check, seen + 1), timeout=30)
@@ -3271,6 +3275,64 @@ def ppid(pid):
return int(open(f'/proc/{pid}/stat').read().rsplit(')', 1)[1].split()[1])
+def where_waits(pid):
+ """A process's state, a line each thread (its name, state, kernel wait
+ channel and the syscall it is in): alive or not, and blocked where."""
+ if not alive(pid):
+ return f'{pid}: gone\n'
+ rows = [f'{pid}: alive, {b" ".join(cmdline(pid)).decode(errors="replace")[:300]}']
+ try:
+ for tid in sorted(os.listdir(f'/proc/{pid}/task'), key=int):
+ t = f'/proc/{pid}/task/{tid}'
+ row = []
+ for leaf in ('comm', 'wchan', 'syscall'):
+ try:
+ row.append(open(f'{t}/{leaf}').read().strip().split(' ')[0])
+ except OSError:
+ row.append('?')
+ state = open(f'{t}/stat').read().rsplit(')', 1)[1].split()[0]
+ rows.append(f' {tid} {row[0]} {state} wchan {row[1]} syscall {row[2]}')
+ except OSError:
+ pass
+ return '\n'.join(rows + [f' fd {link}' for link in links(pid)]) + '\n'
+
+
+def keep_evidence(label, root, env, binary, sock, pids, clients):
+ """What a failed step leaves for its reader, in a directory the run's
+ cleanup does not remove (.scratch/daemon/kept/<label>-<time>-<pid>):
+ each client's terminal text, check file and stats, and its process
+ (alive, and where each thread waits); the session's screen and /log
+ over 9P (dialled with its timeout: a session that does not answer says
+ so), `pardes --ps`, the crash file, and the session's and daemon's
+ processes. `clients`: (name, Term, Popen, check, stats). Its path."""
+ out = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'kept' / f'{label}-{time.strftime("%Y%m%d-%H%M%S")}-{os.getpid()}'
+ out.mkdir(parents=True, exist_ok=True)
+ for name, term, proc, check, stats in clients:
+ (out / f'{name}.tty').write_bytes(term.text())
+ for f, leaf in ((check, 'check'), (stats, 'stats')):
+ if f.exists():
+ shutil.copyfile(f, out / f'{name}.{leaf}')
+ (out / f'{name}.proc').write_text(f'returncode {proc.poll()}\n' + where_waits(proc.pid))
+ c = dial(sock)
+ for leaf, read in (('screen', lambda: screen_text(c).encode()), ('log', lambda: c.read('/log'))):
+ try:
+ (out / f'session.{leaf}').write_bytes(read() if c else b'its 9P did not answer\n')
+ except (OSError, EOFError) as err:
+ (out / f'session.{leaf}').write_text(f'not read: {err!r}\n')
+ if c:
+ c.socket.close()
+ try:
+ listed = subprocess.run([str(binary), '--ps'], env=env, capture_output=True, timeout=10)
+ (out / 'ps').write_bytes(listed.stdout + listed.stderr)
+ except subprocess.TimeoutExpired:
+ (out / 'ps').write_text('pardes --ps did not answer in 10 s\n')
+ crashes = root / 'config' / 'pardes' / 'crashes'
+ if crashes.exists():
+ shutil.copyfile(crashes, out / 'crashes')
+ (out / 'processes').write_text(''.join(f'{what}: {where_waits(pid)}' for what, pid in pids))
+ return out
+
+
def install(binary, at):
"""As `zig build` and install(1) put a build in place: a new file
renamed over the old, which a process running it keeps, deleted."""
@@ -3425,15 +3487,16 @@ def upgrades(old, new):
# whose clients never come back (the raw replica, the old build's):
# each its client's for 30 s, and the session's views all taken.
# The first join waits as long as its refusal says.
+ first = None
if keeps_views(old):
- said = Replica(root / 'pardes-replica.sock').hello('work', new_build)
+ said = first = Replica(root / 'pardes-replica.sock').hello('work', new_build)
kept = re.search(r'one is kept (\d+) s more', said[1]) if said[0] == 'refused' else None
if kept:
time.sleep(int(kept.group(1)) + .5)
print(f'upgrade: two views kept for clients that never came back; the join waited {kept.group(1)} s for one, as its refusal said')
# The daemon lists the session under its new build.
said = Replica(root / 'pardes-replica.sock').hello('work', new_build)
- assert said == ('welcome', session, 'work'), said
+ assert said == ('welcome', session, 'work'), (said, 'the join before it', first)
said = Replica(root / 'pardes-replica.sock').hello('work', old_build)
assert said[0] == 'refused' and 'another build' in said[1], said
os.kill(sleeper, signal.SIGTERM)
@@ -3457,7 +3520,7 @@ def upgrades(old, new):
# it joins again once the session is back, says so, and agrees.
term4 = Term(24, 90)
again = term4.spawn([str(new), f'--attach={root / "pardes-replica.sock"}:work'],
- dict(env, PARDES_REPLICA_CHECK=str(root / 'e.check')))
+ dict(env, PARDES_REPLICA_CHECK=str(root / 'e.check'), PARDES_REPLICA_STATS=str(root / 'e.stats')))
started.append(again.pid)
wait_for('the client of the build running drawn', lambda: b'\x1b[?1049h' in term4.text() and b'one' in term4.text())
# A second, and each a pane of its own in its own view: the
@@ -3465,7 +3528,7 @@ def upgrades(old, new):
# not a new one (a copy of the session's, without it).
term5 = Term(30, 100)
again5 = term5.spawn([str(new), f'--attach={root / "pardes-replica.sock"}:work'],
- dict(env, PARDES_REPLICA_CHECK=str(root / 'f.check')))
+ dict(env, PARDES_REPLICA_CHECK=str(root / 'f.check'), PARDES_REPLICA_STATS=str(root / 'f.stats')))
started.append(again5.pid)
wait_for('the second client of the build running drawn', lambda: b'\x1b[?1049h' in term5.text() and b'one' in term5.text())
owners = ((term4, root / 'e.check'), (term5, root / 'f.check'))
@@ -3476,11 +3539,23 @@ def upgrades(old, new):
client.write('/exec', b'New\n')
mine.append(wait_for('a pane in the client\'s view', lambda: view_panes(client) - shown).pop())
refusing('1')
+ t0 = time.monotonic()
client.write(f'/pane/{shell}/exec', b'Upgrade\n')
client.socket.close()
client = saying(sock, 'it goes on as')
- for t, _ in owners:
- wait_for('the client joined again', lambda: b'joined again: the session is upgrading' in t.text(), timeout=30)
+ back = time.monotonic() - t0
+ joined = {}
+
+ def rejoined():
+ for t, check in owners:
+ if check not in joined and b'joined again: the session is upgrading' in t.text():
+ joined[check] = time.monotonic() - t0
+ return len(joined) == len(owners)
+ try:
+ wait_for('the clients joined again', rejoined, timeout=30)
+ except TimeoutError:
+ raise TimeoutError(f'the client joined again: not {[c.stem for _, c in owners if c not in joined]} '
+ f'{time.monotonic() - t0:.1f} s after the Upgrade, the session back at {back:.1f} s') from None
assert again.poll() is None and again5.poll() is None
for (t, check), pane, theirs in zip(owners, mine, reversed(mine)):
in_own_view('its own view again', lambda: made_live(t, check), client, pane, theirs)
@@ -3488,8 +3563,8 @@ def upgrades(old, new):
c.send_signal(signal.SIGHUP)
c.wait(timeout=10)
t.close()
- print('upgrade: two replica clients of the build running joined again after the upgrade, said so and agreed, '
- 'each in its own view again, its own pane in it')
+ print(f'upgrade: two replica clients of the build running joined again after the upgrade ({back:.1f} s the session back, '
+ f'the clients {" and ".join(f"{joined[c]:.1f}" for _, c in owners)} s), said so and agreed, each in its own view again, its own pane in it')
assert os.stat(f'/proc/{session}/exe').st_ino == running, 'back on the build that ran'
assert alive(shell_pid) and ppid(shell_pid) == session and stub.poll() is None
assert client.read(f'/pane/{text}/body') == b'one\ntwo\n'
@@ -3556,6 +3631,18 @@ def upgrades(old, new):
left = [p for p in processes(root) if alive(p)]
assert not left, [cmdline(p) for p in left]
print('upgrade: nothing left behind')
+ except (TimeoutError, AssertionError, subprocess.TimeoutExpired) as err:
+ # What each terminal and its process say, and the session's, kept
+ # (keep_evidence): the clients of the build running by their check
+ # files' names.
+ at = locals()
+ terms = [(name, at[t], at[p], root / f'{name}.check', root / f'{name}.stats')
+ for name, t, p in (('first', 'term', 'stub'), ('second', 'term2', 'stub2'), ('stale', 'term3', 'stale'),
+ ('e', 'term4', 'again'), ('f', 'term5', 'again5'))
+ if t in at and hasattr(at.get(p), 'poll')]
+ kept = keep_evidence('upgrade', root, env, binary, root / 'pardes-9p-work.sock',
+ [(w, at[w]) for w in ('session', 'daemon') if isinstance(at.get(w), int)], terms)
+ raise type(err)(f'{err} (kept: {kept})') from None
finally:
for pid in started + processes(root):
try: