This is an automated email from the git hooks/post-receive script.

git pushed a commit to branch tymux-10-quiet-head
in repository terminology.

View the commit online.

commit 839f25bd91450a6c42c6d2af8fef81f92741eb74
Author: [email protected] <[email protected]>
AuthorDate: Fri Sep 25 09:34:54 2026 -0600

    tymuxd: send the backlog to clients
    
    A client gets the daemon's backlog right after ATTACHED, then every row
    that scrolls off the screen, batched and sent ahead of the NOTIFY for
    the frame it left. Rows still waiting to be sent are flushed to the
    other clients before a new client's snapshot is taken, so the lines
    around the attach are neither sent twice nor lost.
    
    The snapshot holds the most recent lines, at most 2000 and a quarter of
    the client's 1 MiB output queue: a full backlog of wide lines is several
    times that, and queuing all of it got the client dropped before it saw
    anything. It stops at the first line, newest first, that does not fit,
    so a line larger than the budget is not sent, nor are the older ones. A
    line wider than the wire allows, which is a long line that wrapped, is
    sent in chunks flagged as wrapping onto the next, so that the client's
    own backlog joins them again. A chunk ends on a cell the client will not
    trim, or the flag would go with it.
    
    A client that falls behind stops receiving backlog once a quarter of its
    output queue is used, instead of being dropped when the queue fills. The
    screen keeps flowing. Once its queue drains below a sixteenth, it gets
    BACKLOG_RESET and a fresh snapshot. A client that stops reading
    altogether is still dropped when its queue is full.
    
    Nothing is done when no client is attached. With the one client that
    tybenchd attaches, the cost is copying each row for it: `tybenchd -i 5
    1000000` (seq, large writes) takes 0.347 s instead of 0.342 s (+1.5%),
    and `tybenchd -i 5 -l 100000` (one write per line) 0.283 s instead of
    0.282 s. Release build on an AMD Ryzen 7 6800U; medians of five
    alternating runs of each.
    
    tests/tymux.py checks the backlog from raw clients: lines that scrolled
    off before and after attaching, no duplicate or missing line when a
    client attaches during a flood, a slow reader that is resynchronised
    rather than dropped, the 2000 newest lines of a longer backlog, a
    client attaching to a backlog of wide lines, and a 3000 cell line that
    arrives in two chunks, also when a concealed cell sits where it would
    be cut.
---
 src/bin/termd_tymux.c | 315 +++++++++++++++++++++++++++++++++++++++++++
 src/bin/termd_tymux.h |   4 +
 tests/tymux.py        | 366 ++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 685 insertions(+)

diff --git a/src/bin/termd_tymux.c b/src/bin/termd_tymux.c
index e2d093b0..ef1807cb 100644
--- a/src/bin/termd_tymux.c
+++ b/src/bin/termd_tymux.c
@@ -11,6 +11,7 @@
 #include "config.h"
 #include "termpty.h"
 #include "termsrv.h"
+#include "backlog.h"
 #include "termd_tymux.h"
 
 _Static_assert(sizeof(Termcell) == sizeof(TermSrvCell),
@@ -30,6 +31,14 @@ typedef enum
  * clients. */
 #define CLIENT_OUT_MAX (1 << 20)
 
+/* Above this many queued bytes, a client stops receiving TSRV_MSG_BACKLOG
+ * (NOTIFY and screen updates keep flowing) instead of being dropped: a
+ * scrollback flood is not worth losing a healthy but slow reader over. */
+#define CLIENT_BACKLOG_HIGH (CLIENT_OUT_MAX / 4)
+/* Once the queue drains back under this, the client gets a
+ * TSRV_MSG_BACKLOG_RESET and a fresh snapshot to replace what it missed. */
+#define CLIENT_BACKLOG_LOW  (CLIENT_OUT_MAX / 16)
+
 typedef struct
 {
    int               fd;
@@ -41,6 +50,9 @@ typedef struct
    TermSrvReader     reader;
    Eina_Bool         dispatching : 1;
    Eina_Bool         dead : 1;
+   /* TSRV_MSG_BACKLOG is being withheld until the queue drains, see
+    * CLIENT_BACKLOG_HIGH/LOW */
+   Eina_Bool         backlog_out_of_sync : 1;
 } Client;
 
 struct tag_TermDTymux
@@ -53,6 +65,9 @@ struct tag_TermDTymux
    /* clients paused by a hijack, most recent first */
    Eina_List        *paused;
    Ecore_Animator   *notify_anim;
+   /* lines that entered the backlog since the last TSRV_MSG_BACKLOG
+    * broadcast, packed with termsrv_backlog_line_append() */
+   Eina_Binbuf      *backlog_pending;
    Eina_Bool         dirty : 1;
 };
 
