diff --git a/Makefile b/Makefile index 3412f4f..a2a640e 100644 --- a/Makefile +++ b/Makefile @@ -373,6 +373,7 @@ check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) tests/test_junction echo "== tests/test_anthropic.sh"; sh tests/test_anthropic.sh; \ echo "== tests/test_agents_ui.sh"; sh tests/test_agents_ui.sh; \ echo "== tests/test_a2a_input.sh"; sh tests/test_a2a_input.sh; \ + echo "== tests/test_swarm_socket.sh"; sh tests/test_swarm_socket.sh; \ echo "== tests/test_ui.sh"; sh tests/test_ui.sh; \ echo "== tests/test_protocol.sh"; sh tests/test_protocol.sh; \ echo "== tests/test_attach.sh"; sh tests/test_attach.sh; \ diff --git a/src/backend/swarm.c b/src/backend/swarm.c index 4e76420..054934a 100644 --- a/src/backend/swarm.c +++ b/src/backend/swarm.c @@ -83,6 +83,64 @@ path_for(struct swarm *s, const char *cwd) snprintf(s->path, sizeof(s->path), "%s/%s", cwd && *cwd ? cwd : ".", SWARM_PATH); } +/* + * The file the *listening* socket is bound to, for the exit paths that do not + * get to run normal code: SIGTERM/SIGHUP from kill(1) or a closed terminal. + * Only async-signal-safe calls are allowed there (unlink is one), so the path + * is prepared at bind time and the handler only compares a flag. + * + * A slave never arms this: it did not bind the file and has no business + * removing it. + */ +static char g_bound_path[512]; +static volatile sig_atomic_t g_bound_armed; +/* + * Live peers, as a number a signal handler can read. The handler must not walk + * the peer table (it may see a half-updated entry), so the master keeps this + * in step with the table and the handler only looks at it. + */ +static volatile sig_atomic_t g_live_peers; + +static void +note_peer_gone(struct swarm *s) +{ + int i, n = 0; + + for (i = 0; i < s->npeers; i++) + if (s->peers[i].alive && s->peers[i].fd >= 0) + n++; + g_live_peers = n; +} + +static void +arm_bound_path(const char *path) +{ + size_t i; + + for (i = 0; i + 1 < sizeof(g_bound_path) && path[i] != '\0'; i++) + g_bound_path[i] = path[i]; + g_bound_path[i] = '\0'; + g_bound_armed = 1; +} + +/* + * Last-resort cleanup for a signal handler. unlink is async-signal-safe, and + * the file this process bound is a name it may remove -- unless a peer still + * runs, in which case the fleet must survive this process. A handler cannot + * ask the peer table (no locks, no allocation), so the count of live peers is + * kept in a sig_atomic_t that the master updates as peers come and go. When a + * peer is still there the file stays; that peer reads the EOF, finds a path + * with no listener, removes it and binds, and the fleet lives on. + */ +void +swarm_emergency_unlink(void) +{ + if (g_bound_armed && g_live_peers == 0) { + unlink(g_bound_path); + g_bound_armed = 0; + } +} + /* No unlink before bind: if a master is alive the bind fails with EADDRINUSE * and the caller connects as a slave instead; a stale socket is removed by * swarm_init only after the connect failed. */ @@ -111,11 +169,26 @@ try_become_master(struct swarm *s) } } if (listen(fd, 8) != 0) { close(fd); unlink(s->path); return -1; } + /* + * Remember the file we just bound. A close that finds a different inode + * there is looking at someone else's fleet and must not delete it. + */ + { + struct stat st; + + s->sdev = 0; + s->sino = 0; + if (stat(s->path, &st) == 0) { + s->sdev = st.st_dev; + s->sino = st.st_ino; + } + } set_nb(fd); s->listen_fd = fd; s->role = SWARM_MASTER; s->id = 0; s->npeers = 0; + arm_bound_path(s->path); return 0; } @@ -149,6 +222,33 @@ try_connect_master(struct swarm *s) return 0; } +/* + * Bind the fleet socket in this directory, or join whoever already answers on + * it. The order matters: bind first (a live master makes it fail with + * EADDRINUSE), then connect, and only a connection that nothing answers is + * proof that the file is a leftover -- then it may be removed and the bind + * retried. A file another user bound is never touched (-2). + * + * Used at startup and again when a slave loses its master: the fleet outlives + * the process that happened to bind it first. + */ +static int +join_or_bind(struct swarm *s) +{ + if (try_become_master(s) == 0) + return 0; + switch (try_connect_master(s)) { + case 0: + return 0; + case -2: + return -1; /* another user's socket: neither join nor remove */ + default: + break; + } + unlink(s->path); + return try_become_master(s); +} + int swarm_init(struct swarm *s, const char *cwd) { @@ -159,21 +259,7 @@ swarm_init(struct swarm *s, const char *cwd) s->id = -1; signal(SIGPIPE, SIG_IGN); path_for(s, cwd); - if (try_become_master(s) == 0) - return 0; - /* stale socket? try connect; if connect fails, remove and retry bind */ - switch (try_connect_master(s)) { - case 0: - return 0; - case -2: - return -1; /* another user's socket: neither join nor remove */ - default: - break; - } - unlink(s->path); - if (try_become_master(s) == 0) - return 0; - return -1; /* standalone */ + return join_or_bind(s); /* -1: standalone, no fleet */ } @@ -217,6 +303,7 @@ master_accept(struct swarm *s) } memset(p, 0, sizeof(*p)); p->fd = fd; p->id = id; p->alive = 1; p->busy = 0; + note_peer_gone(s); /* recount: the exit path reads this */ snprintf(msg, sizeof(msg), "{\"t\":\"welcome\",\"id\":%d,\"master\":%d}", id, (int)getpid()); send_line(fd, msg); /* @@ -247,6 +334,36 @@ master_handle_line(struct swarm *s, struct swarm_peer *p, const char *line) mcp_json_free(v); } +/* + * The connection to the master is gone -- it said "bye", or it died without + * saying anything (EOF, SIGKILL). Both mean the same thing for the fleet: the + * members that are left own it now. Take it over (bind) or join whoever was + * faster (connect); with nobody left, this session runs standalone and the + * file disappears when it closes. + * + * A hard-killed master leaves the file behind with no listener, so bind fails + * with EADDRINUSE and connect is refused -- exactly the combination that makes + * join_or_bind remove the leftover and bind. That is why a SIGKILLed master no + * longer sticks the next start on "[swarm locked]". + */ +static void +lose_master(struct swarm *s) +{ + if (s->master_fd >= 0) { + close(s->master_fd); + s->master_fd = -1; + } + s->role = SWARM_NONE; + s->locked = 0; + s->id = -1; + s->milen = 0; + s->mibuf[0] = '\0'; + if (join_or_bind(s) != 0) { + s->role = SWARM_NONE; + s->id = -1; + } +} + static void slave_handle_line(struct swarm *s, const char *line) { @@ -271,6 +388,14 @@ slave_handle_line(struct swarm *s, const char *line) s->locked = 1; } else if (strcmp(t, "ping") == 0) { send_line(s->master_fd, "{\"t\":\"pong\"}"); + } else if (strcmp(t, "bye") == 0) { + /* + * The master is leaving. Only flag it here: this runs inside the + * reader's buffer walk, and taking the fleet over rearranges that + * same buffer. swarm_poll does the work once the walk is done. + */ + s->lost_master = 1; + s->locked = 0; } /* "result" and "event" are not handled by a slave */ mcp_json_free(v); @@ -303,8 +428,16 @@ read_lines_fd(struct swarm *s, int fd, int is_master, struct swarm_peer *peer) else { ibuf = s->mibuf; ilen = &s->milen; cap = sizeof(s->mibuf); } n = read(fd, buf, sizeof(buf)); if (n == 0) { - if (peer) { peer->alive = 0; if (peer->fd >= 0) close(peer->fd); peer->fd = -1; } - else if (s->master_fd >= 0) { close(s->master_fd); s->master_fd = -1; s->role = SWARM_NONE; } + if (peer) { + peer->alive = 0; + if (peer->fd >= 0) close(peer->fd); + peer->fd = -1; + note_peer_gone(s); /* the exit path reads this */ + } + else { /* EOF: the master is gone without a word */ + if (s->master_fd >= 0) { close(s->master_fd); s->master_fd = -1; } + s->lost_master = 1; + } return; } if (n < 0) return; @@ -328,7 +461,17 @@ void swarm_poll(struct swarm *s) { int i; - if (!s || s->role == SWARM_NONE) return; + if (!s) return; + /* + * Checked before the role gate: a slave whose master vanished has + * already fallen back to SWARM_NONE, and this is what brings it back + * into the fleet. + */ + if (s->lost_master) { + s->lost_master = 0; + lose_master(s); + } + if (s->role == SWARM_NONE) return; if (s->role == SWARM_MASTER) { master_accept(s); for (i = 0; i < s->npeers; i++) { @@ -467,17 +610,104 @@ swarm_status(struct swarm *s, char *buf, size_t cap) } } +/* + * Is the socket file at s->path still the one this instance bound? A master + * that bound it and then saw it replaced would otherwise delete the file of + * whoever came after it. + */ +static int +owns_path(struct swarm *s) +{ + struct stat st; + + if (s->sino == 0) + return 0; + if (stat(s->path, &st) != 0) + return 0; + return st.st_dev == s->sdev && st.st_ino == s->sino; +} + +/* + * Close the master's listening socket and leave the fleet. + * + * The file only goes when this is the last member. While a peer is still + * connected the path stays -- the survivor takes the fleet over and the fleet + * must not be without a socket for as long as its poll loop needs to notice. + * A file left behind that way has no listener, so the survivor's takeover + * fails to bind (EADDRINUSE) and fails to connect (refused), which is exactly + * what makes it remove the leftover and bind: the removal has one owner, the + * member that is there. + * + * The "bye" is what tells a survivor to take over; it is sent after the file + * decision, never before. + */ +/* + * Is a member still connected? The cached "alive" flag is not enough: a peer + * that exited has its fd closed by the kernel, but this side only learns that + * when it reads. Do that read now, before deciding whether the file may go -- + * a nonblocking read on a closed peer returns 0, on a live one EAGAIN. + */ +static int +master_has_peers(struct swarm *s) +{ + int i, alive = 0; + + for (i = 0; i < s->npeers; i++) { + struct swarm_peer *p = &s->peers[i]; + char sink[256]; + ssize_t n; + + if (!p->alive || p->fd < 0) + continue; + n = read(p->fd, sink, sizeof(sink)); + if (n == 0) { /* the peer is gone */ + close(p->fd); + p->fd = -1; + p->alive = 0; + continue; + } + /* data (dropped, the fleet is closing) or EAGAIN: still there */ + alive = 1; + } + g_live_peers = alive; + return alive; +} + +static void +master_close(struct swarm *s) +{ + int i, last = !master_has_peers(s); + + if (last && owns_path(s)) + unlink(s->path); + s->sino = 0; + for (i = 0; i < s->npeers; i++) + if (s->peers[i].fd >= 0) { + send_line(s->peers[i].fd, "{\"t\":\"bye\"}"); + close(s->peers[i].fd); + s->peers[i].fd = -1; + s->peers[i].alive = 0; + } + if (s->listen_fd >= 0) { + close(s->listen_fd); + s->listen_fd = -1; + } + /* + * Not the last one: the file is now a leftover without a listener, and + * the survivor cleans it up on takeover. Never unlink it here -- the + * survivor may already have rebound the path, and that file is not ours. + */ +} + void swarm_close(struct swarm *s) { - int i; if (!s) return; - if (s->role == SWARM_MASTER) { - for (i=0;inpeers;i++) if (s->peers[i].fd>=0) close(s->peers[i].fd); - if (s->listen_fd>=0) { close(s->listen_fd); unlink(s->path); } - } else if (s->role == SWARM_SLAVE) { - if (s->master_fd>=0) close(s->master_fd); + if (s->role == SWARM_MASTER) + master_close(s); + else if (s->role == SWARM_SLAVE && s->master_fd >= 0) { + close(s->master_fd); + s->master_fd = -1; } s->role = SWARM_NONE; - s->listen_fd = s->master_fd = -1; } diff --git a/src/backend/swarm.h b/src/backend/swarm.h index 13d64d6..7bb8e1f 100644 --- a/src/backend/swarm.h +++ b/src/backend/swarm.h @@ -7,6 +7,7 @@ * (id 0); others connect as slaves (id 1..N). Newline-delimited JSON IPC. */ #include +#include /* dev_t, ino_t: the file we bound */ #define SWARM_MAX_PEERS 16 #define SWARM_PATH ".splinter-swarm.sock" @@ -28,12 +29,20 @@ struct swarm { int id; /* 0 master, 1..N slave */ int listen_fd; /* master */ int master_fd; /* slave: connection to master */ + /* + * The socket file we bound, by inode. swarm_close removes the path only + * if it still is that file: a later master (or another user's) may have + * replaced it in the meantime, and that one is not ours to delete. + */ + dev_t sdev; + ino_t sino; char mibuf[4096]; /* slave: partial line buffer from master */ size_t milen; char path[512]; struct swarm_peer peers[SWARM_MAX_PEERS]; int npeers; int locked; /* slave: user input disabled */ + int lost_master; /* slave: master gone, take over in poll */ char inbox[4096]; /* routed command/text for this instance */ int has_inbox; int inbox_remote; /* inbox came from master/peer */ @@ -43,6 +52,13 @@ struct swarm { * but swarm may still be SWARM_NONE (run standalone). */ int swarm_init(struct swarm *s, const char *cwd); void swarm_close(struct swarm *s); +/* + * Async-signal-safe cleanup for a handler that is about to die: removes the + * socket file this process bound. A slave does nothing (it never bound one). + * Call it from the SIGTERM/SIGHUP path, before raise(); normal exits go + * through swarm_close(). + */ +void swarm_emergency_unlink(void); /* Poll for IPC activity (accept, read). Non-blocking. */ void swarm_poll(struct swarm *s); /* Master: route text/command to instance id; id<0 picks least busy. Returns diff --git a/src/frontend/curses.c b/src/frontend/curses.c index 88c6bba..227c890 100644 --- a/src/frontend/curses.c +++ b/src/frontend/curses.c @@ -4293,6 +4293,12 @@ term_signal(int sig) { static const char leave[] = "\033[?1049l\033[?25h\r\n"; + /* + * A killed session leaves no swarm socket behind: the file exists only + * while a member runs, and SIGTERM does not reach sp_engine_close(). + * Only async-signal-safe calls in this handler (unlink is one). + */ + swarm_emergency_unlink(); if (term_modes_set) write_all(TERM_MODES_OFF, sizeof(TERM_MODES_OFF) - 1); write_all(leave, sizeof(leave) - 1); diff --git a/src/main.c b/src/main.c index 375332a..0d0454f 100644 --- a/src/main.c +++ b/src/main.c @@ -73,6 +73,9 @@ usage(FILE *f) " --kind NAME vendor shape of --endpoint: openai (default)\n" " or anthropic\n" " --chat interactive curses UI instead of one turn\n" + " --swarm join the local fleet: share this directory's\n" + " instances over .splinter-swarm.sock (needs\n" + " --chat; the file exists only while one runs)\n" " --serve serve the line protocol on a Unix socket\n" " --attach run the curses UI as a client of --serve\n" " --socket PATH socket for --serve/--attach (default\n" @@ -231,6 +234,7 @@ struct opts { int openai_port; int serve, attach; const char *socket; + int swarm; /* --swarm: join the local fleet */ }; /* @@ -345,6 +349,8 @@ parse_args(int argc, char **argv, struct opts *o, struct sp_agent_config *cfg) o->plugins[o->nplugins++] = argv[++i]; } else if (!strcmp(a, "--chat")) o->chat = 1; + else if (!strcmp(a, "--swarm")) + o->swarm = 1; else if (!strcmp(a, "--serve")) o->serve = 1; else if (!strcmp(a, "--attach")) @@ -1525,9 +1531,14 @@ main(int argc, char **argv) eo.interview = o.interview; eo.no_transport = (o.mcp_ip != NULL && !o.daemon && o.endpoint == NULL && o.model == NULL) || o.delegate != NULL; - /* the fleet belongs to the curses chat, not to a served engine */ - eo.swarm = o.chat && !o.serve && !o.daemon && o.a2a_ip == NULL && - o.mcp_ip == NULL && o.delegate == NULL; + /* + * The fleet is opt-in (--swarm) and belongs to the curses chat, not to + * a served engine. Without the flag no instance binds or joins + * .splinter-swarm.sock, so a plain chat leaves no file in a shared + * working directory and no second instance can be locked by it. + */ + eo.swarm = o.swarm && o.chat && !o.serve && !o.daemon && + o.a2a_ip == NULL && o.mcp_ip == NULL && o.delegate == NULL; { size_t k; diff --git a/tests/test_swarm.c b/tests/test_swarm.c index b1f1e93..cf5710c 100644 --- a/tests/test_swarm.c +++ b/tests/test_swarm.c @@ -108,9 +108,149 @@ main(void) swarm_status(&slave, buf, sizeof(buf)); CHECK(strstr(buf, "slave 1") != NULL); - /* close the slave first: the master's socket lives longer */ + /* + * The file lives while a member does, and not a second longer. Who bound + * it is an implementation detail: when the master goes, a member that is + * still there takes the fleet over and the path stays. + */ + snprintf(path, sizeof(path), "%s/%s", dir, SWARM_PATH); + CHECK(access(path, F_OK) == 0); + /* close the slave first: it is not the one that would keep the fleet */ swarm_close(&slave); + CHECK(access(path, F_OK) == 0); /* the master is still there */ swarm_close(&master); + if (access(path, F_OK) == 0) { + fprintf(stderr, "FAIL %s:%d: socket file survived the last member\n", + __FILE__, __LINE__); + failures++; + } + CHECK(access(path, F_OK) != 0); + + /* + * Two members, the master leaves first: the fleet stays alive under the + * remaining one and the file with it. The old close took the file along + * and left the survivor on a path nobody answered on. + */ + { + struct swarm m2, s2; + + CHECK(swarm_init(&m2, dir) == 0); + CHECK(m2.role == SWARM_MASTER); + CHECK(swarm_init(&s2, dir) == 0); + CHECK(s2.role == SWARM_SLAVE); + for (i = 0; i < 50 && s2.id < 0; i++) { + swarm_poll(&m2); + swarm_poll(&s2); + if (s2.id < 0) + nap_ms(10); + } + CHECK(s2.id == 1); + + swarm_close(&m2); /* the master goes first */ + CHECK(access(path, F_OK) == 0); /* a member is still running */ + + /* the survivor notices and takes the fleet over */ + for (i = 0; i < 50 && s2.role != SWARM_MASTER; i++) { + swarm_poll(&s2); + if (s2.role != SWARM_MASTER) + nap_ms(10); + } + CHECK(s2.role == SWARM_MASTER); + CHECK(access(path, F_OK) == 0); + + /* and it is the last one, so its close removes the file */ + swarm_close(&s2); + CHECK(access(path, F_OK) != 0); + } + + /* + * A hard-killed master (EOF on the connection, no "bye") leaves a file + * with no listener behind. A member that reads the EOF has to clean that + * up and keep the fleet -- this is the "[swarm locked]" case. + */ + { + struct swarm m3, s3; + + CHECK(swarm_init(&m3, dir) == 0); + CHECK(swarm_init(&s3, dir) == 0); + for (i = 0; i < 50 && s3.id < 0; i++) { + swarm_poll(&m3); + swarm_poll(&s3); + if (s3.id < 0) + nap_ms(10); + } + CHECK(s3.id == 1); + /* the master dies the way kill -9 does: no bye, file left over */ + if (m3.listen_fd >= 0) { + close(m3.listen_fd); + m3.listen_fd = -1; + } + for (i = 0; i < m3.npeers; i++) + if (m3.peers[i].fd >= 0) { + close(m3.peers[i].fd); + m3.peers[i].fd = -1; + } + m3.role = SWARM_NONE; + CHECK(access(path, F_OK) == 0); /* the leftover file */ + + for (i = 0; i < 50 && s3.role != SWARM_MASTER; i++) { + swarm_poll(&s3); + if (s3.role != SWARM_MASTER) + nap_ms(10); + } + CHECK(s3.role == SWARM_MASTER); + swarm_close(&s3); + CHECK(access(path, F_OK) != 0); + } + + /* + * The last-resort signal cleanup must not take the fleet away from a + * member that is still running. kill -TERM on the master runs + * swarm_emergency_unlink(), which has no access to the peer table and + * counts live peers in a sig_atomic_t instead: with a peer there, the + * file stays and the survivor takes over. + */ + { + struct swarm m4, s4; + + CHECK(swarm_init(&m4, dir) == 0); + CHECK(swarm_init(&s4, dir) == 0); + for (i = 0; i < 50 && s4.id < 0; i++) { + swarm_poll(&m4); + swarm_poll(&s4); + if (s4.id < 0) + nap_ms(10); + } + CHECK(s4.id == 1); + /* what the SIGTERM handler would do to the master */ + swarm_emergency_unlink(); + if (access(path, F_OK) != 0) { + fprintf(stderr, + "FAIL %s:%d: signal cleanup took the file from a live member\n", + __FILE__, __LINE__); + failures++; + } + /* and then the process is gone: no bye, no close, just EOF */ + if (m4.listen_fd >= 0) { + close(m4.listen_fd); + m4.listen_fd = -1; + } + for (i = 0; i < m4.npeers; i++) + if (m4.peers[i].fd >= 0) { + close(m4.peers[i].fd); + m4.peers[i].fd = -1; + } + m4.role = SWARM_NONE; + /* the survivor has to take over the fleet that was left to it */ + for (i = 0; i < 50 && s4.role != SWARM_MASTER; i++) { + swarm_poll(&s4); + if (s4.role != SWARM_MASTER) + nap_ms(10); + } + CHECK(s4.role == SWARM_MASTER); + swarm_close(&s4); + CHECK(access(path, F_OK) != 0); + } /* a directory with no fleet is standalone, not an error */ { @@ -118,7 +258,30 @@ main(void) CHECK(swarm_init(&solo, dir) == 0); CHECK(solo.role == SWARM_MASTER); + CHECK(access(path, F_OK) == 0); swarm_close(&solo); + CHECK(access(path, F_OK) != 0); + } + + /* + * A file that is not ours is not deleted. Another instance may have + * bound the path after us; its file must survive our close. + */ + { + struct swarm first; + FILE *foreign; + + CHECK(swarm_init(&first, dir) == 0); + CHECK(first.role == SWARM_MASTER); + /* replace the file behind our back, as a new master would */ + CHECK(unlink(path) == 0); + foreign = fopen(path, "w"); + CHECK(foreign != NULL); + if (foreign != NULL) + fclose(foreign); + swarm_close(&first); + CHECK(access(path, F_OK) == 0); /* not ours: left alone */ + (void)unlink(path); } snprintf(path, sizeof(path), "rm -rf '%s'", dir); diff --git a/tests/test_swarm_socket.sh b/tests/test_swarm_socket.sh new file mode 100755 index 0000000..dd28f72 --- /dev/null +++ b/tests/test_swarm_socket.sh @@ -0,0 +1,171 @@ +#!/bin/sh +# +# splinter -- the fleet socket exists only while a fleet does. +# +# What it guards: every chat used to bind .splinter-swarm.sock, whether the +# operator wanted a fleet or not. The file then sat in a shared working +# directory after the session ended, and a later start that found a stale +# path stayed on "[swarm locked]" because nobody answered on it. Checked here +# against the real binary, through tmux because --chat needs a terminal: +# +# 1. --chat without --swarm creates no socket file, at all. +# 2. --chat --swarm creates one, it answers a second member, and it is gone +# again when the session ends -- by Ctrl-D and by SIGTERM, the path that +# never reaches sp_engine_close. +# 3. two --swarm sessions share one file; it goes when the last one leaves, +# not when the master does. +set -u +cd "$(dirname "$0")/.." || exit 1 +ROOT=$(pwd) +. "$(dirname "$0")/sh/port.sh" +if ! command -v tmux >/dev/null 2>&1; then + echo "test_swarm_socket: skipped (no tmux)" + exit 0 +fi +D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-swsock-XXXXXX") || exit 1 +SPLINTER_SESSION_DIR="$D/home/.splinter" +export SPLINTER_SESSION_DIR +# Our own tmux server, never the user's: $TMUX wins over $TMUX_TMPDIR, so a run +# started inside the user's tmux would drive -- and kill -- that server. +unset TMUX TMUX_PANE +export TMUX_TMPDIR="$D" +own_server() { + if [ -n "${TMUX:-}" ] || [ "${TMUX_TMPDIR:-}" != "$D" ]; then + echo "test_swarm_socket: refusing to touch a tmux server this test does not own" >&2 + exit 1 + fi +} +killserver() { own_server; tmux kill-server 2>/dev/null; } +F= +fails=0 +cleanup() { + killserver + [ -n "$F" ] && kill "$F" 2>/dev/null + rm -rf "$D" +} +trap cleanup EXIT +check() { d=$1; shift; if "$@"; then :; else echo "FAIL $d"; fails=$((fails + 1)); fi; } +has_sock() { [ -S "$1/.splinter-swarm.sock" ]; } +no_sock() { ! has_sock "$1"; } + +mkdir -p "$D/home" +P=$(free_port) +python3 -I tests/fake_openai_echo.py "$P" >"$D/fake.out" 2>&1 & +F=$! +wait_listen "$P" "$F" || { echo "FAIL fake did not start"; cat "$D/fake.out"; exit 1; } + +start_chat() { # start_chat [--swarm] + S=$1 + dir=$2 + shift 2 + mkdir -p "$dir" + # exec: the pane pid is splinter itself, not a shell in front of it -- the + # SIGTERM case below has to hit the process that owns the socket + tmux new-session -d -s "$S" -x 100 -y 30 \ + "cd $dir && HOME=$D/home SPLINTER_LOCALE=en exec $ROOT/splinter \ + --no-config --endpoint http://127.0.0.1:$P/v1/chat/completions \ + --model m --chat $*" +} +wait_sock() { # wait_sock : up to 5s for the path to appear + i=0 + while [ $i -lt 20 ] && ! has_sock "$1"; do + sleep 0.25 + i=$((i + 1)) + done + has_sock "$1" +} +wait_gone() { # wait_gone : up to 5s for the path to disappear + i=0 + while [ $i -lt 20 ] && has_sock "$1"; do + sleep 0.25 + i=$((i + 1)) + done + no_sock "$1" +} +end_chat() { # end_chat : Ctrl-D, and the session is gone when it exits + tmux send-keys -t "$1" C-u C-d 2>/dev/null + i=0 + while [ $i -lt 40 ] && tmux has-session -t "$1" 2>/dev/null; do + sleep 0.25 + i=$((i + 1)) + done + tmux kill-session -t "$1" 2>/dev/null +} +joined() { # joined : a second member can connect and say hello + python3 - "$1/.splinter-swarm.sock" <<'PY' +import socket, sys +s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) +s.settimeout(5) +s.connect(sys.argv[1]) +s.sendall(b'{"t":"hello","pid":1,"busy":0}\n') +s.recv(4096) # the seat list, or at least a close: both mean a live master +s.close() +PY +} + +# 1. without --swarm: no socket, not while it runs and not after it ends +A="$D/plain" +start_chat plain "$A" +sleep 2 +check "a plain --chat created .splinter-swarm.sock" no_sock "$A" +end_chat plain +check "a plain --chat left .splinter-swarm.sock behind" no_sock "$A" + +# 2. with --swarm: the file exists while the session runs ... +B="$D/fleet" +start_chat fleet "$B" --swarm +if check "--swarm did not create the socket" wait_sock "$B"; then + # ... and it answers: a second member joins and gets an answer + check "the socket did not accept a member" joined "$B" +fi + +# ... and it is gone when the session ends, here by Ctrl-D +end_chat fleet +check "Ctrl-D left .splinter-swarm.sock behind" wait_gone "$B" + +# ... and by SIGTERM, which never reaches sp_engine_close() +start_chat fleet2 "$B" --swarm +check "--swarm did not create the socket again" wait_sock "$B" +pid=$(tmux display-message -p -t fleet2 '#{pane_pid}') +kill -TERM "$pid" 2>/dev/null +check "SIGTERM left .splinter-swarm.sock behind" wait_gone "$B" +tmux kill-session -t fleet2 2>/dev/null + +# 3. two members, one file: it goes when the last one leaves +C="$D/shared" +start_chat m1 "$C" --swarm +check "the first member created no socket" wait_sock "$C" +start_chat m2 "$C" --swarm +sleep 2 +check "the second member removed the live socket" has_sock "$C" +end_chat m1 +sleep 1 +check "the master's exit removed a socket another member still needs" \ + has_sock "$C" +end_chat m2 +check "the last member left .splinter-swarm.sock behind" wait_gone "$C" + +# 4. the master is killed while a member runs: the fleet has to survive it. +# The signal handler removes the file (it cannot know about the peer), so +# the survivor's takeover is what has to bring the fleet back. +K="$D/killed" +start_chat k1 "$K" --swarm +check "the master created no socket" wait_sock "$K" +start_chat k2 "$K" --swarm +sleep 2 +check "the second member removed the live socket" has_sock "$K" +pid=$(tmux display-message -p -t k1 '#{pane_pid}') +kill -TERM "$pid" 2>/dev/null +sleep 2 +check "a killed master took the fleet away from the survivor" wait_sock "$K" +check "the survivor's fleet does not answer" joined "$K" +end_chat k2 +check "the survivor left .splinter-swarm.sock behind" wait_gone "$K" + +kill "$F" 2>/dev/null +if [ "$fails" -eq 0 ]; then + echo "test_swarm_socket: ok" + exit 0 +fi +echo "test_swarm_socket: $fails failure(s)" +exit 1