Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
55 changes: 9 additions & 46 deletions docs/guides/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -352,54 +352,17 @@ container as unhealthy.
telemetry)`. For a 300 s interval and the default 5 s cooldown, that is
730 s, so `1800` leaves room.

### MQTT-based health check
### Checks to avoid

If you want the check to go through the broker, and `mosquitto_sub` is available in
the container, you can use it to verify the app's MQTT heartbeat:
Use the health file probe above. Two checks that look like alternatives report
healthy even when the app is not:

```yaml title="docker-compose.yml (health check snippet)"
services:
myapp:
# ...
healthcheck:
test: >-
mosquitto_sub
-h mosquitto
-t "myapp/status"
-C 1
-W 30
interval: 60s
timeout: 35s
retries: 3
start_period: 15s
```

This subscribes to the status topic, waits up to 30 seconds (`-W`) for a single
message (`-C 1`), and exits 0 if one is received. You'll need `mosquitto-clients`
installed in the runtime image:

```dockerfile
RUN apt-get update \
&& apt-get install -y --no-install-recommends mosquitto-clients \
&& rm -rf /var/lib/apt/lists/*
```

### Process-based fallback

If you'd rather not add `mosquitto-clients` to the image, a simple process check
works as a basic health signal:

```yaml title="docker-compose.yml (process health check)"
services:
myapp:
# ...
healthcheck:
test: ["CMD", "pgrep", "-f", "myapp"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
```
- **Subscribing to `{prefix}/status`**, for example with `mosquitto_sub -C 1`.
The heartbeat and the LWT are both retained, so the broker hands the
subscriber the last message at once, even when that message is `"offline"`.
The command exits `0` for as long as the broker is up.
- **Checking that the process exists**, for example with `pgrep`. A hung app is
still a running process.

!!! info "LWT handles crash detection automatically"

Expand Down
11 changes: 10 additions & 1 deletion docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,16 @@ probe. Neither one loads settings or connects to the broker.
The probe exits `0` and prints the file's age when the file is fresh and no
device has a failing status. It exits `1` and prints the reason on stderr when
the file is missing, unreadable or too old, or when a device has a failing
status. See [Health Checks](../guides/deployment.md#health-checks).
status. A usage error in the `health` arguments, such as `--max-age -1` or an
unknown option, also exits `1`, with `unhealthy: usage error: <message>` on
stderr, because Docker reserves exit code `2`. See
[Health Checks](../guides/deployment.md#health-checks).

!!! note "Errors before `health` still exit 2"

Options placed before the subcommand, as in `myapp --bogus health`, are
parsed by the app's own CLI rather than by `health`, so a usage error there
exits `2`. Put no options before `health` in a probe command.

## Registry Snapshot

Expand Down
4 changes: 2 additions & 2 deletions packages/src/cosalette/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
EXIT_TASK_FAILURE,
)
from cosalette._health._liveness import StaleTelemetryError
from cosalette._health._liveness_cli import health_command
from cosalette._health._liveness_cli import HealthCommand, health_command
from cosalette._mcp._introspect import format_asyncapi_table
from cosalette._schema._cli import schema_app
from cosalette._settings import LoggingSettings
Expand Down Expand Up @@ -187,7 +187,7 @@ def build_cli(app: App) -> typer.Typer:
cli.add_typer(schema_app, name="schema")

# -- health probe (ADR-083) ---------------------------------------------
cli.command("health")(health_command)
cli.command("health", cls=HealthCommand)(health_command)

# -- main command -------------------------------------------------------

Expand Down
20 changes: 19 additions & 1 deletion packages/src/cosalette/_health/_liveness_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@

import time
from pathlib import Path
from typing import Annotated
from typing import Annotated, Any, override

import typer
from typer.core import TyperCommand

from cosalette._health._liveness import (
DEFAULT_FAIL_ON,
Expand All @@ -20,6 +21,23 @@
"""Docker ``HEALTHCHECK`` only knows 0 and 1, and reserves 2."""


class HealthCommand(TyperCommand):
"""Report usage errors as unhealthy (1) instead of Click's usage exit (2).

Only covers the subcommand's own arguments: errors the parent group
parses before it reaches ``health`` still exit 2.
"""

@override
def make_context(self, *args: Any, **kwargs: Any) -> Any:
# Any: the base returns typer's vendored, non-public click Context.
try:
return super().make_context(*args, **kwargs)
except typer.TyperException as exc:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve successful health help exits

When a user runs cosalette health --help or <app> health --help, Typer raises its normal Exit(0) while building the context. Typer 0.27.2 explicitly makes all exception classes, including Exit, inherit TyperException (upstream change), so this handler intercepts the successful help exit and turns it into an exit-1 failure (and may attempt the unavailable format_message() on Exit). Re-raise typer.Exit unchanged or otherwise restrict this handler to actual usage errors.

Useful? React with 👍 / 👎.

typer.echo(f"unhealthy: usage error: {exc.format_message()}", err=True)
raise typer.Exit(EXIT_UNHEALTHY) from exc


def health_command(
file: Annotated[
Path | None,
Expand Down
4 changes: 2 additions & 2 deletions packages/src/cosalette/_package_cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import typer

from cosalette._health._liveness_cli import health_command
from cosalette._health._liveness_cli import HealthCommand, health_command
from cosalette._package_cli._ai_init import (
_check_instructions,
_copy_template_to_target,
Expand Down Expand Up @@ -57,7 +57,7 @@
app.add_typer(schema_app, name="schema")

# Container liveness probe for the opt-in health file (ADR-083)
app.command("health")(health_command)
app.command("health", cls=HealthCommand)(health_command)

# Create MCP command group (lazy — only imports fastmcp when invoked)
mcp_app = typer.Typer(help="MCP server commands")
Expand Down
29 changes: 28 additions & 1 deletion packages/tests/unit/health/test_liveness.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
time at and just under exit_after_stale; invalid exit_after_stale
- Decision Table Testing: device status x --fail-on set
- State Transition Testing: write failure warns once, then DEBUG
- Error Guessing: leftover temporary files, unset environment variable
- Error Guessing: leftover temporary files, unset environment variable,
probe usage errors (Click would exit 2)
- Specification-based Testing: exit-code mapping in both CLIs
- Mock-based Isolation: MockMqttClient, FakeClock and ManualClock
"""
Expand Down Expand Up @@ -357,6 +358,32 @@ def test_too_old_exits_one(self, cli: Any, tmp_path: Path) -> None:
assert result.exit_code == 1
assert "old" in result.output

@pytest.mark.parametrize(
"args",
[
pytest.param(["--max-age", "-1"], id="negative-max-age"),
pytest.param(["--max-age", "abc"], id="non-numeric-max-age"),
pytest.param(["--bogus"], id="unknown-option"),
],
)
def test_usage_error_exits_one(
self, cli: Any, tmp_path: Path, args: list[str]
) -> None:
"""Usage errors exit 1, not Click's 2, which Docker reserves.

Technique: Equivalence Partitioning — out-of-range value, wrong
type and unknown option all take Click's usage-error path.
"""
# Arrange
argv = ["health", "--file", str(tmp_path / "h.json"), *args]

# Act
result = CliRunner().invoke(cli, argv)

# Assert
assert result.exit_code == 1
assert result.stderr.startswith("unhealthy: usage error: ")


class TestAppCallbackSkipsSubcommands:
"""A subcommand runs instead of the app (ADR-083)."""
Expand Down
Loading