Skip to content
Closed
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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<version>`, published from the release workflow, so a
Expand Down
3 changes: 2 additions & 1 deletion docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
47 changes: 47 additions & 0 deletions docs/guide/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions docs/guide/container.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 12 additions & 4 deletions pg_partsmith/cli/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)


Expand Down
8 changes: 6 additions & 2 deletions pg_partsmith/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
221 changes: 221 additions & 0 deletions pg_partsmith/cli/metrics.py
Original file line number Diff line number Diff line change
@@ -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
Loading