Skip to content

fix: restore timeout watchdog compatibility with macOS Bash 3.2 - #6028

Merged
kunchenguid merged 2 commits into
kunchenguid:mainfrom
M00NLIG7:fm/firstmate-macos-bash32-timeout-v1-t6
Oct 6, 2026
Merged

kunchenguid merged 2 commits into
kunchenguid:mainfrom
M00NLIG7:fm/firstmate-macos-bash32-timeout-v1-t6

Conversation

@M00NLIG7

@M00NLIG7 M00NLIG7 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Intent

ok

Approval is for preparing the small macOS fix as a separate upstream Firstmate PR, preserving the other changes.
The approved fix is limited to stock-macOS Bash 3.2 timeout/watchdog compatibility in bin/fm-timeout-lib.sh and accompanying tests/fm-timeout-lib.test.sh: the watchdog ownership code reads the Bash-4-only BASHPID variable under nounset, breaking bounded-command execution on the stock shell.
Correct that ownership handling without losing current upstream timeout/signal-status improvements or process-ownership safeguards, with regression tests.
Full validation and a separate PR to https://github.com/kunchenguid/firstmate are authorized; merge, live installation and reversal of existing local changes are not.
Existing monitoring work, admission-recovery code and other local changes must remain separate and preserved.

What Changed

  • Move watchdog ownership checks from Bash-only BASHPID to Perl’s process ID, preserving the pre-exec parent for startup races.
  • Add regression coverage for missing BASHPID, top-level and subshell exit/signal statuses, and parent death during watchdog startup.
  • Replace BASHPID usage in existing ownership tests with portable PID discovery.

Risk Assessment

✅ Low: The narrowly scoped fix removes the Bash-4-only dependency while preserving ownership checks and timeout/status handling, with behavioral regression coverage and no unrelated changes.

Testing

Path normalization: Local validation directories in the excerpts below are represented by ${REPO_ROOT}, ${TEST_SCRATCH}, and ${VALIDATION_EVIDENCE}.
These are portable placeholders, not literal original command paths; outputs and results are otherwise unchanged.
Local directory paths appeared in an earlier revision of this description; linked evidence artifacts remain unchanged.

Targeted tests and live Bash 3.2 library calls passed after correcting two driver-only assumptions; the original BASHPID failure was reproduced, command/status and process-cleanup evidence was captured, and temporary inputs were removed. GNU fallback remains untested because timeout/gtimeout are unavailable; no UI surface was changed.

  • Live validation: ✅ go - 7 of 8 scenarios driven live against the product
Scenario Result Live Evidence
Run bounded commands on stock Bash 3.2 without losing output or exit status ✅ pass live timeout-live.log: base exits 127 with BASHPID unbound; fixed top-level and subshell calls preserve stdout, stderr, and statuses 0, 7, 137, and 143.
Replace the calling shell rather than adding another wrapper ✅ pass live timeout-live.log: EXEC REPLACEMENT confirms the command's parent matches the pre-exec shell PID in both invocation modes.
Enforce deadlines against cooperative commands and TERM-resistant descendants ✅ pass live timeout-live.log: deadlines return 124, KILL respects the grace period, output pipes close, and recorded child/descendant PIDs disappear.
Forward TERM, INT, and HUP while preserving the command's chosen exit status ✅ pass live timeout-live.log: each signal produces its command-side acknowledgement and exit status 3.
Stop owned processes when the owner disappears before or after watchdog startup ✅ pass live timeout-live.log: top-level and subshell startup/running cases terminate promptly; explicit dead-owner escalation works; unrelated sentinel remains alive.
Refuse invalid bounds or missing timeout mechanisms without executing the command ✅ pass live timeout-live.log: malformed bounds return 125; missing mechanisms return 127; requested command never creates its marker.
Preserve existing fm_run_timed completion, signal, and timeout statuses ✅ pass live timeout-live.log: real Perl execution preserves statuses 0, 7, 137, and 143 and reports deadline expiry as 124.
Enforce deadlines through the GNU timeout fallback ⏸️ untested no Neither executable is on PATH and no repository-local binary was supplied. Provide one on PATH in a validation environment to exercise this unchanged fallback; no packages were installed.
Evidence: Live product transcript, including baseline reproduction

Source: Live product transcript, including baseline reproduction

GNU bash, version 3.2.57(1)-release (arm64-apple-darwin25)
Copyright (C) 2007 Free Software Foundation, Inc.

Darwin arm64

All product calls use real Bash, Perl, and child processes; no runner stubs.
BASE REPRODUCTION: exit=127; stdout=''; stderr='${TEST_SCRATCH}/base-lib.sh: line 224: BASHPID: unbound variable\n'

