apex-twin 1.0.2: fix the empty-stdout flake at its root

The suite occasionally saw the stdio server exit rc=0 with normal startup on
stderr and no replies, and a one-shot retry hid it. It was not the server.

MarauderSim.close() set stop, slept 0.1 s and closed the PTY fds. The reader
thread holds the fd number, not a file object: if it was still inside
select([master]) - a 0.2 s timeout, so roughly half the time after a 0.1 s
sleep - the number was free. The next mkstemp() in run() reused it, select
reported the temp file readable, and the thread read and discarded the
subprocess payload. The child then saw EOF, exited 0 and answered nothing.
That is why every observed failure was the dry-run call, the only run() that
follows a simulator close without a new openpty() in between.

Reproduced outside the suite: copying the shipped class and the close-then-spawn
sequence gave 17 empty spawns in 60 rounds (28%), with the simulator buffer
holding exactly the 47-byte payload.

close() now joins the reader and prompter threads before closing the fds, and
the reader refuses to read once stop is set. tests/run.py repeats
close-then-spawn twelve times and asserts no thread survives and no spawn loses
its stdin; without the fix that is 12/12 threads alive and 6/12 spawns lost.
The retry is removed so empty stdout fails again.

No product-code change. 336 checks, analyze clean, release-check green
including distcheck 1.0.2.
This commit is contained in:
lotherk committed 2026-11-21 10:14:57 +00:00
1 parent fa8f258fb9
commit 12ef98f492
5 files changed
+102 -35

No files matched your search

