diff --git a/AGENTS.md b/AGENTS.md
index 3e81b6f..ea19120 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -181,7 +181,7 @@ src/ops/ compact / expire / manifests / orphans
delete.rs the one deleter both destructive ops share
reachability.rs what a table still needs — safety-critical
store.rs object listing, which FileIO does not offer
-src/sched/ daemon, cron triggers, event debounce
+src/sched/ daemon, cron triggers, event debounce, the /status board
src/obs/ observer trait, audit log, metrics
src/cli/ clap commands, human + JSON output
```
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a0109aa..2c1a5b4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,13 +5,28 @@ and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
Bergman is pre-1.0: **breaking changes land in minor versions**, each with a migration note.
-## [Unreleased]
+## [0.5.0] — 2026-11-20
+
+**Breaking:** `obs::router`, `obs::router_with_events` and `obs::serve` take a `sched::StatusBoard`
+— pass `daemon.status()`. `metrics` is a default feature; a library that wants neither `axum` nor
+`prometheus-client` sets `default-features = false`.
+
+### Added
+
+- **`bergman status`** asks a running daemon what it is doing and what needs attention, from the
+ new **`/status`** endpoint. No config or credentials needed; failures and refusals print first;
+ exits `2` when something needs attention. `Daemon::status()` exposes the same board to embedders.
+
+### Changed
+
+- `cargo install bergman` includes the daemon's HTTP surface and `bergman status`, like every
+ published binary.
### Security
-- `chrono`, `chrono-tz` and `humantime` are marked unmaintained (RUSTSEC-2026-0543, -0555, -0542),
- with no patched version and no vulnerability. All three reach Bergman through arrow, datafusion,
- iceberg and object_store, so they are ignored in `deny.toml` with that reason.
+- `chrono`, `chrono-tz` and `humantime` (RUSTSEC-2026-0543, -0555, -0542) are flagged unmaintained,
+ with no fix and no vulnerability. They reach Bergman through arrow, datafusion, iceberg and
+ object_store, and are ignored in `deny.toml` with that reason.
## [0.4.0] — 2026-11-08
@@ -185,6 +200,8 @@ Initial release. Table health analysis, snapshot expiration with file cleanup,
orphan-file removal, manifest rewriting, and compaction with delete-file
application — as one crate, one binary, and a library, on `iceberg-rust`.
+[0.5.0]: https://github.com/hupe1980/bergman/compare/v0.4.0...v0.5.0
+[0.4.0]: https://github.com/hupe1980/bergman/compare/v0.3.0...v0.4.0
[0.3.0]: https://github.com/hupe1980/bergman/compare/v0.2.0...v0.3.0
[0.2.0]: https://github.com/hupe1980/bergman/compare/v0.1.0...v0.2.0
[0.1.0]: https://github.com/hupe1980/bergman/releases/tag/v0.1.0
diff --git a/Cargo.lock b/Cargo.lock
index 861c384..2e1fd7c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -597,7 +597,7 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bergman"
-version = "0.4.0"
+version = "0.5.0"
dependencies = [
"arrow",
"async-trait",
diff --git a/Cargo.toml b/Cargo.toml
index b73d4ae..ec89cb6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "bergman"
-version = "0.4.0"
+version = "0.5.0"
edition = "2024"
authors = ["hupe1980"]
description = "A Rust-native maintenance engine for Apache Iceberg — policy-driven compaction, snapshot expiration, and orphan cleanup with no JVM"
@@ -17,7 +17,7 @@ rust-version = "1.95"
# Optional dependencies are `dep:` so the feature surface is exactly this list.
# Embedders take `default-features = false` and add what they use.
[features]
-default = ["cli", "catalog-rest", "compaction", "storage-all"]
+default = ["cli", "catalog-rest", "compaction", "storage-all", "metrics"]
# The only operation that reads and writes data. DataFusion applies equality
# deletes as a hash anti-join; without the feature there is no compaction.
diff --git a/README.md b/README.md
index e7ee15c..11f783d 100644
--- a/README.md
+++ b/README.md
@@ -1,35 +1,36 @@
-# Bergman
+# 🏔️ Bergman
**A Rust-native maintenance engine for Apache Iceberg. One crate. One binary. No JVM.**
-Bergman keeps Iceberg tables healthy — compacting small files, applying and
-retiring delete files, expiring snapshots, re-packing manifests and removing
-orphans — driven by declarative policies and built on
-[`iceberg-rust`](https://github.com/apache/iceberg-rust) 0.11.0. No Spark, no
+Bergman keeps Iceberg tables healthy: it compacts small files, applies and
+retires delete files, expires snapshots, re-packs manifests and removes orphans.
+Declarative policies drive it, and it is built on
+[`iceberg-rust`](https://github.com/apache/iceberg-rust) 0.11.0 — no Spark, no
Trino, no cluster. It is **library-first**: the `bergman` binary is a thin
consumer of the same public API an embedder gets.
```bash
-bergman inspect # what is wrong with my tables? (reads only)
-bergman plan # what would maintenance do? (reads only)
-bergman run # do it
+bergman inspect # 🔍 what is wrong with my tables? (reads only)
+bergman plan # 🧭 what would maintenance do, and why? (reads only)
+bergman run # 🛠️ do it
+bergman status # 📡 what is the daemon doing, and what needs me?
```
-- **Documentation:**
-- **Sister project:** [Rustberg](https://github.com/hupe1980/rustberg), an
- authenticated, policy-controlled Iceberg REST catalog. Each works fully
- without the other.
+📚 **Docs:** ·
+🤝 **Sister project:** [Rustberg](https://github.com/hupe1980/rustberg), an
+authenticated, policy-controlled Iceberg REST catalog. Each works fully without
+the other.
---
-## Install
+## 📦 Install
```bash
-brew install hupe1980/tap/bergman # macOS (Apple Silicon) and Linux
-cargo install bergman # anywhere Rust builds
+brew install hupe1980/tap/bergman # macOS (Apple Silicon) and Linux
+cargo install bergman # anywhere Rust 1.95+ builds
```
-As a container — distroless, non-root, statically linked:
+🐳 As a container — distroless, non-root, statically linked:
```bash
docker run --rm \
@@ -37,46 +38,13 @@ docker run --rm \
ghcr.io/hupe1980/bergman:latest plan
```
-Or a binary from the [releases page](https://github.com/hupe1980/bergman/releases):
-static musl Linux for `x86_64` and `aarch64`, and macOS on Apple Silicon, each with
-a `.sha256` beside it. From source, Bergman requires Rust 1.95+.
+Or grab a binary from the [releases page](https://github.com/hupe1980/bergman/releases):
+static musl Linux for `x86_64` and `aarch64`, and macOS on Apple Silicon, each
+with a `.sha256` beside it.
---
-## What it does
-
-| Operation | Built on |
-|---|---|
-| Table health analysis | Manifest metadata only; no data file is opened |
-| Snapshot expiration | Upstream `ExpireSnapshotsAction` |
-| Expiration file cleanup | Bergman — upstream leaves it to the caller |
-| Orphan-file removal | Bergman's object-store layer — `FileIO` has no `list` |
-| Manifest rewrite | Bergman's commit layer |
-| Compaction | Upstream's scan and writers, Bergman's commit layer |
-| Dangling delete-file removal | Bergman's commit layer |
-
-Compaction is **triggered**, not scheduled — by small files, oversized files,
-delete ratio, and a settle time that leaves a partition being written alone. It
-honours the table's `sort-order` and `write.*` properties, and applies equality
-deletes with a DataFusion hash anti-join.
-[Compaction →](https://hupe1980.github.io/bergman/docs/compaction/)
-
-**Format v3** tables are maintained in full: a rewrite writes each row's
-`_row_id` and `_last_updated_sequence_number` physically and the snapshot claims
-its row range; deletion vectors are applied and retired by `(path, offset)`.
-
-**Refused, by name, in `bergman plan`:** encrypted tables (snapshot expiration
-still runs), anything but Parquet, cross-spec rewrites, and any branch but
-`main`. [Status →](https://hupe1980.github.io/bergman/docs/status/)
-
-Bergman owns its commit layer because `iceberg::Transaction` cannot express a
-rewrite: it builds the commit from upstream's public writers and `POST`s it to
-the table endpoint, behind a `TableCommitter` trait.
-[Architecture →](https://hupe1980.github.io/bergman/docs/architecture/)
-
----
-
-## Quickstart
+## ⚡ Quickstart
`bergman.toml` — every setting is optional:
@@ -104,67 +72,108 @@ skip = true
```
```bash
-bergman policy lint # validate offline, for CI
-bergman policy explain prod.analytics.events # each setting and where it came from
-bergman plan
+bergman policy lint # ✅ validate offline, for CI
+bergman policy explain prod.analytics.events # 🧾 each setting and where it came from
+bergman plan # 🧭 read-only, always safe
```
Settings resolve, most specific first, through the matching **rule**,
**`[defaults]`**, the **catalog's own policy** (`policy_source = "polaris"`),
-the **table's properties and `sort-order`**, and the **Iceberg default**.
+the **table's properties and `sort-order`**, and the **Iceberg default** — and
+`policy explain` shows which layer every value came from.
[Configuration →](https://hupe1980.github.io/bergman/docs/configuration/) ·
[Policies →](https://hupe1980.github.io/bergman/docs/policies/)
---
-## Commands
+## 🧹 What it does
+
+| | Operation | Built on |
+|:--:|---|---|
+| 🔍 | Table health analysis | Manifest metadata only; no data file is opened |
+| 🗜️ | Compaction | Upstream's scan and writers, Bergman's commit layer |
+| 🧽 | Dangling delete-file removal | Bergman's commit layer |
+| 📚 | Manifest rewrite | Bergman's commit layer |
+| ⏳ | Snapshot expiration | Upstream `ExpireSnapshotsAction` |
+| 🗑️ | Expiration file cleanup | Bergman — upstream leaves it to the caller |
+| 👻 | Orphan-file removal | Bergman's object-store layer — `FileIO` has no `list` |
+
+🎯 **Compaction is triggered, not scheduled** — by small files, oversized files,
+delete ratio, and a settle time that leaves a partition being written alone. It
+honours the table's `sort-order` and `write.*` properties, and applies equality
+deletes with a DataFusion hash anti-join.
+[Compaction →](https://hupe1980.github.io/bergman/docs/compaction/)
+
+🆕 **Format v3** tables are maintained in full: a rewrite writes each row's
+`_row_id` and `_last_updated_sequence_number` physically and the snapshot claims
+its row range; deletion vectors are applied and retired by `(path, offset)`.
+
+🚫 **Refused by name, never guessed at** — in `bergman plan`, the run report and
+`bergman status`: encrypted tables (snapshot expiration still runs), anything but
+Parquet, cross-spec rewrites, and any branch but `main`.
+[Status →](https://hupe1980.github.io/bergman/docs/status/)
+
+🧱 Bergman owns its commit layer because `iceberg::Transaction` cannot express a
+rewrite: it builds the commit from upstream's public writers and `POST`s it to
+the table endpoint, behind a `TableCommitter` trait.
+[Architecture →](https://hupe1980.github.io/bergman/docs/architecture/)
+
+---
+
+## ⌨️ Commands
| Command | Writes? | What it does |
|---|:--:|---|
-| `bergman inspect` | no | Table health: file counts, sizes, delete ratios, snapshots, manifests |
-| `bergman plan` | no | The operations maintenance would perform, and why |
-| `bergman run` | **yes** | Executes the plan |
-| `bergman run --dry-run` | no | Identical to `plan` |
-| `… --table ` | — | Scopes `inspect`, `plan` and `run`; an excluded table is never read |
-| `… --only [,]` | — | Scopes `plan` and `run` to `compact`, `rewrite-manifests`, `expire-snapshots`, `remove-orphans` |
-| `bergman daemon` | **yes** | Runs cycles on schedules, or when told a table changed (`POST /events`, including Lakekeeper CloudEvents) |
-| `bergman policy lint` | no | Validates config offline |
-| `bergman policy explain
` | no | Effective policy with per-value provenance |
-| `bergman policy match` | no | Which tables each rule matches |
+| `bergman inspect` | — | Table health: file counts, sizes, delete ratios, snapshots, manifests |
+| `bergman plan` | — | The operations maintenance would perform, and why — or why not |
+| `bergman run` | ✍️ | Executes the plan |
+| `bergman run --dry-run` | — | Identical to `plan` |
+| `… --table ` | | Scopes `inspect`, `plan` and `run`; an excluded table is never read |
+| `… --only [,]` | | Scopes `plan` and `run` to `compact`, `rewrite-manifests`, `expire-snapshots`, `remove-orphans` |
+| `bergman daemon` | ✍️ | Runs cycles on schedules, or when told a table changed (`POST /events`, including Lakekeeper CloudEvents) |
+| `bergman status` | — | Asks a running daemon what it is doing; what needs attention comes first |
+| `bergman policy lint` | — | Validates config offline |
+| `bergman policy explain
` | — | Effective policy with per-value provenance |
+| `bergman policy match` | — | Which tables each rule matches |
Global flags: `--config`, `--format text|json`, `--audit-log `, `--log `.
-`bergman run` exits `2` when any operation failed or was refused.
-[Operating →](https://hupe1980.github.io/bergman/docs/operating/)
+`bergman run` and `bergman status` exit `2` when an operation failed or was
+refused, so a scheduler or a check that reads only exit codes still notices.
+
+📡 A daemon started with `--listen` serves `/metrics`, `/health`, `/status` and
+(with `--events`) `/events`. `bergman status --daemon http://host:9090` reads
+`/status` with no config file and no credentials — point it at a pod from your
+laptop. [Operating →](https://hupe1980.github.io/bergman/docs/operating/)
---
-## Safety
+## 🛡️ Safety
-- **Nothing destructive is on by default.** Compaction, orphan deletion and
+- 🔒 **Nothing destructive is on by default.** Compaction, orphan deletion and
expiration's file cleanup default off; metadata-only snapshot expiration is on.
-- **A table Bergman cannot fully read is refused**, and every manifest walk is
+- 📖 **A table Bergman cannot fully read is refused**, and every manifest walk is
all-or-nothing, so nothing is deleted on a partial reading.
-- **Orphan removal has eight independent checks**, including a 24-hour grace
+- 👻 **Orphan removal has eight independent checks**, including a 24-hour grace
floor, segment-wise containment, re-verification before deleting, a deletion
ceiling, and a refusal when the listing and the metadata share no file.
[Orphans →](https://hupe1980.github.io/bergman/docs/orphans/)
-- **One deleter**: orphan removal and expiration cleanup share one blast-radius
+- 🎯 **One deleter**: orphan removal and expiration cleanup share one blast-radius
ceiling, audit record and bounded deletion path.
-- **A rewrite never drops a delete file another file still needs**, and every
+- 🧩 **A rewrite never drops a delete file another file still needs**, and every
file group's row count must land between a floor and a ceiling taken from
metadata.
-- **Carried-forward files keep their sequence numbers; manifests keep their
+- 🔢 **Carried-forward files keep their sequence numbers; manifests keep their
partition spec; a moved branch keeps its retention.**
-- **Commits are compare-and-swap; a lost one is rebuilt, never re-offered.** A
+- ⚖️ **Commits are compare-and-swap; a lost one is rebuilt, never re-offered.** A
429/503 is retried; a 409/412 replans.
-- **Every operation is auditable**: `--audit-log` writes JSON Lines, and a
+- 🧾 **Every operation is auditable**: `--audit-log` writes JSON Lines, and a
deletion manifest is written before the first delete.
-- **Secrets never reach a log**: credentials and catalog config redact in
+- 🤫 **Secrets never reach a log**: credentials and catalog config redact in
`Debug`. `POST /events` can require a bearer token (`--events-token-env`).
---
-## Library
+## 🦀 Library
```rust
use bergman::{Bergman, policy::Config};
@@ -198,19 +207,22 @@ impl MaintenanceObserver for RequireSignoff {
}
```
+Embedding the daemon? `Daemon::status()` hands you the same live board
+`/status` serves.
+
| Feature | Default | Carries |
|---|:--:|---|
| `cli` | ✅ | The binary, terminal rendering, logging setup |
| `catalog-rest` | ✅ | Iceberg REST catalog client |
| `compaction` | ✅ | Data-file rewriting, and the DataFusion executor it needs |
| `storage-s3` / `-gcs` / `-azure` | ✅ via `storage-all` | Cloud object stores |
-| `metrics` | — | Prometheus metrics, and the daemon's HTTP surface: `/metrics`, `/health`, `/events` |
+| `metrics` | ✅ | Prometheus metrics, and the daemon's HTTP surface: `/metrics`, `/health`, `/status`, `/events`; `bergman status` |
[Library →](https://hupe1980.github.io/bergman/docs/library/)
---
-## Development
+## 🧪 Development
```bash
just test # the full suite
@@ -226,11 +238,11 @@ just cross-engine # opt-in, needs uv: PyIceberg 0.12.0 writes, Bergman maintain
The suite needs no containers or cloud credentials: it builds real tables on the
local filesystem and commits to an in-memory catalog.
-## Changelog
+## 📝 Changelog
[CHANGELOG.md](CHANGELOG.md). Bergman is pre-1.0: breaking changes land in minor
versions, with migration notes.
-## License
+## ⚖️ License
Apache-2.0 OR MIT.
diff --git a/site/content/docs/library.md b/site/content/docs/library.md
index c714d7d..eba6f1c 100644
--- a/site/content/docs/library.md
+++ b/site/content/docs/library.md
@@ -18,7 +18,7 @@ cargo add bergman --no-default-features --features catalog-rest,storage-s3
| `catalog-rest` | ✅ | The Iceberg REST catalog client |
| `compaction` | ✅ | Data-file rewriting — **and DataFusion**, which applies equality deletes as a hash anti-join |
| `storage-s3` / `-gcs` / `-azure` | ✅ via `storage-all` | Cloud object stores |
-| `metrics` | — | Prometheus metrics and the `/metrics` endpoint |
+| `metrics` | ✅ | Prometheus metrics and the daemon's HTTP surface: `/metrics`, `/health`, `/status`, `/events` |
`compaction` is the only operation that reads and writes *data*, and the only
one needing a query engine ([why](@/docs/compaction.md#query-engine)). For
diff --git a/site/content/docs/operating.md b/site/content/docs/operating.md
index e26c906..014a0b6 100644
--- a/site/content/docs/operating.md
+++ b/site/content/docs/operating.md
@@ -165,6 +165,43 @@ time. An unauthorized request gets a bare `401` before the body is examined.
The daemon warns when `/events` is served without a token on an address that is
neither loopback nor behind an authenticating mesh.
+### Asking it what it is doing
+
+A daemon started with `--listen` serves `/status`: the cycle in progress or the
+next one due, how the last cycle went, and the latest outcome for every table that
+had work or a note. `bergman status` reads it and puts what needs you first:
+
+```console
+$ bergman status --daemon http://bergman.maintenance:9090
+daemon up 3h, 14 cycles finished; next at 11:00 UTC (interval, in 18m)
+last cycle 14 (2 changed tables) at 10:41 UTC: 2 tables, 3 operations succeeded in 12s
+
+needs attention
+ prod.sales.orders (cycle 12, 09:02 UTC)
+ [XX] remove-orphans: vetoed by observer
+
+maintained
+ prod.sales.events (cycle 14, 10:41 UTC)
+ [ok] expire-snapshots: 8 snapshots expired
+
+1 table needs attention.
+```
+
+It needs no configuration file and no credentials, so it works from a laptop
+pointed at a pod (`BERGMAN_DAEMON_URL` sets the address), and `--format json`
+prints exactly what `/status` serves. It exits `2` when an operation failed or was
+refused, or the last cycle failed outright — the same contract as `bergman run` —
+so it doubles as a check.
+
+A table leaves the list only when a cycle that examined it had nothing to say. An
+event for one table, or a cycle the byte budget stopped short of it, leaves what
+an earlier cycle said in place, with the cycle that said it. The board lives in
+memory: a restarted daemon starts empty and fills in on its first cycle.
+
+`/status` names tables and carries the text of refusals and errors, the same
+content the daemon prints to its own output. It causes no work. Expose it where
+you would let someone read the daemon's logs.
+
### Windows
With a `maintenance_window` set, the daemon sleeps to the window's edge.
diff --git a/site/templates/index.html b/site/templates/index.html
index 81489f5..56afb4e 100644
--- a/site/templates/index.html
+++ b/site/templates/index.html
@@ -194,6 +194,12 @@
Cron job
bergman run \
--config /etc/bergman.toml \
--audit-log /var/log/bergman.jsonl
+
+
+
Daemon
+
Follows each rule's schedule and reacts to commit events. Ask it what it is doing, and what needs you, from anywhere.
+
bergman daemon --listen 0.0.0.0:9090
+bergman status --daemon http://bergman:9090
Read-only first
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index f0f8d9f..f72c901 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -187,6 +187,23 @@ enum Command {
events_token_env: Option,
},
+ /// Ask a running daemon what it is doing, and what needs attention.
+ ///
+ /// Reads the daemon's `/status`; needs no configuration file and no
+ /// credentials, so it works from a laptop pointed at a pod. Exits 2 when
+ /// a table has a failed or refused operation, or the last cycle failed —
+ /// the same contract as `bergman run`, so a check can rely on it.
+ #[cfg(feature = "metrics")]
+ Status {
+ /// The daemon's `--listen` address.
+ #[arg(
+ long,
+ env = "BERGMAN_DAEMON_URL",
+ default_value = "http://127.0.0.1:9090"
+ )]
+ daemon: String,
+ },
+
/// Policy inspection.
#[command(subcommand)]
Policy(PolicyCommand),
@@ -214,6 +231,17 @@ pub async fn main() -> Result<()> {
let cli = Cli::parse();
init_tracing(&cli.log);
+ // Asking a daemon needs neither its configuration nor its credentials.
+ #[cfg(feature = "metrics")]
+ if let Command::Status { daemon } = &cli.command {
+ let status = fetch_status(daemon).await?;
+ render::status(&status, cli.format)?;
+ if status.needs_attention() {
+ std::process::exit(2);
+ }
+ return Ok(());
+ }
+
let config = Config::from_path(&cli.config)?;
// Linting must not require a catalog: it is meant for CI.
@@ -321,10 +349,17 @@ pub async fn main() -> Result<()> {
#[cfg(feature = "metrics")]
let server = listen.map(|addr| {
let metrics = Arc::clone(&metrics);
+ let status = daemon.status();
tokio::spawn(async move {
- if let Err(e) =
- crate::obs::serve(addr, metrics, sender, event_token, shutdown_signal())
- .await
+ if let Err(e) = crate::obs::serve(
+ addr,
+ metrics,
+ status,
+ sender,
+ event_token,
+ shutdown_signal(),
+ )
+ .await
{
eprintln!("bergman: {e}");
}
@@ -399,6 +434,8 @@ pub async fn main() -> Result<()> {
}
Command::Policy(PolicyCommand::Lint) => unreachable!("handled above"),
+ #[cfg(feature = "metrics")]
+ Command::Status { .. } => unreachable!("handled above"),
}
}
@@ -425,6 +462,27 @@ async fn plan_for(
Ok(plan)
}
+/// Read a daemon's `/status`.
+#[cfg(feature = "metrics")]
+async fn fetch_status(daemon: &str) -> Result {
+ let url = format!("{}/status", daemon.trim_end_matches('/'));
+ let unreachable = |e: reqwest::Error| {
+ Error::config(format!(
+ "cannot read {url}: {e} — is the daemon running with --listen?"
+ ))
+ };
+ reqwest::Client::new()
+ .get(&url)
+ .timeout(std::time::Duration::from_secs(10))
+ .send()
+ .await
+ .and_then(reqwest::Response::error_for_status)
+ .map_err(unreachable)?
+ .json()
+ .await
+ .map_err(unreachable)
+}
+
fn lint(config: &Config, format: Format) -> Result<()> {
for catalog in &config.catalogs {
catalog.validate()?;
diff --git a/src/cli/render.rs b/src/cli/render.rs
index 5ab683c..6eb4250 100644
--- a/src/cli/render.rs
+++ b/src/cli/render.rs
@@ -443,3 +443,233 @@ fn table_with_provenance() -> Table {
fn add(t: &mut Table, setting: &str, value: &str, from: &str) {
t.add_row(vec![Cell::new(setting), Cell::new(value), Cell::new(from)]);
}
+
+/// Render `bergman status`.
+#[cfg(feature = "metrics")]
+pub fn status(status: &crate::sched::DaemonStatus, format: Format) -> Result<()> {
+ if format == Format::Json {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(status).unwrap_or_default()
+ );
+ return Ok(());
+ }
+ print!("{}", status_text(status, chrono::Utc::now()));
+ Ok(())
+}
+
+/// The text form of a daemon's status, as of `now`.
+///
+/// Ordered by what an operator came to find out: what needs them first, then
+/// what cannot apply, then what went fine. A daemon with nothing to say says so
+/// in one line rather than printing an empty frame.
+#[cfg(feature = "metrics")]
+fn status_text(s: &crate::sched::DaemonStatus, now: chrono::DateTime) -> String {
+ use std::fmt::Write;
+
+ let ago =
+ |at: chrono::DateTime| human_duration((now - at).to_std().unwrap_or_default());
+ let clock = |at: chrono::DateTime| at.format("%H:%M UTC").to_string();
+
+ let mut out = String::new();
+ let _ = write!(
+ out,
+ "daemon up {}, {} finished",
+ ago(s.started_at),
+ super::plural(s.cycles as usize, "cycle")
+ );
+ match (&s.running, &s.next) {
+ (Some(r), _) => {
+ let _ = write!(
+ out,
+ "; cycle {} running ({}) for {}",
+ r.number,
+ r.trigger,
+ ago(r.since)
+ );
+ }
+ (None, Some(n)) => {
+ let wait = human_duration((n.at - now).to_std().unwrap_or_default());
+ let _ = write!(out, "; next at {} ({}, in {wait})", clock(n.at), n.trigger);
+ }
+ (None, None) => {}
+ }
+ out.push('\n');
+
+ if let Some(c) = &s.last_cycle {
+ let what = match (&c.error, &c.summary) {
+ (Some(e), _) => format!("FAILED: {e}"),
+ (None, Some(summary)) => summary.clone(),
+ (None, None) => String::new(),
+ };
+ let _ = writeln!(
+ out,
+ "last cycle {} ({}) at {}: {what}",
+ c.number,
+ c.trigger,
+ clock(c.finished_at)
+ );
+ if !c.deferred.is_empty() {
+ let names: Vec = c.deferred.iter().map(ToString::to_string).collect();
+ let _ = writeln!(out, "deferred by the byte budget: {}", names.join(", "));
+ }
+ }
+
+ let attention: Vec<_> = s.tables.iter().filter(|t| t.needs_attention()).collect();
+ let noted: Vec<_> = s
+ .tables
+ .iter()
+ .filter(|t| !t.needs_attention() && !t.outcome.notes.is_empty())
+ .collect();
+ let rest: Vec<_> = s
+ .tables
+ .iter()
+ .filter(|t| !t.needs_attention() && t.outcome.notes.is_empty())
+ .collect();
+
+ for (heading, group) in [
+ ("needs attention", &attention),
+ ("cannot apply", ¬ed),
+ ("maintained", &rest),
+ ] {
+ if group.is_empty() {
+ continue;
+ }
+ let _ = writeln!(out, "\n{heading}");
+ for t in group.iter() {
+ let _ = writeln!(
+ out,
+ " {} (cycle {}, {})",
+ t.outcome.table,
+ t.cycle,
+ clock(t.at)
+ );
+ for note in &t.outcome.notes {
+ let _ = writeln!(out, " note: {note}");
+ }
+ for op in &t.outcome.operations {
+ let (marker, detail) = match &op.result {
+ OperationResult::Succeeded { detail } => ("ok", detail),
+ OperationResult::NoOp { detail } => ("--", detail),
+ OperationResult::Refused { reason } => ("XX", reason),
+ OperationResult::Conflicted { detail } => ("<>", detail),
+ OperationResult::Failed { error } => ("XX", error),
+ };
+ let _ = writeln!(out, " [{marker}] {}: {detail}", op.kind);
+ }
+ }
+ }
+
+ out.push('\n');
+ if attention.is_empty() && s.last_cycle.as_ref().is_none_or(|c| c.error.is_none()) {
+ out.push_str(if s.cycles == 0 {
+ "No cycle has finished yet.\n"
+ } else {
+ "Nothing needs attention.\n"
+ });
+ } else {
+ let _ = writeln!(
+ out,
+ "{} need{} attention.",
+ super::plural(attention.len(), "table"),
+ if attention.len() == 1 { "s" } else { "" }
+ );
+ }
+ out
+}
+
+#[cfg(all(test, feature = "metrics"))]
+mod tests {
+ use super::*;
+ use crate::plan::{OperationKind, OperationOutcome, TableOutcome};
+ use crate::sched::{CycleRecord, DaemonStatus, TableStatus};
+
+ fn at(h: u32, m: u32) -> chrono::DateTime {
+ use chrono::TimeZone;
+ chrono::Utc.with_ymd_and_hms(2026, 11, 20, h, m, 0).unwrap()
+ }
+
+ fn entry(name: &str, result: OperationResult, notes: Vec) -> TableStatus {
+ TableStatus {
+ cycle: 3,
+ at: at(9, 0),
+ outcome: TableOutcome {
+ table: TableRef::new("prod", ["db"], name),
+ matched_rule: "prod.**".into(),
+ notes,
+ operations: vec![OperationOutcome {
+ kind: OperationKind::Compact,
+ reason: "small files".into(),
+ result,
+ duration: std::time::Duration::ZERO,
+ }],
+ },
+ }
+ }
+
+ #[test]
+ fn what_needs_attention_is_printed_before_what_went_fine() {
+ // The table order on the board is alphabetical; the output must not
+ // be, or a refusal on `z` scrolls below a hundred healthy tables.
+ let status = DaemonStatus {
+ started_at: at(8, 0),
+ cycles: 3,
+ running: None,
+ next: None,
+ last_cycle: Some(CycleRecord {
+ number: 3,
+ trigger: "interval".into(),
+ finished_at: at(9, 0),
+ summary: Some("2 tables, 1 operations succeeded in 4s".into()),
+ error: None,
+ deferred: vec![],
+ }),
+ tables: vec![
+ entry(
+ "a",
+ OperationResult::Succeeded {
+ detail: "12 files into 1".into(),
+ },
+ vec![],
+ ),
+ entry(
+ "z",
+ OperationResult::Refused {
+ reason: "cross-spec rewrite".into(),
+ },
+ vec![],
+ ),
+ ],
+ };
+ let text = status_text(&status, at(9, 30));
+ let refused = text.find("cross-spec rewrite").expect(&text);
+ let fine = text.find("12 files into 1").expect(&text);
+ assert!(refused < fine, "{text}");
+ assert!(text.contains("needs attention\n prod.db.z"), "{text}");
+ assert!(text.ends_with("1 table needs attention.\n"), "{text}");
+ assert!(status.needs_attention());
+ }
+
+ #[test]
+ fn a_failed_cycle_is_reported_even_with_no_table_in_trouble() {
+ let status = DaemonStatus {
+ started_at: at(8, 0),
+ cycles: 1,
+ running: None,
+ next: None,
+ last_cycle: Some(CycleRecord {
+ number: 1,
+ trigger: "interval".into(),
+ finished_at: at(8, 1),
+ summary: None,
+ error: Some("catalog unreachable".into()),
+ deferred: vec![],
+ }),
+ tables: vec![],
+ };
+ let text = status_text(&status, at(8, 2));
+ assert!(text.contains("FAILED: catalog unreachable"), "{text}");
+ assert!(!text.contains("Nothing needs attention"), "{text}");
+ assert!(status.needs_attention());
+ }
+}
diff --git a/src/obs/serve.rs b/src/obs/serve.rs
index 2733e7f..dd1a5f2 100644
--- a/src/obs/serve.rs
+++ b/src/obs/serve.rs
@@ -1,8 +1,9 @@
-//! Serving metrics and health over HTTP.
+//! Serving metrics, health and status over HTTP.
//!
-//! Two handlers and no router extras. A maintenance engine's HTTP surface
-//! should be the smallest thing that a scrape and a liveness probe can talk to
-//! — anything more is a second product hiding inside the first.
+//! Read-only handlers and no router extras. A maintenance engine's HTTP surface
+//! should be the smallest thing that a scrape, a liveness probe and an operator
+//! asking "what needs me?" can talk to — anything more is a second product
+//! hiding inside the first.
use std::net::SocketAddr;
use std::sync::Arc;
@@ -15,13 +16,23 @@ use axum::routing::get;
use crate::error::{Error, Result};
use crate::obs::Metrics;
+use crate::sched::StatusBoard;
-/// Build the router.
-pub fn router(metrics: Arc) -> Router {
+/// Build the router: `/metrics`, `/health` and `/status`.
+///
+/// `/status` names tables and carries the text of their refusals and errors —
+/// the same content the daemon prints to its own output, and nothing that
+/// causes work. Bind it where you would let someone read the daemon's logs.
+pub fn router(metrics: Arc, status: StatusBoard) -> Router {
Router::new()
.route("/metrics", get(scrape))
.route("/health", get(health))
.with_state(metrics)
+ .merge(
+ Router::new()
+ .route("/status", get(serve_status))
+ .with_state(status),
+ )
}
/// The token `POST /events` must present, when one is configured.
@@ -96,18 +107,15 @@ struct EventState {
/// default, so the choice is made rather than inherited.
pub fn router_with_events(
metrics: Arc,
+ status: StatusBoard,
events: crate::sched::Events,
token: Option,
) -> Router {
- Router::new()
- .route("/metrics", get(scrape))
- .route("/health", get(health))
- .with_state(metrics)
- .merge(
- Router::new()
- .route("/events", axum::routing::post(receive_event))
- .with_state(EventState { events, token }),
- )
+ router(metrics, status).merge(
+ Router::new()
+ .route("/events", axum::routing::post(receive_event))
+ .with_state(EventState { events, token }),
+ )
}
/// Bergman's own notification shape: which table changed.
@@ -289,12 +297,18 @@ async fn health() -> impl IntoResponse {
(StatusCode::OK, "ok")
}
+/// What the daemon is doing, and what each table last said, as JSON.
+async fn serve_status(State(status): State) -> impl IntoResponse {
+ axum::Json(status.snapshot())
+}
+
/// Serve until `shutdown` resolves.
///
/// With `events`, `/events` is served too.
pub async fn serve(
addr: SocketAddr,
metrics: Arc,
+ status: StatusBoard,
events: Option,
token: Option,
shutdown: impl Future