BASH32 STATUS top-level 0
$ /bin/bash -c '. "$1"; fm_exec_timed 5 1 /bin/bash -c "$2"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'echo command-ran; echo command-stderr >&2'
exit=0; elapsed=0.115s; stdout='command-ran\n'; stderr='command-stderr\n'

BASH32 STATUS top-level 7
$ /bin/bash -c '. "$1"; fm_exec_timed 5 1 /bin/bash -c "$2"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'echo command-ran; echo command-stderr >&2; exit 7'
exit=7; elapsed=0.142s; stdout='command-ran\n'; stderr='command-stderr\n'

BASH32 STATUS top-level 137
$ /bin/bash -c '. "$1"; fm_exec_timed 5 1 /bin/bash -c "$2"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'echo command-ran; echo command-stderr >&2; kill -KILL $$'
exit=137; elapsed=0.100s; stdout='command-ran\n'; stderr='command-stderr\n'

BASH32 STATUS top-level 143
$ /bin/bash -c '. "$1"; fm_exec_timed 5 1 /bin/bash -c "$2"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'echo command-ran; echo command-stderr >&2; kill -TERM $$'
exit=143; elapsed=0.108s; stdout='command-ran\n'; stderr='command-stderr\n'

BASH32 STATUS subshell 0
$ /bin/bash -c '. "$1"; ( fm_exec_timed 5 1 /bin/bash -c "$2" ); rc=$?; exit "$rc"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'echo command-ran; echo command-stderr >&2'
exit=0; elapsed=0.151s; stdout='command-ran\n'; stderr='command-stderr\n'

BASH32 STATUS subshell 7
$ /bin/bash -c '. "$1"; ( fm_exec_timed 5 1 /bin/bash -c "$2" ); rc=$?; exit "$rc"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'echo command-ran; echo command-stderr >&2; exit 7'
exit=7; elapsed=0.189s; stdout='command-ran\n'; stderr='command-stderr\n'

BASH32 STATUS subshell 137
$ /bin/bash -c '. "$1"; ( fm_exec_timed 5 1 /bin/bash -c "$2" ); rc=$?; exit "$rc"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'echo command-ran; echo command-stderr >&2; kill -KILL $$'
exit=137; elapsed=0.168s; stdout='command-ran\n'; stderr='command-stderr\n'

BASH32 STATUS subshell 143
$ /bin/bash -c '. "$1"; ( fm_exec_timed 5 1 /bin/bash -c "$2" ); rc=$?; exit "$rc"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'echo command-ran; echo command-stderr >&2; kill -TERM $$'
exit=143; elapsed=0.170s; stdout='command-ran\n'; stderr='command-stderr\n'

EXEC REPLACEMENT top-level
$ /bin/bash -c '. "$1"; echo $$ > "$2"; fm_exec_timed 5 1 /bin/bash -c '"'"'echo parent=$PPID'"'"'' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh ${TEST_SCRATCH}/replace-top-level
exit=0; elapsed=0.099s; stdout='parent=36921\n'; stderr=''
pre-exec shell PID equals bounded command parent PID

EXEC REPLACEMENT subshell
$ /bin/bash -c '. "$1"; ( /usr/bin/perl -e '"'"'print getppid(), "\n"'"'"' > "$2"; fm_exec_timed 5 1 /bin/bash -c '"'"'echo parent=$PPID'"'"' ); rc=$?; exit "$rc"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh ${TEST_SCRATCH}/replace-subshell
exit=0; elapsed=0.118s; stdout='parent=37089\n'; stderr=''
pre-exec shell PID equals bounded command parent PID

DEADLINE cooperative child
$ /bin/bash -c '. "$1"; fm_exec_timed 1 "$2" /bin/bash -c "$3" _ "$4"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 5 'echo $$ > "$1"; exec /bin/sleep 20' ${TEST_SCRATCH}/cooperative-child
exit=124; elapsed=1.267s; stdout=''; stderr=''
process 37350: alive=False

DEADLINE TERM-ignoring child
$ /bin/bash -c '. "$1"; fm_exec_timed 1 "$2" /bin/bash -c "$3" _ "$4"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 1 'trap "" TERM; echo $$ > "$1"; exec /bin/sleep 20' ${TEST_SCRATCH}/TERM-ignoring-child
exit=124; elapsed=2.189s; stdout=''; stderr=''
process 38948: alive=False

