Skip to content

Pass pipeline pipes over a socket instead of named FIFOs (macOS hang) - #154

Open
ibirol wants to merge 1 commit into
masterfrom
macos-fifo-eof-hang
Open

ibirol wants to merge 1 commit into
masterfrom
macos-fifo-eof-hang

Conversation

@ibirol

@ibirol ibirol commented Oct 28, 2026 •

Copy link
Copy Markdown

Problem

On macOS, a process reading a ProcessPipeline's output through its named FIFO can block forever in its final read() after the command has exited. The read should return end of file, but it never does. Every DataSource/DataSink goes through the pipeline, even a plain cat file, so SeqReader and SeqWriter can hang too.

In GoldRush this stalls GoldPolish's reaper. Each later batch then leaves a blocked goldpolish-hold process and its spawner, until the per-user process limit (4,000 on macOS) stops all forks. Two chr20 HG002 runs failed this way, after batches 2,052 and 3,015 of about 4,500.

Cause

The fault is in macOS's named pipes, not in btllib's logic. A pure C program that copies btllib's FIFO setup and reads the way SeqReader does (a 16 KiB fread, then fgetc/ungetc and two getline calls per record) hangs within a few thousand iterations:

  • A read() trace shows the first end-of-file read is the one that never returns.
  • By then cat has exited, and no process holds the write end.

The same program with anonymous pipes ran 120,000 iterations without hanging. Ruled out: close-on-exec on the user side, the spawner's SIGCHLD handling, and Python, since a C++ loop hangs too.

Change

The spawner creates anonymous pipes and passes the user process its ends over a Unix socket pair (SCM_RIGHTS). The FIFO paths, the prefix logic for them (/dev/shm, TMPDIR, /tmp) and their cleanup are removed. Pipe ends are close-on-exec in both processes.

Testing

All on macOS 27.0.1, Apple M5, against master at da1e843:

  • meson test --repeat=5: 100 of 100 pass.
  • C++ loop through SeqReader: before, 8 of 8 copies stalled within 60 s. After, 8 copies × 50,000 iterations ran without a stall.
  • Python loop copying GoldPolish's reaper: before, 3 of 4 copies hung within 10,000 iterations. After, 4 × 10,000 ran clean.
  • GoldRush on chr20 HG002 ONT data: completed on two read sets, with outputs byte-identical across runs. For the full benchmark this also needed the GoldPolish fix linked below.
  • Formatting: clang-format 18 clean.

Not tested on Linux, where the FIFO path never showed the fault. The change removes FIFO-specific code from all platforms, so a Linux CI run is worth checking.

This is separate from #153 (setpgid race); either can merge first.

Related: BirolLab/goldpolish has the same fault in its own named pipes and is fixed separately in BirolLab/goldpolish#36.

Pure C reproducer (run with FIFO_EOF_FASTA=1 ./fifo_eof file.fa 10000)
// Minimal copy of btllib's ProcessPipeline FIFO handshake (READ op: "cat <file>").
// A long-lived spawner process creates two FIFOs per command (child stdin, child stdout),
// both sides open them O_NONBLOCK then switch to blocking, the spawner forks the child
// (cat), and the user side reads the child's stdout to EOF with fgetc in a worker thread.
// The main thread waits up to TIMEOUT_S for EOF; if it does not arrive, report and stop.
//
// Usage: fifo_eof <file> <iterations>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#define TIMEOUT_S 20

static int u2s[2], s2u[2]; // user->spawner, spawner->user
static const char *g_file;

static void xw(int fd, const void *b, size_t n) { if (write(fd, b, n) != (ssize_t)n) { perror("write"); exit(1); } }
static void xr(int fd, void *b, size_t n) { size_t g = 0; while (g < n) { ssize_t r = read(fd, (char *)b + g, n - g); if (r <= 0) { perror("read"); exit(1); } g += r; } }
static void setblock(int fd) { int f = fcntl(fd, F_GETFL); fcntl(fd, F_SETFL, f & ~O_NONBLOCK); }

