: asapien/signet

commit f708d591726d6b8c73d79116bb3640097c3f6600
parent 3b5ff3eb128543ebd6e04c7e5e5639f208b65b64
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Thu, 12 Nov 2026 19:51:15 +0530

Integrate shared command deadlines and child cleanup
9 files changed, 461 insertions(+), 42 deletions(-)
M
.scratch/roadmap/ticket-14.md
|
47
+++++++++++++++++++++++++++++++++++++++++++----
M
HANDOFF.md
|
15
+++++++++------
M
README.md
|
6
++++++
M
src/util.c
|
168
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
M
src/util.h
|
9
++++++---
A
test/command-contract.c
|
205
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
test/command-contract.sh
|
11
+++++++++++
M
test/e2e.sh
|
4
++++
M
test/render-contract.sh
|
38
+++++++++++++++++++++++++++++++++++++-
diff --git a/.scratch/roadmap/ticket-14.md b/.scratch/roadmap/ticket-14.md
@@ -47,15 +47,54 @@ Fresh image signet-roadmap-guards, container of the same name on :8084:
   /tmp/signet-ticket14-{browser,progress}/. Host is Darwin, Git remote absent and
   gh unavailable. No proxy/native production checks or publication were performed.
 
+### Bounded external commands
+
+The shared run_cmd now applies a30-second monotonic wall deadline to every
+pdfinfo/qpdf call, with or without captured output. Nonblocking bounded reads
+keep silent, closed-stdout and flooding children from defeating the deadline.
+Each command owns a process group, killed before the direct child is reaped;
+WNOWAIT plus temporary SIGCHLD blocking prevents PGID/PID reuse during cleanup.
+Exit status must still be0; timeout returns ETIMEDOUT and logs stderr/LOCAL0.
+Linux PR_SET_PDEATHSIG kills the direct exec child if the API/worker dies,
+including the setup race. No shell, watchdog process or new dependency is used.
+
+This is NOT CPU/RSS/I/O containment. A daemon escaping its process group, or
+an orphaned grandchild after caller SIGKILL, still needs service-level controls.
+Linux direct-child death protection and timeout/normal-exit group cleanup are
+tested; do not generalise that into native OpenRC/coexistence certification.
+
+Retained test/command-contract.{c,sh} exercises truncated/one-byte/invalid output
+buffers, nonzero/signalled/missing exec, flood/silence/early stdout close,
+background descendants, interrupted waits, SIGCHLD mask restoration and the
+ignored-SIGCHLD ownership failure. Linux adds subreaper-backed assertions and
+actual caller SIGKILL/direct-child death. The unit-only build uses500ms; installed
+apps use30s, verified by an actual hung qpdf in render-contract.sh. Its killed
+child is reaped, STAMP_FAILED committed before queue drain, and retry succeeds
+with identical proof/stamped bytes.
+
+Latest image/container signet-command-final on :8086:
+
+- /tmp/signet-ticket14-command-build.log: clean -Wall -Wextra, no warnings/errors.
+- /tmp/signet-ticket14-command-e2e.log: standalone Linux command checks plus full
+  identity/API/snapshot tests pass. command-mac.log covers portable unit paths.
+- /tmp/signet-ticket14-command-render.log: actual30s hang/reap/retry and all
+  existing replay/release/enrolment contracts pass.
+- /tmp/signet-ticket14-command-{browser,progress}.log: real browser suites pass;
+  evidence directories use the same prefixes, rendering maths unchanged.
+- /tmp/signet-ticket14-command-rss-summary.txt: approximately31,800KB aggregate
+  app RSS maximum across1,370samples during those fixture suites. Same scope,
+  exclusions, rounding/sampling and non-certification limits as above.
+- Image ID: /tmp/signet-ticket14-command-image.txt. No production services touched.
+
 ## Unfinished technical acceptance (must not be checked off)
 
 - Real trusted-header overwrite/spoof prevention, missing identity, authenticated
   roles for both APIs and blocked direct-backend access.
 - Approved DAM writer enforcement; production PIM authorization.
