mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-02 10:09:02 +01:00
Retain safe facts for opaque prior-stage log read failures
Release run 46300522335 attempt 2 could report only exit 1 for its prior staging-job log read. Capture response headers for raw logs and retain only numeric status and captured stream byte counts in failures, without exposing URLs or response/error text. Preserve existing retry classification, child acknowledgement, dispatch and fail-closed gates. Contract-Neutral: Add diagnostic metadata to prior-stage API read failures without changing release prerequisites, dispatch or recovery admission, source identity, or retry policy. Change-source: pulse-maintainer
This commit is contained in:
@@ -17,6 +17,7 @@ RUN_ID = r"[1-9][0-9]{0,18}"
|
||||
FINISHED_DISPATCH = {"success", "failure", "cancelled", "timed_out", "startup_failure"}
|
||||
MAX_READ_ATTEMPTS = 3
|
||||
RETRY_DELAYS = (1.0, 2.0)
|
||||
RESPONSE_STATUS = re.compile(rb"^HTTP/[0-9]+(?:\.[0-9]+)? ([1-5][0-9]{2})(?:[ \r\n]|$)")
|
||||
HTTP_STATUS = re.compile(r"\bHTTP\s+([1-5][0-9]{2})\b")
|
||||
TRANSIENT_HTTP_CODES = frozenset({429, 500, 502, 503, 504})
|
||||
TRANSIENT_NETWORK_MARKERS = (
|
||||
@@ -63,14 +64,39 @@ def _classify_read_error(exc: Exception) -> tuple[str, bool]:
|
||||
return "os-error", False
|
||||
|
||||
|
||||
def _read_failure_facts(exc: Exception) -> str:
|
||||
"""Emit only fixed metadata, never captured URLs, headers, bodies or errors.
|
||||
|
||||
These facts are diagnostic, not a new retry classifier. In particular an
|
||||
unclassified nonzero exit stays non-retryable, even with a response status.
|
||||
"""
|
||||
if not isinstance(exc, (subprocess.CalledProcessError, subprocess.TimeoutExpired)):
|
||||
return ""
|
||||
|
||||
def as_bytes(value: bytes | str | None) -> bytes:
|
||||
return value.encode("utf-8", errors="replace") if isinstance(value, str) else value or b""
|
||||
|
||||
stdout, stderr = as_bytes(exc.stdout), as_bytes(exc.stderr)
|
||||
status = RESPONSE_STATUS.match(stdout)
|
||||
response = f", response HTTP {status[1].decode('ascii')}" if status else ""
|
||||
return f"{response}, stdout {len(stdout)} bytes, stderr {len(stderr)} bytes"
|
||||
|
||||
|
||||
def read_api(endpoint: str, label: str = "GitHub API") -> str:
|
||||
last_cause = "unknown"
|
||||
for attempt in range(MAX_READ_ATTEMPTS):
|
||||
try:
|
||||
response = subprocess.run(["gh", "api", endpoint], capture_output=True, timeout=30, check=True)
|
||||
command = ["gh", "api", endpoint]
|
||||
if endpoint.endswith("/logs"):
|
||||
# Raw logs are not JSON. Retain their response status as well
|
||||
# so a failed gh read cannot erase it with an opaque exit 1.
|
||||
# ACK matching ignores headers; no captured headers are printed.
|
||||
command.append("--include")
|
||||
response = subprocess.run(command, capture_output=True, timeout=30, check=True)
|
||||
break
|
||||
except (OSError, subprocess.SubprocessError) as exc:
|
||||
last_cause, retryable = _classify_read_error(exc)
|
||||
last_cause += _read_failure_facts(exc)
|
||||
if retryable and attempt + 1 < MAX_READ_ATTEMPTS:
|
||||
delay = RETRY_DELAYS[min(attempt, len(RETRY_DELAYS) - 1)]
|
||||
if delay > 0:
|
||||
|
||||
@@ -1728,8 +1728,13 @@ def record(kind, value):
|
||||
with (fix / "calls").open("a") as out:
|
||||
print(json.dumps([attempt, kind, value]), file=out)
|
||||
|
||||
if len(args) == 2 and args[0] == "api":
|
||||
if args[0] == "api" and (len(args) == 2 or args[2:] == ["--include"]):
|
||||
endpoint = args[1]
|
||||
if endpoint.endswith("/logs"):
|
||||
assert args[2:] == ["--include"]
|
||||
print("HTTP/2.0 200 OK\r\nX-Private: not-for-output\r\n\r\n", end="")
|
||||
else:
|
||||
assert len(args) == 2
|
||||
if match := re.fullmatch(r"repos/rcourtman/Pulse/actions/runs/200/attempts/(\d+)/jobs\?per_page=100", endpoint):
|
||||
assert token == "public-reader"
|
||||
record("jobs", int(match[1]))
|
||||
@@ -2052,6 +2057,61 @@ else:
|
||||
self.assertIn("attempt 1 staging job 101 log: exit 1, HTTP 403", str(ctx.exception))
|
||||
self.assertNotIn("secret-token-marker", str(ctx.exception))
|
||||
|
||||
def test_previous_private_stage_retains_safe_log_read_failure_facts(self) -> None:
|
||||
"""Unknown read errors stay stopped but no longer erase HTTP/stream facts."""
|
||||
import importlib.util
|
||||
from unittest import mock
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"previous_private_stage_diagnostics",
|
||||
REPO_ROOT / "scripts/release_control/previous_private_stage.py",
|
||||
)
|
||||
assert spec and spec.loader
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
endpoint = "repos/rcourtman/Pulse/actions/jobs/101/logs"
|
||||
acknowledgement = (
|
||||
b"2026-11-29T19:42:01Z Acknowledged private Pro build dispatch run "
|
||||
b"46302350320 in rcourtman/pulse-enterprise.\n"
|
||||
)
|
||||
# Native gh --include captures response headers, but only the numeric
|
||||
# status and byte counts may escape a failed read. No URL/body/stderr.
|
||||
headers = b"HTTP/2.0 403 Forbidden\r\nLocation: https://secret.invalid/token\r\n\r\n"
|
||||
payload = headers + b'{"message":"private-response-marker"}'
|
||||
failure = subprocess.CalledProcessError(
|
||||
1, ["gh"], output=payload, stderr=b"private-stderr-marker"
|
||||
)
|
||||
with mock.patch.object(mod.subprocess, "run", side_effect=failure) as run:
|
||||
with self.assertRaises(mod.EvidenceError) as ctx:
|
||||
mod.read_api(endpoint, "attempt 1 staging job 101 log")
|
||||
message = str(ctx.exception)
|
||||
self.assertIn("response HTTP 403", message)
|
||||
run.assert_called_once_with(
|
||||
["gh", "api", endpoint, "--include"], capture_output=True, timeout=30, check=True,
|
||||
)
|
||||
self.assertIn(f"stdout {len(payload)} bytes, stderr 21 bytes", message)
|
||||
for secret in ("secret.invalid", "token", "private-response-marker", "private-stderr-marker"):
|
||||
self.assertNotIn(secret, message)
|
||||
|
||||
# Empty streams are distinguishable from unclassified nonempty stderr;
|
||||
# neither is made retryable by these diagnostic facts.
|
||||
for stdout, stderr in ((b"", b""), (b"private-body", b"unclassified")):
|
||||
with self.subTest(stdout_bytes=len(stdout), stderr_bytes=len(stderr)):
|
||||
error = subprocess.CalledProcessError(1, ["gh"], output=stdout, stderr=stderr)
|
||||
with mock.patch.object(mod.subprocess, "run", side_effect=error) as run:
|
||||
with self.assertRaises(mod.EvidenceError) as ctx:
|
||||
mod.read_api(endpoint)
|
||||
self.assertEqual(run.call_count, 1)
|
||||
self.assertIn(f"stdout {len(stdout)} bytes, stderr {len(stderr)} bytes", str(ctx.exception))
|
||||
|
||||
# Headers on a successful raw log do not alter anchored ACK selection.
|
||||
response = b"HTTP/2.0 200 OK\r\nX-Private: hidden\r\n\r\n" + acknowledgement
|
||||
with mock.patch.object(mod.subprocess, "run", return_value=subprocess.CompletedProcess(
|
||||
[], 0, stdout=response, stderr=b"",
|
||||
)):
|
||||
text = mod.read_api(endpoint)
|
||||
self.assertEqual(mod.ACK.findall(text), ["46302350320"])
|
||||
|
||||
def test_private_pro_promotion_redispatches_only_a_moved_main_source_refusal(self) -> None:
|
||||
"""Run the real dispatch loop against doubles: only a pre-credential refusal caused by a
|
||||
pulse-pro main that moved after dispatch is re-dispatched, and only the terminal failure
|
||||
|
||||
Reference in New Issue
Block a user