carlos / platform Public

scripts: G2 first-service hang trigger for drill 3 (T4)

claude agent, operated by paul@keymail.dev 0a4f5e0b23a518f133ec665692ade03a8d136b31 parent 50064f2
2 files changed, +469 −0
  • scripts/region-ha-g2/g2-firstserve-stop.sh +101 −0
  • scripts/region_ha_g2_firstserve_test.py +368 −0

Intent

Attributed to this commit: 27.3 g CO₂e (3,328,360 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g2-prep, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/scripts/region-ha-g2/g2-firstserve-stop.sh b/scripts/region-ha-g2/g2-firstserve-stop.sh
new file mode 100755
index 000000000..69aac59c7
--- /dev/null
+++ b/scripts/region-ha-g2/g2-firstserve-stop.sh
@@ -0,0 +1,101 @@
+#!/usr/bin/env bash
+# Deliver a copy to /run/g2-firstserve.sh during the approved drill window.
+# systemd-run --unit=g2-firstserve --collect /run/g2-firstserve.sh --fixture <host>
+# Record its sha256 in the window log. This one-shot removes its own script.
+
+set -u -o pipefail
+
+PROC_ROOT=${PROC_ROOT:-/proc}
+ID_CMD=${ID_CMD:-id}
+fixture=''
+stamp=/run/g2-firstserve.stamp
+timeout=3600
+journal_pid=''
+matcher_pid=''
+
+stop_journal() {
+ if [[ -n "$journal_pid" ]]; then
+ builtin kill -TERM "$journal_pid" 2>/dev/null || true
+ wait "$journal_pid" 2>/dev/null || true
+ journal_pid=''
+ fi
+ if [[ -n "$matcher_pid" ]]; then
+ wait "$matcher_pid" 2>/dev/null || true
+ matcher_pid=''
+ fi
+}
+
+cleanup() {
+ local status=$?
+ trap - EXIT INT TERM
+ stop_journal
+ rm -f -- "$0"
+ printf 'First-service trigger exited with status %s.\n' "$status"
+ exit "$status"
+}
+trap cleanup EXIT
+trap 'exit 130' INT
+trap 'exit 143' TERM
+
+refuse() {
+ printf '%s\n' "$1" >&2
+ exit 1
+}
+
+while (( $# )); do
+ case "$1" in
+ --fixture|--stamp|--timeout)
+ (( $# >= 2 )) || refuse "An option value is missing."
+ case "$1" in
+ --fixture) fixture=$2 ;;
+ --stamp) stamp=$2 ;;
+ --timeout) timeout=$2 ;;
+ esac
+ shift 2
+ ;;
+ *) refuse "An option is not recognised." ;;
+ esac
+done
+
+[[ "$fixture" =~ ^[A-Za-z0-9][A-Za-z0-9.:-]*$ ]] || refuse "A fixture host is required without spaces or control characters."
+[[ "$stamp" == /* && "$stamp" != *$'\n'* ]] || refuse "The stamp path must be absolute without a newline."
+[[ "$timeout" =~ ^[1-9][0-9]*$ && ${#timeout} -le 10 ]] && (( timeout <= 2147483647 )) || refuse "The timeout must be a positive whole number of seconds up to 2147483647."
+uid=$("$ID_CMD" -u) || refuse "Could not verify the current user."
+[[ "$uid" == 0 ]] || refuse "This trigger requires root."
+systemctl is-active --quiet carlos-edge || refuse "The carlos-edge service is not active."
+[[ ! -e "$stamp" && ! -L "$stamp" ]] || refuse "The stamp already exists."
+
+printf 'Waiting for the first successful fixture response for %s.\n' "$fixture"
+match="g2fixture status=200 host=${fixture} "
+# Separate descriptors keep a quiet journal from holding up timeout or cleanup.
+# Use exec so the recorded child is journalctl itself, not a pipeline shell.
+exec {journal_fd}< <(exec journalctl -u carlos-edge -f -n0 -o cat)
+journal_pid=$!
+exec {match_fd}< <(exec grep -F --line-buffered -m1 -- "$match" <&"$journal_fd")
+matcher_pid=$!
+IFS= read -r -t "$timeout" matched <&"$match_fd" || refuse "No matching response arrived before the journal ended or the timeout expired."
+printf 'Matched the first successful fixture response for %s.\n' "$fixture"
+
+pid=$(systemctl show -p MainPID --value carlos-edge) || refuse "Could not read the carlos-edge MainPID."
+[[ "$pid" =~ ^[1-9][0-9]*$ && "$pid" != 1 ]] || refuse "The carlos-edge MainPID is not a process that can be suspended."
+exe=$(readlink -- "$PROC_ROOT/$pid/exe") || refuse "Could not verify the carlos-edge executable."
+[[ "$exe" == /opt/carlos/?* ]] || refuse "The carlos-edge executable is outside /opt/carlos."
+timestamp=$(date -u +%FT%T.%NZ) || refuse "Could not read the UTC time."
+[[ ! -e "$stamp" && ! -L "$stamp" ]] || refuse "The stamp already exists."
+env kill -STOP "$pid" || refuse "Could not suspend carlos-edge."
+if ! (set -o noclobber; printf '%s %s\n' "$timestamp" "$pid" > "$stamp"); then
+ refuse "The process was suspended but its stamp could not be written."
+fi
+stop_journal
+
+while [[ -e "$PROC_ROOT/$pid/stat" ]]; do
+ if ! IFS= read -r stat < "$PROC_ROOT/$pid/stat"; then
+ [[ ! -e "$PROC_ROOT/$pid/stat" ]] && break
+ refuse "Could not read the suspended process state."
+ fi
+ # comm can contain spaces and closing parentheses. State follows the last ).
+ state=${stat##*) }
+ [[ "$state" == "$stat" || ! "$state" =~ ^[A-Za-z][[:space:]] ]] && refuse "Could not parse the suspended process state."
+ [[ ${state:0:1} == T ]] || break
+ sleep 1 || refuse "Could not wait for the suspended process."
+done
diff --git a/scripts/region_ha_g2_firstserve_test.py b/scripts/region_ha_g2_firstserve_test.py
new file mode 100644
index 000000000..b5ade9cc8
--- /dev/null
+++ b/scripts/region_ha_g2_firstserve_test.py
@@ -0,0 +1,368 @@
+"""Offline tests for the copied, self-removing G2 drill script."""
+
+import json
+import os
+from pathlib import Path
+import re
+import signal
+import subprocess
+import tempfile
+import time
+import unittest
+
+
+ROOT = Path(__file__).resolve().parent.parent
+SCRIPT = ROOT / 'scripts/region-ha-g2/g2-firstserve-stop.sh'
+FIXTURE = ROOT / 'scripts/region-ha-g2/fixture/main.go'
+LOG_FORMAT = json.loads(re.search(r'LogFormat\s*=\s*("[^"\n]*")',
+ FIXTURE.read_text()).group(1))
+HOST = 'example.com'
+
+
+def fixture_line(status=200, host=HOST):
+ return LOG_FORMAT % (status, host, '/', '-') + '\n'
+
+
+SHIM = r'''#!/usr/bin/python3
+import json, os, pathlib, signal, sys, time
+name = pathlib.Path(sys.argv[0]).name
+args = sys.argv[1:]
+with open(os.environ['CALLS'], 'a') as log:
+ log.write(json.dumps([name] + args) + '\n')
+if os.environ.get('FAIL_AT') == name + ' ' + ' '.join(args):
+ if os.environ.get('FAIL_OUTPUT'):
+ print(os.environ['FAIL_OUTPUT'])
+ sys.exit(1)
+if name == 'fake-id':
+ assert args == ['-u']
+ print(os.environ.get('TEST_UID', '0'))
+elif name == 'systemctl':
+ if args == ['is-active', '--quiet', 'carlos-edge']:
+ sys.exit(0 if os.environ.get('ACTIVE', '1') == '1' else 1)
+ assert args == ['show', '-p', 'MainPID', '--value', 'carlos-edge']
+ print(os.environ['MAIN_PID'])
+elif name == 'journalctl':
+ assert args == ['-u', 'carlos-edge', '-f', '-n0', '-o', 'cat']
+ def finish(*_):
+ pathlib.Path(os.environ['JOURNAL_EXIT']).touch()
+ sys.exit(0)
+ signal.signal(signal.SIGTERM, finish)
+ pathlib.Path(os.environ['JOURNAL_PID']).write_text(str(os.getpid()))
+ if os.environ.get('WAIT_FOR_LINES'):
+ while not pathlib.Path(os.environ['WAIT_FOR_LINES']).exists():
+ time.sleep(0.01)
+ sys.stdout.write(pathlib.Path(os.environ['LINES']).read_text())
+ sys.stdout.flush()
+ if os.environ.get('JOURNAL_EOF') == '1':
+ finish()
+ while True:
+ time.sleep(0.1)
+elif name == 'kill':
+ assert len(args) == 2 and args[0] == '-STOP'
+ if os.environ.get('STAMP_RACE') == '1':
+ pathlib.Path(os.environ['STAMP']).write_text('Another run.\n')
+elif name == 'date':
+ assert args == ['-u', '+%FT%T.%NZ']
+ print('2026-11-05T12:34:56.123456789Z')
+else:
+ raise AssertionError(name)
+'''
+
+
+class FirstServeStopTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory(
+ prefix='g2-firstserve-test-',
+ dir=os.environ.get('TMPDIR', str(Path.home() / '.cache')))
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+ self.bin = self.root / 'bin'
+ self.bin.mkdir()
+ for name in ('fake-id', 'systemctl', 'journalctl', 'kill', 'date'):
+ shim = self.bin / name
+ shim.write_text(SHIM)
+ shim.chmod(0o700)
+ self.stub = subprocess.Popen(['sleep', '60'])
+ self.addCleanup(self.stop_stub)
+ self.pid = str(self.stub.pid)
+ self.proc = self.root / 'proc'
+ self.process = self.proc / self.pid
+ self.process.mkdir(parents=True)
+ (self.process / 'exe').symlink_to('/opt/carlos/carlos')
+ self.set_state('S')
+ self.copy = self.root / 'g2-firstserve.sh'
+ self.stamp = self.root / 'stamp'
+ self.calls_path = self.root / 'calls'
+ self.lines = self.root / 'lines'
+ self.lines.write_text(fixture_line())
+ self.journal_pid = self.root / 'journal.pid'
+ self.journal_exit = self.root / 'journal.exit'
+ self.env = dict(os.environ, PATH=str(self.bin) + ':' + os.environ['PATH'],
+ ID_CMD=str(self.bin / 'fake-id'), PROC_ROOT=str(self.proc),
+ CALLS=str(self.calls_path), MAIN_PID=self.pid,
+ LINES=str(self.lines), JOURNAL_PID=str(self.journal_pid),
+ JOURNAL_EXIT=str(self.journal_exit), STAMP=str(self.stamp))
+ self.env.pop('BASH_ENV', None)
+
+ def stop_stub(self):
+ self.stub.terminate()
+ self.stub.wait(timeout=5)
+
+ def set_state(self, state):
+ (self.process / 'stat').write_text(f'{self.pid} (carlos ) agent) {state} 1 2 3\n')
+
+ def calls(self):
+ return [json.loads(line) for line in self.calls_path.read_text().splitlines()] \
+ if self.calls_path.exists() else []
+
+ def signals(self):
+ return [call[1:] for call in self.calls() if call[0] == 'kill']
+
+ def start(self, args=None, **env):
+ self.copy.write_text(SCRIPT.read_text())
+ self.copy.chmod(0o700)
+ if args is None:
+ args = ['--fixture', HOST, '--stamp', str(self.stamp), '--timeout', '1']
+ child = subprocess.Popen(['bash', str(self.copy), *args], env=dict(self.env, **env),
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ start_new_session=True)
+ self.addCleanup(self.reap, child)
+ return child
+
+ def reap(self, child):
+ # A broken cleanup trap can leave a child after the shell has exited.
+ try:
+ os.killpg(child.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ child.communicate(timeout=5)
+
+ def finish(self, child):
+ stdout, stderr = child.communicate(timeout=6)
+ self.assertFalse(self.copy.exists(), stdout + stderr)
+ if self.journal_pid.exists():
+ self.assertTrue(self.journal_exit.exists(), stdout + stderr)
+ with self.assertRaises(ProcessLookupError):
+ os.kill(int(self.journal_pid.read_text()), 0)
+ self.assertIsNone(self.stub.poll(), 'The test stub must never receive a real signal.')
+ return child.returncode, stdout + stderr
+
+ def run_script(self, args=None, **env):
+ return self.finish(self.start(args, **env))
+
+ def wait_for(self, path):
+ deadline = time.monotonic() + 4
+ while not path.exists() and time.monotonic() < deadline:
+ time.sleep(0.01)
+ self.assertTrue(path.exists(), str(path))
+
+ def assert_refused(self, **env):
+ code, output = self.run_script(**env)
+ self.assertNotEqual(code, 0, output)
+ self.assertEqual(self.signals(), [])
+ self.assertFalse(self.stamp.exists())
+ return output
+
+ def test_nonmatching_host_and_status_never_trigger(self):
+ self.lines.write_text(fixture_line(host='192.0.2.1') +
+ fixture_line(host='carlos') + fixture_line(status=503) +
+ fixture_line(host=HOST + '.other') +
+ fixture_line(host=HOST + ':443'))
+ self.assert_refused()
+
+ def test_matching_200_stops_once_and_stamps(self):
+ self.lines.write_text(fixture_line() * 5)
+ code, output = self.run_script()
+ self.assertEqual(code, 0, output)
+ self.assertEqual(self.signals(), [['-STOP', self.pid]])
+ self.assertEqual(self.stamp.read_text(), f'2026-11-05T12:34:56.123456789Z {self.pid}\n')
+ self.assertIn(['systemctl', 'show', '-p', 'MainPID', '--value', 'carlos-edge'], self.calls())
+ for line in output.splitlines():
+ self.assertTrue(line.endswith('.'), line)
+
+ def test_match_prefix_comes_from_frozen_constant(self):
+ expected = (LOG_FORMAT % (200, HOST, '/', '-')).split('path=', 1)[0]
+ source = SCRIPT.read_text()
+ match = re.search(r'^match="([^"]+)"$', source, re.M)
+ self.assertIsNotNone(match)
+ self.assertEqual(match.group(1).replace('${fixture}', HOST), expected)
+ self.assertIn('grep -F --line-buffered -m1 -- "$match"', source)
+
+ def test_state_leaving_T_exits(self):
+ self.set_state('T')
+ child = self.start()
+ self.wait_for(self.stamp)
+ self.wait_for(self.journal_exit)
+ time.sleep(1.15)
+ self.assertIsNone(child.poll())
+ self.set_state('S')
+ code, output = self.finish(child)
+ self.assertEqual(code, 0, output)
+ self.assertEqual(self.signals(), [['-STOP', self.pid]])
+
+ def test_pid_gone_exits(self):
+ self.set_state('T')
+ child = self.start()
+ self.wait_for(self.stamp)
+ (self.process / 'stat').unlink()
+ code, output = self.finish(child)
+ self.assertEqual(code, 0, output)
+ self.assertEqual(self.signals(), [['-STOP', self.pid]])
+
+ def test_timeout_without_match(self):
+ self.lines.write_text('')
+ start = time.monotonic()
+ self.assert_refused()
+ self.assertLess(time.monotonic() - start, 3)
+
+ def test_journal_eof_refuses(self):
+ self.lines.write_text('')
+ self.assert_refused(JOURNAL_EOF='1')
+
+ def test_nonroot_refuses_before_service_access(self):
+ self.assert_refused(TEST_UID='1000')
+ self.assertEqual(self.calls(), [['fake-id', '-u']])
+
+ def test_failed_id_refuses(self):
+ self.assert_refused(FAIL_AT='fake-id -u', FAIL_OUTPUT='0')
+
+ def test_inactive_service_refuses_before_journal(self):
+ self.assert_refused(ACTIVE='0')
+ self.assertNotIn('journalctl', [call[0] for call in self.calls()])
+
+ def test_existing_stamp_refuses(self):
+ self.stamp.write_text('Previous run.\n')
+ code, output = self.run_script()
+ self.assertNotEqual(code, 0, output)
+ self.assertEqual(self.signals(), [])
+ self.assertEqual(self.stamp.read_text(), 'Previous run.\n')
+ self.assertNotIn('journalctl', [call[0] for call in self.calls()])
+
+ def test_dangling_stamp_symlink_refuses(self):
+ self.stamp.symlink_to(self.root / 'absent')
+ self.assert_refused()
+ self.assertTrue(self.stamp.is_symlink())
+
+ def test_invalid_mainpid_refuses(self):
+ for pid in ('0', '1', '-2', '', 'abc', '2 3', '0002', '2\n3'):
+ with self.subTest(pid=pid):
+ self.calls_path.unlink(missing_ok=True)
+ self.stamp.unlink(missing_ok=True)
+ target = self.proc / pid
+ target.mkdir(exist_ok=True)
+ (target / 'exe').symlink_to('/opt/carlos/carlos')
+ (target / 'stat').write_text(f'{pid} (carlos) S 1 2 3\n')
+ self.assert_refused(MAIN_PID=pid)
+
+ def test_failed_mainpid_read_refuses(self):
+ self.assert_refused(FAIL_AT='systemctl show -p MainPID --value carlos-edge',
+ FAIL_OUTPUT=self.pid)
+
+ def test_unverified_executable_refuses(self):
+ for executable in ('/usr/bin/sleep', '/opt/carlos-other/carlos', '/opt/carlos/', ''):
+ with self.subTest(executable=executable):
+ self.calls_path.unlink(missing_ok=True)
+ self.stamp.unlink(missing_ok=True)
+ (self.process / 'exe').unlink(missing_ok=True)
+ if executable:
+ (self.process / 'exe').symlink_to(executable)
+ self.assert_refused()
+
+ def test_failed_stop_does_not_stamp(self):
+ code, output = self.run_script(FAIL_AT=f'kill -STOP {self.pid}')
+ self.assertNotEqual(code, 0, output)
+ self.assertEqual(self.signals(), [['-STOP', self.pid]])
+ self.assertFalse(self.stamp.exists())
+
+ def test_failed_clock_does_not_stop(self):
+ self.assert_refused(FAIL_AT='date -u +%FT%T.%NZ')
+
+ def test_stamp_created_after_start_refuses_before_stop(self):
+ gate = self.root / 'release-lines'
+ child = self.start(WAIT_FOR_LINES=str(gate))
+ self.wait_for(self.journal_pid)
+ self.stamp.write_text('Another run.\n')
+ gate.touch()
+ code, output = self.finish(child)
+ self.assertNotEqual(code, 0, output)
+ self.assertEqual(self.signals(), [])
+ self.assertEqual(self.stamp.read_text(), 'Another run.\n')
+
+ def test_unreadable_state_refuses(self):
+ (self.process / 'stat').unlink()
+ (self.process / 'stat').mkdir()
+ code, output = self.run_script()
+ self.assertNotEqual(code, 0, output)
+ self.assertIn('Could not read the suspended process state.', output)
+ self.assertEqual(self.signals(), [['-STOP', self.pid]])
+
+ def test_malformed_state_refuses(self):
+ (self.process / 'stat').write_text('Malformed stat.\n')
+ code, output = self.run_script()
+ self.assertNotEqual(code, 0, output)
+ self.assertIn('Could not parse the suspended process state.', output)
+ self.assertEqual(self.signals(), [['-STOP', self.pid]])
+
+ def test_failed_poll_wait_refuses(self):
+ self.set_state('T')
+ shim = self.bin / 'sleep'
+ shim.write_text('#!/bin/sh\nexit 1\n')
+ shim.chmod(0o700)
+ code, output = self.run_script()
+ self.assertNotEqual(code, 0, output)
+ self.assertEqual(self.signals(), [['-STOP', self.pid]])
+
+ def test_noclobber_preserves_concurrent_stamp(self):
+ code, output = self.run_script(STAMP_RACE='1')
+ self.assertNotEqual(code, 0, output)
+ self.assertEqual(self.stamp.read_text(), 'Another run.\n')
+ self.assertEqual(self.signals(), [['-STOP', self.pid]])
+
+ def test_signal_cleanup(self):
+ for signum in (signal.SIGINT, signal.SIGTERM):
+ with self.subTest(signum=signum):
+ self.lines.write_text('')
+ self.journal_pid.unlink(missing_ok=True)
+ self.journal_exit.unlink(missing_ok=True)
+ child = self.start()
+ self.wait_for(self.journal_pid)
+ child.send_signal(signum)
+ code, output = self.finish(child)
+ self.assertEqual(code, 128 + signum, output)
+ self.assertEqual(self.signals(), [])
+ self.assertFalse(self.stamp.exists())
+
+ def test_invalid_arguments_refuse(self):
+ for args in ([], ['--fixture'], ['--fixture', ''], ['--fixture', 'a b'],
+ ['--fixture', HOST, '--timeout', '0'],
+ ['--fixture', HOST, '--timeout', '-1'],
+ ['--fixture', HOST, '--timeout', 'abc'],
+ ['--fixture', HOST, '--timeout', '2147483648'],
+ ['--fixture', HOST, '--timeout', '999999999999999999999'],
+ ['--fixture', HOST, '--stamp', 'relative'],
+ ['--fixture', HOST, '--stamp', '/a\nb'],
+ ['--fixture', HOST, '--stamp'], ['--unknown']):
+ with self.subTest(args=args):
+ self.calls_path.unlink(missing_ok=True)
+ self.stamp.unlink(missing_ok=True)
+ code, output = self.run_script(args=args)
+ self.assertNotEqual(code, 0, output)
+ self.assertEqual(self.signals(), [])
+ self.assertFalse(self.stamp.exists())
+ self.assertEqual(self.calls(), [])
+
+ def test_forbidden_commands(self):
+ source = SCRIPT.read_text()
+ forbidden = (r'\bsystemctl\b[^\n;|&]*\b(?:restart|stop|kill)\b'
+ r'|\bkill\s+-(?:9|KILL)\b|\baws\b|CompleteLifecycleAction|ABANDON')
+ self.assertNotRegex(source, forbidden)
+ commands = [line.strip() for line in source.splitlines()
+ if re.search(r'\bkill\s+-', line) and not line.lstrip().startswith('#')]
+ self.assertEqual(commands, [
+ 'builtin kill -TERM "$journal_pid" 2>/dev/null || true',
+ 'env kill -STOP "$pid" || refuse "Could not suspend carlos-edge."'])
+ self.assertNotRegex(source, '[\u2013\u2014]')
+
+
+if __name__ == '__main__':
+ unittest.main()