-- Concurrent buffered upload containment (current API cap32MiB), bounded rendering
-  children/deadlines and timeout/crash recovery. run_cmd currently has no child
-  timeout/resource limits. The new streamed frozen-input cap alone does not bound
-  decoded image/font memory, upload concurrency or total child RSS.
+- Concurrent buffered upload containment (current API cap32MiB), decoded
+  image/font memory and total child RSS/CPU/I/O. The command deadline above
+  protects hung external commands, not in-process parsing/rendering or whole
+  service trees on crash. Service-level containment/native recovery remains open.
 - Audit other metadata/PIM/placement parse paths and aggregate buffering; the
   save/submit clone guard above is not a whole-runtime memory bound. Oversized
   ignored/client-value fields originally amplified snapshot heap use despite the
diff --git a/HANDOFF.md b/HANDOFF.md
@@ -107,7 +107,8 @@ unrelated changes; inspect `git status` for the live inventory.
 
 ```
 src/conf.[ch]      key = value config, inline "# comments", group-list helpers
-src/util.[ch]      run_cmd (fork/execvp, strict exit), SHA-256, file helpers,
+src/util.[ch]      run_cmd (30s deadline, process-group cleanup, strict exit),
+                   Linux direct-child parent-death safeguard, SHA-256, files,
                    is_uuid / is_safe_name / is_safe_relpath, utf8_next
 src/db.[ch]        lazy PG + Redis connections, db_q / db_do
 src/ttf.[ch]       bounds-checked TrueType reader: cmap 4/12, hmtx, metrics

@@ -308,9 +309,11 @@ The implementation scopes and acceptance criteria are in
    See `.scratch/roadmap/ticket-13.md`. Proxy trust remains ticket 14.
 5. **Ticket14 incomplete, before production:** verify trusted proxy identity,
    decide DAM writer policy and complete runtime/native Alpine/OpenRC acceptance.
-   First local guard limits save/submit JSON before parse/clone (including legacy
-   multibyte rows); fixture suites/browser pass. This does not bound HTTP upload
-   buffering, other parse paths, decoded images or child lifetime/resources.
+   Local guards limit save/submit JSON before parse/clone and bound external
+   commands to30s with group cleanup/Linux direct-child parent-death protection;
+   unit, actual hang/retry, fixture suites and browser checks pass. HTTP buffering,
+   other parse paths, decoded assets and aggregate/service-level resources remain
+   unbounded by those guards and require further work.
    Owner inputs, remaining work and evidence: `.scratch/roadmap/ticket-14.md`.
    Keep provider-specific auth experiments separate from application work.
 6. Later: font-list validation and document-list pagination/search.

@@ -320,8 +323,8 @@ historical completed tickets do not substitute for fresh evidence.
 
 ## 8. Dev environment facts
 
-* Latest isolated verification: image/container `signet-roadmap-guards` on :8084;
-  ticket12 stack `signet-roadmap-review` remains on :8082, ticket11 on :8080.
+* Latest isolated verification: image/container `signet-command-final` on :8086;
+  metadata-guard stack on :8084, ticket12 on :8082, ticket11 on :8080.
   Throw-away DBs and explicit identities; no production/maa-1 services changed.
   Fixture RSS samples do not certify native peak resource safety.
 * Podman machine `podman-machine-default` (2 CPU / 2 GB / 20 GB) was created
diff --git a/README.md b/README.md
@@ -169,6 +169,12 @@ identity headers; never run them against production.
   submit also rejects stored layout/route exceeding1MiB before snapshot cloning.
   This is independent of the32MiB PDF-upload limit and is not a whole-runtime
   memory bound.
+* **External commands have a deadline.** pdfinfo/qpdf must finish within30s;
+  timeout kills the command group. Worker jobs record a retryable render failure;
+  API PDF validation fails without accepting the upload.
+  Linux also kills the direct command child when its API/worker caller dies.
+  This is not a memory/CPU quota or whole-service crash-containment guarantee.
+  `sh test/command-contract.sh` runs the standalone development regression.
 * **Resource/deployment acceptance remains open.** Fixture RSS is not a native
   peak-load certificate. Concurrent buffered uploads, rendering children,
   image/font decoding and shared database impact require containment/measurement
diff --git a/src/util.c b/src/util.c
@@ -1,76 +1,188 @@
+#ifdef __linux__
+#include <sys/prctl.h>
+#endif
 #include <sys/stat.h>
 #include <sys/wait.h>
 
 #include <ctype.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <poll.h>
+#include <signal.h>
 #include <stdarg.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <syslog.h>
+#include <time.h>
 #include <unistd.h>
 
 #include "util.h"
 #include "../vendor/sha256.h"
 
+/* Overridden only by the standalone regression build, never by request/env. */
+#ifndef SIGNET_CMD_TIMEOUT_MS
+#define SIGNET_CMD_TIMEOUT_MS 30000
+#endif
+
+static int64_t
+monotonic_ms(void)
+{
+	struct timespec ts;
+
+	if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
+		return -1;
+	return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+}
+
 int
 run_cmd(char *const argv[], char *out, size_t outsz)
 {
-	int pfd[2] = { -1, -1 }, status, devnull;
-	pid_t pid;
+	int pfd[2] = { -1, -1 }, status, devnull, saved, exited = 0;
+	int64_t now, deadline;
+	pid_t pid, parent = getpid();
+	sigset_t blocked, oldmask;
+	siginfo_t info;
+	struct pollfd pollfd;
 	size_t used = 0;
 	ssize_t n;
-	char sink[512];
+	char sink[4096];
 
-	if (out != NULL && pipe(pfd) == -1)
+	if (argv == NULL || argv[0] == NULL || (out != NULL && outsz == 0)) {
+		errno = EINVAL;
 		return -1;
-	if ((pid = fork()) == -1) {
-		if (out != NULL) {
+	}
+	if (out != NULL)
+		out[0] = '\0';
+	if ((now = monotonic_ms()) == -1)
+		return -1;
+	deadline = now + SIGNET_CMD_TIMEOUT_MS;
+	if (out != NULL) {
+		if (pipe(pfd) == -1)
+			return -1;
+		if (fcntl(pfd[0], F_SETFL, O_NONBLOCK) == -1) {
 			close(pfd[0]);
 			close(pfd[1]);
+			return -1;
 		}
-		return -1;
 	}
-	if (pid == 0) {
-		if ((devnull = open("/dev/null", O_RDWR)) != -1) {
-			dup2(devnull, STDIN_FILENO);
-			if (out == NULL)
-				dup2(devnull, STDOUT_FILENO);
-		}
+	/* Keep ownership of the zombie/PGID until cleanup, even with CGI handlers. */
+	sigemptyset(&blocked);
+	sigaddset(&blocked, SIGCHLD);
+	if (sigprocmask(SIG_BLOCK, &blocked, &oldmask) == -1) {
 		if (out != NULL) {
-			dup2(pfd[1], STDOUT_FILENO);
 			close(pfd[0]);
 			close(pfd[1]);
 		}
+		return -1;
+	}
+	if ((pid = fork()) == 0) {
+		if (setpgid(0, 0) == -1)
+			_exit(127);
+#ifdef __linux__
+		/* Real qpdf/pdfinfo must not outlive a killed API/worker. */
+		if (prctl(PR_SET_PDEATHSIG, SIGKILL) == -1 || getppid() != parent)
+			_exit(127);
+#else
+		(void)parent;
+#endif
+		if (sigprocmask(SIG_SETMASK, &oldmask, NULL) == -1 ||
+		    (devnull = open("/dev/null", O_RDWR)) == -1 ||
+		    dup2(devnull, STDIN_FILENO) == -1 ||
+		    dup2(out != NULL ? pfd[1] : devnull, STDOUT_FILENO) == -1)
+			_exit(127);
+		if (devnull > STDERR_FILENO)
+			close(devnull);
+		if (out != NULL) {
+			if (pfd[0] > STDERR_FILENO)
+				close(pfd[0]);
+			if (pfd[1] > STDERR_FILENO)
+				close(pfd[1]);
+		}
 		execvp(argv[0], argv);
 		_exit(127);
 	}
-	if (out != NULL) {
+	if (out != NULL)
 		close(pfd[1]);
-		for (;;) {
+	if (pid == -1)
+		goto fail;
+	/* Close the fork/setup race before a very short deadline can expire. */
+	if (setpgid(pid, pid) == -1 && errno != EACCES && errno != ESRCH)
+		goto fail;
+	for (;;) {
+		if ((now = monotonic_ms()) == -1)
+			goto fail;
+		if (now >= deadline) {
+			errno = ETIMEDOUT;
+			goto fail;
+		}
+		memset(&info, 0, sizeof(info));
+		if (!exited && waitid(P_PID, pid, &info,
+		    WEXITED | WNOHANG | WNOWAIT) == -1) {
+			if (errno == EINTR)
+				continue;
+			if (errno == ECHILD)
+				pid = -1; /* Never signal a PID no longer owned by us. */
+			goto fail;
+		}
+		if (!exited && info.si_pid == pid) {
+			exited = 1;
+			/* A background descendant must not keep stdout (or work) alive. */
+			kill(-pid, SIGKILL);
+		}
+		if (pfd[0] != -1) {
+			/* One bounded read per iteration: a flood cannot starve the clock. */
 			if (used + 1 < outsz)
-				n = read(pfd[0], out + used, outsz - 1 - used);
+				n = read(pfd[0], out + used,
+				    outsz - 1 - used < sizeof(sink) ?
+				    outsz - 1 - used : sizeof(sink));
 			else
 				n = read(pfd[0], sink, sizeof(sink));
-			if (n == -1 && errno == EINTR)
-				continue;
-			if (n <= 0)
-				break;
-			if (used + 1 < outsz)
+			if (n > 0 && used + 1 < outsz) {
 				used += (size_t)n;
+				out[used] = '\0';
+			} else if (n == 0) {
+				close(pfd[0]);
+				pfd[0] = -1;
+			} else if (n == -1 && errno != EAGAIN && errno != EINTR)
+				goto fail;
 		}
-		out[used] = '\0';
-		close(pfd[0]);
+		if (exited && pfd[0] == -1)
+			break;
+		pollfd.fd = pfd[0];
+		pollfd.events = POLLIN;
+		if (poll(&pollfd, 1, deadline - now < 20 ?
+		    (int)(deadline - now) : 20) == -1 && errno != EINTR)
+			goto fail;
 	}
-	while (waitpid(pid, &status, 0) == -1)
-		if (errno != EINTR)
-			return -1;
+	while (waitpid(pid, &status, 0) == -1) {
+		if (errno == EINTR)
+			continue;
+		if (errno == ECHILD)
+			pid = -1;
+		goto fail;
+	}
+	sigprocmask(SIG_SETMASK, &oldmask, NULL);
 	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
-		fprintf(stderr, "signet: %s failed (status 0x%x)\n", argv[0], status);
+		log_err("command %s failed (status 0x%x)", argv[0], status);
+		errno = EIO;
 		return -1;
 	}
 	return 0;
+fail:
+	saved = errno;
+	if (pid > 0) {
+		kill(-pid, SIGKILL);
+		kill(pid, SIGKILL);
+		while (waitpid(pid, &status, 0) == -1 && errno == EINTR)
+			;
+	}
+	if (pfd[0] != -1)
+		close(pfd[0]);
+	sigprocmask(SIG_SETMASK, &oldmask, NULL);
+	log_err("command %s failed: %s", argv[0], strerror(saved));
+	errno = saved;
+	return -1;
 }
 
 /* --- SHA-256 (vendored) ------------------------------------------------ */
diff --git a/src/util.h b/src/util.h
@@ -5,9 +5,12 @@
 #include <stdint.h>
 
 /*
- * fork/execvp `argv`, wait, and require exit status 0.
- * If `out` is non-NULL, the child's stdout is captured (NUL-terminated,
- * truncated to outsz-1).  Returns 0 on success, -1 on any failure.
+ * fork/execvp `argv`, require exit status 0 within 30 seconds (monotonic).
+ * Kill the command process group before reaping; Linux also kills the direct
+ * child if its caller dies. Escaped groups/crash-orphaned grandchildren still
+ * require service-level containment; this is not an RSS limit.
+ * If `out` is non-NULL, outsz must be positive; stdout is NUL-terminated and
+ * truncated to outsz-1. Returns 0 on success, -1 on failure (timeout: ETIMEDOUT).
  */
 int run_cmd(char *const argv[], char *out, size_t outsz);
 
diff --git a/test/command-contract.c b/test/command-contract.c
@@ -0,0 +1,205 @@
+#ifdef __linux__
+#include <sys/prctl.h>
+#endif
+#include <sys/time.h>
+#include <sys/wait.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "util.h"
+
+static volatile sig_atomic_t interrupted;
+
+static void
+interrupt(int sig)
+{
+	(void)sig;
+	interrupted++;
+}
+
+static double
+seconds(void)
+{
+	struct timespec ts;
+
+	assert(clock_gettime(CLOCK_MONOTONIC, &ts) == 0);
+	return ts.tv_sec + ts.tv_nsec / 1e9;
+}
+
+static int
+helper(const char *mode, const char *path)
+{
+	char buf[4096];
+	pid_t child;
+	FILE *f;
+
+	if (strcmp(mode, "ok") == 0) {
+		printf("abcdef");
+		return 0;
+	}
+	if (strcmp(mode, "fail") == 0)
+		return 17;
+	if (strcmp(mode, "signal") == 0) {
+		raise(SIGTERM);
+		return 1;
+	}
+	if (strcmp(mode, "descendant") == 0 || strcmp(mode, "tree") == 0) {
+		assert((child = fork()) != -1);
+		if (child == 0) {
+			signal(SIGTERM, SIG_IGN);
+			for (;;)
+				pause();
+		}
+		printf("%ld", (long)child);
+		fflush(stdout);
+		if (strcmp(mode, "descendant") == 0)
+			return 0;
+	}
+	if (strcmp(mode, "announce") == 0) {
+		assert((f = fopen(path, "w")) != NULL);
+		fprintf(f, "%ld", (long)getpid());
+		assert(fclose(f) == 0);
+	}
+	if (strcmp(mode, "empty") == 0)
+		close(STDOUT_FILENO);
+	if (strcmp(mode, "flood") == 0) {
+		memset(buf, 'x', sizeof(buf));
+		while (write(STDOUT_FILENO, buf, sizeof(buf)) > 0)
+			;
+		return 1;
+	}
+	for (;;)
+		pause();
+}
+
+#ifdef __linux__
+static void
+reaped(pid_t pid)
+{
+	int status;
+	double start = seconds();
+	struct timespec delay = { 0, 1000000 };
+
+	for (;;) {
+		pid_t result = waitpid(pid, &status, WNOHANG);
+		if (result == pid) {
+			assert(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL);
+			return;
+		}
+		assert(result == 0 || (result == -1 && errno == EINTR));
+		assert(seconds() - start < 2);
+		nanosleep(&delay, NULL);
+	}
+}
+#endif
+
+int
+main(int argc, char **argv)
+{
+	char out[32], one = '!', path[] = "/tmp/signet-command.XXXXXX";
+	char *cmd[] = { argv[0], "ok", path, NULL };
+	char *missing[] = { "/no/such/signet-command", NULL };
+#ifdef __linux__
+	int fd;
+	pid_t caller, child = 0;
+	struct timespec delay = { 0, 1000000 };
+#endif
+	struct sigaction sa, oldsa;
+	sigset_t original, current, blocked;
+	struct itimerval timer = { { 0, 10000 }, { 0, 10000 } };
+	double start;
+	int i;
+	const char *modes[] = { "hold", "empty", "flood", "tree" };
+
+	if (argc > 1)
+		return helper(argv[1], argc > 2 ? argv[2] : NULL);
+#ifdef __linux__
+	/* Own orphan test descendants so assertions do not rely on container PID1. */
+	assert(prctl(PR_SET_CHILD_SUBREAPER, 1) == 0);
+#endif
+	assert(sigprocmask(SIG_SETMASK, NULL, &original) == 0);
+	sigemptyset(&blocked);
+	sigaddset(&blocked, SIGCHLD);
+	assert(sigprocmask(SIG_BLOCK, &blocked, NULL) == 0);
+	assert(run_cmd(cmd, out, 4) == 0 && strcmp(out, "abc") == 0);
+	assert(sigprocmask(SIG_SETMASK, NULL, &current) == 0);
+	assert(sigismember(&current, SIGCHLD) == 1);
+	assert(sigprocmask(SIG_SETMASK, &original, NULL) == 0);
+	memset(&sa, 0, sizeof(sa));
+	sa.sa_handler = SIG_IGN;
+	sigemptyset(&sa.sa_mask);
+	assert(sigaction(SIGCHLD, &sa, &oldsa) == 0);
+	assert(run_cmd(cmd, out, sizeof(out)) == -1 && errno == ECHILD);
+	assert(sigaction(SIGCHLD, &oldsa, NULL) == 0);
+	assert(run_cmd(cmd, &one, 1) == 0 && one == '\0');
+	assert(run_cmd(cmd, out, 0) == -1 && errno == EINVAL);
+	cmd[1] = "fail";
+	assert(run_cmd(cmd, NULL, 0) == -1 && errno == EIO);
+	cmd[1] = "signal";
+	assert(run_cmd(cmd, NULL, 0) == -1 && errno == EIO);
+	assert(run_cmd(missing, out, sizeof(out)) == -1 && errno == EIO);
+	for (i = 0; i < 4; i++) {
+		cmd[1] = (char *)modes[i];
+		start = seconds();
+		assert(run_cmd(cmd, out, sizeof(out)) == -1 && errno == ETIMEDOUT);
+		assert(seconds() - start < 2);
+#ifdef __linux__
+		if (strcmp(modes[i], "tree") == 0)
+			reaped((pid_t)strtol(out, NULL, 10));
+#endif
+	}
+	cmd[1] = "descendant";
+	assert(run_cmd(cmd, out, sizeof(out)) == 0);
+#ifdef __linux__
+	reaped((pid_t)strtol(out, NULL, 10));
+#endif
+	memset(&sa, 0, sizeof(sa));
+	sa.sa_handler = interrupt;
+	sigemptyset(&sa.sa_mask);
+	assert(sigaction(SIGALRM, &sa, NULL) == 0);
+	assert(setitimer(ITIMER_REAL, &timer, NULL) == 0);
+	cmd[1] = "hold";
+	start = seconds();
+	assert(run_cmd(cmd, NULL, 0) == -1 && errno == ETIMEDOUT);
+	assert(seconds() - start < 2 && interrupted > 0);
+	memset(&timer, 0, sizeof(timer));
+	assert(setitimer(ITIMER_REAL, &timer, NULL) == 0);
+#ifdef __linux__
+	fd = mkstemp(path);
+	assert(fd != -1);
+	close(fd);
+	assert((caller = fork()) != -1);
+	if (caller == 0) {
+		cmd[1] = "announce";
+		run_cmd(cmd, NULL, 0);
+		_exit(1);
+	}
+	start = seconds();
+	while (!child) {
+		FILE *f = fopen(path, "r");
+		long value = 0;
+		assert(f != NULL);
+		if (fscanf(f, "%ld", &value) == 1)
+			child = (pid_t)value;
+		fclose(f);
+		assert(seconds() - start < 2);
+		nanosleep(&delay, NULL);
+	}
+	assert(kill(caller, SIGKILL) == 0);
+	reaped(caller);
+	reaped(child);
+	unlink(path);
+#endif
+	assert(sigprocmask(SIG_SETMASK, NULL, &current) == 0);
+	assert(sigismember(&current, SIGCHLD) == sigismember(&original, SIGCHLD));
+	puts("command contract: all passed");
+	return 0;
+}
diff --git a/test/command-contract.sh b/test/command-contract.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+# Portable unit check; no services or PDF tools. Production uses the 30s ceiling.
+set -eu
+cd "$(dirname "$0")/.."
+TMP=$(mktemp -d /tmp/signet-command.XXXXXX)
+trap 'rm -rf "$TMP"' EXIT
+${CC:-cc} -O2 -std=c99 -Ivendor -c vendor/sha256.c -o "$TMP/sha256.o"
+${CC:-cc} -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 \
+    -D_DARWIN_C_SOURCE -DSIGNET_CMD_TIMEOUT_MS=500 -Wall -Wextra -Isrc \
+    test/command-contract.c src/util.c "$TMP/sha256.o" -o "$TMP/command-contract"
+"$TMP/command-contract"
diff --git a/test/e2e.sh b/test/e2e.sh
@@ -1,6 +1,9 @@
 #!/bin/sh
 # API/worker acceptance against an isolated dev container (run as root).
 set -eu
+if [ "${1-}" = command-contract ]; then
+	exec sh /src/test/command-contract.sh
+fi
 if [ "${1-}" = render-contract ]; then
 	exec sh /src/test/render-contract.sh
 fi

@@ -10,6 +13,7 @@ fi
 if [ "${1-}" = identity-contract ]; then
 	exec sh /src/test/identity-contract.sh
 fi
+sh /src/test/command-contract.sh
 sh /src/test/identity-contract.sh
 B=http://localhost:8080
 curl -fsS "$B/pim/pim.js" >/dev/null # Clean installs must include the PIM client.
diff --git a/test/render-contract.sh b/test/render-contract.sh
@@ -4,6 +4,7 @@ set -eu
 B=http://localhost:8080
 X='X-Requested-With: signet'
 Q=queue:stamping
+COMMAND_TMP=
 sql() { su-exec postgres psql -X -At -v ON_ERROR_STOP=1 -d signet "$@"; }
 as() { u=$1; g=$2; shift 2; curl -fsS -H "Remote-User: $u" -H "Remote-Groups: $g" "$@"; }
 post() { as "$1" "$2" -H "$X" -d '' "$B/api/docs/$ID/$3"; }

@@ -17,6 +18,7 @@ cleanup() {
 	[ ! -e /var/lib/signatures/manager.png.saved ] || mv /var/lib/signatures/manager.png.saved /var/lib/signatures/manager.png
 	stop_worker
 	start_worker
+	[ -z "$COMMAND_TMP" ] || rm -rf "$COMMAND_TMP"
 }
 trap cleanup EXIT
 wait_done() {

@@ -29,7 +31,7 @@ wait_done() {
 	fail 'render did not finish'
 }
 wait_error() {
-	for i in $(seq 1 80); do
+	for i in $(seq 1 "${1:-80}"); do
 		D=$(as asha clerks "$B/api/docs/$ID")
 		[ "$(echo "$D" | jq -r .render_error)" = null ] || return 0
 		sleep .1

@@ -203,6 +205,40 @@ wait_empty
 [ ! -e "$BASE/stamped.pdf" ] || fail 'post-commit cleanup did not recover'
 ok 'release replay commits exactly once, hashes the body and gates final access until commit'
 
+# A real hung qpdf must time out, commit a retryable failure and leave no child.
+stop_worker
+new_doc
+BASE=/var/lib/signet/docs/$ID
+post asha clerks submit >/dev/null
+COMMAND_TMP=$(mktemp -d /tmp/signet-command-job.XXXXXX)
+chmod 0755 "$COMMAND_TMP"
+mkdir "$COMMAND_TMP/bin"
+touch "$COMMAND_TMP/hang" "$COMMAND_TMP/pid"
+chown signetd:signet "$COMMAND_TMP/pid"
+cat > "$COMMAND_TMP/bin/qpdf" <<EOF
+#!/bin/sh
+if [ -e '$COMMAND_TMP/hang' ]; then
+ echo \$\$ > '$COMMAND_TMP/pid'
+ exec sleep 120
+fi
+exec /usr/bin/qpdf "\$@"
+EOF
+chmod 0755 "$COMMAND_TMP/bin/qpdf"
+PATH="$COMMAND_TMP/bin:$PATH" su-exec signetd:signet /usr/local/sbin/signetd >>/tmp/render-contract-worker.log 2>&1 &
+wait_error 400
+wait_empty
+echo "$D" | jq -e '.status=="PENDING" and .render_seq==1 and .rendered_seq==0 and .can_retry' >/dev/null || fail 'timeout not retryable'
+IFS= read -r COMMAND_PID < "$COMMAND_TMP/pid"
+[ ! -e "/proc/$COMMAND_PID" ] || fail 'timed-out command was not reaped'
+grep -q 'command qpdf failed:.*timed out' /tmp/render-contract-worker.log || fail 'timeout not logged'
+[ "$(sql -c "SELECT count(*) FROM doc_events WHERE doc_id='$ID' AND action='STAMP_FAILED'")" = 1 ] || fail 'timeout outcome not committed'
+rm "$COMMAND_TMP/hang"
+post asha clerks rerender >/dev/null
+wait_done
+wait_empty
+cmp "$BASE/proof.pdf" "$BASE/stamped.pdf" || fail 'timeout retry did not preserve proof/stamped equality'
+ok 'hung command is killed/reaped, failure committed before acknowledgement and retry succeeds'
+
 # A queue outage after submit commits leaves a retryable render, even without an error string.
 stop_worker
 new_doc