@@ -84,6 +99,34 @@ _screen_flush(TermDTymux *td)
 
 static void _client_del(Client *client);
 static void _client_free(Client *client);
+static void _client_attach_backlog_send(Client *client);
+static Eina_Bool _client_send(Client *client, TermSrvMsgType type,
+                              const void *payload, uint32_t size);
+static void _backlog_pending_flush(TermDTymux *td);
+
+/* Called once a client's queue has drained back under CLIENT_BACKLOG_LOW
+ * after it had fallen behind on TSRV_MSG_BACKLOG: tell it to discard its
+ * now-stale shadow backlog and give it a fresh snapshot, the same one a
+ * client attaching right now would get. */
+static void
+_client_backlog_resync(Client *client)
+{
+   /* Lines still sitting in td->backlog_pending are already part of
+    * ty->back, so the snapshot below would include them: flush them to the
+    * other clients first (client is still marked out of sync, so
+    * _broadcast_backlog() skips it here) or the next ordinary flush would
+    * hand them to this client a second time, right after its snapshot. */
+   _backlog_pending_flush(client->td);
+   client->backlog_out_of_sync = EINA_FALSE;
+   if (!_client_send(client, TSRV_MSG_BACKLOG_RESET, NULL, 0))
+     {
+        _client_del(client);
+        return;
+     }
+   if (client->dead)
+     return;
+   _client_attach_backlog_send(client);
+}
 
 /* For a client that missed a message, when it cannot be deleted right away:
  * its fd handler sees the end of file and deletes it. */
@@ -117,6 +160,10 @@ _client_flush(Client *client)
      }
    ecore_main_fd_handler_active_set(client->handler,
                                     ECORE_FD_READ | (len ? ECORE_FD_WRITE : 0));
+
+   if (client->backlog_out_of_sync && len <= CLIENT_BACKLOG_LOW)
+     _client_backlog_resync(client);
+
    return EINA_TRUE;
 }
 
@@ -155,6 +202,55 @@ _broadcast(TermDTymux *td, TermSrvMsgType type,
      }
 }
 
+/* Like _broadcast(), but for TSRV_MSG_BACKLOG: a client whose queue is
+ * already past CLIENT_BACKLOG_HIGH is not sent this message (and not
+ * dropped for it), and is instead marked out of sync so that
+ * _client_flush() resyncs it with a TSRV_MSG_BACKLOG_RESET and a fresh
+ * snapshot once it catches up. NOTIFY and screen updates go through the
+ * ordinary _broadcast() and are unaffected. */
+static void
+_broadcast_backlog(TermDTymux *td, const void *payload, uint32_t size)
+{
+   Eina_List *l, *l_next;
+   Client *client;
+
+   EINA_LIST_FOREACH_SAFE(td->clients, l, l_next, client)
+     {
+        if (client->role == CLIENT_PENDING)
+          continue;
+        if (client->backlog_out_of_sync)
+          continue;
+        if (eina_binbuf_length_get(client->out) > CLIENT_BACKLOG_HIGH)
+          {
+             client->backlog_out_of_sync = EINA_TRUE;
+             continue;
+          }
+        if (!_client_send(client, TSRV_MSG_BACKLOG, payload, size))
+          _client_del(client);
+     }
+}
+
+/* Broadcast whatever backlog lines piled up since the last flush, then
+ * empty the accumulator. Lines are pushed in already-framed
+ * (cols + cells) form by _cb_pty_backlog(), one TSRV_MSG_BACKLOG message
+ * for the lot: _cb_pty_backlog() never lets it grow past the payload cap,
+ * so it always fits in one message. */
+static void
+_backlog_pending_flush(TermDTymux *td)
+{
+   size_t len;
+
+   if (!td->backlog_pending)
+     return;
+   len = eina_binbuf_length_get(td->backlog_pending);
+   if (len == 0)
+     return;
+   _broadcast_backlog(td, eina_binbuf_string_get(td->backlog_pending),
+                      (uint32_t)len);
+   eina_binbuf_free(td->backlog_pending);
+   td->backlog_pending = NULL;
+}
+
 static void
 _flush_and_notify(TermDTymux *td)
 {
@@ -175,6 +271,10 @@ _flush_and_notify(TermDTymux *td)
         td->notify_anim = NULL;
      }
 
+   /* lines that scrolled off before this frame so a client applies them to
+    * its backlog before the frame that no longer shows them */
+   _backlog_pending_flush(td);
+
    notify.write_seq = _screen_flush(td);
    _broadcast(td, TSRV_MSG_NOTIFY, &notify, sizeof(notify));
 }
