interplane.Get Omega
Read in your language

gpu-head-to-head

aien-dev/gpu-head-to-head

Brought by drakestapleton

branch main Branches Tags History

gpu-head-to-head / bench / test-run-arm-lifecycle.py

256 lines · 11393 bytes Raw Blame History
1#!/usr/bin/env python3
2"""CPU-only ownership and interruption controls for external benchmark lifecycle."""
3from pathlib import Path
4import shlex
5import os
6import signal
7import time
8import subprocess
9import tempfile
10import unittest
11HERE=Path(__file__).resolve().parent
12
13class ContainerOwnershipTests(unittest.TestCase):
14 def test_foreign_container_is_never_stopped(self):
15 source=(HERE/'run_arm.sh').read_text()
16 function=source[source.index('stop_server() {'):source.index('ready() {')]
17 with tempfile.TemporaryDirectory() as tmp:
18 script='''set -u
19ARM=VLLM CTR=fixture-unowned SPID=999999999 PAT=fixture-no-match
20RUN_ID=our-session LOGD=%s
21board() { :; }
22docker() { case "$1" in inspect) echo someone-else ;; stop) echo stopped > "$LOGD/foreign-stopped" ;; esac; }
23kill() { return 1; }
24sleep() { :; }
25pgrep() { return 1; }
26''' % shlex.quote(tmp)
27 result=subprocess.run(['bash','-c',script+function+'\nstop_server\n'],capture_output=True,text=True,timeout=5)
28 self.assertFalse((Path(tmp)/'foreign-stopped').exists(),result.stderr)
29 self.assertNotEqual(result.returncode,0)
30
31 def test_owned_container_launch_records_label_and_shutdown(self):
32 source=(HERE/'run_arm.sh').read_text()
33 functions=source[source.index('start_server() {'):source.index('ready() {')]
34 with tempfile.TemporaryDirectory() as tmp:
35 script="""set -u
36source %s
37LOGD=%s ARM=VLLM CTR=stack-fixture RUN_ID=fixture SPID=
38MDIR=/fixture VLLM_IMG=fixture-image SRV_CPUS=0-1 VLLM_UTIL=0.50
39trap 'for p in $(jobs -pr); do kill -TERM "$p" 2>/dev/null || true; done; wait 2>/dev/null || true' EXIT
40timeout() { shift; "$@"; }
41docker() {
42 case "$1" in
43 create) printf '%%s\n' "$@" > "$LOGD/create-args"; echo fixture-id ;;
44 start) echo started > "$LOGD/start-called"; exec sleep 60 ;;
45 inspect) echo fixture ;;
46 stop) echo stopped > "$LOGD/stop-called" ;;
47 esac
48}
49""" % (shlex.quote(str(HERE/'session-lifecycle.sh')),shlex.quote(tmp))
50 result=subprocess.run(['bash','-c',script+functions+'\nstart_server && stop_server\n'],
51 capture_output=True,text=True,timeout=5)
52 self.assertEqual(result.returncode,0,result.stderr)
53 args=(Path(tmp)/'create-args').read_text().splitlines()
54 self.assertIn('aien.stack-comparison.run=fixture',args)
55 self.assertIn('never',args)
56 self.assertTrue((Path(tmp)/'server-identity.txt').exists())
57 self.assertTrue((Path(tmp)/'stop-called').exists())
58
59 def test_failed_container_creation_never_starts_server(self):
60 source=(HERE/'run_arm.sh').read_text()
61 function=source[source.index('start_server() {'):source.index('stop_server() {')]
62 with tempfile.TemporaryDirectory() as tmp:
63 script="""set -u
64source %s
65LOGD=%s ARM=VLLM CTR=stack-fixture RUN_ID=fixture SPID=
66MDIR=/fixture VLLM_IMG=fixture-image SRV_CPUS=0-1 VLLM_UTIL=0.50
67timeout() { shift; "$@"; }
68docker() { if [ "$1" = create ]; then return 7; fi; echo wrongly-started > "$LOGD/start-called"; }
69""" % (shlex.quote(str(HERE/'session-lifecycle.sh')),shlex.quote(tmp))
70 result=subprocess.run(['bash','-c',script+function+'\nstart_server\n'],capture_output=True,text=True,timeout=5)
71 self.assertNotEqual(result.returncode,0)
72 self.assertFalse((Path(tmp)/'start-called').exists())
73
74class ProcessLifecycleTests(unittest.TestCase):
75 def shell(self, body):
76 prefix="""set -u
77trap 'for p in $(jobs -pr); do kill -TERM "$p" 2>/dev/null || true; done; wait 2>/dev/null || true' EXIT
78source %s
79""" % shlex.quote(str(HERE/'session-lifecycle.sh'))
80 result=subprocess.run(['bash','-c',prefix+body],capture_output=True,text=True,timeout=15)
81 self.assertEqual(result.returncode,0,result.stderr)
82 return result.stdout
83
84 def test_tracked_child_stops_and_untracked_decoy_survives(self):
85 self.shell("""sleep 60 & own=$!; h2h_track "$own"
86sleep 60 & decoy=$!
87h2h_stop "$own" 10 || exit 1
88kill -0 "$decoy" || exit 2
89kill -TERM "$decoy"; wait "$decoy" 2>/dev/null || true
90[ -z "${H2H_PID_START[$own]:-}" ]
91""")
92
93 def test_stale_birth_does_not_signal_process(self):
94 self.shell("""sleep 60 & own=$!; h2h_track "$own"
95H2H_PID_START[$own]=stale
96if h2h_stop "$own" 1; then exit 1; fi
97kill -0 "$own" || exit 2
98kill -TERM "$own"; wait "$own" 2>/dev/null || true
99""")
100
101 def test_cleanup_deadline_forces_own_term_ignoring_child(self):
102 with tempfile.TemporaryDirectory() as tmp:
103 ready=Path(tmp)/'ready'
104 body="""bash -c 'trap "" TERM; echo ready > "$1"; exec sleep 60' fixture %s & own=$!
105h2h_track "$own"
106for attempt in {1..100}; do [ -e %s ] && break; sleep 0.01; done
107H2H_STOP_DEADLINE=$SECONDS
108h2h_stop "$own" || exit 1
109if kill -0 "$own" 2>/dev/null; then exit 2; fi
110""" % (shlex.quote(str(ready)),shlex.quote(str(ready)))
111 self.shell(body)
112
113 def test_non_child_and_untracked_process_refused(self):
114 self.shell("""if h2h_track $$; then exit 1; fi
115sleep 60 & other=$!
116if h2h_stop "$other" 1; then kill "$other"; exit 2; fi
117kill -0 "$other" || exit 3
118kill -TERM "$other"; wait "$other" 2>/dev/null || true
119""")
120
121 def test_already_exited_child_can_be_reaped(self):
122 self.shell("""true & own=$!; wait "$own"
123h2h_track "$own" || exit 1
124h2h_stop "$own" 1
125""")
126
127 def test_term_ignoring_child_is_killed_after_grace(self):
128 with tempfile.TemporaryDirectory() as tmp:
129 ready=Path(tmp)/'ready'
130 body="""bash -c 'trap "" TERM; echo ready > "$1"; exec sleep 60' fixture %s & own=$!
131h2h_track "$own"
132for attempt in {1..100}; do [ -e %s ] && break; sleep 0.01; done
133h2h_stop "$own" 2 || exit 1
134if kill -0 "$own" 2>/dev/null; then exit 2; fi
135""" % (shlex.quote(str(ready)),shlex.quote(str(ready)))
136 self.shell(body)
137
138 def test_descendant_is_stopped_with_root(self):
139 with tempfile.TemporaryDirectory() as tmp:
140 ready=Path(tmp)/'child'
141 body="""( sleep 60 & child=$!
142trap 'kill -TERM "$child" 2>/dev/null || true; wait "$child" 2>/dev/null || true; exit 0' TERM
143printf '%%s' "$child" > %s
144wait "$child"
145) & own=$!
146h2h_track "$own"
147for attempt in {1..100}; do [ -s %s ] && break; sleep 0.01; done
148child=$(cat %s)
149h2h_stop "$own" 10 || exit 1
150identity=$(h2h_identity "$child") || exit 0
151read -r state birth parent <<< "$identity"
152[ "$state" = Z ] || [ "$state" = X ]
153""" % tuple(shlex.quote(str(ready)) for _ in range(3))
154 self.shell(body)
155
156 def test_memory_sampler_resolves_published_server_identity(self):
157 source=(HERE/'run_arm.sh').read_text()
158 function=source[source.index('server_pids() {'):source.index('start_server() {')]
159 with tempfile.TemporaryDirectory() as tmp:
160 script='LOGD=%s\nCTR= SPID= RUN_ID=fixture\n' % shlex.quote(tmp)
161 script+=function+"""
162sleep 60 & actual=$!; h2h_track "$actual"
163sleep 60 & decoy=$!
164printf '%s %s\n' "$actual" "${H2H_PID_START[$actual]}" > "$LOGD/server-identity.txt"
165observed=$(server_pids)
166[ "$observed" = "$actual" ] || exit 1
167h2h_stop "$actual" 10 || exit 2
168kill -TERM "$decoy"; wait "$decoy" 2>/dev/null || true
169"""
170 self.shell(script)
171
172 def test_cleanup_preserves_parent_lock_and_releases_own_lock(self):
173 source=(HERE/'run_arm.sh').read_text()
174 cleanup=source[source.index('cleanup_session() {'):source.index('# ---- session ----')]
175 for release in [0,1]:
176 with self.subTest(release=release),tempfile.TemporaryDirectory() as tmp:
177 prefix="""set -u
178LOGD=%s
179SPID= CPID= CMON_PID= WD= SAMP= VMS= BASE=100 GPU_LOCK_HELD=1 GPU_LOCK_RELEASE=%d
180ARM=CONTROL ROUND=R0
181timeout() { shift; "$@"; }
182nvidia-smi() { case "$*" in *noheader*) : ;; *) echo fixture-empty-inventory-header ;; esac; }
183memavail() { echo 100; }
184ktpsr() { echo 99; }
185board() { :; }
186stop_server() { :; }
187""" % (shlex.quote(tmp),release)
188 script=prefix+cleanup+"""
189export LOGD SPID CPID CMON_PID WD SAMP VMS BASE GPU_LOCK_HELD GPU_LOCK_RELEASE ARM ROUND
190export -f cleanup_session timeout nvidia-smi memavail ktpsr board stop_server
191exec 9> "$LOGD/lock"
192flock -n 9 || exit 1
193bash -c 'trap cleanup_session EXIT; exit 0' || exit 2
194if flock -n "$LOGD/lock" true; then acquired=1; else acquired=0; fi
195[ "$acquired" = "$GPU_LOCK_RELEASE" ] || exit 3
196flock -u 9
197flock -n "$LOGD/lock" true
198"""
199 result=subprocess.run(['bash','-c',script],capture_output=True,text=True,timeout=5)
200 self.assertEqual(result.returncode,0,result.stderr)
201
202 def lifecycle_fixture(self, mode):
203 source=(HERE/'run_arm.sh').read_text()
204 stop=source[source.index('stop_server() {'):source.index('ready() {')]
205 cleanup=source[source.index('start_watchdog() {'):source.index('# ---- session ----')]
206 with tempfile.TemporaryDirectory() as tmp:
207 root=Path(tmp)
208 prefix='''set -u
209source %s
210LOGD=%s
211SPID= CPID= CMON_PID= WD= SAMP= VMS= BASE= GPU_LOCK_HELD=0 CTR=
212ARM=OURS ROUND=R0 RUN_ID=fixture
213board() { :; }
214''' % (shlex.quote(str(HERE/'session-lifecycle.sh')),shlex.quote(tmp))
215 body="""
216trap cleanup_session EXIT
217trap 'exit 143' TERM
218trap 'exit 130' INT
219sleep 60 & SPID=$!; h2h_track "$SPID"
220sleep 60 & CPID=$!; h2h_track "$CPID"
221sleep 60 & CMON_PID=$!; h2h_track "$CMON_PID"
222sleep 60 & WD=$!; h2h_track "$WD"
223sleep 60 & SAMP=$!; h2h_track "$SAMP"
224sleep 60 & VMS=$!; h2h_track "$VMS"
225touch "$LOGD/DONE"
226printf '%s\n' "$SPID" "$CPID" "$CMON_PID" "$WD" "$SAMP" "$VMS" > "$LOGD/children"
227"""
228 if mode=='timeout':
229 body += 'h2h_stop "$WD" 10; WD=; start_watchdog 0.02 0.02; wait "$CPID"\n'
230 else:
231 body += 'wait "$CPID"\n' if mode=='term' else ('exit 7\n' if mode=='fail' else 'exit 0\n')
232 process=subprocess.Popen(['bash','-c',prefix+stop+cleanup+body],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
233 try:
234 if mode=='term':
235 deadline=time.monotonic()+5
236 while not (root/'children').exists() and time.monotonic()<deadline:
237 if process.poll() is not None: break
238 time.sleep(0.01)
239 self.assertTrue((root/'children').exists())
240 process.send_signal(signal.SIGTERM)
241 stdout,stderr=process.communicate(timeout=12)
242 self.assertEqual(process.returncode,143 if mode in ['term','timeout'] else 7 if mode=='fail' else 0,stderr)
243 pids=(root/'children').read_text().splitlines()
244 for pid in pids:
245 self.assertFalse(Path('/proc/'+pid).exists(),'owned child survived cleanup: '+pid)
246 self.assertEqual((root/'DONE').exists(),mode=='normal')
247 finally:
248 if process.poll() is None:
249 process.kill();process.communicate(timeout=5)
250
251 def test_normal_exit_cleans_own_processes(self): self.lifecycle_fixture('normal')
252 def test_failed_exit_cleans_own_processes_and_removes_done(self): self.lifecycle_fixture('fail')
253 def test_term_interrupt_cleans_own_processes_and_removes_done(self): self.lifecycle_fixture('term')
254 def test_watchdog_interrupt_cleans_own_processes_and_removes_done(self): self.lifecycle_fixture('timeout')
255
256if __name__=='__main__':unittest.main()