+17 -1
View File
@@ -8,7 +8,23 @@ fields, and state from an older version is read by a newer one.
There are no git tags. The hash next to a version is the commit that introduced
it; the current entry is the commit that adds this section.
## 1.0.1 — 2026-11-21 — this change
## 1.0.2 — 2026-11-21 — this change
- Fixed the rare "empty stdout, rc=0" flake in the suite. Root cause was the
test harness, not the server: `MarauderSim.close()` freed the PTY fd numbers
while its reader thread might still be inside `select()`. The next `mkstemp()`
reused a number, the thread read and discarded the subprocess payload, and the
child saw EOF, exited 0 and answered nothing. Measured 28% per close-then-spawn
round, which matches the observed frequency and the fact that only the
dry-run call right after the last simulator close ever failed.
- `close()` now joins the reader and prompter threads before closing the fds;
the reader also refuses to touch the fd after `stop` is set.
- `tests/run.py` repeats close-then-spawn twelve times and asserts no thread is
left and no spawn loses its stdin. Without the fix: 12/12 threads alive and
6/12 spawns lost. The one-shot retry is removed, so empty stdout fails again.
- No product-code change; 45 tools, 336 checks.
## 1.0.1 — 2026-11-21 — fa8f258
- `tests/version_check.py` makes the five places that carry a version agree with
`APEX_VERSION`: the man page `.TH`, the README status line, the top CHANGELOG
+13 -4
View File
@@ -32,7 +32,7 @@ separate, explicitly armed switch.
```sh
make # apex-twin, ~239 kB static-ish binary, zero warnings under -Werror
make test # version check + gate audit + 334 end-to-end checks
make test # version check + gate audit + 336 end-to-end checks
make asan # apex-twin-asan with ASan + UBSan
make test-asan # the whole suite against the sanitizer binary
make version-check # the five places that carry a version must agree
@@ -384,7 +384,7 @@ finding and the next report no longer mentions it.
make test
```
334 checks, real binary, real DNS, real files written; no mocks. The suite was
336 checks, real binary, real DNS, real files written; no mocks. The suite was
seen red on purpose: with the "no scope" branch disabled by `if (0 && ...)`,
three checks fail, because they assert the *reason* and not merely that an error
came back — a gate that falls through to the next deny branch looks identical
@@ -414,8 +414,17 @@ A port is never assumed: an earlier version of the HTTP test used 18797, which o
this host is an SSH forward to another machine, and a foreign server answered
`{"serverInfo":{"name":"koder"}}` while the suite was green.
A rare empty-stdout flake in the suite was a bug in the test harness, not the
server: the PTY Marauder simulator closed its fd numbers while its reader thread
could still be inside `select()`, the next `mkstemp()` reused one, and the thread
consumed the subprocess's stdin — the child then saw EOF, exited 0 and answered
nothing. `MarauderSim.close()` now joins its threads before closing, and
`tests/run.py` repeats the close-then-spawn sequence twelve times as a
regression check (12/12 threads alive and 6/12 lost spawns were seen before the
fix). The retry that used to mask it is gone: empty stdout is a failure.
The suite is also run against `apex-twin-asan` (`make test-asan`), built with
`-fsanitize=address,undefined`. All 334 checks pass with no ASan or UBSan report,
`-fsanitize=address,undefined`. All 336 checks pass with no ASan or UBSan report,
and a separate batch of error paths, network captures and report generation was
run with leak detection on: no leaks. `make analyze` runs `gcc -fanalyzer` over
every translation unit; it was red first on `vendor/libmcp/mcp.h`, where
@@ -494,7 +503,7 @@ the copied scope reason is now bounded with a precision, not left to snprintf.
## Status
1.0.1. Built and run: 45 tools, 334 checks, 340 fuzz cases and 76.9% line
1.0.2. Built and run: 45 tools, 336 checks, 340 fuzz cases and 76.9% line
coverage. The loop closes: a probe captures the exchange as a pair, a finding
points at it, `finding_update` gives it a state, an asset records the host it
came from, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a
+1 -1
View File
@@ -1,5 +1,5 @@
.\" apex-twin.1 - manual page for APEX TWIN
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.0.1" "User Commands"
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.0.2" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.0.1"
#define APEX_VERSION "1.0.2"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+70 -28
View File
@@ -47,33 +47,26 @@ def run(msgs, home=None, extra_env=None):
if extra_env:
env.update(extra_env)
payload = ("\n".join(json.dumps(m) for m in msgs) + "\n").encode()
proc = None
for attempt in (1, 2):
# Feed stdin from a file, not a pipe: a pipe write that the child never
# sees would look like a silent exit. A clean exit with no output has
# been seen rarely under a full release-check; retry that case once,
# loudly. Non-zero exits are never retried.
fd, in_path = tempfile.mkstemp(prefix="apex-stdin-")
# Feed stdin from a file rather than a pipe. Empty stdout is a failure, not
# a retry: it once meant a stray thread in this process had eaten the
# payload (see the simulator-close regression test).
fd, in_path = tempfile.mkstemp(prefix="apex-stdin-")
try:
off = 0
while off < len(payload):
n = os.write(fd, payload[off:])
if n <= 0:
break
off += n
os.lseek(fd, 0, os.SEEK_SET)
proc = subprocess.run([BIN], stdin=fd, capture_output=True,
text=True, env=env, timeout=180)
finally:
os.close(fd)
try:
off = 0
while off < len(payload):
n = os.write(fd, payload[off:])
if n <= 0:
break
off += n
os.lseek(fd, 0, os.SEEK_SET)
proc = subprocess.run([BIN], stdin=fd, capture_output=True,
text=True, env=env, timeout=180)
finally:
os.close(fd)
try:
os.unlink(in_path)
except OSError:
pass
if proc.stdout.strip() or proc.returncode != 0:
break
sys.stderr.write("run: empty stdout on attempt %d (rc=0), retrying\n" %
attempt)
os.unlink(in_path)
except OSError:
pass
if not proc.stdout.strip():
sys.stderr.write("run: empty stdout (rc=%r, stderr=%r)\n" %
(proc.returncode, proc.stderr[:400]))
@@ -1134,11 +1127,14 @@ class MarauderSim:
self.stop = False
self.thread = threading.Thread(target=self._run, daemon=True)
self.thread.start()
self.prompt_thread = None
if console:
# A real console prints its prompt on its own; send it repeatedly
# until the first command arrives so a slow thread start cannot make
# the guard see silence and assume a radio.
threading.Thread(target=self._prompt, daemon=True).start()
self.prompt_thread = threading.Thread(target=self._prompt,
daemon=True)
self.prompt_thread.start()
def _prompt(self):
while not self.stop:
@@ -1185,6 +1181,8 @@ class MarauderSim:
break
if not ready:
continue
if self.stop:
break
try:
data = os.read(self.master, 4096)
except OSError:
@@ -1197,13 +1195,21 @@ class MarauderSim:
self._handle(line.strip(b"\r").decode("utf-8", "replace").strip())
def close(self):
# Join first, close second. The threads hold the fd number, not a file
# object: closing while a thread is still inside select() frees a number
# the next mkstemp() can reuse, and the thread then reads (and eats) a
# subprocess's stdin. That is the "empty stdout, rc=0" flake.
self.stop = True
time.sleep(0.1)
for t in (self.thread, self.prompt_thread):
if t is not None and t is not threading.current_thread():
t.join(timeout=2.0)
for fd in (self.master, self.slave):
try:
os.close(fd)
except OSError:
pass
self.master = -1
self.slave = -1
sim = MarauderSim()
@@ -1268,6 +1274,42 @@ check("the transmitting command reached the radio", "attack" in sent, sent)
tx_sim.close()
shutil.rmtree(tx_home, ignore_errors=True)
print("\n== simulator close and the next spawn ==")
# Regression for the empty-stdout flake: close() used to free the pty fd
# numbers while the reader thread might still be inside select() on them. The
# next mkstemp() reused a number, the thread read and discarded the payload,
# and the child saw EOF: rc=0, normal startup, no replies. Twelve rounds make
# the old race show up essentially every run (28% per round was measured).
race_home = tempfile.mkdtemp(prefix="apex-race-")
write_scope(race_home, {"label": "race", "expires": "2099-12-31T23:59:59Z",
"allow_ip": ["192.0.2.0/24"]})
late_threads = 0
lost_outputs = 0
race_payload = b'{"jsonrpc":"2.0","id":1,"method":"tools/list"}\n'
for _ in range(12):
race_sim = MarauderSim()
race_sim.close()
if race_sim.thread.is_alive():
late_threads += 1
fd, in_path = tempfile.mkstemp(prefix="apex-race-stdin-")
try:
os.write(fd, race_payload)
os.lseek(fd, 0, os.SEEK_SET)
renv = dict(os.environ)
renv["APEX_HOME"] = race_home
raced = subprocess.run([BIN], stdin=fd, capture_output=True, text=True,
env=renv, timeout=30)
finally:
os.close(fd)
os.unlink(in_path)
if not raced.stdout.strip():
lost_outputs += 1
check("a closed simulator leaves no reader thread alive", late_threads == 0,
"%d of 12" % late_threads)
check("a spawn right after a simulator close still gets its stdin",
lost_outputs == 0, "%d of 12 lost" % lost_outputs)
shutil.rmtree(race_home, ignore_errors=True)
print("\n== dry run and dns ==")
res, _ = run([
call(1, "nmap", target="192.0.2.5", profile="quick"),