@@ -205,6 +305,65 @@ _cb_pty_change(void *data)
      td->notify_anim = ecore_animator_add(_cb_notify_anim, td);
 }
 
+/* Whether any client has attached (or is still waiting for its own
+ * TSRV_MSG_BACKLOG snapshot flow -- CLIENT_PENDING clients get theirs from
+ * _client_attach_backlog_send(), not from here) so that keeping
+ * td->backlog_pending fed is worth the cost. With no client at all, as in
+ * the default tybenchd workload, _cb_pty_backlog() should cost nothing. */
+static Eina_Bool
+_td_has_backlog_client(TermDTymux *td)
+{
+   Eina_List *l;
+   Client *client;
+
+   EINA_LIST_FOREACH(td->clients, l, client)
+     if (client->role != CLIENT_PENDING)
+       return EINA_TRUE;
+   return EINA_FALSE;
+}
+
+/* Called synchronously whenever a line permanently enters the daemon's own
+ * backlog (termpty_text_save_top()), i.e. potentially many times between
+ * two animator ticks under a flood such as `seq 1 1000000`. Pack it
+ * straight into td->backlog_pending (no intermediate copy: CELLS is
+ * exactly TermSrvCell laid out, per the _Static_assert above), flushing
+ * what is there first if the line would not fit in one TSRV_MSG_BACKLOG
+ * payload, so the accumulator never grows past TERMSRV_MAX_MSG_PAYLOAD and
+ * a flood cannot build up an unbounded amount of memory or a single
+ * oversized send. Older lines that get flushed this way are still
+ * recoverable: they are already in ty->back and get sent to any client
+ * attaching afterwards (see _client_attach_backlog_send()). W is at most
+ * ty->w (see termpty_backlog_hook_set()'s contract), itself capped to
+ * TERMSRV_MAX_COLS by _client_resize(), so it always fits in one message
+ * on its own. */
+static void
+_cb_pty_backlog(void *data, Termpty *ty EINA_UNUSED, const Termcell *cells, ssize_t w)
+{
+   TermDTymux *td = data;
+   uint32_t off, cols = (uint32_t)w;
+   uint64_t need = sizeof(cols) + (uint64_t)cols * sizeof(TermSrvCell);
+
+   if (!_td_has_backlog_client(td))
+     return;
+
+   if (!td->backlog_pending)
+     td->backlog_pending = eina_binbuf_new();
+   if (!td->backlog_pending)
+     return;
+
+   off = (uint32_t)eina_binbuf_length_get(td->backlog_pending);
+   if (need > TERMSRV_MAX_MSG_PAYLOAD)
+     return;
+   if (off + need > TERMSRV_MAX_MSG_PAYLOAD)
+     _backlog_pending_flush(td);
+
+   eina_binbuf_append_length(td->backlog_pending,
+                             (const unsigned char *)&cols, sizeof(cols));
+   eina_binbuf_append_length(td->backlog_pending,
+                             (const unsigned char *)cells,
+                             cols * sizeof(TermSrvCell));
+}
+
 static void
 _cb_pty_title(void *data)
 {
@@ -236,6 +395,150 @@ _cb_pty_exited(void *data)
    ecore_main_loop_quit();
 }
 
