Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Preserve operator boot jobs during Unraid agent upgrades
pulse-triage[bot]f56b7e2b38bc
diff --git a/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md b/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.mdindex a4efa6fa66..04472457be 100644--- a/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md+++ b/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md@@ -1336,3 +1336,21 @@ as verification progresses:removal against the production writer's output.- Confined source checks are not native NAS lifecycle or customer acceptance;original QNAP installed-recovery dependencies remain independent.++### Unraid boot replacement preservation++- `TestInstallSHUnraidBootReplacementPreservesUnrelatedJobs`: twenty actual+ producer/caller controls preserve unrelated jobs, exact legacy/current+ entries, complete CRLF and modes. Ambiguous/foreign/compound launches and+ launch-like heredoc/quote/continuation data are refused unchanged. Bounded+ prefix and candidate syntax checks never execute boot text.+- Copy/rename/parser/render/write/readback/cleanup failures, linked files,+ pending recovery and concurrent changes cannot be called configured. Partial+ first creation retains the staged candidate and prevents a blind retry.+ Actual caller failure exits before watchdog start or reboot-success output.+ The no-chmod control preserves the FAT boundary without claiming to mount+ real FAT; go is consumed through bash, not execute bits.+- Existing `TestInstallSHUnraidGoEntryDoesNotBlockLaterBootLines` retains the+ boot-logger/foreground adverse control and detached launch; the production+ NAS removal inventory consumes this writer. These are source fixtures, not+ native Unraid lifecycle or original installed-recovery acceptance.diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 889a5599ef..a3921c025a 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -10467,3 +10467,31 @@ content, filesystem/write failures, concurrent source changes and unmountfailure. The existing NAS removal inventory consumes the changed writer too.These checks establish boot-file preservation and truthful local completion,not a native QNAP install/reboot/update/removal or resolution of #2897/#1617.++### Unraid upgrade boot-file ownership (27 October 2026)++The Unraid writer replaces only exact generated top-level launches, including+the earlier foreground form. A hand-edited, compound, indirect or foreign+launch is preserved and refused, not erased together with unrelated jobs.+Exact-looking text inside a heredoc, quote, compound or continued line is not+an owned entry. Bounded syntax-only prefix checks admit at most sixteen owned+entries; boot text is never evaluated. Complete CRLF input is normalised as+Unraid's fromdos does; incomplete or malformed content is not repaired silently.++Replacement is staged on the boot filesystem, preserves the existing mode and+compares the original before rename. Linked/unknown files, pending recovery,+failed preparation or readback cannot yield a configured verdict. A partial+first write retains its staged candidate and bars a blind retry. Registration+failure stops before starting the watchdog or claiming reboot persistence;+the agent may already have been stopped earlier in installation.++Unraid boot media need not support chmod or execute bits. Registration does+not require either: rc.local consumes go through bash. Ordinary Unix modes+are preserved when copying the existing file; FAT mount masks remain its own+semantics. The no-chmod control models that boundary, not a native FAT mount.++`TestInstallSHUnraidBootReplacementPreservesUnrelatedJobs` runs twenty+ordinary-user producer/caller controls through the normal installer inventory.+Existing boot-logger and NAS-removal tests retain detached execution and exact+removal compatibility. Source fixtures do not establish native Unraid lifecycle+or original installed-recovery acceptance.diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.mdindex e44868e8aa..9cf3b69caf 100644--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md@@ -15,6 +15,27 @@```## Purpose+### Unraid boot replacement preserves operator work++Agent setup/upgrade replaces only complete exact generated top-level go entries.+Unknown/compound/foreign launches and launch-like data remain untouched and+require reconciliation. The writer normalises complete CRLF input, stages on+the boot filesystem, parses without execution, compares the original before+rename and checks final bytes. Existing modes and unrelated jobs survive.+Linked/incomplete/malformed content, pending recovery and failed writes or+readback cannot be reported as reboot persistence. An initial failed write+retains its staged candidate; no blind retry overwrites that evidence.++Boot media may be FAT: no chmod operation or executable go file is required;+rc.local consumes go through bash. Existing Unix modes are preserved where+supported, without inventing FAT permission semantics. The real registration+caller exits on failure before starting the watchdog or printing success.+Recovery files remain, but the earlier stop means a running agent is not+guaranteed. Twenty controls in+`TestInstallSHUnraidBootReplacementPreservesUnrelatedJobs`, plus the existing+boot-logger and NAS-removal inventory, qualify this confined source behaviour,+not native flash, reboot, update, removal or customer recovery.+### Manual bootstrap transport remains HTTPS-onlyThe generated manual update helper restricts curl's initial protocol and everydiff --git a/scripts/install.sh b/scripts/install.shindex 49c1086f12..0f74abd676 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -3971,11 +3971,23 @@ filter_nas_agent_boot_file() {}if (marker) {if (!launch($0)) { bad = 1; exit 1 }- marker = 0; owned++; next+ marker = 0; owned+++ if (mode == "boundaries") {+ if (owned > 16) { bad = 1; exit 1 }+ print NR - 2+ }+ next}if ($0 == "# Pulse Agent") { marker = 1; next }if ($0 == "# Pulse Agent bootstrap end") { bad = 1; exit 1 }- if (launch($0)) { owned++; next }+ if (launch($0)) {+ owned+++ if (mode == "boundaries") {+ if (owned > 16) { bad = 1; exit 1 }+ print NR - 1+ }+ next+ }if ($0 !~ /^[[:space:]]*#/ && (target($0, "start-pulse-agent.sh") || target($0, runtime))) {bad = 1; exit 1}@@ -4157,67 +4169,76 @@ render_unraid_go_launch() {printf 'bash %q >> %q 2>&1 &\n' "$1" "/var/log/${AGENT_NAME}.log"}-# go is the user's boot script. Remove only the installer's marker and command-# lines that reference a Pulse wrapper or this runtime binary, which covers-# foreground, hand-edited and old-location entries, so the new entry is the-# only launch. Other lines that mention pulse-agent (log directories, hosts-# entries, a co-installed agent, comments) stay. Line endings become LF, as-# Unraid's fromdos makes them before running go, so removal can parse the file.-# A removed line must not leave go unparseable either: bash stops at a syntax-# error, which skips the rest of boot just as a hang does.+# go belongs to the operator. Only exact generated entries may be replaced;+# a line mentioning a wrapper can also run unrelated jobs. Unknown launches+# need reconciliation, not deletion. Stage on the boot filesystem and parse+# without execution before replacing the original. Normalise CRLF as Unraid's+# fromdos does, but do not turn an incomplete last line into admitted content.write_unraid_go_entry() {- local go_script="$1" wrapper_script="$2" runtime_binary="$3" filtered=""- if [[ -f "$go_script" ]]; then- filtered=$(mktemp) || return 1- if ! LC_ALL=C awk -v runtime="$runtime_binary" '- # Whether s names word as a whole file name: neither neighbour can- # continue the name. A runtime path must not continue a longer path.- function refers(s, word, slash, rest, i, b, a) {- rest = s- while ((i = index(rest, word)) > 0) {- b = i > 1 ? substr(rest, i - 1, 1) : ""- a = substr(rest, i + length(word), 1)- if (b !~ /[A-Za-z0-9._-]/ && (slash || b != "/") && a !~ /[A-Za-z0-9._-]/) return 1- rest = substr(rest, i + length(word))- }- return 0- }- # Text before a comment, only when the comment is certain. A- # backslash, an expansion, a backquote or an unterminated quote- # makes the line doubtful, and a doubtful line is still checked.- function code(s, i, c, q) {- q = ""- for (i = 1; i <= length(s); i++) {- c = substr(s, i, 1)- if (q == "\047") { if (c == "\047") q = ""; continue }- if (c == "\\" || c == "$" || c == "`") return s- if (q == "\"") { if (c == "\"") q = ""; continue }- if (c == "\"" || c == "\047") { q = c; continue }- if (c == "#" && (i == 1 || substr(s, i - 1, 1) ~ /[[:space:];&|(]/)) return substr(s, 1, i - 1)- }- return s- }- {- line = $0- sub(/\r$/, "", line)- if (line == "# Pulse Agent") next- command = code(line)- if (refers(command, "start-pulse-agent.sh", 1) || refers(command, runtime, 0)) next- print line- }- ' "$go_script" > "$filtered" ||- { LC_ALL=C awk '{ sub(/\r$/, ""); print }' "$go_script" | bash -n 2>/dev/null &&- ! bash -n "$filtered" 2>/dev/null; } ||- ! cat "$filtered" > "$go_script"; then- rm -f "$filtered"- return 1+ local go_script="$1" wrapper_script="$2" runtime_binary="$3"+ local STATE_DIR="${2%/start-pulse-agent.sh}" INSTALL_DIR="${3%/*}" BINARY_NAME="${3##*/}"+ local parent="" staging="" prior="" size="" last="" prefixes="" prefix="" existed=false+ [[ "$go_script" == /* && "$wrapper_script" == /*/start-pulse-agent.sh && "$runtime_binary" == /*/* &&+ "$go_script$wrapper_script$runtime_binary" != *$'\n'* &&+ "$go_script$wrapper_script$runtime_binary" != *$'\r'* &&+ "$wrapper_script$runtime_binary" != *[\$\`\"\\]* ]] || return 1+ parent=$(dirname "$go_script") || return 1+ [[ -d "$parent" && ! -L "$parent" && "$(portable_path_uid "$parent")" == "$(id -u)" ]] || return 1+ for prior in "$go_script".pulse-setup.* "$go_script".pulse-removal.*; do+ [[ ! -e "$prior" && ! -L "$prior" ]] || return 1+ done+ if [[ -e "$go_script" || -L "$go_script" ]]; then+ nas_agent_removal_file_safe "$go_script" || return 1+ size=$(wc -c < "$go_script") || return 1+ [[ "$size" =~ ^[[:space:]]*([0-9]+)[[:space:]]*$ && ${BASH_REMATCH[1]} -le 1048576 ]] || return 1+ if (( ${BASH_REMATCH[1]} > 0 )); then+ last=$(tail -c 1 "$go_script" && printf x) || return 1+ [[ "$last" == $'\nx' ]] || return 1fi- rm -f "$filtered"+ existed=true+ fi+ staging=$(mktemp -d "$go_script.pulse-setup.XXXXXX") || return 1+ # mktemp requests a private directory where supported. Unraid boot media+ # can be FAT: do not require chmod or executable go files there. rc.local+ # runs go through bash, and all staging remains on the same boot volume.+ if [[ "$existed" == true ]]; then+ cp -p "$go_script" "$staging/original" || return 1+ LC_ALL=C awk '{ sub(/\r$/, ""); print }' "$staging/original" > "$staging/normalised" || return 1+ prefixes=$(filter_nas_agent_boot_file Unraid "$staging/normalised" boundaries) || return 1+ # An exact launch inside a heredoc, quote, compound or continued line+ # is not an owned top-level command. Parse each bounded prefix without+ # execution; even a successful parse with a heredoc warning is unsure.+ while IFS= read -r prefix; do+ [[ -n "$prefix" ]] || continue+ [[ "$prefix" =~ ^[0-9]+$ ]] || return 1+ head -n "$prefix" "$staging/normalised" > "$staging/prefix" || return 1+ [[ "$(tail -n 1 "$staging/prefix")" != *\\ ]] || return 1+ bash -n "$staging/prefix" > "$staging/parse-errors" 2>&1 || return 1+ [[ ! -s "$staging/parse-errors" ]] || return 1+ done <<< "$prefixes"+ filter_nas_agent_boot_file Unraid "$staging/normalised" filter > "$staging/updated" || return 1+ # Preserve the boot file's mode on replacement; FAT may ignore modes.+ cp -p "$staging/original" "$staging/ready" || return 1else- printf '#!/bin/bash\n' > "$go_script" || return 1- chmod +x "$go_script"+ printf '#!/bin/bash\n' > "$staging/updated" || return 1+ printf '' > "$staging/ready" || return 1+ fi+ { printf '# Pulse Agent\n' && render_unraid_go_launch "$wrapper_script"; } >> "$staging/updated" || return 1+ bash -n "$staging/updated" > "$staging/parse-errors" 2>&1 || return 1+ [[ ! -s "$staging/parse-errors" ]] || return 1+ cat "$staging/updated" > "$staging/ready" || return 1+ cmp -s "$staging/ready" "$staging/updated" || return 1+ if [[ "$existed" == true ]]; then+ nas_agent_removal_file_safe "$go_script" && cmp -s "$go_script" "$staging/original" || return 1+ mv -- "$staging/ready" "$go_script" || return 1+ else+ # FAT need not support hard links or mv -n. Refuse a concurrent file+ # or link; a failed first write retains the complete staged candidate.+ (set -o noclobber; cat "$staging/ready" > "$go_script") || return 1fi- { printf '# Pulse Agent\n'; render_unraid_go_launch "$wrapper_script"; } >> "$go_script"+ nas_agent_removal_file_safe "$go_script" && cmp -s "$go_script" "$staging/updated" || return 1+ rm -f -- "$staging/original" "$staging/normalised" "$staging/prefix" "$staging/parse-errors" "$staging/updated" "$staging/ready" || return 1+ rmdir -- "$staging"}write_qnap_wrapper_script() {@@ -7679,8 +7700,7 @@ EOFif write_unraid_go_entry "$GO_SCRIPT" "$WRAPPER_SCRIPT" "$RUNTIME_BINARY"; thenlog_info "Added startup entry to ${GO_SCRIPT}..."else- log_warn "Could not update ${GO_SCRIPT} safely. To start the agent on boot, replace its Pulse Agent lines with:"- log_warn " $(render_unraid_go_launch "$WRAPPER_SCRIPT")"+ fail "Unraid boot setup was not confirmed; agent recovery files and any go.pulse-setup staging were retained. The agent may already be stopped. Reconcile the boot file before retrying; no automatic restart was attempted." "$EXIT_GENERAL"fi# Start the agent now using the wrapper script (includes watchdog)diff --git a/scripts/installtests/agent_nas_teardown.py b/scripts/installtests/agent_nas_teardown.pyindex 3ddbe5c17f..e77de63df2 100644--- a/scripts/installtests/agent_nas_teardown.py+++ b/scripts/installtests/agent_nas_teardown.py@@ -634,7 +634,7 @@ remove_safe_profile_state_dir() { rm -rf -- "$SAFE_PROFILE_STATE_DIR"; }rendered = subprocess.run(['bash', str(render_file)], env=env, capture_output=True, text=True)self.assertEqual(rendered.returncode, 0, rendered.stdout + rendered.stderr)else:- emitter = definitions(self.source, ('render_unraid_go_launch', 'write_unraid_go_entry'))+ emitter = definitions(self.source, ('portable_path_uid', 'nas_agent_removal_file_safe', 'filter_nas_agent_boot_file', 'render_unraid_go_launch', 'write_unraid_go_entry'))render_file.write_text(setup + emitter + '\nwrite_unraid_go_entry ' + shlex.quote(str(bootfile)) + ' "$WRAPPER_SCRIPT" "$RUNTIME_BINARY"\n')rendered = subprocess.run(['bash', str(render_file)], env=env, capture_output=True, text=True)self.assertEqual(rendered.returncode, 0, rendered.stdout + rendered.stderr)diff --git a/scripts/installtests/install_sh_test.go b/scripts/installtests/install_sh_test.goindex acd527f5b7..ee962a9ba8 100644--- a/scripts/installtests/install_sh_test.go+++ b/scripts/installtests/install_sh_test.go@@ -2865,16 +2865,18 @@ func runUnraidGoWriter(functions, goScript, wrapper, runtimeBinary string) ([]byfunc unraidGoEntryShellFunctions(t *testing.T) string {t.Helper()- return extractInstallShellFunction(t, "render_unraid_go_launch") + "\n" ++ return extractInstallShellFunction(t, "portable_path_uid") + "\n" ++ extractInstallShellFunction(t, "nas_agent_removal_file_safe") + "\n" ++ extractInstallShellFunction(t, "filter_nas_agent_boot_file") + "\n" ++ extractInstallShellFunction(t, "render_unraid_go_launch") + "\n" +extractInstallShellFunction(t, "write_unraid_go_entry") + "\n"}// TestInstallSHUnraidGoEntryReplacesOnlyPulseLaunches runs the installer's// /boot/config/go writer. go is the user's boot script: only the installer's-// marker and command lines that reference a Pulse wrapper or the runtime-// binary are replaced. The earlier cleanup, sed '/pulse-agent/d', also deleted-// any user line that merely mentioned pulse-agent. Removal must admit the-// written entry, and a removal that would leave go unparseable is refused.+// marker and exact generated launches are replaced. Hand-edited/foreign and+// compound commands must be reconciled, not deleted along with unrelated work.+// Removal must admit the written entry; unknown or unparseable input is kept.func TestInstallSHUnraidGoEntryReplacesOnlyPulseLaunches(t *testing.T) {if runtime.GOOS == "windows" {t.Skip("Unraid boot-file fixture needs bash")@@ -2899,9 +2901,6 @@ func TestInstallSHUnraidGoEntryReplacesOnlyPulseLaunches(t *testing.T) {before string // empty: go does not exist yetafter stringrefused bool- // Removal refuses any command line naming the wrapper, even in a- // trailing comment; that conservatism is removal's, not the writer's.- skipRemoval bool}{{name: "missing go is created",@@ -2918,6 +2917,11 @@ func TestInstallSHUnraidGoEntryReplacesOnlyPulseLaunches(t *testing.T) {before: userTop + "\n# Pulse Agent\nbash " + wrapper + "\n\n" + userRest,after: userTop + "\n\n" + userRest + entry,},+ {+ name: "CRLF exact legacy entry",+ before: strings.ReplaceAll(userTop+"# Pulse Agent\nbash \""+wrapper+"\"\n"+userRest, "\n", "\r\n"),+ after: user + entry,+ },{// Unraid runs go through fromdos, so CRLF lines become LF.name: "hand-edited, old-location and direct runtime launches",@@ -2934,13 +2938,12 @@ func TestInstallSHUnraidGoEntryReplacesOnlyPulseLaunches(t *testing.T) {"bash /mnt/user/appdata/old/start-pulse-agent.sh\n" +runtimeBinary + " --url https://pulse.example.invalid &\n" +userRest,- after: user + entry,+ refused: true,},{- name: "command whose comment names the wrapper",- before: "#!/bin/bash\nswapon /mnt/cache/swapfile # start-pulse-agent.sh needs this\n",- after: "#!/bin/bash\nswapon /mnt/cache/swapfile # start-pulse-agent.sh needs this\n" + entry,- skipRemoval: true,+ name: "uncertain command whose comment names the wrapper",+ before: "#!/bin/bash\nswapon /mnt/cache/swapfile # start-pulse-agent.sh needs this\n",+ refused: true,},{name: "removal that would break go's syntax",@@ -2964,6 +2967,9 @@ func TestInstallSHUnraidGoEntryReplacesOnlyPulseLaunches(t *testing.T) {extractInstallShellFunction(t, "render_unraid_go_launch") + "\n"for i, tc := range cases {t.Run(tc.name, func(t *testing.T) {+ if tc.refused && tc.after == "" {+ tc.after = tc.before+ }goScript := filepath.Join(dir, fmt.Sprintf("go-%d", i))if tc.before != "" {if err := os.WriteFile(goScript, []byte(tc.before), 0644); err != nil {@@ -2983,7 +2989,7 @@ func TestInstallSHUnraidGoEntryReplacesOnlyPulseLaunches(t *testing.T) {t.Fatalf("go after install %d:\n--- got ---\n%s\n--- want ---\n%s", run, got, tc.after)}}- if tc.refused || tc.skipRemoval {+ if tc.refused {return}diff --git a/scripts/installtests/unraid_go_update.py b/scripts/installtests/unraid_go_update.pynew file mode 100644index 0000000000..414f24edb3--- /dev/null+++ b/scripts/installtests/unraid_go_update.py@@ -0,0 +1,289 @@+#!/usr/bin/env python3+"""Exercise the real Unraid boot writer in private ordinary-user directories.++Boot text is never executed. Filesystem faults/concurrency and registration+results are models, not a native NAS, flash, watchdog or installed-agent proof.+"""+from pathlib import Path+import os+import shlex+import shutil+import subprocess+import tempfile+import unittest++SOURCE = Path(__file__).resolve().parents[2] / 'scripts/install.sh'+BASH = shutil.which('bash')+NAMES = ('portable_path_uid', 'nas_agent_removal_file_safe',+ 'filter_nas_agent_boot_file', 'render_unraid_go_launch', 'write_unraid_go_entry')+++def definitions(source):+ result = []+ for name in NAMES:+ marker = name + '() {'+ if source.count(marker) != 1:+ raise ValueError('missing or ambiguous production function: ' + name)+ result.append(marker + source.split(marker, 1)[1].split('\n}\n', 1)[0] + '\n}\n')+ return '\n'.join(result)+++class UnraidGoUpdate(unittest.TestCase):+ source = SOURCE.read_text()++ def setUp(self):+ directory = tempfile.TemporaryDirectory(prefix='pulse-unraid-boot-')+ self.addCleanup(directory.cleanup)+ self.root = Path(directory.name)+ for name in ('flash', 'state', 'tools'):+ (self.root / name).mkdir(mode=0o700)+ self.boot = self.root / 'flash/go'+ self.wrapper = self.root / 'state/start-pulse-agent.sh'+ self.runtime = self.root / 'bin/pulse-agent'+ self.secret = self.root / 'state/token'+ self.secret.write_text('synthetic-secret-not-for-logs')+ self.environment = dict(os.environ, PATH=str(self.root / 'tools') + ':' + os.environ['PATH'])++ def invoke(self, override=''):+ code = ('set -euo pipefail\nAGENT_NAME=pulse-agent\n' + definitions(self.source) ++ '\n' + override + '\nwrite_unraid_go_entry "$1" "$2" "$3"\n')+ result = subprocess.run([BASH, '-c', code, '_', str(self.boot), str(self.wrapper), str(self.runtime)],+ env=self.environment, capture_output=True, text=True, timeout=10)+ self.assertNotIn('synthetic-secret-not-for-logs', result.stdout + result.stderr)+ self.assertEqual(self.secret.read_text(), 'synthetic-secret-not-for-logs')+ self.assertFalse((self.root / 'executed').exists(), 'boot text must not execute')+ return result++ def write(self, content):+ self.boot.write_bytes(content if isinstance(content, bytes) else content.encode())+ self.boot.chmod(0o640)++ def stub(self, name, code):+ path = self.root / 'tools' / name+ path.write_text('#!/bin/sh\n' + code + '\n')+ path.chmod(0o700)++ def assert_refused_unchanged(self, original):+ self.write(original)+ before = self.boot.read_bytes()+ result = self.invoke()+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(self.boot.read_bytes(), before)++ def test_first_install_and_repeat_create_one_detached_entry(self):+ self.assertEqual(self.invoke().returncode, 0)+ first = self.boot.read_bytes()+ self.assertTrue(first.startswith(b'#!/bin/bash\n'))+ self.assertEqual(first.count(b'# Pulse Agent\n'), 1)+ self.assertTrue(first.endswith(b' >> /var/log/pulse-agent.log 2>&1 &\n'))+ self.assertEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_bytes(), first)+ self.assertEqual(list(self.boot.parent.glob('*.pulse-setup.*')), [])++ def test_unrelated_jobs_comments_and_multiline_constructs_survive(self):+ original = ('#!/bin/bash\n# Archive start-pulse-agent.sh first\n'+ 'cp /private/start-pulse-agent.sh.bak /backup/wrapper\n'+ 'bash /other/start-pulse-agent-prod.sh &\n'+ 'if true; then\n echo unrelated\nfi\n'+ 'cat <<EOF\nordinary data\nEOF\n'+ 'printf synthetic-secret-not-for-logs\n'+ 'touch ' + shlex.quote(str(self.root / 'executed')) + '\n')+ self.write(original)+ self.assertEqual(self.invoke().returncode, 0)+ self.assertTrue(self.boot.read_text().startswith(original))+ self.assertEqual(self.boot.stat().st_mode & 0o777, 0o640)+ first = self.boot.read_bytes()+ self.assertEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_bytes(), first)++ def test_exact_legacy_current_and_crlf_entries_become_one(self):+ self.write('#!/bin/bash\r\necho before\r\n# Pulse Agent\r\nbash "' + str(self.wrapper) + '"\r\necho after\r\n')+ self.assertEqual(self.invoke().returncode, 0)+ first = self.boot.read_text()+ self.assertTrue(first.startswith('#!/bin/bash\necho before\necho after\n'))+ entry = first[first.index('# Pulse Agent\n'):]+ self.write(first + entry)+ self.assertEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_text(), first)++ def test_compound_foreign_and_indirect_launches_are_not_deleted(self):+ commands = ('printf unrelated; bash ' + str(self.wrapper),+ 'bash ' + str(self.wrapper) + ' && echo unrelated',+ 'bash /other/start-pulse-agent.sh &',+ 'setsid bash ' + str(self.wrapper) + ' &',+ str(self.runtime) + ' --url https://pulse.example.invalid &',+ 'w=start-pulse-agent.sh; bash "$w"',+ 'echo literal-start-pulse-agent.sh',+ 'swapon /cache/swapfile # start-pulse-agent.sh needs this')+ for i, command in enumerate(commands):+ with self.subTest(command=command):+ self.boot = self.boot.with_name('unknown-' + str(i))+ self.assert_refused_unchanged('#!/bin/bash\n' + command + '\necho later\n')++ def test_exact_text_inside_shell_context_is_not_an_owned_launch(self):+ launch = 'bash ' + str(self.wrapper) + '\n'+ contexts = ('cat <<EOF\n' + launch + 'EOF\n',+ 'printf \'multiline\n' + launch + '\'\n',+ 'if true; then\n' + launch + 'fi\n',+ 'echo unrelated \\\n' + launch,+ 'echo unrelated |\n' + launch,+ 'cat <<EOF\n# Pulse Agent\n' + launch + 'EOF\n')+ for i, context in enumerate(contexts):+ with self.subTest(context=context):+ self.boot = self.boot.with_name('context-' + str(i))+ self.assert_refused_unchanged('#!/bin/bash\n' + context)++ def test_malformed_incomplete_binary_and_oversized_files_stay_unchanged(self):+ contents = ('#!/bin/bash\n# Pulse Agent\necho unrelated\n',+ '#!/bin/bash\necho incomplete', '#!/bin/bash\nif true; then\n',+ '#!/bin/bash\ncat <<EOF\nincomplete heredoc\n',+ b'#!/bin/bash\necho before\0\n', '#!/bin/bash\n#' + 'x' * 1048577 + '\n')+ for i, content in enumerate(contents):+ with self.subTest(case=i):+ self.boot = self.boot.with_name('invalid-' + str(i))+ self.assert_refused_unchanged(content)++ def test_linked_files_directories_and_linked_parent_are_not_rewritten(self):+ other = self.root / 'foreign'; other.write_text('untouched\n')+ self.boot.symlink_to(other)+ self.assertNotEqual(self.invoke().returncode, 0)+ self.assertTrue(self.boot.is_symlink()); self.assertEqual(other.read_text(), 'untouched\n')+ self.boot.unlink(); self.boot.mkdir()+ self.assertNotEqual(self.invoke().returncode, 0)+ self.assertTrue(self.boot.is_dir())+ self.boot.rmdir(); self.boot.parent.rmdir()+ foreign = self.root / 'foreign-directory'; foreign.mkdir()+ (foreign / 'go').write_text('untouched\n')+ (self.root / 'flash').symlink_to(foreign)+ self.assertNotEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_text(), 'untouched\n')++ def test_unreadable_or_foreign_owned_file_is_not_rewritten(self):+ self.write('#!/bin/bash\necho kept\n')+ self.boot.chmod(0)+ try:+ self.assertNotEqual(self.invoke().returncode, 0)+ finally:+ self.boot.chmod(0o640)+ before = self.boot.read_bytes()+ self.assertNotEqual(self.invoke('portable_path_uid() { printf "999999\\n"; }').returncode, 0)+ self.assertEqual(self.boot.read_bytes(), before)++ def test_pending_setup_and_removal_recovery_bar_another_write(self):+ self.write('#!/bin/bash\necho kept\n')+ for suffix in ('.pulse-setup.retained', '.pulse-removal.retained'):+ with self.subTest(suffix=suffix):+ recovery = Path(str(self.boot) + suffix); recovery.mkdir()+ before = self.boot.read_bytes()+ self.assertNotEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_bytes(), before)+ recovery.rmdir()++ def test_copy_rename_and_parser_failures_preserve_original(self):+ for command in ('cp', 'mv', 'bash'):+ with self.subTest(command=command):+ self.boot = self.boot.with_name(command + '-failure')+ self.write('#!/bin/bash\necho kept\n'); before = self.boot.read_bytes()+ self.stub(command, 'exit 1')+ self.assertNotEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_bytes(), before)+ (self.root / 'tools' / command).unlink()++ def test_fat_boot_does_not_require_chmod(self):+ # Model the unsupported operation, not an actual FAT mount. go is+ # consumed by bash, so no successful permission change is required.+ self.stub('chmod', 'exit 1')+ self.assertEqual(self.invoke().returncode, 0)+ first = self.boot.read_bytes()+ self.assertEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_bytes(), first)++ def test_partial_stage_write_cannot_truncate_original(self):+ self.write('#!/bin/bash\necho kept\n'); before = self.boot.read_bytes()+ self.stub('cat', 'printf partial; exit 28')+ self.assertNotEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_bytes(), before)+ originals = list(self.boot.parent.glob('*.pulse-setup.*/original'))+ self.assertEqual(len(originals), 1); self.assertEqual(originals[0].read_bytes(), before)++ def test_partial_renderer_preserves_original_and_recovery(self):+ self.write('#!/bin/bash\necho kept\n'); before = self.boot.read_bytes()+ result = self.invoke('render_unraid_go_launch() { printf partial; return 1; }')+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(self.boot.read_bytes(), before)+ self.assertTrue(list(self.boot.parent.glob('*.pulse-setup.*/original')))++ def test_source_change_during_staging_is_not_clobbered(self):+ self.write('#!/bin/bash\necho kept\n'); before = self.boot.read_bytes()+ self.stub('cp', shlex.quote(shutil.which('cp')) + ' "$@" || exit $?\nif [ "$2" = ' + shlex.quote(str(self.boot)) + ' ]; then printf "# concurrent change\\n" >> "$2"; fi')+ self.assertNotEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_bytes(), before + b'# concurrent change\n')++ def test_first_write_refuses_concurrent_file_directory_or_link(self):+ other = self.root / 'foreign'; other.write_text('foreign target\n')+ for kind in ('file', 'directory', 'link'):+ with self.subTest(kind=kind):+ self.boot = self.boot.with_name('new-' + kind)+ create = ('ln -s ' + shlex.quote(str(other)) + ' ' + shlex.quote(str(self.boot)) if kind == 'link'+ else 'mkdir ' + shlex.quote(str(self.boot)) if kind == 'directory'+ else 'printf "foreign file\\n" > ' + shlex.quote(str(self.boot)))+ self.stub('cat', shlex.quote(shutil.which('cat')) + ' "$@" || exit $?\ncase "$1" in */updated) ' + create + ';; esac')+ self.assertNotEqual(self.invoke().returncode, 0)+ self.assertEqual(other.read_text(), 'foreign target\n')+ if kind == 'link': self.assertTrue(self.boot.is_symlink())+ elif kind == 'directory': self.assertTrue(self.boot.is_dir())+ else: self.assertEqual(self.boot.read_text(), 'foreign file\n')+ self.assertTrue(list(self.boot.parent.glob(self.boot.name + '.pulse-setup.*/updated')))++ def test_partial_first_write_is_not_success_and_blocks_blind_retry(self):+ self.stub('cat', 'case "$1" in */ready) printf partial; exit 28;; esac\n' + shlex.quote(shutil.which('cat')) + ' "$@"')+ self.assertNotEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_bytes(), b'partial')+ staged = list(self.boot.parent.glob('*.pulse-setup.*/updated'))+ self.assertEqual(len(staged), 1); self.assertIn(b'# Pulse Agent\n', staged[0].read_bytes())+ (self.root / 'tools/cat').unlink()+ self.assertNotEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_bytes(), b'partial')++ def test_final_readback_and_cleanup_failures_are_not_success(self):+ for command in ('mv', 'rmdir'):+ with self.subTest(command=command):+ self.boot = self.boot.with_name('terminal-' + command)+ self.write('#!/bin/bash\necho kept\n')+ code = ('exit 1' if command == 'rmdir' else shlex.quote(shutil.which('mv')) + ' "$@" || exit $?\nprintf "# concurrent change\\n" >> ' + shlex.quote(str(self.boot)))+ self.stub(command, code)+ self.assertNotEqual(self.invoke().returncode, 0)+ self.assertTrue(self.boot.read_text().startswith('#!/bin/bash\necho kept\n'))+ self.assertTrue(list(self.boot.parent.glob(self.boot.name + '.pulse-setup.*')))+ (self.root / 'tools' / command).unlink()+ self.assertNotEqual(self.invoke().returncode, 0)++ def test_too_many_entries_need_reconciliation_not_unbounded_parser_work(self):+ self.assert_refused_unchanged('#!/bin/bash\n' + ('# Pulse Agent\nbash ' + str(self.wrapper) + '\n') * 17)++ def test_wrapper_paths_with_spaces_remain_idempotent(self):+ self.wrapper = self.root / 'state with spaces/start-pulse-agent.sh'+ self.assertEqual(self.invoke().returncode, 0)+ first = self.boot.read_bytes()+ self.assertIn(b'state\\ with\\ spaces/', first)+ self.assertEqual(self.invoke().returncode, 0)+ self.assertEqual(self.boot.read_bytes(), first)++ def test_registration_failure_exits_before_start_or_persistence_success(self):+ start = self.source.index(' if write_unraid_go_entry "$GO_SCRIPT"')+ entry = self.source[start:self.source.index(' # Start the agent now using the wrapper', start)]+ events = self.root / 'events'+ for fault, expected in ((False, ['replace', 'configured', 'would-start']), (True, ['replace', 'failed'])):+ with self.subTest(fault=fault):+ events.write_text('')+ setup = ('set -euo pipefail\nGO_SCRIPT=fixture WRAPPER_SCRIPT=fixture RUNTIME_BINARY=fixture EXIT_GENERAL=1\n'+ 'event() { printf "%s\\n" "$1" >> ' + shlex.quote(str(events)) + '; }\n'+ 'write_unraid_go_entry() { event replace; return ' + ('1' if fault else '0') + '; }\n'+ 'log_info() { event configured; }\nfail() { event failed; exit 1; }\n')+ result = subprocess.run([BASH, '-c', setup + entry + '\nevent would-start\n'], capture_output=True, text=True, timeout=5)+ self.assertEqual(result.returncode != 0, fault, result.stderr)+ self.assertEqual(events.read_text().splitlines(), expected)+++if __name__ == '__main__':+ unittest.main()diff --git a/scripts/installtests/unraid_go_update_test.go b/scripts/installtests/unraid_go_update_test.gonew file mode 100644index 0000000000..9a052fe560--- /dev/null+++ b/scripts/installtests/unraid_go_update_test.go@@ -0,0 +1,27 @@+package installtests++import (+ "context"+ "os/exec"+ "runtime"+ "strings"+ "testing"+ "time"+)++func TestInstallSHUnraidBootReplacementPreservesUnrelatedJobs(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("Unix shell/filesystem fixture; native Unraid acceptance remains separate")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)+ defer cancel()+ command := exec.CommandContext(ctx, "python3", repoFile("scripts", "installtests", "unraid_go_update.py"), "-v")+ output, err := command.CombinedOutput()+ if err != nil {+ t.Fatalf("Unraid boot replacement controls: %v\n%s", err, output)+ }+ if !strings.Contains(string(output), "Ran 20 tests in ") ||+ !strings.Contains(string(output), "\nOK\n") || strings.Contains(string(output), "skipped") {+ t.Fatalf("incomplete Unraid boot replacement controls:\n%s", output)+ }+}