From a3d98f0e465ed9634d0534e0a6c71767b2a709b9 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 23 Nov 2026 00:05:38 -0300 Subject: link: a client whose link is up and must take the session's state again (it diverged, fell 2 s behind, or the session cut it off 64 MB behind) comes back OVER THAT LINK, the daemon not asked: its goodbye that says `again` and today's hello for its view in one write (`replica.comeBack`, runtime/client.zig `Loop.run` when `Link.backHere`), its reader letting the stream it leaves go (units, blobs and checks not even copied) and stopping at the session's welcome there, put back at its framer's front for the join's reader (`readLink`'s back mode, `Framer.putBack`), the join read on that framer (`joinOn` takes it; `replica.join`'s `here`); on the session the reader reads on after a `bye` that says `again`, a hello after it is the same client back (`Peer.take`, inputs numbered afresh), and `Peers.joinAgain` dumps for it there with what the old road put on the tape (`awayView`, then the join's `viewFor`: every side's terminals reloaded in that step), what was queued for it let go, the cut over; one writer loop writes a join whenever one is due (`Peer.gen`, `Peer.written`; the `.joined` note carries its gen so a stale one releases nothing), what it was sent a MiB at most a write at a message's end (`writeOut`) so a join due waits for no more of the old stream, a far client's old zstd frame ended before the welcome; a cut keeps the link (its words, then nothing until the hello); a link that ends before the welcome (an Upgrade's or a Restore's words: the session closes it), or one gone, is dialled again as before: the one case left for a redial; and a client refused its own load (`fromDump`) asks ONCE more over the same link with the session's digest a word a field after that dump (wire 31, nothing at 31 installed: a bye's byte 3 = `again` + `parts`, a new ServerTag `parts` 0x0d) and only then gives up, naming the fields that differ in its words and its log; the failing run first: test/daemon.py's new `pair_back` (a no-daemon pair whose client diverges, and one stopped 3 s while the session is edited) on the installed build 79b73e14711e: "the client and the session went (client exit 1)", "'diverged' let this client go", on this tree both join again over their own link, the session alive, the unsaved text there, agreed; `clients`: client D's socket the same across its rejoin, the session counting 6 joins, 1 over a client's own link and 5 handed by the daemon; `far_flood` (20 KB/s, 200 ms): the same link after 3 joins again of 0.56 s each against a dial each time on the installed build (0.99 s each), but agreement 68.6 s after `yes` ended against 22.7 s: the client reads through what the relay holds for it (the relay buffers without bound; ssh bounds it by its window), said in reports/pardes-link-lifecycle.md; `Peer.rejoin` and `hungUp` stay for the one road that still dials after a goodbye saying `again` (a client of another build exec'ing: `sameBuild`), their test rewritten for it; core tests at the replica's surface with real link threads (near and far: back over its own link; a refused load asked once more and loaded; refused twice and named, against a session played by hand; a cut client back over its link, the same peer, connection and view); the soak models the road (`ended`, `Soak.joinDown`, the `here` column); core-test 924/1084 (160 skipped), shell-test 1126/1129 (3 skipped), root.zig's machine_lines for replica.zig 76 -> 90 (the tests' sockets and sleeps; the session's one shutdown of a link it will not dump for again, and a close) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/daemon.py | 140 ++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 135 insertions(+), 5 deletions(-) (limited to 'test/daemon.py') diff --git a/test/daemon.py b/test/daemon.py index fcaae3d7..6cf29411 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -286,6 +286,31 @@ def links(pid): return out +def sockets(pid): + """The sockets process `pid` holds (`socket:[inode]`): a client's link + among them, the same one while it joins again over it.""" + out = set() + for fd in os.listdir(f'/proc/{pid}/fd'): + try: + link = os.readlink(f'/proc/{pid}/fd/{fd}') + except OSError: + continue + if link.startswith('socket:'): + out.add(link) + return out + + +def session_stats(path): + """A session's PARDES_REPLICA_STATS line, its words a dict, and its joins' + count (`joins_us`'s).""" + text = path.read_text() if path.exists() else '' + line = next((l for l in text.splitlines() if l.startswith('session inputs')), '') + w = line.split() + d = {w[i]: w[i + 1] for i in range(1, len(w) - 1, 2)} + joins = next((len(l.split()) - 2 for l in text.splitlines() if l.startswith('session joins_us')), 0) + return d, joins + + def state_fds(pid): """Its fds on the state file, which a session keeps open (Db.zig).""" return sum(1 for path in links(pid) if path.endswith('/pardes.xitdb')) @@ -489,8 +514,10 @@ def clients(binary): started = [] terms = [] try: - sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + # Its joins counted at its end (PARDES_REPLICA_STATS): those over a + # client's own link (`again`) and all of them (`joins_us`). + sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=dict(env, PARDES_REPLICA_STATS=str(root / 'session.stats')), + cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) sock = root / 'pardes-replica.sock' wait_for('the replica socket', sock.exists) @@ -536,6 +563,7 @@ def clients(binary): started.append(d.pid) wait_for('client D\'s first frame', lambda: b'line 3 of the notes' in td.text(), timeout=20) made_live(td, root / 'd.check') + d_links = sockets(d.pid) shown = view_panes(nine) nine.write('/exec', b'New\n') mine = wait_for('a pane in client D\'s view', lambda: view_panes(nine) - shown).pop() @@ -546,6 +574,9 @@ def clients(binary): os.write(ta.master, b'jk') time.sleep(.2) assert d.poll() is None + # Over its own link: the same connection, no hand-over (counted at + # the session's end). + assert sockets(d.pid) == d_links, ('client D joined again over its own link', d_links, sockets(d.pid)) made_live(td, root / 'd.check') assert mine in view_panes(nine), ('client D in its own view again', mine, nine.read('/layout')) seen = len(checks(root / 'd.check')) @@ -598,8 +629,12 @@ def clients(binary): exit_session(nine, pane) sess.wait(timeout=60) nine.socket.close() + said, joins = session_stats(root / 'session.stats') + here = int(said.get('again', '-1')) + assert here >= 1, ('the session joined client D again over its link', said) wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) - print('daemon: replica clients\' session ended, nothing left behind') + print(f'daemon: replica clients\' session ended, nothing left behind; its joins: {joins}, of them over a ' + f'client\'s own link {here}, handed by the daemon {joins - here}') finally: for t in terms: t.close() @@ -948,6 +983,86 @@ def pair_rows(binary): shutil.rmtree(root, ignore_errors=True) +def pair_back(binary): + """A pair with no daemon (PARDES_DAEMON=off, the pair's default-to-be + with none reachable): its client put off the session's state + (PARDES_TEST_DIVERGE), and apart from that stopped 3 s while the + session's file is edited over 9P (SIGSTOP: past replica.behind_max_ms): + each time it joins again over its own link ("joined again" on its + screen, its socket the same), the session lives on with the text typed + in it, unsaved, and the client agrees; its terminal closed, the session + ends with its last link. Before pardes-link-1 its rejoin dialled the + daemon's socket, nothing took it, and the whole session went (the + client exit 1: reports/pardes-pair-12.md, 2b).""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rb-', dir=scratch)) + env = base_env() + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', + SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1', PARDES_DAEMON='off') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30))) + terms = [] + try: + for how in ('diverged', 'behind'): + t = Term(30, 100) + terms.append(t) + check = root / f'{how}.check' + e = dict(env, PARDES_REPLICA_CHECK=str(check), **({'PARDES_TEST_DIVERGE': '3'} if how == 'diverged' else {})) + c = t.spawn([binary, f'--9p={how}', str(notes)], e) + wait_for('the socket', (root / f'pardes-9p-{how}.sock').exists) + nine = Client(root / f'pardes-9p-{how}.sock') + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) + links = sockets(c.pid) + mark = len(t.text()) + words = f'unsaved-{how}'.encode() + os.write(t.master, b'O' + words + b'\x1b') + wait_for('its keys in the session\'s text', lambda: words in nine.read(f'/pane/{pane}/body')) + if how == 'behind': + os.kill(c.pid, signal.SIGSTOP) + for k in range(30): + nine.write(f'/pane/{pane}/exec', f'Edit 3a/ edit {k} /\n'.encode()) + time.sleep(.1) + os.kill(c.pid, signal.SIGCONT) + deadline = time.monotonic() + 30 + while b'joined again' not in t.text()[mark:]: + went = [w for w, gone in (('the client', c.poll() is not None), ('the session', not alive(session))) if gone] + assert not went, (f'{how}: {" and ".join(went)} went (client exit {c.poll()}); ' + f'its terminal\'s last bytes: {t.text()[-600:]!r}') + assert time.monotonic() < deadline, f'{how}: the client joined again' + os.write(t.master, b'jk') + time.sleep(.2) + said = b'this client diverged' if how == 'diverged' else b' s behind' + wait_for(f'{how}: its notice says why', lambda: said in t.text()[mark:], timeout=10) + assert c.poll() is None and alive(session), (how, c.poll()) + assert sockets(c.pid) == links, (f'{how}: joined again over its own link', links, sockets(c.pid)) + assert words in nine.read(f'/pane/{pane}/body'), how + seen = len(checks(check)) + os.write(t.master, b'jj') + wait_for(f'{how}: the client agrees after it', lambda: agreed(check, seen), timeout=30) + nine.socket.close() + t.close() + terms.remove(t) + c.wait(timeout=20) + wait_for(f'{how}: the session ended with its last link', lambda: not alive(session), timeout=20) + print(f'pair back: no daemon, its client {how}: joined again over its own link, the session alive, ' + f'its unsaved text there, agreed; its terminal closed, the session ended') + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) + finally: + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + for t in terms: + t.close() + shutil.rmtree(root, ignore_errors=True) + + def attach_upgrading(binary, rounds=6, dump=True): """`pardes attach` as its session upgrades: started at once after the Upgrade's word, it is handed to the session before the exec; told the @@ -2233,8 +2348,8 @@ def far_flood(binary): started = [] terms = [] try: - sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=dict(env, PARDES_REPLICA_STATS=str(root / 'session.stats')), + cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) sock = root / 'pardes-replica.sock' wait_for('the replica socket', sock.exists) @@ -2258,13 +2373,22 @@ def far_flood(binary): dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check), PARDES_REPLICA_STATS=str(stats))) started.append(c.pid) wait_for('the far client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=60) + links = sockets(c.pid) nine.write(f'/pane/{shell}/pty/data', b'timeout 20 yes; echo yes-done\r') wait_for('yes ended', lambda: b'yes-done' in nine.read(f'/pane/{shell}/body').replace(b'\r', b''), timeout=60) + ended_at = time.monotonic() seen = len(checks(check)) wait_for('the far client agrees once yes ended', lambda: agreed(check, seen), timeout=120) # Queued behind the flood, let go for its lag, joined again from a # dump: a link of its ended (its stats line), and its notice says why. assert joins(stats), ('no link of the far client ended under the flood', checks(stats)) + # Over its own link (the relay's one connection for it), each join's + # time and the KB it was sent; the flood's end to its agreement. + same = sockets(c.pid) == links + print(f'far flood: the far client\'s link {"the same" if same else "another"} after {len(joins(stats))} joins again ' + f'(join ms {[j.get("join_ms") for j in joins(stats)]}, sent KB {[j.get("sent_kb") for j in joins(stats)]}); ' + f'agreed {time.monotonic() - ended_at:.1f} s after yes ended') + assert same, ('the far client joined again over its own link', links, sockets(c.pid)) wait_for('the far client\'s notice of its join again', lambda: b'joined again: ' in t.text() and b' s behind' in t.text(), timeout=30) os.write(t.master, b'echo from-far\r') wait_for('the far client\'s keys in the shell', lambda: b'from-far' in nine.read(f'/pane/{shell}/body'), timeout=30) @@ -2825,6 +2949,7 @@ def main(binary, cycles): launch(binary) pair(binary) pair_rows(binary) + pair_back(binary) attach_upgrading(binary) kept_views(binary) pair_upgrade_views(binary) @@ -3927,8 +4052,11 @@ if __name__ == '__main__': elif sys.argv[1:2] == ['--pair']: pair(sys.argv[2]) pair_rows(sys.argv[2]) + pair_back(sys.argv[2]) attach_upgrading(sys.argv[2], dump=False) pair_upgrade_views(sys.argv[2]) + elif sys.argv[1:2] == ['--pair-back']: + pair_back(sys.argv[2]) elif sys.argv[1:2] == ['--attach-upgrading']: attach_upgrading(sys.argv[2]) elif sys.argv[1:2] == ['--relink']: @@ -3941,6 +4069,8 @@ if __name__ == '__main__': far_flood(sys.argv[2]) by_hash(sys.argv[2]) far_find(sys.argv[2]) + elif sys.argv[1:2] == ['--far-flood']: + far_flood(sys.argv[2]) elif sys.argv[1:2] == ['--far-find']: far_find(sys.argv[2]) elif sys.argv[1:2] == ['--kitty-image']: -- cgit v1.3 From 396247178d20678a36e9e1782c2a457eeb1916de Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 23 Nov 2026 04:21:13 -0300 Subject: link: a far client that falls behind dials again, as before round 1 (the coordinator's ruling P63a): `Link.backHere` says no for a link that crosses machines (`Link.far`, set by runtime/client.zig from its `Have`) and fell behind `behind_max_ms`, so that client says its goodbye, shuts its link and dials again through the daemon, a new connection that drops what the old one holds for it; every other way back (a divergence, a near lag, a cut, a refused load's ask) stays on the link; marked in the code as the second road it is, with what replaces it (bounded flight: the session never more than a window past what its client has taken); the failing row first: test/daemon.py `--far` on ReleaseSafe 6 of 7 on round 1's tree (`far_flood`: over its own link the far client read through all the relay held for it, agreeing 49-68 s after `yes` against 22.7 s by a dial); `far_flood` now asserts the far client behind took ANOTHER connection; the lag test asserts both roads (`backHere` near yes, far no) ; gated with the next change as its tree (g1, rnllpvzw fd3730201cb3): `--far` on ReleaseSafe 7 of 7, far_flood ANOTHER connection each time and agreed 22.3-26.0 s after `yes` ended (Debug 25.3 s), every other row as before: core-test 931/1095 (164 skipped), shell-test 1137/1140 (3 skipped), process-test 0 of 146 failed both ways, the soak x3 and --pair x3 clean, daemon.py every mode on both builds, the upgrades 12 of 12, frames 77/77 and 121 counts within 0.1% against tree6, the cross-builds Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 16 ++++++++++++++++ runtime/client.zig | 2 +- test/daemon.py | 8 +++++--- 3 files changed, 22 insertions(+), 4 deletions(-) (limited to 'test/daemon.py') diff --git a/core/replica.zig b/core/replica.zig index 448c428f..79abd977 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -3292,6 +3292,9 @@ pub const Link = struct { fresh: bool = true, /// How far behind it was as it let its link go (`rejoins` says so). lagged: u64 = 0, + /// Its link crosses machines (a `Have`: ssh's forward, a relay): fallen + /// behind, it dials again (`backHere`). + far: bool = false, /// A pair's first join, its own boot not confirmed yet: its inputs /// kept here, not sent (`release`; client.zig `confirm`). held: ?std.ArrayListUnmanaged(u8) = null, @@ -3526,7 +3529,15 @@ pub const Link = struct { /// a cut's keep the link, an Upgrade's and a Restore's end it, which the /// join there finds): its goodbye and hello are said on it (`comeBack`). /// One that is gone, or a last word, is not. + /// THE SECOND ROAD: a far client that fell behind dials again (a new + /// connection; the one it leaves is shut): over its own link it would + /// first read through all that link holds for it, which a relay or a + /// forward buffers without bound (test/daemon.py `far_flood`: 49-68 s + /// to agree after the flood against 22.7 s by a dial). Bounded flight + /// (the session never more than a window past what its client has + /// taken) replaces it, and this line goes. pub fn backHere(c: *const Link) bool { + if (c.far and c.lagged != 0) return false; return !c.gone and c.ended == null and !c.left and (c.r.diverged != null or c.lagged != 0 or c.refused != null); } @@ -6053,6 +6064,11 @@ test "a client whose session's units come more than two seconds later than its q // core is behind on purpose, no divergence. link.take(.{ .checked = digestOf(a) +% 1 }); try std.testing.expect(r.diverged == null); + // It comes back over its link; far, it dials again (`backHere`). + try std.testing.expect(link.backHere()); + link.far = true; + try std.testing.expect(!link.backHere()); + link.far = false; try std.testing.expect(link.rejoins()); try std.testing.expectEqualStrings("joined again: 2.1 s behind", link.notice()); try std.testing.expect(!link.rejoins()); diff --git a/runtime/client.zig b/runtime/client.zig index 2fbc75c8..1d348aea 100644 --- a/runtime/client.zig +++ b/runtime/client.zig @@ -175,7 +175,7 @@ pub fn Loop(comptime Frontend: type) type { frames: *pardes.FrameStats, pub fn init(fe: *Frontend, s: *Start) !L { - var l: L = .{ .link = .{ .r = s.r, .fd = s.joined.fd }, .fe = fe, .frames = &s.frames }; + var l: L = .{ .link = .{ .r = s.r, .fd = s.joined.fd, .far = s.have != null }, .fe = fe, .frames = &s.frames }; try l.link.fromEnv(s.gpa, s.env); return l; } diff --git a/test/daemon.py b/test/daemon.py index c22d95d4..caa1272b 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -2382,13 +2382,15 @@ def far_flood(binary): # Queued behind the flood, let go for its lag, joined again from a # dump: a link of its ended (its stats line), and its notice says why. assert joins(stats), ('no link of the far client ended under the flood', checks(stats)) - # Over its own link (the relay's one connection for it), each join's - # time and the KB it was sent; the flood's end to its agreement. + # Fallen behind, a far client dials again (core/replica.zig + # `Link.backHere`: the second road until bounded flight): a new + # connection, not what the old one holds for it read through; each + # join's time and the KB it was sent; the flood's end to its agreement. same = sockets(c.pid) == links print(f'far flood: the far client\'s link {"the same" if same else "another"} after {len(joins(stats))} joins again ' f'(join ms {[j.get("join_ms") for j in joins(stats)]}, sent KB {[j.get("sent_kb") for j in joins(stats)]}); ' f'agreed {time.monotonic() - ended_at:.1f} s after yes ended') - assert same, ('the far client joined again over its own link', links, sockets(c.pid)) + assert not same, ('the far client behind dialled again: another connection', links, sockets(c.pid)) wait_for('the far client\'s notice of its join again', lambda: b'joined again: ' in t.text() and b' s behind' in t.text(), timeout=30) os.write(t.master, b'echo from-far\r') wait_for('the far client\'s keys in the shell', lambda: b'from-far' in nine.read(f'/pane/{shell}/body'), timeout=30) -- cgit v1.3