+/* Where the chunk of a backlog entry that starts at from ends. An entry is
+ * as wide as the line it holds was before it wrapped, so it can be wider
+ * than TERMSRV_MAX_COLS, which one wire line cannot carry. The client trims
+ * the empty cells off the end of what it receives, with the same
+ * termpty_line_length() used here, and that would take the wrap flag of the
+ * chunk with them: the chunk ends on a cell that is not empty. */
+static uint32_t
+_backlog_chunk_end(const TermSrvCell *cells, uint32_t from, uint32_t total)
+{
+   ssize_t used;
+
+   if (total - from <= TERMSRV_MAX_COLS)
+     return total;
+   used = termpty_line_length((const Termcell *)(cells + from),
+                              TERMSRV_MAX_COLS);
+   return from + (used > 0 ? used : TERMSRV_MAX_COLS);
+}
+
+/* Bytes the entry takes on the wire, in as many chunks as it needs */
+static uint64_t
+_backlog_entry_size(const Termsave *ts)
+{
+   const TermSrvCell *cells = (const TermSrvCell *)ts->cells;
+   uint64_t size = 0;
+   uint32_t from = 0, end;
+
+   do
+     {
+        end = _backlog_chunk_end(cells, from, ts->w);
+        size += sizeof(uint32_t) + (uint64_t)(end - from) * sizeof(*cells);
+        from = end;
+     }
+   while (from < ts->w);
+   return size;
+}
+
+/* Send the daemon's existing backlog to a client that just attached, oldest
+ * first, so it can rebuild the same scrollback a client that had been there
+ * all along would have. At most TERMD_TYMUX_ATTACH_BACKLOG_MAX lines, and no
+ * more than CLIENT_BACKLOG_HIGH bytes: the most recent ones are kept. A
+ * snapshot that filled the queue would get the client dropped before it
+ * showed anything. The lines are packed into as few TSRV_MSG_BACKLOG
+ * messages as the payload cap allows, and one wider than TERMSRV_MAX_COLS
+ * is cut into chunks, all but the last flagged as wrapping onto the next so
+ * that the client's backlog joins them again, the way it joins the rows a
+ * long line wrapped over. Called synchronously while handling ATTACH, so it
+ * always lands before any NOTIFY: the daemon does not send frames from
+ * inside message handling, only from the animator. */
+static void
+_client_attach_backlog_send(Client *client)
+{
+   Termpty *ty = client->td->pty;
+   ssize_t length = termpty_backlog_length(ty);
+   ssize_t start, first = 0;
+   int64_t budget;
+   Eina_Binbuf *buf;
+
+   if (length <= 0)
+     return;
+   /* length counts screen rows, which is at least the number of entries
+    * and can pass the size of the ring, where BACKLOG_ROW_GET() wraps */
+   if (length > (ssize_t)ty->backsize - 1)
+     length = (ssize_t)ty->backsize - 1;
+   if (length > TERMD_TYMUX_ATTACH_BACKLOG_MAX)
+     length = TERMD_TYMUX_ATTACH_BACKLOG_MAX;
+
+   /* the headers of the messages the lines are packed into */
+   budget = (int64_t)CLIENT_BACKLOG_HIGH -
+      (int64_t)eina_binbuf_length_get(client->out) -
+      64 * (int64_t)sizeof(TermSrvMsgHdr);
+   /* backlog_y counts back from 1 (most recent line) */
+   for (start = 1; start <= length; start++)
+     {
+        const Termsave *ts = BACKLOG_ROW_GET(ty, start);
+        uint64_t size;
+
+        if (!ts->cells)
+          continue;
+        size = _backlog_entry_size(ts);
+        if (budget < 0 || size > (uint64_t)budget)
+          break;
+        budget -= size;
+        first = start;
+     }
+   if (first == 0)
+     return;
+
+   buf = eina_binbuf_new();
+   if (!buf)
+     return;
+
+   for (start = first; start >= 1; start--)
+     {
+        const Termsave *ts = BACKLOG_ROW_GET(ty, start);
+        const TermSrvCell *cells = (const TermSrvCell *)ts->cells;
+        uint32_t from = 0, end;
+
+        if (!cells)
+          continue;
+        do
+          {
+             unsigned char stage[sizeof(uint32_t) +
+                                 TERMSRV_MAX_COLS * sizeof(TermSrvCell)];
+             uint32_t stage_off = 0;
+             size_t cur = eina_binbuf_length_get(buf);
+
+             end = _backlog_chunk_end(cells, from, ts->w);
+             if (termsrv_backlog_line_append(stage, sizeof(stage), &stage_off,
+                                             end - from, cells + from) < 0)
+               break;
+             if (end < ts->w)
+               {
+                  unsigned char *last = stage + stage_off - sizeof(*cells);
+                  TermSrvCell cell;
+
+                  memcpy(&cell, last, sizeof(cell));
+                  cell.att.autowrapped = 1;
+                  memcpy(last, &cell, sizeof(cell));
+               }
+             if (cur + stage_off > TERMSRV_MAX_MSG_PAYLOAD)
+               {
+                  if (!_client_send(client, TSRV_MSG_BACKLOG,
+                                    eina_binbuf_string_get(buf),
+                                    (uint32_t)cur))
+                    {
+                       _client_del(client);
+                       eina_binbuf_free(buf);
+                       return;
+                    }
+                  eina_binbuf_reset(buf);
+               }
+             eina_binbuf_append_length(buf, stage, stage_off);
+             from = end;
+          }
+        while (from < ts->w);
+     }
+   if (eina_binbuf_length_get(buf) > 0 &&
+       !_client_send(client, TSRV_MSG_BACKLOG,
+                     eina_binbuf_string_get(buf),
+                     (uint32_t)eina_binbuf_length_get(buf)))
+     _client_del(client);
+   eina_binbuf_free(buf);
+}
+
 static void
 _client_attach(Client *client, TermSrvAttachMode mode)
 {
@@ -250,6 +553,15 @@ _client_attach(Client *client, TermSrvAttachMode mode)
         _client_del(client);
         return;
      }