DEADLINE output-holding descendant
$ /bin/bash -c '. "$1"; fm_exec_timed 1 "$2" /bin/bash -c "$3" _ "$4"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 5 '( trap "" TERM; exec /bin/sleep 20 ) & echo $! > "$1"; wait' ${TEST_SCRATCH}/output-holding-descendant
exit=124; elapsed=1.228s; stdout=''; stderr=''
process 43253: alive=False

FORWARD TERM
$ /bin/bash -c '. "$1"; fm_exec_timed 20 1 /bin/bash -c "$2" _ "$3"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'trap "echo forwarded-TERM; exit 3" TERM; echo $$ > "$1"; while :; do /bin/sleep .1; done' ${TEST_SCRATCH}/signal-TERM
signalled watchdog=45359; child=45679; exit=3; stdout='forwarded-TERM\n'; stderr='Terminated: 15\n'
process 45679: alive=False

FORWARD INT
$ /bin/bash -c '. "$1"; fm_exec_timed 20 1 /bin/bash -c "$2" _ "$3"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'trap "echo forwarded-INT; exit 3" INT; echo $$ > "$1"; while :; do /bin/sleep .1; done' ${TEST_SCRATCH}/signal-INT
signalled watchdog=45964; child=46225; exit=3; stdout='forwarded-INT\n'; stderr=''
process 46225: alive=False

FORWARD HUP
$ /bin/bash -c '. "$1"; fm_exec_timed 20 1 /bin/bash -c "$2" _ "$3"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'trap "echo forwarded-HUP; exit 3" HUP; echo $$ > "$1"; while :; do /bin/sleep .1; done' ${TEST_SCRATCH}/signal-HUP
signalled watchdog=46454; child=47496; exit=3; stdout='forwarded-HUP\n'; stderr='Hangup: 1\n'
process 47496: alive=False

OWNER DEATH top-level startup
$ /bin/bash -c '/bin/bash -c "$5" _ "$1" "$2" "$3" "$4" & while :; do /bin/sleep .02; done' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh ${TEST_SCRATCH}/top-levelstartup-watchdog ${TEST_SCRATCH}/top-levelstartup-child 'echo $$ > "$1"; exec /bin/sleep 20' '. "$1"; echo $$ > "$2"; while kill -0 "$PPID" 2>/dev/null; do /bin/sleep .02; done; fm_exec_timed 20 1 /bin/bash -c "$4" _ "$3"'
killed owner=47860; watchdog=47973; child=None; drain=1.180s; stdout=''; stderr=''
process 47973: alive=False
process 48303: alive=False
unrelated sentinel=47850 remains alive

OWNER DEATH top-level running
$ /bin/bash -c '/bin/bash -c "$5" _ "$1" "$2" "$3" "$4" & while :; do /bin/sleep .02; done' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh ${TEST_SCRATCH}/top-levelrunning-watchdog ${TEST_SCRATCH}/top-levelrunning-child 'echo $$ > "$1"; exec /bin/sleep 20' '. "$1"; echo $$ > "$2"; fm_exec_timed 20 1 /bin/bash -c "$4" _ "$3"'
killed owner=50103; watchdog=50123; child=50223; drain=0.104s; stdout=''; stderr=''
process 50123: alive=False
process 50223: alive=False
unrelated sentinel=47850 remains alive

OWNER DEATH subshell startup
$ /bin/bash -c '. "$1"; ( /usr/bin/perl -e '"'"'print getppid(), "\n"'"'"' > "$2"; while kill -0 "$$" 2>/dev/null; do /bin/sleep .02; done; fm_exec_timed 20 1 /bin/bash -c "$4" _ "$3" ) & while :; do /bin/sleep .02; done' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh ${TEST_SCRATCH}/subshellstartup-watchdog ${TEST_SCRATCH}/subshellstartup-child 'echo $$ > "$1"; exec /bin/sleep 20' ''
killed owner=50507; watchdog=50551; child=None; drain=0.291s; stdout=''; stderr=''
process 50551: alive=False
unrelated sentinel=47850 remains alive

OWNER DEATH subshell running
$ /bin/bash -c '. "$1"; ( /usr/bin/perl -e '"'"'print getppid(), "\n"'"'"' > "$2"; fm_exec_timed 20 1 /bin/bash -c "$4" _ "$3" ) & while :; do /bin/sleep .02; done' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh ${TEST_SCRATCH}/subshellrunning-watchdog ${TEST_SCRATCH}/subshellrunning-child 'echo $$ > "$1"; exec /bin/sleep 20' ''
killed owner=51153; watchdog=51188; child=51382; drain=0.149s; stdout=''; stderr=''
process 51188: alive=False
process 51382: alive=False
unrelated sentinel=47850 remains alive

