Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(chaos): grade readiness where the keys live, and make the fusion kill a crash (#1446) (#1493)

Beenu Arora477b04aff8e1
diff --git a/.github/workflows/chaos.yml b/.github/workflows/chaos.yml
index 481857131..19fccfcde 100644
--- a/.github/workflows/chaos.yml
+++ b/.github/workflows/chaos.yml
@@ -109,10 +109,35 @@ jobs:
# Dependent URLs point at readiness-class endpoints: a 503 there
# means "alive but cannot do my job", which `_responding` counts as
# not serving — the required outcome for a block store's dependents.
- # Legs whose owning service does not yet export the store's key
- # (fusion: lake_writer/kafka; ingest: kafka/graph) stay red with the
- # finding naming that service — that red is the job of this
- # workflow, and the follow-ups live on #1446.
+ #
+ # Every URL below now names the endpoint that actually carries the
+ # store's key. It previously named `/health` for fusion, ingest,
+ # agents and actions, and none of those four reports a dependency
+ # there: `register_dependency` writes to `/readyz` only, fusion's
+ # `/health` is a static `{"status": "healthy"}` from
+ # `app/api/router.py`, and ingest's is `Handler.Health`, which
+ # deliberately checks nothing so a restart loop stays
+ # distinguishable from a dependency outage. So four legs read a key
+ # that the endpoint they asked was never going to mention, and
+ # reported "readiness does not say so" about services that do say
+ # so, one route over. The two legs that passed are exactly the two
+ # already pointing somewhere the key exists.
+ #
+ # Conflating liveness and readiness on one route would be the other
+ # way to close that gap, and it is the anti-pattern `app/_health.py`
+ # and `Handler.Readyz` are both written against — a service that
+ # fails `/health` because a dependency is gone gets restarted in a
+ # loop instead of taken out of rotation.
+ #
+ # qdrant is the one leg that still reads `/health`, and deliberately:
+ # threatintel declares `vector_store` on a hand-written `/health`
+ # rather than through `register_dependency`, so `/readyz` does not
+ # carry it. Worth making uniform one day; pointing this leg at
+ # `/readyz` today would simply lose the key.
+ #
+ # realtime answers `/health`, `/healthz` and `/readyz` from one
+ # handler; it is spelled `/readyz` here so the sentence above is true
+ # of every row.
fail-fast: false
matrix:
include:
@@ -121,15 +146,15 @@ jobs:
readiness_url: http://127.0.0.1:8000/api/v1/health/ready
dependent_urls: >-
api=http://127.0.0.1:8000/api/v1/health/ready
- fusion=http://127.0.0.1:8003/health
- agents=http://127.0.0.1:8001/health
- actions=http://127.0.0.1:8002/health
+ fusion=http://127.0.0.1:8003/readyz
+ agents=http://127.0.0.1:8001/readyz
+ actions=http://127.0.0.1:8002/readyz
- store: redis
profile: core
readiness_url: http://127.0.0.1:8000/api/v1/health/ready
dependent_urls: >-
api=http://127.0.0.1:8000/api/v1/health/ready
- agents=http://127.0.0.1:8001/health
+ agents=http://127.0.0.1:8001/readyz
- store: qdrant
profile: core
readiness_url: http://127.0.0.1:8005/health
@@ -137,22 +162,22 @@ jobs:
threatintel=http://127.0.0.1:8005/health
- store: kafka
profile: core
- readiness_url: http://127.0.0.1:8081/health
+ readiness_url: http://127.0.0.1:8081/readyz
dependent_urls: >-
- ingest=http://127.0.0.1:8081/health
- fusion=http://127.0.0.1:8003/health
- realtime=http://127.0.0.1:8086/health
+ ingest=http://127.0.0.1:8081/readyz
+ fusion=http://127.0.0.1:8003/readyz
+ realtime=http://127.0.0.1:8086/readyz
- store: clickhouse
profile: full
- readiness_url: http://127.0.0.1:8003/health
+ readiness_url: http://127.0.0.1:8003/readyz
dependent_urls: >-
- fusion=http://127.0.0.1:8003/health
+ fusion=http://127.0.0.1:8003/readyz
api=http://127.0.0.1:8000/api/v1/health/ready
- store: neo4j
profile: full
- readiness_url: http://127.0.0.1:8081/health
+ readiness_url: http://127.0.0.1:8081/readyz
dependent_urls: >-
- ingest=http://127.0.0.1:8081/health
+ ingest=http://127.0.0.1:8081/readyz
api=http://127.0.0.1:8000/api/v1/health/ready
steps:
- uses: actions/checkout@v7
diff --git a/scripts/chaos/fusion_restart.py b/scripts/chaos/fusion_restart.py
index 777c2edde..f8f148ca8 100644
--- a/scripts/chaos/fusion_restart.py
+++ b/scripts/chaos/fusion_restart.py
@@ -81,6 +81,13 @@ from load_harness import ( # noqa: E402
_FUSION_K8S_SELECTOR = "app.kubernetes.io/component=alert-fusion"
+#: Named so the self-test can assert the relation between them rather than
+#: either value: a stall rule shorter than a Kafka consumer-group rejoin
+#: cannot tell loss from an unfinished drain, and one longer than the drain
+#: budget can never fire.
+_DEFAULT_DRAIN_TIMEOUT_SECONDS = 420
+_DEFAULT_DRAIN_STALL_SECONDS = 90.0
+
@dataclass
class Verdict:
@@ -160,19 +167,152 @@ def fusion_victims(target: Target, namespace: str) -> list[str]:
return [name for name in out.stdout.split() if name]
+def _inspect(victim: str, template: str) -> str | None:
+ done = subprocess.run( # noqa: S603
+ ["docker", "inspect", "-f", template, victim],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ )
+ value = (done.stdout or "").strip()
+ return value if done.returncode == 0 and value else None
+
+
+def crash_rungs(pid: str, image: str, *, host_pid_is_ours: bool) -> list[tuple[str, list[str]]]:
+ """Every way this harness is allowed to make a container's PID 1 die.
+
+ Pure, and public, so the self-test can assert the one property that
+ matters and cannot be read off a passing live run: **none of these is
+ ``docker kill``**. Each rung delivers SIGKILL to the same process; they
+ differ only in the privilege the host makes available.
+
+ ``host_pid_is_ours`` gates the two rungs that signal a bare pid. On a
+ Docker Desktop host the daemon reports a pid from inside its VM, which on
+ the host is either absent or -- the reason this gate exists -- some
+ unrelated local process. Signalling it would kill a bystander on a
+ developer's laptop, so the bare-pid rungs are offered only when ``/proc``
+ confirms that pid belongs to this container, and the ``--pid=host``
+ container handles every other host.
+ """
+ rungs: list[tuple[str, list[str]]] = []
+ if host_pid_is_ours:
+ # Already privileged: root in a CI container, or a rootless daemon.
+ rungs.append(("direct kill", ["kill", "-9", pid]))
+ # The GitHub runner shape: an unprivileged job user with passwordless sudo.
+ rungs.append(("sudo kill", ["sudo", "-n", "kill", "-9", pid]))
+ # Works wherever a Docker daemon does, including Docker Desktop. Uses the
+ # victim's own image so nothing has to be pulled while the stream is in
+ # flight.
+ rungs.append(
+ (
+ "privileged --pid=host container",
+ ["docker", "run", "--rm", "--privileged", "--pid=host", "--entrypoint", "sh", image, "-c", f"kill -9 {pid}"],
+ )
+ )
+ return rungs
+
+
+def host_pid_is_container(container: str, pid: str) -> bool:
+ """Whether host pid *pid* really is this container's own process.
+
+ ``/proc`` is the only authority that can answer, and the question has to
+ be asked before any bare ``kill``: a pid number that is valid inside a
+ Docker Desktop VM is meaningless on the macOS host and may well name
+ something else. No ``/proc``, no match, no bare kill.
+ """
+ full_id = _inspect(container, "{{.Id}}")
+ if not full_id:
+ return False
+ try:
+ cgroup = Path(f"/proc/{pid}/cgroup").read_text(encoding="utf-8")
+ except OSError:
+ return False
+ # Both cgroup drivers put the container id in the path:
+ # systemd `…/docker-<id>.scope`, cgroupfs `/docker/<id>`.
+ return full_id in cgroup or full_id[:12] in cgroup
+
+
+def _compose_crash(victim: str) -> tuple[bool, str]:
+ """Make the container's main process die the way a crash kills it.
+
+ ``docker kill`` is not a crash, and the difference is the whole of the
+ "1650 of 3000 events lost" measurement this harness used to produce.
+ The daemon records a killed container as *manually stopped*, and
+ ``restartmanager.ShouldRestart`` then declines to restart it. Measured on
+ Docker 29.5.2, 60 s after the signal:
+
+ =========================================== ==========================
+ action result
+ =========================================== ==========================
+ ``docker kill -s KILL``, ``unless-stopped`` ``running=false``, ``restartCount=0``
+ ``docker kill -s KILL``, ``always`` ``running=false``, ``restartCount=0``
+ SIGKILL of the main process, host PID ns ``running=true``, ``restartCount=1`` (~4 s)
+ =========================================== ==========================
+
+ So ``restart: unless-stopped`` in ``docker-compose.yml`` was never the
+ problem -- ``always`` behaves identically -- and fusion staying dead was
+ the harness asking the daemon for an administrative stop and then
+ reporting the absence of a consumer as event loss. Under Kubernetes the
+ equivalent is genuine: ``kubectl delete pod --force`` is replaced by the
+ Deployment controller, so only the compose leg was wrong.
+
+ Signalling the container's PID 1 from the *host* namespace is the shape a
+ real crash has: the daemon sees an unexpected exit 137 it did not ask
+ for, and applies the restart policy. That also makes the policy itself
+ part of what is graded, which nothing else in CI checks.
+
+ ``docker exec <c> kill -9 1`` is not an alternative: PID 1 is
+ signal-protected inside its own PID namespace and survives (measured).
+
+ The three rungs exist because the privilege needed differs by host, not
+ because any of them is a weaker test -- they all deliver the same signal
+ to the same process. If none of them lands the caller is told, and the
+ run is refused rather than silently falling back to ``docker kill``,
+ which is the fallback that produced a number nobody could interpret.
+ """
+ pid = _inspect(victim, "{{.State.Pid}}")
+ if not pid or pid == "0":
+ return False, f"could not read a host PID for {victim}: docker reported {pid!r}"
+ image = _inspect(victim, "{{.Config.Image}}") or "busybox:1.36"
+ restarts_before = int(_inspect(victim, "{{.RestartCount}}") or 0)
+
+ attempted: list[str] = []
+ for label, argv in crash_rungs(pid, image, host_pid_is_ours=host_pid_is_container(victim, pid)):
+ done = subprocess.run(argv, capture_output=True, text=True, timeout=120, check=False) # noqa: S603
+ detail = (done.stderr or done.stdout or "").strip()[:160]
+ attempted.append(f"{label}: rc={done.returncode} {detail}".strip())
+ # The exit code of `kill` is not the measurement -- whether the
+ # process died is. Watch the daemon's own view instead: either the
+ # container is down, or the restart policy has already replaced it.
+ deadline = time.time() + 20
+ while time.time() < deadline:
+ running = _inspect(victim, "{{.State.Running}}")
+ restarts = int(_inspect(victim, "{{.RestartCount}}") or restarts_before)
+ if running == "false" or restarts > restarts_before:
+ return True, f"{label} (restartCount {restarts_before} -> {restarts})"
+ time.sleep(0.5)
+
+ return False, (
+ f"the main process of {victim} (host pid {pid}) could not be signalled. "
+ "Refusing to fall back to `docker kill`, which the daemon treats as an administrative "
+ "stop and never restarts, so the run would measure a missing consumer as event loss. "
+ "Tried -- " + "; ".join(attempted)
+ )
+
+
def kill_fusion(target: Target, namespace: str, victim: str) -> tuple[bool, str]:
"""Destroy the replica without letting it shut down cleanly.
- ``--grace-period=0 --force`` and ``docker kill -s KILL`` are both
+ ``--grace-period=0 --force`` and the host-namespace SIGKILL are both
deliberate: a graceful stop runs fusion's ``stop()``, which stops the
consumer in an orderly way and would test the shutdown path rather than
the crash path. The failure worth proving survivable is the one where the
process never gets to run any code at all.
"""
- if target.name == "kubernetes":
- argv = ["kubectl", "-n", namespace, "delete", "pod", victim, "--grace-period=0", "--force", "--wait=false"]
- else:
- argv = ["docker", "kill", "-s", "KILL", victim]
+ if target.name != "kubernetes":
+ return _compose_crash(victim)
+ argv = ["kubectl", "-n", namespace, "delete", "pod", victim, "--grace-period=0", "--force", "--wait=false"]
done = subprocess.run(argv, capture_output=True, text=True, check=False) # noqa: S603
return done.returncode == 0, (done.stderr or done.stdout).strip()[:300]
@@ -249,7 +389,17 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument("--postgres-ref", default="statefulset/postgres")
parser.add_argument("--kafka-ref", default="statefulset/aisoc-kafka")
parser.add_argument("--producer-bin", default=os.environ.get("AISOC_PRODUCER_BIN", ""))
- parser.add_argument("--drain-timeout", type=int, default=420)
+ parser.add_argument("--drain-timeout", type=int, default=_DEFAULT_DRAIN_TIMEOUT_SECONDS)
+ parser.add_argument(
+ "--drain-stall-seconds",
+ type=float,
+ default=_DEFAULT_DRAIN_STALL_SECONDS,
+ help=(
+ "how long the alert count may stand still before the drain is called finished. "
+ "Must exceed the time a replacement consumer takes to be evicted from its group, "
+ "restart and get an assignment, or the stopping rule fires before recovery can show"
+ ),
+ )
parser.add_argument("--restart-timeout", type=int, default=180)
parser.add_argument("--out", type=Path)
args = parser.parse_args(argv)
@@ -369,19 +519,53 @@ def main(argv: list[str] | None = None) -> int:
summary = json.loads(summary_path.read_text(encoding="utf-8"))
accepted = int(summary["accepted_events"])
+ # Wait for the replacement BEFORE grading, not after.
+ #
+ # This ran last, which meant the loss figure was computed over a window
+ # in which nothing was consuming by construction: the drain stopped
+ # ~20 s after the last row and the replacement was polled for afterwards,
+ # so even a replica that came back in 30 s and caught up in a minute
+ # would have been published as total loss. The measurement has to begin
+ # once there is something to measure.
+ replacement_started = time.time()
+ after = wait_for_replacement(
+ target,
+ args.namespace,
+ victim=victim,
+ replicas_before=before,
+ timeout_seconds=args.restart_timeout,
+ )
+ if _is_compose(args.target):
+ replaced = bool(after) and len(after) >= len(before)
+ else:
+ replaced = victim not in after and len(after) >= len(before)
+ replacement_seconds = round(time.time() - replacement_started, 1)
+ print(
+ f"chaos: replacement {'observed' if replaced else 'NOT observed'} after {replacement_seconds}s "
+ f"(replicas now: {', '.join(after) or 'none'})"
+ )
+
drain_started = time.time()
- stable_reads = 0
last = -1
+ last_progress = time.time()
while time.time() - drain_started < args.drain_timeout:
count = count_marked(target, run_id)
if count >= accepted:
break
- # Three identical reads is the stopping rule when rows are still
- # missing: one could be the gap between two batches.
- stable_reads = stable_reads + 1 if count == last else 0
- if stable_reads >= 3:
+ if count != last:
+ last = count
+ last_progress = time.time()
+ # A stall window, not a read count. The old rule -- three identical
+ # reads five seconds apart -- gave up ~20 s after the last row, which
+ # is shorter than a hard-killed consumer takes to be evicted from its
+ # group and replaced (the coordinator alone waits out
+ # `session.timeout.ms`). A stopping rule shorter than the recovery it
+ # is watching for cannot tell "lost" from "not finished yet".
+ #
+ # This is a stopping rule, not a threshold: `--drain-timeout` is
+ # unchanged, so rows that genuinely never arrive still fail.
+ if time.time() - last_progress >= args.drain_stall_seconds:
break
- last = count
time.sleep(5)
seq_counts: dict[int, int] = {}
@@ -389,18 +573,6 @@ def main(argv: list[str] | None = None) -> int:
seq_counts[row.seq] = seq_counts.get(row.seq, 0) + 1
verdict = grade(accepted, seq_counts)
- after = wait_for_replacement(
- target,
- args.namespace,
- victim=victim,
- replicas_before=before,
- timeout_seconds=args.restart_timeout,
- )
- if _is_compose(args.target):
- replaced = bool(after) and len(after) >= len(before)
- else:
- replaced = victim not in after and len(after) >= len(before)
-
report = {
"schema": "aisoc.chaos_fusion_restart/v1",
"measured_at": datetime.now(UTC).isoformat(timespec="seconds"),
@@ -412,6 +584,7 @@ def main(argv: list[str] | None = None) -> int:
"replica_replaced": replaced,
"killed_at_offset_seconds": round(killed_at - started, 1),
"alerts_stored_when_killed": in_flight,
+ "replacement_seconds": replacement_seconds,
"drain_seconds": round(time.time() - drain_started, 1),
**verdict.as_dict(),
}
@@ -420,15 +593,25 @@ def main(argv: list[str] | None = None) -> int:
args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
print(json.dumps(report, indent=2))
- if not verdict.ok:
+ # Replacement is reported first when it failed, because it is the fact
+ # that makes the other number meaningless. A run with no consumer loses
+ # everything that arrives after the kill *by construction*, so leading
+ # with the loss count invites a reader to diagnose the durability path
+ # for a defect that is not there -- which is exactly what happened to
+ # "1650 of 3000 events lost" before the kill primitive was fixed.
+ if not replaced:
print(
- f"\nFAIL: {len(verdict.missing)} event(s) produced no alert and {len(verdict.duplicated)} produced more than one.",
+ f"\nFAIL: the killed replica was not replaced within {args.restart_timeout}s "
+ f"({len(verdict.missing)} event(s) also produced no alert, which this explains: with no "
+ "consumer, every event accepted after the kill is lost by construction and the figure "
+ "says nothing about durability).",
file=sys.stderr,
)
return 1
- if not replaced:
+ if not verdict.ok:
print(
- "\nFAIL: the killed replica was not replaced, so the run survived by running at reduced capacity rather than by recovering.",
+ f"\nFAIL: {len(verdict.missing)} event(s) produced no alert and {len(verdict.duplicated)} produced more than one, "
+ f"across a replacement that was back in {replacement_seconds}s.",
file=sys.stderr,
)
return 1
@@ -477,6 +660,36 @@ def _self_test() -> int:
"the compose branch is chosen for the adapter's target name, not the CLI's spelling",
_is_compose(compose_name) and not _is_compose("kubernetes"),
),
+ (
+ "no crash rung is `docker kill` — the daemon treats that as an administrative stop and never restarts",
+ all(
+ argv[:2] != ["docker", "kill"]
+ for _label, argv in crash_rungs("4242", "ghcr.io/beenuar/aisoc-fusion:latest", host_pid_is_ours=True)
+ ),
+ ),
+ (
+ "every crash rung delivers SIGKILL to the pid it was handed",
+ all("4242" in " ".join(argv) and "-9" in " ".join(argv) for _label, argv in crash_rungs("4242", "img", host_pid_is_ours=True)),
+ ),
+ (
+ "a pid that /proc cannot attribute to the container is never signalled directly — it may be a bystander",
+ [label for label, _argv in crash_rungs("4242", "img", host_pid_is_ours=False)] == ["privileged --pid=host container"],
+ ),
+ (
+ "the --pid=host rung reuses the victim's own image, so nothing is pulled mid-stream",
+ any(
+ "ghcr.io/beenuar/aisoc-fusion:latest" in argv
+ for _label, argv in crash_rungs("1", "ghcr.io/beenuar/aisoc-fusion:latest", host_pid_is_ours=False)
+ ),
+ ),
+ (
+ "the drain stall window is long enough to outlast a consumer-group rejoin and short enough to fire inside the drain budget",
+ # Asserted as a relation rather than a value: the numbers may move,
+ # but a stall rule shorter than a Kafka session timeout cannot tell
+ # "lost" from "not finished yet", and one longer than the drain
+ # budget can never fire at all.
+ 30.0 < _DEFAULT_DRAIN_STALL_SECONDS < _DEFAULT_DRAIN_TIMEOUT_SECONDS,
+ ),
]
ok = True
for description, passed in checks:
diff --git a/scripts/chaos/store_outage.py b/scripts/chaos/store_outage.py
index c9b188d6a..54ed6c686 100644
--- a/scripts/chaos/store_outage.py
+++ b/scripts/chaos/store_outage.py
@@ -151,6 +151,9 @@ class OutageResult:
behaviour: str
expected: str
readiness_reported: bool = False
+ #: The status line the owning readiness surface answered during the
+ #: outage. ``None`` means it answered nothing at all.
+ readiness_status: int | None = None
dependents_up: tuple[str, ...] = ()
dependents_down: tuple[str, ...] = ()
recovered: bool = False
@@ -167,6 +170,7 @@ class OutageResult:
"expected": self.expected,
"observed": self.behaviour,
"readiness_reported": self.readiness_reported,
+ "readiness_status": self.readiness_status,
"dependents_up": list(self.dependents_up),
"dependents_down": list(self.dependents_down),
"recovered": self.recovered,
@@ -180,18 +184,25 @@ def grade_outage(
expectation: StoreExpectation,
*,
readiness: dict[str, Any],
+ readiness_status: int | None,
dependents_responding: dict[str, bool],
recovered: bool,
+ recovery_observable: bool = True,
recovery_seconds: float | None = None,
) -> OutageResult:
"""Grade one outage against what the store's loss is supposed to look like.
Pure, so the self-test can drive every branch without containers.
+
+ ``readiness_status`` is the status line the owning readiness surface
+ answered while the store was down, or ``None`` if it answered nothing at
+ all. It is graded rather than discarded: see :meth:`_grade_status_line`.
"""
result = OutageResult(
store=expectation.store,
behaviour=expectation.behaviour,
expected=expectation.behaviour,
+ readiness_status=readiness_status,
recovered=recovered,
recovery_seconds=recovery_seconds,
)
@@ -203,13 +214,24 @@ def grade_outage(
# from a healthy idle one.
reported = readiness.get(expectation.readiness_key)
result.readiness_reported = reported is False or reported == "down" or reported == "degraded"
- if not result.readiness_reported:
+ if readiness_status is None:
+ # Distinct from "answered without the key", and the distinction is
+ # the operator's first question: a refusal with a reason and an
+ # unreachable socket look identical in a body-only reading.
+ result.findings.append(
+ f"{expectation.store} is down and the readiness surface answered nothing at all — "
+ "no status line and no body, so a service that is refusing with a reason cannot be "
+ "told apart from one that is gone"
+ )
+ elif not result.readiness_reported:
result.findings.append(
f"{expectation.store} is down and readiness does not say so "
f"(`{expectation.readiness_key}` reads {reported!r}) — an operator cannot tell this "
"apart from a healthy idle service"
)
+ _grade_status_line(expectation, result, readiness_status)
+
if expectation.behaviour == "block":
if result.dependents_up:
result.findings.append(
@@ -222,13 +244,59 @@ def grade_outage(
f"{expectation.store} is down and {', '.join(result.dependents_down)} stopped serving; {expectation.why}"
)
- if not recovered:
+ if not recovery_observable:
+ # Separated from "did not recover" because they are different facts
+ # and only one of them is about the product. An endpoint that never
+ # mentions the key cannot be used to watch a reconnection, and the
+ # grader used to score exactly that silence as recovery in 0.0s --
+ # `probe.get(key)` returned None, `None not in (False, "down",
+ # "degraded")` was true, and three legs reported a recovery nobody
+ # had observed. An unknown must never be a pass.
+ result.findings.append(
+ f"{expectation.store} came back and readiness never reported `{expectation.readiness_key}` "
+ "at any point, so reconnection could not be observed — a recovery nobody can see is not "
+ "a recovery an operator can rely on"
+ )
+ elif not recovered:
result.findings.append(
f"{expectation.store} came back and the dependents did not reconnect — an outage plus a manual restart is worse than an outage"
)
return result
+def _grade_status_line(expectation: StoreExpectation, result: OutageResult, status: int | None) -> None:
+ """Require the status code the behaviour implies, rather than tolerating it.
+
+ The body said whether the store was named; the status line says whether
+ the service asked to be taken out of rotation, and the two are separate
+ claims. Grading only the body let a ``block`` store's owner answer ``200``
+ beside ``"database": false`` and still pass the readiness half — which is
+ the load balancer continuing to send work to a service that cannot do it.
+
+ * ``block``: readiness MUST fail. The orchestrator is the thing that acts
+ on this, and it reads the status code, not the JSON.
+ * ``degrade`` / ``refuse``: readiness MUST stay 2xx. Failing readiness
+ over a store whose loss the service is supposed to survive pulls a
+ working service out of the load balancer to fix a feature.
+ """
+ if status is None:
+ return # already reported, above, as "answered nothing at all"
+ ok = 200 <= status < 300
+ if expectation.behaviour == "block":
+ if ok:
+ result.findings.append(
+ f"{expectation.store} is down and readiness still answered {status}; a blocking "
+ "outage must fail readiness, because the orchestrator acts on the status line and "
+ "never on the body"
+ )
+ elif not ok:
+ result.findings.append(
+ f"{expectation.store} is down and readiness answered {status}; losing "
+ f"{expectation.store} is a {expectation.behaviour}, so refusing readiness over it takes "
+ "a service that can still do its job out of the load balancer"
+ )
+
+
def _resolve_container(service: str) -> str | None:
"""The container id for a compose service, or ``None`` if it is not up.
@@ -298,16 +366,26 @@ def _container_action(container: str, action: str) -> bool:
_ALLOWED_PROBE_PREFIXES = ("http://127.0.0.1:", "http://localhost:", "https://127.0.0.1:")
-def _probe(url: str, timeout: float = 4.0) -> dict[str, Any] | None:
- """Read a readiness body, *including* from an HTTP error response.
+def _probe(url: str, timeout: float = 4.0) -> tuple[int | None, dict[str, Any] | None]:
+ """Read a readiness answer: the status line *and* the body.
- A block-store dependency failing readiness with a 503 **and a JSON body
- naming why** is exactly the correct behaviour — the API answers 503 with
+ Both halves are graded, so both are returned. The status line is what an
+ orchestrator acts on; the body is what an operator reads. A grader that
+ keeps only one of them can score a service that answers ``200`` beside
+ ``{"database": false}`` as correct, which is the load balancer being told
+ to keep sending work to something that cannot do it.
+
+ The body is read *including* from an HTTP error response. A block-store
+ owner failing readiness with a 503 **and a JSON body naming why** is
+ exactly the correct behaviour — the API answers 503 with
``{"database": false, ...}`` while Postgres is down. ``urlopen`` raises on
any 4xx/5xx, so without reading ``HTTPError``'s body the grader scored
- that correct behaviour as silence ("``database`` reads None"). Connection
- refused, timeouts and non-JSON bodies still read as ``None``: those are
- genuinely "nothing was said".
+ that correct behaviour as silence ("``database`` reads None").
+
+ ``(None, None)`` means nothing answered: connection refused, a timeout, or
+ a reply that is not JSON. That is genuinely "nothing was said", and it is
+ reported as its own finding rather than folded into "did not mention the
+ key" — a refusal with a reason and a dead socket are different facts.
"""
if not url.startswith(_ALLOWED_PROBE_PREFIXES):
raise ValueError(
@@ -316,14 +394,24 @@ def _probe(url: str, timeout: float = 4.0) -> dict[str, Any] | None:
)
try:
with urllib.request.urlopen(url, timeout=timeout) as response: # noqa: S310 - prefix-checked above
- return dict(json.loads(response.read().decode("utf-8")))
+ return response.status, dict(json.loads(response.read().decode("utf-8")))
except urllib.error.HTTPError as err:
try:
- return dict(json.loads(err.read().decode("utf-8")))
+ return err.code, dict(json.loads(err.read().decode("utf-8")))
except (ValueError, OSError):
- return None
+ # A status line with an unreadable body is still an answer, and
+ # saying so is more useful than reporting silence.
+ return err.code, None
except (urllib.error.URLError, TimeoutError, ValueError, OSError):
- return None
+ return None, None
+
+
+#: What a readiness key reads when the store behind it is back. Every key this
+#: harness grades (`database`, `cache`, `kafka`, `graph`, `lake_writer`,
+#: `vector_store`) is a boolean; the string spellings are accepted so a service
+#: that reports a tri-state does not read as permanently broken. A key that is
+#: *absent* is deliberately not in this set -- see `recovery_observable`.
+_RECOVERED_VALUES: frozenset[Any] = frozenset({True, "up", "ok", "ready", "healthy"})
def _responding(url: str, timeout: float = 4.0) -> bool:
@@ -357,10 +445,11 @@ def _self_test() -> int:
cases = [
(
- "degrade: readiness admits it and dependents keep serving",
+ "degrade: readiness admits it, stays 200, and dependents keep serving",
grade_outage(
clickhouse,
readiness={"lake_writer": False},
+ readiness_status=200,
dependents_responding={"fusion": True, "api": True},
recovered=True,
),
@@ -371,6 +460,7 @@ def _self_test() -> int:
grade_outage(
clickhouse,
readiness={"lake_writer": True},
+ readiness_status=200,
dependents_responding={"fusion": True, "api": True},
recovered=True,
),
@@ -381,41 +471,90 @@ def _self_test() -> int:
grade_outage(
clickhouse,
readiness={"lake_writer": False},
+ readiness_status=200,
dependents_responding={"fusion": False, "api": True},
recovered=True,
),
False,
),
(
- "block: dependents correctly drop out of the load balancer",
+ "degrade: readiness refused with 503 over a store the service survives",
+ grade_outage(
+ clickhouse,
+ readiness={"lake_writer": False},
+ readiness_status=503,
+ dependents_responding={"fusion": True, "api": True},
+ recovered=True,
+ ),
+ False,
+ ),
+ (
+ "block: readiness fails with 503 and dependents drop out of the load balancer",
grade_outage(
kafka,
readiness={"kafka": False},
+ readiness_status=503,
dependents_responding={"ingest": False, "fusion": False},
recovered=True,
),
True,
),
+ (
+ "block: the key is named but readiness still answers 200 — the orchestrator reads the status line",
+ grade_outage(
+ kafka,
+ readiness={"kafka": False},
+ readiness_status=200,
+ dependents_responding={"ingest": False, "fusion": False},
+ recovered=True,
+ ),
+ False,
+ ),
(
"block: ingest still ready without the spine it writes to",
grade_outage(
kafka,
readiness={"kafka": False},
+ readiness_status=503,
dependents_responding={"ingest": True, "fusion": False},
recovered=True,
),
False,
),
+ (
+ "readiness answered nothing at all — not the same fact as answering without the key",
+ grade_outage(
+ kafka,
+ readiness={},
+ readiness_status=None,
+ dependents_responding={"ingest": False, "fusion": False},
+ recovered=True,
+ ),
+ False,
+ ),
(
"recovery: degraded correctly and never reconnected",
grade_outage(
clickhouse,
readiness={"lake_writer": False},
+ readiness_status=200,
dependents_responding={"fusion": True, "api": True},
recovered=False,
),
False,
),
+ (
+ "recovery: the key was never reported, so reconnection was unobservable — an unknown is not a pass",
+ grade_outage(
+ clickhouse,
+ readiness={"lake_writer": False},
+ readiness_status=200,
+ dependents_responding={"fusion": True, "api": True},
+ recovered=False,
+ recovery_observable=False,
+ ),
+ False,
+ ),
]
failures = 0
@@ -427,6 +566,72 @@ def _self_test() -> int:
for finding in result.findings:
print(f" {finding}")
+ # Failing is not enough: a case that fails for the wrong reason proves
+ # nothing about the discrimination it was written to make. These pin the
+ # finding each new branch is supposed to produce.
+ named = [
+ (
+ "a block store answering 200 is reported as a status-line defect, not a body one",
+ "still answered 200",
+ grade_outage(
+ kafka,
+ readiness={"kafka": False},
+ readiness_status=200,
+ dependents_responding={"ingest": False, "fusion": False},
+ recovered=True,
+ ),
+ ),
+ (
+ "a degrade store refusing readiness is reported as taking a working service out of rotation",
+ "out of the load balancer",
+ grade_outage(
+ clickhouse,
+ readiness={"lake_writer": False},
+ readiness_status=503,
+ dependents_responding={"fusion": True, "api": True},
+ recovered=True,
+ ),
+ ),
+ (
+ "an unobservable recovery is reported as unobservable, not as a failure to reconnect",
+ "could not be observed",
+ grade_outage(
+ clickhouse,
+ readiness={"lake_writer": False},
+ readiness_status=200,
+ dependents_responding={"fusion": True, "api": True},
+ recovered=False,
+ recovery_observable=False,
+ ),
+ ),
+ (
+ "a silent readiness surface is reported as answering nothing, not as omitting a key",
+ "answered nothing at all",
+ grade_outage(
+ kafka,
+ readiness={},
+ readiness_status=None,
+ dependents_responding={"ingest": False, "fusion": False},
+ recovered=True,
+ ),
+ ),
+ ]
+ for name, fragment, result in named:
+ ok = any(fragment in finding for finding in result.findings)
+ print(f" self-test [{'ok' if ok else 'FAIL'}] {name}")
+ if not ok:
+ failures += 1
+ for finding in result.findings:
+ print(f" {finding}")
+
+ # The unobservable case must NOT also claim the dependents failed to
+ # reconnect: two findings for one fact is how a report stops being read.
+ unobservable = named[2][2]
+ exclusive = not any("did not reconnect" in finding for finding in unobservable.findings)
+ print(f" self-test [{'ok' if exclusive else 'FAIL'}] an unobservable recovery is reported once, not twice")
+ if not exclusive:
+ failures += 1
+
# Every store must declare a behaviour the grader implements, or it
# silently grades nothing.
for store in STORES:
@@ -447,6 +652,8 @@ def _probe_self_test() -> int:
* ``_probe`` reads the JSON body of a **503** — a block store failing
readiness with a reason is correct behaviour, not silence.
+ * ``_probe`` returns the **status line** alongside it, because the
+ behaviour contract is graded on both halves.
* ``_responding`` refuses that same 503 — a dependent that is alive but
cannot do its job is not serving.
"""
@@ -477,12 +684,16 @@ def _probe_self_test() -> int:
failures = 0
try:
cases = [
- ("_probe reads a 200 body", _probe(f"{base}/ready-200") == {"status": "ready", "database": True}),
+ ("_probe reads a 200 body", _probe(f"{base}/ready-200") == (200, {"status": "ready", "database": True})),
(
"_probe reads the JSON body of a 503 (a refusal with a reason is not silence)",
- _probe(f"{base}/ready-503") == {"status": "not_ready", "database": False},
+ _probe(f"{base}/ready-503") == (503, {"status": "not_ready", "database": False}),
+ ),
+ (
+ "_probe keeps the status line of a non-JSON error body (an answer with an unreadable body is still an answer)",
+ _probe(f"{base}/ready-junk") == (503, None),
),
- ("_probe returns None for a non-JSON error body", _probe(f"{base}/ready-junk") is None),
+ ("_probe reports a dead socket as no answer at all", _probe("http://127.0.0.1:1/ready") == (None, None)),
("_responding accepts a 200", _responding(f"{base}/ready-200") is True),
("_responding refuses a 503 (alive but not doing its job is not serving)", _responding(f"{base}/ready-503") is False),
("_responding refuses a dead socket", _responding("http://127.0.0.1:1/ready") is False),
@@ -525,7 +736,8 @@ def main(argv: list[str] | None = None) -> int:
try:
time.sleep(args.settle_seconds)
- readiness = _probe(args.readiness_url) or {}
+ readiness_status, readiness_body = _probe(args.readiness_url)
+ readiness = readiness_body or {}
responding: dict[str, bool] = {}
for pair in args.dependent_url:
name, _, url = pair.partition("=")
@@ -535,18 +747,27 @@ def main(argv: list[str] | None = None) -> int:
started = time.monotonic()
recovered = False
+ # Whether the readiness surface ever named the key at all during the
+ # recovery poll. An endpoint that never mentions it cannot be used to
+ # watch a reconnection, and scoring that silence as recovery is the
+ # defect this flag exists to make visible rather than to hide.
+ recovery_observable = expectation.readiness_key in readiness
while time.monotonic() - started < 120:
- probe = _probe(args.readiness_url)
- if probe and probe.get(expectation.readiness_key) not in (False, "down", "degraded"):
- recovered = True
- break
+ _status, probe = _probe(args.readiness_url)
+ if probe is not None and expectation.readiness_key in probe:
+ recovery_observable = True
+ if probe[expectation.readiness_key] in _RECOVERED_VALUES:
+ recovered = True
+ break
time.sleep(3)
result = grade_outage(
expectation,
readiness=readiness,
+ readiness_status=readiness_status,
dependents_responding=responding,
recovered=recovered,
+ recovery_observable=recovery_observable,
recovery_seconds=round(time.monotonic() - started, 1) if recovered else None,
)
print(json.dumps(result.as_dict(), indent=2))