+   /* Lines still sitting in td->backlog_pending are already part of
+    * ty->back, so the snapshot below would include them: flush them to the
+    * already-attached clients first (client is still CLIENT_PENDING, so
+    * _broadcast_backlog() skips it) or it would get them twice, once in
+    * its snapshot and again in the next flush. */
+   _backlog_pending_flush(td);
+   _client_attach_backlog_send(client);
+   if (client->dead)
+     return;
 
    switch (mode)
      {
@@ -486,6 +798,7 @@ termd_tymux_new(const char *name, const char *cmd)
    td->pty->cb.bell.data = ""
    td->pty->cb.exited.func = _cb_pty_exited;
    td->pty->cb.exited.data = ""
+   termpty_backlog_hook_set(td->pty, _cb_pty_backlog, td);
 
    _screen_flush(td);
    return td;
@@ -504,6 +817,8 @@ termd_tymux_free(TermDTymux *td)
      return;
    if (td->notify_anim)
      ecore_animator_del(td->notify_anim);
+   if (td->backlog_pending)
+     eina_binbuf_free(td->backlog_pending);
    EINA_LIST_FREE(td->clients, client)
      {
         struct timeval timeout = { .tv_sec = 0, .tv_usec = 200 * 1000 };
diff --git a/src/bin/termd_tymux.h b/src/bin/termd_tymux.h
index a6e95efc..c8cababd 100644
--- a/src/bin/termd_tymux.h
+++ b/src/bin/termd_tymux.h
@@ -3,6 +3,10 @@
 
 typedef struct tag_TermDTymux TermDTymux;
 
+/* Most backlog lines sent to a client attaching mid-stream, bounding how
+ * much a slow client is asked to catch up on. */
+#define TERMD_TYMUX_ATTACH_BACKLOG_MAX 2000
+
 /* Start the shell (cmd, or the user's shell if NULL) on a new pty whose
  * screen is published in shared memory. The main loop is quit when the
  * shell exits. Returns NULL on failure. */
diff --git a/tests/tymux.py b/tests/tymux.py
index 44779b3f..823299f1 100644
--- a/tests/tymux.py
+++ b/tests/tymux.py
@@ -328,6 +328,372 @@ def main():
     a.send("echo alive-$((6+6))\r")
     check(a.expect("alive-12"), "the primary still works")
 
+    # a native client's backlog: a raw socket plays the wire protocol
+    # directly since the CLI proxy has no scrollback of its own to check.
+    NAME4 = "k%d" % os.getpid()
+    b = Client(["new", NAME4])
+    check(b.expect("$ "), "backlog: new session shell prompt shown")
+    b.send("seq 1 100\r")
+    check(b.expect("100"), "backlog: seq output is drawn")
+    b.idle(0.5)
+
+    path4 = os.path.join(XDG, "terminology", "tymux", NAME4 + ".sock")
+    raw = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+    raw.connect(path4)
+    raw.send(struct.pack("=IIB", 1, 1, 2))  # ATTACH, readonly
+    msg, fds, _, _ = socket.recv_fds(raw, 20, 1)
+    for fd in fds:
+        os.close(fd)
+    check(len(msg) == 20 and struct.unpack_from("=II", msg)[0] == 2,
+          "backlog: ATTACHED is received")
+
+    def recv_msg(sock, buf, timeout=5):
+        end = time.time() + timeout
+        while True:
+            if len(buf) >= 8:
+                mtype, msize = struct.unpack_from("=II", bytes(buf))
+                if len(buf) >= 8 + msize:
+                    payload = bytes(buf[8:8 + msize])
+                    del buf[:8 + msize]
+                    return mtype, payload
+            if time.time() > end:
+                return None
+            ready, _, _ = select.select([sock], [], [], 0.2)
+            if ready:
+                data = ""
+                if not data:
+                    return None
+                buf.extend(data)
+
+    # sizeof(TermSrvCell): a uint32_t codepoint and a 12 byte TermSrvAtt
+    cell_size = 16
+
+    def backlog_lines(payload):
+        lines = []
+        off = 0
+        while off < len(payload):
+            (cols,) = struct.unpack_from("=I", payload, off)
+            off += 4
+            cells = []
+            for _ in range(cols):
+                cp = struct.unpack_from("<I", payload, off)[0]
+                cells.append(cp)
+                off += cell_size
+            lines.append("".join(chr(c) if c else " " for c in cells)
+                        .rstrip())
+        return lines
+
+    # the shell is idle after the seq: nothing dirties the screen, so no
+    # NOTIFY is due yet. Only the backlog sent right after ATTACHED can
+    # show up in this window.
+    buf = bytearray()
+    seen_before_notify = []
+    end = time.time() + 2
+    while time.time() < end:
+        got = recv_msg(raw, buf, timeout=max(0.1, end - time.time()))
+        if got is None:
+            break
+        mtype, payload = got
+        if mtype == 12:  # BACKLOG
+            seen_before_notify += backlog_lines(payload)
+    check("1" in seen_before_notify,
+          "backlog: the existing backlog is sent to a client on attach")
+
+    # Do not assert on b's own rendered screen here: with two clients
+    # attached, exactly how many of its frames termio's diff renderer
+    # coalesces before drawing is not deterministic enough to match
+    # against literal digits with a scroll this fast. The daemon's
+    # backlog stream, read below, is the ground truth for this test.
+    b.send("seq 101 200\r")
+    b.idle(1)
+    seen_after_attach = []
+    end = time.time() + 5
+    while time.time() < end and "101" not in seen_after_attach:
+        got = recv_msg(raw, buf, timeout=max(0.1, end - time.time()))
+        if got is None:
+            break
+        mtype, payload = got
+        if mtype == 12:
+            seen_after_attach += backlog_lines(payload)
+    check("101" in seen_after_attach,
+          "backlog: lines that scroll off after attach are streamed too")
+
+    raw.close()
+    tymux("kill", NAME4)
+    check(b.wait() is not None, "backlog: killing the session detaches it")
+
+    def attach_raw(name):
+        """attach read-only, returns (socket, bytes received so far)"""
+        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+        sock.connect(os.path.join(XDG, "terminology", "tymux", name + ".sock"))
+        sock.send(struct.pack("=IIB", 1, 1, 2))
+        msg, fds, _, _ = socket.recv_fds(sock, 20, 1)
+        for fd in fds:
+            os.close(fd)
+        return sock
+
+    def snapshot_read(sock, duration=3):
+        """the BACKLOG lines received for duration seconds, as lists of
+        (codepoint, autowrapped), and whether the daemon hung up"""
+        lines = []
+        buf = bytearray()
+        end = time.time() + duration
+        while time.time() < end:
+            ready, _, _ = select.select([sock], [], [], 0.2)
+            if not ready:
+                continue
+            data = "" << 20)
+            if not data:
+                return lines, True
+            buf.extend(data)
+            while len(buf) >= 8:
+                mtype, msize = struct.unpack_from("=II", bytes(buf))
+                if len(buf) < 8 + msize:
+                    break
+                payload = bytes(buf[8:8 + msize])
+                del buf[:8 + msize]
+                if mtype != 12:
+                    continue
+                off = 0
+                while off < len(payload):
+                    (cols,) = struct.unpack_from("=I", payload, off)
+                    off += 4
+                    cells = []
+                    for _ in range(cols):
+                        cp = struct.unpack_from("<I", payload, off)[0]
+                        # autowrapped is the first flag of the third word of
+                        # the attributes, after the codepoint
+                        wrapped = payload[off + 12] & 1
+                        cells.append((cp, wrapped))
+                        off += cell_size
+                    lines.append(cells)
+        return lines, False
+
+    # a client attaching gets the 2000 most recent lines, not all of them
+    NAME9 = "n%d" % os.getpid()
+    nr = Client(["new", NAME9])
+    check(nr.expect("$ "), "narrow: new session shell prompt shown")
+    nr.send("seq 1 5000; echo done-$((1+2))\r")
+    check(nr.expect("done-3"), "narrow: the lines are printed")
+    nr.idle(1)
+    narrow = attach_raw(NAME9)
+    lines, hung_up = snapshot_read(narrow)
+    numbers = [int(t) for t in ("".join(chr(c) if c else " " for c, _ in l)
+                                .strip() for l in lines) if t.isdigit()]
+    check(not hung_up and len(numbers) == 2000,
+          "narrow: the snapshot holds 2000 lines (%d)" % len(numbers))
+    check(numbers == list(range(numbers[0], numbers[0] + len(numbers)))
+          and numbers[-1] >= 4950,
+          "narrow: they are the most recent ones, in order (last: %d)"
+          % (numbers[-1] if numbers else 0))
+    narrow.close()
+    tymux("kill", NAME9)
+    nr.wait()
+
+    # a full backlog of wide lines does not fit the output queue of a client:
+    # attaching to it must not get the client dropped, and it gets the most
+    # recent lines
+    NAME7 = "w%d" % os.getpid()
+    w = Client(["new", NAME7], rows=24, cols=200)
+    check(w.expect("$ "), "wide: new session shell prompt shown")
+    w.send("seq 1 3000 | awk '{printf \"%s %0176d\\n\", $1, 0}';"
+           " echo done-$((1+2))\r")
+    check(w.expect("done-3"), "wide: the lines are printed")
+    w.idle(2)
+    wide = attach_raw(NAME7)
+    lines, hung_up = snapshot_read(wide)
+    check(not hung_up, "wide: a client attaching to a wide backlog is not"
+          " dropped")
+    numbers = [int("".join(chr(c) for c, _ in l).split()[0])
+               for l in lines if l and l[0][0]]
+    check(len(numbers) > 0 and max(numbers) >= 2950,
+          "wide: the snapshot ends with the most recent lines")
+    check(numbers == sorted(numbers) and len(numbers) < 3000,
+          "wide: the snapshot is in order and limited")
+    check(NAME7 in tymux("list").stdout, "wide: the session is still running")
+    wide.close()
+    tymux("kill", NAME7)
+    w.wait()
+
+    # a line wrapped over more rows than TERMSRV_MAX_COLS cells is sent in
+    # chunks that the client joins through the autowrapped flag
+    NAME8 = "l%d" % os.getpid()
+    lg = Client(["new", NAME8])
+    check(lg.expect("$ "), "long line: new session shell prompt shown")
+    lg.send("printf '%03000d\\n' 0; seq 1 60; echo done-$((1+2))\r")
+    check(lg.expect("done-3"), "long line: the line is printed")
+    lg.idle(1)
+    longline = attach_raw(NAME8)
+    lines, hung_up = snapshot_read(longline)
+    texts = ["".join(chr(c) if c else " " for c, _ in l) for l in lines]
+    chunks = [i for i, l in enumerate(lines) if l and set(c for c, _ in l)
+              == {ord("0")}]
+    joined = "".join(texts[i] for i in chunks)
+    check(joined == "0" * 3000,
+          "long line: the 3000 cells arrive (%d)" % len(joined))
+    check(len(chunks) >= 2 and all(lines[i][-1][1] for i in chunks[:-1])
+          and not lines[chunks[-1]][-1][1],
+          "long line: the chunks are flagged to be joined again")
+    longline.close()
+    tymux("kill", NAME8)
+    lg.wait()
+
+    # a chunk cannot end on a concealed cell: the client would trim it, and
+    # with it the flag that joins the next chunk. 79 columns so that the
+    # concealed cell, the 1920th of the line, is not at the end of a row,
+    # where it would be trimmed before being saved.
+    NAME10 = "c%d" % os.getpid()
+    cn = Client(["new", NAME10], cols=79)
+    check(cn.expect("$ "), "concealed: new session shell prompt shown")
+    cn.send("printf '%01919d\\033[8mX\\033[0m%01080d\\n' 0 0; seq 1 60;"
+            " echo done-$((1+2))\r")
+    check(cn.expect("done-3"), "concealed: the line is printed")
+    cn.idle(1)
+    concealed = attach_raw(NAME10)
+    lines, hung_up = snapshot_read(concealed)
+    wide_lines = [l for l in lines if len(l) > 100]
+    check(len(wide_lines) == 2 and len(wide_lines[0]) == 1919
+          and wide_lines[0][-1][1] and len(wide_lines[1]) == 1081,
+          "concealed: the first chunk ends before the concealed cell (%s)"
+          % [len(l) for l in wide_lines])
+    concealed.close()
+    tymux("kill", NAME10)
+    cn.wait()
+
+    # a client attaching in the middle of a flood must not see any backlog
+    # line twice: the daemon has to flush what it was about to broadcast to
+    # the already-attached clients before it snapshots ty->back for the new
+    # one, or the snapshot and the next flush both carry the same lines.
+    NAME5 = "p%d" % os.getpid()
+    c = Client(["new", NAME5])
+    check(c.expect("$ "), "dup: new session shell prompt shown")
+    path5 = os.path.join(XDG, "terminology", "tymux", NAME5 + ".sock")
+    c.send("seq 1 60000\r")
+    raw2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+    raw2.connect(path5)
+    raw2.send(struct.pack("=IIB", 1, 1, 2))  # ATTACH, readonly, no idle:
+    # racing the flood is the point of this test.
+    msg, fds, _, _ = socket.recv_fds(raw2, 20, 1)
+    for fd in fds:
+        os.close(fd)
+    check(len(msg) == 20 and struct.unpack_from("=II", msg)[0] == 2,
+          "dup: ATTACHED is received during a flood")
+
+    # A resync (see the slow-reader test below) legitimately re-sends a
+    # window of lines the client already had: it always starts with a
+    # TSRV_MSG_BACKLOG_RESET, on which a real client discards its shadow
+    # backlog before applying what follows. Do the same here, or a resync
+    # racing this test's own reader -- which, being Python, can lag behind
+    # a 60000-line flood enough to trigger the same flow control a slow
+    # native client would -- would look like a duplicate.
+    numbers = []
+    got_reset = False
+    buf2 = bytearray()
+    end = time.time() + 15
+    while time.time() < end:
+        got = recv_msg(raw2, buf2, timeout=max(0.1, end - time.time()))
+        if got is None:
+            break
+        mtype, payload = got
+        if mtype == 13:  # BACKLOG_RESET
+            numbers = []
+            got_reset = True
+        elif mtype == 12:
+            numbers += [int(n) for n in backlog_lines(payload)
+                       if n and n.isdigit()]
+        if numbers and numbers[-1] == 60000:
+            break
+    raw2.close()
+    check(c.expect("$ "), "dup: seq finished")
+    check(len(numbers) == len(set(numbers)),
+          "dup: no backlog line is delivered twice to a client that"
+          " attached mid-flood (%d lines, %d unique%s)"
+          % (len(numbers), len(set(numbers)),
+             ", after a resync" if got_reset else ""))
+    check(numbers == sorted(numbers),
+          "dup: backlog lines arrive in order")
+
+    tymux("kill", NAME5)
+
+    # a client too slow to keep up with a scrollback flood is not dropped
+    # for it: it stops receiving TSRV_MSG_BACKLOG for a while instead, and
+    # is caught back up with a TSRV_MSG_BACKLOG_RESET plus a fresh snapshot
+    # once its queue has drained.
+    NAME6 = "q%d" % os.getpid()
+    d = Client(["new", NAME6])
+    check(d.expect("$ "), "slow: new session shell prompt shown")
+    path6 = os.path.join(XDG, "terminology", "tymux", NAME6 + ".sock")
+    raw3 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+    raw3.connect(path6)
+    raw3.send(struct.pack("=IIB", 1, 1, 2))
+    msg, fds, _, _ = socket.recv_fds(raw3, 20, 1)
+    for fd in fds:
+        os.close(fd)
+    check(len(msg) == 20 and struct.unpack_from("=II", msg)[0] == 2,
+          "slow: ATTACHED is received")
+
+    resets = 0
+    tail_numbers = []
+    buf3 = bytearray()
+
+    def take(data):
+        nonlocal resets, tail_numbers
+        buf3.extend(data)
+        while len(buf3) >= 8:
+            mtype, msize = struct.unpack_from("=II", bytes(buf3))
+            if len(buf3) < 8 + msize:
+                break
+            payload = bytes(buf3[8:8 + msize])
+            del buf3[:8 + msize]
+            if mtype == 12:
+                nums = [int(n) for n in backlog_lines(payload)
+                        if n and n.isdigit()]
+                tail_numbers = (tail_numbers + nums)[-200:]
+            elif mtype == 13:  # BACKLOG_RESET
+                resets += 1
+                tail_numbers = []
+
+    d.send("seq 1 300000\r")
+    end = time.time() + 8
+    while time.time() < end:
+        # a slow reader: read whatever is queued, then back off, instead of
+        # draining the socket as fast as tymuxd can fill it.
+        time.sleep(0.3)
+        ready, _, _ = select.select([raw3], [], [], 0)
+        if not ready:
+            continue
+        data = ""
+        if not data:
+            break
+        take(data)
+    check(d.expect("$ ", timeout=30), "slow: seq finished")
+    d.send("echo alive-$((3+4))\r")
+    check(d.expect("alive-7"), "slow: the reader was not dropped")
+    # then it catches up, however long the flood took on this machine: what
+    # it was sent ends with the last lines of the flood
+    end = time.time() + 60
+    while time.time() < end and not (tail_numbers and
+                                     tail_numbers[-1] >= 299000):
+        ready, _, _ = select.select([raw3], [], [], 0.5)
+        if ready:
+            data = ""
+            if not data:
+                break
+            take(data)
+    try:
+        raw3.getpeername()
+        still_open = True
+    except OSError:
+        still_open = False
+    check(still_open, "slow: the reader's socket is still open")
+    check(tail_numbers == sorted(set(tail_numbers)),
+          "slow: the tail of the replayed backlog has no duplicates")
+    check(bool(tail_numbers) and tail_numbers[-1] >= 299000,
+          "slow: the reader's backlog ends near the end of the flood"
+          " (last seen: %d)" % (tail_numbers[-1] if tail_numbers else 0))
+    raw3.close()
+    tymux("kill", NAME6)
+
     # a client stalling in the middle of a message costs tymuxd nothing
     path = os.path.join(XDG, "terminology", "tymux", NAME + ".sock")
     pending = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

-- 
To stop receiving notification emails like this one, please contact
the administrator of this repository.

Reply via email to