EXPLICIT DEAD OWNER
$ /bin/bash -c '. "$1"; fm_exec_timed 20 1 /bin/sleep 20' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh
exit=137; elapsed=1.232s; stdout=''; stderr=''

INVALID BOUND
$ /bin/bash -c '. "$1"; fm_exec_timed "$2" "$3" /bin/bash -c '"'"'echo ran > "$1"'"'"' _ "$4"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 0 1 ${TEST_SCRATCH}/must-not-run
exit=125; elapsed=0.013s; stdout=''; stderr='fm_exec_timed: usage: fm_exec_timed <positive-seconds> <positive-grace-seconds> <command> [args...]\n'

INVALID BOUND
$ /bin/bash -c '. "$1"; fm_exec_timed "$2" "$3" /bin/bash -c '"'"'echo ran > "$1"'"'"' _ "$4"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 1 0 ${TEST_SCRATCH}/must-not-run
exit=125; elapsed=0.018s; stdout=''; stderr='fm_exec_timed: usage: fm_exec_timed <positive-seconds> <positive-grace-seconds> <command> [args...]\n'

INVALID BOUND
$ /bin/bash -c '. "$1"; fm_exec_timed "$2" "$3" /bin/bash -c '"'"'echo ran > "$1"'"'"' _ "$4"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 01 1 ${TEST_SCRATCH}/must-not-run
exit=125; elapsed=0.019s; stdout=''; stderr='fm_exec_timed: usage: fm_exec_timed <positive-seconds> <positive-grace-seconds> <command> [args...]\n'

INVALID BOUND
$ /bin/bash -c '. "$1"; fm_exec_timed "$2" "$3" /bin/bash -c '"'"'echo ran > "$1"'"'"' _ "$4"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 1 x ${TEST_SCRATCH}/must-not-run
exit=125; elapsed=0.017s; stdout=''; stderr='fm_exec_timed: usage: fm_exec_timed <positive-seconds> <positive-grace-seconds> <command> [args...]\n'

NO BOUNDING BACKEND
$ /bin/bash -c '. "$1"; fm_exec_timed 1 1 /bin/bash -c '"'"'echo ran > "$1"'"'"' _ "$2"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh ${TEST_SCRATCH}/must-not-run
exit=127; elapsed=0.018s; stdout=''; stderr='fm_exec_timed: cannot bound bash within 1s: none of perl, timeout, or gtimeout is available\n'
Requested command never executed on refused calls.

RUN_TIMED REAL PERL 0
$ /bin/bash -c '. "$1"; fm_run_timed 1 /bin/bash -c "$2"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'echo completed'
exit=0; elapsed=0.062s; stdout='completed\n'; stderr=''

RUN_TIMED REAL PERL 7
$ /bin/bash -c '. "$1"; fm_run_timed 1 /bin/bash -c "$2"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'exit 7'
exit=7; elapsed=0.066s; stdout=''; stderr=''

RUN_TIMED REAL PERL 137
$ /bin/bash -c '. "$1"; fm_run_timed 1 /bin/bash -c "$2"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'kill -KILL $$'
exit=137; elapsed=0.056s; stdout=''; stderr=''

RUN_TIMED REAL PERL 143
$ /bin/bash -c '. "$1"; fm_run_timed 1 /bin/bash -c "$2"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'kill -TERM $$'
exit=143; elapsed=0.046s; stdout=''; stderr=''

RUN_TIMED REAL PERL 124
$ /bin/bash -c '. "$1"; fm_run_timed 1 /bin/bash -c "$2"' _ ${REPO_ROOT}/bin/fm-timeout-lib.sh 'exec /bin/sleep 20'
exit=124; elapsed=1.373s; stdout=''; stderr=''

All manual product scenarios passed; transient inputs cleaned.
Evidence: Targeted regression tests

Source: Targeted regression tests

ok - fm_exec_timed passes a command's status and output through unchanged
ok - system Bash top-level and subshell calls preserve success, failure, and signal status
_: line 3: 92094 Terminated: 15          "$@"
ok - fm_run_timed reports 124 when the bound TERMs a read whose wrapper recorded 143
ok - fm_run_timed passes a natural exit through when the bound fired after completion
ok - fm_exec_timed sends TERM at the bound and a cooperative command ends there
ok - fm_exec_timed kills a TERM-ignoring command once the grace has passed
ok - fm_exec_timed replaces the calling shell instead of wrapping it
ok - fm_exec_timed reaps a descendant that would otherwise hold the output past the bound
ok - fm_exec_timed forwards a TERM it receives to the bounded command
ok - fm_exec_timed ends the command when its named owner is already gone
ok - fm_exec_timed ends the command when its owner dies during watchdog startup
ok - fm_exec_timed preserves a top-level shell's parent across exec startup
ok - fm_exec_timed prefers its perl watchdog over timeout
ok - fm_exec_timed refuses instead of running unbounded when no mechanism exists
ok - fm_exec_timed rejects a zero, padded, non-numeric, or missing bound and a missing command
ok - fm_exec_timed's GNU timeout fallback (skipped: no timeout binary on this host)
ok - fm_timed_out accepts 124 and 137 and nothing else
Evidence: Reproducible live driver

