Executive summary. Consider a deliberately hypothetical Bash consumer that reads two plausible records, reaches EOF, and gets zero from mapfile, while the process substitution generating those records was configured to terminate with status 7. Nothing in the successful read tells the consumer that its asynchronous producer succeeded. Linux pipe EOF answers whether writers remain; it does not carry a process exit status. Bash process substitution runs its command asynchronously, while mapfile reports the result of its own read operation. Those are different boundaries.
The practical repair is ownership, not another global shell switch. Acquire the process-substitution descriptor, immediately preserve the producer PID exposed through $!, consume into held state, close the descriptor, and have the same Bash process perform wait "$producer_pid". Only then compare the held records with an independently authored manifest. Bash documents both explicit per-child waiting and the special behavior of a no-argument wait; the latter is a completion barrier whose normal return is zero, not a substitute for the producer's individual status.
Everything below is a reproducible laboratory design, not a transcript. DOCUMENTED means a cited interface or semantic rule. EXPECTED / NOT EXECUTED means the fixture predicts a result but no command was run for this article. OBSERVED should be used only after an operator actually executes the supplied code and records the environment, identities, statuses, bytes, and cleanup evidence.
Define whose success can authorize the records
The acceptance contract comes before the Bash syntax. Records may be marked ACCEPT only when four independent conditions are present: the reader completed successfully; the identity of the required producer matches the process that was launched; the shell that owns that child obtained zero from wait "$producer_pid"; and the held records equal the expected sequence ["R1", "R2", "R3"] in identity and order. A zero in only one channel is insufficient.
That distinction matters because the underlying interfaces report different operations. Linux describes a pipe as a byte stream. EOF occurs after all file descriptors referring to its write end have been closed. Nothing in that EOF event communicates the writer's termination status. Bash separately documents that process substitution runs its command asynchronously and that mapfile reads lines from its input or a specified descriptor.
This is therefore a different execution boundary from Bash local assignment and hidden command failures, where a declaration can obscure a command-substitution result. Here the reader can truthfully report that it consumed everything the descriptor supplied while still knowing nothing about whether the asynchronous generator succeeded.
Use five decision labels consistently. ACCEPT means all required identity, status, content, and evidence checks passed. REJECT_PRODUCER means the identified required producer was explicitly waited for by its owner and returned nonzero. REJECT_MANIFEST means the producer succeeded but the exact records violate the independent manifest. HOLD_EVIDENCE means identity, ownership, status, cleanup, or required observations are unknown. REPAIR means the implementation itself uses an unsafe witness, for example, trusting reader success, a later value of $!, or bare wait. A diagnostic that successfully demonstrates such a defect can be a good test while remaining an unacceptable operational gate.
The reusable artifact is therefore an ownership-aware decision record. It keeps configured producer intent separate from the reader result, actual per-PID wait result, outer wrapper result, content completeness, and final acceptance. A planned exit code is configuration. Only a collected wait result is evidence of what that child actually returned.
Pin the shell and the input contract
Each case belongs in a new disposable directory. The authored success manifest is fixed before execution:
records = ["R1", "R2", "R3"]
full bytes:
52 31 0a 52 32 0a 52 33 0a
R1\nR2\nR3\n
prefix bytes:
52 31 0a 52 32 0a
R1\nR2\nEvery record is small ASCII and LF-terminated. The laboratory therefore does not test residual bytes after an unterminated final line, NUL-delimited records, mutable inputs, or arbitrary framing. The missing R3 in a prefix case is intentional producer content, not a parser edge case.
The semantic baseline is GNU Bash 5.3. Its reference manual identifies itself as Edition 5.3 for Bash 5.3 and documents process substitution on systems that provide FIFOs or /dev/fd-style naming. Dynamic {varname} descriptors are allocated by Bash and normally persist beyond the command so the script can manage their lifetime; the varredir_close option changes that behavior. This laboratory explicitly keeps varredir_close disabled.
Fresh shells are invoked as noninteractive bash --noprofile --norc processes. The external driver supplies a replacement environment rather than inheriting BASH_ENV, exported shell functions, SHELLOPTS, or BASHOPTS. It sets LC_ALL=C, disables job control inside the wrapper with set +m, and does not manufacture a fake HOME. Python documents that a non-None env mapping replaces normal inherited environment behavior for the subprocess.
Record executable and shell identity
Documentation versions are semantic references, not runtime proof. An executed report must contain the absolute selected Bash and CPython paths, their full version/build strings, the operating-system description, wrapper shell PID, run ID, and effective shell options. That is also why Bash executable lookup in the owning shell is relevant provenance: an assumed command name does not prove which executable an existing shell selected.
Require absolute paths on the driver command line rather than silently searching:
/path/to/python3.13 run_lab.py \
--bash /absolute/path/to/bash-5.3 \
--python /absolute/path/to/python3.13 \
--out ./evidenceThe driver below rejects nonabsolute paths and checks that the selected Python reports 3.13 and Bash reports a 5.3 version string. If a real execution disagrees with the documented baseline, do not reinterpret the result to fit the table. Record the mismatch and use HOLD_EVIDENCE until the behavior is investigated.
An executed inventory should preserve at least bash --version, the selected interpreter's sys.version, platform.platform(), wrapper $$, the run ID, set +o, shopt -p, the scripts used, stdout/stderr files, receipts, structured report, and validator result. Keep those artifacts under the case directory rather than relying on terminal history.
Build one owned asynchronous producer
The producer has deliberately little personality. It accepts a role, run ID, mode, planned exit code, and receipt pathname. A required producer emits either the full or prefix payload. A B09 sibling emits no records. The helper has no descendants, pipelines, services, timing protocol, or side effects outside its owned receipt and stdout.
Python's os.getpid() supplies its own process identity. Low-level os.write() returns the number of bytes actually written, so the helper loops until all declared bytes have been emitted rather than assuming one call consumed the entire buffer.
#!/usr/bin/env python3
# producer.py
import argparse
import os
import sys
FULL = b"R1\nR2\nR3\n"
PREFIX = b"R1\nR2\n"
def write_all(fd: int, data: bytes) -> None:
view = memoryview(data)
while view:
n = os.write(fd, view)
if n <= 0:
raise OSError("short/zero write")
view = view[n:]
def main() -> int:
p = argparse.ArgumentParser()
p.add_argument("--role", choices=("producer", "sibling"), required=True)
p.add_argument("--run-id", required=True)
p.add_argument("--mode", choices=("full", "prefix", "none"), required=True)
p.add_argument("--exit-code", type=int, required=True)
p.add_argument("--receipt", required=True)
args = p.parse_args()
payload = {
"full": FULL,
"prefix": PREFIX,
"none": b"",
}[args.mode]
fd = os.open(
args.receipt,
os.O_WRONLY | os.O_CREAT | os.O_EXCL,
0o600,
)
receipt = (
f"role\t{args.role}\n"
f"run_id\t{args.run_id}\n"
f"pid\t{os.getpid()}\n"
f"ppid\t{os.getppid()}\n"
f"mode\t{args.mode}\n"
f"planned_exit\t{args.exit_code}\n"
f"python_build\t{sys.version.replace(chr(10), ' ')}\n"
).encode("ascii")
write_all(fd, receipt)
os.close(fd)
write_all(1, payload)
return args.exit_code
if name == "__main__":
raise SystemExit(main())The receipt says planned_exit, not observed_exit. That distinction is intentional. The helper can state what it was instructed to return and identify itself, but only its parent shell can produce the laboratory's relevant observed wait status.
Capture the PID before another background launch
The central acquisition pattern is:
exec {source_fd}< <(
exec "$PYTHON" "$PRODUCER" \
--role producer \
--run-id "$run_id" \
--mode "$mode" \
--exit-code "$planned_rc" \
--receipt "$producer_receipt"
)
producer_pid=$!The explicit exec inside the process substitution replaces the substitution shell with the selected Python process, making the identity comparison simple: the PID Bash exposes for that substitution is expected to be the same PID written by os.getpid() in the producer receipt. Bash documents process substitution as asynchronous; Chet Ramey's 2024 clarification explains that the process-substitution PID is exposed through $! so callers can wait for it.
Capture $! immediately. Bash defines $! in terms of the most recently backgrounded job, and the documented no-argument wait behavior also refers specifically to the last process substitution when its PID still equals $!. A later background launch changes the evidence you are looking at.
If descriptor acquisition fails, $! is empty, the receipt never appears, or its PID does not reconcile with producer_pid, do not guess. Close whatever owned state can be safely closed, preserve the evidence, and assign HOLD_EVIDENCE.
Reproduce the consumer-only false success
B01 and B02 establish the defect without pretending to be production gates. B01 is the positive diagnostic baseline: full records and planned producer exit 0. B02 supplies only R1 and R2 and plans to exit 7.
The relevant reader is deliberately ordinary:
records=()
if mapfile -t -u "$source_fd" records; then
reader_rc=0
else
reader_rc=$?
fiThe Bash manual documents mapfile as a builtin that reads lines from standard input or a descriptor supplied with -u. Its exit status concerns that operation (for example, invalid descriptors and assignment errors), not the asynchronous producer's independent termination status.
In B02, the unsafe witness may visibly make its bad decision:
if (( reader_rc == 0 )); then
printf '%s\n' 'NAIVE_ACCEPT'
fiThat marker is diagnostic. It is not the approved ACCEPT marker. After exposing the mistake, the script still waits for the saved producer PID so the report can prove why the naive decision was wrong:
if wait "$producer_pid"; then
producer_rc=0
else
producer_rc=$?
fiThe B02 wrapper deliberately returns zero after diagnostic cleanup. That policy is authored to preserve the misleading outer-success witness. It must not be described as the natural result of the later checked wait; the wait is expected to return 7.
The expected distinction is:
Case | Reader | Records | Explicit producer wait | Wrapper policy | Operational interpretation |
B01 | 0 | R1,R2,R3 | 0 | 0 | ACCEPT as diagnostic baseline evidence |
B02 | 0 | R1,R2 | 7 | 0 deliberately | REPAIR; records are also REJECT_PRODUCER |
Both rows are EXPECTED / NOT EXECUTED. An operator must replace the numbers in the “observed” report only with values captured from an actual run.
Check what errexit and pipefail actually cover
B03 enables errexit and pipefail, asks the producer to emit the complete three-record sequence, and configures that producer to exit 7. The point is not that these options are useless. The point is that they monitor different shell execution boundaries.
Process substitution is documented as an asynchronous expansion. mapfile remains the foreground command consuming its descriptor. Therefore a successful mapfile does not become nonzero merely because the asynchronous process later terminates unsuccessfully. pipefail changes how Bash derives a foreground pipeline's status; it does not manufacture an asynchronous process-substitution status and attach it to mapfile.
The fixture avoids the separate question of whether some intermediate command inside the producer should trigger errexit. The Python helper simply emits its configured bytes and exits with its explicit final code. B03 therefore asks one narrow question: can the foreground reader finish successfully while the asynchronous producer's final status is 7? The expected answer under the documented boundary is yes.
The wrapper can record that the options were active during the read:
if [[ "$case_id" == B03 ]]; then
set -e
set -o pipefail
fi
records=()
mapfile -t -u "$source_fd" records
reader_rc=$?
if [[ "$case_id" == B03 ]]; then
set +e
fiThe production-quality version later uses explicit conditional status handling rather than depending on set -e. B03's role is diagnostic: correctly demonstrating continuation does not authorize the unsafe implementation.
Keep process substitution outside the foreground pipeline contract
Bash defines PIPESTATUS as the statuses from the most recently executed foreground pipeline. That wording is the critical boundary. A process substitution is an asynchronous expansion, not another slot you can assume will appear in the reader's foreground pipeline vector.
If the actual problem is preserving a test producer and logging sink across a foreground pipeline, pipeline status checks around tee address that different topology. This laboratory does not reproduce its PIPESTATUS matrix.
No amount of more careful preservation of mapfile's zero can create the missing producer evidence. The relevant new datum must come from the process-substitution child's identity and an explicit wait performed by the shell that owns it.
A useful mental model is:
|
Compare bare wait with an explicit PID wait
B04 is intentionally deceptive. The producer emits the full manifest but is configured to return 7. After mapfile finishes, the wrapper closes the descriptor and calls:
if wait; then
bare_wait_rc=0
else
bare_wait_rc=$?
fiBash 5.3 documentation is unusually explicit here: when wait receives no options or IDs, it waits for all running background jobs and the last-executed process substitution if that substitution's PID is still $!, and the return status is zero.
Therefore B04's expected evidence is bare_wait_rc=0, while the dedicated producer_rc field remains absent or null. Do not populate producer_rc=7 merely because the case configuration requested 7. That would convert an expectation into fabricated observation.
The dated maintainer explanation is useful context. Ramey wrote in July 2024 that process substitutions are word expansions rather than ordinary background jobs, while also explaining that the PID exposure through $! exists so callers can wait for it. That history should not be inflated into a claim that this behavior was introduced in 2024 or 2026.
Do not follow the bare wait with wait "$producer_pid" and assume Bash must still retain the individual status for your experiment. B04 is designed to test what evidence bare wait itself supplies. Once that operation has consumed completion handling, the laboratory should not invent a second contract. A completion barrier answers “have the relevant asynchronous activities completed?” An explicit per-PID wait answers “what status did this identified child return?” Those are different questions.
Hold the records until the producer has been checked
B05 through B08 use the guarded path. Records are never approved directly from the live descriptor. The wrapper first stores them in an array, closes the owned descriptor, reaps the saved producer, validates identity and content, and only then decides whether an inert approval marker may be printed.
The central pattern is:
records=()
if mapfile -t -u "$source_fd" records; then
reader_rc=0
else
reader_rc=$?
fi
exec {source_fd}<&-
if wait "$producer_pid"; then
producer_rc=0
else
producer_rc=$?
fiClosing the descriptor explicitly matters to the fixture's ownership discipline. Bash's dynamic-descriptor documentation says {varname} redirections persist for manual management unless varredir_close changes that behavior. The laboratory keeps that option off and owns the close itself.
Reader failure does not excuse abandoning the child. A guarded wrapper still reaps the known producer before making a final decision. Likewise, receipt absence, PID mismatch, an unknown wait target, or cleanup uncertainty cannot be “fixed” by complete-looking records.
The complete wrapper below implements all ten cases. It writes simple tab-separated facts whose values are constrained to the fixture's controlled ASCII domain.
#!/usr/bin/env bash
# wrapper.bash
set -u
set +m
shopt -u varredir_close
case_id=$1
run_id=$2
mode=$3
planned_rc=$4
BASH_PATH=$5
PYTHON=$6
PRODUCER=$7
case_dir=$8
facts=$case_dir/facts.tsv
producer_receipt=$case_dir/producer.receipt
sibling_receipt=$case_dir/sibling.receipt
wrong_owner=$case_dir/nonowner.tsv
: >"$facts"
fact() { printf '%s\t%s\n' "$1" "$2" >>"$facts"; }
fact case_id "$case_id"
fact run_id "$run_id"
fact shell_pid "$$"
fact bash_version "$BASH_VERSION"
fact mode "$mode"
fact planned_exit "$planned_rc"
fact varredir_close off
fact job_control off
set +o >"$case_dir/set-options.txt"
shopt -p >"$case_dir/shopt-options.txt"
exec {source_fd}< <(
exec "$PYTHON" "$PRODUCER" \
--role producer \
--run-id "$run_id" \
--mode "$mode" \
--exit-code "$planned_rc" \
--receipt "$producer_receipt"
)
producer_pid=${!:-}
if [[ -z "$producer_pid" || -z "${source_fd:-}" ]]; then
fact decision HOLD_EVIDENCE
exit 72
fi
fact source_fd "$source_fd"
fact producer_pid "$producer_pid"
sibling_pid=
if [[ "$case_id" == B09 ]]; then
"$PYTHON" "$PRODUCER" \
--role sibling \
--run-id "$run_id" \
--mode none \
--exit-code 0 \
--receipt "$sibling_receipt" \
>/dev/null 2>>"$case_dir/sibling.stderr" &
sibling_pid=$!
fact sibling_pid "$sibling_pid"
fact dollar_bang_after_sibling "$!"
fi
if [[ "$case_id" == B03 ]]; then
set -e
set -o pipefail
fact errexit on
fact pipefail on
else
fact errexit off
fact pipefail off
fi
records=()
if mapfile -t -u "$source_fd" records; then
reader_rc=0
else
reader_rc=$?
fi
if [[ "$case_id" == B03 ]]; then
set +e
fi
fact reader_rc "$reader_rc"
fact record_count "${#records[@]}"
for i in "${!records[@]}"; do
fact "record_$i" "${records[$i]}"
done
if [[ "$case_id" == B02 && "$reader_rc" -eq 0 ]]; then
printf '%s\n' NAIVE_ACCEPT
fi
exec {source_fd}<&-
manifest_ok=0
if (( ${#records[@]} == 3 )) &&
[[ "${records[0]-}" == R1 ]] &&
[[ "${records[1]-}" == R2 ]] &&
[[ "${records[2]-}" == R3 ]]; then
manifest_ok=1
fi
fact manifest_ok "$manifest_ok"
producer_rc=
bare_wait_rc=
if [[ "$case_id" == B04 ]]; then
if wait; then
bare_wait_rc=0
else
bare_wait_rc=$?
fi
fact wait_mode bare
fact bare_wait_rc "$bare_wait_rc"
fact decision HOLD_EVIDENCE
exit 0
fi
if [[ "$case_id" == B10 ]]; then
env -i PATH="$PATH" LC_ALL=C \
"$BASH_PATH" --noprofile --norc -c '
set +m
out=$1
target=$2
printf "shell_pid\t%s\n" "$$" >"$out"
printf "wait_target\t%s\n" "$target" >>"$out"
if wait "$target"; then rc=0; else rc=$?; fi
printf "wait_rc\t%s\n" "$rc" >>"$out"
exit 0
' "$wrongowner" "$producer_pid"
fi
if wait "$producer_pid"; then
producer_rc=0
else
producer_rc=$?
fi
fact wait_mode explicit_pid
fact wait_target "$producer_pid"
fact wait_owner "$$"
fact producer_rc "$producer_rc"
if [[ -n "$sibling_pid" ]]; then
if wait "$sibling_pid"; then
sibling_rc=0
else
sibling_rc=$?
fi
fact sibling_rc "$sibling_rc"
fi
case "$case_id" in
B01)
if (( reader_rc == 0 && producer_rc == 0 && manifest_ok == 1 )); then
fact decision ACCEPT
exit 0
fi
fact decision HOLD_EVIDENCE
exit 72
;;
B02|B03)
fact decision REPAIR
exit 0
;;
B05)
if (( reader_rc == 0 && producer_rc == 0 && manifest_ok == 1 )); then
fact decision ACCEPT
printf '%s\n' ACCEPT
exit 0
fi
fact decision HOLD_EVIDENCE
exit 72
;;
B06|B07|B09|B10)
if (( producer_rc != 0 )); then
fact decision REJECT_PRODUCER
exit 70
fi
fact decision HOLD_EVIDENCE
exit 72
;;
B08)
if (( producer_rc == 0 && manifest_ok == 0 )); then
fact decision REJECT_MANIFEST
exit 71
fi
fact decision HOLD_EVIDENCE
exit 72
;;
*)
fact decision HOLD_EVIDENCE
exit 72
;;
esacThe wrapper's 70, 71, and 72 are laboratory policy codes, not Bash's producer result. Keep wrapper_rc and producer_rc separate.
Preserve the failed wait code in the owning shell
The safe failure-preservation idiom is deliberately plain:
if wait "$producer_pid"; then
producer_rc=0
else
producer_rc=$?
fiCapture $? immediately in the else branch. Do not write if ! wait "$producer_pid"; then producer_rc=$?; fi, because $? there describes the negated command result rather than preserving the child's original failure in the straightforward way this fixture requires.
For B05 the expected producer result is zero, the manifest matches, and exactly one inert ACCEPT marker is emitted. For the known failure cases, the fixture expects the per-PID wait to preserve producer code 7 in producer_rc, while a separate wrapper rejection code expresses the gate's policy.
Require the independent record manifest
Producer success and content completeness are orthogonal. B06 uses prefix output and planned exit 7. B07 uses the complete sequence but planned exit 7. Both should become REJECT_PRODUCER once the identified producer's explicit wait returns 7.
B08 supplies the complementary control: prefix output with producer exit 0. That case prevents the wrapper from degenerating into “status zero means business-valid data.” Its expected decision is REJECT_MANIFEST.
The distinction can be summarized without relying on record count alone:
Case | Expected records | Expected producer status | Manifest | Decision |
B05 | R1,R2,R3 | 0 | match | ACCEPT |
B06 | R1,R2 | 7 | mismatch | REJECT_PRODUCER |
B07 | R1,R2,R3 | 7 | match | REJECT_PRODUCER |
B08 | R1,R2 | 0 | mismatch | REJECT_MANIFEST |
B07 is important because complete-looking output cannot pardon producer failure. B08 is equally important because producer status zero cannot establish business completeness. The manifest is authored before execution and checks exact values and order, not merely record_count == 3.
The neighboring article on Bash record boundaries at EOF handles an intentionally different problem: preserving a final record whose file does not end in the expected line terminator. This fixture excludes that ambiguity by generating only LF-terminated records.
The manifest proves only this declared synthetic contract. It does not establish schema correctness for arbitrary records, durability, atomic publication, exactly-once execution, or fitness of a real dataset.
Detect a changed $! and the wrong process
B09 captures the required producer PID and then starts one separate known background sibling. The required producer emits the full manifest but is configured to return 7; the sibling emits no records and returns zero.
Immediately after the sibling launch, Bash's $! is expected to identify the sibling rather than the original process substitution because $! denotes the most recently backgrounded job.
The report must therefore keep these identities distinct:
producer_pid
producer.receipt: pid, role=producer, run_id
sibling_pid
sibling.receipt: pid, role=sibling, run_id
dollar_bang_after_sibling
wait_target for producer
producer_rc
sibling_rcThe important expected comparison is not “some child returned zero.” It is:
producer_pid == producer receipt PID
sibling_pid == sibling receipt PID
dollar_bang_after_sibling == sibling_pid
wait_target == producer_pid
producer_rc == 7
sibling_rc == 0That yields REJECT_PRODUCER. Waiting on the later $! and observing zero would prove only that the known sibling succeeded.
Do not repair this by scanning /proc, matching process names, repeatedly sampling $!, or assuming launch order from scheduler behavior. Ownership metadata is cheapest and strongest at the point of creation: save the PID, run ID, role, receipt path, and intended wait owner when the process is launched. If those observations cannot be reconciled later, use HOLD_EVIDENCE.
B09 is also why the manifest alone is insufficient. It deliberately gives the required failing producer complete-looking output. The wrong child's zero and the right records can coexist. Only identity-bound status collection tells the wrapper which result belongs to the process authorized to generate them.
Test the wait from a different shell
B10 tests the other half of process ownership. The original wrapper saves its producer PID, consumes the full records, and starts a separate fresh Bash process whose only task is to attempt wait on that PID.
That new Bash process is not the producer's parent. Bash documents wait in terms of child processes and says that when a supplied identifier does not name a child the shell can wait for, the result is 127.
The expected B10 evidence therefore looks conceptually like this:
original_shell_pid = <observed after execution>
producer_pid = <observed after execution>
nonowner_shell_pid = <different observed PID>
nonowner_wait_target = producer_pid
nonowner_wait_rc = 127
original_wait_target = producer_pid
original_wait_owner = original_shell_pid
original_producer_rc = 7Those placeholders remain unfilled here because the laboratory was not executed.
The original shell still performs wait "$producer_pid" after the nonowning attempt. Its expected result is 7. That is the status relevant to REJECT_PRODUCER.
This case does not test descendant supervision. The separate discussion of inherited stdout and Python subprocess EOF examines a child/descendant topology where file-descriptor inheritance can keep a pipe open after a direct child exits. Our producer creates no descendants, so control sockets, pidfds, subreapers, and descendant cleanup would only obscure the ownership question here.
Distinguish an unknown child from producer failure
A 127 from the nonowning shell cannot be relabeled “the producer returned 127.” It means that this shell did not possess a waitable child matching the requested identifier under Bash's documented wait contract.
This distinction is operationally important. producer_rc=7 says something about the identified producer because its owner collected that child's status. nonowner_wait_rc=127 says something about the attempted observation: the observer lacked the ownership relationship needed to collect the target's result.
That is also why evidence schemas need an explicit wait_owner and wait_target. A naked field called exit_code invites the reviewer to merge fundamentally different events.
Reconcile every case with its captured evidence
The full matrix below is the oracle for expected behavior, not a substitute for observations.
Case | Configuration | Observed fields now | EXPECTED / NOT EXECUTED | Decision | Evidence required |
B01 | full / 0 | unfilled | reader 0; producer wait 0; exact manifest | ACCEPT | PID/receipt match, explicit owner wait, records |
B02 | prefix / 7 | unfilled | reader 0; NAIVE_ACCEPT; producer 7; wrapper 0 | REPAIR; records reject producer | saved PID, reader result, producer wait, marker |
B03 | full / 7; errexit, pipefail on during read | unfilled | reader continues successfully; producer 7 | REPAIR; records reject producer | option inventory, PID, wait result |
B04 | full / 7; bare wait | unfilled | bare wait 0; individual producer status not collected | HOLD_EVIDENCE | bare-wait field distinct from producer status |
B05 | full / 0 | unfilled | explicit producer wait 0; exact manifest; one ACCEPT | ACCEPT | complete identity/status/content inventory |
B06 | prefix / 7 | unfilled | producer 7; manifest mismatch | REJECT_PRODUCER | explicit owner wait plus records |
B07 | full / 7 | unfilled | producer 7; manifest match | REJECT_PRODUCER | explicit owner wait plus records |
B08 | prefix / 0 | unfilled | producer 0; manifest mismatch | REJECT_MANIFEST | explicit wait and exact manifest |
B09 | full / 7 + sibling / 0 | unfilled | $! changes to sibling; producer 7; sibling 0 | REJECT_PRODUCER | both receipts, both targets and statuses |
B10 | full / 7 + nonowning Bash | unfilled | nonowner wait 127; owner wait 7 | REJECT_PRODUCER | both shell PIDs and both wait results |
The external driver creates a unique run ID, one directory per case, regular files for stdout and stderr, and a fresh wrapper process group. Python's subprocess API accepts an argument vector, an explicit replacement env, existing file objects for standard streams, bounded waits, and start_new_session=True; these are the documented primitives used here.
#!/usr/bin/env python3
# run_lab.py
import argparse
import json
import os
import platform
import signal
import subprocess
import sys
import uuid
from pathlib import Path
CASES = {
"B01": ("full", 0),
"B02": ("prefix", 7),
"B03": ("full", 7),
"B04": ("full", 7),
"B05": ("full", 0),
"B06": ("prefix", 7),
"B07": ("full", 7),
"B08": ("prefix", 0),
"B09": ("full", 7),
"B10": ("full", 7),
}
def run_text(argv, env):
p = subprocess.run(
argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
env=env, check=False
)
return p.returncode, p.stdout.decode("utf-8", "replace"), \
p.stderr.decode("utf-8", "replace")
def parse_tsv(path):
out = {}
if not path.exists():
return out
for raw in path.read_text("utf-8").splitlines():
key, sep, value = raw.partition("\t")
if sep:
out[key] = value
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--bash", required=True)
ap.add_argument("--python", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--timeout", type=float, default=5.0)
ns = ap.parse_args()
bash = Path(ns.bash)
python = Path(ns.python)
if not bash.is_absolute() or not python.is_absolute():
raise SystemExit("Bash and Python paths must be absolute")
base = Path(ns.out).resolve()
base.mkdir(parents=True, exist_ok=False)
here = Path(__file__).resolve().parent
wrapper = (here / "wrapper.bash").resolve()
producer = (here / "producer.py").resolve()
env = {
"PATH": os.environ.get("PATH", "/usr/bin:/bin"),
"LC_ALL": "C",
}
brc, bout, berr = run_text([str(bash), "--version"], env)
prc, pout, perr = run_text(
[str(python), "-c",
"import sys; print(sys.version.replace(chr(10),' '))"], env
)
metadata = {
"laboratory": "refonte-process-substitution-v1",
"status_at_article_publication": "EXPECTED / NOT EXECUTED",
"bash_path": os.path.realpath(bash),
"bash_version_command_rc": brc,
"bash_version": bout,
"bash_version_stderr": berr,
"python_path": os.path.realpath(python),
"python_version_command_rc": prc,
"python_build": pout.strip(),
"python_version_stderr": perr,
"driver_build": sys.version.replace("\n", " "),
"os": platform.platform(),
}
(base / "runtime.json").write_text(
json.dumps(metadata, indent=2) + "\n", "utf-8"
)
if "version 5.3" not in bout.lower():
raise SystemExit("HOLD_EVIDENCE: selected Bash is not 5.3")
if not pout.startswith("3.13."):
raise SystemExit("HOLD_EVIDENCE: selected Python is not 3.13")
run_id = uuid.uuid4().hex
for case_id, (mode, planned_rc) in CASES.items():
case_dir = base / case_id
case_dir.mkdir()
stdout_path = case_dir / "stdout.bin"
stderr_path = case_dir / "stderr.bin"
argv = [
str(bash), "--noprofile", "--norc", str(wrapper),
case_id, run_id, mode, str(planned_rc),
str(bash), str(python), str(producer), str(case_dir)
]
timed_out = False
cleanup = []
with stdout_path.open("wb") as out, stderr_path.open("wb") as err:
proc = subprocess.Popen(
argv,
cwd=case_dir,
env=env,
stdout=out,
stderr=err,
start_new_session=True,
)
try:
wrapper_rc = proc.wait(timeout=ns.timeout)
except subprocess.TimeoutExpired:
timed_out = True
cleanup.append("SIGTERM_PROCESS_GROUP")
os.killpg(proc.pid, signal.SIGTERM)
try:
wrapper_rc = proc.wait(timeout=1.0)
except subprocess.TimeoutExpired:
cleanup.append("SIGKILL_PROCESS_GROUP")
os.killpg(proc.pid, signal.SIGKILL)
wrapper_rc = proc.wait(timeout=1.0)
facts = parse_tsv(case_dir / "facts.tsv")
producer_receipt = parse_tsv(case_dir / "producer.receipt")
sibling_receipt = parse_tsv(case_dir / "sibling.receipt")
nonowner = parse_tsv(case_dir / "nonowner.tsv")
report = {
"case_id": case_id,
"run_id": run_id,
"configured": {
"mode": mode,
"planned_exit": planned_rc,
},
"wrapper_pid": proc.pid,
"wrapper_rc": wrapper_rc,
"timed_out": timed_out,
"cleanup": cleanup,
"facts": facts,
"producer_receipt": producer_receipt,
"sibling_receipt": sibling_receipt or None,
"nonowner_wait": nonowner or None,
"stdout_hex": stdout_path.read_bytes().hex(),
"stderr_hex": stderr_path.read_bytes().hex(),
}
(case_dir / "report.json").write_text(
json.dumps(report, indent=2) + "\n", "utf-8"
)
if name == "__main__":
main()start_new_session=True creates a new session for the direct wrapper on POSIX; the driver then knows the process-group ID it created. On timeout, this laboratory uses os.killpg() only against that owned group, which Python documents as sending a signal to the specified process group. The bounded cleanup policy does not imply universal descendant supervision outside this fixture.
Reject missing, duplicate, and mismatched observations
Validation must fail closed. Every case ID must occur exactly once. Run IDs must agree. Receipt PIDs must match launch-time ownership records. Explicit waits need a target, owner, and result. B09 requires both child identities. B10 requires a distinct nonowner shell record. B05 needs exactly one ACCEPT; no other case may contain it.
An independent validator can enforce those structural properties before a human interprets the matrix:
#!/usr/bin/env python3
# validate.py
import argparse
import copy
import json
from pathlib import Path
EXPECTED = {f"B{i:02d}" for i in range(1, 11)}
def fail(msg):
raise ValueError(msg)
def validate_reports(reports):
ids = [r.get("case_id") for r in reports]
if set(ids) != EXPECTED or len(ids) != len(EXPECTED):
fail("missing, extra, or duplicate case IDs")
run_ids = {r.get("run_id") for r in reports}
if len(run_ids) != 1 or None in run_ids:
fail("run ID mismatch")
by_id = {r["case_id"]: r for r in reports}
for cid, r in by_id.items():
if r.get("timed_out"):
fail(f"{cid}: cleanup uncertainty")
f = r.get("facts", {})
receipt = r.get("producer_receipt", {})
if not f.get("producer_pid"):
fail(f"{cid}: missing producer PID")
if receipt.get("role") != "producer":
fail(f"{cid}: bad producer role")
if receipt.get("run_id") != r["run_id"]:
fail(f"{cid}: producer run ID mismatch")
if receipt.get("pid") != f.get("producer_pid"):
fail(f"{cid}: producer PID mismatch")
if cid == "B04":
if "bare_wait_rc" not in f:
fail("B04: missing bare-wait observation")
if "producer_rc" in f:
fail("B04: individual producer status must remain unclaimed")
else:
for key in ("wait_mode", "wait_target",
"wait_owner", "producer_rc"):
if key not in f:
fail(f"{cid}: missing {key}")
if f["wait_mode"] != "explicit_pid":
fail(f"{cid}: wrong wait mode")
if f["wait_target"] != f["producer_pid"]:
fail(f"{cid}: wrong wait target")
if f["wait_owner"] != f["shell_pid"]:
fail(f"{cid}: wrong wait owner")
b09 = by_id["B09"]
f9 = b09["facts"]
s9 = b09.get("sibling_receipt") or {}
if s9.get("role") != "sibling":
fail("B09: sibling identity missing")
if s9.get("pid") != f9.get("sibling_pid"):
fail("B09: sibling PID mismatch")
if f9.get("dollar_bang_after_sibling") != f9.get("sibling_pid"):
fail("B09: changed $! not reconciled")
b10 = by_id["B10"]
n10 = b10.get("nonowner_wait") or {}
if not n10.get("shell_pid") or not n10.get("wait_rc"):
fail("B10: nonowner observation missing")
if n10["shell_pid"] == b10["facts"]["shell_pid"]:
fail("B10: nonowner shell not distinct")
accept_count = 0
for r in reports:
out = bytes.fromhex(r["stdout_hex"]).splitlines()
accept_count += sum(line == b"ACCEPT" for line in out)
if accept_count != 1:
fail("approved ACCEPT marker count is not exactly one")
def load_reports(root):
return [
json.loads(p.read_text("utf-8"))
for p in sorted(Path(root).glob("B*/report.json"))
]
def oracle_selftest(reports):
damaged = []
a = copy.deepcopy(reports)
for r in a:
if r["case_id"] == "B05":
del r["facts"]["producer_rc"]
damaged.append(("delete_wait_observation", a))
b = copy.deepcopy(reports)
b.append(copy.deepcopy(b[0]))
damaged.append(("duplicate_case", b))
c = copy.deepcopy(reports)
for r in c:
if r["case_id"] == "B09":
r["producer_receipt"]["pid"] = "999999"
damaged.append(("alter_pid", c))
for name, specimen in damaged:
try:
validate_reports(specimen)
except ValueError:
print(f"DIAGNOSTIC_PASS {name}")
else:
fail(f"negative oracle was accepted: {name}")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("root")
ap.add_argument("--oracle-selftest", action="store_true")
ns = ap.parse_args()
reports = load_reports(ns.root)
validate_reports(reports)
print("STRUCTURE_VALID")
if ns.oracle_selftest:
oracle_selftest(reports)
if name == "__main__":
main()The negative controls delete a required wait observation, duplicate a case, and falsify the B09 producer PID. Their expected rejection demonstrates validator sensitivity; a future DIAGNOSTIC_PASS from those tests still does not mean B01–B10 operational evidence is acceptable. Never backfill a missing observation from this article's expected table.
Recover without reusing failed-run records
Rejected records are evidence, not retry input. Preserve the original case directory, including held record fields, receipts, wrapper streams, structured report, runtime inventory, and cleanup state. Mark that run rejected or held without rewriting its evidence.
Then repair the ownership defect and rerun from the original declared input with a new run ID. If the defect was late $! capture, save the PID at launch. If the problem was a nonowning wait, move status collection back into the shell that owns the child. If the manifest itself was wrong, review and version the manifest rather than quietly accepting the observed payload.
Do not concatenate R1,R2 from a failed prefix run with R3 produced by a retry. That would create a new record stream that neither producer emitted under the fixture contract. Likewise, the mere presence of producer.receipt proves neither successful termination nor acceptance; its planned_exit is intentionally not an observed wait result.
Timeout or uncertain cleanup deserves a different response from ordinary rejection. A clean producer_rc=7 is strong negative evidence and supports REJECT_PRODUCER. A timeout followed by incomplete cleanup means the laboratory cannot establish a complete end state and should use HOLD_EVIDENCE, even if the available records look correct.
The driver's process-group cleanup is deliberately bounded. Python documents Popen.wait(timeout=...), start_new_session, and process-group signaling interfaces, but none of those facts turns this fixture into arbitrary process-tree supervision.
Restore only fixture state you explicitly own. If a real operational workflow has a separately proven, previously accepted snapshot, selecting that snapshot can be a rollback policy; it does not retroactively validate the rejected run. Production integration would need its own contracts for persistence, downstream consumers, cancellation, replay, and publication. Those guarantees are outside this laboratory.
Apply the acceptance matrix and assign owners
A reviewer should be able to reach the decision without guessing what a particular zero means.
Evidence condition | Decision | Primary owner | Required action |
Reader 0, matching producer identity, explicit owner wait 0, exact manifest, complete cleanup | ACCEPT | Wrapper + consumer reviewer | Preserve evidence and approved marker |
Explicit owner wait reports identified producer nonzero | REJECT_PRODUCER | Producer contract owner | Diagnose producer; do not use held records |
Producer 0 but exact sequence mismatches | REJECT_MANIFEST | Consumer manifest owner | Correct producer/content contract before rerun |
Wait result belongs to sibling or PID cannot be reconciled | HOLD_EVIDENCE | Wrapper PID/wait owner | Repair launch-time ownership metadata |
Wait attempted only by nonowning shell | HOLD_EVIDENCE | Wrapper PID/wait owner | Collect status in owning shell |
Bare-wait zero is the only completion evidence | HOLD_EVIDENCE | Wrapper PID/wait owner | Replace with explicit saved-PID wait |
Implementation accepts on reader success alone | REPAIR | Wrapper maintainer | Add ownership/status/content gate |
Timeout or incomplete cleanup | HOLD_EVIDENCE | Laboratory/reviewer owner | Preserve evidence and investigate cleanup |
Ownership is intentionally split. The producer contract owner defines what the generator may emit and what its exit statuses mean. The wrapper owner captures the PID, retains the descriptor, waits from the correct shell, and keeps wrapper policy codes separate from producer codes. The consumer manifest owner defines the exact authorized records independently of what was observed. The reviewer checks that the evidence set is complete, unique, internally consistent, and tied to one run ID.
Acceptance criteria should forbid missing B01–B10 rows, duplicate case IDs, inferred statuses, mismatched receipts, guessed identities, duplicate ACCEPT markers, and approval printed before producer and manifest checks. The acceptance marker is intentionally inert; it represents a decision record, not publication.
Diagnostic success and operational acceptance must remain separate. If B02 prints NAIVE_ACCEPT and the later explicit owner wait records 7, the laboratory has successfully reproduced the unsafe condition. The proper implementation decision remains REPAIR. If B03 shows that mapfile can finish under errexit and pipefail while the producer later yields 7, that is likewise a useful diagnostic result, not permission to rely on those options as the gate.
The final reviewable handoff should include the original helper, wrapper, driver and validator; expected manifest; absolute executable paths; runtime builds; run ID; case configuration; option inventory; regular stdout/stderr files; producer and sibling receipts; nonowner evidence; structured case reports; cleanup records; validator output; and explicit limitations.
As of the December 3, 2026 research cutoff, the relevant Bash manual is Edition 5.3, last updated May 18, 2025; the maintainer clarification is dated July 3, 2024; Linux pipe(7) documents pipe EOF and byte-stream semantics; and the referenced Python 3.13 documentation exposes the subprocess, PID, write, and process-group operations used by this controlled driver. These are documentation baselines. Actual runtime behavior still has to be captured before any case moves from EXPECTED to OBSERVED.
Develop disciplined scripting through the DevOps Engineering Program
This ownership exercise is a narrow Bash laboratory, not a claim that a specific training syllabus teaches process-substitution PID capture or this exact B01–B10 fixture.
Refonte Learning's DevOps Engineering Program does list Linux fundamentals and scripting alongside Git/GitHub and CI/CD, which are directly relevant foundations for reasoning about shell wrappers and automation gates. The current page describes a three-month program with a stated commitment of 12–14 hours per week and an admission requirement of being engaged in bachelor's or postgraduate studies. Its curriculum also names Docker/Kubernetes, Terraform, AWS/Azure/GCP, monitoring and logging, and a capstone.
The page describes educational mentoring and virtual internship opportunities, and says successful completion carries a Training Certificate and a Certificate of Internship. It names DevOps Engineer, Cloud Engineer, and Site Reliability Engineer as career directions; that should not be converted into an employment guarantee. Its FAQ calls Jenkins, Prometheus, and Grafana common DevOps tools, which is weaker than claiming each is a confirmed dedicated curriculum module.
For engineers who want structured practice around Linux scripting and CI/CD reasoning, the useful connection is the discipline shown here: identify the operation whose result matters, preserve process ownership, keep evidence channels distinct, and refuse to turn missing observations into success. Review the program's current requirements and published curriculum directly before deciding whether that study format fits your goals.

