diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f16e50..e23c65a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -165,6 +165,24 @@ Both mirrors run the command through one implementation, so it does not depend o event loop being able to spawn processes — a hook that works in production works on a developer's machine too. +### Monitoring, for free + +`--output metrics` renders any command as Prometheus text exposition for a node_exporter +textfile collector. Most systems that partition PostgreSQL have no monitoring of it at all +— they find out at 03:00, from an insert PostgreSQL rejected — and a CronJob already runs +this on a schedule, so the cheapest monitoring available is for that run to leave a file +behind. + +`plan` emits pending operations by kind and findings by severity, `inspect` the size of the +tree and the age of the oldest orphan, `validate` whether each table still matches its +configuration, and `apply` what it did and what it could not. Every run also stamps +`pg_partsmith_run_timestamp_seconds`, so a textfile nothing refreshed reads as stale rather +than as good news, and a converged table reports zeroes rather than nothing — a missing +series and a zero are different alerts. + +The numbers come off the same envelope the JSON does, so a metric cannot disagree with what +the same run printed. + ### A container image `ghcr.io/bedrock-python/pg-partsmith:`, published from the release workflow, so a diff --git a/docs/agents.md b/docs/agents.md index 043b50b..fe435e5 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -62,7 +62,8 @@ A configuration is a **scheme** — the shape of the tree, level by level — an configuration that has since changed (`--allow-config-drift` overrides). Exit codes: 0 nothing pending, 2 drift under `plan --check`, 3 findings or run issues, 4 configuration, 5 connection, 6 lock held, 1 unexpected. `--output json` is the model dump under a - versioned envelope. See `guide/cli.md`. + versioned envelope; `--output metrics` is Prometheus text exposition for a node_exporter + textfile, all gauges, prefixed `pg_partsmith_`. See `guide/cli.md`. * `CommandHooks` (both mirrors) runs a configured command per phase with the `PartitionEvent` as JSON on stdin; a non-zero exit refuses the operation. In a document it is the `hooks` section, honoured only under `apply --allow-hooks`. Hooks never fire diff --git a/docs/guide/cli.md b/docs/guide/cli.md index dd5d933..7ea1e35 100644 --- a/docs/guide/cli.md +++ b/docs/guide/cli.md @@ -102,6 +102,53 @@ versioned envelope, in the vocabulary a configuration file is written in: It is the dump, never a shape assembled by the CLI — a hand-rolled one drifts from the library the first time a field is added. Logs go to stderr, so stdout stays parseable. +## Monitoring, for free + +`--output metrics` renders the same run as Prometheus text exposition, for a node_exporter +textfile collector: + +```bash +pg-partsmith plan -c partitions.yaml --output metrics > /var/lib/node_exporter/textfile/partsmith.prom +``` + +``` +# HELP pg_partsmith_pending_operations Operations a maintenance run would carry out. +# TYPE pg_partsmith_pending_operations gauge +pg_partsmith_pending_operations{table="public.events",kind="create"} 2 +pg_partsmith_pending_operations{table="public.events",kind="drop"} 0 +# HELP pg_partsmith_findings What the planner saw and left alone. A warning needs a person. +# TYPE pg_partsmith_findings gauge +pg_partsmith_findings{table="public.events",severity="warning"} 0 +``` + +Every command emits something: + +| Command | Series | +|---|---| +| `plan` | `pending_operations{table,kind}`, `pending_relations{table}`, `findings{table,severity}` | +| `inspect` | `partitioned{table}`, `partitions{table}`, `detached_partitions{table}`, `oldest_detached_age_seconds{table}` | +| `validate` | `config_valid{table}` | +| `apply` | `applied_operations{table,operation}`, `issues{table}` | + +All prefixed `pg_partsmith_`, all gauges — a one-shot job cannot own a counter, since the +next run is a new process with no memory of this one. Every run also emits +`pg_partsmith_run_timestamp_seconds{command}`, so a textfile nothing has refreshed is +visible as stale rather than as good news. + +A converged table reports zeroes rather than nothing: a missing series and a zero are +different alerts. + +The numbers are read off the same envelope the JSON is, so a metric cannot disagree with +what the same run printed. + +Three alerts worth having, in the order they will save you: + +- `pg_partsmith_pending_operations` above zero for longer than your schedule — maintenance + has stopped running, and inserts will start being rejected. +- `pg_partsmith_findings{severity="warning"}` above zero — something needs a person. +- `time() - pg_partsmith_run_timestamp_seconds` above a couple of intervals — the job + itself is not running, which no other metric here can tell you. + ## One table at a time `--table events` (or `--table public.events`), repeatable. A name that no table in the diff --git a/docs/guide/container.md b/docs/guide/container.md index 740fd13..b1e263d 100644 --- a/docs/guide/container.md +++ b/docs/guide/container.md @@ -125,6 +125,18 @@ a `python:3.13-slim` base plus the venv: pydantic, SQLAlchemy, python-dateutil, and PyYAML, with pip, the build backend and every `__pycache__` left behind in the discarded build stage. +## Monitoring + +`--output metrics` writes Prometheus text exposition, which in a CronJob means mounting a +node_exporter textfile directory and redirecting into it: + +```yaml +args: ["plan", "-c", "/etc/partitions.yaml", "--check", "--output", "metrics"] +``` + +See [the CLI page](cli.md#monitoring-for-free) for the series and the alerts worth +building on them. + ## Exit codes The same ones [the CLI](cli.md#exit-codes) documents. `0` nothing pending, `2` drift under diff --git a/pg_partsmith/cli/commands.py b/pg_partsmith/cli/commands.py index 4dd73dc..e447e5d 100644 --- a/pg_partsmith/cli/commands.py +++ b/pg_partsmith/cli/commands.py @@ -18,6 +18,7 @@ from .exit_codes import ExitCode from .loader import ConfigError +from .metrics import render_metrics from .render import describe_tree, envelope, plan_entry, to_json, tree_entry if TYPE_CHECKING: @@ -44,10 +45,17 @@ class CommandResult: lines: list[str] = field(default_factory=list) payload: dict[str, Any] | None = None - def render(self, *, as_json: bool) -> str: - """The text to print, in the form that was asked for.""" - if as_json and self.payload is not None: - return to_json(self.payload) + def render(self, *, output: str = "human") -> str: + """The text to print, in the form that was asked for. + + The JSON and the metrics are read off the same envelope, so a number in + one cannot disagree with a number in the other. + """ + if self.payload is not None: + if output == "json": + return to_json(self.payload) + if output == "metrics": + return render_metrics(self.payload).rstrip("\n") return "\n\n".join(self.lines) diff --git a/pg_partsmith/cli/main.py b/pg_partsmith/cli/main.py index 3b3f4b5..ada4f98 100644 --- a/pg_partsmith/cli/main.py +++ b/pg_partsmith/cli/main.py @@ -120,7 +120,7 @@ def main(argv: Sequence[str] | None = None) -> int: except KeyboardInterrupt: # pragma: no cover - interactive only return _failed("interrupted", ExitCode.FAILED) - text = result.render(as_json=args.output == "json") + text = result.render(output=args.output) if text: sys.stdout.write(text + "\n") return result.code @@ -256,6 +256,10 @@ def _add_common_arguments(parser: argparse.ArgumentParser) -> None: help="only this table, qualified or bare; repeatable (default: every table in the document)", ) parser.add_argument( - "-o", "--output", choices=("human", "json"), default="human", help="output format (default: human)" + "-o", + "--output", + choices=("human", "json", "metrics"), + default="human", + help="output format: human, json, or Prometheus text for a node_exporter textfile (default: human)", ) parser.add_argument("-v", "--verbose", action="store_true", help="log what it is doing, to stderr") diff --git a/pg_partsmith/cli/metrics.py b/pg_partsmith/cli/metrics.py new file mode 100644 index 0000000..8ad05ab --- /dev/null +++ b/pg_partsmith/cli/metrics.py @@ -0,0 +1,221 @@ +"""The same run, as numbers a Prometheus node_exporter can pick up. + +Most systems that partition PostgreSQL have no monitoring of it at all -- they +find out at 03:00, from an insert that PostgreSQL rejected. A CronJob already +runs this tool on a schedule, so the cheapest possible monitoring is for that +run to leave a textfile behind: + + pg-partsmith plan -c partitions.yaml --output metrics > /var/lib/node_exporter/partsmith.prom + +Every command can do it. The numbers are read off the JSON envelope rather than +collected separately, so a metric cannot disagree with what the same run +printed. + +The format is the text exposition one: ``HELP``, ``TYPE``, then samples. Every +value is a gauge, because a one-shot job cannot own a counter -- the next run is +a new process with no memory of this one. +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Sequence +from datetime import UTC, datetime +from typing import Any + +__all__ = ["render_metrics"] + +_PREFIX = "pg_partsmith" + + +def render_metrics(payload: dict[str, Any]) -> str: + """Render one command's envelope as Prometheus text exposition. + + Args: + payload: The envelope the command built. + + Returns: + The metrics, ending in a newline, ready to write to a textfile + collector's directory. + """ + command = str(payload.get("command", "unknown")) + lines: list[str] = [] + _emit( + lines, + f"{_PREFIX}_run_timestamp_seconds", + "When this run happened, so a stale textfile is visible as one.", + [({"command": command}, _timestamp(payload.get("generated_at")))], + ) + + tables = [entry for entry in payload.get("tables", []) if isinstance(entry, dict)] + renderer = _RENDERERS.get(command) + if renderer is not None: + renderer(lines, tables) + return "\n".join(lines) + "\n" + + +# ── Per command ───────────────────────────────────────────────────────────────── + + +def _plan_metrics(lines: list[str], tables: list[dict[str, Any]]) -> None: + """What is waiting to be applied, and what nothing will apply.""" + pending: list[tuple[dict[str, str], float]] = [] + relations: list[tuple[dict[str, str], float]] = [] + findings: list[tuple[dict[str, str], float]] = [] + for entry in tables: + table = str(entry.get("table", "")) + plan = entry.get("plan") or {} + operations = plan.get("operations", []) + counted = Counter(str(op.get("kind", "unknown")) for op in operations) + for kind in ("create", "attach", "detach", "drop"): + pending.append(({"table": table, "kind": kind}, counted.get(kind, 0))) + relations.append(({"table": table}, _relation_count(operations))) + by_severity = Counter(str(f.get("severity", "unknown")) for f in plan.get("findings", [])) + for severity in ("info", "warning"): + findings.append(({"table": table, "severity": severity}, by_severity.get(severity, 0))) + + _emit(lines, f"{_PREFIX}_pending_operations", "Operations a maintenance run would carry out.", pending) + _emit( + lines, + f"{_PREFIX}_pending_relations", + "Relations those operations would create, subtrees included.", + relations, + ) + _emit( + lines, + f"{_PREFIX}_findings", + "What the planner saw and left alone. A warning needs a person.", + findings, + ) + + +def _inspect_metrics(lines: list[str], tables: list[dict[str, Any]]) -> None: + """What exists, and what is waiting to be cleaned up.""" + partitions: list[tuple[dict[str, str], float]] = [] + orphans: list[tuple[dict[str, str], float]] = [] + oldest: list[tuple[dict[str, str], float]] = [] + partitioned: list[tuple[dict[str, str], float]] = [] + now = datetime.now(UTC) + for entry in tables: + table = str(entry.get("table", "")) + tree = entry.get("tree") + partitioned.append(({"table": table}, 0 if tree is None else 1)) + if tree is None: + continue + detached = [o for o in tree.get("orphans", []) if isinstance(o, dict)] + partitions.append(({"table": table}, _count_nodes(tree.get("root", {})))) + orphans.append(({"table": table}, len(detached))) + age = _oldest_age_seconds(detached, now) + if age is not None: + oldest.append(({"table": table}, age)) + + _emit(lines, f"{_PREFIX}_partitioned", "1 when the table is partitioned at all, 0 when it is not.", partitioned) + _emit(lines, f"{_PREFIX}_partitions", "Relations attached below the root, at every level.", partitions) + _emit(lines, f"{_PREFIX}_detached_partitions", "Detached partitions this library has not dropped yet.", orphans) + _emit( + lines, + f"{_PREFIX}_oldest_detached_age_seconds", + "Age of the oldest detached partition. A number that only grows means drops are not happening.", + oldest, + ) + + +def _validate_metrics(lines: list[str], tables: list[dict[str, Any]]) -> None: + """Whether the document still describes the database.""" + valid = [({"table": str(entry.get("table", ""))}, 1 if entry.get("ok") else 0) for entry in tables] + _emit(lines, f"{_PREFIX}_config_valid", "1 when the table matches the configuration describing it.", valid) + + +def _apply_metrics(lines: list[str], tables: list[dict[str, Any]]) -> None: + """What the run actually did, and what it could not.""" + applied: list[tuple[dict[str, str], float]] = [] + issues: list[tuple[dict[str, str], float]] = [] + for entry in tables: + table = str(entry.get("table", "")) + result = entry.get("result") or {} + for name in ("created", "repaired", "attached", "detached", "dropped"): + applied.append(({"table": table, "operation": name}, result.get(f"{name}_count", 0))) + issues.append(({"table": table}, len(result.get("issues", [])))) + + _emit(lines, f"{_PREFIX}_applied_operations", "What this run carried out.", applied) + _emit(lines, f"{_PREFIX}_issues", "Problems this run reported and did not fail on.", issues) + + +_RENDERERS = { + "plan": _plan_metrics, + "inspect": _inspect_metrics, + "validate": _validate_metrics, + "apply": _apply_metrics, +} + + +# ── Module helpers ────────────────────────────────────────────────────────────── + + +def _emit(lines: list[str], name: str, help_text: str, samples: Sequence[tuple[dict[str, str], float]]) -> None: + """One metric family: its documentation, its type, and every sample of it.""" + if not samples: + return + lines.append(f"# HELP {name} {help_text}") + lines.append(f"# TYPE {name} gauge") + for labels, value in samples: + lines.append(f"{name}{_labels(labels)} {_number(value)}") + + +def _labels(labels: dict[str, str]) -> str: + """Render a label set, escaping what the exposition format reserves.""" + if not labels: + return "" + rendered = ",".join(f'{key}="{_escape(value)}"' for key, value in labels.items()) + return "{" + rendered + "}" + + +def _escape(value: str) -> str: + return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + + +def _number(value: float) -> str: + """Integers without a decimal point, everything else as a plain float.""" + return str(int(value)) if float(value).is_integer() else repr(float(value)) + + +def _timestamp(generated_at: object) -> float: + """The envelope's instant as a UNIX timestamp, falling back to now.""" + if isinstance(generated_at, str): + try: + return datetime.fromisoformat(generated_at).timestamp() + except ValueError: + pass + return datetime.now(UTC).timestamp() + + +def _relation_count(operations: list[Any]) -> int: + """Every relation the creations would make, nested children included.""" + total = 0 + for operation in operations: + if isinstance(operation, dict) and operation.get("kind") == "create": + total += 1 + _relation_count(operation.get("children", [])) + return total + + +def _count_nodes(node: dict[str, Any]) -> int: + """Relations below the root, the root itself not counted.""" + children = node.get("children", []) + return sum(1 + _count_nodes(child) for child in children if isinstance(child, dict)) + + +def _oldest_age_seconds(orphans: list[dict[str, Any]], now: datetime) -> float | None: + """How long the longest-waiting orphan has been detached, when any says.""" + ages = [] + for orphan in orphans: + detached_at = orphan.get("detached_at") + if not isinstance(detached_at, str): + continue + try: + moment = datetime.fromisoformat(detached_at) + except ValueError: + continue + if moment.tzinfo is None: + moment = moment.replace(tzinfo=UTC) + ages.append((now - moment).total_seconds()) + return max(ages) if ages else None diff --git a/tests/integration/aio/test_cli.py b/tests/integration/aio/test_cli.py index 040beeb..2de2d8a 100644 --- a/tests/integration/aio/test_cli.py +++ b/tests/integration/aio/test_cli.py @@ -301,3 +301,20 @@ async def test__apply__hooks_declared_but_not_allowed__refuses_before_connecting # Act / Assert assert await _run_cli("apply", "-c", config) == ExitCode.CONFIG + + +async def test__output_metrics__a_real_run__is_a_textfile_a_collector_can_serve( + db_engine: AsyncEngine, table: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Arrange + config = _document(tmp_path, table, _dsn(db_engine)) + + # Act + code = await _run_cli("plan", "-c", config, "--check", "--output", "metrics") + printed = capsys.readouterr().out + + # Assert: the drift the same run reports on its exit code, as a number + assert code == ExitCode.DRIFT + assert "# TYPE pg_partsmith_pending_operations gauge" in printed + assert f'pg_partsmith_pending_operations{{table="{table}",kind="create"}} 2' in printed + assert f'pg_partsmith_pending_operations{{table="{table}",kind="drop"}} 0' in printed diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index 7e3e211..c7ef2ae 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -246,7 +246,7 @@ async def test__plan__an_actionable_finding__outranks_drift() -> None: async def test__plan__json__is_the_model_dump_under_a_versioned_envelope() -> None: # Arrange / Act result = await run_plan(_kit(_plan()), _configs(), check=False) - payload = json.loads(result.render(as_json=True)) + payload = json.loads(result.render(output="json")) # Assert: the vocabulary a configuration file is written in, not one of ours assert payload["version"] == 1 @@ -270,7 +270,7 @@ async def test__validate__a_table_the_catalog_disagrees_with__exits_config(monke # Assert assert result.code is ExitCode.CONFIG - assert json.loads(result.render(as_json=True))["tables"][0]["ok"] is False + assert json.loads(result.render(output="json"))["tables"][0]["ok"] is False async def test__validate__a_table_the_catalog_agrees_with__exits_ok(monkeypatch: pytest.MonkeyPatch) -> None: @@ -282,7 +282,7 @@ async def test__validate__a_table_the_catalog_agrees_with__exits_ok(monkeypatch: # Assert assert result.code is ExitCode.OK - assert json.loads(result.render(as_json=True))["tables"][0] == { + assert json.loads(result.render(output="json"))["tables"][0] == { "table": "public.events", "ok": True, "error": None, @@ -361,7 +361,7 @@ async def test__apply__by_default__withholds_every_destructive_operation() -> No # Assert applied = kit.service.apply.await_args.args[1] assert [op.kind.value for op in applied.operations] == ["create"] - assert "--allow-destructive" in result.render(as_json=False) + assert "--allow-destructive" in result.render(output="human") async def test__apply__allow_destructive__carries_the_drop_out_too() -> None: @@ -409,7 +409,7 @@ async def test__apply__issues_reported_by_the_run__exit_findings() -> None: # Assert assert result.code is ExitCode.FINDINGS - assert "refused" in result.render(as_json=False) + assert "refused" in result.render(output="human") async def test__apply__json__carries_the_plan_beside_the_result() -> None: @@ -419,7 +419,7 @@ async def test__apply__json__carries_the_plan_beside_the_result() -> None: # Act result = await run_apply(kit, _configs(), plans={"public.events": _plan()}) - payload = json.loads(result.render(as_json=True)) + payload = json.loads(result.render(output="json")) # Assert entry = payload["tables"][0] diff --git a/tests/unit/test_metrics.py b/tests/unit/test_metrics.py new file mode 100644 index 0000000..647d361 --- /dev/null +++ b/tests/unit/test_metrics.py @@ -0,0 +1,195 @@ +"""``--output metrics``: the same run, as a node_exporter textfile.""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from pg_partsmith.cli.metrics import render_metrics + + +def _samples(text: str) -> dict[str, float]: + """Every sample line as ``name{labels} -> value``, comments dropped.""" + samples: dict[str, float] = {} + for line in text.splitlines(): + if line.startswith("#") or not line.strip(): + continue + series, _, value = line.rpartition(" ") + samples[series] = float(value) + return samples + + +def _envelope(command: str, tables: list[dict[str, Any]]) -> dict[str, Any]: + return { + "version": 1, + "command": command, + "generated_at": "2026-09-01T12:00:00+00:00", + "tables": tables, + } + + +def test__render_metrics__every_family__is_documented_and_typed() -> None: + # A textfile collector serves these to Prometheus verbatim, so the HELP and + # TYPE lines are part of the output, not a nicety. + text = render_metrics(_envelope("validate", [{"table": "public.events", "ok": True}])) + + # Assert + assert "# HELP pg_partsmith_config_valid" in text + assert "# TYPE pg_partsmith_config_valid gauge" in text + assert text.endswith("\n") + + +def test__render_metrics__the_run_timestamp__is_the_one_in_the_envelope() -> None: + # Arrange / Act: a stale textfile has to be visible as stale + text = render_metrics(_envelope("plan", [])) + + # Assert + expected = datetime.fromisoformat("2026-09-01T12:00:00+00:00").timestamp() + assert _samples(text)['pg_partsmith_run_timestamp_seconds{command="plan"}'] == expected + + +def test__plan__pending_operations__are_counted_by_kind() -> None: + # Arrange + payload = _envelope( + "plan", + [ + { + "table": "public.events", + "plan": { + "operations": [ + {"kind": "create", "children": [{"kind": "create", "children": []}]}, + {"kind": "create", "children": []}, + {"kind": "drop"}, + ], + "findings": [{"severity": "warning"}, {"severity": "info"}, {"severity": "warning"}], + }, + } + ], + ) + + # Act + samples = _samples(render_metrics(payload)) + + # Assert + assert samples['pg_partsmith_pending_operations{table="public.events",kind="create"}'] == 2 + assert samples['pg_partsmith_pending_operations{table="public.events",kind="drop"}'] == 1 + assert samples['pg_partsmith_pending_operations{table="public.events",kind="detach"}'] == 0 + # Three relations: two top-level creations and one nested child + assert samples['pg_partsmith_pending_relations{table="public.events"}'] == 3 + assert samples['pg_partsmith_findings{table="public.events",severity="warning"}'] == 2 + assert samples['pg_partsmith_findings{table="public.events",severity="info"}'] == 1 + + +def test__plan__a_converged_table__reports_zeroes_rather_than_nothing() -> None: + # A missing series and a zero are different alerts; converged is a zero. + payload = _envelope("plan", [{"table": "public.events", "plan": {"operations": [], "findings": []}}]) + + # Act + samples = _samples(render_metrics(payload)) + + # Assert + assert samples['pg_partsmith_pending_operations{table="public.events",kind="create"}'] == 0 + assert samples['pg_partsmith_pending_relations{table="public.events"}'] == 0 + + +def test__inspect__counts_the_tree_and_ages_the_oldest_orphan() -> None: + # Arrange + payload = _envelope( + "inspect", + [ + { + "table": "public.events", + "tree": { + "root": { + "children": [ + {"children": [{"children": []}, {"children": []}]}, + {"children": []}, + ] + }, + "orphans": [ + {"name": "public.events__2025_01", "detached_at": "2026-09-01T11:00:00+00:00"}, + {"name": "public.events__2025_02", "detached_at": None}, + ], + }, + } + ], + ) + + # Act + samples = _samples(render_metrics(payload)) + + # Assert: four relations below the root, two orphans, one of them datable + assert samples['pg_partsmith_partitions{table="public.events"}'] == 4 + assert samples['pg_partsmith_detached_partitions{table="public.events"}'] == 2 + assert samples['pg_partsmith_partitioned{table="public.events"}'] == 1 + assert samples['pg_partsmith_oldest_detached_age_seconds{table="public.events"}'] > 0 + + +def test__inspect__a_table_that_is_not_partitioned__says_so_in_one_series() -> None: + # Arrange / Act + samples = _samples(render_metrics(_envelope("inspect", [{"table": "public.events", "tree": None}]))) + + # Assert + assert samples['pg_partsmith_partitioned{table="public.events"}'] == 0 + assert 'pg_partsmith_partitions{table="public.events"}' not in samples + + +def test__validate__a_table_the_catalog_disagrees_with__is_a_zero() -> None: + # Arrange / Act + payload = _envelope( + "validate", + [{"table": "public.events", "ok": True}, {"table": "public.audit", "ok": False, "error": "not partitioned"}], + ) + samples = _samples(render_metrics(payload)) + + # Assert + assert samples['pg_partsmith_config_valid{table="public.events"}'] == 1 + assert samples['pg_partsmith_config_valid{table="public.audit"}'] == 0 + + +def test__apply__reports_what_it_did_and_what_it_could_not() -> None: + # Arrange + payload = _envelope( + "apply", + [ + { + "table": "public.events", + "result": { + "created_count": 2, + "repaired_count": 0, + "attached_count": 1, + "detached_count": 1, + "dropped_count": 1, + "issues": [{"step": "drop", "error": "refused"}], + }, + } + ], + ) + + # Act + samples = _samples(render_metrics(payload)) + + # Assert + assert samples['pg_partsmith_applied_operations{table="public.events",operation="created"}'] == 2 + assert samples['pg_partsmith_applied_operations{table="public.events",operation="dropped"}'] == 1 + assert samples['pg_partsmith_issues{table="public.events"}'] == 1 + + +def test__render_metrics__a_table_name_with_a_quote_in_it__is_escaped() -> None: + # PostgreSQL allows it, and an unescaped quote would break the whole file. + payload = _envelope("validate", [{"table": 'public."odd"', "ok": True}]) + + # Act + text = render_metrics(payload) + + # Assert + assert 'pg_partsmith_config_valid{table="public.\\"odd\\""} 1' in text + + +def test__render_metrics__a_command_it_has_no_numbers_for__still_says_when_it_ran() -> None: + # Arrange / Act + text = render_metrics(_envelope("something-else", [])) + + # Assert + assert "pg_partsmith_run_timestamp_seconds" in text + assert len(_samples(text)) == 1