Source: Reproducible live driver

import os
import pathlib
import shlex
import signal
import subprocess
import tempfile
import time

ROOT = pathlib.Path.cwd()
LIB = ROOT / 'bin/fm-timeout-lib.sh'
ENV = os.environ.copy()
ENV.pop('FM_EXEC_TIMED_OWNER_PID', None)
ENV.pop('FM_TIMEOUT_MECHANISM_OVERRIDE', None)
ENV['PATH'] = '/usr/bin:/bin:/usr/sbin:/sbin'
tracked = set()

def alive(pid):
    try:
        os.kill(pid, 0)
        return True
    except ProcessLookupError:
        return False

def gone(pid):
    end = time.monotonic() + 5
    while alive(pid) and time.monotonic() < end:
        time.sleep(.02)
    print(f'process {pid}: alive={alive(pid)}', flush=True)
    assert not alive(pid)
    tracked.discard(pid)

def readpid(path):
    end = time.monotonic() + 5
    while time.monotonic() < end:
        if path.exists() and path.read_text().strip():
            pid = int(path.read_text().strip())
            tracked.add(pid)
            return pid
        time.sleep(.01)
    raise AssertionError(f'no PID published: {path}')

def run(label, script, args=(), expected=0, env=None):
    argv = ['/bin/bash', '-c', script, '_', str(LIB), *map(str, args)]
    print(f'\n{label}\n$ {shlex.join(argv)}', flush=True)
    start = time.monotonic()
    p = subprocess.run(argv, env=env or ENV, text=True, capture_output=True, timeout=12)
    elapsed = time.monotonic() - start
    print(f'exit={p.returncode}; elapsed={elapsed:.3f}s; stdout={p.stdout!r}; stderr={p.stderr!r}', flush=True)
    assert p.returncode in (expected if isinstance(expected, tuple) else (expected,))
    return p, elapsed

print(subprocess.check_output(['/bin/bash', '--version'], text=True), flush=True)
print(subprocess.check_output(['uname', '-sm'], text=True), flush=True)
print('All product calls use real Bash, Perl, and child processes; no runner stubs.', flush=True)
try:
    with tempfile.TemporaryDirectory(prefix='.timeout-live-', dir=ROOT) as temp:
        d = pathlib.Path(temp)
        base = d / 'base-lib.sh'
        base.write_bytes(subprocess.check_output(['git', 'show', '29213a09322a35d87b2f8acc29c415f3f860cb64:bin/fm-timeout-lib.sh']))
        script = '. "$1"; fm_exec_timed 5 1 /bin/bash -c "echo command-ran"'
        original = subprocess.run(['/bin/bash', '-c', script, '_', str(base)], env=ENV, capture_output=True, text=True)
        print(f'BASE REPRODUCTION: exit={original.returncode}; stdout={original.stdout!r}; stderr={original.stderr!r}', flush=True)
        assert original.returncode != 0 and 'BASHPID: unbound variable' in original.stderr and not original.stdout
        for mode in ['top-level', 'subshell']:
            for code, cmd in [(0, 'echo command-ran; echo command-stderr >&2'), (7, 'echo command-ran; echo command-stderr >&2; exit 7'), (137, 'echo command-ran; echo command-stderr >&2; kill -KILL $$'), (143, 'echo command-ran; echo command-stderr >&2; kill -TERM $$')]:
                call = 'fm_exec_timed 5 1 /bin/bash -c "$2"'
                if mode == 'subshell':
                    call = '( ' + call + ' ); rc=$?; exit "$rc"'
                p, _ = run(f'BASH32 STATUS {mode} {code}', '. "$1"; ' + call, [cmd], code)
                assert p.stdout == 'command-ran\n' and p.stderr == 'command-stderr\n'

        for mode in ['top-level', 'subshell']:
            call = 'echo $$ > "$2"; fm_exec_timed 5 1 /bin/bash -c \'echo parent=$PPID\'' if mode == 'top-level' else '( /usr/bin/perl -e \'print getppid(), "\\n"\' > "$2"; fm_exec_timed 5 1 /bin/bash -c \'echo parent=$PPID\' ); rc=$?; exit "$rc"'
            pidfile = d / ('replace-' + mode)
            p, _ = run(f'EXEC REPLACEMENT {mode}', '. "$1"; ' + call, [pidfile])
            assert p.stdout == f'parent={pidfile.read_text().strip()}\n'
            print('pre-exec shell PID equals bounded command parent PID', flush=True)

        for label, child, grace, minimum in [
            ('cooperative child', 'echo $$ > "$1"; exec /bin/sleep 20', 5, 1),
            ('TERM-ignoring child', 'trap "" TERM; echo $$ > "$1"; exec /bin/sleep 20', 1, 2),
            ('output-holding descendant', '( trap "" TERM; exec /bin/sleep 20 ) & echo $! > "$1"; wait', 5, 1),
        ]:
            pidfile = d / label.replace(' ', '-')
            p, elapsed = run('DEADLINE ' + label, '. "$1"; fm_exec_timed 1 "$2" /bin/bash -c "$3" _ "$4"', [grace, child, pidfile], 124)
            assert minimum <= elapsed < 4
            gone(readpid(pidfile))

        for sig in ['TERM', 'INT', 'HUP']:
            pidfile = d / ('signal-' + sig)
            child = f'trap "echo forwarded-{sig}; exit 3" {sig}; echo $$ > "$1"; while :; do /bin/sleep .1; done'
            argv = ['/bin/bash', '-c', '. "$1"; fm_exec_timed 20 1 /bin/bash -c "$2" _ "$3"', '_', str(LIB), child, str(pidfile)]
            print(f'\nFORWARD {sig}\n$ {shlex.join(argv)}', flush=True)
            watchdog = subprocess.Popen(argv, env=ENV, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            tracked.add(watchdog.pid)
            childpid = readpid(pidfile)
            os.kill(watchdog.pid, getattr(signal, 'SIG' + sig))
            out, err = watchdog.communicate(timeout=5)
            tracked.discard(watchdog.pid)
            print(f'signalled watchdog={watchdog.pid}; child={childpid}; exit={watchdog.returncode}; stdout={out!r}; stderr={err!r}', flush=True)
            assert watchdog.returncode == 3 and out == f'forwarded-{sig}\n'
            gone(childpid)

        # An unrelated process must not be swept up by any ownership escalation.
        sentinel = subprocess.Popen(['/bin/sleep', '30'], env=ENV)
        tracked.add(sentinel.pid)
        for mode in ['top-level', 'subshell']:
            for timing in ['startup', 'running']:
                wdfile = d / (mode + timing + '-watchdog')
                childfile = d / (mode + timing + '-child')
                child = 'echo $$ > "$1"; exec /bin/sleep 20'
                if mode == 'top-level':
                    inner = '. "$1"; echo $$ > "$2"; '
                    if timing == 'startup':
                        inner += 'while kill -0 "$PPID" 2>/dev/null; do /bin/sleep .02; done; '
                    inner += 'fm_exec_timed 20 1 /bin/bash -c "$4" _ "$3"'
                    launcher = '/bin/bash -c "$5" _ "$1" "$2" "$3" "$4" & '
                else:
                    inner = ''
                    launcher = '. "$1"; ( /usr/bin/perl -e \'print getppid(), "\\n"\' > "$2"; '
                    if timing == 'startup':
                        launcher += 'while kill -0 "$$" 2>/dev/null; do /bin/sleep .02; done; '
                    launcher += 'fm_exec_timed 20 1 /bin/bash -c "$4" _ "$3" ) & '
                launcher += 'while :; do /bin/sleep .02; done'
                argv = ['/bin/bash', '-c', launcher, '_', str(LIB), str(wdfile), str(childfile), child, inner]
                print(f'\nOWNER DEATH {mode} {timing}\n$ {shlex.join(argv)}', flush=True)
                parent = subprocess.Popen(argv, env=ENV, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
                tracked.add(parent.pid)
                wdpid = readpid(wdfile)
                childpid = readpid(childfile) if timing == 'running' else None
                start = time.monotonic()
                parent.kill()
                # Reap the killed owner before draining descendants' pipes: a zombie
                # still answers kill(0) and would hold our startup barrier open.
                parent.wait(timeout=5)
                tracked.discard(parent.pid)
                out, err = parent.communicate(timeout=5)
                elapsed = time.monotonic() - start
                print(f'killed owner={parent.pid}; watchdog={wdpid}; child={childpid}; drain={elapsed:.3f}s; stdout={out!r}; stderr={err!r}', flush=True)
                gone(wdpid)
                if childfile.exists() and childfile.read_text().strip():
                    gone(readpid(childfile))
                assert sentinel.poll() is None
                print(f'unrelated sentinel={sentinel.pid} remains alive', flush=True)

        dead = subprocess.Popen(['/bin/sleep', '0'])
        dead.wait()
        env = ENV.copy()
        env['FM_EXEC_TIMED_OWNER_PID'] = str(dead.pid)
        p, elapsed = run('EXPLICIT DEAD OWNER', '. "$1"; fm_exec_timed 20 1 /bin/sleep 20', expected=(143, 137), env=env)
        assert elapsed < 3 and sentinel.poll() is None
        sentinel.terminate()
        sentinel.wait()
        tracked.discard(sentinel.pid)

        # Guard failures must never execute the requested command.
        marker = d / 'must-not-run'
        for seconds, grace in [('0', '1'), ('1', '0'), ('01', '1'), ('1', 'x')]:
            p, _ = run('INVALID BOUND', '. "$1"; fm_exec_timed "$2" "$3" /bin/bash -c \'echo ran > "$1"\' _ "$4"', [seconds, grace, marker], 125)
            assert not marker.exists()
        emptybin = d / 'emptybin'
        emptybin.mkdir()
        env = ENV.copy()
        env['PATH'] = str(emptybin)
        p, _ = run('NO BOUNDING BACKEND', '. "$1"; fm_exec_timed 1 1 /bin/bash -c \'echo ran > "$1"\' _ "$2"', [marker], 127, env)
        assert not marker.exists() and 'none of perl, timeout, or gtimeout' in p.stderr
        print('Requested command never executed on refused calls.', flush=True)

        # Existing upstream run_timed signal semantics, without the test suite's timeout stub.
        for status, child in [(0, 'echo completed'), (7, 'exit 7'), (137, 'kill -KILL $$'), (143, 'kill -TERM $$'), (124, 'exec /bin/sleep 20')]:
            run('RUN_TIMED REAL PERL ' + str(status), '. "$1"; fm_run_timed 1 /bin/bash -c "$2"', [child], status)
        print('\nAll manual product scenarios passed; transient inputs cleaned.', flush=True)
finally:
    for pid in tracked:
        if alive(pid):
            try:
                os.kill(pid, signal.SIGKILL)
            except ProcessLookupError:
                pass

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 7 of 8 scenarios driven live against the product
Scenario Result Live Evidence
Run bounded commands on stock Bash 3.2 without losing output or exit status ✅ pass live timeout-live.log: base exits 127 with BASHPID unbound; fixed top-level and subshell calls preserve stdout, stderr, and statuses 0, 7, 137, and 143.
Replace the calling shell rather than adding another wrapper ✅ pass live timeout-live.log: EXEC REPLACEMENT confirms the command's parent matches the pre-exec shell PID in both invocation modes.
Enforce deadlines against cooperative commands and TERM-resistant descendants ✅ pass live timeout-live.log: deadlines return 124, KILL respects the grace period, output pipes close, and recorded child/descendant PIDs disappear.
Forward TERM, INT, and HUP while preserving the command's chosen exit status ✅ pass live timeout-live.log: each signal produces its command-side acknowledgement and exit status 3.
Stop owned processes when the owner disappears before or after watchdog startup ✅ pass live timeout-live.log: top-level and subshell startup/running cases terminate promptly; explicit dead-owner escalation works; unrelated sentinel remains alive.
Refuse invalid bounds or missing timeout mechanisms without executing the command ✅ pass live timeout-live.log: malformed bounds return 125; missing mechanisms return 127; requested command never creates its marker.
Preserve existing fm_run_timed completion, signal, and timeout statuses ✅ pass live timeout-live.log: real Perl execution preserves statuses 0, 7, 137, and 143 and reports deadline expiry as 124.
Enforce deadlines through the GNU timeout fallback ⏸️ untested no Neither executable is on PATH and no repository-local binary was supplied. Provide one on PATH in a validation environment to exercise this unchanged fallback; no packages were installed.
  • /bin/bash --version confirmed Bash 3.2.57 on Darwin arm64.
  • /bin/bash tests/fm-timeout-lib.test.sh passed; GNU timeout coverage skipped because the binary is unavailable.
  • python3 ${VALIDATION_EVIDENCE}/drive-timeout.py reproduced the base commit failure and exercised the actual library with real processes.
  • Corrected two manual-driver assumptions—reaping a killed parent before draining pipes and accepting TERM or KILL after owner death—then reran successfully.
  • git status --short and the transient-directory check confirmed cleanup and an unchanged worktree.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Fixes timeout watchdog compatibility with older Bash versions.

The PR appears safe to merge based on the changes since the previous review.

Reviews (2) · Last reviewed commit: "no-mistakes(ci): Fixed ci-1 in tests/fm-..."

Comment thread tests/fm-timeout-lib.test.sh Resolved
…rtup-owner failure paths now kill the bounded command group before killing the watchdog. Fault injection reproduced both leaks before the fix and confirmed cleanup afterward. Bash 3.2 suite, syntax check, ShellCheck, and diff checks passed; GNU timeout coverage skipped because the binary is unavailable. Production code unchanged
@jonathankv

Copy link
Copy Markdown

+1, another affected home here.

On macOS with the stock /bin/bash 3.2 (no Homebrew bash installed), every ship and scout dispatch on this machine has failed at the backlog transition with BASHPID: unbound variable (bin/fm-timeout-lib.sh:224) since that line reached main.

We are carrying a local one-line stopgap (${BASHPID:-$$}, the pattern the rest of bin/ already uses). Because it stays uncommitted, it also keeps the home dirty, so fm-update.sh skips both our main firstmate home and our secondmate home and neither can take new releases until this lands.

This PR is green and mergeable; merging it would unblock us. Related: #6074 (shared lock on bash 3.2, also from the missing BASHPID).

@guanchengh-lgtm

Copy link
Copy Markdown
Contributor

Verified on stock macOS /bin/bash 3.2.57 (arm64), applied to current main 23e55847:

  • /bin/bash tests/fm-timeout-lib.test.sh: 17 ok, 5 of 5 runs.
  • bin/fm-lint.sh bin/fm-timeout-lib.sh tests/fm-timeout-lib.test.sh: clean (ShellCheck 0.11.0).
  • A top-level caller whose parent exits before a 1s-delayed watchdog starts ends within 1s; with the ${BASHPID:-} stopgap it runs on toward its bound.
  • The new top-level test fails against both ${BASHPID:-} and ${BASHPID:-$$}, so it pins the fix rather than only the crash.

This is the smallest fix among the open PRs on this line: it answers "is the owner the process being replaced" inside the watchdog, where exec has kept the pid, so it needs no pid probe and no fork.
One suggestion: macos-stock-bash does not run this suite yet, so a step there would have caught #5770 on the day it landed:

timeout_output=$(/bin/bash tests/fm-timeout-lib.test.sh)
printf '%s\n' "$timeout_output"
timeout_count=$(printf '%s\n' "$timeout_output" | grep -c '^ok - ')
[ "$timeout_count" -eq 17 ] || {
  echo "::error::expected 17 fm-timeout-lib bash 3.2 regressions, got $timeout_count"
  exit 1
}

@kunchenguid

Copy link
Copy Markdown
Owner

Kun's firstmate triage (firstmate-oss) — merge stamp

Why this one: it drops the bash-4-only $BASHPID read and does the "am I the top-level caller?" check inside the perl watchdog after exec. At that point perl's $$ is the shell's own PID, subshell included, so the owner semantics stay exactly what they were on bash 4+. The ${BASHPID:-$$} guard gets the subshell case wrong on bash 3.2 (it would watch the script's parent). The ${BASHPID:-} skip gets the top-level case wrong. This PR's new top-level/startup-race tests pin that difference. I merged it locally onto main 2d7daa9e and tests/fm-timeout-lib.test.sh passes. CI is green on the tip (run 36462284459, plus 36465399046), Greptile shows no open P1 (its one P2 is resolved), and the merge state is CLEAN.

VISION check:

  • Scripts own the mechanics: aligned. It's a deterministic fix inside the existing bounded-exec script, with no new judgment and no new layer.
  • Fleet outlives any vendor / setup stays simple ("clone the repo, run your agent in it"): aligned. Stock macOS /bin/bash 3.2 is a supported default path, and it broke every spawn.
  • Delegation with a spine / field incidents become regression coverage: aligned. Regression tests cover a missing BASHPID and owner death at startup.
  • Authority, scope, token budget: unaffected. No new capability, no contract text growth.

Merge intent: squash-merge now at c0be3dca, close #5847, then close the one-line-guard duplicates as superseded, crediting their authors.

@kunchenguid
kunchenguid merged commit 5838f10 into kunchenguid:main Oct 6, 2026
21 checks passed
This was referenced Oct 6, 2026
umeranjum17 added a commit to umeranjum17/juggernaut that referenced this pull request Oct 9, 2026