Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 27 additions & 8 deletions pm-stack/health-hooks/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,13 +573,15 @@ def post_to_throat(record, deadline=None):
"severity": record["severity"],
"title": record["title"],
"body": record["body"],
"stackHealth": {
"serviceId": record["target"],
"name": TARGETS[record["target"]],
"state": "down" if record["state"] == "down" else "up",
"since": record["firedAt"],
"detail": record["body"],
},
# The record's own stackHealth member, built once in main —
# never rebuilt here, so the JSONL record, this POST body, and
# the ledger-bound extension below share one shape (#12603).
"stackHealth": record["stackHealth"],
# The full incident record as the healthHook extension: the
# aggregator stores it in the alerts ledger as the C3 record of
# detail (#12599 decision b). Best-effort like the rest of this
# post — a rejection never changes the verdict or the record.
"healthHook": record,
}
try:
data = json.dumps(body).encode()
Expand Down Expand Up @@ -686,11 +688,18 @@ def main(argv):
intake_key = (open_incident or {}).get(
"key"
) or f"health-hook:{target}:{incident_id}"
# A recovery reads "recovered", not "is up" (#12603); dedupe is by
# key, never title, so the wording change cannot split an incident.
title = (
f"Health hook: {TARGETS[target]} recovered"
if state == "up" and recovery_of
else f"Health hook: {TARGETS[target]} is {state}"
)
record = {
"source": "health-hook",
"key": intake_key,
"severity": severity,
"title": f"Health hook: {TARGETS[target]} is {state}",
"title": title,
"body": summary,
"target": target,
"state": state,
Expand All @@ -700,6 +709,16 @@ def main(argv):
"incidentId": incident_id,
"recoveryOf": recovery_of,
"evidence": evidence,
# Built once, here: the JSONL record, the throat POST body, and
# the ledger-bound healthHook extension all carry this member
# (#12603, one record shape).
"stackHealth": {
"serviceId": target,
"name": TARGETS[target],
"state": "down" if state == "down" else "up",
"since": fired_at,
"detail": summary,
},
}

# Only record incidents for down/transient? Record all for audit, but
Expand Down
142 changes: 142 additions & 0 deletions pm-stack/health-hooks/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,148 @@ def test_sessions_last_hour_reads_the_live_store():
assert R.count_sessions_last_hour(Path(td) / "missing.db", now_ms=now) is None


def _capture_throat_body(record):
"""Run the real post_to_throat against a fake intake; return the
decoded JSON body it sent. Oracle: the #12599 record shape."""
captured = {}

class Resp:
def __enter__(self):
return self

def __exit__(self, *exc):
return False

def read(self):
return b""

def getcode(self):
return 200

def fake_urlopen(req, timeout=None):
captured["body"] = json.loads(req.data.decode())
return Resp()

with (
mock.patch.object(R, "bws_lookup", return_value=("resolved", "tok")),
mock.patch.object(R, "urlopen", side_effect=fake_urlopen),
):
result = R.post_to_throat(record)
assert result["posted"] is True
return captured["body"]


def test_record_shape_one_shape_for_jsonl_and_post():
# #12603 item 1: the record is built once, in the full design shape
# including stackHealth; the JSONL record and the record handed to
# post_to_throat are the same shape.
with tempfile.TemporaryDirectory() as td:
incident_file = Path(td) / "incidents.jsonl"
with (
mock.patch.dict(
os.environ, {"PM_HEALTH_HOOKS_INCIDENT_FILE": str(incident_file)}
),
mock.patch.object(
R, "probe_opencode", return_value=("down", "unreachable", {"tcp": {}})
),
mock.patch.object(
R, "post_to_throat", return_value={"posted": True}
) as post,
):
with redirect_stdout(StringIO()):
assert R.main(["--target", "opencode-working"]) == 0
record = post.call_args.args[0]
stored = json.loads(incident_file.read_text().splitlines()[0])
assert stored == record
assert record["stackHealth"] == {
"serviceId": "opencode-working",
"name": "OpenCode working",
"state": "down",
"since": record["firedAt"],
"detail": record["body"],
}
assert record["title"] == "Health hook: OpenCode working is down"


def test_post_to_throat_posts_the_full_record_as_healthhook_extension():
# #12603 item 2: the POST body carries the full record as the
# healthHook extension alongside the pre-existing members, and its
# stackHealth member is the record's own (reuse, not rebuild — a
# sentinel detail proves the value came from the record).
record = {
"source": "health-hook",
"key": "health-hook:opencode-working:inc-1",
"severity": "warning",
"title": "Health hook: OpenCode working is down",
"body": "unreachable",
"target": "opencode-working",
"state": "down",
"caller": "test",
"firedAt": "2026-11-20T03:04:05Z",
"observedAt": None,
"incidentId": "inc-1",
"recoveryOf": None,
"evidence": {"tcp": {"ok": False}},
"stackHealth": {
"serviceId": "opencode-working",
"name": "OpenCode working",
"state": "down",
"since": "2026-11-20T03:04:05Z",
"detail": "sentinel-detail",
},
}
body = _capture_throat_body(record)
assert body["healthHook"] == record
assert body["stackHealth"] == record["stackHealth"]
assert body["stackHealth"]["detail"] == "sentinel-detail"
assert body["source"] == "health-hook"
assert body["key"] == record["key"]
assert body["severity"] == record["severity"]
assert body["title"] == record["title"]
assert body["body"] == record["body"]


def test_recovery_title_reads_recovered_and_record_links_lineage():
# #12603 item 3: a recovery's title is "Health hook: <name>
# recovered"; its record carries recoveryOf lineage and an "up"
# stackHealth member, and the posted extension is that same record.
with tempfile.TemporaryDirectory() as td:
incident_file = Path(td) / "incidents.jsonl"
incident_file.write_text(
json.dumps(
{
"target": "opencode-working",
"state": "down",
"incidentId": "down-123",
"key": "health-hook:opencode-working:down-123",
}
)
+ "\n"
)
with (
mock.patch.dict(
os.environ, {"PM_HEALTH_HOOKS_INCIDENT_FILE": str(incident_file)}
),
mock.patch.object(
R, "probe_opencode", return_value=("transient", "probe recovered", {})
),
mock.patch.object(
R, "post_to_throat", return_value={"posted": True}
) as post,
):
with redirect_stdout(StringIO()):
assert R.main(["--target", "opencode-working"]) == 0
record = post.call_args.args[0]
assert record["title"] == "Health hook: OpenCode working recovered"
assert record["state"] == "up"
assert record["recoveryOf"] == "down-123"
assert record["stackHealth"]["state"] == "up"
body = _capture_throat_body(record)
assert body["title"] == "Health hook: OpenCode working recovered"
assert body["healthHook"]["recoveryOf"] == "down-123"
assert body["healthHook"]["incidentId"] == record["incidentId"]


def test_shell_wrappers_are_executable():
for wrapper in (HERE / "pm-stack-reachable.sh", HERE / "opencode-working.sh"):
assert wrapper.stat().st_mode & 0o111, wrapper
Expand Down