mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-01 01:52:30 +01:00
Reduce repeated manager startup in updater controls (#4552)
**Reduce repeated manager startup in updater controls** Use built-in private-file I/O instead of repeatedly loading pathlib for every modeled manager command. Keep exact JSON arguments, monotonic observations, faults, state changes and real process deadlines; the native log-sink transaction still must finish within fifteen seconds. Register a direct independent check of manager transcripts and service transitions. Contract-Neutral: Test-double startup and protocol verification only; production updater, service deadlines, trust, saved state, release and rendered-surface contracts are unchanged. **Format updater timestamps without a process per line** The real installer log collector started an external date process for every line. Use the shell's time formatter for the same local timestamp, retaining the legacy date fallback when unsupported and preserving journal/stdout failure precedence. Prove that the normal path starts no date command, that both successful and failed legacy date reads keep prior output/exit behavior, and retain the full bounded installer/recovery matrix. Contract-Neutral: Logging implementation and registered regression controls only; timestamp presentation, sink failure precedence, service deadlines, updater trust, saved state and release behavior are unchanged. --- Fleet candidate `20261117T150006Z-delivery-trust` from the `delivery-trust` lane. Reviewed tip `2badc30b82ebe5937059784cb8d8f0a3e0bc3b67` on `main`. [How Pulse handles triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
@@ -225,6 +225,7 @@ func TestAutoUpdateTransactionLock(t *testing.T) {
|
||||
// matrix below; no native service or published input is used by this fixture.
|
||||
func TestAutoUpdateServiceStateFailsClosed(t *testing.T) {
|
||||
runParallelPythonFixtureControls(t, repoFile("scripts", "tests", "test_auto_update_service_state.py"), "UpdateServiceState", []string{
|
||||
"test_manager_double_retains_exact_calls_phases_and_state",
|
||||
"test_fixture_timeout_retains_partial_output_and_owned_cleanup",
|
||||
"test_transaction_model_clock_is_not_advanced_by_wall_time",
|
||||
"test_poll_timeout_retains_backup_without_start_or_rollback",
|
||||
@@ -264,6 +265,7 @@ func TestAutoUpdateLogSinkFailures(t *testing.T) {
|
||||
"test_fixture_timeout_cannot_be_hidden_by_interrupted_protocol_writes",
|
||||
"test_fixture_success_cannot_hide_malformed_protocol",
|
||||
"test_logger_double_keeps_complete_argument_frames_and_exit_sequence",
|
||||
"test_real_log_timestamp_avoids_date_startup_and_preserves_legacy_fallback",
|
||||
"test_real_log_retains_each_sink_failure_in_conditional_calls",
|
||||
"test_real_logger_deadline_preserves_stdout_exit_and_owned_cleanup",
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ PINNED_RELEASE_SSH_PUBLIC_KEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMZd/DaH+Bldz
|
||||
log() {
|
||||
local level=$1
|
||||
shift
|
||||
local logger_status=0 output_status=0
|
||||
local logger_status=0 output_status=0 timestamp=""
|
||||
# Conditional callers disable errexit throughout this function. Try both
|
||||
# sinks, but never let successful stdout hide a failed journal write (or
|
||||
# vice versa). The installer collector owns draining and the first error.
|
||||
@@ -30,7 +30,13 @@ log() {
|
||||
# recovery path until systemd kills the whole update. Keep a TERM deadline
|
||||
# and KILL backstop; timeout's observed failure still wins over stdout.
|
||||
timeout -k 1 5 logger -t "$LOG_TAG" -p "user.$level" "$@" || logger_status=$?
|
||||
echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $@" || output_status=$?
|
||||
# Installer output can contain many lines. Format the same local timestamp
|
||||
# without a subshell and date process for each one. Older Bash versions
|
||||
# without the time conversion keep the existing date path and semantics.
|
||||
if ! printf -v timestamp '%(%Y-%m-%d %H:%M:%S)T' -1 2>/dev/null; then
|
||||
timestamp=$(date '+%Y-%m-%d %H:%M:%S') || :
|
||||
fi
|
||||
echo "[$timestamp] [$level] $@" || output_status=$?
|
||||
if [[ "$logger_status" != 0 ]]; then
|
||||
return "$logger_status"
|
||||
fi
|
||||
|
||||
@@ -25,16 +25,23 @@ UPDATER = Path(os.environ.get("PULSE_AUTO_UPDATER_UNDER_TEST", ROOT / "scripts/p
|
||||
|
||||
MANAGER = r'''#!/usr/bin/env python3
|
||||
import json, os, sys, time
|
||||
from pathlib import Path
|
||||
f = Path(os.environ["FIXTURE"])
|
||||
# This executable runs for every modeled manager read. Keep startup independent
|
||||
# of pathlib's transitive imports; the private fixture only needs named files.
|
||||
f = os.environ["FIXTURE"]
|
||||
def read(name):
|
||||
with open(os.path.join(f, name)) as source:
|
||||
return source.read()
|
||||
def write(name, text):
|
||||
with open(os.path.join(f, name), "w") as target:
|
||||
target.write(text)
|
||||
args = sys.argv[1:]
|
||||
with (f / "calls").open("a") as out:
|
||||
with open(os.path.join(f, "calls"), "a") as out:
|
||||
out.write(json.dumps(args) + "\n")
|
||||
mode = os.environ["MODE"]
|
||||
after = (f / "installer-ran").exists()
|
||||
stopped = (f / "stop-ran").exists()
|
||||
state = (f / "state").read_text().strip()
|
||||
with (f / "call-observations").open("a") as out:
|
||||
after = os.path.exists(os.path.join(f, "installer-ran"))
|
||||
stopped = os.path.exists(os.path.join(f, "stop-ran"))
|
||||
state = read("state").strip()
|
||||
with open(os.path.join(f, "call-observations"), "a") as out:
|
||||
out.write(json.dumps(dict(args=args, state=state, after_install=after,
|
||||
after_stop=stopped, monotonic_ns=time.monotonic_ns())) + "\n")
|
||||
if args[0] == "show":
|
||||
@@ -70,14 +77,14 @@ if args[0] == "show":
|
||||
if args[0] == "is-active":
|
||||
sys.exit(0 if state == "active" and not mode.startswith("initial-") else 1)
|
||||
if args[0] == "stop":
|
||||
(f / "stop-ran").write_text("attempted\n")
|
||||
write("stop-ran", "attempted\n")
|
||||
if mode == "stop-hang": time.sleep(30)
|
||||
if mode == "stop-error": sys.exit(1)
|
||||
if mode != "stop-noop": (f / "state").write_text("inactive\n")
|
||||
if mode != "stop-noop": write("state", "inactive\n")
|
||||
sys.exit(0)
|
||||
if args[0] == "start":
|
||||
(f / "start-ran").write_text("attempted\n")
|
||||
(f / "state").write_text("active\n")
|
||||
write("start-ran", "attempted\n")
|
||||
write("state", "active\n")
|
||||
sys.exit(0)
|
||||
sys.exit(97)
|
||||
'''
|
||||
@@ -567,6 +574,47 @@ exec sleep 30
|
||||
|
||||
# Keep the expensive real-collector matrix separate from manager timeout
|
||||
# controls, without widening their deadline or dropping any combinations.
|
||||
def test_real_log_timestamp_avoids_date_startup_and_preserves_legacy_fallback(self):
|
||||
for legacy, date_exit in ((False, 0), (True, 0), (True, 23)):
|
||||
with self.subTest(legacy=legacy, date_exit=date_exit):
|
||||
with tempfile.TemporaryDirectory(prefix="pulse-updater-timestamp-") as directory:
|
||||
f = Path(directory)
|
||||
(f / "logger").write_text('#!/bin/sh\nexit 0\n')
|
||||
(f / "date").write_text(
|
||||
'#!/bin/sh\nprintf "%s\\n" "$*" >> "$FIXTURE/date-calls"\n'
|
||||
'printf "legacy timestamp\\n"\nexit "$DATE_EXIT"\n')
|
||||
for name in ("logger", "date"):
|
||||
(f / name).chmod(0o755)
|
||||
env = dict(os.environ, UPDATER=str(UPDATER), FIXTURE=str(f), DATE_EXIT=str(date_exit),
|
||||
PATH=str(f) + os.pathsep + os.environ["PATH"], TZ="UTC0")
|
||||
script = 'source "$UPDATER"\n'
|
||||
if legacy:
|
||||
# Model only an unsupported time conversion. All other
|
||||
# printf calls retain the real shell builtin, and log()
|
||||
# still runs the actual timeout/sink and stdout write.
|
||||
script += r'''
|
||||
printf() {
|
||||
if [[ "${1:-}" == -v && "${3:-}" == '%(%Y-%m-%d %H:%M:%S)T' ]]; then return 1; fi
|
||||
builtin printf "$@"
|
||||
}
|
||||
'''
|
||||
script += "log info 'timestamp boundary'\n"
|
||||
before = time.time()
|
||||
result = subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, timeout=5)
|
||||
after = time.time()
|
||||
self.assertEqual((result.returncode, result.stderr), (0, ""))
|
||||
if legacy:
|
||||
self.assertEqual(result.stdout, "[legacy timestamp] [info] timestamp boundary\n")
|
||||
self.assertEqual((f / "date-calls").read_text(), "+%Y-%m-%d %H:%M:%S\n")
|
||||
else:
|
||||
self.assertFalse((f / "date-calls").exists(), "one date process per log line remains")
|
||||
stamp = result.stdout[:21]
|
||||
self.assertEqual(result.stdout[21:], " [info] timestamp boundary\n")
|
||||
import calendar
|
||||
observed = calendar.timegm(time.strptime(stamp, "[%Y-%m-%d %H:%M:%S]"))
|
||||
self.assertLessEqual(int(before), observed)
|
||||
self.assertLessEqual(observed, int(after))
|
||||
|
||||
def test_real_log_retains_each_sink_failure_in_conditional_calls(self):
|
||||
for logger_exit, closed_stdout, expected in ((0, False, 0), (73, False, 73),
|
||||
(0, True, 1), (73, True, 73)):
|
||||
@@ -749,6 +797,53 @@ child.wait()
|
||||
|
||||
|
||||
class UpdateServiceState(UpdaterFixture):
|
||||
def test_manager_double_retains_exact_calls_phases_and_state(self):
|
||||
# The low-startup-cost manager is still a separate process. Verify its
|
||||
# real private-file protocol independently of the updater's verdict so
|
||||
# an optimization cannot silently erase recovery or phase evidence.
|
||||
with tempfile.TemporaryDirectory(prefix="pulse-updater-manager-") as directory:
|
||||
f = Path(directory)
|
||||
manager = f / "manager.py"
|
||||
manager.write_text(MANAGER)
|
||||
(f / "state").write_text("active\n")
|
||||
env = dict(os.environ, FIXTURE=str(f), MODE="normal", LOAD_STATE="loaded")
|
||||
service = 'pulse-custom@quoted " \\ and\ttab\nnext ü'
|
||||
show = ["show", service, "--no-pager", "--property=LoadState", "--property=ActiveState"]
|
||||
commands, expected = [], []
|
||||
|
||||
def command(args, state, *, installed=False, stopped=False, status=0, output=b""):
|
||||
result = subprocess.run([sys.executable, "-I", "-S", str(manager)] + args,
|
||||
env=env, capture_output=True, timeout=5)
|
||||
self.assertEqual((result.returncode, result.stdout, result.stderr), (status, output, b""))
|
||||
commands.append(args)
|
||||
expected.append(dict(args=args, state=state, after_install=installed, after_stop=stopped))
|
||||
|
||||
active = b"ActiveState=active\nLoadState=loaded\n"
|
||||
inactive = b"ActiveState=inactive\nLoadState=loaded\n"
|
||||
command(show, "active", output=active)
|
||||
(f / "installer-ran").write_text("attempted\n")
|
||||
(f / "state").write_text("inactive\n")
|
||||
command(show, "inactive", installed=True, output=inactive)
|
||||
command(["start", service], "inactive", installed=True)
|
||||
self.assertEqual((f / "start-ran").read_text(), "attempted\n")
|
||||
self.assertEqual((f / "state").read_text(), "active\n")
|
||||
command(show, "active", installed=True, output=active)
|
||||
command(["stop", service], "active", installed=True)
|
||||
self.assertEqual((f / "stop-ran").read_text(), "attempted\n")
|
||||
self.assertEqual((f / "state").read_text(), "inactive\n")
|
||||
command(show, "inactive", installed=True, stopped=True, output=inactive)
|
||||
command(["is-active", service], "inactive", installed=True, stopped=True, status=1)
|
||||
command(["unsupported", service], "inactive", installed=True, stopped=True, status=97)
|
||||
protocol = read_fixture_protocol(f)
|
||||
self.assertEqual(protocol["protocol_errors"], {})
|
||||
self.assertEqual(protocol["calls"], commands)
|
||||
observations = protocol["call_observations"]
|
||||
times = [item["monotonic_ns"] for item in observations]
|
||||
self.assertTrue(all(isinstance(value, int) and value > 0 for value in times))
|
||||
self.assertTrue(all(a < b for a, b in zip(times, times[1:])))
|
||||
self.assertEqual([{key: value for key, value in item.items() if key != "monotonic_ns"}
|
||||
for item in observations], expected)
|
||||
|
||||
def test_fixture_timeout_retains_partial_output_and_owned_cleanup(self):
|
||||
result, execution = capture_fixture_command(
|
||||
["bash", "-c", "printf 'partial stdout\\n'; printf 'partial stderr\\n' >&2; "
|
||||
|
||||
Reference in New Issue
Block a user