serve: a second client is told why, not left hanging

`--serve` holds one engine, so one client talks to it at a time - that part is
deliberate. What was not: the second client connected into the listen backlog
and then waited for a greeting that could not come until the first one left.
splinterctl printed nothing and hung; --attach gave up 10 s later with "no
greeting from the backend", which names the wrong cause.

The accept is non-blocking now and a client that arrives while the engine is
taken is answered at once: an error event with the reason, then a shutdown of
the write side. That reads on the other end as "another client is attached:
one conversation runs one turn at a time". Descriptors are drained before the
close, or the RST would eat the message the client has not read yet.

Two smaller ones on the same path:
- --attach reconnects on a broken connection; it now carries the server's error
  text through instead of replacing it with "no greeting".
- a client that reads nothing is not waited for forever: a greeting timeout
  turns a silent server into a message instead of a hang.
This commit is contained in:
lotherk committed 2026-11-22 10:26:06 +00:00
1 parent a48a2deec5
commit a00534cf6c
9 files changed
+282 -10

No files matched your search

+1
View File
@@ -339,6 +339,7 @@ check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) tests/test_junction
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; \
echo "== tests/test_attach_busy.sh"; sh tests/test_attach_busy.sh; \
echo "== tests/test_gateway_openai.sh"; sh tests/test_gateway_openai.sh; \
echo "== tests/test_usage_request.sh"; sh tests/test_usage_request.sh; \
echo "== tests/test_reconnect.sh"; sh tests/test_reconnect.sh; \
+10
View File
@@ -46,6 +46,16 @@ engine would be a second history. When a client disconnects in the middle of a t
cancels the turn (an approval nobody can answer would otherwise park the
engine forever) and accepts the next client.
A client that arrives while another is attached is told so at once: it is
accepted only to be sent
`{"ev":"error","reason":"attached","text":"another client is attached: ..."}`
and then closed, and `splinterctl` exits non-zero. The server answers the door
even in the middle of a turn, so a second `splinterctl --cmd /status` gets that
error instead of hanging in the listen backlog with no output at all - which
reads as a broken engine. A client that hears no greeting at all (an older
server) gives up after five seconds with a message rather than waiting for an
outer `timeout`.
## Sequence
```
+1
View File
@@ -21,6 +21,7 @@ ui.steer_queued_line = Steuerung eingereiht: %s
ui.steer_failed = Steuerung nicht angenommen (kein Turn laeuft)
ui.model_title = Modell
ui.open_busy = Sitzungswechsel geht nicht waehrend ein Turn laeuft; /open danach
ui.attach_busy = ein anderer Client haengt schon dran: eine Unterhaltung fuehrt einen Turn zur Zeit - die andere Verbindung schliessen, oder sie benutzen
ui.command_busy = nicht waehrend ein Turn laeuft; danach noch einmal
ui.model_filter = filter:
ui.model_hint = tippen filtert Pfeile bewegen Enter waehlt Esc bricht ab
+1
View File
@@ -20,6 +20,7 @@ ui.steer_queued_line = steering queued: %s
ui.steer_failed = steering not accepted (no turn is running)
ui.model_title = model
ui.open_busy = cannot switch sessions while a turn runs; /open after the turn
ui.attach_busy = another client is attached: one conversation runs one turn at a time - close the other connection, or use it
ui.command_busy = not while a turn runs; run it again after the turn
ui.model_filter = filter:
ui.model_hint = type to filter Up/Down move Enter selects Esc cancels
+1
View File
@@ -21,6 +21,7 @@ ui.steer_queued_line = direcionamento na fila: %s
ui.steer_failed = direcionamento nao aceito (nenhum turno em andamento)
ui.model_title = modelo
ui.open_busy = nao da para trocar de sessao durante um turno; /open depois
ui.attach_busy = outro cliente ja esta conectado: uma conversa roda um turno por vez - feche a outra conexao, ou use-a
ui.command_busy = nao durante um turno; rode de novo depois
ui.model_filter = filtro:
ui.model_hint = digite para filtrar setas movem Enter escolhe Esc cancela
+24
View File
@@ -17,6 +17,7 @@
* them its own way. See docs/PROTOCOL.md.
*/
#include <errno.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -42,6 +43,7 @@ struct client {
int failed;
int said_session;
int busy;
int greeted; /* the server has spoken at least once */
};
/* the same default as the server, without linking the server object */
@@ -282,6 +284,27 @@ wait_for(struct client *c)
nl = memchr(c->in.p, '\n', c->in.len);
if (nl == NULL) {
/*
* Until the first event arrives, wait five seconds and no
* longer: a server that is serving somebody else used to
* leave this client hanging in accept() with no output at
* all until an outer `timeout` fired (rc=124). An answer of
* "somebody is attached" is worth more than silence, and a
* server that is merely slow still has its turn's own time.
*/
if (!c->greeted) {
struct pollfd pfd;
pfd.fd = c->fd;
pfd.events = POLLIN;
pfd.revents = 0;
if (poll(&pfd, 1, 5000) == 0) {
fprintf(stderr, "splinterctl: no answer "
"from the server in 5 s - another "
"client may be attached\n");
return -1;
}
}
got = recv(c->fd, chunk, sizeof(chunk), 0);
if (got < 0) {
if (errno == EINTR)
@@ -292,6 +315,7 @@ wait_for(struct client *c)
return -1;
if (sp_buf_add(&c->in, chunk, (size_t)got) != 0)
return -1;
c->greeted = 1; /* the server is talking: its own clock now */
continue;
}
len = (size_t)(nl - c->in.p);
+98 -10
View File
@@ -811,9 +811,87 @@ abandon_turn(struct sp_engine *eng)
(void)sp_engine_wait(eng);
}
/* the whole life of one connected client */
/*
* One engine, one conversation, one writer - that part of the design is right
* and stays. What was wrong is what the second client got: nothing. It sat in
* the listen backlog while the first was served, was never read, and its
* splinterctl ran into a 20 s timeout with empty output (rc=124) - which reads
* like a broken engine, for commands as harmless as /status.
*
* So the server answers the door while it works. A second client that arrives
* is accepted only to be told, at once and in the protocol's own words, that
* somebody is attached already.
*/
static void
refuse_attached(int fd)
{
struct client c;
struct sp_buf b;
memset(&c, 0, sizeof(c));
c.fd = fd;
if (sp_buf_init(&b) != 0)
return;
ev_start(&b, "error");
ev_str(&b, "text", sp_t("ui.attach_busy"));
ev_str(&b, "reason", "attached");
sp_buf_puts(&b, "}");
(void)send_line(&c, &b);
sp_buf_free(&b);
/*
* Drain what the client already sent (a real front end asks for the
* commands and the history in its first breath). Closing a socket with
* unread input makes the kernel send RST, and an RST destroys the
* answer that is still in the client's receive buffer: `--attach`
* reported "no greeting" instead of the sentence just written.
*/
{
struct pollfd p = { fd, POLLIN, 0 };
char drain[4096];
int pr;
while ((pr = poll(&p, 1, 200)) > 0 && (p.revents & POLLIN)) {
if (recv(fd, drain, sizeof(drain), 0) <= 0)
break;
p.revents = 0;
}
}
}
static int same_user(int);
/*
* Answer the door while one client has the engine. Only a peer of this user is
* told why: a stranger's connection is closed without a word, exactly as the
* accept loop refuses it (see same_user).
*/
static void
take_waiting(int lfd)
{
if (lfd < 0)
return;
for (;;) {
int fd = accept(lfd, NULL, NULL);
if (fd < 0) {
if (errno == EINTR)
continue;
return;
}
(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
if (same_user(fd))
refuse_attached(fd);
close(fd);
}
}
/*
* The whole life of one connected client. `lfd` is the listening socket: it is
* polled alongside the client so a second client is told at once that it
* cannot attach (take_waiting), instead of waiting unseen in the backlog.
*/
static int
serve_client(struct proto *p, int fd)
serve_client(struct proto *p, int fd, int lfd)
{
struct client c;
int rc = 0, hup = 0;
@@ -832,24 +910,34 @@ serve_client(struct proto *p, int fd)
return -1;
}
while (!c.quit && !hup) {
struct pollfd pfd;
struct pollfd pfd[2];
int pr;
char chunk[4096];
ssize_t got;
struct sp_event ev;
pfd.fd = fd;
pfd.events = POLLIN;
pfd.revents = 0;
pr = poll(&pfd, 1, 100);
if (pr > 0 && (pfd.revents & (POLLERR | POLLNVAL)))
pfd[0].fd = fd;
pfd[0].events = POLLIN;
pfd[0].revents = 0;
pfd[1].fd = lfd;
pfd[1].events = POLLIN;
pfd[1].revents = 0;
pr = poll(pfd, lfd >= 0 ? 2 : 1, 100);
/*
* Somebody else wants in while this client has the engine. Answer
* the door before reading: the second client is waiting on its
* greeting and would otherwise be told nothing at all.
*/
if (pr > 0 && lfd >= 0 && (pfd[1].revents & POLLIN))
take_waiting(lfd);
if (pr > 0 && (pfd[0].revents & (POLLERR | POLLNVAL)))
break;
/*
* A hangup may come with the client's last command still in
* the socket: read until recv() says end of file, run the
* complete lines, then leave.
*/
if (pr > 0 && (pfd.revents & (POLLIN | POLLHUP))) {
if (pr > 0 && (pfd[0].revents & (POLLIN | POLLHUP))) {
got = recv(fd, chunk, sizeof(chunk), 0);
if (got < 0 && (errno == EINTR || errno == EAGAIN))
continue;
@@ -1081,7 +1169,7 @@ sp_proto_serve(const struct sp_proto_opts *opts, struct sp_buf *err)
close(fd);
continue;
}
(void)serve_client(&p, fd);
(void)serve_client(&p, fd, lfd);
close(fd);
if (p.eng == NULL || sp_engine_quit(p.eng))
break;
+11
View File
@@ -1004,6 +1004,17 @@ rem_greet(struct rem *r, struct sp_buf *err)
got_cmds = 1;
if (r->got_history)
got_history = 1;
if (!got_state && r->last.len > 0) {
/*
* The server said why it will not talk: "another
* client is attached" comes as an error event before
* anything else. Repeating "no greeting" would hide
* the one sentence the user needs.
*/
if (err != NULL)
sp_buf_puts(err, r->last.p);
return -1;
}
}
if (!got_state) {
if (err != NULL)
+135
View File
@@ -0,0 +1,135 @@
#!/bin/sh
#
# splinter -- --serve answers a second client instead of leaving it hanging.
#
# What it guards, as found: the protocol server serves one client at a time by
# design (docs/PROTOCOL.md), but a second `splinterctl` connected, sat in the
# accept() backlog and printed nothing at all - not even an error - until an
# outer `timeout` killed it (rc=124). A silent hang looks like a broken engine.
# Two answers are wanted and this test asks for both:
#
# * the server tells a second client at once that one conversation runs one
# turn at a time, and exits non-zero;
# * the first client keeps its connection and is not disturbed by that;
# * a server that never greets at all (an older build) cannot trap a client
# for longer than the greeting timeout.
#
# The first is the fix, the second is the regression it could cause, the third
# is the safety net for the version of the server the user already runs.
set -e
cd "$(dirname "$0")/.."
. "$(dirname "$0")/sh/port.sh"
SPLINTER=./splinter
CTL=./splinterctl
D=$(mktemp -d)
trap 'kill $SRV 2>/dev/null; rm -rf "$D"' EXIT INT TERM
fail() { echo "FAIL: $*" >&2; exit 1; }
pass() { echo "ok $*"; }
# The server's own default socket lives in $HOME; --serve takes no path.
export HOME="$D/home"
mkdir -p "$HOME/.splinter"
$SPLINTER --no-config --autonomous --serve --endpoint http://127.0.0.1:1/v1 \
--model m >"$D/serve.log" 2>&1 &
SRV=$!
SOCK="$HOME/.splinter/splinter.sock"
i=0
while [ "$i" -lt 100 ]; do
[ -S "$SOCK" ] && break
i=$((i + 1))
sleep 0.1
done
[ -S "$SOCK" ] || { cat "$D/serve.log" >&2; fail "the server did not create $SOCK"; }
# The first client holds the engine for as long as its socket stays open. A
# raw connection is enough: what the server sees is one attached client.
python3 - "$SOCK" <<'EOF' >"$D/c1.log" 2>&1 &
import socket, sys, time
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(sys.argv[1])
s.settimeout(0.5)
end = time.time() + 60
while time.time() < end:
try:
chunk = s.recv(4096)
if not chunk:
break
sys.stdout.write(chunk.decode("utf-8", "replace")); sys.stdout.flush()
except socket.timeout:
pass
EOF
C1=$!
sleep 0.7
grep -q '"ready"' "$D/c1.log" 2>/dev/null ||
fail "the first client never got a greeting: $(cat "$D/c1.log")"
pass "the first client is attached"
# The second client must be sent away with a reason, and quickly.
START=$(date +%s)
set +e
timeout 20 $CTL --socket "$SOCK" --cmd /status >"$D/c2.out" 2>"$D/c2.err"
RC=$?
set -e
TOOK=$(($(date +%s) - START))
[ "$RC" -ne 0 ] || fail "the second client exited 0 with the engine taken"
[ "$RC" -ne 124 ] || fail "the second client hung (rc=124) instead of being refused"
[ "$TOOK" -le 10 ] || fail "the second client took ${TOOK}s to hear 'no'"
grep -qi 'another client is attached' "$D/c2.err" ||
fail "no reason on stderr, got: $(cat "$D/c2.err")"
pass "the second client is refused at once with a reason (${TOOK}s, rc=$RC)"
# Being refused must not close the first client's connection.
kill -0 "$C1" 2>/dev/null || fail "the first client died when the second was refused"
[ -S "$SOCK" ] || fail "the server went away"
pass "the first client and the server survive the refusal"
# A real front end sends its greeting requests at once. The server used to
# close with that input unread, the kernel answered with RST, and the RST ate
# the explanation still sitting in the client's buffer: --attach printed
# "no greeting from the backend" instead of "another client is attached".
set +e
timeout 15 script -qec "$SPLINTER --no-config --attach --socket $SOCK" \
/dev/null >"$D/c4.log" 2>&1
set -e
grep -qi 'another client is attached' "$D/c4.log" ||
fail "--attach lost the reason, got: $(head -3 "$D/c4.log")"
pass "--attach as a second client reports why it cannot attach"
# The safety net: a server that accepts but never speaks must not trap us.
python3 - "$D/mute.sock" <<'EOF' &
import socket, sys, time
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.bind(sys.argv[1]); s.listen(4)
held = []
end = time.time() + 30
while time.time() < end:
try:
s.settimeout(1.0)
c, _ = s.accept()
held.append(c) # keep it open and say nothing
except Exception:
pass
EOF
MUTE=$!
sleep 0.5
START=$(date +%s)
set +e
timeout 30 $CTL --socket "$D/mute.sock" --cmd /status >"$D/c3.out" 2>"$D/c3.err"
RC=$?
set -e
TOOK=$(($(date +%s) - START))
kill $MUTE 2>/dev/null || true
[ "$RC" -ne 124 ] || fail "a mute server trapped the client past 30 s"
[ "$RC" -ne 0 ] || fail "a mute server made the client exit 0"
[ "$TOOK" -le 12 ] || fail "the greeting timeout let the client wait ${TOOK}s"
grep -qi 'no answer' "$D/c3.err" || fail "a mute server gave no message: $(cat "$D/c3.err")"
pass "a mute server ends the client in ${TOOK}s with a message"
echo "test_attach_busy: ok"