Tighten endless-wait: a timeout inside a loop caps nothing, and cover each branch

This commit is contained in:
2026-11-18 19:33:09 +01:00
parent 1d411be20d
commit 281220a69b
3 changed files with 33 additions and 31 deletions
+20 -26
View File
@@ -3,6 +3,7 @@
Both kinds hang the session that waits on them: `until [ -s f ] && ! pgrep -f "chunk-pr merg"; do sleep 15; done` matches its own shell, so its condition never holds. Both kinds hang the session that waits on them: `until [ -s f ] && ! pgrep -f "chunk-pr merg"; do sleep 15; done` matches its own shell, so its condition never holds.
Shell forms it does not read: a loop inside a function, a variable or a script file, and a count or deadline it does not recognise (it refuses the loop, and an override waives that). Shell forms it does not read: a loop inside a function, a variable or a script file, and a count or deadline it does not recognise (it refuses the loop, and an override waives that).
""" """
import itertools
import re import re
from command_lines.shell_command import launched, segments, Simple from command_lines.shell_command import launched, segments, Simple
@@ -11,49 +12,45 @@ from command_lines.shell_command import launched, segments, Simple
KEYWORDS = frozenset({"!", "do", "else", "then", "{"}) KEYWORDS = frozenset({"!", "do", "else", "then", "{"})
LOOPS = frozenset({"for", "until", "while"}) LOOPS = frozenset({"for", "until", "while"})
SHELLS = frozenset({"bash", "dash", "sh", "zsh"}) SHELLS = frozenset({"bash", "dash", "sh", "zsh"})
# A word with which a loop counts its rounds or compares a clock: `[ "$n" -lt 40 ]`, `$SECONDS`. # A word with which a loop counts its rounds: `[ "$n" -lt 40 ]`.
COUNTERS = frozenset({"-ge", "-gt", "-le", "-lt"}) COUNTERS = frozenset({"-ge", "-gt", "-le", "-lt"})
# `for ((;;))` has no condition. The lexer splits at its parentheses, so the check reads the command's text. # `for ((;;))` has no condition. The lexer splits at its parentheses, so the check reads the command's text.
FOREVER = re.compile(r"\bfor\s*\(\(\s*[^;)]*;\s*;") FOREVER = re.compile(r"\bfor\s*\(\(\s*[^;)]*;\s*;")
# A signal given to pkill, as -9 or -KILL, which is not a cluster of options.
SIGNAL = re.compile(r"-(?:\d+|[A-Z]{2,})")
# pgrep's and pkill's options that take a value, as short letters and as long names. # pgrep's and pkill's options that take a value, as short letters and as long names.
VALUED = frozenset("dFgGPrstuU") VALUED = frozenset("dFgGPrstuU")
VALUED_LONG = frozenset({"--delimiter", "--euid", "--group", "--ns", "--nslist", "--parent", "--pgroup", "--pidfile", "--runstates", "--session", "--signal", "--terminal", "--uid"}) VALUED_LONG = frozenset({"--delimiter", "--euid", "--group", "--ns", "--nslist", "--parent", "--pgroup", "--pidfile", "--runstates", "--session", "--signal", "--terminal", "--uid"})
HOW = "use `~/.claude/bin/wait-for <file> [<pattern>] --timeout <seconds>`" HOW = "use `~/.claude/bin/wait-for <file> [<pattern>] --timeout <seconds>`"
def endless_waits(command: str, simples: list[Simple]) -> list[tuple[str, str]]: def endless_waits(command: str, simples: list[Simple], capped: bool = False) -> list[tuple[str, str]]:
"""Each endless wait the command starts, as its detail and the directory it runs in.""" """Each endless wait the command starts, as its detail and the directory it runs in. capped is whether a `timeout` ends every loop in the simple commands, as it does inside `timeout 60 bash -c '…'`."""
return waits(command, simples, False) found = [] if capped else [(f"a loop that sleeps, `{' '.join(loop[0].words)[:60]}`, has neither a time limit nor a count cap; {HOW}, or give the loop a deadline compared with `date` or $SECONDS, or a counter, as in `for i in $(seq 1 40)`", loop[0].directory) for loop in loops(simples) if endless(loop, command)]
def waits(command: str, simples: list[Simple], capped: bool) -> list[tuple[str, str]]:
"""capped is whether a `timeout` outside the simple commands ends them all, as for the inside of `timeout 60 bash -c '…'`."""
found = [] if capped else [(f"a loop that sleeps, `{' '.join(loop[0].words)[:60]}`, has neither a time limit nor a count cap; {HOW}, or give the loop a deadline compared with `date`, `timeout`, or a count as in `for i in $(seq 1 40)`", loop[0].directory) for loop in loops(simples) if endless(loop, command)]
for simple in simples: for simple in simples:
if (pattern := self_match(simple.words, command)) is not None: if (pattern := self_match(simple.words, command)) is not None:
found.append((f"`{pattern}` is matched by the command line that holds this `pgrep -f` or `pkill -f`, so it finds its own shell; {HOW}, a `pgrep -x` on the process name, or a pattern the command doesn't contain, such as `[c]hunk` for `chunk`", simple.directory)) found.append((f"`{pattern}` is matched by the command line that holds this `pgrep -f` or `pkill -f`, so it finds its own shell; {HOW}, a `pgrep -x` on the process name, or a pattern the command doesn't contain, such as `[c]hunk` for `chunk`", simple.directory))
if (script := shell_script(simple.words)) is not None: if (script := shell_script(simple.words)) is not None:
found += waits(command, [Simple(words, simple.directory) for words in segments(script)], capped or launched(simple.words, {"timeout"}) is not None) found += endless_waits(command, [Simple(words, simple.directory) for words in segments(script)], capped or launched(simple.words, {"timeout"}) is not None)
return found return found
def core(words: list[str]) -> list[str]: def core(words: list[str]) -> list[str]:
"""The words of a segment without the keywords before its command.""" """The words of a segment without the keywords before its command."""
start = next((i for i, word in enumerate(words) if word not in KEYWORDS), len(words)) return list(itertools.dropwhile(KEYWORDS.__contains__, words))
return words[start:]
def loops(simples: list[Simple]) -> list[list[Simple]]: def loops(simples: list[Simple]) -> list[list[Simple]]:
"""Each loop as the segments from its keyword to its `done`, those of a loop nested in it included.""" """Each loop as the segments from its keyword to its `done`, those of a loop nested in it included."""
open_loops: list[list[Simple]] = [] open_loops: list[list[Simple]] = []
closed = [] closed = []
for simple in simples: for simple in (Simple(core(simple.words), simple.directory) for simple in simples):
words = core(simple.words) first = simple.words[0] if simple.words else ""
for loop in open_loops: for loop in open_loops:
loop.append(Simple(words, simple.directory)) loop.append(simple)
if words[:1] and words[0] in LOOPS: if first in LOOPS:
open_loops.append([Simple(words, simple.directory)]) open_loops.append([simple])
elif words[:1] == ["done"] and open_loops: elif first == "done" and open_loops:
closed.append(open_loops.pop()) closed.append(open_loops.pop())
return closed + open_loops return closed + open_loops
@@ -67,10 +64,10 @@ def endless(loop: list[Simple], command: str) -> bool:
# A list ends the loop; an arithmetic for, whose words end at the lexer's split at `((`, does only where it has a condition. # A list ends the loop; an arithmetic for, whose words end at the lexer's split at `((`, does only where it has a condition.
return head == ["for"] and FOREVER.search(command) is not None return head == ["for"] and FOREVER.search(command) is not None
# `while ((i < 10))` splits the same way, so a bare keyword reads as a count. # `while ((i < 10))` splits the same way, so a bare keyword reads as a count.
if head == [head[0]]: if len(head) == 1:
return False return False
words = {word for simple in loop for word in simple.words} words = {word for simple in loop for word in simple.words}
return not (COUNTERS & words or any("SECONDS" in word for word in words) or any(launched(simple.words, {"date", "timeout"}) for simple in loop)) return not (COUNTERS & words or any("SECONDS" in word for word in words) or any(launched(simple.words, {"date"}) for simple in loop))
def shell_script(words: list[str]) -> str | None: def shell_script(words: list[str]) -> str | None:
@@ -91,12 +88,9 @@ def self_match(words: list[str], command: str) -> str | None:
for word in rest: for word in rest:
if word.startswith("--"): if word.startswith("--"):
full = full or word == "--full" full = full or word == "--full"
if "=" not in word and word in VALUED_LONG: if word in VALUED_LONG:
next(rest, None) next(rest, None)
elif word.startswith("-") and len(word) > 1: elif word.startswith("-") and len(word) > 1 and not SIGNAL.fullmatch(word):
# A signal, such as -9 or -KILL, isn't a cluster of options.
if word[1:].isdigit() or (word[1:].isupper() and len(word) > 2):
continue
for at, letter in enumerate(word[1:], 1): for at, letter in enumerate(word[1:], 1):
full = full or letter == "f" full = full or letter == "f"
if letter in VALUED: if letter in VALUED:
@@ -104,7 +98,7 @@ def self_match(words: list[str], command: str) -> str | None:
if at == len(word) - 1: if at == len(word) - 1:
next(rest, None) next(rest, None)
break break
else: elif not word.startswith("-") or len(word) == 1:
patterns.append(word) patterns.append(word)
return next((pattern for pattern in patterns if full and matches(pattern, command)), None) return next((pattern for pattern in patterns if full and matches(pattern, command)), None)
+1 -1
View File
@@ -43,7 +43,7 @@ RULES: dict[RuleName, Rule] = {
), ),
"endless-wait": Rule( "endless-wait": Rule(
"a wait ends: a loop that sleeps has a time limit or a count cap, and a `pgrep -f` or `pkill -f` has a pattern its own command line doesn't match, since such a pattern finds the shell that runs the command and the wait never ends, and the session that waits on it hangs; wait with `~/.claude/bin/wait-for <file> [<pattern>] --timeout <seconds>`, or find a process by name with `pgrep -x`", "a wait ends: a loop that sleeps has a time limit or a count cap, and a `pgrep -f` or `pkill -f` has a pattern its own command line doesn't match, since such a pattern finds the shell that runs the command and the wait never ends, and the session that waits on it hangs; wait with `~/.claude/bin/wait-for <file> [<pattern>] --timeout <seconds>`, or find a process by name with `pgrep -x`",
"a Bash or Monitor command with an `until`, `while` or `for ((;;))` loop that runs `sleep` and has no `timeout`, no `date` or $SECONDS comparison and no counter compared with -lt, -le, -gt or -ge, or a `pgrep -f` or `pkill -f` whose pattern, read as a regular expression, matches the command's text; the same inside the script of a `bash -c`, unless a `timeout` runs the shell. A loop over a list, such as `for i in $(seq 1 40)`, is a count and passes", "a Bash or Monitor command with an `until`, `while` or `for ((;;))` loop that runs `sleep` and has no `date` or $SECONDS comparison and no counter compared with -lt, -le, -gt or -ge, or a `pgrep -f` or `pkill -f` whose pattern, read as a regular expression, matches the command's text; the same inside the script of a `bash -c`, unless a `timeout` runs the shell. A loop over a list, such as `for i in $(seq 1 40)`, is a count and passes",
), ),
# A marker would let the credentials into the transcript all the same, so no marker waives it. # A marker would let the credentials into the transcript all the same, so no marker waives it.
"env-file-read": Rule( "env-file-read": Rule(
+12 -4
View File
@@ -145,28 +145,36 @@ class CommandBreaches(unittest.TestCase):
self.assertEqual(checked(command), []) self.assertEqual(checked(command), [])
def test_a_loop_that_sleeps_without_a_time_or_count_cap_breaks_endless_wait(self): def test_a_loop_that_sleeps_without_a_time_or_count_cap_breaks_endless_wait(self):
for command in ["until [ -s /tmp/x.log ]; do sleep 15; done", "while true; do sleep 1; done", "while ! curl -sf localhost:80; do sleep 2; done", "until [ -s /tmp/merge.log ] && ! pgrep -x chunk-pr; do sleep 15; done", "for ((;;)); do sleep 1; done", "echo a && until test -f f; do sleep 1; done", "bash -c 'until [ -s f ]; do sleep 1; done'", "if x; then while true; do sleep 1; done; fi", "for i in 1 2; do until [ -s f ]; do sleep 1; done; done", "tail -f x | while read l; do sleep 1; done"]: for command in ["until [ -s /tmp/x.log ]; do sleep 15; done", "while true; do sleep 1; done", "while ! curl -sf localhost:80; do sleep 2; done", "until [ -s /tmp/merge.log ] && ! pgrep -x chunk-pr; do sleep 15; done", "for ((;;)); do sleep 1; done", "echo a && until test -f f; do sleep 1; done", "bash -c 'until [ -s f ]; do sleep 1; done'", "if x; then while true; do sleep 1; done; fi", "for i in 1 2; do until [ -s f ]; do sleep 1; done; done", "tail -f x | while read l; do sleep 1; done", "until timeout 5 curl -sf x; do sleep 1; done", "until [ -s f ]; do echo seconds; sleep 1; done", "until [ -s f ]\ndo\n sleep 1\ndone", "bash -x -c 'until [ -s f ]; do sleep 1; done'"]:
with self.subTest(command): with self.subTest(command):
self.assertEqual(checked(command), ["endless-wait"]) self.assertEqual(checked(command), ["endless-wait"])
def test_a_loop_with_a_deadline_a_count_or_no_sleep_passes_endless_wait(self): def test_a_loop_with_a_deadline_a_count_or_no_sleep_passes_endless_wait(self):
for command in ["until [ -s f ]; do sleep 15; [ $((n+=1)) -ge 40 ] && break; done", "end=$((SECONDS+600)); until [ -s f ] || [ $SECONDS -gt $end ]; do sleep 5; done", "until [ -s f ] || [ $(date +%s) -ge $end ]; do sleep 5; done", "n=0; while [ $n -lt 40 ]; do sleep 1; n=$((n+1)); done", "while ((n < 40)); do sleep 1; done", "for i in $(seq 1 40); do [ -s f ] && break; sleep 15; done", "for f in a b c; do sleep 1; done", "for ((i=0; i<40; i++)); do sleep 1; done", "timeout 600 bash -c 'until [ -s f ]; do sleep 1; done'", "~/.claude/bin/wait-for /tmp/x.log 'merged' --timeout 600", "while read l; do echo $l; done < f", "until [ -s f ]; do echo waiting; done", "echo 'until x; do sleep 1; done'"]: for command in ["until [ -s f ]; do sleep 15; [ $((n+=1)) -ge 40 ] && break; done", "end=$((SECONDS+600)); until [ -s f ] || [ $SECONDS -gt $end ]; do sleep 5; done", "until [ -s f ] || [ $(date +%s) -ge $end ]; do sleep 5; done", "n=0; while [ $n -lt 40 ]; do sleep 1; n=$((n+1)); done", "while ((n < 40)); do sleep 1; done", "until [ -s f ] || [ \"$SECONDS\" = 600 ]; do sleep 5; done", "until [ -s f ] || [ $(date +%s) = $end ]; do sleep 5; done", "while read l; do echo $l; done < f; sleep 5", "bash script.sh", "bash -c", "bash -x", "for i in $(seq 1 40); do [ -s f ] && break; sleep 15; done", "for f in a b c; do sleep 1; done", "for ((i=0; i<40; i++)); do sleep 1; done", "timeout 600 bash -c 'until [ -s f ]; do sleep 1; done'", "~/.claude/bin/wait-for /tmp/x.log 'merged' --timeout 600", "while read l; do echo $l; done < f", "until [ -s f ]; do echo waiting; done", "echo 'until x; do sleep 1; done'"]:
with self.subTest(command): with self.subTest(command):
self.assertEqual(checked(command), []) self.assertEqual(checked(command), [])
def test_a_pgrep_or_pkill_f_whose_pattern_the_command_contains_breaks_endless_wait(self): def test_a_pgrep_or_pkill_f_whose_pattern_the_command_contains_breaks_endless_wait(self):
for command in ["pgrep -f chunk-pr", "pkill -f 'loop-claude'", "pgrep -fa chunk-pr", "pgrep -u me -f chunk-pr", "pgrep --full chunk-pr", "pkill -9 -f loop-claude", "pgrep -f 'chunk-pr .*merg'", "nice pgrep -f chunk-pr", "bash -c 'pgrep -f chunk-pr'"]: for command in ["pgrep -f chunk-pr", "pkill -f 'loop-claude'", "pgrep -fa chunk-pr", "pgrep -u me -f chunk-pr", "pgrep --full chunk-pr", "pkill -9 -f loop-claude", "pkill -KILL -f loop-claude", "pgrep -f chunk-pr -u", "pgrep -f -", "pgrep -U me -f chunk-pr", "pgrep -fUME chunk-pr", "pgrep -f9 chunk-pr", "pgrep --signal TERM --full chunk-pr", "pgrep -f 'chunk[pr'", "pgrep -f 'chunk-pr .*merg'", "nice pgrep -f chunk-pr", "bash -c 'pgrep -f chunk-pr'"]:
with self.subTest(command): with self.subTest(command):
self.assertEqual(checked(command), ["endless-wait"]) self.assertEqual(checked(command), ["endless-wait"])
self.assertIn("pgrep -x", breaches("pgrep -f chunk-pr")[0].detail) self.assertIn("pgrep -x", breaches("pgrep -f chunk-pr")[0].detail)
def test_an_endless_wait_names_its_loop_and_the_folder_it_runs_in(self):
head = "until [ -s /tmp/a-file-whose-name-takes-the-head-past-sixty-characters-by-itself ]"
found = breaches(f"cd /w && {head}; do sleep 1; done")
self.assertEqual([breach.directory for breach in found], ["/w"])
self.assertIn(f"`{head[:60]}`, has neither a time limit nor a count cap; use `~/.claude/bin/wait-for", found[0].detail)
self.assertEqual([breach.directory for breach in breaches("cd /w && bash -c 'pgrep -f x; until [ -s f ]; do sleep 1; done'")], ["/w", "/w"])
self.assertEqual(len(breaches("pgrep -f aa; bash -c 'pgrep -f bb'")), 2)
def test_a_loop_that_waits_on_its_own_pgrep_breaks_endless_wait_twice(self): def test_a_loop_that_waits_on_its_own_pgrep_breaks_endless_wait_twice(self):
command = 'until [ -s /tmp/merge-402.log ] && ! pgrep -f "chunk-pr merg"; do sleep 15; done' command = 'until [ -s /tmp/merge-402.log ] && ! pgrep -f "chunk-pr merg"; do sleep 15; done'
self.assertEqual(checked(command), ["endless-wait", "endless-wait"]) self.assertEqual(checked(command), ["endless-wait", "endless-wait"])
self.assertEqual(checked(command.replace("-f ", "-x ")), ["endless-wait"]) self.assertEqual(checked(command.replace("-f ", "-x ")), ["endless-wait"])
def test_a_pgrep_f_on_a_pattern_the_command_lacks_or_a_pgrep_without_f_passes_endless_wait(self): def test_a_pgrep_f_on_a_pattern_the_command_lacks_or_a_pgrep_without_f_passes_endless_wait(self):
for command in ["pgrep -f '[c]hunk-pr merg'", "pgrep -f \"$name\"", "pgrep -f '^python3 .*loop-claude$'", "pgrep -x chunk-pr", "pgrep chunk-pr", "pgrep -u me -x chunk-pr", "pkill -f -u me '[l]oop-claude'", "echo pgrep -f chunk-pr", "git commit -m 'Refuse pgrep -f chunk-pr'", "pgrep -f"]: for command in ["pgrep -f '[c]hunk-pr merg'", "pgrep -f \"$name\"", "pgrep -f '^python3 .*loop-claude$'", "pgrep -x chunk-pr", "pgrep chunk-pr", "pgrep -u me -x chunk-pr", "pkill -f -u me '[l]oop-claude'", "pkill --signal TERM --full '[c]hunk'", "pkill --signal=TERM --full '[c]hunk'", "pgrep -f -U me '[c]hunk' -u", "echo pgrep -f chunk-pr", "git commit -m 'Refuse pgrep -f chunk-pr'", "pgrep -f"]:
with self.subTest(command): with self.subTest(command):
self.assertEqual(checked(command), []) self.assertEqual(checked(command), [])