static void spawner(void) {
  long id = 0;
  char c = 0;
  for (;;) {
    xr(u2s[0], &c, 1); // request
    if (c == 'q') _exit(0);
    if (c == 'w') {
      char wp[256]; snprintf(wp, sizeof wp, "%s/fifo_eof-%d-w", getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp", getpid());
      unlink(wp); mkfifo(wp, 0600);
      int rfd = open(wp, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
      xw(s2u[1], wp, sizeof wp);
      xr(u2s[0], &c, 1); // user opened write end
      unlink(wp); setblock(rfd);
      pid_t wpid = fork();
      if (wpid == 0) { dup2(rfd, 0); int o = open(getenv("FIFO_EOF_OUT") ? getenv("FIFO_EOF_OUT") : "/dev/null", O_WRONLY | O_CREAT | O_TRUNC, 0600); dup2(o, 1); close(o); execlp("cat", "cat", (char *)NULL); _exit(127); }
      close(rfd);
      continue;
    }
    char path[2][256];
    int fd[2];
    const int flags[2] = {O_RDONLY, O_WRONLY}; // spawner: child's stdin (read), child's stdout (write)
    for (int i = 0; i < 2; i++) {
      snprintf(path[i], sizeof path[i], "%s/fifo_eof-%d-%ld", getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp", getpid(), id++);
      unlink(path[i]);
      if (mkfifo(path[i], 0600)) { perror("mkfifo"); exit(1); }
      xw(s2u[1], path[i], sizeof path[i]);
      if (i > 0) xr(u2s[0], &c, 1); // user opened read end first
      fd[i] = open(path[i], flags[i] | O_NONBLOCK | O_CLOEXEC);
      if (fd[i] < 0) { perror("spawner open"); exit(1); }
      xw(s2u[1], &c, 1);
      if (i == 0) xr(u2s[0], &c, 1);
      unlink(path[i]);
      setblock(fd[i]);
      xw(s2u[1], &c, 1);
    }
    pid_t pid = fork();
    if (pid == 0) {
      dup2(fd[0], 0); dup2(fd[1], 1);
      close(fd[0]); close(fd[1]);
      execlp("cat", "cat", g_file, (char *)NULL);
      _exit(127);
    }
    close(fd[0]); close(fd[1]);
    xw(s2u[1], &pid, sizeof pid);
    int st; waitpid(pid, &st, 0);
  }
}

// Trace of read() results for the current iteration (funopen wrapper around the FIFO fd).
static char trace[4096]; static volatile int tlen;
static int traced_read(void *cookie, char *b, int n) {
  int fd = (int)(long)cookie;
  if (tlen < 4000) tlen += snprintf(trace + tlen, sizeof trace - tlen, " >%d", n);
  ssize_t r = read(fd, b, n);
  if (tlen < 4000) tlen += snprintf(trace + tlen, sizeof trace - tlen, "=%zd", r);
  return (int)r;
}
static int traced_close(void *cookie) { return close((int)(long)cookie); }
struct job { FILE *f; long bytes; int done; pthread_mutex_t m; pthread_cond_t cv; };

static void *reader(void *a) {
  struct job *j = a;
  tlen = 0; trace[0] = 0;
  int ch;
  long n = 0;
  if (getenv("FIFO_EOF_STOPAT")) { // GoldPolish fix: raw read() until the data ends with "\nx\n"; never an EOF read
    static __thread char buf[16384]; char tail[3] = {0, 0, 0}; int fd = fileno(j->f);
    for (;;) {
      ssize_t r = read(fd, buf, sizeof buf);
      if (r <= 0) break;
      n += r;
      for (ssize_t i = 0; i < r; i++) { tail[0] = tail[1]; tail[1] = tail[2]; tail[2] = buf[i]; }
      if (tail[0] == '\n' && tail[1] == 'x' && tail[2] == '\n') break;
    }
  } else if (getenv("FIFO_EOF_FASTA")) { // btllib SeqReader: initial fread into a 16 KiB buffer, then the FASTA module loop
    static __thread char buf[16384]; size_t got = 0;
    do { got += fread(buf + got, 1, sizeof buf - got, j->f); } while (got < sizeof buf && !feof(j->f));
    n += got;
    char *line = NULL; size_t cap = 0; ssize_t len;
    for (;;) {
      ch = fgetc(j->f); if (ch == EOF) break; ungetc(ch, j->f);
      if ((len = getline(&line, &cap, j->f)) > 0) n += len;
      if ((len = getline(&line, &cap, j->f)) > 0) n += len;
    }
    free(line);
  } else {
    while ((ch = fgetc(j->f)) != EOF) n++;
  }
  if (getenv("FIFO_EOF_TRACE_ALL")) printf("trace:%s\n", trace);
  { int zeros = 0; for (char *p = trace; (p = strstr(p, "=0")); p++) if (p[2] == ' ' || p[2] == 0) zeros++;
    if (zeros > 1) { printf("MULTI-EOF trace:%s\n", trace); fflush(stdout); } }
  pthread_mutex_lock(&j->m); j->bytes = n; j->done = 1; pthread_cond_signal(&j->cv); pthread_mutex_unlock(&j->m);
  return NULL;
}

int main(int argc, char **argv) {
  g_file = argv[1];
  long iters = atol(argv[2]);
  struct stat sb; stat(g_file, &sb);
  if (pipe(u2s) || pipe(s2u)) { perror("pipe"); return 1; }
  pid_t sp = fork();
  if (sp == 0) { close(u2s[1]); close(s2u[0]); spawner(); }
  close(u2s[0]); close(s2u[1]);
  FILE *wf = NULL;
  if (getenv("FIFO_EOF_WRITER")) {
    char c = 'w', wp[256];
    xw(u2s[1], &c, 1);
    xr(s2u[0], wp, sizeof wp);
    int wfd = open(wp, O_WRONLY | O_NONBLOCK);
    if (wfd < 0) { perror("writer open"); return 1; }
    setblock(wfd);
    xw(u2s[1], &c, 1);
    wf = fdopen(wfd, "w");
  }
  static char payload[60015]; memset(payload, 'A', sizeof payload);
  for (long it = 0; it < iters; it++) {
    char c = 'r', path[256];
    int fd[2];
    const int flags[2] = {O_WRONLY, O_RDONLY}; // user: child's stdin (write), child's stdout (read)
    xw(u2s[1], &c, 1);
    for (int i = 0; i < 2; i++) {
      xr(s2u[0], path, sizeof path);
      if (i == 0) xr(s2u[0], &c, 1); // spawner opened read end first
      fd[i] = open(path, flags[i] | O_NONBLOCK); // as btllib: no O_CLOEXEC on the user side
      if (fd[i] < 0) { fprintf(stderr, "user open %s: %s\n", path, strerror(errno)); return 1; }
      xw(u2s[1], &c, 1);
      if (i > 0) xr(s2u[0], &c, 1);
      setblock(fd[i]);
      xr(s2u[0], &c, 1);
    }
    pid_t child; xr(s2u[0], &child, sizeof child);
    struct job j = {getenv("FIFO_EOF_TRACE") ? funopen((void *)(long)fd[1], traced_read, NULL, NULL, traced_close) : fdopen(fd[1], "r"), 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
    pthread_t th; pthread_create(&th, NULL, reader, &j);
    if (wf) { fwrite(payload, 1, sizeof payload, wf); }
    struct timespec dl; clock_gettime(CLOCK_REALTIME, &dl); dl.tv_sec += TIMEOUT_S;
    pthread_mutex_lock(&j.m);
    while (!j.done) if (pthread_cond_timedwait(&j.cv, &j.m, &dl) == ETIMEDOUT) break;
    int done = j.done;
    pthread_mutex_unlock(&j.m);
    if (!done) {
      printf("trace so far:%s\n", trace);
      printf("HANG pid=%d iteration=%ld child=%d (expected %lld bytes; reader fd %d)\n", getpid(), it, child, (long long)sb.st_size, fd[1]);
      fflush(stdout);
      char cmd[256]; snprintf(cmd, sizeof cmd, "lsof -p %d 2>/dev/null | grep -E 'FIFO|PIPE'; ps -o pid,ppid,stat,command -p %d", getpid(), child);
      system(cmd);
      fflush(stdout);
      pause(); // keep the evidence
    }
    pthread_join(th, NULL);
    if (j.bytes != sb.st_size) { printf("SHORT iteration=%ld got %ld\n", it, j.bytes); }
    fclose(j.f);
    close(fd[0]);
  }
  char q = 'q'; xw(u2s[1], &q, 1);
  printf("pid %d: %ld iterations, no hang\n", getpid(), iters);
  return 0;
}

🤖 Generated with Claude Code

On macOS, a process reading a pipeline's output through a named FIFO can
block forever after the command has exited, instead of reading EOF. The
spawner now creates anonymous pipes and hands the user process its ends
over a Unix socket pair (SCM_RIGHTS). The FIFO paths, their prefix logic
(/dev/shm, TMPDIR, /tmp) and their cleanup are removed. Pipe ends in both
processes are close-on-exec.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ibirol

ibirol commented Oct 29, 2026

Copy link
Copy Markdown
Author

CI note: the Linux job failed before building anything. In "Install dependencies", mamba install crashed with a segmentation fault (build 12106, log 13), so meson was missing in the next step. The macOS job passed (build, clang-format, tests). This needs a rerun of the Linux job, which I'm requesting below.

@ibirol

ibirol commented Oct 29, 2026

Copy link
Copy Markdown
Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@ibirol

ibirol commented Oct 29, 2026

Copy link
Copy Markdown
Author

The rerun (build 12109) hit the same mamba install segmentation fault on Linux before building; macOS passed again. All three Linux attempts today crashed at that step, while #153's Linux job passed earlier, so the CI image or mamba version seems to have changed. It's unrelated to this diff.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants