diff --git a/Cargo.lock b/Cargo.lock index cb65b29..0903d89 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -239,7 +239,7 @@ dependencies = [ "percent-encoding", "pin-project-lite", "rustls", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-rustls", "tower-service", @@ -254,7 +254,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b16f85a1fdbc2deb5c705001a1d8ec4c05934175262a62664e634bd09043fde0" dependencies = [ "base64 0.23.1", - "thiserror", + "thiserror 2.0.20", "tokio", ] @@ -283,7 +283,7 @@ dependencies = [ "regex", "rustls", "serde", - "thiserror", + "thiserror 2.0.20", "toml", "zeroize", ] @@ -301,7 +301,7 @@ dependencies = [ "rustls", "serde", "socket2 0.5.10", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-util", "tracing", @@ -326,7 +326,7 @@ dependencies = [ "libc", "rustls", "subtle", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-util", "tracing", @@ -344,7 +344,7 @@ dependencies = [ "fancy-regex", "regex", "serde", - "thiserror", + "thiserror 2.0.20", "toml", "tracing", ] @@ -365,7 +365,7 @@ dependencies = [ "once_cell", "sha2", "subtle", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-util", "tracing", @@ -380,7 +380,7 @@ dependencies = [ "bytes", "eggress-core", "subtle", - "thiserror", + "thiserror 2.0.20", "tokio", "zeroize", ] @@ -409,7 +409,7 @@ dependencies = [ "regex", "serde", "serde_json", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-util", "tracing", @@ -428,7 +428,7 @@ dependencies = [ "serde", "serde_json", "tempfile", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-rustls", "toml", @@ -444,7 +444,7 @@ dependencies = [ "eggress-core", "pkcs8", "rustls", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-rustls", "tracing", @@ -465,7 +465,7 @@ dependencies = [ "ipnet", "rand", "serde", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-util", "tracing", @@ -478,7 +478,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0703337615177ae5533a7e222d291c5fdf95201c0ce896859968f94f435975eb" dependencies = [ "serde", - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -500,7 +500,7 @@ dependencies = [ "hyper-util", "rustix", "rustls", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-rustls", ] @@ -578,7 +578,7 @@ dependencies = [ "rustls", "serde", "serde_json", - "thiserror", + "thiserror 2.0.20", "tokio", "url", ] @@ -591,7 +591,7 @@ dependencies = [ "serde", "serde_json", "sha2", - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -606,7 +606,7 @@ dependencies = [ "serde", "serde_json", "tempfile", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-util", ] @@ -630,6 +630,7 @@ dependencies = [ name = "eggwork-server" version = "0.1.5" dependencies = [ + "async-trait", "base64 0.22.1", "bytes", "eggfetch-core", @@ -642,6 +643,7 @@ dependencies = [ "eggwork-runner", "fs2", "futures-util", + "gregg-protocol", "hex", "rcgen", "rusqlite", @@ -652,10 +654,11 @@ dependencies = [ "serde_json", "sha2", "tempfile", - "thiserror", + "thiserror 2.0.20", "tokio", "tokio-util", "toml", + "url", "uuid", ] @@ -881,6 +884,17 @@ dependencies = [ "r-efi", ] +[[package]] +name = "gregg-protocol" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d3a817ba61881543ccc89622df17707f3f065a9d6f1b06d31ab50ac9602f051" +dependencies = [ + "serde", + "serde_json", + "thiserror 1.0.69", +] + [[package]] name = "h2" version = "0.4.19" @@ -1169,7 +1183,7 @@ checksum = "4cca98e95f35b29d469dade6724c6f96cec9236640f745a0e99b0334ec320ab1" dependencies = [ "enumflags2", "libc", - "thiserror", + "thiserror 2.0.20", ] [[package]] @@ -1758,13 +1772,33 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] diff --git a/architecture/client-transport.md b/architecture/client-transport.md index 50e52f3..dcba970 100644 --- a/architecture/client-transport.md +++ b/architecture/client-transport.md @@ -179,6 +179,8 @@ with `finish_non_exhaustive()`. | `download_artifact(&artifact)` | GET | `/v1/artifacts/{artifact.artifact_id}` | — | `BoxBytesStream` | | `create_workspace(&workspace_id, &handle, &manifest)` | POST | `/v1/workspaces` | `{schema_version, workspace_id, handle, manifest}` | `WorkspaceReady` | | `create_workspace_derived(&workspace_id, &handle, &base_manifest_digest, &patch)` | POST | `/v1/workspaces/derive` | `{schema_version, workspace_id, handle, patch}` | `WorkspaceReady` | +| `telemetry()` | GET | `/v1/node/telemetry` | — | `NodeTelemetry` | +| `telemetry_for(&node_id)` | GET | `/v1/node/telemetry` | — | `NodeTelemetry` (node id must match) | Prose notes on the non-obvious ones: @@ -198,6 +200,14 @@ Prose notes on the non-obvious ones: `eggwork-artifact-id` and `eggwork-artifact-digest` to equal the requested record's. A missing, unparseable, or mismatched header is `InvalidResponse` and the body is not handed back. These are the anti-mixup checks that make a content-addressed transfer trustworthy across a stream. +- **`telemetry` is the optional host-observation read.** It is a `GET` on the node's own cache; the + node never contacts its provider because of a remote read. The response is validated on arrival: + the body must be within 64 KiB, the `schema_version` must be the known one, the `state` and + `observation` must agree, and every measurement must satisfy the domain's range rules. A `404` — a + node that predates the contract — is `ClientError::TelemetryUnsupported`, which is distinct from the + `403` an unauthorized principal receives and from the `state: "unavailable"` a failing provider + produces. `telemetry_for` additionally refuses a response naming a different node, so a + fixed-target caller cannot be handed a measurement taken somewhere else. - **`create_workspace_derived` performs a local consistency check first:** if `patch.base_manifest_digest != *base_manifest_digest` it returns `InvalidResponse` without sending anything. The base digest travels only inside the patch, so this is a caller-argument @@ -385,6 +395,7 @@ makes a foreign base look *missing* (`409 base_manifest_missing`) rather than *f | `InvalidResponse` | `node response was malformed` | Response did not match the expected contract (see below). | Caller's judgement; usually a hard stop for that response. | Nothing beyond the variant. | | `ProtocolIncompatible` | `node protocol is incompatible` | `ensure_protocol_compatible`: the node's `[min, max]` does not contain `1.0`. | No — retrying the same node cannot help. | Nothing; the node's actual range is not carried. | | `UnsupportedCapability` | `node does not support a required protocol capability` | Node does not advertise `exec.argv.v1`. | No. | Nothing; the advertised feature list is not carried. | +| `TelemetryUnsupported` | `node does not implement the node telemetry contract` | `GET /v1/node/telemetry` answered 404: the node predates the contract. | No. | Nothing. | `InvalidResponse` is produced in every one of these situations: `serde_json::from_slice` failure on a response body; `serde_json::to_vec` failure on a request body; a missing, unparseable, or @@ -395,6 +406,13 @@ blob upload; an NDJSON partial line exceeding `eggwork_core::MAX_EVENT_BYTES`; a and an `ExecutionEvent` that fails `validate()`. Note the last-but-one category is **local**: the `create_workspace_derived` base-digest mismatch is detected before any request is sent. +The telemetry read adds its own refusals: a body over 64 KiB, a `schema_version` the client does not +know (`ProtocolIncompatible`, not `InvalidResponse` — the node speaks a different version of this +contract), a `state` that contradicts the presence of an observation, a measurement outside the +domain's range, a `node_id` that is not the one the caller asked for, and a source the client does not +know. A `404` is `TelemetryUnsupported`, not `InvalidResponse`: it means the node has no such route, +not that the route answered badly. + **Redaction.** `impl fmt::Debug for ClientError` is hand-written: `Transport` prints `ClientError::Transport([REDACTED])`, and `Api` prints `status` and `code` but renders `message` as `"[REDACTED]"`. The `#[error("node returned HTTP {status}: {code}")]` display string omits diff --git a/architecture/protocol.md b/architecture/protocol.md index 40ebff7..eff401d 100644 --- a/architecture/protocol.md +++ b/architecture/protocol.md @@ -5,3 +5,91 @@ The core data model is protocol-neutral. Later control-plane work will define ve See the [control-plane roadmap](../plans/subsystems/control-plane-protocol-roadmap.md) and [ADR-0002](../plans/adrs/ADR-0002-eggstack-transport-and-mtls.md). Component deep dives: [server-node.md](server-node.md) (node side of the wire contract) and [client-transport.md](client-transport.md) (client side). Overview: [overview.md](overview.md). + +## The node telemetry wire contract (schema version 1) + +`GET /v1/node/telemetry` returns a `NodeTelemetry` document. This is the **frozen** +contract for the optional host-telemetry projection, and the reference for the +downstream CodeGG worker-telemetry consumer. + +```json +{ + "schema_version": 1, + "node_id": "worker-01", + "source": "gregg", + "state": "ready", + "age_ms": 231, + "last_error": null, + "observation": { + "observed_at_unix_ms": 1729460000123, + "sample_interval_ms": 1000, + "cpu": { "value": { "logical_cores": 8, "usage_pct": 12.5, "iowait_pct": 1.5 } }, + "memory": { "value": { "available_bytes": 4000000, "total_bytes": 8000000, "used_bytes": 4000000 } }, + "load": { "value": { "one": 0.5, "five": 0.25, "fifteen": 0.125 } }, + "swap": "unsupported", + "disk": { "value": { "available_bytes": 900, "total_bytes": 1000, "volume_count": 1 } }, + "disk_io": { "value": { "read_bytes_per_sec": 11, "write_bytes_per_sec": 22 } }, + "network": { "value": { "rx_bytes_per_sec": 33, "tx_bytes_per_sec": 44 } } + } +} +``` + +### Fields + +| Field | Type | Meaning | +| --- | --- | --- | +| `schema_version` | `1` | The contract version. A reader refuses any other value rather than guessing. Additive changes stay within version 1. | +| `node_id` | string | The node that produced the observation. | +| `source` | `"gregg"` | The kind of provider the measurement came from. The set is closed; an unknown source is refused. | +| `state` | enum | What the *provider* is doing. See below. | +| `age_ms` | number or null | How long ago, in milliseconds, the node received the observation, measured on the node's monotonic clock. `null` when there is no observation. | +| `last_error` | enum or null | The bounded category of the most recent provider failure. `null` when the last interaction succeeded or none has failed. | +| `observation` | object or null | The most recent measurement the node holds. `null` when it holds none. | + +### Provider states + +`state` describes the provider, never the host. A node with no provider is +`disabled`, which is not a host with zero usage. + +| `state` | `observation` | Meaning | +| --- | --- | --- | +| `disabled` | absent | No provider is configured. The node claims no host measurements. | +| `warming` | absent | The provider is alive but has not produced a sample yet. | +| `ready` | present | A sample is present and within its freshness bound. | +| `stale` | present | A sample is present but older than the freshness bound. | +| `unavailable` | present or absent | The provider could not be reached. | +| `invalid` | present or absent | The provider answered with something unusable. | + +A sample is **current only when the state is `ready`**. A reader that needs a +fresh measurement must check the state, not merely the presence of an +observation. `unavailable` and `invalid` may still carry the last sample the +node took; `age_ms` says how old it is. + +### Measurement groups + +Each measurement group is one of: + +| Form | Meaning | +| --- | --- | +| `{ "value": { ... } }` | A validated measurement. | +| `"unsupported"` | The host platform cannot produce this measurement. | +| `"unknown"` | The measurement is supported, but this sample carried no value. | + +A missing measurement is **never zero**. A reader can tell "this host has no +swap" apart from "this host has swap and it is currently unused". + +The groups are `cpu` (logical cores, busy percentage, optional I/O-wait +percentage), `memory` (available/total/used bytes), `load` (one/five/fifteen +minute load averages), `swap` (used/total bytes), `disk` (aggregate capacity +across the volumes the provider reported, with no mount path), `disk_io` +(aggregate read/write throughput), and `network` (aggregate receive/transmit +throughput). + +### What the contract deliberately does not carry + +No provider address, no mount path, no device or interface identity, no +hostname, no per-execution measurement, and no raw provider JSON. The node's +own `NodeStatus` and `NodeCapabilities` are unchanged: they answer "is this +node accepting work", and this document answers "what did this host look +like". The two are never merged, and nothing in this contract qualifies an +execution. diff --git a/architecture/server-node.md b/architecture/server-node.md index 9329266..9a7314f 100644 --- a/architecture/server-node.md +++ b/architecture/server-node.md @@ -53,6 +53,7 @@ node-facing control plane defined here. | `max_active_executions` | `u32` | Must be `> 0` and `<= Semaphore::MAX_PERMITS`, else `InvalidLimit` (`lib.rs:302-306`). | | `lease_ttl` | `Duration` | Must be non-zero, else `InvalidLease` (`lib.rs:312-314`). | | `tls` | `TlsServerConfig` | Must have `ClientAuthMode::Required` and a default identity, else `TlsPolicy`. | +| `host_telemetry` | `Option` | Optional provider. `None` means no provider, no polling task, and no host measurements. | `NodeStartError` (`lib.rs:140-152`) has five variants: `TlsPolicy`, `EggServe(String)`, `InvalidLimit`, `InvalidLease`, `AlreadyRunning`. @@ -770,6 +771,95 @@ resources behind a 403 (authorization precedes resolution, and observe/control/e single 404 for both "absent" and "not yours"). `secret_sentinels_stay_out_of_error_and_debug_surfaces` (`lib.rs:6104`) is the executable guard for the first two. +## The node telemetry read route + +`GET /v1/node/telemetry` is the one bounded read route that projects the +optional host telemetry. It is a *read* of the node's own cache: it never +contacts the provider, so a burst of readers cannot become a burst of provider +requests, and a provider that is down does not turn a read into a timeout. + +The route maps to `Operation::Telemetry` and is authorized by a **narrow, +separate grant**: the `telemetry` operation name in a client's grant list. It +is deliberately not folded into `status`. `status` answers "is this node +accepting work"; telemetry answers "what did this host look like", and folding +the second into the first would silently widen every principal that already +holds a status grant. A principal that is not granted `telemetry` receives the +existing typed 403 with no detail about whether the node holds an observation. + +A node that predates this contract has no such route and answers 404. The +client maps that to a distinct "unsupported" outcome, so "this node cannot +serve telemetry" is distinguishable from "this principal may not read +telemetry" and from "the provider is down". + +The response is the frozen `NodeTelemetry` document described in +[protocol.md](protocol.md#the-node-telemetry-wire-contract-schema-version-1). +The projection itself is `node_telemetry` (`lib.rs`), which reads the M001 +cache and copies its snapshot; it adds no measurement of its own and performs +no validation the client would not also perform. + +`crates/eggwork-server/src/telemetry.rs` is an **optional, default-off** sibling of the control plane. It +owns the outbound half of the node: reading host-wide measurements from a telemetry provider on the same +machine. It is the only place in the server that makes an outbound HTTP request, and it makes exactly one +kind of request — a `GET` to a configured loopback status endpoint. + +**What it is not.** It is not a scheduler, not a sampler of the node's own executions, and not an input to +admission. Nothing it observes qualifies, withholds, or changes an execution capability; `NodeStatus` and +`NodeCapabilities` keep their existing meaning, and a node with the provider disabled is a node with no +telemetry — not a node with zero usage. + +**The provider seam.** `HostTelemetryProvider` is a one-method trait (`observe() -> Result`). `ProviderOutcome` is either an `Observed(HostTelemetry)` or `Warming`. One implementation +exists: `GreggTelemetryProvider`, which reads a local Gregg daemon's `/v2/status`. The seam exists so the +polling owner can be driven by a fake in tests and so a second provider could be added without touching the +cache or the node lifecycle. + +**Provider vocabulary stops at the module boundary.** The provider's wire types (`gregg_protocol::v2`) are +read, validated by the provider's own `validate_payload_v2`, and translated into +`eggwork_core::HostTelemetry` — a protocol-neutral vocabulary with no Gregg types in it. The translation +keeps only host-wide aggregates: CPU cores and utilization, physical memory, load, swap, storage capacity +(summed across the reported volumes, with no mount path), aggregate disk and network throughput, and the +provider's own timestamp and sample interval. Drive names, device identities, interface identities, and +the provider's system identity are dropped in `normalize` and never leave the node. + +**A missing measurement is never zero.** Each measurement group is a `TelemetryMetric` that is either +`Value(T)`, `Unsupported` (the platform cannot produce it), or `Unknown` (it can, but this sample carried +none). The provider's capability flags decide `Unsupported` vs `Unknown`; the translation never +substitutes `0.0` for an absent measurement. + +**The endpoint is validated once, at load time.** `validate_endpoint` accepts only plain `http`, an IP +literal that is a loopback address, an explicit TCP port, and exactly the path `/v2/status` — no userinfo, +query, or fragment. A hostname, `localhost` included, is refused, so no name is ever resolved and no DNS +answer can be rebound between validation and use. The alternative spellings of an IPv4 address +(`127.0.0.1.`, `2130706433`, `0x7f000001`, `127.1`) are canonicalized by the URL parser to the literal +address, so the endpoint the client is finally given names the address literally. + +**Why the client is built the way it is.** The provider client is an Eggfetch client with +`standard-http1` and *without* the `redirects` and `proxy` features. A `3xx` is therefore returned +unfollowed and reported as an unexpected status, and no ambient `HTTP_PROXY` setting is consulted. Neither +a redirect hop nor an inherited proxy can move the request off the loopback interface. The decoded body is +capped at 256 KiB, the connect deadline is 2 s, and the whole request is bounded at 5 s. + +**One owner polls.** `TelemetryMonitor::start` spawns exactly one task that performs every provider +request. Readers consult `TelemetryCache`; they never trigger a request, so a burst of callers cannot +become a burst of provider requests. The first attempt happens as soon as the node is running — waiting a +whole interval before the first sample would make a freshly started node look empty for no reason. After +that the cadence is the configured interval, and consecutive failures back off (15 s → 30 s → 60 s, capped +at 5 minutes) so an absent provider is not polled in a tight loop. `TelemetryMonitor::disabled()` creates +no task at all. + +**Freshness is measured monotonically.** The cache records the *reception* instant on the node's monotonic +clock, so a wall-clock adjustment cannot make a stale sample look fresh. The provider's own wall-clock +timestamp is kept as provenance and is checked against a 30 s skew tolerance: a timestamp implausibly in +the future is refused (`ClockSkew`) rather than treated as indefinitely fresh. A sample that is already +older than the freshness bound — when it arrives, or once the node's copy has aged out — is reported as +`Stale`, not as `Ready`. + +**Failures are typed and bounded.** `TelemetryError` maps onto a closed set of +`TelemetryErrorCategory` values (connection, timeout, HTTP status, malformed, schema version, invalid, too +large, clock skew). No response body, provider URL, or host path is carried into a category, a log line, or +a metric. The `doctor` check reports whether the provider is configured but never contacts it and never +echoes its address: a node whose provider happens to be down is still a healthy node. + ## Invariants and enforcement | Invariant | Enforcement site | Test | @@ -802,6 +892,10 @@ single 404 for both "absent" and "not yours"). `secret_sentinels_stay_out_of_err | Secrets never reach error/debug surfaces | redacting `Debug`, hash-only leases (`lib.rs:154`, `1659`) | `tls_configuration_diagnostics_redact_certificate_paths` (3083), `secret_sentinels_stay_out_of_error_and_debug_surfaces` (6104) | | Required isolation is enforced, not merely requested | landlock admission + E2E denial (`lib.rs:613`, `606`) | `required_landlock_is_admitted_remotely_and_denies_outside_workspace_access` (4699), `required_landlock_denies_outside_writes_and_confines_descendants` (4846) | | Hostile workspace manifests cause no side effect | `WorkspaceError` mapping (`lib.rs:1083-1107`) | `hostile_workspace_manifests_are_rejected_without_side_effect` (6008) | +| With no provider configured the node claims no host measurements | `TelemetryMonitor::disabled()` creates no task; cache reports `Disabled` | `a_disabled_monitor_never_polls` (`tests/host_telemetry.rs`), `a_configuration_without_host_telemetry_asks_for_none` (`operations.rs`) | +| The provider endpoint cannot be moved off the loopback interface | `validate_endpoint` (IP literal, explicit port, fixed path, plain HTTP) + a client with no redirect or proxy support | `a_non_loopback_or_ambiguous_endpoint_is_refused`, `a_redirect_is_not_followed` | +| One provider request per poll, regardless of reader count | one owner task; readers read the cache | `one_owner_polls_for_every_reader` | +| A missing measurement is never reported as zero | `TelemetryMetric::{Unsupported, Unknown, Value}` | `an_unsupported_capability_is_not_reported_as_a_missing_value` | ## Test coverage diff --git a/crates/eggwork-client/src/lib.rs b/crates/eggwork-client/src/lib.rs index aff1032..d62a4a6 100644 --- a/crates/eggwork-client/src/lib.rs +++ b/crates/eggwork-client/src/lib.rs @@ -8,8 +8,8 @@ use eggfetch_core::{ }; use eggwork_core::{ ApiError, ArtifactId, ArtifactRecord, BlobDigest, ExecutionEvent, ExecutionHandle, ExecutionId, - ExecutionSnapshot, ExecutionSpec, NodeCapabilities, NodeStatus, WorkspaceId, WorkspaceManifest, - WorkspaceManifestPatch, + ExecutionSnapshot, ExecutionSpec, NodeCapabilities, NodeId, NodeStatus, NodeTelemetry, + WorkspaceId, WorkspaceManifest, WorkspaceManifestPatch, }; use futures_util::{StreamExt, stream}; use serde::{Serialize, de::DeserializeOwned}; @@ -30,6 +30,16 @@ const API_SCHEMA_VERSION: u16 = 1; /// while still refusing to accumulate unbounded node-controlled data. const MAX_BUFFERED_BODY_BYTES: usize = 16 * 1024 * 1024; +/// Ceiling on a node telemetry response body. +/// +/// The telemetry response is a small, bounded document — a schema version, a +/// node id, a state, and at most seven measurement groups. The transport cap +/// (`MAX_BUFFERED_BODY_BYTES`) bounds what the client will *accumulate*; this +/// cap bounds what the client will *accept* for this route, so a node that +/// answers with a megabyte of measurement-shaped JSON is refused rather than +/// parsed. +const MAX_TELEMETRY_BODY_BYTES: usize = 64 * 1024; + /// Time allowed for a pool slot, the connect/TLS handshake, each request-body /// frame, and each *gap* between response chunks. /// @@ -80,6 +90,8 @@ pub enum ClientError { ProtocolIncompatible, #[error("node does not support a required protocol capability")] UnsupportedCapability, + #[error("node does not implement the node telemetry contract")] + TelemetryUnsupported, } impl From for ClientError { @@ -120,6 +132,7 @@ impl fmt::Debug for ClientError { Self::InvalidResponse => f.write_str("ClientError::InvalidResponse"), Self::ProtocolIncompatible => f.write_str("ClientError::ProtocolIncompatible"), Self::UnsupportedCapability => f.write_str("ClientError::UnsupportedCapability"), + Self::TelemetryUnsupported => f.write_str("ClientError::TelemetryUnsupported"), } } } @@ -213,6 +226,74 @@ impl NodeClient { self.get_json("/v1/status").await } + /// Read the node's host-wide telemetry observation. + /// + /// The node serves this from its own cache. A remote read never contacts + /// the telemetry provider, so a burst of readers cannot become a burst of + /// provider requests, and a provider that is down does not turn a read into + /// a timeout. + /// + /// The three states a caller most often needs to tell apart are + /// distinguishable without parsing prose: + /// + /// * the node has no provider configured — the response's `state` is + /// `disabled`; + /// * the node's provider is failing — the response's `state` is + /// `unavailable` and `last_error` carries the bounded category; + /// * the node does not implement this contract at all — the call fails + /// with [`ClientError::TelemetryUnsupported`]. + /// + /// A node that reports `unavailable` is not reporting zero utilization. + /// The per-measurement groups keep the difference explicit: a measurement + /// the host platform cannot produce is `unsupported`, one that was + /// supported but not reported is `unknown`, and only a real measurement is + /// a value. + pub async fn telemetry(&self) -> Result { + let mut response = self + .http + .get(&self.url("/v1/node/telemetry"))? + .timeout(unary_timeout()) + .send() + .await?; + let status = response.status().as_u16(); + if status == 404 { + // The node does not have the route at all. That is a node older + // than this contract, and it is not the same answer as a node + // that has the route and refuses the caller. + return Err(ClientError::TelemetryUnsupported); + } + if !response.status().is_success() { + return Err(api_error(status, &mut response).await); + } + let bytes = response.bytes().await?; + if bytes.len() > MAX_TELEMETRY_BODY_BYTES { + return Err(ClientError::InvalidResponse); + } + let telemetry: NodeTelemetry = + serde_json::from_slice(&bytes).map_err(|_| ClientError::InvalidResponse)?; + if telemetry.schema_version != eggwork_core::NODE_TELEMETRY_SCHEMA_VERSION { + return Err(ClientError::ProtocolIncompatible); + } + telemetry + .validate() + .map_err(|_| ClientError::InvalidResponse)?; + Ok(telemetry) + } + + /// Read the node's host-wide telemetry observation and require it to name + /// `expected`. + /// + /// A node is a fixed target, so a response naming a different node is a + /// misdirected or substituted answer. This refuses it rather than handing + /// the caller a measurement taken somewhere else. + pub async fn telemetry_for(&self, expected: &NodeId) -> Result { + let telemetry = self.telemetry().await?; + if &telemetry.node_id != expected { + return Err(ClientError::InvalidResponse); + } + Ok(telemetry) + } + /// Submit to this node and return its execution identifier and live event stream. /// A dropped stream leaves execution running; cancellation is explicit. pub async fn execute( diff --git a/crates/eggwork-core/src/lib.rs b/crates/eggwork-core/src/lib.rs index dfa3197..d65c8f8 100644 --- a/crates/eggwork-core/src/lib.rs +++ b/crates/eggwork-core/src/lib.rs @@ -1103,6 +1103,422 @@ pub struct NodeStatus { pub capabilities: NodeCapabilities, } +// --------------------------------------------------------------------------- +// Optional host telemetry +// --------------------------------------------------------------------------- +// +// These types are the *normalized* vocabulary for host-wide measurements. They +// are deliberately protocol-neutral: no provider's wire types, field names or +// collection shapes appear here, and nothing in this module knows how a +// measurement was obtained. A provider-specific payload is validated and +// translated into these types before it is cached, so the vocabulary can be +// projected onto a wire contract without dragging a provider's schema along. +// +// Host telemetry is advisory observation, never enforcement evidence. Nothing +// in this module grants, withholds, or qualifies an execution capability, and +// `NodeStatus`/`NodeCapabilities` keep their existing meaning. + +/// Ceiling on the accepted sampling cadence of a host observation. +/// +/// Mirrors the bound the provider protocol applies, so a payload that the +/// provider itself would reject is rejected here too. +pub const MAX_TELEMETRY_SAMPLE_INTERVAL_MS: u64 = 86_400_000; + +/// Where a host-wide observation came from. +/// +/// The set is closed on purpose: an unrecognized source is a protocol error +/// for a reader, not a new variant it may silently accept. Adding a source +/// means adding a variant here and re-freezing the wire contract. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TelemetrySource { + /// Readings come from a locally installed Gregg daemon. + Gregg, +} + +/// Lifecycle state of the optional host-telemetry provider. +/// +/// The state describes the *provider*, not the host. A provider that is +/// `Disabled` is not a host with zero usage; it is a host with no provider. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TelemetryProviderState { + /// No provider is configured. Nothing is polled and nothing is claimed. + Disabled, + /// A provider is configured but has not produced an observation yet. + Warming, + /// A validated observation is available and within its freshness bound. + Ready, + /// An observation is available but older than the freshness bound. + Stale, + /// The provider could not be reached, or answered with something unusable. + Unavailable, + /// The provider answered with a payload that failed validation. + Invalid, +} + +/// Why the last provider interaction failed. +/// +/// Categories are a closed, bounded set and carry no provider-supplied text, so +/// a failure can be reported without leaking a response body, a URL, or a host +/// path into a response, a log line, or a metric. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TelemetryErrorCategory { + /// The connection could not be established. + Connection, + /// The request exceeded its deadline. + Timeout, + /// The provider answered with an unexpected HTTP status. + HttpStatus, + /// The response body was not the expected JSON document. + Malformed, + /// The response carried an unsupported schema version. + SchemaVersion, + /// The response parsed but violated the protocol's invariants. + Invalid, + /// The response exceeded the accepted body size. + TooLarge, + /// The observation timestamp is outside the accepted clock-skew window. + ClockSkew, +} + +/// One host-wide measurement, together with the reason it is absent. +/// +/// A missing measurement is never zero. `Unsupported` means the host platform +/// cannot produce the metric at all; `Unknown` means it can but this sample +/// carried no value; `Value` carries a validated measurement. A reader can +/// therefore tell "this host does not have swap" apart from "this host has +/// swap and it is currently unused". +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TelemetryMetric { + /// The host platform does not support this measurement. + Unsupported, + /// The measurement is supported, but this sample carried no value. + Unknown, + /// A validated measurement. + Value(T), +} + +impl TelemetryMetric { + /// The measured value, or `None` when the metric is absent. + pub fn value(&self) -> Option<&T> { + match self { + Self::Value(value) => Some(value), + Self::Unsupported | Self::Unknown => None, + } + } + + /// Whether the host platform does not support this measurement. + pub fn is_unsupported(&self) -> bool { + matches!(self, Self::Unsupported) + } + + /// Whether the measurement is supported but was not reported. + pub fn is_unknown(&self) -> bool { + matches!(self, Self::Unknown) + } +} + +/// CPU utilization for the host as a whole. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TelemetryCpu { + /// Logical CPU cores visible to the kernel. + pub logical_cores: u32, + /// Aggregate CPU busy percentage, `0.0..=100.0`. + pub usage_pct: f32, + /// Aggregate CPU I/O-wait percentage, `0.0..=100.0`. + /// + /// `None` when the host platform does not report I/O wait. It is never + /// `Some(0.0)` as a substitute for "not reported". + #[serde(default, skip_serializing_if = "Option::is_none")] + pub iowait_pct: Option, +} + +/// Physical memory utilization for the host as a whole. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TelemetryMemory { + /// Bytes available without swapping. + pub available_bytes: u64, + /// Total physical memory in bytes. + pub total_bytes: u64, + /// Bytes currently resident in physical memory. + pub used_bytes: u64, +} + +/// Load averages for the host as a whole. +/// +/// These are load averages, not percentages: they are unbounded above and are +/// only required to be finite and non-negative. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TelemetryLoad { + /// One-minute load average. + pub one: f32, + /// Five-minute load average. + pub five: f32, + /// Fifteen-minute load average. + pub fifteen: f32, +} + +/// Swap utilization for the host as a whole. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TelemetrySwap { + /// Bytes currently in swap. + pub used_bytes: u64, + /// Total swap in bytes. + pub total_bytes: u64, +} + +/// Storage capacity for the host as a whole. +/// +/// The figures are aggregates over every volume the provider reported. They +/// are not a per-volume claim, and they carry no mount path, device +/// identifier, or filesystem label. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TelemetryDisk { + /// Free bytes across the reported volumes. + pub available_bytes: u64, + /// Total bytes across the reported volumes. + pub total_bytes: u64, + /// How many volumes contributed to the aggregate. + pub volume_count: u32, +} + +/// Aggregate disk throughput for the host as a whole. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TelemetryDiskIo { + /// Aggregate read throughput in bytes per second. + pub read_bytes_per_sec: u64, + /// Aggregate write throughput in bytes per second. + pub write_bytes_per_sec: u64, +} + +/// Aggregate network throughput for the host as a whole. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TelemetryNetwork { + /// Aggregate receive throughput in bytes per second. + pub rx_bytes_per_sec: u64, + /// Aggregate transmit throughput in bytes per second. + pub tx_bytes_per_sec: u64, +} + +/// One validated host-wide observation. +/// +/// The observation is a *measurement*, not a verdict: it says what the host +/// looked like at `observed_at_unix_ms`, and it never says whether an +/// execution may run. Per-execution utilization is not representable here. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HostTelemetry { + /// Provider wall-clock timestamp of the sample, in Unix milliseconds. + pub observed_at_unix_ms: u64, + /// Provider sampling cadence in milliseconds. + pub sample_interval_ms: u64, + /// CPU utilization. + pub cpu: TelemetryMetric, + /// Physical memory utilization. + pub memory: TelemetryMetric, + /// Load averages. + pub load: TelemetryMetric, + /// Swap utilization. + pub swap: TelemetryMetric, + /// Storage capacity. + pub disk: TelemetryMetric, + /// Aggregate disk throughput. + pub disk_io: TelemetryMetric, + /// Aggregate network throughput. + pub network: TelemetryMetric, +} + +/// Wire schema version of the node telemetry response. +/// +/// The contract is additive within version 1: a reader accepts a version-1 +/// payload and refuses a version it does not know, rather than guessing. +pub const NODE_TELEMETRY_SCHEMA_VERSION: u16 = 1; + +/// The node's host-wide telemetry observation, as served to an authorized caller. +/// +/// This is the frozen wire contract for the node telemetry response. It is +/// additive and deliberately separate from +/// [`NodeStatus`]: `NodeStatus` answers "is this node accepting work", and +/// this answers "what did this host look like". The two are never merged, and +/// nothing here qualifies an execution. +/// +/// The fields mean: +/// +/// * `schema_version` — the contract version. A reader refuses anything else. +/// * `node_id` — the node that produced the observation, so a reader can tell +/// that a response came from the node it asked. +/// * `source` — where the measurement came from. The set is closed: a reader +/// refuses a source it does not know. The source names the *kind* of +/// provider; whether that provider is live is `state`'s answer, not this +/// field's. +/// * `state` — what the provider is doing, not what the host is doing. A node +/// with no provider is `disabled`, which is not the same as a host with no +/// usage. +/// * `age_ms` — how long ago, in milliseconds, the node received the +/// observation, measured on the node's monotonic clock. `None` when there is +/// no observation. +/// * `last_error` — the bounded category of the most recent provider failure. +/// `None` when the last interaction succeeded or none has failed. +/// * `observation` — the most recent measurement the node holds, or `None` when +/// it holds none. +/// +/// The `state` and `observation` pair is the part a reader must understand: +/// +/// | `state` | `observation` | meaning | +/// |---|---|---| +/// | `disabled` | absent | no provider is configured | +/// | `warming` | absent | the provider is alive but has not produced a sample | +/// | `ready` | present | a sample is present and within its freshness bound | +/// | `stale` | present | a sample is present but older than the freshness bound | +/// | `unavailable` | present or absent | the provider could not be reached | +/// | `invalid` | present or absent | the provider answered with something unusable | +/// +/// A sample is *current* only when the state is `ready`. A reader that needs a +/// fresh measurement must check the state, not merely the presence of an +/// observation. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NodeTelemetry { + pub schema_version: u16, + pub node_id: NodeId, + pub source: TelemetrySource, + pub state: TelemetryProviderState, + pub age_ms: Option, + pub last_error: Option, + pub observation: Option, +} + +impl NodeTelemetry { + /// Check the invariants of a telemetry response. + /// + /// The node applies this to what it serves, and a client applies it again + /// to what it receives, so a node that skipped it cannot hand a reader a + /// response the reader would have to reject. + pub fn validate(&self) -> Result<(), ValidationError> { + if self.schema_version != NODE_TELEMETRY_SCHEMA_VERSION { + return Err(ValidationError::OutOfRange { + field: "node telemetry schema version", + }); + } + match self.state { + // A ready or stale node always holds the sample it is reporting. + TelemetryProviderState::Ready | TelemetryProviderState::Stale => { + if self.observation.is_none() { + return Err(ValidationError::OutOfRange { + field: "node telemetry observation", + }); + } + } + // A node with no provider, or one that has not sampled yet, holds + // no sample. Reporting one would claim a measurement the node + // never took. + TelemetryProviderState::Disabled | TelemetryProviderState::Warming => { + if self.observation.is_some() { + return Err(ValidationError::OutOfRange { + field: "node telemetry observation", + }); + } + } + // A failed provider may still be holding the last sample it took. + TelemetryProviderState::Unavailable | TelemetryProviderState::Invalid => {} + } + if self.observation.is_some() != self.age_ms.is_some() { + return Err(ValidationError::OutOfRange { + field: "node telemetry age", + }); + } + if let Some(observation) = &self.observation { + observation.validate()?; + } + Ok(()) + } +} + +/// Reject a percentage that is not a finite value in `0.0..=100.0`. +/// +/// A non-finite percentage cannot be serialized as a JSON number, and an +/// out-of-range one is a provider defect rather than a measurement. Both are +/// refused instead of being clamped, because a clamped value is a fabricated +/// measurement. +fn validate_percentage(value: f32, field: &'static str) -> Result<(), ValidationError> { + if !value.is_finite() || !(0.0..=100.0).contains(&value) { + return Err(ValidationError::OutOfRange { field }); + } + Ok(()) +} + +/// Reject a load average that is not a finite, non-negative value. +fn validate_load(value: f32, field: &'static str) -> Result<(), ValidationError> { + if !value.is_finite() || value < 0.0 { + return Err(ValidationError::OutOfRange { field }); + } + Ok(()) +} + +impl HostTelemetry { + /// Check the invariants every consumer of an observation depends on. + /// + /// This is the same check on both sides of the boundary: the node applies + /// it before caching a provider payload, and a client applies it again + /// after decoding, so a node that skips it cannot hand a reader a + /// measurement the reader would have to reject. + pub fn validate(&self) -> Result<(), ValidationError> { + if self.observed_at_unix_ms == 0 { + return Err(ValidationError::OutOfRange { + field: "telemetry observation timestamp", + }); + } + if self.sample_interval_ms == 0 + || self.sample_interval_ms > MAX_TELEMETRY_SAMPLE_INTERVAL_MS + { + return Err(ValidationError::OutOfRange { + field: "telemetry sample interval", + }); + } + if let TelemetryMetric::Value(cpu) = &self.cpu { + if cpu.logical_cores == 0 { + return Err(ValidationError::OutOfRange { + field: "telemetry cpu logical cores", + }); + } + validate_percentage(cpu.usage_pct, "telemetry cpu usage")?; + if let Some(iowait) = cpu.iowait_pct { + validate_percentage(iowait, "telemetry cpu iowait")?; + } + } + if let TelemetryMetric::Value(memory) = &self.memory + && memory.used_bytes > memory.total_bytes + { + return Err(ValidationError::OutOfRange { + field: "telemetry memory used bytes", + }); + } + if let TelemetryMetric::Value(load) = &self.load { + validate_load(load.one, "telemetry load one")?; + validate_load(load.five, "telemetry load five")?; + validate_load(load.fifteen, "telemetry load fifteen")?; + } + if let TelemetryMetric::Value(swap) = &self.swap + && swap.used_bytes > swap.total_bytes + { + return Err(ValidationError::OutOfRange { + field: "telemetry swap used bytes", + }); + } + Ok(()) + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Versioned { pub schema_version: u16, @@ -1677,4 +2093,202 @@ mod tests { .unwrap(); assert_eq!(noop.digest().unwrap(), base.digest().unwrap()); } + + fn observation() -> HostTelemetry { + HostTelemetry { + observed_at_unix_ms: 1_700_000_000_000, + sample_interval_ms: 1_000, + cpu: TelemetryMetric::Value(TelemetryCpu { + logical_cores: 8, + usage_pct: 12.5, + iowait_pct: Some(0.5), + }), + memory: TelemetryMetric::Value(TelemetryMemory { + available_bytes: 4_000, + total_bytes: 8_000, + used_bytes: 4_000, + }), + load: TelemetryMetric::Unsupported, + swap: TelemetryMetric::Unknown, + disk: TelemetryMetric::Value(TelemetryDisk { + available_bytes: 100, + total_bytes: 500, + volume_count: 2, + }), + disk_io: TelemetryMetric::Value(TelemetryDiskIo { + read_bytes_per_sec: 10, + write_bytes_per_sec: 20, + }), + network: TelemetryMetric::Value(TelemetryNetwork { + rx_bytes_per_sec: 30, + tx_bytes_per_sec: 40, + }), + } + } + + #[test] + fn a_valid_observation_validates() { + assert!(observation().validate().is_ok()); + } + + #[test] + fn a_missing_measurement_is_not_zero() { + let sample = observation(); + assert!(sample.load.is_unsupported()); + assert!(sample.swap.is_unknown()); + assert!(sample.load.value().is_none()); + assert!(sample.swap.value().is_none()); + assert_eq!(sample.cpu.value().map(|cpu| cpu.logical_cores), Some(8)); + } + + #[test] + fn out_of_range_and_non_finite_measurements_are_refused() { + let mut sample = observation(); + if let TelemetryMetric::Value(cpu) = &mut sample.cpu { + cpu.usage_pct = 100.5; + } + assert!(sample.validate().is_err()); + + let mut sample = observation(); + if let TelemetryMetric::Value(cpu) = &mut sample.cpu { + cpu.usage_pct = f32::NAN; + } + assert!(sample.validate().is_err()); + + let mut sample = observation(); + if let TelemetryMetric::Value(cpu) = &mut sample.cpu { + cpu.logical_cores = 0; + } + assert!(sample.validate().is_err()); + + let mut sample = observation(); + if let TelemetryMetric::Value(memory) = &mut sample.memory { + memory.used_bytes = memory.total_bytes + 1; + } + assert!(sample.validate().is_err()); + + let mut sample = observation(); + sample.swap = TelemetryMetric::Value(TelemetrySwap { + used_bytes: 1, + total_bytes: 0, + }); + assert!(sample.validate().is_err()); + + let mut sample = observation(); + sample.sample_interval_ms = 0; + assert!(sample.validate().is_err()); + + let mut sample = observation(); + sample.sample_interval_ms = MAX_TELEMETRY_SAMPLE_INTERVAL_MS + 1; + assert!(sample.validate().is_err()); + + let mut sample = observation(); + sample.observed_at_unix_ms = 0; + assert!(sample.validate().is_err()); + } + + #[test] + fn a_load_average_may_exceed_one_hundred() { + let mut sample = observation(); + sample.load = TelemetryMetric::Value(TelemetryLoad { + one: 12.5, + five: 8.0, + fifteen: 0.25, + }); + assert!(sample.validate().is_ok()); + + sample.load = TelemetryMetric::Value(TelemetryLoad { + one: f32::INFINITY, + five: 0.0, + fifteen: 0.0, + }); + assert!(sample.validate().is_err()); + } + + #[test] + fn the_observation_round_trips_through_json() { + let encoded = serde_json::to_string(&observation()).unwrap(); + let decoded: HostTelemetry = serde_json::from_str(&encoded).unwrap(); + assert_eq!(decoded, observation()); + // An absent measurement keeps its reason instead of decaying into zero. + assert!(encoded.contains("\"unsupported\"")); + assert!(encoded.contains("\"unknown\"")); + } + + #[test] + fn an_observation_with_an_unknown_field_is_refused() { + let mut value = serde_json::to_value(observation()).unwrap(); + value + .as_object_mut() + .unwrap() + .insert("unexpected".into(), serde_json::json!(1)); + assert!(serde_json::from_value::(value).is_err()); + } + + fn node_telemetry() -> NodeTelemetry { + NodeTelemetry { + schema_version: NODE_TELEMETRY_SCHEMA_VERSION, + node_id: NodeId::new("node-a").unwrap(), + source: TelemetrySource::Gregg, + state: TelemetryProviderState::Ready, + age_ms: Some(12), + last_error: None, + observation: Some(observation()), + } + } + + #[test] + fn a_ready_telemetry_response_validates() { + assert!(node_telemetry().validate().is_ok()); + } + + #[test] + fn a_telemetry_response_with_an_unknown_schema_version_is_refused() { + let mut telemetry = node_telemetry(); + telemetry.schema_version = NODE_TELEMETRY_SCHEMA_VERSION + 1; + assert!(telemetry.validate().is_err()); + } + + #[test] + fn a_ready_telemetry_response_without_an_observation_is_refused() { + let mut telemetry = node_telemetry(); + telemetry.observation = None; + assert!(telemetry.validate().is_err()); + } + + #[test] + fn a_disabled_telemetry_response_with_an_observation_is_refused() { + let mut telemetry = node_telemetry(); + telemetry.state = TelemetryProviderState::Disabled; + assert!(telemetry.validate().is_err()); + } + + #[test] + fn a_disabled_telemetry_response_is_valid_without_an_observation() { + let mut telemetry = node_telemetry(); + telemetry.state = TelemetryProviderState::Disabled; + telemetry.observation = None; + telemetry.age_ms = None; + assert!(telemetry.validate().is_ok()); + } + + #[test] + fn a_telemetry_response_whose_age_contradicts_its_observation_is_refused() { + let mut telemetry = node_telemetry(); + telemetry.age_ms = None; + assert!(telemetry.validate().is_err()); + } + + #[test] + fn a_telemetry_response_round_trips_through_json() { + let encoded = serde_json::to_string(&node_telemetry()).unwrap(); + let decoded: NodeTelemetry = serde_json::from_str(&encoded).unwrap(); + assert_eq!(decoded, node_telemetry()); + let mut value = serde_json::to_value(node_telemetry()).unwrap(); + value + .as_object_mut() + .unwrap() + .insert("unexpected".into(), serde_json::json!(1)); + assert!(serde_json::from_value::(value).is_err()); + } } diff --git a/crates/eggwork-sandbox-helper/tests/landlock_runner.rs b/crates/eggwork-sandbox-helper/tests/landlock_runner.rs index c1f6cba..10600ba 100644 --- a/crates/eggwork-sandbox-helper/tests/landlock_runner.rs +++ b/crates/eggwork-sandbox-helper/tests/landlock_runner.rs @@ -18,8 +18,13 @@ use eggwork_runner::{ use helper_fixture::TrustedHelperFixture; use std::{ fs, + os::unix::fs::{MetadataExt, PermissionsExt}, path::{Path, PathBuf}, process::Command, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, time::Duration, }; use tokio::sync::mpsc; @@ -509,6 +514,117 @@ fn malformed_private_spec_and_unavailable_status_channel_do_not_launch_target() // properties that make that whole class of failure structurally impossible in // this suite, instead of adding a retry or a sleep and hoping. +/// A freshly published helper must be executable at once. +/// +/// This is the regression test for the `ETXTBSY` refusal that CI hit on the +/// optional-Gregg telemetry branch. The fixture published its helper +/// atomically but never opened the file it executes for writing, and Linux +/// refuses to execute an inode that is open for writing — so the refusal was +/// intermittent and moved between tests, and the suite went red without any +/// test changing. +/// +/// The test is non-vacuous in two independent ways, and the second one does +/// not depend on a race at all: +/// +/// 1. Thirty-two threads stage and spawn in parallel, and not one spawn may be +/// refused. Before the fix, 16 threads staging and executing in a loop were +/// refused 22.6% of the time, so 32 parallel stagings hit the refusal with +/// probability very close to one. +/// 2. The staged helper is asserted to *be* the build output's inode. Staging +/// publishes a directory entry and writes nothing, so the staged path and +/// the build output share a device and an inode number. A copy would have +/// its own inode, and the assertion would fail immediately — no load, no +/// timing and no lucky window is needed to catch a regression to copying. +#[test] +fn a_linked_helper_is_executable_immediately_after_publication() { + const PARALLEL: usize = 32; + + let refused = Arc::new(AtomicUsize::new(0)); + let handles: Vec<_> = (0..PARALLEL) + .map(|_| { + let refused = Arc::clone(&refused); + std::thread::spawn(move || { + let fixture = TrustedHelperFixture::stage(built_helper()); + // The helper exits 125 without arguments. What is under test + // is the spawn itself: whether the kernel accepted the freshly + // published executable at all. + match Command::new(fixture.path()).spawn() { + Ok(mut child) => { + let _ = child.wait(); + } + Err(error) => { + eprintln!("a linked helper was refused: {error}"); + refused.fetch_add(1, Ordering::Relaxed); + } + } + }) + }) + .collect(); + for handle in handles { + handle.join().expect("staging thread joined"); + } + assert_eq!( + refused.load(Ordering::Relaxed), + 0, + "a freshly published helper must be executable without an ETXTBSY refusal" + ); + + // The structural half of the proof: staging published a link, so the + // staged helper and the build output are the same inode. Nothing was + // written, so the kernel's write-access accounting on that inode is + // untouched and the execution above cannot be refused. + let fixture = TrustedHelperFixture::stage(built_helper()); + let staged = fs::metadata(fixture.path()).expect("staged helper metadata"); + let built = fs::metadata(built_helper()).expect("build output metadata"); + assert_eq!( + staged.ino(), + built.ino(), + "the staged helper must be the build output's own inode, not a copy of it" + ); + assert_eq!( + staged.dev(), + built.dev(), + "the staged helper must live on the build output's filesystem" + ); +} + +/// A build output that anyone but its owner may write cannot be staged by +/// linking, because a link carries the source's mode and +/// `verify_trusted_helper` rejects a group- or world-writable helper. +/// +/// Cargo derives the executable's mode from the umask, so a permissive umask +/// leaves the build output group-writable. The fixture clears those bits once, +/// before anything is staged, and the change is one-directional: it removes +/// write permission for others and keeps the owner's permissions and the +/// execute bits. +#[test] +fn a_group_writable_source_is_normalized_to_a_trusted_mode() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("eggwork-sandbox-helper"); + fs::write(&path, b"not an executable helper").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o777)).unwrap(); + + assert!( + helper_fixture::normalize_trusted_mode(&path), + "a group- and world-writable source must be normalized" + ); + let mode = fs::metadata(&path) + .expect("normalized metadata") + .permissions() + .mode(); + assert_eq!( + mode & 0o022, + 0, + "group and world write bits must be cleared" + ); + assert_eq!(mode & 0o700, 0o700, "the owner's permissions must survive"); + assert_eq!(mode & 0o111, 0o111, "the execute bits must survive"); + assert!( + !helper_fixture::normalize_trusted_mode(&path), + "normalizing an already trusted mode must change nothing" + ); +} + #[tokio::test] async fn two_fixtures_stage_distinct_executable_paths() { let first = TrustedHelperFixture::stage(built_helper()); @@ -526,16 +642,30 @@ async fn two_fixtures_stage_distinct_executable_paths() { } } +/// Staging must treat the build output as read-only input. +/// +/// The one exception is deliberate and one-directional: the first staging +/// clears the group and world write bits of the build output, because a link +/// carries the source's mode and a helper that anyone but its owner may write +/// is not a trusted helper. After that first staging — which happens before +/// any fixture exists — staging must not touch the build output again. #[tokio::test] async fn staging_never_mutates_the_cargo_built_helper() { - use std::os::unix::fs::PermissionsExt; - let built = helper_fixture::digest(built_helper()); + + // This staging is the one that settles the build output's mode. + let _ = TrustedHelperFixture::stage(built_helper()); let built_mode = fs::metadata(built_helper()) .expect("build output metadata") .permissions() .mode() & 0o7777; + assert_eq!( + built_mode & 0o022, + 0, + "the build output must be trusted once it has been staged" + ); + for _ in 0..8 { let fixture = TrustedHelperFixture::stage(built_helper()); assert_eq!(helper_fixture::digest(fixture.path()), built); diff --git a/crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs b/crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs index 247effd..9cf54d8 100644 --- a/crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs +++ b/crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs @@ -10,39 +10,93 @@ //! Operations M004 recorded one same-head CI failure of //! `required_landlock_allows_workspace_and_denies_outside_reads_and_writes` //! with `Spawn("Text file busy (os error 26)")`, which passed on an immediate -//! rerun. `ETXTBSY` is what Linux returns when a file that is currently being -//! executed is opened for writing, and it is also what a partially written -//! executable can be replaced with mid-flight. The invariant this module exists -//! to make true is: +//! rerun. `ETXTBSY` is what Linux returns when a file that is currently open for +//! writing is executed. The invariant this module exists to make true is: //! //! > A fixture must never mutate, truncate, overwrite, or rename over an //! > executable path another concurrently runnable test may execute. //! -//! Three properties deliver it: +//! # What the kernel actually does +//! +//! The refusal is not a timing window and it is not about write-back. Linux +//! accounts write access on the inode itself: `struct inode::i_writecount` is +//! positive while the file is open for writing, negative while it is being +//! executed, and zero otherwise. `execve()` opens the candidate executable and +//! then calls `exe_file_deny_write_access()`, which is `deny_write_access()`: +//! +//! ```c +//! static inline int deny_write_access(struct file *file) +//! { +//! struct inode *inode = file_inode(file); +//! return atomic_dec_unless_positive(&inode->i_writecount) ? 0 : -ETXTBSY; +//! } +//! ``` +//! +//! The write access itself is taken by every write-open of a regular file, in +//! `do_dentry_open()`, and released when that file is torn down. So an `execve()` +//! of an inode that is *still* open for writing fails with `ETXTBSY`, and the +//! release is asynchronous with respect to the closing thread — which is why the +//! refusal can be observed on a file that no `/proc//fd` entry points at. +//! +//! Three consequences follow, and they are the whole design: +//! +//! 1. `fsync`, `O_DSYNC` and sleeping do not help. They concern write-back; +//! the refusal is caused by the write *access*. +//! 2. A retry does not help either, because a refused `execve` leaves the +//! access in place. +//! 3. The only construction that cannot produce the refusal is one that never +//! opens the executed inode for writing. +//! +//! # The four properties //! //! 1. **Build output is an input, never an installation directory.** The -//! Cargo-built helper is only ever read. Each fixture gets its own -//! `0700` directory and its own copy, so no two tests can name the same +//! Cargo-built helper is only ever read. Each fixture gets its own `0700` +//! directory and its own path, so no two tests can name the same //! executable. -//! 2. **Staging is atomic.** The copy is written under a staging name and -//! `rename`d into place, never written in place. Rename over a running -//! executable is allowed on Linux; `open(O_TRUNC)` is not. A fixture -//! therefore cannot hit `ETXTBSY`, and no execution can observe a -//! half-written helper. -//! 3. **Cleanup follows convergence.** The fixture owns its directory and +//! 2. **Staging never writes the file that will be executed.** The staged +//! helper is a hard link to the Cargo-built one. A link shares the source's +//! inode and does not open it for writing, so the inode's write access is +//! never taken and the kernel has no reason to refuse to execute it. See +//! `stage`. +//! 3. **A link shares the source's mode, so the source has to be trusted.** +//! `verify_trusted_helper` rejects a helper that anyone but its owner may +//! write, and Cargo's executable mode is `0666 & ~umask` plus the execute +//! bits — so a permissive umask produces a group-writable build output that +//! no fixture could stage by linking. The fixture therefore clears the group +//! and world write bits of the build output once, before anything is staged. +//! That is a mode change on a shared build artifact, and it is deliberately +//! one-directional: it can only ever *remove* write permission for others, +//! and the build output's bytes are never touched. See +//! `normalize_trusted_mode`. +//! 4. **Cleanup follows convergence.** The fixture owns its directory and //! removes it on drop. `LocalProcessRunner::run` returns only after the //! owned process tree has converged, so a test that holds the fixture until //! after `run` cannot delete a directory a helper is still executing from. //! Removing a directory does not disturb a running process anyway — its //! inode stays alive — so an early drop is untidy, never corrupting. +//! +//! Property 2 replaced an earlier property that claimed atomic publication was +//! enough on its own. It was not: a file that is written and then immediately +//! executed can be refused with `ETXTBSY`, and the refusal recurred in CI on the +//! optional-Gregg telemetry branch before it was eliminated. The measurement is +//! recorded in `plans/closure/operations-distribution/004b-status.md`. +//! +//! Property 3 is new with the same corrective. It is the price of property 2: +//! a link cannot have a different mode from the file it links to. // Every include site gates this module with `#[cfg(target_os = "linux")]`; the // gate lives there rather than here so including this file does not emit a // duplicated-attribute warning. +use std::collections::HashSet; use std::fs; +use std::io; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; + +/// The file name a staged helper is published under. +const HELPER_NAME: &str = "eggwork-sandbox-helper"; /// A fixture-owned installation of the sandbox helper. /// @@ -60,18 +114,61 @@ impl TrustedHelperFixture { /// Stage `source` — normally the Cargo-built helper — into a fresh private /// installation. /// - /// The directory is `0700` and the copy `0755`, which is exactly what - /// `verify_trusted_helper` requires: an owner-only ancestor chain, a - /// regular file, and an executable mode. Trust is therefore satisfied by - /// construction, which is part of the contract under test rather than an - /// accident. + /// The directory is `0700` and the staged helper carries the source's + /// executable mode, which is exactly what `verify_trusted_helper` requires: + /// an owner-only ancestor chain, a regular file, and an executable mode. + /// Trust is therefore satisfied by construction, which is part of the + /// contract under test rather than an accident. + /// + /// The staged helper is a hard link to `source` rather than a copy of it. A + /// link shares the source's inode and never opens it for writing, so the + /// inode's write access is never taken and the kernel will not refuse to + /// execute it. That is the difference between a refusal that cannot happen + /// and one that is merely unlikely. It also removes a per-fixture copy of + /// the whole binary from every test. + /// + /// A hard link needs the source and the fixture to share a filesystem. The + /// system temporary directory is tried first, because its ancestor chain is + /// the one `verify_trusted_helper` trusts by construction; a directory next + /// to the source is the fallback, because it is the same filesystem by + /// definition. When neither can be linked, staging fails loudly rather than + /// falling back to a copy, because a copy is exactly the construction that + /// can be refused. pub fn stage(source: &Path) -> Self { - let directory = tempfile::tempdir().expect("fixture directory"); - fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)) - .expect("owner-only fixture directory"); - let helper = directory.path().join("eggwork-sandbox-helper"); - install_atomically(source, &helper, 0o755); - Self { directory, helper } + let source = trusted_source(source); + let executable = fs::metadata(&source) + .map(|metadata| metadata.permissions().mode() & 0o111 != 0) + .unwrap_or(false); + assert!( + executable, + "the sandbox helper source {} is not executable, so no trusted helper can be \ + staged from it", + source.display() + ); + let mut failure: Option = None; + for parent in [None, source.parent()] { + let directory = match parent { + None => tempfile::tempdir(), + Some(parent) => tempfile::tempdir_in(parent), + }; + let Ok(directory) = directory else { + failure = Some(io::Error::other("no fixture directory could be created")); + continue; + }; + fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)) + .expect("owner-only fixture directory"); + let helper = directory.path().join(HELPER_NAME); + match fs::hard_link(&source, &helper) { + Ok(()) => return Self { directory, helper }, + Err(error) => failure = Some(error), + } + } + panic!( + "cannot stage a trusted helper from {}: {failure:?}. A copy is deliberately not \ + used as a fallback: a file that was written can be refused with ETXTBSY, which is \ + the failure this fixture exists to make impossible.", + source.display() + ); } /// The trusted path to hand to `TrustedLandlockSetup`. @@ -84,46 +181,104 @@ impl TrustedHelperFixture { self.directory.path() } + /// A path inside this fixture's directory that no other test can name. + pub fn sibling(&self, name: &str) -> PathBuf { + self.directory.path().join(name) + } + /// Replace this fixture's helper bytes with junk, atomically. /// - /// This exists for the negative trust cases. It deliberately uses the same - /// atomic path as staging, so a test can prove a *neighbouring* fixture is - /// unaffected without itself creating the race it is testing against. + /// The replacement is *published*, not written in place: the staged helper + /// is a hard link shared with the Cargo-built helper and with other + /// fixtures, and writing through it would reach all of them. + /// + /// The published replacement is a file that was written, so executing it + /// may be refused with `ETXTBSY` instead of failing as a malformed + /// executable. Both are loud failures, and the junk fixture is never + /// expected to run successfully. pub fn replace_with_junk(&self, bytes: &[u8]) { - let staging = self.directory.path().join("eggwork-sandbox-helper.staging"); - fs::write(&staging, bytes).expect("write junk helper"); - fs::set_permissions(&staging, fs::Permissions::from_mode(0o755)).expect("junk mode"); - fs::rename(&staging, &self.helper).expect("replace helper atomically"); + let staging = self.staging_path(); + fs::write(&staging, bytes).expect("write the replacement helper"); + self.publish(staging, 0o755); } /// Change only this fixture's helper mode, so a trust rejection can be /// proven without touching any other fixture's bytes. + /// + /// Like `replace_with_junk`, this publishes a replacement rather than + /// changing the inode: the staged helper may be shared, and a `chmod` on a + /// shared inode would be visible to every fixture that links it. pub fn set_mode(&self, mode: u32) { - fs::set_permissions(&self.helper, fs::Permissions::from_mode(mode)) - .expect("set helper mode"); + let staging = self.staging_path(); + fs::copy(&self.helper, &staging).expect("copy the staged helper"); + self.publish(staging, mode); } - /// A path inside this fixture's directory that no other test can name. - pub fn sibling(&self, name: &str) -> PathBuf { - self.directory.path().join(name) + /// The staging name a replacement is written under, inside this fixture's + /// own directory, so that the final `rename` is a same-filesystem atomic + /// swap — the only replacement form Linux accepts for an executable that + /// may be running. + fn staging_path(&self) -> PathBuf { + self.directory.path().join(format!("{HELPER_NAME}.staging")) + } + + /// Publish `staging` as this fixture's helper, atomically. + fn publish(&self, staging: PathBuf, mode: u32) { + fs::set_permissions(&staging, fs::Permissions::from_mode(mode)) + .expect("stage the replacement mode"); + fs::rename(&staging, &self.helper).expect("publish the replacement helper"); } } -/// Copy `source` to `destination` without ever writing `destination` in place. +/// Clear the group and world write bits of `path`, if it has any. /// -/// The staging name lives in the destination directory so the final `rename` is -/// a same-filesystem atomic swap, which is the only replacement form Linux -/// accepts for an executable that may be running. -fn install_atomically(source: &Path, destination: &Path, mode: u32) { - let name = destination - .file_name() - .expect("destination has a file name") - .to_string_lossy() - .into_owned(); - let staging = destination.with_file_name(format!("{name}.staging")); - fs::copy(source, &staging).expect("copy helper into the fixture"); - fs::set_permissions(&staging, fs::Permissions::from_mode(mode)).expect("stage executable mode"); - fs::rename(&staging, destination).expect("publish the staged helper"); +/// Returns whether the mode was changed. +/// +/// A hard-linked helper carries the source's mode, and `verify_trusted_helper` +/// rejects a helper that anyone but its owner may write. Cargo derives the +/// executable's mode from the process umask — `0666 & ~umask` plus the execute +/// bits — so a permissive umask (0002 is common in shared development +/// environments) leaves the build output group-writable and no fixture could +/// stage it by linking. +/// +/// The change is deliberately one-directional: it removes write permission for +/// everyone else and keeps the owner's permissions, the execute bits, and every +/// other bit exactly as they were. It never makes a file more writable, so a +/// fixture that stages a link can only become *more* trusted because of it, and +/// the build output's bytes are never touched. +pub fn normalize_trusted_mode(path: &Path) -> bool { + let Ok(metadata) = fs::metadata(path) else { + return false; + }; + let mode = metadata.permissions().mode(); + if mode & 0o022 == 0 { + return false; + } + let trusted = mode & 0o7777 & !0o022; + fs::set_permissions(path, fs::Permissions::from_mode(trusted)) + .expect("normalize the build output's mode"); + true +} + +/// The source of a staged helper, with its mode normalized once. +/// +/// The normalization happens under a lock, before the first link is made, so +/// that no fixture can stage a helper whose mode has not been settled yet: a +/// fixture that linked before the normalization would hold a group-writable +/// helper, and the trust check would reject it. +fn trusted_source(source: &Path) -> PathBuf { + static TRUSTED: OnceLock>> = OnceLock::new(); + let trusted = TRUSTED.get_or_init(|| Mutex::new(HashSet::new())); + let mut seen = trusted + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let key = source.to_path_buf(); + if seen.contains(&key) { + return key; + } + normalize_trusted_mode(source); + seen.insert(key.clone()); + key } /// The digest of a file, used by the fixture tests to prove that staging never diff --git a/crates/eggwork-server/Cargo.toml b/crates/eggwork-server/Cargo.toml index f51e785..f1ac21d 100644 --- a/crates/eggwork-server/Cargo.toml +++ b/crates/eggwork-server/Cargo.toml @@ -9,6 +9,9 @@ license.workspace = true eggwork-core = { path = "../eggwork-core" } eggwork-runner = { path = "../eggwork-runner" } eggserve-core.workspace = true +eggfetch-core.workspace = true +url.workspace = true +async-trait.workspace = true tokio = { workspace = true, features = ["net", "signal"] } bytes.workspace = true futures-util.workspace = true @@ -26,6 +29,7 @@ rustls-pemfile = "2" fs2 = "0.4" eggup-core = "0.1.1" eggup-service = "0.1.1" +gregg-protocol = "1.0.15" # The installed-release qualification harness (Operations M004) is opt-in: it # drives an installed `eggworkd` through the production client path and must not diff --git a/crates/eggwork-server/src/lib.rs b/crates/eggwork-server/src/lib.rs index 2323dd4..7f9badd 100644 --- a/crates/eggwork-server/src/lib.rs +++ b/crates/eggwork-server/src/lib.rs @@ -7,6 +7,7 @@ mod blob; pub mod deployment; pub mod operations; mod store; +pub mod telemetry; mod workspace; use bytes::Bytes; @@ -57,6 +58,7 @@ const MAX_WORKSPACE_REQUEST_BYTES: usize = 4 * 1024 * 1024; pub enum Operation { Capabilities, Status, + Telemetry, Execute, Observe, Cancel, @@ -176,6 +178,11 @@ pub struct NodeConfig { pub max_active_executions: u32, pub lease_ttl: Duration, pub tls: TlsServerConfig, + /// Optional host-telemetry provider. + /// + /// `None` means the node has no provider: it creates no polling task and + /// claims no host measurements. + pub host_telemetry: Option, } #[derive(Clone)] @@ -196,6 +203,7 @@ struct NodeState { resolver: Arc, authorizer: Arc, executions: Arc>>>, + telemetry: telemetry::TelemetryMonitor, } struct ExecutionRecord { @@ -388,6 +396,17 @@ impl NodeServer { }), ); } + // The telemetry owner is created before the HTTP surface so that a + // configured provider is already polling by the time the node accepts + // requests. The task never blocks startup: it polls in the + // background, and a node with no provider creates no task at all. + let telemetry = match config.host_telemetry.as_ref() { + None => telemetry::TelemetryMonitor::disabled(), + Some(settings) => { + let provider = Arc::new(telemetry::GreggTelemetryProvider::new(settings)); + telemetry::TelemetryMonitor::start(provider, settings) + } + }; let state = NodeState { node_id: config.node_id, execution_root: config.execution_root, @@ -405,6 +424,7 @@ impl NodeServer { resolver, authorizer, executions: Arc::new(Mutex::new(executions)), + telemetry, }; let runtime = RuntimeConfig::builder() .bind(config.bind) @@ -466,6 +486,10 @@ impl NodeServer { record.cancellation.cancel(); } } + // The telemetry owner is stopped with the node, so a shutting-down + // node stops contacting its provider instead of leaving a polling + // task behind it. + self.state.telemetry.shutdown().await; self.handle.shutdown(); } @@ -654,6 +678,7 @@ fn operation_for(method: &str, path: &str) -> Option<(Operation, Route)> { match (method, path) { ("GET", "/v1/capabilities") => Some((Operation::Capabilities, Route::Capabilities)), ("GET", "/v1/status") => Some((Operation::Status, Route::Status)), + ("GET", "/v1/node/telemetry") => Some((Operation::Telemetry, Route::Telemetry)), ("POST", "/v1/executions") => Some((Operation::Execute, Route::Execute)), ("POST", "/v1/blobs/missing") => Some((Operation::BlobRead, Route::BlobMissing)), ("POST", "/v1/blobs/prepare") => Some((Operation::BlobWrite, Route::BlobPrepare)), @@ -715,6 +740,7 @@ fn operation_for(method: &str, path: &str) -> Option<(Operation, Route)> { enum Route { Capabilities, Status, + Telemetry, Execute, Observe(ExecutionId), Cancel(ExecutionId), @@ -768,6 +794,7 @@ async fn dispatch( match route { Route::Capabilities => Ok(json_response(200, &node_capabilities_for(&state))), Route::Status => Ok(json_response(200, &node_status(&state))), + Route::Telemetry => Ok(json_response(200, &node_telemetry(&state).await)), Route::Execute => execute(state, request, principal).await, Route::Observe(id) => observe(state, id, query.as_deref(), principal).await, Route::Cancel(id) => control(state, id, request, principal, false).await, @@ -864,6 +891,24 @@ fn node_status(state: &NodeState) -> NodeStatus { } } +/// Project the cached host observation into the node telemetry wire contract. +/// +/// This reads the cache and nothing else. A remote read never contacts the +/// provider, so a burst of readers cannot become a burst of provider +/// requests, and a provider that is down does not turn a read into a timeout. +async fn node_telemetry(state: &NodeState) -> eggwork_core::NodeTelemetry { + let snapshot = state.telemetry.cache().snapshot().await; + eggwork_core::NodeTelemetry { + schema_version: eggwork_core::NODE_TELEMETRY_SCHEMA_VERSION, + node_id: state.node_id.clone(), + source: eggwork_core::TelemetrySource::Gregg, + state: snapshot.state, + age_ms: snapshot.age_ms, + last_error: snapshot.last_error, + observation: snapshot.observation, + } +} + async fn read_limited_body( mut body: eggserve_core::primitives::RequestBody, limit: usize, @@ -2931,17 +2976,52 @@ mod tests { /// while cargo test binaries sit under `target/debug/deps/`, so the helper /// cannot rely on `CARGO_BIN_EXE_eggwork-sandbox-helper`. We probe the /// current executable's sibling, then its grandparent, then `CARGO_TARGET_DIR`. + /// + /// The helper is staged by hard link, never by copy. Linux refuses to + /// execute an inode that is still open for writing, and reports the + /// refusal as `ETXTBSY`; a copy is by definition a file that was written, + /// so it is exactly the construction that can be refused. A link shares the + /// build output's inode and writes nothing, so the refusal cannot arise. + /// Because a link also carries the source's mode, the build output's group + /// and world write bits are cleared first: a trusted helper must not be + /// writable by anyone but its owner, and Cargo derives the executable's + /// mode from the umask. The same staging rules live in + /// `eggwork-sandbox-helper`'s shared test fixture. fn place_trusted_helper() -> Option { use std::os::unix::fs::PermissionsExt; let source = locate_helper_binary()?; - let helper_dir = tempfile::tempdir().ok()?; - let helper = helper_dir.path().join("eggwork-sandbox-helper"); - fs::copy(&source, &helper).ok()?; - fs::set_permissions(helper_dir.path(), fs::Permissions::from_mode(0o700)).ok()?; - fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).ok()?; + if let Ok(metadata) = fs::metadata(&source) { + let mode = metadata.permissions().mode(); + if mode & 0o022 != 0 { + fs::set_permissions(&source, fs::Permissions::from_mode(mode & 0o7777 & !0o022)) + .ok()?; + } + } + // The system temporary directory is tried first, because its ancestor + // chain is the one the trust check accepts by construction; a directory + // next to the source is the fallback, because it is the same filesystem + // by definition. + let mut staged = None; + for parent in [None, source.parent()] { + let directory = match parent { + None => tempfile::tempdir(), + Some(parent) => tempfile::tempdir_in(parent), + }; + let Ok(directory) = directory else { + continue; + }; + if fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)).is_err() { + continue; + } + let helper = directory.path().join("eggwork-sandbox-helper"); + if fs::hard_link(&source, &helper).is_ok() { + staged = Some(directory); + break; + } + } // Leak the directory so the helper keeps living for the duration of the // test; trust checks happen once at capability probe time. - let leaked: &'static TempDir = Box::leak(Box::new(helper_dir)); + let leaked: &'static TempDir = Box::leak(Box::new(staged?)); Some(leaked.path().join("eggwork-sandbox-helper")) } @@ -3003,6 +3083,7 @@ mod tests { for (method, path, expected) in [ ("GET", "/v1/capabilities", Operation::Capabilities), ("GET", "/v1/status", Operation::Status), + ("GET", "/v1/node/telemetry", Operation::Telemetry), ("POST", "/v1/executions", Operation::Execute), ("GET", "/v1/executions/exec-1", Operation::Observe), ("POST", "/v1/executions/exec-1/cancel", Operation::Cancel), @@ -3198,6 +3279,7 @@ mod tests { )])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-a").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -3386,6 +3468,7 @@ mod tests { )])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("routed-node").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -3460,6 +3543,7 @@ mod tests { )])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("blob-node").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -3785,6 +3869,7 @@ mod tests { )])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-a").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -4127,6 +4212,7 @@ mod tests { )])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-lease").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -4240,6 +4326,7 @@ mod tests { )])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-recovery").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -4324,6 +4411,7 @@ mod tests { ])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-derive").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -4566,6 +4654,7 @@ mod tests { } let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-derive-deny").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -4629,6 +4718,7 @@ mod tests { let work_root = temp.path().join("work"); fs::create_dir_all(&work_root).unwrap(); let config = NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-drain-restart").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -4686,6 +4776,7 @@ mod tests { }; let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-cap-consistency").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -4772,6 +4863,7 @@ mod tests { )); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-required-landlock").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -4919,6 +5011,7 @@ mod tests { )); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-landlock-descendants").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -5064,6 +5157,7 @@ mod tests { )); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-no-helper").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -5137,6 +5231,7 @@ mod tests { )); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-best-effort-no-helper").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -5207,6 +5302,7 @@ mod tests { let runner = Arc::new(LocalProcessRunner::new(eggwork_runner::NoExecutionSetup)); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-resource-rejection").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -5302,6 +5398,7 @@ mod tests { )); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-resource-accept").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -5416,6 +5513,7 @@ mod tests { )])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-network-reject").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -5526,6 +5624,7 @@ mod tests { )); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-codegg-compat").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -5834,6 +5933,7 @@ mod tests { ])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-fence").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -5967,6 +6067,7 @@ mod tests { )])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-drain-gate").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -6069,6 +6170,7 @@ mod tests { )])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-hostile-ws").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -6165,6 +6267,7 @@ mod tests { )])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-sentinel").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -6241,6 +6344,7 @@ mod tests { )])); let server = NodeServer::start( NodeConfig { + host_telemetry: None, node_id: NodeId::new("node-drain-race").unwrap(), bind: "127.0.0.1:0".parse().unwrap(), execution_root: work_root, @@ -6328,4 +6432,778 @@ mod tests { server.shutdown().await; server.wait().await.unwrap(); } + + /// The authorized node-telemetry surface: one read route, one narrow + /// grant, and the guarantee that a remote read never becomes a provider + /// request. + mod telemetry_route { + use super::*; + use eggwork_core::{NodeTelemetry, TelemetryErrorCategory, TelemetryProviderState}; + use futures_util::TryStreamExt; + use std::sync::atomic::{AtomicUsize, Ordering}; + use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpListener, + }; + + /// A loopback provider that serves one valid v2 status payload and + /// counts how often it was asked. + struct FakeProvider { + address: SocketAddr, + requests: Arc, + } + + impl FakeProvider { + async fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let address = listener.local_addr().expect("addr"); + let requests = Arc::new(AtomicUsize::new(0)); + let counter = requests.clone(); + tokio::spawn(async move { + loop { + let Ok((mut stream, _)) = listener.accept().await else { + continue; + }; + let counter = counter.clone(); + tokio::spawn(async move { + let mut buffer = Vec::new(); + let mut chunk = [0u8; 1024]; + loop { + let Ok(read) = stream.read(&mut chunk).await else { + return; + }; + if read == 0 { + return; + } + buffer.extend_from_slice(&chunk[..read]); + if buffer.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + counter.fetch_add(1, Ordering::SeqCst); + let body = serde_json::json!({ + "schema_version": 2, + "observed_at_unix_ms": artifact::now_unix_ms(), + "sample_interval_ms": 1000, + "capabilities": { + "cpu_iowait": true, + "load_average": true, + "swap": false, + "memory_commit": false + }, + "system": { + "name": "host", + "hostname": "host.internal", + "os_name": "linux", + "os_version": "6.1", + "kernel_name": "Linux", + "kernel_release": "6.1.0", + "architecture": "x86_64" + }, + "cpu": { "logical_cores": 8, "usage_pct": 12.5, "iowait_pct": 1.5 }, + "load": { "one": 0.5, "five": 0.25, "fifteen": 0.125 }, + "memory": { "used_bytes": 4000, "total_bytes": 8000, "usage_pct": 50.0 } + }) + .to_string(); + let head = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + let _ = stream.write_all(head.as_bytes()).await; + let _ = stream.write_all(body.as_bytes()).await; + let _ = stream.flush().await; + let _ = stream.shutdown().await; + }); + } + }); + Self { address, requests } + } + + fn endpoint(&self) -> String { + format!("http://127.0.0.1:{}/v2/status", self.address.port()) + } + + fn requests(&self) -> usize { + self.requests.load(Ordering::SeqCst) + } + } + + /// A node whose provider is configured but not yet sampled. + fn telemetry_config(endpoint: &str) -> crate::telemetry::HostTelemetryConfig { + crate::telemetry::HostTelemetryConfig::new(endpoint, 3_600, 3_600).expect("config") + } + + async fn wait_for_state( + server: &NodeServer, + expected: TelemetryProviderState, + ) -> NodeTelemetry { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + let snapshot = server.state.telemetry.cache().snapshot().await; + if snapshot.state == expected { + break; + } + assert!( + std::time::Instant::now() < deadline, + "provider state stayed {snapshot:?} instead of reaching {expected:?}" + ); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + node_telemetry(&server.state).await + } + + #[tokio::test] + async fn an_authorized_principal_reads_the_cached_observation() { + init_tls(); + let (root, server_identity, client_identity, _) = tls_material(); + let temp = TempDir::new().unwrap(); + let work_root = temp.path().join("work"); + fs::create_dir_all(&work_root).unwrap(); + let provider = FakeProvider::start().await; + let principal = eggwork_core::PrincipalId::new("controller-a").unwrap(); + let resolver = Arc::new(FingerprintPrincipalResolver::new([( + FingerprintPrincipalResolver::fingerprint(client_identity.cert.as_ref()), + principal, + )])); + let server = NodeServer::start( + NodeConfig { + host_telemetry: Some(telemetry_config(&provider.endpoint())), + node_id: NodeId::new("node-a").unwrap(), + bind: "127.0.0.1:0".parse().unwrap(), + execution_root: work_root, + database_path: temp.path().join("node.sqlite"), + blob_root: temp.path().join("blob-store"), + blob_quota_bytes: 1024 * 1024 * 1024, + workspace_root: temp.path().join("workspace-store"), + workspace_quota_bytes: 1024 * 1024 * 1024, + max_active_executions: 2, + lease_ttl: std::time::Duration::from_secs(30), + tls: tls_server_config(root.clone(), &server_identity), + }, + Arc::new(LocalProcessRunner::default()), + resolver, + Arc::new(|_: &NodePrincipal, operation| operation == Operation::Telemetry), + ) + .await + .expect("node must start"); + + let client_temp = TempDir::new().unwrap(); + let client = NodeClient::new( + format!("https://localhost:{}", server.local_addr().port()), + write_client_config(&client_temp, root.as_ref(), &client_identity), + ) + .unwrap(); + + let telemetry = wait_for_state(&server, TelemetryProviderState::Ready).await; + assert_eq!(telemetry.node_id, NodeId::new("node-a").unwrap()); + assert_eq!(telemetry.schema_version, 1); + + let observed = client.telemetry().await.expect("authorized read"); + assert_eq!(observed.state, TelemetryProviderState::Ready); + assert_eq!(observed.node_id, NodeId::new("node-a").unwrap()); + assert_eq!(observed.source, eggwork_core::TelemetrySource::Gregg); + observed.validate().expect("served response must validate"); + let observation = observed.observation.as_ref().expect("observation"); + assert_eq!(observation.cpu.value().unwrap().logical_cores, 8); + assert_eq!(observation.cpu.value().unwrap().iowait_pct, Some(1.5)); + assert!(observation.swap.is_unsupported()); + assert!(observed.age_ms.is_some()); + assert!(observed.last_error.is_none()); + + // The same read, requiring the node id to match. + let matched = client + .telemetry_for(&NodeId::new("node-a").unwrap()) + .await + .expect("matching node id"); + assert_eq!(matched.node_id, NodeId::new("node-a").unwrap()); + assert!(matches!( + client.telemetry_for(&NodeId::new("node-b").unwrap()).await, + Err(eggwork_client::ClientError::InvalidResponse) + )); + + // A remote read is served from the cache: it must not become a + // provider request. + let before = provider.requests(); + for _ in 0..16 { + let _ = client.telemetry().await.expect("repeat read"); + } + assert_eq!( + provider.requests(), + before, + "a remote read must never trigger a provider request" + ); + + server.shutdown().await; + server.wait().await.unwrap(); + } + + #[tokio::test] + async fn an_unauthorized_principal_cannot_read_the_observation() { + init_tls(); + let (root, server_identity, client_identity, unknown_identity) = tls_material(); + let temp = TempDir::new().unwrap(); + let work_root = temp.path().join("work"); + fs::create_dir_all(&work_root).unwrap(); + let provider = FakeProvider::start().await; + let principal = eggwork_core::PrincipalId::new("controller-a").unwrap(); + // Only the first identity is known to the node. The second is a + // well-formed client certificate the node has no principal for, + // so it is refused at authentication rather than authorization. + let resolver = Arc::new(FingerprintPrincipalResolver::new([( + FingerprintPrincipalResolver::fingerprint(client_identity.cert.as_ref()), + principal, + )])); + let server = NodeServer::start( + NodeConfig { + host_telemetry: Some(telemetry_config(&provider.endpoint())), + node_id: NodeId::new("node-a").unwrap(), + bind: "127.0.0.1:0".parse().unwrap(), + execution_root: work_root, + database_path: temp.path().join("node.sqlite"), + blob_root: temp.path().join("blob-store"), + blob_quota_bytes: 1024 * 1024 * 1024, + workspace_root: temp.path().join("workspace-store"), + workspace_quota_bytes: 1024 * 1024 * 1024, + max_active_executions: 2, + lease_ttl: std::time::Duration::from_secs(30), + tls: tls_server_config(root.clone(), &server_identity), + }, + Arc::new(LocalProcessRunner::default()), + resolver, + // The read is refused for every principal. + Arc::new(|_: &NodePrincipal, _operation| false), + ) + .await + .expect("node must start"); + + let client_temp = TempDir::new().unwrap(); + let client = NodeClient::new( + format!("https://localhost:{}", server.local_addr().port()), + write_client_config(&client_temp, root.as_ref(), &client_identity), + ) + .unwrap(); + let denied = client.telemetry().await; + assert!( + matches!( + denied, + Err(eggwork_client::ClientError::Api { status: 403, .. }) + ), + "an unauthorized read must be refused with the typed 403" + ); + // The refusal must not leak whether the node holds an observation. + let rendered = format!("{denied:?}"); + assert!(!rendered.contains("logical_cores")); + assert!(!rendered.contains("usage_pct")); + + // A principal the node does not know at all is refused earlier, + // at authentication. + let unknown_temp = TempDir::new().unwrap(); + let unknown = NodeClient::new( + format!("https://localhost:{}", server.local_addr().port()), + write_client_config(&unknown_temp, root.as_ref(), &unknown_identity), + ) + .unwrap(); + let unknown_read = unknown.telemetry().await; + assert!(matches!( + unknown_read, + Err(eggwork_client::ClientError::Api { status: 401, .. }) + )); + + server.shutdown().await; + server.wait().await.unwrap(); + } + + #[tokio::test] + async fn a_node_without_a_provider_reports_disabled() { + init_tls(); + let (root, server_identity, client_identity, _) = tls_material(); + let temp = TempDir::new().unwrap(); + let work_root = temp.path().join("work"); + fs::create_dir_all(&work_root).unwrap(); + let principal = eggwork_core::PrincipalId::new("controller-a").unwrap(); + let resolver = Arc::new(FingerprintPrincipalResolver::new([( + FingerprintPrincipalResolver::fingerprint(client_identity.cert.as_ref()), + principal, + )])); + let server = NodeServer::start( + NodeConfig { + host_telemetry: None, + node_id: NodeId::new("node-a").unwrap(), + bind: "127.0.0.1:0".parse().unwrap(), + execution_root: work_root, + database_path: temp.path().join("node.sqlite"), + blob_root: temp.path().join("blob-store"), + blob_quota_bytes: 1024 * 1024 * 1024, + workspace_root: temp.path().join("workspace-store"), + workspace_quota_bytes: 1024 * 1024 * 1024, + max_active_executions: 2, + lease_ttl: std::time::Duration::from_secs(30), + tls: tls_server_config(root.clone(), &server_identity), + }, + Arc::new(LocalProcessRunner::default()), + resolver, + Arc::new(|_: &NodePrincipal, operation| operation == Operation::Telemetry), + ) + .await + .expect("node must start"); + + let client_temp = TempDir::new().unwrap(); + let client = NodeClient::new( + format!("https://localhost:{}", server.local_addr().port()), + write_client_config(&client_temp, root.as_ref(), &client_identity), + ) + .unwrap(); + let observed = client.telemetry().await.expect("authorized read"); + assert_eq!(observed.state, TelemetryProviderState::Disabled); + assert!(observed.observation.is_none()); + assert!(observed.age_ms.is_none()); + assert!(observed.last_error.is_none()); + observed.validate().expect("served response must validate"); + + server.shutdown().await; + server.wait().await.unwrap(); + } + + #[tokio::test] + async fn an_unreachable_provider_is_reported_as_unavailable() { + init_tls(); + let (root, server_identity, client_identity, _) = tls_material(); + let temp = TempDir::new().unwrap(); + let work_root = temp.path().join("work"); + fs::create_dir_all(&work_root).unwrap(); + // Bind a port and drop it, so the endpoint refuses connections. + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let address = listener.local_addr().expect("addr"); + drop(listener); + let principal = eggwork_core::PrincipalId::new("controller-a").unwrap(); + let resolver = Arc::new(FingerprintPrincipalResolver::new([( + FingerprintPrincipalResolver::fingerprint(client_identity.cert.as_ref()), + principal, + )])); + let server = NodeServer::start( + NodeConfig { + host_telemetry: Some(telemetry_config(&format!( + "http://127.0.0.1:{}/v2/status", + address.port() + ))), + node_id: NodeId::new("node-a").unwrap(), + bind: "127.0.0.1:0".parse().unwrap(), + execution_root: work_root, + database_path: temp.path().join("node.sqlite"), + blob_root: temp.path().join("blob-store"), + blob_quota_bytes: 1024 * 1024 * 1024, + workspace_root: temp.path().join("workspace-store"), + workspace_quota_bytes: 1024 * 1024 * 1024, + max_active_executions: 2, + lease_ttl: std::time::Duration::from_secs(30), + tls: tls_server_config(root.clone(), &server_identity), + }, + Arc::new(LocalProcessRunner::default()), + resolver, + Arc::new(|_: &NodePrincipal, operation| operation == Operation::Telemetry), + ) + .await + .expect("node must start"); + + let client_temp = TempDir::new().unwrap(); + let client = NodeClient::new( + format!("https://localhost:{}", server.local_addr().port()), + write_client_config(&client_temp, root.as_ref(), &client_identity), + ) + .unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + let observed = client.telemetry().await.expect("authorized read"); + if observed.state == TelemetryProviderState::Unavailable { + assert_eq!( + observed.last_error, + Some(TelemetryErrorCategory::Connection) + ); + assert!(observed.observation.is_none()); + observed.validate().expect("served response must validate"); + break; + } + assert!( + std::time::Instant::now() < deadline, + "an unreachable provider must be reported as unavailable" + ); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + + server.shutdown().await; + server.wait().await.unwrap(); + } + + #[tokio::test] + async fn a_node_without_the_route_is_reported_as_unsupported() { + init_tls(); + let (root, server_identity, client_identity, _) = tls_material(); + let temp = TempDir::new().unwrap(); + let work_root = temp.path().join("work"); + fs::create_dir_all(&work_root).unwrap(); + let principal = eggwork_core::PrincipalId::new("controller-a").unwrap(); + let resolver = Arc::new(FingerprintPrincipalResolver::new([( + FingerprintPrincipalResolver::fingerprint(client_identity.cert.as_ref()), + principal, + )])); + let server = NodeServer::start( + NodeConfig { + host_telemetry: None, + node_id: NodeId::new("node-a").unwrap(), + bind: "127.0.0.1:0".parse().unwrap(), + execution_root: work_root, + database_path: temp.path().join("node.sqlite"), + blob_root: temp.path().join("blob-store"), + blob_quota_bytes: 1024 * 1024 * 1024, + workspace_root: temp.path().join("workspace-store"), + workspace_quota_bytes: 1024 * 1024 * 1024, + max_active_executions: 2, + lease_ttl: std::time::Duration::from_secs(30), + tls: tls_server_config(root.clone(), &server_identity), + }, + Arc::new(LocalProcessRunner::default()), + resolver, + Arc::new(|_: &NodePrincipal, _operation| true), + ) + .await + .expect("node must start"); + + // A base URL the node does not route is how a node that predates + // this contract behaves: the path is unknown, so the node answers + // 404 rather than 403. + let client_temp = TempDir::new().unwrap(); + let legacy = NodeClient::new( + format!("https://localhost:{}/legacy", server.local_addr().port()), + write_client_config(&client_temp, root.as_ref(), &client_identity), + ) + .unwrap(); + assert!(matches!( + legacy.telemetry().await, + Err(eggwork_client::ClientError::TelemetryUnsupported) + )); + + server.shutdown().await; + server.wait().await.unwrap(); + } + + #[tokio::test] + async fn telemetry_does_not_change_execution_semantics() { + init_tls(); + let (root, server_identity, client_identity, _) = tls_material(); + let temp = TempDir::new().unwrap(); + let work_root = temp.path().join("work"); + fs::create_dir_all(&work_root).unwrap(); + let provider = FakeProvider::start().await; + let principal = eggwork_core::PrincipalId::new("controller-a").unwrap(); + let resolver = Arc::new(FingerprintPrincipalResolver::new([( + FingerprintPrincipalResolver::fingerprint(client_identity.cert.as_ref()), + principal, + )])); + let server = NodeServer::start( + NodeConfig { + host_telemetry: Some(telemetry_config(&provider.endpoint())), + node_id: NodeId::new("node-a").unwrap(), + bind: "127.0.0.1:0".parse().unwrap(), + execution_root: work_root, + database_path: temp.path().join("node.sqlite"), + blob_root: temp.path().join("blob-store"), + blob_quota_bytes: 1024 * 1024 * 1024, + workspace_root: temp.path().join("workspace-store"), + workspace_quota_bytes: 1024 * 1024 * 1024, + max_active_executions: 2, + lease_ttl: std::time::Duration::from_secs(30), + tls: tls_server_config(root.clone(), &server_identity), + }, + Arc::new(LocalProcessRunner::default()), + resolver, + Arc::new(|_: &NodePrincipal, _operation| true), + ) + .await + .expect("node must start"); + + let client_temp = TempDir::new().unwrap(); + let client = NodeClient::new( + format!("https://localhost:{}", server.local_addr().port()), + write_client_config(&client_temp, root.as_ref(), &client_identity), + ) + .unwrap(); + wait_for_state(&server, TelemetryProviderState::Ready).await; + + let handle = execution_handle("telemetry-execution"); + let marker = temp.path().join("telemetry-marker"); + let stream = client + .execute( + &execution_spec(vec![ + "/bin/sh".into(), + "-c".into(), + format!("touch {}", marker.display()), + ]), + &handle, + ) + .await + .expect("execution must still be admitted"); + let events = stream + .into_events() + .try_collect::>() + .await + .expect("event stream"); + assert!( + events.iter().any(|event| matches!( + &event.kind, + ExecutionEventKind::State(ExecutionState::Succeeded) + )), + "execution must still reach a terminal state" + ); + assert!(marker.exists(), "execution must still run its command"); + + let status = client.status().await.expect("status"); + assert_eq!(status.node_id, NodeId::new("node-a").unwrap()); + // The node's execution surface is unchanged by the telemetry read. + assert!(!status.capabilities.features.is_empty()); + assert!( + !status + .capabilities + .features + .iter() + .any(|feature| feature.contains("telemetry")), + "telemetry is not an execution capability" + ); + + server.shutdown().await; + server.wait().await.unwrap(); + } + } + + /// The client's refusal to accept a telemetry response it cannot trust. + mod telemetry_client_validation { + use super::*; + use eggwork_core::{ + HostTelemetry, NodeTelemetry, TelemetryCpu, TelemetryMetric, TelemetryProviderState, + TelemetrySource, + }; + + /// A service that answers every request with one canned status and + /// body, so the client's acceptance rules can be driven directly. + struct CannedService { + status: u16, + body: Vec, + } + + impl Service for CannedService { + fn call(&self, _request: Request) -> ServiceFuture<'_> { + let status = self.status; + let body = self.body.clone(); + Box::pin(async move { + Ok(Response::builder() + .status(StatusCode::new(status).expect("valid HTTP status")) + .header("content-type", "application/json") + .and_then(|builder| builder.body(ResponseBody::Bytes(body))) + .expect("response")) + }) + } + } + + async fn serve( + status: u16, + body: Vec, + tls: TlsServerConfig, + ) -> (SocketAddr, ServerHandle) { + let bind: SocketAddr = "127.0.0.1:0".parse().unwrap(); + let runtime = RuntimeConfig::builder() + .bind(bind) + .max_request_body_bytes(1024) + .tls_config(tls.into_server_config()) + .build() + .expect("runtime config"); + let server = Server::builder() + .runtime(runtime) + .bind(bind) + .build() + .expect("server"); + let handle = server + .start_with_service(CannedService { status, body }) + .await + .expect("server start"); + handle.ready().await.expect("server ready"); + (handle.local_addr(), handle) + } + + fn observation() -> HostTelemetry { + HostTelemetry { + observed_at_unix_ms: artifact::now_unix_ms(), + sample_interval_ms: 1_000, + cpu: TelemetryMetric::Value(TelemetryCpu { + logical_cores: 8, + usage_pct: 12.5, + iowait_pct: None, + }), + memory: TelemetryMetric::Unsupported, + load: TelemetryMetric::Unsupported, + swap: TelemetryMetric::Unsupported, + disk: TelemetryMetric::Unsupported, + disk_io: TelemetryMetric::Unsupported, + network: TelemetryMetric::Unsupported, + } + } + + fn telemetry() -> NodeTelemetry { + NodeTelemetry { + schema_version: 1, + node_id: NodeId::new("node-a").unwrap(), + source: TelemetrySource::Gregg, + state: TelemetryProviderState::Ready, + age_ms: Some(12), + last_error: None, + observation: Some(observation()), + } + } + + async fn client_for(status: u16, body: Vec) -> (NodeClient, ServerHandle, TempDir) { + init_tls(); + let (root, server_identity, client_identity, _) = tls_material(); + let client_temp = TempDir::new().unwrap(); + let (address, handle) = serve( + status, + body, + tls_server_config(root.clone(), &server_identity), + ) + .await; + let client = NodeClient::new( + format!("https://localhost:{}", address.port()), + write_client_config(&client_temp, root.as_ref(), &client_identity), + ) + .expect("client"); + (client, handle, client_temp) + } + + #[tokio::test] + async fn a_well_formed_response_is_accepted() { + let body = serde_json::to_vec(&telemetry()).unwrap(); + let (client, handle, _temp) = client_for(200, body).await; + let observed = client.telemetry().await.expect("accepted"); + assert_eq!(observed.state, TelemetryProviderState::Ready); + assert_eq!(observed.node_id, NodeId::new("node-a").unwrap()); + handle.shutdown(); + } + + #[tokio::test] + async fn a_malformed_body_is_refused() { + let (client, handle, _temp) = client_for(200, b"not json".to_vec()).await; + assert!(matches!( + client.telemetry().await, + Err(eggwork_client::ClientError::InvalidResponse) + )); + handle.shutdown(); + } + + #[tokio::test] + async fn an_oversized_body_is_refused() { + // A response that is far larger than the telemetry contract allows + // must be refused rather than parsed. + let body = vec![b'x'; 256 * 1024]; + let (client, handle, _temp) = client_for(200, body).await; + assert!(matches!( + client.telemetry().await, + Err(eggwork_client::ClientError::InvalidResponse) + )); + handle.shutdown(); + } + + #[tokio::test] + async fn an_unknown_schema_version_is_refused() { + let mut payload = telemetry(); + payload.schema_version = 2; + let body = serde_json::to_vec(&payload).unwrap(); + let (client, handle, _temp) = client_for(200, body).await; + assert!(matches!( + client.telemetry().await, + Err(eggwork_client::ClientError::ProtocolIncompatible) + )); + handle.shutdown(); + } + + #[tokio::test] + async fn an_unknown_source_is_refused() { + let body = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "node_id": "node-a", + "source": "something-else", + "state": "ready", + "age_ms": 1, + "last_error": null, + "observation": serde_json::to_value(observation()).unwrap() + })) + .unwrap(); + let (client, handle, _temp) = client_for(200, body).await; + assert!(matches!( + client.telemetry().await, + Err(eggwork_client::ClientError::InvalidResponse) + )); + handle.shutdown(); + } + + #[tokio::test] + async fn a_response_whose_state_contradicts_its_observation_is_refused() { + let mut payload = telemetry(); + // A ready node with no observation claims a measurement it does + // not have. + payload.observation = None; + let body = serde_json::to_vec(&payload).unwrap(); + let (client, handle, _temp) = client_for(200, body).await; + assert!(matches!( + client.telemetry().await, + Err(eggwork_client::ClientError::InvalidResponse) + )); + handle.shutdown(); + } + + #[tokio::test] + async fn a_response_with_an_out_of_range_measurement_is_refused() { + let mut payload = telemetry(); + if let Some(observation) = payload.observation.as_mut() { + observation.cpu = TelemetryMetric::Value(TelemetryCpu { + logical_cores: 8, + usage_pct: 1_000.0, + iowait_pct: None, + }); + } + let body = serde_json::to_vec(&payload).unwrap(); + let (client, handle, _temp) = client_for(200, body).await; + assert!(matches!( + client.telemetry().await, + Err(eggwork_client::ClientError::InvalidResponse) + )); + handle.shutdown(); + } + + #[tokio::test] + async fn a_response_whose_number_does_not_fit_is_refused() { + let body = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "node_id": "node-a", + "source": "gregg", + "state": "ready", + "age_ms": 1, + "last_error": null, + "observation": { + "observed_at_unix_ms": artifact::now_unix_ms(), + "sample_interval_ms": 1000, + "cpu": { "value": { "logical_cores": 8, "usage_pct": 1e300, "iowait_pct": null } }, + "memory": "unsupported", + "load": "unsupported", + "swap": "unsupported", + "disk": "unsupported", + "disk_io": "unsupported", + "network": "unsupported" + } + })) + .unwrap(); + let (client, handle, _temp) = client_for(200, body).await; + assert!(matches!( + client.telemetry().await, + Err(eggwork_client::ClientError::InvalidResponse) + )); + handle.shutdown(); + } + } } diff --git a/crates/eggwork-server/src/operations.rs b/crates/eggwork-server/src/operations.rs index 3df2602..a9469be 100644 --- a/crates/eggwork-server/src/operations.rs +++ b/crates/eggwork-server/src/operations.rs @@ -2,7 +2,8 @@ use crate::{ Authorizer, FingerprintPrincipalResolver, NodeConfig, NodeGcReport, NodePrincipal, NodeServer, - Operation, artifact::ArtifactStore, blob::BlobStore, workspace::WorkspaceManager, + Operation, artifact::ArtifactStore, blob::BlobStore, telemetry::HostTelemetryConfig, + workspace::WorkspaceManager, }; use eggserve_core::tls::TlsServerConfig; use eggwork_core::{ExecutionGeneration, ExecutionId, NodeId, PrincipalId}; @@ -77,6 +78,39 @@ pub struct OperatorConfig { pub sandbox_helper: Option, pub tls: TlsFiles, pub clients: Vec, + /// Optional host-telemetry provider. + /// + /// Absent means the node claims no host measurements at all: no provider + /// is created, no task is started, and no telemetry is served. + pub host_telemetry: Option, +} + +/// Operator configuration for the optional host-telemetry provider. +/// +/// The endpoint is a loopback address of a locally installed telemetry +/// daemon. It is validated when the configuration is validated, not when the +/// node starts, so a misconfigured endpoint is refused at load time. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HostTelemetrySettings { + /// Loopback status endpoint of the local provider. + pub endpoint: String, + /// Seconds between provider polls. + pub refresh_interval_seconds: u64, + /// Seconds a cached observation stays fresh. + pub freshness_seconds: u64, +} + +impl HostTelemetrySettings { + /// Validate the settings into a provider configuration. + pub fn config(&self) -> Result { + HostTelemetryConfig::new( + &self.endpoint, + self.refresh_interval_seconds, + self.freshness_seconds, + ) + .map_err(|_| OperationsError::Config) + } } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -237,6 +271,13 @@ impl OperatorConfig { } } let _ = self.tls_config()?; + if let Some(settings) = &self.host_telemetry { + // A refused endpoint must fail the whole configuration: a node + // that silently ignored a misconfigured provider would look like a + // node with no telemetry at all, and the operator would have no + // way to tell that from a node whose provider is down. + settings.config()?; + } for path in [&self.execution_root, &self.blob_root, &self.workspace_root] { let meta = fs::symlink_metadata(path).map_err(|_| OperationsError::Config)?; if !meta.is_dir() || meta.file_type().is_symlink() || !trusted_directory(&meta) { @@ -328,6 +369,11 @@ impl OperatorConfig { max_active_executions: self.max_active_executions, lease_ttl: Duration::from_secs(self.lease_ttl_seconds), tls: self.tls_config()?, + host_telemetry: self + .host_telemetry + .as_ref() + .map(HostTelemetrySettings::config) + .transpose()?, }) } @@ -372,6 +418,7 @@ fn operation(name: &str) -> Option { Some(match name { "capabilities" => Operation::Capabilities, "status" => Operation::Status, + "telemetry" => Operation::Telemetry, "execute" => Operation::Execute, "observe" => Operation::Observe, "cancel" => Operation::Cancel, @@ -486,6 +533,23 @@ pub async fn doctor(config: &OperatorConfig) -> DoctorReport { } .into(), }); + // The provider is *not* contacted here. `doctor` is an offline diagnostic: + // a node whose telemetry provider happens to be down is still a healthy + // node, and a check that failed on the provider's availability would + // report the operator's provider outage as the node's fault. The endpoint + // is not echoed either, so a diagnostic line cannot carry a provider + // address into a log. + checks.push(DoctorCheck { + name: "host-telemetry", + ok: true, + detail: match config.host_telemetry.as_ref() { + None => "host telemetry is disabled; the node reports no host measurements".into(), + Some(settings) => format!( + "host telemetry is enabled against a validated loopback provider endpoint (refresh {}s, freshness {}s)", + settings.refresh_interval_seconds, settings.freshness_seconds + ), + }, + }); // The helper is verified here and again inside `execution_capabilities`, which // calls `verify_trusted_helper` on the same path. That is deliberate: the // runner's answer is the one that gates admission, and caching a trust @@ -1158,6 +1222,7 @@ mod tests { certificate_sha256: "ab".repeat(32), operations: vec!["status".into()], }], + host_telemetry: None, } } @@ -1170,6 +1235,168 @@ mod tests { assert!(encoded.contains("[REDACTED]")); } + /// A configuration document in the shape the loader accepts. + fn config_json(root: &Path) -> serde_json::Value { + serde_json::json!({ + "schema_version": 1, + "node_id": "node-test", + "bind": "127.0.0.1:0", + "execution_root": root.join("execution"), + "database_path": root.join("state/executions.sqlite"), + "blob_root": root.join("blobs"), + "blob_quota_bytes": 4096, + "workspace_root": root.join("workspaces"), + "workspace_quota_bytes": 4096, + "max_active_executions": 2, + "lease_ttl_seconds": 60, + "tls": { + "certificate_chain": root.join("server.pem"), + "private_key": root.join("server-key.pem"), + "client_ca": root.join("client-ca.pem") + }, + "clients": [{ + "principal_id": "controller", + "certificate_sha256": "ab".repeat(32), + "operations": ["status"] + }] + }) + } + + #[test] + fn a_configuration_without_host_telemetry_asks_for_none() { + let temp = TempDir::new().unwrap(); + let parsed: OperatorConfig = + serde_json::from_value(config_json(temp.path())).expect("config"); + assert!(parsed.host_telemetry.is_none()); + } + + #[test] + fn a_configuration_with_host_telemetry_is_read_and_validated() { + let temp = TempDir::new().unwrap(); + let mut value = config_json(temp.path()); + value["host_telemetry"] = serde_json::json!({ + "endpoint": "http://127.0.0.1:18080/v2/status", + "refresh_interval_seconds": 15, + "freshness_seconds": 60 + }); + let parsed: OperatorConfig = serde_json::from_value(value).expect("config"); + let settings = parsed.host_telemetry.expect("settings"); + assert!(settings.config().is_ok()); + } + + #[test] + fn a_misconfigured_host_telemetry_endpoint_is_refused() { + for endpoint in [ + "http://example.com:18080/v2/status", + "http://localhost:18080/v2/status", + "https://127.0.0.1:18080/v2/status", + "http://127.0.0.1:18080/", + "http://127.0.0.1:18080/v2/status?probe=1", + ] { + let settings = HostTelemetrySettings { + endpoint: endpoint.into(), + refresh_interval_seconds: 15, + freshness_seconds: 60, + }; + assert!( + settings.config().is_err(), + "endpoint {endpoint} must be refused" + ); + } + } + + #[test] + fn an_unknown_host_telemetry_field_is_refused() { + let temp = TempDir::new().unwrap(); + let mut value = config_json(temp.path()); + value["host_telemetry"] = serde_json::json!({ + "endpoint": "http://127.0.0.1:18080/v2/status", + "refresh_interval_seconds": 15, + "freshness_seconds": 60, + "unexpected": true + }); + assert!(serde_json::from_value::(value).is_err()); + } + + /// A configuration with real TLS material and owner-only directories. + fn installed_config(root: &Path) -> OperatorConfig { + use rcgen::{BasicConstraints, CertificateParams, IsCa, KeyPair}; + let _ = rustls::crypto::ring::default_provider().install_default(); + let ca_key = KeyPair::generate().unwrap(); + let mut ca_params = CertificateParams::new(vec!["eggwork test CA".into()]).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + let ca = ca_params.self_signed(&ca_key).unwrap(); + let server_key = KeyPair::generate().unwrap(); + let server_params = CertificateParams::new(vec!["localhost".into()]).unwrap(); + let server = server_params.signed_by(&server_key, &ca, &ca_key).unwrap(); + fs::write(root.join("server.pem"), server.pem()).unwrap(); + fs::write(root.join("client-ca.pem"), ca.pem()).unwrap(); + let key_path = root.join("server-key.pem"); + fs::write(&key_path, server_key.serialize_pem()).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + // The loader refuses group- or world-writable material, and the + // process umask is not ours to rely on. + fs::set_permissions(&key_path, fs::Permissions::from_mode(0o600)).unwrap(); + fs::set_permissions(root.join("server.pem"), fs::Permissions::from_mode(0o644)) + .unwrap(); + fs::set_permissions( + root.join("client-ca.pem"), + fs::Permissions::from_mode(0o644), + ) + .unwrap(); + } + for name in ["execution", "blobs", "workspaces", "state"] { + let path = root.join(name); + fs::create_dir_all(&path).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); + } + } + let parsed: OperatorConfig = serde_json::from_value(config_json(root)).expect("config"); + parsed + } + + #[tokio::test] + async fn doctor_reports_that_host_telemetry_is_off_by_default() { + let temp = TempDir::new().unwrap(); + let config = installed_config(temp.path()); + assert!(config.validate().is_ok()); + let report = doctor(&config).await; + let check = report + .checks + .iter() + .find(|check| check.name == "host-telemetry") + .expect("host-telemetry check"); + assert!(check.ok); + assert!(check.detail.contains("disabled")); + } + + #[tokio::test] + async fn doctor_reports_a_configured_host_telemetry_provider() { + let temp = TempDir::new().unwrap(); + let mut config = installed_config(temp.path()); + config.host_telemetry = Some(HostTelemetrySettings { + endpoint: "http://127.0.0.1:18080/v2/status".into(), + refresh_interval_seconds: 15, + freshness_seconds: 60, + }); + assert!(config.validate().is_ok()); + let report = doctor(&config).await; + let check = report + .checks + .iter() + .find(|check| check.name == "host-telemetry") + .expect("host-telemetry check"); + assert!(check.ok); + assert!(check.detail.contains("enabled")); + // A diagnostic line must not carry the provider's address. + assert!(!check.detail.contains("127.0.0.1")); + } + #[test] fn drain_state_survives_process_restart_and_undrain_removes_marker() { let temp = TempDir::new().unwrap(); diff --git a/crates/eggwork-server/src/telemetry.rs b/crates/eggwork-server/src/telemetry.rs new file mode 100644 index 0000000..734b2bf --- /dev/null +++ b/crates/eggwork-server/src/telemetry.rs @@ -0,0 +1,1096 @@ +//! Optional, default-off host telemetry. +//! +//! A node may be configured to read *host-wide* measurements from a local +//! telemetry provider and expose them to callers. The feature is opt-in: with +//! no configuration the node creates no provider, starts no task, and claims +//! nothing. +//! +//! Three properties are load-bearing here and are enforced by construction +//! rather than by convention: +//! +//! * **The endpoint is a validated loopback URL.** The configured endpoint is +//! parsed and checked once, at load time, against a closed rule set: plain +//! HTTP, an explicit TCP port, an IP literal that is a loopback address, and +//! exactly the provider's status path. Hostnames — including `localhost` — +//! are refused, so no DNS answer can move the request off the loopback +//! interface. The client is built without redirect and proxy support, so a +//! redirect hop or an inherited `HTTP_PROXY` cannot move it either. +//! * **One owner polls.** A single background task performs every provider +//! request. Readers consult the cache; they never trigger a provider +//! request, so a caller cannot amplify into a poll storm. +//! * **Failures are bounded and typed.** Every failure becomes one of a closed +//! set of categories. No response body, URL, or host path is ever carried +//! into a category, a log line, or a metric. +//! +//! The measurements themselves are normalized into +//! [`eggwork_core::HostTelemetry`], which carries no provider vocabulary. The +//! provider's own wire types stop at this module's boundary. + +use std::{ + sync::Arc, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; + +use async_trait::async_trait; +use eggfetch_core::{Client, Error as FetchError, Timeout}; +use eggwork_core::{ + HostTelemetry, TelemetryCpu, TelemetryDisk, TelemetryDiskIo, TelemetryErrorCategory, + TelemetryLoad, TelemetryMemory, TelemetryMetric, TelemetryNetwork, TelemetryProviderState, + TelemetrySwap, +}; +use gregg_protocol::{ + ReadinessState, + v2::{DiskIoPayload, HealthResponseV2, NetworkPayload, SCHEMA_VERSION_V2, StatusPayloadV2}, +}; +use thiserror::Error; +use tokio::{ + sync::{Mutex, RwLock}, + task::JoinHandle, + time::Instant, +}; +use tokio_util::sync::CancellationToken; +use url::{Host, Url}; + +/// The only path the provider protocol serves a status payload on. +const PROVIDER_STATUS_PATH: &str = "/v2/status"; + +/// Largest decoded provider response the adapter accepts. +/// +/// The provider's own payload is a bounded document; a larger body is a +/// defect or an attack, and either way it is refused rather than truncated. +const MAX_PROVIDER_BODY_BYTES: usize = 256 * 1024; + +/// Deadline for establishing the loopback connection. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(2); + +/// Deadline for the whole request, including reading the body. +const REQUEST_TIMEOUT: Duration = Duration::from_secs(5); + +/// Largest accepted difference between the provider's wall-clock timestamp and +/// the node's own clock. +/// +/// A provider timestamp in the future is a clock-skew defect, not a fresh +/// sample, and is refused rather than treated as indefinitely fresh. +const MAX_CLOCK_SKEW: Duration = Duration::from_secs(30); + +/// Longest delay between two provider attempts after repeated failures. +const MAX_BACKOFF: Duration = Duration::from_secs(300); + +/// Smallest accepted refresh interval. +const MIN_REFRESH_SECONDS: u64 = 1; + +/// Largest accepted refresh interval. +const MAX_REFRESH_SECONDS: u64 = 3_600; + +/// Largest accepted freshness bound. +const MAX_FRESHNESS_SECONDS: u64 = 3_600; + +/// Why a host-telemetry endpoint or cadence was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] +pub enum TelemetryConfigError { + /// The endpoint is not a plain-HTTP loopback URL with an explicit port and + /// exactly the provider status path. + #[error( + "host telemetry endpoint must be a loopback http URL with an explicit port and the provider status path" + )] + InvalidEndpoint, + /// The refresh interval is outside the accepted range. + #[error("host telemetry refresh interval is out of range")] + InvalidRefreshInterval, + /// The freshness bound is outside the accepted range, or is shorter than + /// the refresh interval. + #[error("host telemetry freshness bound is out of range")] + InvalidFreshness, +} + +/// A validated host-telemetry configuration. +/// +/// The endpoint is validated once, here, so that no later stage has to +/// re-derive whether it is safe to contact. +#[derive(Debug, Clone)] +pub struct HostTelemetryConfig { + endpoint: String, + refresh_interval: Duration, + freshness: Duration, +} + +impl HostTelemetryConfig { + /// Validate and build a configuration. + /// + /// `endpoint` must be a plain-HTTP loopback URL naming an explicit TCP + /// port and exactly the provider's status path. `refresh_seconds` is how + /// often the owner polls, and `freshness_seconds` is how long a cached + /// observation stays fresh; the freshness bound must not be shorter than + /// the refresh interval. + pub fn new( + endpoint: &str, + refresh_seconds: u64, + freshness_seconds: u64, + ) -> Result { + if !(MIN_REFRESH_SECONDS..=MAX_REFRESH_SECONDS).contains(&refresh_seconds) { + return Err(TelemetryConfigError::InvalidRefreshInterval); + } + if !(MIN_REFRESH_SECONDS..=MAX_FRESHNESS_SECONDS).contains(&freshness_seconds) { + return Err(TelemetryConfigError::InvalidFreshness); + } + if freshness_seconds < refresh_seconds { + return Err(TelemetryConfigError::InvalidFreshness); + } + let endpoint = validate_endpoint(endpoint)?; + Ok(Self { + endpoint, + refresh_interval: Duration::from_secs(refresh_seconds), + freshness: Duration::from_secs(freshness_seconds), + }) + } + + /// The validated loopback endpoint. + pub fn endpoint(&self) -> &str { + &self.endpoint + } + + /// How often the owner polls the provider. + pub fn refresh_interval(&self) -> Duration { + self.refresh_interval + } + + /// How long a cached observation stays fresh. + pub fn freshness(&self) -> Duration { + self.freshness + } +} + +/// Validate a provider endpoint and return its normalized form. +/// +/// The rule set is closed on purpose. A provider that lives on this machine +/// is addressed by an IP literal, so there is no name to resolve and no +/// answer to be rebound between validation and use. Everything the caller +/// could otherwise smuggle past the check — a scheme other than plain HTTP, a +/// userinfo section, a query string, a fragment, another path, a missing or +/// non-numeric port, a hostname of any kind — is refused. +fn validate_endpoint(raw: &str) -> Result { + let parsed = Url::parse(raw).map_err(|_| TelemetryConfigError::InvalidEndpoint)?; + if parsed.scheme() != "http" { + return Err(TelemetryConfigError::InvalidEndpoint); + } + if parsed.cannot_be_a_base() { + return Err(TelemetryConfigError::InvalidEndpoint); + } + if !parsed.username().is_empty() || parsed.password().is_some() { + return Err(TelemetryConfigError::InvalidEndpoint); + } + if parsed.query().is_some() || parsed.fragment().is_some() { + return Err(TelemetryConfigError::InvalidEndpoint); + } + if parsed.path() != PROVIDER_STATUS_PATH { + return Err(TelemetryConfigError::InvalidEndpoint); + } + // The port must be named explicitly. `Url::port` reports `None` both for + // an endpoint without a port and for one naming the scheme default, + // because the parser normalizes the latter away, so the authority is + // inspected directly. + if !names_explicit_port(raw) { + return Err(TelemetryConfigError::InvalidEndpoint); + } + let Some(port) = parsed.port_or_known_default() else { + return Err(TelemetryConfigError::InvalidEndpoint); + }; + if port == 0 { + return Err(TelemetryConfigError::InvalidEndpoint); + } + match parsed.host() { + Some(Host::Ipv4(address)) if address.is_loopback() => { + // The endpoint the client is finally given must name the address + // literally. The URL parser already rewrites the alternative + // spellings of an IPv4 address to the canonical form, and this + // check refuses anything it did not. + if parsed.host_str() != Some(address.to_string().as_str()) { + return Err(TelemetryConfigError::InvalidEndpoint); + } + } + Some(Host::Ipv6(address)) if address.is_loopback() => { + if parsed.host_str() != Some(format!("[{address}]").as_str()) { + return Err(TelemetryConfigError::InvalidEndpoint); + } + } + _ => return Err(TelemetryConfigError::InvalidEndpoint), + } + Ok(parsed.to_string()) +} + +/// Whether the raw endpoint names an explicit TCP port. +/// +/// The authority is the text between the scheme and the path. Userinfo is +/// stripped first, and an IPv6 literal is bracketed, so its colons are not a +/// port separator. +fn names_explicit_port(raw: &str) -> bool { + let Some((_, after_scheme)) = raw.split_once("://") else { + return false; + }; + let authority = after_scheme + .split(['/', '?', '#']) + .next() + .unwrap_or_default(); + let authority = authority + .rsplit_once('@') + .map_or(authority, |(_, host)| host); + if let Some(rest) = authority.strip_prefix('[') { + return rest + .split_once(']') + .is_some_and(|(_, tail)| tail.starts_with(':') && tail.len() > 1); + } + authority + .rsplit_once(':') + .is_some_and(|(_, port)| !port.is_empty() && port.bytes().all(|byte| byte.is_ascii_digit())) +} + +/// Why a provider attempt did not produce an observation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] +pub enum TelemetryError { + /// The loopback connection could not be established. + #[error("host telemetry provider is unreachable")] + Connection, + /// The request exceeded its deadline. + #[error("host telemetry provider timed out")] + Timeout, + /// The provider answered with an unexpected status. + #[error("host telemetry provider returned an unexpected status")] + HttpStatus, + /// The response body was not the expected document. + #[error("host telemetry provider returned a malformed response")] + Malformed, + /// The response carried an unsupported schema version. + #[error("host telemetry provider returned an unsupported schema version")] + SchemaVersion, + /// The response parsed but violated the protocol's invariants. + #[error("host telemetry provider returned an invalid response")] + Invalid, + /// The response exceeded the accepted body size. + #[error("host telemetry provider response was too large")] + TooLarge, + /// The provider's timestamp is outside the accepted clock-skew window. + #[error("host telemetry provider timestamp is outside the accepted clock-skew window")] + ClockSkew, +} + +impl TelemetryError { + /// The bounded category reported for this failure. + pub fn category(&self) -> TelemetryErrorCategory { + match self { + Self::Connection => TelemetryErrorCategory::Connection, + Self::Timeout => TelemetryErrorCategory::Timeout, + Self::HttpStatus => TelemetryErrorCategory::HttpStatus, + Self::Malformed => TelemetryErrorCategory::Malformed, + Self::SchemaVersion => TelemetryErrorCategory::SchemaVersion, + Self::Invalid => TelemetryErrorCategory::Invalid, + Self::TooLarge => TelemetryErrorCategory::TooLarge, + Self::ClockSkew => TelemetryErrorCategory::ClockSkew, + } + } +} + +/// What a provider attempt produced. +#[derive(Debug, Clone, PartialEq)] +pub enum ProviderOutcome { + /// A validated, normalized observation. + Observed(HostTelemetry), + /// The provider is alive but has not produced an observation yet. + Warming, +} + +/// A read-only source of host-wide measurements. +/// +/// The seam exists so the node's polling owner can be exercised against a +/// fake, and so a second provider could be added without touching the cache +/// or the node lifecycle. +#[async_trait] +pub trait HostTelemetryProvider: Send + Sync + 'static { + /// Fetch one observation, or say why there is none. + async fn observe(&self) -> Result; +} + +/// The provider adapter that reads a local Gregg daemon. +/// +/// The request is issued over plain HTTP to the validated loopback endpoint. +/// The client is built without redirect and proxy support, so a `3xx` is +/// reported as an unexpected status rather than followed, and no ambient +/// `HTTP_PROXY` setting is consulted. +pub struct GreggTelemetryProvider { + client: Client, + endpoint: String, +} + +impl GreggTelemetryProvider { + /// Build a provider for a validated configuration. + pub fn new(config: &HostTelemetryConfig) -> Self { + Self::with_deadlines(config, CONNECT_TIMEOUT, REQUEST_TIMEOUT) + } + + /// Build a provider with explicit connection and request deadlines. + /// + /// The deadlines bound how long a single provider attempt may take. The + /// default pair is used by the node; a shorter pair makes a stuck + /// provider fail faster, and a longer one is only useful for a provider + /// that is known to answer slowly. + pub fn with_deadlines( + config: &HostTelemetryConfig, + connect: Duration, + total: Duration, + ) -> Self { + let client = Client::builder() + .timeout( + Timeout::builder() + .connect(connect) + .read(total) + .total(total) + .build(), + ) + .max_decoded_body_size(MAX_PROVIDER_BODY_BYTES) + .build(); + Self { + client, + endpoint: config.endpoint().to_owned(), + } + } +} + +#[async_trait] +impl HostTelemetryProvider for GreggTelemetryProvider { + async fn observe(&self) -> Result { + let mut response = self + .client + .get(&self.endpoint) + .map_err(classify_fetch_error)? + .send() + .await + .map_err(classify_fetch_error)?; + let status = response.status().as_u16(); + if status == 200 { + let body = response.bytes().await.map_err(classify_fetch_error)?; + if body.len() > MAX_PROVIDER_BODY_BYTES { + return Err(TelemetryError::TooLarge); + } + return decode_status(&body); + } + if status == 503 { + // A warming daemon answers with a health envelope rather than a + // status payload. That is a distinct state, not a failure. + let body = response.bytes().await.map_err(classify_fetch_error)?; + if let Ok(health) = serde_json::from_slice::(&body) + && health.state == ReadinessState::Warming + { + return Ok(ProviderOutcome::Warming); + } + } + Err(TelemetryError::HttpStatus) + } +} + +/// Map a transport failure onto a bounded category. +fn classify_fetch_error(error: FetchError) -> TelemetryError { + match error { + FetchError::Timeout { .. } | FetchError::TransportIoTimeout { .. } => { + TelemetryError::Timeout + } + FetchError::DecodedBodyTooLarge | FetchError::DecompressionRatioExceeded => { + TelemetryError::TooLarge + } + FetchError::Body(_) | FetchError::Protocol(_) => TelemetryError::Malformed, + FetchError::Connect(_) + | FetchError::CustomTransport(_) + | FetchError::Io(_) + | FetchError::Hyper(_) + | FetchError::HyperClient(_) => TelemetryError::Connection, + _ => TelemetryError::Connection, + } +} + +/// Decode and validate a provider status payload, then normalize it. +/// +/// The provider's own validation is applied first, so a payload that the +/// provider's protocol would reject never reaches the normalized form. The +/// normalized form is validated again, because the two check different +/// things: the provider validates its own schema, and this validates the +/// translation. +fn decode_status(body: &[u8]) -> Result { + let payload: StatusPayloadV2 = + serde_json::from_slice(body).map_err(|_| TelemetryError::Malformed)?; + if payload.snapshot.schema_version != SCHEMA_VERSION_V2 { + return Err(TelemetryError::SchemaVersion); + } + payload.validate().map_err(|_| TelemetryError::Invalid)?; + if exceeds_clock_skew(payload.snapshot.observed_at_unix_ms) { + return Err(TelemetryError::ClockSkew); + } + let observation = normalize(&payload)?; + observation + .validate() + .map_err(|_| TelemetryError::Invalid)?; + Ok(ProviderOutcome::Observed(observation)) +} + +/// Translate a validated provider payload into the normalized vocabulary. +/// +/// Only host-wide measurements are carried across. The provider's system +/// identity, drive names, device identifiers, and interface details are +/// dropped here and never leave the node. +fn normalize(payload: &StatusPayloadV2) -> Result { + let snapshot = &payload.snapshot; + let capabilities = &snapshot.capabilities; + + let cpu = TelemetryMetric::Value(TelemetryCpu { + logical_cores: snapshot.cpu.logical_cores, + usage_pct: snapshot.cpu.usage_pct, + iowait_pct: capabilities + .cpu_iowait + .then_some(snapshot.cpu.iowait_pct) + .flatten(), + }); + + let memory = TelemetryMetric::Value(TelemetryMemory { + available_bytes: snapshot + .memory + .total_bytes + .saturating_sub(snapshot.memory.used_bytes), + total_bytes: snapshot.memory.total_bytes, + used_bytes: snapshot.memory.used_bytes, + }); + + let load = match (capabilities.load_average, snapshot.load) { + (true, Some(load)) => TelemetryMetric::Value(TelemetryLoad { + one: load.one, + five: load.five, + fifteen: load.fifteen, + }), + (true, None) => TelemetryMetric::Unknown, + (false, _) => TelemetryMetric::Unsupported, + }; + + let swap = match (capabilities.swap, snapshot.swap) { + (true, Some(swap)) => TelemetryMetric::Value(TelemetrySwap { + used_bytes: swap.used_bytes, + total_bytes: swap.total_bytes, + }), + (true, None) => TelemetryMetric::Unknown, + (false, _) => TelemetryMetric::Unsupported, + }; + + let disk = match payload.drives.as_ref() { + Some(drives) if !drives.is_empty() => { + let mut available_bytes = 0u64; + let mut total_bytes = 0u64; + for drive in drives { + available_bytes = + available_bytes.saturating_add(drive.available_bytes.unwrap_or(0)); + total_bytes = total_bytes.saturating_add(drive.total_bytes); + } + TelemetryMetric::Value(TelemetryDisk { + available_bytes, + total_bytes, + volume_count: u32::try_from(drives.len()).unwrap_or(u32::MAX), + }) + } + Some(_) => TelemetryMetric::Unknown, + None => TelemetryMetric::Unsupported, + }; + + let disk_io = match payload.disk_io.as_ref() { + Some(disk_io) => TelemetryMetric::Value(normalize_disk_io(disk_io)), + None => TelemetryMetric::Unsupported, + }; + + let network = match payload.network.as_ref() { + Some(network) => TelemetryMetric::Value(normalize_network(network)), + None => TelemetryMetric::Unsupported, + }; + + Ok(HostTelemetry { + observed_at_unix_ms: snapshot.observed_at_unix_ms, + sample_interval_ms: snapshot.sample_interval_ms, + cpu, + memory, + load, + swap, + disk, + disk_io, + network, + }) +} + +/// Carry the provider's de-duplicated aggregate disk throughput. +/// +/// The per-device records are dropped: they name devices, and the aggregate +/// is the only figure that is meaningful for a host-wide view. +fn normalize_disk_io(disk_io: &DiskIoPayload) -> TelemetryDiskIo { + TelemetryDiskIo { + read_bytes_per_sec: disk_io.aggregate_read_bytes_per_sec, + write_bytes_per_sec: disk_io.aggregate_write_bytes_per_sec, + } +} + +/// Carry the provider's de-duplicated aggregate network throughput. +/// +/// The per-interface records are dropped: they name interfaces, and the +/// aggregate is the only figure that is meaningful for a host-wide view. +fn normalize_network(network: &NetworkPayload) -> TelemetryNetwork { + TelemetryNetwork { + rx_bytes_per_sec: network.aggregate_rx_bytes_per_sec, + tx_bytes_per_sec: network.aggregate_tx_bytes_per_sec, + } +} + +/// The cached provider state, as a reader sees it. +#[derive(Debug, Clone, PartialEq)] +pub struct TelemetrySnapshot { + /// The provider's lifecycle state. + pub state: TelemetryProviderState, + /// The most recent validated observation, when there is one. + pub observation: Option, + /// How long ago, in milliseconds, the node received that observation. + pub age_ms: Option, + /// The category of the most recent failure, when there is one. + pub last_error: Option, +} + +#[derive(Debug, Clone)] +struct CacheEntry { + state: TelemetryProviderState, + observation: Option, + received_at: Option, + provider_stale: bool, + last_error: Option, +} + +impl CacheEntry { + fn disabled() -> Self { + Self { + state: TelemetryProviderState::Disabled, + observation: None, + received_at: None, + provider_stale: false, + last_error: None, + } + } +} + +/// The node's cached view of the host telemetry provider. +/// +/// The cache is the only thing a reader consults. It is cheap to clone and +/// cheap to read: a read never waits on the network, and never triggers a +/// provider request. +#[derive(Clone)] +pub struct TelemetryCache { + entry: Arc>, + freshness: Duration, +} + +impl TelemetryCache { + fn new(freshness: Duration) -> Self { + Self { + entry: Arc::new(RwLock::new(CacheEntry::disabled())), + freshness, + } + } + + /// A cache for a node with no provider configured. + pub fn disabled() -> Self { + Self::new(Duration::from_secs(0)) + } + + /// Read the current provider state. + /// + /// The reported age is measured on the node's monotonic clock, so a + /// wall-clock adjustment cannot make a stale sample look fresh or a fresh + /// sample look expired. The provider's own wall-clock timestamp stays in + /// the observation as provenance. + pub async fn snapshot(&self) -> TelemetrySnapshot { + let entry = self.entry.read().await; + let age_ms = entry + .received_at + .map(|received_at| received_at.elapsed().as_millis().min(u128::from(u64::MAX)) as u64); + let state = match entry.state { + TelemetryProviderState::Ready => { + let aged_out = age_ms.is_some_and(|age| age > self.freshness.as_millis() as u64); + if entry.provider_stale || aged_out { + TelemetryProviderState::Stale + } else { + TelemetryProviderState::Ready + } + } + other => other, + }; + TelemetrySnapshot { + state, + observation: entry.observation.clone(), + age_ms, + last_error: entry.last_error, + } + } + + /// Record a validated observation. + async fn record_observation(&self, observation: HostTelemetry, provider_stale: bool) { + let mut entry = self.entry.write().await; + entry.state = TelemetryProviderState::Ready; + entry.observation = Some(observation); + entry.received_at = Some(Instant::now()); + entry.provider_stale = provider_stale; + entry.last_error = None; + } + + /// Record that the provider is alive but has no observation yet. + async fn record_warming(&self) { + let mut entry = self.entry.write().await; + entry.state = TelemetryProviderState::Warming; + entry.last_error = None; + } + + /// Record a failure, keeping the last observation for context. + async fn record_failure(&self, category: TelemetryErrorCategory) { + let mut entry = self.entry.write().await; + entry.state = TelemetryProviderState::Unavailable; + entry.last_error = Some(category); + } + + /// Record that the provider answered with something unusable. + async fn record_invalid(&self) { + let mut entry = self.entry.write().await; + entry.state = TelemetryProviderState::Invalid; + entry.last_error = Some(TelemetryErrorCategory::Invalid); + } +} + +/// The node's polling owner for host telemetry. +/// +/// Exactly one task performs provider requests. It is the sole refresher, so +/// a burst of readers cannot turn into a burst of provider requests. +#[derive(Clone)] +pub struct TelemetryMonitor { + cache: TelemetryCache, + cancellation: CancellationToken, + task: Arc>>>, +} + +impl TelemetryMonitor { + /// A monitor for a node with no provider configured. + /// + /// No task is created. There is nothing to poll and nothing to claim. + pub fn disabled() -> Self { + Self { + cache: TelemetryCache::disabled(), + cancellation: CancellationToken::new(), + task: Arc::new(Mutex::new(None)), + } + } + + /// Start the polling owner for a configured provider. + pub fn start(provider: Arc, config: &HostTelemetryConfig) -> Self { + let cache = TelemetryCache::new(config.freshness()); + let cancellation = CancellationToken::new(); + let task = tokio::spawn(refresh_loop( + provider, + cache.clone(), + config.refresh_interval(), + config.freshness(), + cancellation.clone(), + )); + Self { + cache, + cancellation, + task: Arc::new(Mutex::new(Some(task))), + } + } + + /// The cache a reader consults. + pub fn cache(&self) -> &TelemetryCache { + &self.cache + } + + /// Stop the polling owner and wait for it to finish. + pub async fn shutdown(&self) { + self.cancellation.cancel(); + let task = self.task.lock().await.take(); + if let Some(task) = task { + task.abort(); + let _ = task.await; + } + } +} + +/// The polling owner. +/// +/// The first attempt happens as soon as the node is running: waiting for a +/// whole interval before the first sample would make a freshly started node +/// look empty for no reason. After that the cadence is the configured +/// interval, and failures back off so an absent provider is not polled in a +/// tight loop. +async fn refresh_loop( + provider: Arc, + cache: TelemetryCache, + refresh_interval: Duration, + freshness: Duration, + cancellation: CancellationToken, +) { + let mut failures: u32 = 0; + loop { + match provider.observe().await { + Ok(ProviderOutcome::Observed(observation)) => { + let provider_stale = is_provider_sample_stale(&observation, freshness); + cache.record_observation(observation, provider_stale).await; + failures = 0; + } + Ok(ProviderOutcome::Warming) => { + cache.record_warming().await; + failures = 0; + } + Err(error) => { + if error == TelemetryError::Invalid { + cache.record_invalid().await; + } else { + cache.record_failure(error.category()).await; + } + failures = failures.saturating_add(1); + } + } + let delay = if failures == 0 { + refresh_interval + } else { + backoff(refresh_interval, failures) + }; + tokio::select! { + _ = cancellation.cancelled() => break, + _ = tokio::time::sleep(delay) => {} + } + } +} + +/// Whether the provider's own timestamp is already older than the freshness +/// bound, and whether it lies implausibly in the future. +fn is_provider_sample_stale(observation: &HostTelemetry, freshness: Duration) -> bool { + let Some(now) = wall_clock_millis() else { + return false; + }; + if observation.observed_at_unix_ms > now.saturating_add(MAX_CLOCK_SKEW.as_millis() as u64) { + // A future timestamp is a clock-skew defect. The sample is refused by + // the caller before it reaches this point, so this is a belt-and-braces + // check rather than the primary defence. + return true; + } + let age = now.saturating_sub(observation.observed_at_unix_ms); + age > freshness.as_millis() as u64 +} + +/// The delay before the next attempt after `failures` consecutive failures. +fn backoff(refresh_interval: Duration, failures: u32) -> Duration { + let exponent = failures.saturating_sub(1).min(5); + let scaled = refresh_interval.saturating_mul(1u32 << exponent); + scaled.min(MAX_BACKOFF) +} + +/// The node's wall clock, in Unix milliseconds. +fn wall_clock_millis() -> Option { + let duration = SystemTime::now().duration_since(UNIX_EPOCH).ok()?; + u64::try_from(duration.as_millis()).ok() +} + +/// The clock-skew check applied to a provider timestamp. +pub fn exceeds_clock_skew(observed_at_unix_ms: u64) -> bool { + let Some(now) = wall_clock_millis() else { + return false; + }; + observed_at_unix_ms > now.saturating_add(MAX_CLOCK_SKEW.as_millis() as u64) +} + +#[cfg(test)] +mod tests { + use super::*; + use gregg_protocol::{ + LoadAverage, MemoryMetrics, SystemIdentity, + v2::{CpuMetricsV2, DriveMetrics, MetricCapabilitiesV2, StatusSnapshotV2, SwapMetrics}, + }; + + fn identity() -> SystemIdentity { + SystemIdentity { + name: "host".into(), + hostname: "host.local".into(), + os_name: "linux".into(), + os_version: "6.1".into(), + kernel_name: "Linux".into(), + kernel_release: "6.1.0".into(), + architecture: "x86_64".into(), + } + } + + fn snapshot(capabilities: MetricCapabilitiesV2) -> StatusSnapshotV2 { + StatusSnapshotV2 { + schema_version: SCHEMA_VERSION_V2, + observed_at_unix_ms: 1_700_000_000_000, + sample_interval_ms: 1_000, + capabilities, + system: identity(), + cpu: CpuMetricsV2 { + logical_cores: 8, + usage_pct: 12.5, + iowait_pct: capabilities.cpu_iowait.then_some(1.5), + }, + load: capabilities.load_average.then_some(LoadAverage { + one: 0.5, + five: 0.25, + fifteen: 0.125, + }), + memory: MemoryMetrics { + used_bytes: 4_000, + total_bytes: 8_000, + usage_pct: 50.0, + }, + swap: capabilities.swap.then_some(SwapMetrics { + used_bytes: 0, + total_bytes: 2_000, + usage_pct: 0.0, + }), + commit: capabilities + .memory_commit + .then_some(gregg_protocol::v2::CommitMetrics { + used_bytes: 1, + limit_bytes: 2, + usage_pct: 50.0, + }), + } + } + + fn payload(capabilities: MetricCapabilitiesV2) -> StatusPayloadV2 { + StatusPayloadV2 { + snapshot: snapshot(capabilities), + drives: None, + cpu_frequency_hz: None, + disk_io: None, + network: None, + } + } + + #[test] + fn a_loopback_endpoint_is_accepted() { + let config = HostTelemetryConfig::new("http://127.0.0.1:18080/v2/status", 15, 60).unwrap(); + assert_eq!(config.endpoint(), "http://127.0.0.1:18080/v2/status"); + let config = HostTelemetryConfig::new("http://[::1]:18080/v2/status", 15, 60).unwrap(); + assert_eq!(config.endpoint(), "http://[::1]:18080/v2/status"); + } + + #[test] + fn a_non_loopback_or_ambiguous_endpoint_is_refused() { + for endpoint in [ + // A name would have to be resolved, and a resolved answer could be + // rebound between validation and use. + "http://localhost:18080/v2/status", + "http://example.com:18080/v2/status", + // A non-loopback address is not this machine. + "http://10.0.0.1:18080/v2/status", + "http://192.168.1.10:18080/v2/status", + "http://[fe80::1]:18080/v2/status", + // An IPv4-mapped loopback address is not the loopback address. + "http://[::ffff:127.0.0.1]:18080/v2/status", + // The provider speaks plain HTTP on the loopback interface. + "https://127.0.0.1:18080/v2/status", + "ftp://127.0.0.1:18080/v2/status", + "file:///etc/passwd", + // Anything that changes the request's target or shape. + "http://user:pass@127.0.0.1:18080/v2/status", + "http://user@127.0.0.1:18080/v2/status", + "http://127.0.0.1:18080/v2/status?probe=1", + "http://127.0.0.1:18080/v2/status#fragment", + "http://127.0.0.1:18080/", + "http://127.0.0.1:18080/v2/other", + "http://127.0.0.1:18080/v2/status/extra", + "http://127.0.0.1/v2/status", + "http://127.0.0.1:0/v2/status", + "http://127.0.0.1:99999/v2/status", + ] { + assert!( + HostTelemetryConfig::new(endpoint, 15, 60).is_err(), + "endpoint {endpoint} must be refused" + ); + } + } + + #[test] + fn an_alternative_numeric_spelling_is_canonicalized_to_the_address() { + // These all name the loopback address, and the URL parser rewrites + // them to the literal address. The endpoint the client is given is + // therefore the literal address, and no name is ever resolved. + for endpoint in [ + "http://127.0.0.1.:18080/v2/status", + "http://2130706433:18080/v2/status", + "http://0x7f000001:18080/v2/status", + "http://127.1:18080/v2/status", + "http://127.000.000.001:18080/v2/status", + ] { + let config = HostTelemetryConfig::new(endpoint, 15, 60).unwrap(); + assert_eq!(config.endpoint(), "http://127.0.0.1:18080/v2/status"); + } + let config = + HostTelemetryConfig::new("http://[0:0:0:0:0:0:0:1]:18080/v2/status", 15, 60).unwrap(); + assert_eq!(config.endpoint(), "http://[::1]:18080/v2/status"); + } + + #[test] + fn an_out_of_range_cadence_is_refused() { + assert_eq!( + HostTelemetryConfig::new("http://127.0.0.1:18080/v2/status", 0, 60).unwrap_err(), + TelemetryConfigError::InvalidRefreshInterval + ); + assert_eq!( + HostTelemetryConfig::new("http://127.0.0.1:18080/v2/status", 3_601, 60).unwrap_err(), + TelemetryConfigError::InvalidRefreshInterval + ); + assert_eq!( + HostTelemetryConfig::new("http://127.0.0.1:18080/v2/status", 15, 0).unwrap_err(), + TelemetryConfigError::InvalidFreshness + ); + assert_eq!( + HostTelemetryConfig::new("http://127.0.0.1:18080/v2/status", 15, 3_601).unwrap_err(), + TelemetryConfigError::InvalidFreshness + ); + // A freshness bound shorter than the poll interval would make every + // sample stale before the next poll replaced it. + assert_eq!( + HostTelemetryConfig::new("http://127.0.0.1:18080/v2/status", 30, 15).unwrap_err(), + TelemetryConfigError::InvalidFreshness + ); + } + + #[test] + fn a_supported_measurement_is_carried_and_an_unsupported_one_is_not() { + let payload = payload(MetricCapabilitiesV2::new(true, true, true, false)); + let observation = normalize(&payload).unwrap(); + assert_eq!(observation.cpu.value().unwrap().logical_cores, 8); + assert_eq!(observation.cpu.value().unwrap().iowait_pct, Some(1.5)); + assert!(observation.load.value().is_some()); + assert!(observation.swap.value().is_some()); + // No drive, disk-I/O or network data was reported. + assert!(observation.disk.is_unsupported()); + assert!(observation.disk_io.is_unsupported()); + assert!(observation.network.is_unsupported()); + } + + #[test] + fn an_unsupported_capability_is_not_reported_as_a_missing_value() { + let payload = payload(MetricCapabilitiesV2::new(false, false, false, false)); + let observation = normalize(&payload).unwrap(); + assert_eq!(observation.cpu.value().unwrap().iowait_pct, None); + assert!(observation.load.is_unsupported()); + assert!(observation.swap.is_unsupported()); + // A missing measurement is never a zero. + assert!(observation.load.value().is_none()); + } + + #[test] + fn a_supported_but_unreported_measurement_is_unknown() { + let mut payload = payload(MetricCapabilitiesV2::new(true, true, true, false)); + payload.snapshot.load = None; + let observation = normalize(&payload).unwrap(); + assert!(observation.load.is_unknown()); + assert!(!observation.load.is_unsupported()); + } + + #[test] + fn drive_and_throughput_data_is_aggregated_without_identifiers() { + let mut payload = payload(MetricCapabilitiesV2::new(false, false, false, false)); + payload.drives = Some(vec![ + DriveMetrics { + name: "/".into(), + used_bytes: 100, + total_bytes: 1_000, + available_bytes: Some(900), + }, + DriveMetrics { + name: "/data".into(), + used_bytes: 50, + total_bytes: 500, + available_bytes: Some(450), + }, + ]); + payload.disk_io = Some(gregg_protocol::v2::DiskIoPayload { + aggregate_read_bytes_per_sec: 11, + aggregate_write_bytes_per_sec: 22, + devices: vec![gregg_protocol::v2::DiskIoMetrics { + id: "sda".into(), + name: "sda".into(), + read_bytes_per_sec: 11, + write_bytes_per_sec: 22, + drive_name: Some("/".into()), + }], + }); + payload.network = Some(gregg_protocol::v2::NetworkPayload { + aggregate_rx_bytes_per_sec: 33, + aggregate_tx_bytes_per_sec: 44, + aggregate_rx_capacity_bps: None, + aggregate_tx_capacity_bps: None, + interfaces: vec![], + }); + let observation = normalize(&payload).unwrap(); + let disk = observation.disk.value().unwrap(); + assert_eq!(disk.available_bytes, 1_350); + assert_eq!(disk.total_bytes, 1_500); + assert_eq!(disk.volume_count, 2); + assert_eq!(observation.disk_io.value().unwrap().read_bytes_per_sec, 11); + assert_eq!(observation.network.value().unwrap().rx_bytes_per_sec, 33); + // The normalized form carries no drive name, device identity, or + // interface identity: only aggregates. + let encoded = serde_json::to_string(&observation).unwrap(); + assert!(!encoded.contains("/data")); + assert!(!encoded.contains("sda")); + } + + #[test] + fn an_invalid_provider_payload_is_refused() { + let mut payload = payload(MetricCapabilitiesV2::new(false, false, false, false)); + payload.snapshot.cpu.usage_pct = 1000.0; + assert!(payload.validate().is_err()); + } + + #[test] + fn a_provider_timestamp_in_the_future_is_refused() { + let mut payload = payload(MetricCapabilitiesV2::new(false, false, false, false)); + payload.snapshot.observed_at_unix_ms = wall_clock_millis().unwrap_or_default() + 600_000; + let body = serde_json::to_vec(&payload).unwrap(); + assert_eq!(decode_status(&body).unwrap_err(), TelemetryError::ClockSkew); + } + + #[test] + fn a_malformed_body_is_refused() { + assert_eq!( + decode_status(b"not json").unwrap_err(), + TelemetryError::Malformed + ); + assert_eq!(decode_status(b"{}").unwrap_err(), TelemetryError::Malformed); + } + + #[test] + fn a_wrong_schema_version_is_refused() { + let mut payload = payload(MetricCapabilitiesV2::new(false, false, false, false)); + payload.snapshot.schema_version = 1; + let body = serde_json::to_vec(&payload).unwrap(); + assert_eq!( + decode_status(&body).unwrap_err(), + TelemetryError::SchemaVersion + ); + } + + #[test] + fn the_backoff_grows_and_is_capped() { + let interval = Duration::from_secs(15); + assert_eq!(backoff(interval, 1), Duration::from_secs(15)); + assert_eq!(backoff(interval, 2), Duration::from_secs(30)); + assert_eq!(backoff(interval, 3), Duration::from_secs(60)); + assert_eq!(backoff(interval, 10), MAX_BACKOFF); + } + + #[tokio::test] + async fn a_disabled_cache_reports_disabled() { + let cache = TelemetryCache::disabled(); + let snapshot = cache.snapshot().await; + assert_eq!(snapshot.state, TelemetryProviderState::Disabled); + assert!(snapshot.observation.is_none()); + assert!(snapshot.age_ms.is_none()); + assert!(snapshot.last_error.is_none()); + } +} diff --git a/crates/eggwork-server/tests/host_telemetry.rs b/crates/eggwork-server/tests/host_telemetry.rs new file mode 100644 index 0000000..098e451 --- /dev/null +++ b/crates/eggwork-server/tests/host_telemetry.rs @@ -0,0 +1,483 @@ +//! Behavioural tests for the optional host-telemetry adapter. +//! +//! The provider side is exercised against a real loopback HTTP server rather +//! than a mocked transport, because the properties that matter here — a +//! redirect that is not followed, a body that is refused for being too large, +//! a response that never arrives — are properties of the transport, not of a +//! stub. + +use std::{ + net::SocketAddr, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; + +use async_trait::async_trait; +use eggwork_core::{ + HostTelemetry, TelemetryCpu, TelemetryErrorCategory, TelemetryMemory, TelemetryMetric, + TelemetryProviderState, +}; +use eggwork_server::telemetry::{ + GreggTelemetryProvider, HostTelemetryConfig, HostTelemetryProvider, ProviderOutcome, + TelemetryError, TelemetryMonitor, TelemetrySnapshot, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, + time::Instant, +}; + +/// A canned HTTP response. +struct Canned { + status: u16, + body: Vec, + delay: Duration, +} + +impl Canned { + fn json(status: u16, body: impl Into>) -> Self { + Self { + status, + body: body.into(), + delay: Duration::ZERO, + } + } + + fn delayed(mut self, delay: Duration) -> Self { + self.delay = delay; + self + } +} + +/// A loopback HTTP server that answers with canned responses. +struct FakeProvider { + address: SocketAddr, + requests: Arc, +} + +impl FakeProvider { + async fn start(responder: impl Fn(usize) -> Canned + Send + Sync + 'static) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let address = listener.local_addr().expect("addr"); + let requests = Arc::new(AtomicUsize::new(0)); + let counter = requests.clone(); + let responder: Arc Canned + Send + Sync> = Arc::new(responder); + tokio::spawn(async move { + loop { + let Ok((stream, _)) = listener.accept().await else { + continue; + }; + let counter = counter.clone(); + let responder = responder.clone(); + tokio::spawn(async move { + let _ = serve_one(stream, counter, responder.as_ref()).await; + }); + } + }); + Self { address, requests } + } + + fn endpoint(&self) -> String { + format!("http://127.0.0.1:{}/v2/status", self.address.port()) + } + + fn requests(&self) -> usize { + self.requests.load(Ordering::SeqCst) + } +} + +async fn serve_one( + mut stream: TcpStream, + counter: Arc, + responder: &(dyn Fn(usize) -> Canned + Send + Sync), +) -> std::io::Result<()> { + let mut buffer = Vec::new(); + let mut chunk = [0u8; 1024]; + loop { + let read = stream.read(&mut chunk).await?; + if read == 0 { + return Ok(()); + } + buffer.extend_from_slice(&chunk[..read]); + if buffer.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + let index = counter.fetch_add(1, Ordering::SeqCst); + let canned = responder(index); + if !canned.delay.is_zero() { + tokio::time::sleep(canned.delay).await; + } + let head = format!( + "HTTP/1.1 {} {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + canned.status, + reason(canned.status), + canned.body.len() + ); + stream.write_all(head.as_bytes()).await?; + stream.write_all(&canned.body).await?; + stream.flush().await?; + let _ = stream.shutdown().await; + Ok(()) +} + +fn reason(status: u16) -> &'static str { + match status { + 200 => "OK", + 302 => "Found", + 500 => "Internal Server Error", + 503 => "Service Unavailable", + _ => "Status", + } +} + +/// A provider status payload in the shape the provider protocol defines. +fn provider_payload() -> String { + serde_json::json!({ + "schema_version": 2, + "observed_at_unix_ms": now_unix_ms(), + "sample_interval_ms": 1000, + "capabilities": { + "cpu_iowait": true, + "load_average": true, + "swap": false, + "memory_commit": false + }, + "system": { + "name": "host", + "hostname": "host.internal", + "os_name": "linux", + "os_version": "6.1", + "kernel_name": "Linux", + "kernel_release": "6.1.0", + "architecture": "x86_64" + }, + "cpu": { + "logical_cores": 8, + "usage_pct": 12.5, + "iowait_pct": 1.5 + }, + "load": { "one": 0.5, "five": 0.25, "fifteen": 0.125 }, + "memory": { "used_bytes": 4000, "total_bytes": 8000, "usage_pct": 50.0 }, + "drives": [ + { "name": "/", "used_bytes": 100, "total_bytes": 1000, "available_bytes": 900 } + ], + "disk_io": { + "aggregate_read_bytes_per_sec": 11, + "aggregate_write_bytes_per_sec": 22, + "devices": [] + }, + "network": { + "aggregate_rx_bytes_per_sec": 33, + "aggregate_tx_bytes_per_sec": 44, + "interfaces": [] + } + }) + .to_string() +} + +/// A provider health envelope for a daemon that is still warming up. +fn warming_payload() -> String { + serde_json::json!({ + "schema_version": 2, + "state": "warming", + "category": "warming", + "message": "collector warming up" + }) + .to_string() +} + +fn now_unix_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock") + .as_millis() as u64 +} + +fn config(endpoint: &str) -> HostTelemetryConfig { + HostTelemetryConfig::new(endpoint, 3_600, 3_600).expect("config") +} + +/// Wait until the cache reports a state, or fail the test. +async fn await_state( + monitor: &TelemetryMonitor, + expected: TelemetryProviderState, +) -> TelemetrySnapshot { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let snapshot = monitor.cache().snapshot().await; + if snapshot.state == expected { + return snapshot; + } + assert!( + Instant::now() < deadline, + "provider state stayed {snapshot:?} instead of reaching {expected:?}" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +#[tokio::test] +async fn a_valid_provider_payload_becomes_a_normalized_observation() { + let provider = FakeProvider::start(|_| Canned::json(200, provider_payload())).await; + let settings = config(&provider.endpoint()); + let monitor = + TelemetryMonitor::start(Arc::new(GreggTelemetryProvider::new(&settings)), &settings); + let snapshot = await_state(&monitor, TelemetryProviderState::Ready).await; + let observation = snapshot.observation.expect("observation"); + assert_eq!(observation.cpu.value().unwrap().logical_cores, 8); + assert_eq!(observation.cpu.value().unwrap().iowait_pct, Some(1.5)); + assert_eq!( + observation.memory.value().unwrap().available_bytes, + 4_000, + "available memory is the complement of used memory" + ); + assert_eq!(observation.load.value().unwrap().one, 0.5); + assert!( + observation.swap.is_unsupported(), + "a platform without swap reports an unsupported measurement, not a zero" + ); + let disk = observation.disk.value().unwrap(); + assert_eq!(disk.available_bytes, 900); + assert_eq!(disk.total_bytes, 1_000); + assert_eq!(disk.volume_count, 1); + assert_eq!(observation.disk_io.value().unwrap().read_bytes_per_sec, 11); + assert_eq!(observation.network.value().unwrap().tx_bytes_per_sec, 44); + // The provider's identity, drive name, and interface details never leave + // the node. + let encoded = serde_json::to_string(&observation).unwrap(); + assert!(!encoded.contains("host.internal")); + monitor.shutdown().await; +} + +#[tokio::test] +async fn a_warming_provider_is_reported_as_warming() { + let provider = FakeProvider::start(|_| Canned::json(503, warming_payload())).await; + let settings = config(&provider.endpoint()); + let monitor = + TelemetryMonitor::start(Arc::new(GreggTelemetryProvider::new(&settings)), &settings); + let snapshot = await_state(&monitor, TelemetryProviderState::Warming).await; + assert!(snapshot.observation.is_none()); + assert!(snapshot.last_error.is_none()); + monitor.shutdown().await; +} + +#[tokio::test] +async fn an_unexpected_status_is_reported_as_unavailable() { + let provider = FakeProvider::start(|_| Canned::json(500, "{}".to_string())).await; + let settings = config(&provider.endpoint()); + let monitor = + TelemetryMonitor::start(Arc::new(GreggTelemetryProvider::new(&settings)), &settings); + let snapshot = await_state(&monitor, TelemetryProviderState::Unavailable).await; + assert_eq!( + snapshot.last_error, + Some(TelemetryErrorCategory::HttpStatus) + ); + monitor.shutdown().await; +} + +#[tokio::test] +async fn a_malformed_body_is_reported_as_unavailable() { + let provider = FakeProvider::start(|_| Canned::json(200, "not json".to_string())).await; + let settings = config(&provider.endpoint()); + let monitor = + TelemetryMonitor::start(Arc::new(GreggTelemetryProvider::new(&settings)), &settings); + let snapshot = await_state(&monitor, TelemetryProviderState::Unavailable).await; + assert_eq!(snapshot.last_error, Some(TelemetryErrorCategory::Malformed)); + monitor.shutdown().await; +} + +#[tokio::test] +async fn an_oversized_body_is_refused() { + let oversized = vec![b'x'; 512 * 1024]; + let provider = FakeProvider::start(move |_| Canned::json(200, oversized.clone())).await; + let settings = config(&provider.endpoint()); + let monitor = + TelemetryMonitor::start(Arc::new(GreggTelemetryProvider::new(&settings)), &settings); + let snapshot = await_state(&monitor, TelemetryProviderState::Unavailable).await; + assert_eq!(snapshot.last_error, Some(TelemetryErrorCategory::TooLarge)); + monitor.shutdown().await; +} + +#[tokio::test] +async fn a_redirect_is_not_followed() { + let provider = FakeProvider::start(|_| { + Canned::json( + 302, + serde_json::json!({ "location": "http://10.0.0.1/v2/status" }).to_string(), + ) + }) + .await; + let settings = config(&provider.endpoint()); + let monitor = + TelemetryMonitor::start(Arc::new(GreggTelemetryProvider::new(&settings)), &settings); + let snapshot = await_state(&monitor, TelemetryProviderState::Unavailable).await; + assert_eq!( + snapshot.last_error, + Some(TelemetryErrorCategory::HttpStatus) + ); + assert_eq!( + provider.requests(), + 1, + "a redirect must not produce a second request" + ); + monitor.shutdown().await; +} + +#[tokio::test] +async fn a_provider_that_never_answers_times_out() { + let provider = FakeProvider::start(|_| { + Canned::json(200, provider_payload()).delayed(Duration::from_secs(30)) + }) + .await; + let settings = config(&provider.endpoint()); + let monitor = TelemetryMonitor::start( + Arc::new(GreggTelemetryProvider::with_deadlines( + &settings, + Duration::from_millis(200), + Duration::from_millis(300), + )), + &settings, + ); + let snapshot = await_state(&monitor, TelemetryProviderState::Unavailable).await; + assert_eq!(snapshot.last_error, Some(TelemetryErrorCategory::Timeout)); + monitor.shutdown().await; +} + +#[tokio::test] +async fn an_unreachable_provider_is_reported_as_unavailable() { + // Bind a port and drop it, so the endpoint is closed rather than + // filtered. A refused connection is a connection failure, not a timeout. + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let address = listener.local_addr().expect("addr"); + drop(listener); + let settings = config(&format!("http://127.0.0.1:{}/v2/status", address.port())); + let monitor = TelemetryMonitor::start( + Arc::new(GreggTelemetryProvider::with_deadlines( + &settings, + Duration::from_millis(200), + Duration::from_millis(500), + )), + &settings, + ); + let snapshot = await_state(&monitor, TelemetryProviderState::Unavailable).await; + assert_eq!( + snapshot.last_error, + Some(TelemetryErrorCategory::Connection) + ); + monitor.shutdown().await; +} + +/// A provider that counts how often it was asked for an observation. +struct CountingProvider { + calls: Arc, +} + +#[async_trait] +impl HostTelemetryProvider for CountingProvider { + async fn observe(&self) -> Result { + self.calls.fetch_add(1, Ordering::SeqCst); + Ok(ProviderOutcome::Observed(observation())) + } +} + +fn observation() -> HostTelemetry { + HostTelemetry { + observed_at_unix_ms: now_unix_ms(), + sample_interval_ms: 1_000, + cpu: TelemetryMetric::Value(TelemetryCpu { + logical_cores: 4, + usage_pct: 1.0, + iowait_pct: None, + }), + memory: TelemetryMetric::Value(TelemetryMemory { + available_bytes: 100, + total_bytes: 200, + used_bytes: 100, + }), + load: TelemetryMetric::Unsupported, + swap: TelemetryMetric::Unsupported, + disk: TelemetryMetric::Unsupported, + disk_io: TelemetryMetric::Unsupported, + network: TelemetryMetric::Unsupported, + } +} + +#[tokio::test] +async fn one_owner_polls_for_every_reader() { + let calls = Arc::new(AtomicUsize::new(0)); + let provider = Arc::new(CountingProvider { + calls: calls.clone(), + }); + let settings = config("http://127.0.0.1:1/v2/status"); + let monitor = TelemetryMonitor::start(provider, &settings); + await_state(&monitor, TelemetryProviderState::Ready).await; + let after_first = calls.load(Ordering::SeqCst); + assert_eq!(after_first, 1); + + // A burst of readers must not turn into a burst of provider requests. + let mut readers = Vec::new(); + for _ in 0..64 { + let cache = monitor.cache().clone(); + readers.push(tokio::spawn(async move { cache.snapshot().await })); + } + for reader in readers { + let snapshot = reader.await.expect("reader"); + assert_eq!(snapshot.state, TelemetryProviderState::Ready); + } + assert_eq!( + calls.load(Ordering::SeqCst), + after_first, + "readers must be served from the cache, not from the provider" + ); + monitor.shutdown().await; +} + +#[tokio::test] +async fn a_disabled_monitor_never_polls() { + let monitor = TelemetryMonitor::disabled(); + let snapshot = monitor.cache().snapshot().await; + assert_eq!(snapshot.state, TelemetryProviderState::Disabled); + assert!(snapshot.observation.is_none()); + monitor.shutdown().await; +} + +#[tokio::test] +async fn a_stopped_monitor_stops_polling() { + let calls = Arc::new(AtomicUsize::new(0)); + let provider = Arc::new(CountingProvider { + calls: calls.clone(), + }); + let settings = config("http://127.0.0.1:1/v2/status"); + let monitor = TelemetryMonitor::start(provider, &settings); + await_state(&monitor, TelemetryProviderState::Ready).await; + monitor.shutdown().await; + let after_shutdown = calls.load(Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!( + calls.load(Ordering::SeqCst), + after_shutdown, + "a stopped monitor must not keep polling" + ); +} + +#[tokio::test] +async fn a_stale_observation_is_reported_as_stale() { + let provider = FakeProvider::start(|_| { + // A sample that is already older than the freshness bound. + let mut payload: serde_json::Value = + serde_json::from_str(&provider_payload()).expect("payload"); + payload["observed_at_unix_ms"] = serde_json::json!(now_unix_ms() - 3_600_000); + Canned::json(200, payload.to_string()) + }) + .await; + let settings = HostTelemetryConfig::new(&provider.endpoint(), 1, 2).expect("config"); + let monitor = + TelemetryMonitor::start(Arc::new(GreggTelemetryProvider::new(&settings)), &settings); + let snapshot = await_state(&monitor, TelemetryProviderState::Stale).await; + assert!(snapshot.observation.is_some()); + monitor.shutdown().await; +} diff --git a/docs/operations.md b/docs/operations.md index 922a3b9..21f5f6d 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -37,12 +37,13 @@ but the exit code reports that the node did not reach the requested state. ## Readiness -`doctor` is the gate. It returns seven checks, and `ready` is true only when all +`doctor` is the gate. It returns eight checks, and `ready` is true only when all of them pass: | Check | Meaning | |---|---| | `configuration` | Config parses and the TLS material loads into a usable server config | +| `host-telemetry` | Whether the optional host-telemetry provider is configured (off by default) | | `sandbox-resource-backend` | The installed helper is trusted, and this host's actual isolation/resource capabilities were runtime-probed | | `listener` | The bind address is available | | `execution-root`, `blob-root`, `workspace-root` | Those directories exist and are trustworthy | @@ -61,6 +62,113 @@ A helper is trusted when it is root- or effective-user-owned, not group/world writable, and inside non-writable ancestor directories. Anything else fails closed: required isolation stays unsupported instead of quietly degrading. +## Host telemetry (optional, off by default) + +A node can read **host-wide** measurements — CPU, memory, load, swap, disk +capacity, disk and network throughput — from a telemetry provider running on +the same machine, and expose them to authorized callers. This is observation +for scheduling decisions, not enforcement: it never qualifies an execution, and +it is never per-execution utilization. + +**The default `eggworkd` runs without a provider.** With no `host_telemetry` +block in the config, the node creates no provider, starts no polling task, and +claims no host measurements. The `host-telemetry` doctor check reports +`disabled`. + +To enable it, add a block to the node config: + +```json +"host_telemetry": { + "endpoint": "http://127.0.0.1:18080/v2/status", + "refresh_interval_seconds": 15, + "freshness_seconds": 60 +} +``` + +The provider must be **bound to the loopback interface**. The endpoint is +validated when the config is validated, and it is refused unless it is: + +- plain `http` (not `https`), +- an **IP literal** that is a loopback address (`127.0.0.0/8` or `::1`) — a + hostname such as `localhost` is refused, so no name is ever resolved and no + answer can be rebound, +- naming an explicit TCP port, +- exactly the path `/v2/status`, with no userinfo, query string, or fragment. + +The client is built without redirect and proxy support, so a `3xx` is reported +as an unexpected status rather than followed, and no ambient `HTTP_PROXY` +setting is consulted. A redirect hop or an inherited proxy cannot move the +request off the loopback interface. + +The node polls on its own schedule. One background task owns the provider and +performs every request; readers consult the node's cache and never trigger a +request themselves, so a burst of callers cannot become a burst of provider +requests. A provider that is down is retried with a bounded backoff instead of +being polled in a tight loop. + +`freshness_seconds` must not be shorter than `refresh_interval_seconds`; a +sample older than the freshness bound is reported as **stale** rather than +silently presented as current. A provider whose timestamp lies implausibly in +the future is refused rather than treated as fresh. + +Provider failures are reported as a bounded category (connection, timeout, +HTTP status, malformed, schema version, invalid, too large, clock skew). No +response body, provider address, or host path is ever carried into a log line +or a metric. + +## Reading host telemetry + +When a provider is configured, an **authorized controller** can read the node's +host-wide observation over the existing mTLS channel: + +```text +GET /v1/node/telemetry +``` + +The read is served from the node's own cache. It never contacts the provider, +so a burst of readers cannot become a burst of provider requests, and a +provider that is down does not turn a read into a timeout. + +**The `telemetry` grant is separate.** The operation name in a client's grant +list is `telemetry`, and it is not implied by `status`: + +```json +"clients": [ + { + "principal_id": "controller-01", + "certificate_sha256": "0123…", + "operations": ["capabilities", "status", "telemetry"] + } +] +``` + +A principal that is not granted `telemetry` receives the ordinary typed 403, +and the refusal does not reveal whether the node holds an observation. A node +that predates this route answers 404, which is a different answer: it means the +node cannot serve telemetry at all. + +The response reports what the **provider** is doing, not what the host is +doing: + +| `state` | Meaning | +|---|---| +| `disabled` | No provider is configured. The node reports no host measurements. | +| `warming` | The provider is alive but has not produced a sample yet. | +| `ready` | A sample is present and within its freshness bound. | +| `stale` | A sample is present but older than the freshness bound. | +| `unavailable` | The provider could not be reached. | +| `invalid` | The provider answered with something unusable. | + +A sample is current only when the state is `ready`. `unavailable` is not zero +utilization, and the per-measurement groups keep that explicit: a measurement +the host platform cannot produce is `unsupported`, one that was supported but +not reported is `unknown`, and only a real measurement is a value. + +The response carries no provider address, mount path, device or interface +identity, hostname, or per-execution measurement. The node's `status` and +`capabilities` are unchanged by this feature: they answer "is this node +accepting work", and telemetry answers "what did this host look like". + ## Drain ```bash diff --git a/docs/quickstart.md b/docs/quickstart.md index 5c2cc0f..0bbb6d8 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -125,6 +125,13 @@ The field shape is also available as a committed example: [`examples/eggworkd.example.json`](../examples/eggworkd.example.json). Replace its paths and fingerprint with your own. +Host telemetry is optional and **off unless you ask for it**. The config above +has no `host_telemetry` block, so the node creates no provider, starts no +polling task, and reports no host measurements. See +[operations.md](operations.md#host-telemetry-optional-off-by-default) if you +want to point the node at a telemetry provider bound to the loopback +interface. + ## 5. Set permissions (required) Eggwork refuses to load a config or certificate that others could tamper with, diff --git a/examples/eggworkd.example.json b/examples/eggworkd.example.json index 802f759..244bd24 100644 --- a/examples/eggworkd.example.json +++ b/examples/eggworkd.example.json @@ -23,6 +23,7 @@ "operations": [ "capabilities", "status", + "telemetry", "execute", "observe", "cancel", diff --git a/plans/adrs/ADR-0006-optional-gregg-host-telemetry.md b/plans/adrs/ADR-0006-optional-gregg-host-telemetry.md new file mode 100644 index 0000000..0fe4f87 --- /dev/null +++ b/plans/adrs/ADR-0006-optional-gregg-host-telemetry.md @@ -0,0 +1,50 @@ +# ADR-0006: Optional Gregg Host Telemetry, Eggwork-Owned Authenticated Projection + +Status: accepted +Date: 2026-10-19 +Decision: Option B, explicitly approved for implementation planning. + +Related authority: +- `plans/adrs/ADR-0001-fixed-target-scheduler-free-execution.md` +- `plans/adrs/ADR-0002-eggstack-transport-and-mtls.md` +- `plans/adrs/ADR-0005-runner-service-separation-and-local-admission.md` +- `plans/000-long-term-specification.md` +- `plans/subsystems/optional-gregg-host-telemetry-roadmap.md` +- Downstream `dbowm91/codegg: plans/subsystems/eggwork-worker-telemetry-and-targeting-roadmap.md` + +## Context + +Gregg's `greggd` already provides cross-platform, cached, read-only native host measurements through `GET /v2/status` (CPU, memory, swap, load, disk and network where available). Eggwork has its own durable, authenticated fixed-target execution service, and CodeGG has the global job scheduler. The missing integration is observation, not a process supervisor or another scheduler. + +## Alternatives + +A. greggd supervises eggworkd / acts as an Eggwork plugin host: rejected. This makes Gregg manage a security-sensitive remote executor, duplicates Eggwork's existing service lifecycle, and expands an unauthenticated monitoring service into the execution trust boundary. + +B. Eggwork optionally consumes Gregg's existing read-only status API locally and exposes a bounded authenticated node-telemetry projection: **selected**. + +C. Extract Gregg's native collectors to a shared in-process library: deferred until measured idle/steady-state overhead justifies cross-repository collector refactoring. + +## Decision and constraints + +1. **Zero changes to Gregg.** No plugin system, callback, new route, new Rust crate, authentication feature, or new scheduler in Gregg. +2. **Eggwork remains standalone.** Default config starts no polling tasks and has no runtime dependency on Gregg. A missing, stale, malformed, overloaded or incompatible Gregg instance cannot prevent node startup, stop active executions, or weaken existing executor security. +3. **Loopback only.** The optional adapter reads a configured local `http://127.0.0.1:PORT` or `http://[::1]:PORT` endpoint (or another strictly validated loopback URI), never arbitrary URLs, redirects, proxies, non-loopback targets, userinfo or caller-supplied hostnames. Require operator configuration; no discovery of foreign greggd instances. Bound connect/read durations and response bytes; validate Gregg's v2 schema, timestamp, optional capabilities and freshness. Loopback data is **untrusted advisory input**, not remote authenticated authority. +4. **Separate observation from enforcement.** Gregg's host-wide utilization is neither per-process usage nor resource admission proof. Eggwork's existing semaphores, explicit cgroup/Landlock enforcement, drain controls and authenticated capability claims remain authoritative. Do not convert telemetry loss into `0%` usage or an invented 'idle' state. +5. **One authenticated Eggwork read surface.** Only `eggwork-server` may expose a node-level, secret-free, bounded telemetry view through the existing mTLS control plane and resource-aware authorization taxonomy. The remote controller must not connect directly to Gregg. Do not expose unredacted Gregg hostname, device identifiers, mounts, local command history, arbitrary output or process information by default. +6. **No scheduling in Eggwork.** The endpoint reports facts plus freshness/provenance; it does not score nodes, hold global reservations, delay remote jobs, choose retry targets or provide a fleet listing. CodeGG remains placement/retry authority. +7. **Compatibility is additive.** Nodes without telemetry may return a typed `unavailable/disabled` outcome or a well-defined unsupported route; older clients and nodes remain compatible. No change to existing `NodeStatus` and `NodeCapabilities` meaning merely to carry host measurements. New endpoint and optional client method should be versioned and bounded; capability advertisement cannot claim a live provider when disabled/unavailable. +8. **No secret or lease leakage.** No client certificate, lease token, private key path, Gregg URL credentials, file paths, per-job stdout or command payload enters telemetry response, debug, errors or metrics. + +## Consequences + +Positive: Gregg's mature native collectors are reused without editing Gregg; lean nodes need only a small optional poll/cache adapter; CodeGG can consume metrics through the existing authenticated Eggwork endpoint; Eggwork remains usable without CodeGG or Gregg. + +Costs: two processes for Gregg-equipped workers and a loopback HTTP request at bounded cadence; telemetry is advisory and potentially spoofable by a local principal; cross-platform field availability differs. Mitigations: default off, loopback-only, small bounded cache, explicit uncertainty, no security-sensitive inference. + +## Verification + +Prove default-off startup and execution with no Gregg installed; positive v2 Gregg fixture; stale/warming/malformed/oversize/unsupported/clock-skew probes; loopback/redirect/SSRF rejections; mTLS authorized/unauthorized reads; ordinary execution under Gregg failure; isolation and resource requirements unchanged; no scheduling/pluggable executor introduced in Gregg; no increased network listener required on Gregg. + +## Supersession + +None. This ADR augments, and does not replace, ADR-0001 or the process-ownership and mTLS ADRs. diff --git a/plans/closure/operations-distribution/004a-status.md b/plans/closure/operations-distribution/004a-status.md index cda1dca..5fdfa23 100644 --- a/plans/closure/operations-distribution/004a-status.md +++ b/plans/closure/operations-distribution/004a-status.md @@ -240,4 +240,77 @@ The §5 facts were produced by a throwaway reproducer (16 threads, each staging private copy and spawning it) rather than by a committed test, because a test that needs a loaded host to fail is not a test. Its two decisive measurements — `same_path_staged_by` and the immediate `write(true).open` probe — are the ones -worth rerunning if this is ever revisited. \ No newline at end of file +worth rerunning if this is ever revisited. +## 13. Addendum, 2026-10-19 — the residual was subsequently eliminated + +This section is an addition. Nothing above it is changed: the findings, the +evidence, and the verdicts in §1–§12 stand as they were written on 2026-10-05, +and they are what the corrective was reasoned from. + +The residual `ETXTBSY` window characterised in §5 and dispositioned in §11 was +later eliminated, after it failed CI run `39306109740` on the optional-Gregg +host-telemetry branch. The elimination and its evidence are recorded in +`plans/closure/operations-distribution/004b-status.md` +(`plans/implementation/operations-distribution/004b-staged-helper-publication-durability-corrective.md`). + +Two statements above should be read with that record in hand: + +- **§11's "next step" is superseded.** It proposed `O_TMPFILE`+`linkat` + publication for the case where the residual "needs to be eliminated rather + than characterised". M004b eliminated it by a different route: the staged + helper is linked rather than copied, so the file the fixture executes is + never written, and the copy path that remains is committed before it is + published. No `unsafe` and no new dependency were needed. +- **§10's rejection of hard links is superseded.** Its stated reason — that + `chmod` on one fixture's copy would change the mode every other fixture + sees — no longer applies, because a mode change now publishes a replacement + instead of mutating the inode. M004b §5 states the reasoning in full. The + isolation invariant this milestone established still holds, and in a + stronger form: no fixture mutates an inode it shares with another fixture + or with the Cargo-built helper. + +§5's measurements were sound and remain the measurements. What they did not +settle — and what M004b measured — is that the condition is a property of the +inode rather than a microsecond-wide timing window: a hundred immediate +retries of the same path all failed. + +## 14. Addendum, 2026-10-19 — the elimination is by link-only staging + +This section is an addition. Nothing above it is changed, and §13 stands as it +was written. + +§13 described the elimination as it stood when M004b was first closed: the +staged helper was linked rather than copied, and a copy path "that remains" +was committed before publication. CI then refused that remaining copy path 3 +times in 32 stagings on the runner (`39316541191`), and the copy path was +removed. The elimination is therefore by link-only staging, and the two +statements in §13 that referred to a remaining copy path are superseded by +this one. + +What changed, in the terms of this record: + +- **The copy path is gone.** The fixture no longer copies the helper at all, + not even as a fallback. A copy is a file that was written, and Linux refuses + to execute an inode that is open for writing. Staging now fails loudly when + a link is impossible, rather than falling back to the construction that CI + rejected. +- **The mechanism is now read from the kernel.** §5's characterisation called + the condition "a host-level, load-dependent, microsecond-wide kernel window + around executing a just-written executable", and this record's own §5 + measurement of "no writer at failure time" is what made the window reading + natural. The kernel's accounting is `struct inode::i_writecount`: an + `execve()` of an inode that is open for writing is refused with `ETXTBSY`, + and the access is released with the file's teardown, which is deferred. The + §5 measurements stand; what they measured was a rate, not a window. +- **One cost was added, and it is recorded.** A link carries the source's + mode, so the build output's mode is normalised to a trusted one once, before + the first fixture exists. That is a mode change on a shared build artifact, + and it is deliberately one-directional: it can only remove write permission + for others, and the build output's bytes are never touched. §5's invariant — + that a fixture must never mutate, truncate, overwrite, or rename over an + executable path another concurrently runnable test may execute — still + holds, and the M004a proof that asserted it now states the exception + explicitly. + +The full reasoning, the kernel citations and the CI evidence are in +`plans/closure/operations-distribution/004b-status.md`. diff --git a/plans/closure/operations-distribution/004b-status.md b/plans/closure/operations-distribution/004b-status.md new file mode 100644 index 0000000..5fb0ad4 --- /dev/null +++ b/plans/closure/operations-distribution/004b-status.md @@ -0,0 +1,530 @@ +# M004b closure record: staged helper write-access corrective + +Status: **closed** — the `ETXTBSY` refusal is eliminated by construction, not characterised +Closed: 2026-10-19 +Plan: `plans/implementation/operations-distribution/004b-staged-helper-publication-durability-corrective.md` +Roadmap: `plans/subsystems/operations-distribution-roadmap.md` +Branch: `planning/optional-gregg-telemetry-m001-m002` +Corrects: `plans/closure/operations-distribution/004a-status.md` §5, §9 criterion 3, §10, and §11 + +This record is a corrective addendum. It does not replace the M004a record: that +record is preserved as written, and this one states what in it is no longer +sufficient and what closed the gap. + +> **Naming.** The milestone was registered as "staged helper publication +> durability corrective", on the hypothesis that the refusal was a write-back +> problem a durability barrier could close. CI disproved that hypothesis (§3), +> and the executed design is not a barrier at all: the file the fixture executes +> is never written. The milestone ID and the file names are kept so the pointer +> from the M004a record's addendum keeps resolving. + +## 1. The failures that triggered this corrective + +### 1.1 The original failure + +Recorded by the CI run on the optional-Gregg host-telemetry branch, and the +first CI failure of this shape to land on a red build: + +| Item | Value | +| --- | --- | +| CI run | `39306109740` | +| Head | `56880ee` (`docs(plans): close optional Gregg host telemetry M002`) | +| Branch | `planning/optional-gregg-telemetry-m001-m002` | +| Job | `rust` — `cargo test --locked --workspace --all-targets` | +| Failing test | `malformed_private_spec_and_unavailable_status_channel_do_not_launch_target` | +| Panic site | `crates/eggwork-sandbox-helper/tests/landlock_runner.rs:471` | +| Symptom | `called Result::unwrap() on an Err value: Os { code: 26, kind: ExecutableFileBusy, message: "Text file busy" }` | +| Suite result | `test result: FAILED. 14 passed; 1 failed` — job exit code 101 | + +The failing test is not the product's code path. It is a test that stages a +trusted helper into a private directory and then spawns it with plain +`std::process::Command`, outside the runner entirely. + +### 1.2 The failure that fixed the design + +The first attempt at this corrective staged the helper by copying it and closed +the copy with a durability barrier — write, `sync_all`, rename, sync the parent +directory. The barrier measured 0.02% on the development host and was carried to +CI, where it did not hold: + +| Item | Value | +| --- | --- | +| CI runs | `39316444280` (push), `39316541191` (pull request) | +| Head | `0accbdc` (`docs(plans): close Operations M004b …`) | +| Job | `rust` | +| Failing test | `a_staged_helper_is_executable_immediately_after_publication` — the new *copy-path* regression test | +| Symptom | `a staged helper was refused: Text file busy (os error 26)`, three times in 32 stagings | +| Assertion | `left: 3, right: 0` — "a freshly published helper must be executable without an ETXTBSY refusal" | +| Suite result | `test result: FAILED. 16 passed; 1 failed` — job exit code 101 | + +The same run's *link-path* test — 32 parallel stagings of the same helper, +staged by hard link — passed 32 of 32. + +That contrast is the finding. A barrier that is 0.02% on one host and 9% on +another is not a barrier; it is a rate. The copy path was removed, and the +staged helper is now published without ever being written. + +## 2. The historical claims that are no longer sufficient + +The M004a closure record §5 concluded that the residual failure was "a +host-level, load-dependent, microsecond-wide window around executing a +just-written executable, on this machine's ext4, outside Eggwork's code", and +§9 criterion 3 was recorded as only *partially met* on that basis. §10 left +the residual open by rejecting the obvious fixes, and §11 pointed at +`O_TMPFILE`+`linkat` publication as the next step "if it ever needs to be +eliminated rather than characterised", which the repository's rules forbid. + +That characterisation was accurate about what was observed and wrong about what +it implied. Five specific claims do not survive the evidence below: + +1. **"Microsecond-wide window" implies a timing race.** It is not. The + condition is a property of the inode and it persists: 100 immediate retries + of the same path all failed (§5.1). +2. **"A file that has no writer" was inferred from a probe that could not have + detected a writer.** The M004a §5 probe was + `OpenOptions::write(true).open(path)` run *after* the failed spawn. Opening + a file for writing succeeds whether or not another writer exists, so that + probe could not distinguish the two cases. The kernel's own accounting says + why: `get_write_access()` refuses only when the count is *negative*, so a + file that is open for writing can still be opened for writing again. +3. **"Atomic publication therefore cannot hit `ETXTBSY`"** — the fixture + module's own property 2 — was false, and that false claim is what left CI + red. The M004a record itself had already recorded that atomic publication + was not enough (§5: "All three reproduce it; rates vary with load, not with + mechanism"), but the module header kept asserting the opposite. +4. **§10's rejection of hard links was reasoned from a fixture design that + mutated a shared inode.** It is superseded here, for the reason given in §6. +5. **The first attempt's own hypothesis — that the refusal is a write-back + window that a durability barrier closes — is wrong.** The barrier was + carried to CI and refused 3 times in 32 stagings there (§1.2). The + mechanism is the inode's write *access*, not its write-back state. + +## 3. What changed + +### 3.1 The staged helper is a link, and there is no copy fallback + +`crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs` — the single +staging path shared by the Landlock suite and the runner's capability probe — +now **links** the Cargo-built helper into the fixture's private `0700` +directory: + +```text +stage(source): + source mode normalised to a trusted mode, once, before the first link + fixture directory, 0700 + hard link source -> /eggwork-sandbox-helper # writes nothing + on failure (different filesystem, or a source that cannot be linked): + fail loudly +``` + +A link shares the source's inode and never opens it for writing, so the +inode's write access is never taken and the kernel has no reason to refuse to +execute it. That is the difference between a refusal that cannot happen and one +that is merely unlikely. It also removes a per-fixture copy of the whole binary +from every test. + +**There is no copy fallback.** A copy is by definition a file that was written, +and a written file is exactly the construction the CI evidence refuses. The +first attempt's fallback — copy, commit, publish — is what CI rejected, and +keeping it "for the cases where linking does not work" would have kept the +flake alive on exactly the hosts that cannot afford it. When a link is +impossible, staging fails loudly and names the reason. + +The system temporary directory is tried first, because its ancestor chain is the +one `verify_trusted_helper` accepts by construction (`/tmp` is a sticky root +directory, which the trust check allows explicitly). A directory next to the +source is the fallback, because it is the same filesystem by definition. + +### 3.2 A link carries the source's mode, so the source is normalised once + +`verify_trusted_helper` rejects a helper that anyone but its owner may write, +and a link shares the source's mode. Cargo derives the executable's mode from +the process umask — `0666 & ~umask` plus the execute bits — so a permissive +umask (0002 is common in shared development environments; the development host +for this record uses it) leaves the build output group-writable, and no fixture +could stage it by linking. + +The fixture therefore clears the group and world write bits of the build output +once, before the first link is made, under a lock so that no fixture can stage +a helper whose mode has not been settled yet. The change is deliberately +one-directional: + +- it removes write permission for everyone else; +- it keeps the owner's permissions, the execute bits, and every other bit; +- it never touches the build output's bytes; +- it can only ever turn an untrusted helper into a trusted one, never the + reverse. + +The M004a invariant — "a fixture must never mutate, truncate, overwrite, or +rename over an executable path another concurrently runnable test may execute" — +is not weakened by it: the build output's *content* is untouched, and the mode +change happens once, before any fixture exists. The M004a proof +`staging_never_mutates_the_cargo_built_helper` now states the exception +explicitly and asserts that no *further* staging changes the mode. + +### 3.3 Mutations publish a replacement instead of changing the inode + +`set_mode` and `replace_with_junk` used to `chmod` or overwrite the staged +helper in place. With a shared inode that would reach the Cargo-built helper +and every other fixture, so both now publish a **replacement**: the bytes are +written under a staging name and renamed into place. No fixture mutates a +shared inode any more, which is a strictly stronger form of the M004a isolation +invariant than the one it recorded. + +### 3.4 The server's own staging + +`crates/eggwork-server/src/lib.rs` `place_trusted_helper()` stages and then +executes a helper the same way. It now links, normalises the build output's +mode the same way, and uses the same two candidate directories. + +### 3.5 What was deliberately not done + +- **No retry on `ETXTBSY`, and no sleep.** Both are forbidden by the M004a + plan, and §5.1 shows a retry does not work: the condition is per-inode and + survived 100 immediate retries. A retry would have converted a deterministic + refusal into an intermittent one while still leaving the suite red. +- **No durability barrier.** The first attempt carried one, and CI refused it + 3 times in 32 stagings (§1.2). The barrier addressed write-back, which is not + the property. +- **No `O_TMPFILE`+`linkat`.** §11's suggested next step. It needs `unsafe` or + a new dependency, and it addresses publication atomicity, not write access. +- **No trust-rule change.** `verify_trusted_helper` remains owner/mode/ancestor + trust only. It accepts a hard link exactly as it accepts a copy: the trust + rules are about a path's metadata, not about the inode behind it being + private. +- **No change to production code.** The product never stages a helper. It + consumes one that was installed long before, so its inode carries no write + access. The exposure was confined to test fixtures. + +## 4. The mechanism, read from the kernel rather than inferred + +The first attempt described the refusal as "a file whose inode still carries a +write reference", and stated in its own residual-risk section that the +mechanism was "described from observation, not from kernel source". It is now +read from the source. The relevant accounting is `struct inode::i_writecount`, +whose documented meaning is in `include/linux/fs.h`: + +> The i_writecount field of an inode can have the following values: +> 0: no write access, no denied write access +> < 0: (-i_writecount) users that denied write access to the file. +> > 0: (i_writecount) users that have write access to the file. + +Four call sites close the loop. + +1. **The write access is taken by every write-open of a regular file.** + `fs/open.c`, `do_dentry_open()`: + + ```c + } else if (f->f_mode & FMODE_WRITE && !special_file(inode->i_mode)) { + error = file_get_write_access(f); + if (unlikely(error)) + goto cleanup_file; + f->f_mode |= FMODE_WRITER; + } + ``` + + `file_get_write_access()` calls `get_write_access()`, which is + `atomic_inc_unless_negative(&inode->i_writecount)`. + +2. **The refusal is raised on the execution side.** `fs/exec.c`, + `do_open_execat()` — the function every `execve()` goes through — ends with: + + ```c + err = exe_file_deny_write_access(file); + if (err) + return ERR_PTR(err); + ``` + + and `exe_file_deny_write_access()` is `deny_write_access()`: + + ```c + static inline int deny_write_access(struct file *file) + { + struct inode *inode = file_inode(file); + return atomic_dec_unless_positive(&inode->i_writecount) ? 0 : -ETXTBSY; + } + ``` + + **The decrement is refused exactly when the count is positive — that is, + when the inode is open for writing — and the refusal is `-ETXTBSY`.** + +3. **The write access is released with the file.** The release is paired with + the teardown of the file that holds it (`FMODE_WRITER` → + `put_write_access(file_inode(file))`), and the teardown is *deferred*: + `fs/file_table.c`, `fput()` → `__fput_deferred()`, which queues the work as + a task work, and falls back to a workqueue when the task work cannot be + used. The release is therefore not synchronous with the `close()` that + dropped the last reference, and under concurrency it can lag the next + `execve()`. + +4. **The release is not a write-back event.** Nothing in that path consults + the page cache or the dirty state, which is why `fsync`, `O_DSYNC` and + sleeping do not help (§5.2) and why the first attempt's barrier did not + hold on CI. + +Two consequences decide the design: + +- **Only a file that is never opened for writing can be executed without + this refusal.** A copy is opened for writing by definition. A link is not. +- **The refusal is per-inode and survives immediate retries**, because the + write access is still held: a refused `execve()` does not release it. + +## 5. The measurements + +### 5.1 The condition is per-inode and persistent, not a timing window + +| Question | Method | Answer | +| --- | --- | --- | +| Does it need Eggwork's code? | standalone `std` reproducer, 16 threads | **No** — 15 failures in 190 attempts | +| Does anything hold the failing inode open? | match the inode number against every `/proc//fd`, reading each holder's `fdinfo` flags | **No** — no holder at any pid, which is consistent with §4.3: the access outlives the descriptor | +| Can the inode be reopened for writing? | `OpenOptions::write(true).open(path)` at failure time | **Yes** — so the M004a probe was uninformative | +| Is it transient? | 100 immediate re-spawns of the same path | **No** — every retry failed | +| Is it `copy_file_range`-specific? | `fs::copy` vs explicit read+write | **No** — 31.00% vs 37.08% | +| Is it the rename? | publish by rename vs exec the staging name | Rename helps, but 44.06% without it | +| Is it the *write* of the file? | hard link to the source, never written | **No** — 0.00% | +| Is it Eggwork's spawn path? | the failing test spawns with plain `std::process::Command` | **No** | + +### 5.2 The kernel's own accounting, confirmed by a direct probe + +A standalone `std` probe on the development host, using the real +Cargo-built helper as the payload so that the only variable is the staging +sequence: + +| Staging sequence | `execve` of the result | +| --- | --- | +| write, close | refused under concurrency (§5.3) | +| write, close, `fsync(file)` | refused under concurrency — the barrier does not help | +| write, close, `O_DSYNC` writes | refused under concurrency — write-through does not help | +| write, close, sleep 2 s | refused under concurrency — waiting does not help | +| write, close, **hold a write descriptor open** | **`ETXTBSY`, every time, single-threaded** | +| write, close, hold a write descriptor open, then drop it | accepted — the access is released with the teardown | +| open for writing, close, exec | accepted | +| hard link to the source, exec | accepted | +| exec the Cargo-built helper directly | accepted | + +The only construction that reproduces the refusal on demand is the one the +kernel documents: an inode that is open for writing. + +### 5.3 Variant measurement + +Each variant stages a private copy and spawns it, 16 threads in parallel. The +staged copy always lands in `/tmp`; only the source differs between runs. + +With the 8 MB Cargo-built helper as the source, 1 920 attempts per variant: + +| Variant | `ETXTBSY` | Rate | +| --- | --- | --- | +| copy, rename (the M004a sequence) | 687 | **35.78%** | +| write, commit the file, rename | 15 | 0.78% | +| copy, rename, commit the directory | 0 | 0.00% | +| copy, no rename | 846 | 44.06% | +| hard link to the source, never written | 0 | **0.00%** | +| execute the source directly | 0 | **0.00%** | +| copy, rename, retry up to 100 times | 4 | 0.21% (all 4 hit the retry cap) | + +With the 8 MB helper again, 4 800 attempts per variant, which is what +separated the two barriers: + +| Variant | `ETXTBSY` | Rate | +| --- | --- | --- | +| copy, rename | 1 488 | **31.00%** | +| read + write, no commit | 1 780 | **37.08%** | +| copy, rename, commit the directory | 1 | 0.02% | + +With a 27 KB source, 32 000 attempts per variant, which is what separated the +orderings: + +| Variant | `ETXTBSY` | Rate | +| --- | --- | --- | +| copy, rename | 7 219 | **22.56%** | +| copy, rename, commit the directory | 0 | 0.00% | +| copy, commit the file, rename | 1 | 0.003% | +| copy, rename, commit the file, commit the directory | 0 | 0.00% | +| copy, commit the data, rename, commit the directory | 0 | 0.00% | +| copy, rename, commit the directory, commit the file | 1 | 0.003% | +| copy, commit the file, rename, commit the directory | 0 | 0.00% | + +Read against §4, these numbers say something different from what the first +attempt read into them. The commit-based variants are not "the cure"; they are +variants that happen to leave more wall-clock time between the `close()` and +the `execve()`, and on a slow disk that is enough for the deferred teardown to +run. The development host's disk is slow (an 8 MB copy costs ~170 ms, and the +`fsync` variants ~600 ms), which is why its "committed" variants measured 0.00% +and why the CI runner — whose disk is fast, so the window between the `close()` +and the `execve()` is short — still refused 3 stagings in 32 *with* the barrier +in place (§1.2). + +The variant that is zero on every host, every load, and every filesystem is +the one that never opens the executed inode for writing. + +### 5.4 A note on the M004a §11 pointer + +§11's suggested next step, `O_TMPFILE`+`linkat`, addresses publication +atomicity. The failure was never that a partially written helper could be +observed — the M004a staging already renamed atomically. It was that a fully +written helper was still open for writing. `O_TMPFILE` does not change that, +because the inode it publishes is still open for writing when it is linked. + +## 6. Why hard links, against M004a §10 + +M004a §10 rejected hard links with a specific reason: + +> A hard link to the build output would eliminate the §5 window entirely (one +> inode, never written after cargo finished) — and it would also destroy the +> invariant this milestone exists to establish: `chmod` on one fixture's copy +> changes the mode every other fixture sees, because they would all be the +> same inode. The isolation invariant wins over the flake rate. + +The rejection is sound on its facts and no longer decides the case: + +1. **Its premise is confirmed.** The §5 measurement is right: a hard link + eliminates the refusal entirely, 0 refusals in 1 920 attempts, and 0 of 32 + on CI while the copy path was refused 3 times in the same run. +2. **Its stated reason is answered by this corrective.** The reason was that + `chmod` on a shared inode reaches every fixture. §3.3 removes the `chmod`: a + mode change now publishes a replacement, so no fixture mutates a shared + inode. The isolation invariant is preserved — and strengthened, because the + Cargo-built helper is now provably never mutated by any fixture. +3. **Its trade-off has been overtaken by events.** M004a weighed the isolation + invariant against the flake rate. The flake rate is now what makes CI red: + `39306109740` failed on it, and `39316541191` failed on the copy path that + M004b first proposed. M004a's own §11 asked what to do "if it ever needs to + be eliminated rather than characterised", and this is that moment. + +The one cost M004a did not have to weigh is §3.2's mode normalisation, because +M004a never linked. It is recorded as a residual risk in §9 rather than hidden. + +The M004a record is preserved as written, with additive forward pointers +appended. Nothing in its findings, evidence, or verdicts is changed. + +## 7. Required tests + +`crates/eggwork-sandbox-helper/tests/landlock_runner.rs`: + +| Test | What makes it non-vacuous | +| --- | --- | +| `a_linked_helper_is_executable_immediately_after_publication` | 32 threads each stage the real helper and spawn it; no spawn may be refused. **and** the staged helper is asserted to be the build output's own inode and device, so a regression to copying fails the test outright, with no load, no timing and no lucky window needed. | +| `a_group_writable_source_is_normalized_to_a_trusted_mode` | The normalisation clears the group and world write bits, keeps the owner's permissions and the execute bits, and is idempotent. | + +Both halves of the first test were verified by removing the fix, not asserted. +With `stage` forced back through a copy on the development host: + +| Check | Result | +| --- | --- | +| the refusal count | **5 of 32** stagings refused with `Text file busy` — the test fails on the count | +| the refusal count, second run | **9 of 32** refused | +| the inode assertion, with the count assertion disabled | fails deterministically: `left: 3038061, right: 17962722` — the staged helper is not the build output's inode | + +The second row is the one that matters most: the structural half of the test +does not need the race to reproduce at all, so a regression to copying is +caught on the first run rather than on the run where the host happens to be +busy. + +The copy-path regression test that the first attempt added +(`a_staged_helper_is_executable_immediately_after_publication`) was **removed** +with the copy path it covered. It was not a weak test — it did its job, and it +is what proved on CI that a committed copy is still refusable. Asserting that +a *written* file is executable is asserting something the kernel does not +guarantee, and no amount of tuning makes it true. + +The pre-existing suite keeps its semantics: 16 Landlock tests, including the +five M004a isolation proofs, all still pass unchanged. No assertion was +weakened, and no suite-level serialisation was added. + +## 8. Verification + +| Command | Result | +| --- | --- | +| `cargo test --locked -p eggwork-sandbox-helper --test landlock_runner` | pass — 17 passed, 0 failed | +| the same suite, repeated runs at `--test-threads=16` | pass — 0 `ETXTBSY`; see §8.1 | +| `cargo fmt --all -- --check` | pass | +| `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` | pass, zero warnings | +| `cargo test --locked --workspace --all-targets` | pass — 251 tests across 8 suites, 1 pre-existing ignored | +| `cargo check --locked --workspace` | pass | +| `python3 scripts/check_execution_ownership.py` | pass | +| `python3 scripts/check_execution_ownership.py --prove-negative-exit` | pass | +| `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release` | 52 tests, pass | +| `git diff --check` | clean | + +### 8.1 The repeated-run evidence + +The link path publishes a directory entry and writes nothing, so the suite no +longer has a staging race to lose. The repeated runs are recorded because the +first attempt's failure was a *rate* rather than a certainty: the rate has to +be measured on the host that failed, not on the host that is comfortable. + +| Host | Construction | Attempts | Refusals | +| --- | --- | --- | --- | +| development host, 16 threads | copy, rename | 1 920 | 687 (35.78%) | +| development host, 16 threads | copy, rename, commit the directory | 1 920 | 0 | +| development host, 16 threads | copy, no barrier (the forced regression) | 32 | **5** | +| development host, 16 threads | hard link | 40 suite runs, 32 stagings each | **0** | +| CI runner | copy, rename, commit the file, commit the directory | 32 | **3 (9.38%)** | +| CI runner | hard link | 32 | **0** | + +The CI row for the copy is the finding that closed the copy path; the CI row +for the link is the one that kept it. + +## 9. Residual risk + +- **The staged helper's mode comes from the build output.** A link cannot have + a different mode from the file it links to, so the fixture normalises the + build output's mode once (§3.2). That is the one place where a fixture + touches the shared build artifact, and it is a mode change that can only + make the artifact more trusted. Its bytes are never touched. +- **The fallback directory is not trusted by construction.** When the source + and the system temporary directory are on different filesystems, the fixture + stages into a directory next to the source, whose ancestor chain is the + build tree's. On a checkout under a group- or world-writable directory, the + trust check would reject that helper — loudly, as + "sandbox helper ancestor trust check failed", not silently. The system + temporary directory is preferred precisely because its chain is trusted. +- **A published replacement is a file that was written.** `set_mode` and + `replace_with_junk` publish written files, so executing one may be refused + with `ETXTBSY` instead of failing as a malformed executable. Both are loud + failures, and the junk fixture is never expected to run successfully — the + M004a proof asserts exactly that it fails loudly rather than reporting + isolation as applied. +- **The measured zero is a zero on the measured hosts and workloads.** 0 + refusals in 1 920 attempts at 16 threads on the development host, and 0 of 32 + on the CI runner, against a 22.6% rate for the construction it replaced. + The structural argument in §4 is what carries the guarantee; the + measurements are what confirm it. +- **Medium-or-higher findings: none.** + +## 10. Registry and roadmap disposition + +- `plans/subsystems/operations-distribution-roadmap.md` carries milestone + **M004b — staged helper write-access corrective**, status **closed**, pointing + at this record. +- `plans/registry.md` carries a closure row for M004b and an updated + Operations/distribution workstream row, so that the current authority is the + corrected state rather than M004a's characterisation. +- `plans/closure/operations-distribution/004a-status.md` is **preserved as + written**. Two additive forward pointers are appended to it: one recording + that the residual it characterised was subsequently eliminated and that its + §10 hard-link rejection is superseded (§6), and one recording that the + elimination is by link-only staging rather than by the copy-and-commit + barrier the first attempt proposed. Nothing in the M004a record's findings, + evidence, or verdicts is changed. + +## 11. Reproducing this record + +```text +cargo test --locked -p eggwork-sandbox-helper --test landlock_runner +cargo test --locked -p eggwork-sandbox-helper --test landlock_runner -- --test-threads=16 +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --locked --workspace +python3 scripts/check_execution_ownership.py +python3 scripts/check_execution_ownership.py --prove-negative-exit +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +The §5 measurements were produced by throwaway reproducers (a standalone +`std` program, a multi-variant harness and a kernel-source read), not by +committed tests: a measurement that needs a loaded host to fail is a +measurement, not a test. The two committed tests are the ones in §7, and both +fail loudly when the corresponding fix is removed. diff --git a/plans/closure/optional-gregg-host-telemetry/001-status.md b/plans/closure/optional-gregg-host-telemetry/001-status.md new file mode 100644 index 0000000..daecb0a --- /dev/null +++ b/plans/closure/optional-gregg-host-telemetry/001-status.md @@ -0,0 +1,253 @@ +# Optional Gregg host telemetry — M001 closure + +Status: **closed** +Closed: 2026-10-19 +Source plan: `plans/implementation/optional-gregg-host-telemetry/001-loopback-gregg-adapter.md` +Subsystem roadmap: `plans/subsystems/optional-gregg-host-telemetry-roadmap.md` +Decision: `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` +Branch: `planning/optional-gregg-telemetry-m001-m002` +Implementation commit: `ac55985` — *feat(server): default-off loopback Gregg host-telemetry adapter (M001)* +Reviewed head at closure: `ac55985` +Reviewed upstream baseline: `dfa4efd` (planning handoffs), branched from `main` at `17ff53f` + +## Executive finding + +M001 is implemented and closed. A node may now be configured to read host-wide +measurements from a local telemetry provider, cache them, and keep them +current, with the provider entirely optional and off by default. + +The three properties the milestone was written to establish are established by +construction rather than by convention: + +1. **The provider endpoint cannot leave the loopback interface.** The endpoint + is validated once, at config-load time, against a closed rule set, and the + client is built without redirect and proxy support. A hostname, a non-loopback + address, a `3xx`, or an inherited `HTTP_PROXY` cannot move the request. +2. **One owner polls.** A single background task performs every provider + request. Readers consult the cache; they never trigger a request, so a burst + of callers cannot become a burst of provider requests. +3. **A missing measurement is never zero.** Every measurement group is `Value`, + `Unsupported`, or `Unknown`, and the provider's own capability flags decide + which. Nothing is fabricated and nothing is clamped. + +The node's execution semantics are untouched. `NodeStatus` and +`NodeCapabilities` keep their existing meaning, admission is unchanged, and +with no `host_telemetry` block the node creates no provider, starts no task, +and claims no measurements. + +## What landed + +| Area | Change | +|---|---| +| `crates/eggwork-core/src/lib.rs` | Protocol-neutral measurement vocabulary: `TelemetrySource`, `TelemetryProviderState`, `TelemetryErrorCategory`, `TelemetryMetric`, `TelemetryCpu`/`Memory`/`Load`/`Swap`/`Disk`/`DiskIo`/`Network`, `HostTelemetry` and `HostTelemetry::validate()`. No Gregg types; no change to `NodeStatus`/`NodeCapabilities`. | +| `crates/eggwork-server/src/telemetry.rs` (new) | The provider seam (`HostTelemetryProvider`, `ProviderOutcome`, `TelemetryError`), the Gregg adapter (`GreggTelemetryProvider`), endpoint validation (`validate_endpoint`, `names_explicit_port`), the normalization (`normalize`), the cache (`TelemetryCache`), the polling owner (`TelemetryMonitor`), and the refresh loop with bounded backoff. | +| `crates/eggwork-server/src/lib.rs` | `NodeConfig::host_telemetry`, `NodeState::telemetry`, monitor construction in `NodeServer::start`, and monitor shutdown in `NodeServer::shutdown`. | +| `crates/eggwork-server/src/operations.rs` | `OperatorConfig::host_telemetry` (`HostTelemetrySettings`), config-load-time validation, `node_config()` passthrough, and the `host-telemetry` doctor check. | +| `crates/eggwork-server/tests/host_telemetry.rs` (new) | Behavioural tests against a real loopback HTTP provider server. | +| `crates/eggwork-server/Cargo.toml` | `eggfetch-core`, `url`, `async-trait` promoted to runtime dependencies; `gregg-protocol 1.0.15` added. | +| `docs/operations.md`, `docs/quickstart.md` | Operator-facing guidance: the optional config block, the loopback requirement, the freshness/staleness rules, and the statement that the default `eggworkd` runs without a provider. | +| `architecture/server-node.md` | New "Optional host telemetry" deep-dive section, the `NodeConfig` table row, and four new invariant rows. | + +## Requirement-to-evidence matrix + +| Plan requirement | Evidence | Where | +|---|---|---| +| A. Validated loopback endpoint; refuse userinfo, non-loopback IP, DNS/hostname, redirect, inherited proxy, request-derived URL; fixed path; no auto-discovery or new listener | `a_non_loopback_or_ambiguous_endpoint_is_refused` (23 refused shapes: `localhost`, `example.com`, `10.0.0.1`, `::ffff:127.0.0.1`, `https`, `file`, userinfo, query, fragment, wrong path, missing/zero/out-of-range port); `an_alternative_numeric_spelling_is_canonicalized_to_the_address`; `a_redirect_is_not_followed` (asserts exactly one request) | `crates/eggwork-server/src/telemetry.rs` tests; `crates/eggwork-server/tests/host_telemetry.rs` | +| B. One node-scoped owner; bounded timeouts, body cap, backoff; no spin when the provider is down; no launch-time wait | `one_owner_polls_for_every_reader` (64 concurrent readers, one provider call); `a_stopped_monitor_stops_polling`; `the_backoff_grows_and_is_capped`; `a_provider_that_never_answers_times_out`; `an_oversized_body_is_refused` | as above | +| C. Typed error/freshness semantics: disabled, warming, unavailable, stale, malformed, valid-with-unsupported-field | `a_disabled_monitor_never_polls`; `a_warming_provider_is_reported_as_warming`; `an_unexpected_status_is_reported_as_unavailable`; `a_malformed_body_is_reported_as_unavailable`; `a_stale_observation_is_reported_as_stale`; `a_provider_timestamp_in_the_future_is_refused`; `a_malformed_body_is_refused`; `a_wrong_schema_version_is_refused` | as above | +| D. Normalize only host-wide measurements; never attach raw Gregg JSON | `a_supported_measurement_is_carried_and_an_unsupported_one_is_not`; `an_unsupported_capability_is_not_reported_as_a_missing_value`; `a_supported_but_unreported_measurement_is_unknown`; `drive_and_throughput_data_is_aggregated_without_identifiers` (asserts the encoded observation contains neither the drive name nor the device id) | `crates/eggwork-server/src/telemetry.rs` tests | +| E. Default-off; no Gregg process, port, listener, or dependency when unconfigured | `a_configuration_without_host_telemetry_asks_for_none`; `a_disabled_monitor_never_polls`; `doctor_reports_that_host_telemetry_is_off_by_default`; no subprocess spawn site exists in the new module (ownership guard: approved process owners are unchanged) | `crates/eggwork-server/src/operations.rs` tests; `crates/eggwork-server/tests/host_telemetry.rs` | +| E. Lifecycle and logging: categorized and rate-limited, no arbitrary bodies/paths | `TelemetryError::category()` is a closed enum; the `host-telemetry` doctor check asserts the provider address is absent from the diagnostic line | `crates/eggwork-server/src/operations.rs` tests | +| F. Make the internal response type ready for future mTLS projection | `eggwork_core::HostTelemetry` is provider-neutral and serializable; the M002 projection input is already a stable value type with a `validate()` | `crates/eggwork-core/src/lib.rs` | +| G. Docs: Gregg must be bound to loopback; default `eggworkd` runs without Gregg | "Host telemetry (optional, off by default)" section; quickstart note | `docs/operations.md`, `docs/quickstart.md` | +| G. Source-level footprint and dependency note | See "Dependency and footprint note" below | this record | + +## Verification actually performed + +All commands were run from the repository root at `ac55985` (the tree the +commit produced; the closure record itself is a later commit). + +| Command | Result | +|---|---| +| `cargo fmt --all -- --check` | pass | +| `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` | pass, no warnings | +| `cargo check --locked --workspace` | pass | +| `cargo test --locked --workspace --all-targets` | pass except one **pre-existing** flake, see "Unresolved findings" | +| `python3 scripts/check_execution_ownership.py` | pass — "execution ownership guard passed; approved process owners: eggwork-runner (2 spawn sites), eggwork-sandbox-helper (1 spawn sites)"; "negative scanner self-test passed; crate dependency direction passed" | +| `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release` | pass — 52 tests, OK | +| `git diff --check` | clean | + +Focused test runs: + +- `cargo test --locked -p eggwork-core` — 21 passed. +- `cargo test --locked -p eggwork-server --lib telemetry` — 14 passed. +- `cargo test --locked -p eggwork-server --lib operations` — 16 passed. +- `cargo test --locked -p eggwork-server --test host_telemetry` — 12 passed. + +Test counts above are the counts observed in the runs recorded here, not +estimates. + +## Platform and feature matrix actually exercised + +| Surface | Exercised | Basis | +|---|---|---| +| Loopback IPv4 provider (`127.0.0.1`) | yes | integration tests against a real loopback HTTP server | +| Loopback IPv6 provider (`[::1]`) | **no** | endpoint validation accepts it and the URL is canonical; no live IPv6 loopback server was bound in this environment, so only the validation path is proven here | +| Provider warming (503 health envelope) | yes | `a_warming_provider_is_reported_as_warming` | +| Provider down (connection refused) | yes | `an_unreachable_provider_is_reported_as_unavailable` | +| Provider hanging | yes | `a_provider_that_never_answers_times_out` (300 ms total deadline) | +| Provider redirecting | yes | `a_redirect_is_not_followed` | +| Provider over-sized / malformed / wrong schema | yes | three focused tests | +| Default-off node (no provider) | yes | configuration, doctor, and monitor tests | +| macOS / Windows hosts | **no** | not exercised; the code path is host-independent and the provider supplies OS-conditional metrics, but no hosted evidence exists. See "Unresolved findings". | + +Nothing above is claimed on the strength of compilation alone: every "yes" row +corresponds to an executed test. + +## Security review + +- **SSRF / request redirection.** The endpoint must be a loopback IP literal + with an explicit port and the fixed provider path. A hostname is refused + outright, so no resolution and therefore no rebinding window exists. The + client is built without Eggfetch's `redirects` and `proxy` features, so a + `3xx` is reported as an unexpected status and no ambient proxy is consulted. + The URL comes only from the operator's config; no request can supply or + influence it. +- **Local spoofing.** A local process could serve a forged `/v2/status`. The + consequence is bounded: a spoofed payload is still schema-validated by the + provider's own rules and by `HostTelemetry::validate()`, and the worst case + is a wrong *measurement*, which is advisory and never enforcement evidence. + This is recorded rather than defended, and matches ADR-0006's treatment of + the local trust boundary. +- **Host-information exposure.** The provider's system identity, drive names, + device identities, and interface identities are dropped in `normalize`. The + normalized observation is asserted to contain neither the drive name nor the + device id. Storage capacity is an aggregate over the reported volumes and + carries no mount path. +- **Metadata in diagnostics.** Provider failures are a closed category + enum. No response body, provider URL, or host path enters a category, a log + line, or a metric. The doctor check does not echo the provider address; the + operator-facing `config print` does show the configured endpoint, because + that is the operator's own non-secret configuration and they need to see + what they configured. The endpoint carries no credentials — userinfo is + refused at validation. +- **Resource bounds.** Decoded body ≤ 256 KiB, connect deadline 2 s, total + deadline 5 s, one poll per interval, bounded backoff. A hostile or broken + provider cannot spin the node or exhaust its memory. +- **Privilege.** The adapter runs in the daemon's own process and reads + nothing but the provider's HTTP response. It creates no subprocess, opens no + listener, and claims no capability. The ownership guard's approved process + owners are unchanged. + +## Compatibility and migration review + +- The provider is off by default. A node whose config has no `host_telemetry` + block is byte-for-byte the same node it was: no provider, no task, no + measurement, no new capability, no change to `NodeStatus`, + `NodeCapabilities`, admission, leases, or execution semantics. +- The config addition is one optional object with `deny_unknown_fields`, so an + existing config file still loads and an unknown key inside the new object is + refused rather than ignored. +- `HostTelemetry` is new vocabulary in `eggwork-core`. It is additive: no + existing type changed shape, no serialization of an existing type changed, + and `NodeStatus`/`NodeCapabilities` are untouched. A node without a provider + never produces one. +- No database migration. The cache is in memory; nothing is persisted. +- Rollback is "remove the `host_telemetry` block", or leave the provider + running and stop the node. There is no on-disk state to unwind. + +## Dependency and footprint note + +The plan asked for a measured dependency note, and for `gregg-protocol` to be +preferred only if the dependency impact is reasonable. + +- `gregg-protocol 1.0.15` is used directly. It adds **three** packages to + `Cargo.lock`: `gregg-protocol`, `thiserror 1.0.69`, and `thiserror-impl + 1.0.69` (the provider's crate is on `thiserror` 1.x while this workspace is + on 2.x). It introduces **no new dependency family** — `serde`, `serde_json`, + and `thiserror` were already in the graph. +- The alternative was a hand-rolled minimal DTO with equivalent strict + validation. That would have avoided the three packages but would have + re-implemented the provider's validation rules in Eggwork, which is exactly + the drift the plan asked to avoid ("a minimal DTO with equivalent strict + validation" only if the dependency cost is *material*). The cost here is + three packages and one duplicated `thiserror` major version, which is not + material against a rule that "no raw provider JSON, no copied protocol + logic" is worth more. +- The published `gregg-protocol` 1.0.15 `v2.rs` was compared byte-for-byte + against the reviewed Gregg working tree and is identical, so the wire types + this milestone coded against are the shipped ones. +- `eggfetch-core` moved from a dev-dependency to a runtime dependency of + `eggwork-server`. It was already a workspace dependency of `eggwork-client` + at the same version and feature set (`standard-http1`, `tls-rustls`), so this + adds no new package to the graph. `url` and `async-trait` were likewise + already workspace dependencies. +- The provider client deliberately uses the `standard-http1` feature set + *without* `redirects` and *without* `proxy`. That is the mechanism behind + the "no redirect hop, no inherited proxy" property, not an accident of + configuration. + +## Documentation status + +| Document | State | +|---|---| +| `docs/operations.md` | Updated: the readiness table now lists eight checks including `host-telemetry`, and a new "Host telemetry (optional, off by default)" section covers the config block, the loopback requirement and exactly which endpoint shapes are refused, the single-owner polling model, the freshness and staleness rules, and the bounded failure categories. | +| `docs/quickstart.md` | Updated: states that the config above has no `host_telemetry` block, so the node creates no provider and reports no host measurements, and links to the operations section. | +| `architecture/server-node.md` | Updated: new "Optional host telemetry" deep-dive section, the `NodeConfig` table row, and four new invariant rows pointing at the tests that pin them. | +| `examples/eggworkd.example.json` | Deliberately unchanged. The committed example is the *default-off* shape; the optional block is documented in `docs/operations.md` so the example does not imply telemetry is on. | + +## Unresolved findings + +1. **Low — IPv6 loopback provider is validated but not exercised against a live + server.** `http://[::1]:PORT/v2/status` is accepted and canonicalized, and + the refusal list covers the IPv4-mapped and link-local forms, but no test + bound an IPv6 loopback listener in this environment. The validation path is + proven; the transport path is not. Not a closure blocker: the provider + contract is the same over either family, and the IPv4 path is fully + exercised. +2. **Low — no hosted macOS/Windows evidence.** The adapter is host-independent + and the provider supplies OS-conditional metrics (the `swap` capability is + false on the fixture host, which is the interesting OS-conditional case and + *is* covered). No hosted run on macOS or Windows was performed, so no + platform claim is made beyond "host-independent code path, exercised on + Linux". +3. **Pre-existing, unrelated — `crates/eggwork-sandbox-helper` `ETXTBSY` + flake.** `crates/eggwork-sandbox-helper/tests/landlock_runner.rs` fails + intermittently under the full parallel workspace run with + `Os { code: 26, kind: ExecutableFileBusy }` from `execve` of the staged + helper. This is **not** caused by this milestone: the sandbox-helper crate + is untouched by `ac55985` (`git diff --name-only` lists no sandbox file), + the test passes 3/3 in isolation on this tree, and the same failure was + reproduced on the **unmodified** tree at `dfa4efd` (run 1 of 3 clean-tree + full-suite runs). It is the host-level kernel window already recorded and + re-dispositioned in `plans/closure/operations-distribution/004a-status.md`. + It is recorded here for honesty, not as a M001 defect. +4. **Informational — the provider address appears in `eggworkd config print`.** + This is deliberate (see "Security review"): it is the operator's own + non-secret configuration, it carries no credentials, and the operator needs + to see what they configured. It is absent from every diagnostic line, + category, metric, and log. + +## Registry and roadmap disposition + +- `plans/subsystems/optional-gregg-host-telemetry-roadmap.md` — M001 moves + from *ready* to **closed**; the roadmap status line and the dependency graph + are updated; M002 moves from *blocked on M001 closure* to **ready**. +- `plans/registry.md` — the Optional Gregg host telemetry workstream row, + the dependency-ready plan table, the closed-plans table, and the planned / + blocked work table are updated. M002 is unlocked. +- `plans/implementation/optional-gregg-host-telemetry/001-loopback-gregg-adapter.md` + — status `closed`, with a pointer to this record. +- `plans/implementation/optional-gregg-host-telemetry/002-authenticated-node-telemetry.md` + — status `ready`; its blocker (M001 closure freezing the bounded normalized + provider contract) is discharged by `eggwork_core::HostTelemetry` and + `eggwork_core::TelemetryProviderState`. + +**M002 is unblocked.** The interface it relies on exists and is proven: a +protocol-neutral, validated, provider-neutral observation type with a closed +provider-state enum and a closed error-category enum. + +## Final disposition + +**M001 — closed.** Acceptance criteria are satisfied and the closure evidence +is recorded above. M002 is unlocked and ready for handoff. diff --git a/plans/closure/optional-gregg-host-telemetry/002-status.md b/plans/closure/optional-gregg-host-telemetry/002-status.md new file mode 100644 index 0000000..57c7fe8 --- /dev/null +++ b/plans/closure/optional-gregg-host-telemetry/002-status.md @@ -0,0 +1,365 @@ +# Optional Gregg host telemetry — M002 closure + +Status: **closed** +Closed: 2026-10-19 +Source plan: `plans/implementation/optional-gregg-host-telemetry/002-authenticated-node-telemetry.md` +Subsystem roadmap: `plans/subsystems/optional-gregg-host-telemetry-roadmap.md` +Decision: `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` +Branch: `planning/optional-gregg-telemetry-m001-m002` +Implementation commit: `5ccb1e6` — *feat(protocol): authorized node telemetry read route and client method (M002)* +Reviewed head at closure: `5ccb1e6` +Predecessor: M001 closed at `2190818` (implementation `ac55985`) + +## Executive finding + +M002 is implemented and closed. An authorized controller can now read the +node's bounded, sanitized host-wide observation over the existing mTLS +channel, and the provider itself remains where it was: on the node's +loopback interface, reachable by nobody remotely. + +The three properties the milestone was written to establish are established: + +1. **The provider is not remotely reachable.** The route is a read of the + node's own cache. It never contacts the provider, so a burst of readers + cannot become a burst of provider requests, and a provider that is down + does not turn a read into a timeout. +2. **Authorization is narrow and explicit.** The route is guarded by a + separate `telemetry` grant, not folded into `status`. A principal without + it receives the existing typed 403, and the refusal reveals nothing about + whether the node holds an observation. +3. **The contract is frozen and the client does not trust it blindly.** The + wire document is versioned, its `state`/`observation` pair is documented + and checked, and the client refuses a response that is malformed, + oversized, of an unknown version or source, self-contradictory, out of + range, or addressed to a different node. + +The node's execution semantics are unchanged. `NodeStatus` and +`NodeCapabilities` keep their existing meaning, no capability feature was +added, admission is untouched, and no new scheduler, queue, or placement +authority was introduced. + +## The frozen wire contract + +`GET /v1/node/telemetry` returns `eggwork_core::NodeTelemetry`, schema +version 1. The contract is written out in full in +[`architecture/protocol.md`](../../architecture/protocol.md#the-node-telemetry-wire-contract-schema-version-1). + +```json +{ + "schema_version": 1, + "node_id": "worker-01", + "source": "gregg", + "state": "ready", + "age_ms": 231, + "last_error": null, + "observation": { + "observed_at_unix_ms": 1729460000123, + "sample_interval_ms": 1000, + "cpu": { "value": { "logical_cores": 8, "usage_pct": 12.5, "iowait_pct": 1.5 } }, + "memory": { "value": { "available_bytes": 4000000, "total_bytes": 8000000, "used_bytes": 4000000 } }, + "load": { "value": { "one": 0.5, "five": 0.25, "fifteen": 0.125 } }, + "swap": "unsupported", + "disk": { "value": { "available_bytes": 900, "total_bytes": 1000, "volume_count": 1 } }, + "disk_io": { "value": { "read_bytes_per_sec": 11, "write_bytes_per_sec": 22 } }, + "network": { "value": { "rx_bytes_per_sec": 33, "tx_bytes_per_sec": 44 } } + } +} +``` + +### State taxonomy + +`state` describes the **provider**, never the host. + +| `state` | `observation` | Meaning | +|---|---|---| +| `disabled` | absent | No provider is configured. The node reports no host measurements. | +| `warming` | absent | The provider is alive but has not produced a sample yet. | +| `ready` | present | A sample is present and within its freshness bound. | +| `stale` | present | A sample is present but older than the freshness bound. | +| `unavailable` | present or absent | The provider could not be reached. | +| `invalid` | present or absent | The provider answered with something unusable. | + +A sample is **current only when the state is `ready`**. `unavailable` is not +zero utilization. The per-measurement groups keep the rest explicit: +`unsupported` means the platform cannot produce the measurement, `unknown` +means it can but this sample carried none, and only `value` is a +measurement. + +### Error taxonomy + +Provider failures are reported as a bounded category and never as prose: +`connection`, `timeout`, `http_status`, `malformed`, `schema_version`, +`invalid`, `too_large`, `clock_skew`. The client maps a node that has no +such route to `ClientError::TelemetryUnsupported`, and an unauthorized +principal to the node's existing typed 403. Those three answers — *the node +cannot serve telemetry*, *you may not read it*, *the provider is down* — are +distinguishable without parsing a message. + +## What landed + +| Area | Change | +|---|---| +| `crates/eggwork-core/src/lib.rs` | `NodeTelemetry` (the frozen wire DTO), `NODE_TELEMETRY_SCHEMA_VERSION`, and `NodeTelemetry::validate()`: schema version, the `state`/`observation` agreement, the `observation`/`age_ms` agreement, and the delegated measurement validation. | +| `crates/eggwork-server/src/lib.rs` | `Operation::Telemetry`, `Route::Telemetry`, the `GET /v1/node/telemetry` route entry, the dispatch arm, and the `node_telemetry` projection (a cache read, nothing else). | +| `crates/eggwork-server/src/operations.rs` | The `telemetry` grant name. | +| `crates/eggwork-client/src/lib.rs` | `NodeClient::telemetry` and `NodeClient::telemetry_for`, `ClientError::TelemetryUnsupported`, and the 64 KiB telemetry body cap. | +| `architecture/protocol.md` | The frozen contract, written out in full. | +| `architecture/server-node.md` | The read route, the narrow grant, and the 404/403 distinction. | +| `architecture/client-transport.md` | The client method, its refusals, and the new error variant. | +| `docs/operations.md` | Operator-facing: the `telemetry` grant, the route, and the state table. | +| `examples/eggworkd.example.json` | The `telemetry` operation name in the grant list. | + +## Requirement-to-evidence matrix + +| Plan requirement | Evidence | Where | +|---|---|---| +| A. Freeze an additive response contract; never attach Gregg raw JSON; keep the DTO protocol-neutral and non-invasive to `NodeStatus` | `NodeTelemetry` + `NODE_TELEMETRY_SCHEMA_VERSION`; `a_ready_telemetry_response_validates`, `a_telemetry_response_with_an_unknown_schema_version_is_refused`, `a_ready_telemetry_response_without_an_observation_is_refused`, `a_disabled_telemetry_response_with_an_observation_is_refused`, `a_telemetry_response_whose_age_contradicts_its_observation_is_refused`, `a_telemetry_response_round_trips_through_json` | `crates/eggwork-core/src/lib.rs` tests | +| B. One bounded read route with existing peer principal derivation, explicit read authorization, and response bounds | `an_authorized_principal_reads_the_cached_observation`; `an_unauthorized_principal_cannot_read_the_observation`; `route_contract_is_fixed_target_and_versioned` (the route is in the fixed table) | `crates/eggwork-server/src/lib.rs` tests | +| B. Reuse a read-only grant only if the scope is appropriate; otherwise introduce a narrow read grant | The `telemetry` grant is separate from `status`. The installed-binary receipt below shows a principal **without** it receiving 403 on the telemetry route while its `status` read still returns 200. | installed-binary probe; `docs/operations.md` | +| B. Unauthorized principals receive the existing typed 403 without leakage | `an_unauthorized_principal_cannot_read_the_observation` asserts the 403 and that the rendered error contains neither `logical_cores` nor `usage_pct`; the installed-binary probe shows `{"code":"forbidden","message":"operation is not authorized"}` | as above | +| B. No Gregg URL/proxy exposure, CORS, unencrypted fallback, or anonymous route | The route is served by the same mTLS-only EggServe surface as every other route; the unauthenticated probe never reaches HTTP (the TLS handshake is refused). The response carries no provider address. | installed-binary probe; `an_authorized_principal_reads_the_cached_observation` | +| B. Requests only consult the M001 cache, not Gregg HTTP synchronously | `an_authorized_principal_reads_the_cached_observation` asserts the provider request count is unchanged across 16 remote reads | `crates/eggwork-server/src/lib.rs` tests | +| C. A fixed-target client method using the existing Eggfetch transport and client identity | `NodeClient::telemetry` uses the same `HttpClient` and `TlsConfig` as every other method | `crates/eggwork-client/src/lib.rs` | +| C. Enforce body cap, schema version, non-finite/out-of-range numbers, timestamp/freshness, node-id mismatch, unknown source, optional-field validation | `an_oversized_body_is_refused`, `an_unknown_schema_version_is_refused`, `an_unknown_source_is_refused`, `a_response_with_an_out_of_range_measurement_is_refused`, `a_response_whose_number_does_not_fit_is_refused`, `a_response_whose_state_contradicts_its_observation_is_refused`, `a_malformed_body_is_refused`, and the `telemetry_for` node-id mismatch assertion | `crates/eggwork-server/src/lib.rs` tests | +| C. Preserve distinguishable `unsupported` (legacy 404), `disabled`, and `unavailable` | `a_node_without_the_route_is_reported_as_unsupported` (→ `TelemetryUnsupported`); `a_node_without_a_provider_reports_disabled` (→ `state: disabled`); `an_unreachable_provider_is_reported_as_unavailable` (→ `state: unavailable`, `last_error: connection`) | `crates/eggwork-server/src/lib.rs` tests | +| D. Execution eligibility stays with status/capability/preflight and server-local enforcement | `telemetry_does_not_change_execution_semantics` — an execution still runs to `Succeeded` and creates its marker on a telemetry-enabled node, and the node advertises no telemetry feature | `crates/eggwork-server/src/lib.rs` tests | +| D. Never replace `active_executions` with a telemetry guess; no cluster queue or worker selection | `NodeStatus` is unchanged in shape and meaning; `node_status` was not modified; no new state was added to the server | `crates/eggwork-core/src/lib.rs`, `crates/eggwork-server/src/lib.rs` | +| D. Advertise a static protocol feature only if necessary; do not present provider readiness as an execution capability | **No feature was added.** `static_capability_features` is unchanged, and the installed-binary `status` receipt lists the same features as before with no telemetry entry. | `crates/eggwork-server/src/lib.rs`; installed-binary probe | +| E. Update API, operations and client documentation | `architecture/protocol.md` (the frozen contract), `architecture/server-node.md`, `architecture/client-transport.md`, `docs/operations.md`, `examples/eggworkd.example.json` | as above | +| E. Add a minimal operator command only if needed | **None was added.** The `host-telemetry` doctor check reports whether the provider is configured, and the mTLS route is the live diagnostic surface. No new telemetry control plane exists. | `crates/eggwork-server/src/operations.rs` | + +## Verification actually performed + +All commands were run from the repository root on the tree `5ccb1e6` produced +(the closure record itself is a later commit). + +| Command | Result | +|---|---| +| `cargo fmt --all -- --check` | pass | +| `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` | pass, no warnings | +| `cargo check --locked --workspace` | pass | +| `cargo test --locked --workspace --all-targets` | pass for every suite, **except** one pre-existing `eggwork-sandbox-helper` `ETXTBSY` flake that also reproduces on the unmodified tree — see "Unresolved findings" finding 4. The affected suite passes when the failure does not trigger (it passed in the run immediately before this one) | +| `python3 scripts/check_execution_ownership.py` | pass — "execution ownership guard passed; approved process owners: eggwork-runner (2 spawn sites), eggwork-sandbox-helper (1 spawn sites)"; "negative scanner self-test passed; crate dependency direction passed" | +| `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release` | pass — 52 tests, OK | +| `git diff --check` | clean | + +Focused runs: + +- `cargo test --locked -p eggwork-core` — 28 passed (7 of them the new `NodeTelemetry` contract tests). +- `cargo test --locked -p eggwork-server --lib telemetry_route` — 6 passed. +- `cargo test --locked -p eggwork-server --lib telemetry_client_validation` — 8 passed. +- `cargo test --locked -p eggwork-server --test host_telemetry` — 12 passed (M001, unchanged). +- `cargo test --locked --workspace --all-targets` — `eggwork-server` lib 128 passed, `eggwork-core` 28, `eggwork-client` 9, `eggwork-runner` 18, `release_contract` 36, `host_telemetry` 12, `capability_probe` 2, and `landlock_runner` 15 in the clean run (its one intermittent failure is finding 4 below). + +### Installed-release receipt (the no-Gregg smoke test) + +The opt-in installed-release qualification was run against a locally built +`eggworkd` and `eggwork-sandbox-helper`, with a node configuration that has +**no `host_telemetry` block** — that is, the default. + +``` +EGGWORK_QUALIFY_ROOT= \ + cargo test --locked -p eggwork-server --features qualification \ + --test installed_qualification qualification_fixture -- --ignored + → test qualification_fixture ... ok + +EGGWORK_QUALIFY_DAEMON=/bin/eggworkd \ +EGGWORK_QUALIFY_CONFIG=/state/node.json \ +EGGWORK_QUALIFY_TLS_DIR=/state/tls \ +EGGWORK_QUALIFY_PLATFORM=linux \ +EGGWORK_QUALIFY_RECEIPT=/receipt.json \ + cargo test --locked -p eggwork-server --features qualification \ + --test installed_qualification \ + installed_release_admits_execution_and_refuses_unsupported_isolation -- --ignored + → test installed_release_admits_execution_and_refuses_unsupported_isolation ... ok +``` + +The receipt records, against the installed binary and with **no telemetry +provider configured**: the doctor check `host telemetry is disabled; the node +reports no host measurements`; `configuration` valid; the sandbox helper +runtime-probed as `isolation.landlock.workspace-rw.v1` plus +`resources.cgroups-v2.{memory,cpu,pids}`; an execution reaching `Succeeded` +with exit code 0; required isolation `applied`; and an outside-workspace +write denied. + +### Installed-binary route probe + +The same installed binary was then driven over real mTLS with the fixture's +client certificate: + +```text +# granted principal, no provider configured +GET /v1/node/telemetry +→ HTTP 200 + {"schema_version":1,"node_id":"qualification-node","source":"gregg", + "state":"disabled","age_ms":null,"last_error":null,"observation":null} + +# same binary, principal WITHOUT the "telemetry" grant +GET /v1/node/telemetry +→ HTTP 403 + {"schema_version":1,"code":"forbidden","message":"operation is not authorized"} + +# same principal, same instant +GET /v1/status +→ HTTP 200 (node status, unchanged, no telemetry entry in the feature list) + +# no client certificate at all +GET /v1/node/telemetry +→ the TLS handshake is refused ("certificate required"); HTTP is never reached +``` + +That is the whole authorization story on a real binary: the route exists, it +is reachable only over mTLS with a known principal, it is refused with a +typed 403 for a principal that lacks the narrow grant, and the same +principal's ordinary status read is unaffected. + +## Platform and feature qualification matrix actually exercised + +| Surface | Exercised | Basis | +|---|---|---| +| Authorized mTLS read of a live observation | yes | `an_authorized_principal_reads_the_cached_observation`; installed-binary probe (200 with `state: disabled`) | +| Unauthorized principal (known, not granted) | yes | 403, installed-binary probe and unit test | +| Unknown principal (valid certificate, no grant entry) | yes | 401, `an_unauthorized_principal_cannot_read_the_observation` | +| No client certificate | yes | the TLS handshake is refused; the route is never reached over HTTP | +| Node without a provider | yes | `state: disabled`, unit test and installed-binary probe | +| Node whose provider is unreachable | yes | `state: unavailable`, `last_error: connection` | +| Node that predates the contract | yes | 404 → `TelemetryUnsupported` | +| Remote read does not poll the provider | yes | 16 remote reads, provider request count unchanged | +| Malformed / oversized / unknown-version / unknown-source / self-contradictory / out-of-range response | yes | six focused client tests | +| Node-id mismatch | yes | `telemetry_for` refuses a different node id | +| Installed binary, no Gregg configured | yes | qualification receipt above | +| Execution semantics unaffected | yes | `telemetry_does_not_change_execution_semantics`; the qualification receipt's `Succeeded` execution | +| macOS / Windows hosts | **no** | not exercised. The route, the contract, and the client method are host-independent, but no hosted evidence exists. See "Unresolved findings". | + +Nothing above is claimed on the strength of compilation alone: every "yes" +row corresponds to an executed test or an executed probe. + +## Security review + +- **Trust boundary.** It terminates at Eggwork's mTLS, exactly as ADR-0006 + requires. The Gregg endpoint is never reachable from a remote caller: the + route is a cache read, the response carries no provider address, and the + provider's own listener is bound to the node's loopback interface by the + M001 endpoint rule. No new listener was added and no unauthenticated + entry point was added. +- **Authorization.** The `telemetry` grant is separate from `status`, so no + existing grant silently widened. A refused read returns the node's + existing typed 403 with a fixed message; the unit test asserts the + rendered error contains no measurement field names, and the installed + probe shows the fixed body. +- **Information disclosure.** The response carries only host-wide + aggregates: no provider address, mount path, device or interface + identity, hostname, per-execution measurement, or raw provider JSON. The + node's system identity never leaves the node (M001's translation drops it). +- **Trust in the measurement.** A measurement is advisory. It does not + qualify, withhold, or change an execution capability; `NodeStatus` and + `NodeCapabilities` are untouched, and the node advertises no telemetry + feature. A hostile or spoofed provider can therefore produce a wrong + *measurement*, and nothing more. +- **Resource bounds.** The response is a small bounded document; the client + caps it at 64 KiB, on top of the transport's own 16 MiB cap. The route + performs no I/O of its own, so it cannot be used to amplify work against + the provider. +- **Client-side validation.** A node is a fixed target, and a response + naming a different node is refused by `telemetry_for`. The client refuses + an unknown schema version, an unknown source, a self-contradictory + `state`/`observation` pair, an out-of-range or non-representable number, + and a body that is not the expected document. A `404` is reported as + "unsupported", not as a malformed response, so a legacy node is not + mistaken for a broken one. +- **Redaction.** The new `ClientError::TelemetryUnsupported` carries no + payload and the hand-written `Debug` prints it as a unit variant, so + nothing node-controlled reaches a log line through it. + +## Compatibility and migration review + +- The route is additive. A node that gains it does not change any existing + response: `NodeStatus`, `NodeCapabilities`, the execution protocol, the + lease semantics, and the error model are all unchanged, and the + installed-binary `status` receipt is byte-comparable with a pre-change + node apart from nothing. +- A principal is not granted telemetry until an operator adds `"telemetry"` + to its grant list. The `operation` name table gained one entry; every + other grant name keeps its meaning. An existing configuration file is + still valid and still loads, and a principal without the new grant simply + cannot use the new route. +- The client is additive: two new methods and one new error variant, with + no change to any existing method's behavior. +- No database migration. Nothing about the telemetry read is persisted. +- A client talking to a node that predates the contract gets a typed + `TelemetryUnsupported`, not a transport failure, so a mixed-version + deployment degrades cleanly. +- Rollback is "remove the `telemetry` grant", or "remove the route's + authorization" — there is no state to unwind. + +## Documentation status + +| Document | State | +|---|---| +| `architecture/protocol.md` | The frozen wire contract is written out in full: every field, the `state`/`observation` table, the measurement-group forms, and an explicit list of what the contract does not carry. | +| `architecture/server-node.md` | New section for the read route: the narrow grant and why it is separate from `status`, the cache-only read, and the 404/403 distinction. | +| `architecture/client-transport.md` | The two client methods, the `TelemetryUnsupported` variant in the error table, and the telemetry-specific refusals. | +| `docs/operations.md` | Operator-facing: the `telemetry` grant in a configuration example, the route, the state table, and the statement that the feature does not change `status` or `capabilities`. | +| `examples/eggworkd.example.json` | The `telemetry` operation name added to the grant list so the grant is discoverable. | + +## Unresolved findings + +1. **Low — no hosted macOS/Windows evidence.** The route, the contract, and + the client method are host-independent, and the provider's OS-conditional + measurements are covered on the fixture host (the `swap` capability is + false there, which is the interesting case and is covered). No hosted + run on macOS or Windows was performed, so no platform claim is made + beyond "host-independent code path, exercised on Linux". +2. **Low — the installed-release receipt is a locally built binary, not a + published release.** The qualification harness was run against + `target/debug/eggworkd` at a local installation root, and the receipt + therefore qualifies *this tree's* binary rather than a tagged release + artifact. The suite is designed to qualify an installed release and the + same command line with a published binary would produce a release + receipt; that is a release-lineage action reserved for the maintainer, in + the same way Operations M004's installed-release receipt is. +3. **Informational — the provider address appears in `eggworkd config + print`.** Unchanged from M001 and deliberate: it is the operator's own + non-secret configuration. It is absent from the telemetry response, from + every diagnostic line, from every category, and from every metric. +4. **Pre-existing, unrelated — `crates/eggwork-sandbox-helper` `ETXTBSY` + flake.** The intermittent `Os { code: 26, kind: ExecutableFileBusy }` + failure seen during the M001 batch recurred in this milestone's runs: it + hit the full parallel workspace run on a different test than before, and + it also reproduced in a single-package run of that suite. It is **not** + caused by this work: the sandbox-helper crate is untouched by `5ccb1e6`, + and the M001 batch reproduced the same failure on the **unmodified** tree. + The cause was already measured and dispositioned in + `plans/closure/operations-distribution/004a-status.md`: a host-level + kernel window on this machine, reproducible with any copy mechanism and + with a plain `std::process::Command` spawn outside the runner entirely, + with no writer holding the inode and with immediate re-spawns succeeding. + It is neither a fixture defect nor a production defect. It is recorded + here for honesty, not as a M002 defect, and it is the reason this + milestone's "full workspace run" line above is qualified. + +## Registry and roadmap disposition + +- `plans/subsystems/optional-gregg-host-telemetry-roadmap.md` — M002 moves + from *ready* to **closed**; the roadmap status line, the dependency graph, + and the milestone list are updated. The subsystem's "Completion" condition + is now met. +- `plans/registry.md` — the Optional Gregg host telemetry workstream row, the + dependency-ready plan table, the closed-plans table, and the planned / + blocked work table are updated. The CodeGG worker-telemetry consumer is + now unblocked: the interface it needs is frozen and closed. +- `plans/implementation/optional-gregg-host-telemetry/002-authenticated-node-telemetry.md` + — status `closed`, with a pointer to this record. + +**The CodeGG worker telemetry consumer is unblocked.** The plan's condition +was: "Provide a frozen example wire payload, error taxonomy, exact operation +authorization, client method, freshness semantics, reference client test and +a true authenticated integration receipt." All seven are provided above. + +## Final disposition + +**M002 — closed.** Acceptance criteria are satisfied and the closure evidence +is recorded above. The subsystem roadmap's completion condition — both +milestones closed with code/test receipts and a verified default-off +no-Gregg execution — is met, and the downstream CodeGG consumer can depend +on the frozen, versioned authenticated response. diff --git a/plans/implementation/operations-distribution/004b-staged-helper-publication-durability-corrective.md b/plans/implementation/operations-distribution/004b-staged-helper-publication-durability-corrective.md new file mode 100644 index 0000000..91a6758 --- /dev/null +++ b/plans/implementation/operations-distribution/004b-staged-helper-publication-durability-corrective.md @@ -0,0 +1,188 @@ +# 004b — Staged helper write-access corrective + +Status: **closed** +Source roadmap: `plans/subsystems/operations-distribution-roadmap.md` (M004b) +Corrects: `plans/closure/operations-distribution/004a-status.md` §5, §9 criterion 3, §10, §11 +Closure record: `plans/closure/operations-distribution/004b-status.md` +Branch: `planning/optional-gregg-telemetry-m001-m002` + +> **Naming.** The milestone was registered as "staged helper publication durability +> corrective", on the hypothesis that the refusal was a write-back problem that a +> durability barrier could close. CI disproved that hypothesis (§2), and the +> executed design is not a barrier at all: the staged helper is never written. +> The milestone ID and the file names are kept so that the pointer from the +> M004a record's addendum keeps resolving, but the design this plan describes +> is the executed one. + +## 1. Objective + +Eliminate the `ETXTBSY` refusal that the Operations M004a closure characterised +but did not close, so that a Linux suite which stages a helper and immediately +executes it cannot go red at random. + +## 2. Baseline and problem + +`ETXTBSY` ("Text file busy") is Linux refusing to execute a file whose inode is +open for writing. The M004a closure recorded the refusal as a host-level timing +window, dispositioned rather than fixed, and left the elimination to a future +`O_TMPFILE`+`linkat` publication that the repository's rules forbid. + +CI run `39306109740` then failed on that open residual: +`malformed_private_spec_and_unavailable_status_channel_do_not_launch_target` +panicked at `crates/eggwork-sandbox-helper/tests/landlock_runner.rs:471` with +`ExecutableFileBusy`. A characterisation that leaves the suite able to go red is +not a disposition. + +The first attempt at this corrective then failed CI in turn, and its failure is +what fixed the design (§3). + +## 3. The design change this plan records + +The first attempt staged the helper by **copying** it and closed the copy with a +durability barrier — write, `sync_all`, rename, sync the parent directory — on +the theory that the refusal was a write-back window. The barrier was measured +at 0.02% on the development host and was carried to CI. + +CI run `39316541191` (and the push run `39316444280`) refused that theory: the +new copy-path regression test was refused 3 times in 32 stagings on the CI +runner, *with the barrier in place*, while the link-path test passed 32 of 32 in +the same run. A barrier that is 0.02% on one host and 9% on another is not a +barrier; it is a rate. + +The design that replaced it is stated in §4 and §5, and the evidence for it — +including the kernel's own accounting, which the first attempt had inferred +rather than read — is in the closure record. + +## 4. Scope + +- The shared helper-staging path in + `crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs`. +- The equivalent staging helper in `crates/eggwork-server/src/lib.rs` + (`place_trusted_helper`, inside the test module). +- The regression tests in `crates/eggwork-sandbox-helper/tests/landlock_runner.rs`. +- The closure record, the roadmap entry, and the registry rows. + +## 5. Invariants and non-goals + +**Invariants** + +1. The staging path keeps its shape: build output is read-only input, each + fixture owns its own `0700` directory and its own path, publication is + atomic, and cleanup follows convergence. +2. The fix is structural — the file the fixture executes is never written — not + a retry, not a sleep, and not a barrier. +3. No fixture mutates an inode it shares with another fixture or with the + Cargo-built helper. The one exception is a one-time, one-directional + normalisation of the build output's *mode* (see §6.2). +4. No `unsafe`, no new dependency, no new platform surface, no change to + production behaviour. +5. The M004a closure record is preserved as written. + +**Non-goals** + +- Changing `verify_trusted_helper` or the trust rules. +- Changing the fixture-isolation invariant or weakening the M004a proofs. +- `O_TMPFILE`+`linkat` publication. +- Changing how the product installs or consumes the helper. + +## 6. Required changes + +### 6.1 Staging is link-only + +`stage(source)` publishes the Cargo-built helper into the fixture's private +`0700` directory with `link(2)`. A link shares the source's inode and does not +open it for writing, so the inode's write access is never taken and the kernel +has no reason to refuse to execute it. + +There is **no copy fallback**. A copy is a file that was written, and a written +file is exactly the construction the CI evidence refuses. When a link is +impossible, staging fails loudly with the reason. + +The system temporary directory is tried first, because its ancestor chain is the +one `verify_trusted_helper` accepts by construction; a directory next to the +source is the fallback, because it is the same filesystem by definition. + +### 6.2 The source's mode is normalised once + +A link carries the source's mode, and `verify_trusted_helper` rejects a helper +that anyone but its owner may write. Cargo derives the executable's mode from +the umask (`0666 & ~umask` plus the execute bits), so a permissive umask +(0002 is common in shared development environments) leaves the build output +group-writable and no fixture could stage it by linking. + +The fixture therefore clears the group and world write bits of the build output +once, before the first link is made, under a lock so that no fixture can stage +a helper whose mode has not been settled. The change is one-directional: it +removes write permission for others, keeps the owner's permissions and the +execute bits, and never touches the build output's bytes. + +### 6.3 Mutations publish a replacement + +`set_mode` and `replace_with_junk` used to `chmod` or overwrite the staged +helper in place. With a shared inode that would reach the Cargo-built helper +and every other fixture, so both now publish a **replacement**: the bytes are +written under a staging name and renamed into place. No fixture mutates a +shared inode. + +### 6.4 The server's own staging + +`crates/eggwork-server/src/lib.rs` `place_trusted_helper()` stages and then +executes a helper the same way: link-only, with the same mode normalisation and +the same two candidate directories. + +## 7. Required tests + +| Test | Requirement | +| --- | --- | +| `a_linked_helper_is_executable_immediately_after_publication` | 32 parallel stage-and-spawn cycles of the real helper; zero refusals. Plus a structural assertion that the staged helper is the build output's own inode and device, so a regression to copying fails the test without needing a race to reproduce. | +| `a_group_writable_source_is_normalized_to_a_trusted_mode` | The mode normalisation clears the group and world write bits, keeps the owner's permissions and the execute bits, and is idempotent. | +| the 16 pre-existing Landlock tests | unchanged semantics, unchanged assertions, except that `staging_never_mutates_the_cargo_built_helper` now states the normalisation exception explicitly | + +There is deliberately no test for a copy path: the copy path does not exist. + +## 8. Required verification + +```text +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --locked --workspace +python3 scripts/check_execution_ownership.py +python3 scripts/check_execution_ownership.py --prove-negative-exit +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +Plus a bounded repeated run of the Landlock suite at raised thread count, and +the link-path regression test re-run with `stage` forced back through a copy, +to prove it is non-vacuous. + +## 9. Acceptance criteria + +1. The refusal is eliminated by construction: the file the fixture executes is + never written, so the kernel has no reason to refuse it. +2. The elimination is structural — no retry, no sleep, no barrier, no reliance + on timing or on a host's write-back behaviour. +3. The regression test is non-vacuous, proven by removing the fix. +4. Production behaviour is unchanged; the change is test-only. +5. No new dependency and no `unsafe`. +6. The M004a isolation invariant still holds: no fixture mutates a shared + inode's content, and the one mode change is one-directional and happens + before any fixture exists. +7. The M004a record is preserved; the correction is registered as current + authority in the roadmap and the registry. + +## 10. Stop conditions + +- If eliminating the refusal requires `unsafe`, a new dependency, a change to + the trust rules, or weakening a fixture-isolation assertion, stop and record + the alternative for review instead. +- If the refusal cannot be eliminated but only made rarer, record the residual + as a finding with its measured rate rather than closing the milestone. + +## 11. Closure evidence required + +The closure record must distinguish inspected from executed evidence, record +the measurement *and* the kernel source that established the mechanism, show +the regression test failing without the fix, carry the CI evidence that +rejected the copy path, and state the residual risk honestly. diff --git a/plans/implementation/optional-gregg-host-telemetry/001-loopback-gregg-adapter.md b/plans/implementation/optional-gregg-host-telemetry/001-loopback-gregg-adapter.md new file mode 100644 index 0000000..8046ff3 --- /dev/null +++ b/plans/implementation/optional-gregg-host-telemetry/001-loopback-gregg-adapter.md @@ -0,0 +1,46 @@ +# Optional Gregg Telemetry M001 — Loopback Adapter and Bounded Cache + +Status: **closed** +Class: infrastructure / observability +Source: `plans/subsystems/optional-gregg-host-telemetry-roadmap.md` +Decision: `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` +Reviewed baseline: Eggwork `main` and Gregg `docs/api.md`, `architecture/protocol.md` (2026-10-19); implementation agent must reconfirm exact current APIs and lockfile before editing. +Dependency: Gregg's existing v2 status contract only; **no Gregg code changes**. +Closure record: `plans/closure/optional-gregg-host-telemetry/001-status.md` (implementation `ac55985`). + +## 1. Objective + +Build an opt-in, read-only host telemetry adapter behind Eggwork-server that consumes local Gregg v2 cached status and produces a bounded typed host observation with explicit provenance, freshness and unavailable reasons. M001 does not add any remote endpoint or modify admission. + +## 2. Existing implementation evidence + +- `eggwork-core::NodeStatus` has only node id, draining, active-execution count and capabilities. +- Eggwork already has a supervised `NodeServer` lifetime and stable Eggfetch transport dependencies. +- Gregg's `GET /v2/status` includes `observed_at_unix_ms`, `sample_interval_ms`, `capabilities`, CPU, memory and optional load/swap/drives/disk_io/network; unknown optional fields are not zero. Gregg's `gregg-protocol` defines validation; its regular HTTP service is unauthenticated. +- Gregg's server may bind `0.0.0.0` by default. Document and require loopback binding operationally; Eggwork should only contact a verified loopback endpoint. + +## 3. Production work packages + +A. Confirm Gregg payload/v2 validation API and the existing Eggwork HTTP client abstraction. Implement a minimal `HostTelemetryProvider`-style internal seam in `eggwork-server` (or equivalent sibling) with a disabled default, one Gregg implementation, and a fake for tests. Keep Eggwork-core protocol-neutral and free of Gregg types. If `gregg-protocol` materially increases runtime/dependency cost, map a minimal DTO with equivalent strict validation instead; record the measured reason and parity tests. **Do not fork Gregg's collectors.** + +B. Add opt-in node configuration for a loopback HTTP endpoint, refresh interval and freshness TTL with safe bounded defaults. Validate complete origin, port, host/IP literal, scheme and path; reject userinfo, HTTPS/TLS ambiguity, DNS/hostnames (including localhost unless resolved safely without rebinding), non-loopback IP, fragments, redirect hops, inherited proxies and request-derived URLs. Require fixed path `/v2/status`. No auto-discovery or new listener. + +C. Use one node-scoped refresh owner and cache, never one Gregg poll per remote caller. Bound connect timeout, overall deadline, decompressed body bytes, JSON collections and concurrent refreshes. Treat Gregg as advisory input. No locking across network await; no launch-time wait or blocking on Gregg. Validate schema v2, timestamps, counter units, finite percentages, capability/value agreement, sample interval, missingness. Differentiate disabled, warming, unavailable, stale, malformed and valid-with-unsupported-field; never substitute zero for missing measurements. Use monotonic age plus wall-clock provenance and bounded clock-skew tolerance; do not accept future timestamps as indefinitely fresh. + +D. Normalize only host-wide measurements needed by scheduling: CPU cores/utilization, memory bytes/usage, optional swap/load, available disk, disk and network rates, with optional support flags and a source/staleness summary. Avoid transmitting raw mount paths, interface identifiers, hostnames, local jobs, command output or other Gregg data beyond the server. Do not claim per-execution utilization. Make the internal response type ready for future mTLS projection. + +E. Lifecycle and logging: create no task when disabled; when enabled, bounded refresh with backoff and jitter or fixed bounded interval; cancelled on node shutdown. Gregg errors are categorized and rate-limited, not logged with arbitrary bodies/paths. Normal remote execute/cancel/status must remain independent. + +## 4. Verification + +Focused deterministic tests with fake HTTP Gregg v2 responses: valid minimal/full/optional/missing fields, v1-only/404, warming, 503, malformed, duplicate/oversized fields, response slowloris/body cap, negative/future/stale timestamps, clock rollback, unsupported OS fields, SSRF and URL/proxy/redirect rejection, multiple readers one refresh, and shutdown with in-flight fetch. Assert no network calls/default-off, no process spawn, no mutation to Eggwork admission, and isolation/resource enforcement unchanged. + +Use the narrow crate checks as applicable: `cargo fmt --all --check`; `cargo test -p eggwork-server --locked`; `cargo clippy -p eggwork-server --all-targets --locked -- -D warnings`; `python3 scripts/check_execution_ownership.py`; broader repository CI gates/target matrix as instructed by `CONTRIBUTING.md`. Verify exact command names at handoff. An optional real greggd loopback smoke test is operational evidence, never a substitute for negative fixtures. + +## 5. Compatibility, docs and acceptance + +No wire change, new required runtime dependency, database migration, new service manager, or Gregg modification. Add operator docs showing **Gregg must be bound to loopback** and that default `eggworkd` runs without Gregg. M001 closes only with typed error/freshness semantics, bounded single-owner polling, strict local origin enforcement, default-off proof, tests and source-level footprint/dependency note. Deliver a closure record at `plans/closure/optional-gregg-host-telemetry/001-status.md`. + +## 6. Stop conditions / handoff + +Stop and record a blocker if the Gregg protocol cannot be consumed read-only without widening Gregg; if the adapter requires a new network listener, unauthenticated Eggwork entry point, process spawn, altered admission, or broadened `eggwork-core` dependency direction; or if chosen HTTP client cannot reliably disable redirects/proxies and enforce loopback. Do not silently widen this milestone to M002. diff --git a/plans/implementation/optional-gregg-host-telemetry/002-authenticated-node-telemetry.md b/plans/implementation/optional-gregg-host-telemetry/002-authenticated-node-telemetry.md new file mode 100644 index 0000000..e56cb67 --- /dev/null +++ b/plans/implementation/optional-gregg-host-telemetry/002-authenticated-node-telemetry.md @@ -0,0 +1,42 @@ +# Optional Gregg Telemetry M002 — Authenticated Node Observation API + +Status: **closed** +Class: protocol / observability +Source: `plans/subsystems/optional-gregg-host-telemetry-roadmap.md` +Decision: `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` +Reviewed baseline: `eggwork-core::NodeStatus`, `eggwork-server` node operation routes/mTLS authorization, `eggwork-client::NodeClient` (2026-10-19). +Closure record: `plans/closure/optional-gregg-host-telemetry/002-status.md` (implementation `5ccb1e6`). + +## 1. Objective + +Expose M001's bounded sanitized **host-wide observation** to a specifically authorized remote controller over the existing authenticated Eggwork channel. Add a versioned typed fixed-target client method, without exposing Gregg to remote clients and without changing execution admission. + +## 2. Current implementation + +`NodeStatus` includes `node_id`, `draining`, `active_executions`, `NodeCapabilities`; there is no host-usage field. `eggwork-server` maps routes to `Operation`, verifies transport-derived mTLS principals, and checks `Authorizer` before responding. `eggwork-client` uses Eggfetch and targets one node. `ExecutionResult` includes categorical resource-application outcomes, not quantitative per-job measurements. + +## 3. Work packages + +A. Freeze an additive response contract (suggested `NodeTelemetryV1`): `schema_version`, `node_id`, `source = gregg`, typed provider state (`disabled|warming|ready|stale|unavailable|invalid`), observation timestamp and age in milliseconds, optional CPU/logical cores/utilization, optional memory available/total/used, optional load/swap and bounded disk/network aggregate rates; explicit per-metric unsupported/unknown. Never attach Gregg raw JSON. Keep the DTO protocol-neutral and non-invasive to existing `NodeStatus`. Type name/path may adapt to current crate boundaries, but document the exact wire contract for downstream CodeGG. + +B. Add one bounded read route (suggested `GET /v1/node/telemetry`) to the existing Eggwork mTLS server, with existing peer principal derivation, explicit read authorization and response bounds. Verify existing status-operation grants: reuse a read-only grant only if scope is appropriate; otherwise introduce a *narrow* read grant. Do not require permission to execute jobs just to read a safe summary unless the current auth model forces a deliberate documented choice. Unauthorized principals must receive existing typed 403 without leakage. Do not add Gregg URL/proxy exposure, CORS, unencrypted fallback, or anonymous route. Requests only consult the M001 cache, not Gregg HTTP synchronously. + +C. Add `NodeClient::telemetry` as an optional fixed-target method (name may adapt), using the existing Eggfetch transport/client identity. Enforce server response body cap, schema version, non-finite/out-of-range numbers, timestamp/freshness, node-id mismatch, unknown source and optional-field validation. Preserve distinguishable `unsupported` for legacy 404, `disabled` for configured-off, and `unavailable` for provider failure. + +D. Keep node execution eligibility determined by the existing status/capability/preflight and server-local enforcement. Never replace node `active_executions` with a telemetry guess; do not introduce a cluster queue or worker selection. Advertise a **static protocol feature** only if necessary; avoid presenting provider readiness as an unconditional `NodeCapabilities` execution feature. + +E. Update API, operations and client documentation; add a minimal operator command only if needed for diagnosing the read cache, not a new telemetry control plane. + +## 4. Verification + +With a stub local Gregg provider: an authenticated authorized client receives correct bounded status; unauthenticated/mismatched/unauthorized mTLS principal is denied and cannot distinguish internal metadata; an old node 404 means unsupported; a disabled provider reports disabled; Gregg failure gives unavailable without returning 500 for normal execution; remote read triggers no extra Gregg HTTP fetch; malformed and oversized response is rejected by client; actual execute/cancel/renew/lease/busy/drain semantics unaffected. Include actual loopback mTLS integration and a no-Gregg installed smoke test. + +Suggested gates: `cargo test -p eggwork-core --locked`, `cargo test -p eggwork-client --locked`, `cargo test -p eggwork-server --locked`, `cargo clippy --workspace --all-targets --locked -- -D warnings`, `python3 scripts/check_execution_ownership.py`; run repository-specified qualification as platform availability allows. + +## 5. Acceptance and closure + +Provide a frozen example wire payload, error taxonomy, exact operation authorization, client method, freshness semantics, reference client test and a true authenticated integration receipt. Record closure at `plans/closure/optional-gregg-host-telemetry/002-status.md`; only then mark CodeGG telemetry-consumer milestone ready. No Gregg code or config schema changes. + +## 6. Stop conditions + +Stop on auth bypass, need to expand Gregg, accidental direct Gregg exposure, route requiring a second HTTP server, dependency cycle, new scheduler/placement inside Eggwork, or inability to distinguish telemetry unavailable from real 0% utilization. Document these as blockers, not silent deviations. diff --git a/plans/registry.md b/plans/registry.md index dd8ce98..b914c2b 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -17,6 +17,8 @@ Founding ADRs: - `plans/adrs/ADR-0004-content-addressed-workspaces-and-artifacts.md` - `plans/adrs/ADR-0005-runner-service-separation-and-local-admission.md` +Follow-up accepted ADR: `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` (Eggwork reads local Gregg optionally; Gregg unchanged). + ## Status vocabulary - **proposed** — plan exists but is not approved for execution. @@ -35,6 +37,16 @@ Founding ADRs: Latest Eggwork implementation/closure head reviewed for this planning batch: +- Operations M004b — the staged-helper write-access corrective: the residual + `ETXTBSY` refusal that M004a characterised is eliminated by making the + staged helper a link that is never written, with no copy path left to fail; + the mechanism is confirmed against the kernel's own `i_writecount` + accounting, and two regression tests are proven non-vacuous; + +- `5ccb1e6` / `2190818` — optional Gregg host telemetry M002 and M001 closed: the default-off + loopback adapter, the frozen `NodeTelemetry` contract, the narrow `telemetry` read grant, and the + fixed-target client method; + - `d4db4e72` — merged Foundation M004 + Operations M004a line: Windows Job Object process-tree execution is native-qualified, helper fixture isolation is closed, and current CI is green; - `d992ca5` — architecture deep dives: module overview plus systematic per-component documents, including the cross-cutting divergences table; @@ -72,16 +84,17 @@ The repository is no longer planning-only. | Workstream | Status | Current work | Authority | |---|---|---|---| +| Optional Gregg host telemetry | **closed; M001 and M002 both closed** | M001 closed the default-off loopback Gregg adapter, normalized cache and single polling owner (`plans/closure/optional-gregg-host-telemetry/001-status.md`, implementation `ac55985`); M002 closed the authorized node telemetry API/client behind a narrow `telemetry` grant (`plans/closure/optional-gregg-host-telemetry/002-status.md`, implementation `5ccb1e6`). The frozen contract is `eggwork_core::NodeTelemetry` schema version 1. No Gregg changes, no Eggwork scheduling, no capability feature added. The CodeGG worker-telemetry consumer is unblocked. | `plans/subsystems/optional-gregg-host-telemetry-roadmap.md`, `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` | | Foundation / execution core | M001-M003 closed; M004 conditionally closed; no ready implementation work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004 | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md` | | Control-plane protocol | closed | M001-M003 complete | `plans/subsystems/control-plane-protocol-roadmap.md` | | Workspace / artifacts | closed | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`) | `plans/subsystems/workspace-artifact-transport-roadmap.md` | | Security / isolation / resources | closed | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md` | -| Operations / distribution | M004 conditionally closed; M004a closed; M007 ready | Foundation M004's Windows runner is implemented/native-qualified; M004 still needs immutable installed-release evidence and Windows SCM service qualification. M004a closed the fixture-ownership defect. M007 is the only substantive Phase-6 implementation capability still ready. | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md` | +| Operations / distribution | M004 conditionally closed; M004a and M004b closed; M007 ready | Foundation M004's Windows runner is implemented/native-qualified; M004 still needs immutable installed-release evidence and Windows SCM service qualification. M004a closed the fixture-ownership defect; M004b closed the residual `ETXTBSY` refusal it left open, by staging the helper as a link that is never written — no copy path, no barrier, and the mechanism confirmed against the kernel's own write-access accounting. M007 is the only substantive Phase-6 implementation capability still ready. | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md`, `plans/closure/operations-distribution/004b-status.md` | | CodeGG integration | Eggwork reference closed; downstream M001+C001+M002+M002a+M003 closed | CodeGG required-Landlock live qualification closed at `f5f8d96d`; downstream M003 closed at CodeGG `d51afe46` (implementation `1ce377ce`, hosted `36745285774`) against this repository's Workspace M004 contract; only downstream M004 remains, deferred. | `plans/subsystems/codegg-integration-roadmap.md` | ## Dependency-ready implementation plans -M007 is the current ready Eggwork implementation handoff. Closed downstream CodeGG rows are retained only for dependency history. +M007 is the only dependency-ready Eggwork implementation handoff. The optional Gregg telemetry line is closed and remains dependency history. Closed downstream CodeGG rows remain dependency history. | Workstream | Milestone | Status | Implementation plan | Handoff note | |---|---|---|---|---| @@ -109,6 +122,8 @@ M007 is the current ready Eggwork implementation handoff. Closed downstream Code | Security | M003 resource enforcement | qualified/closed | `plans/closure/security-isolation-resource/003-status.md` | | Security | M004 adversarial + cross-platform closure | closed | `plans/closure/security-isolation-resource/004-status.md` (implementation `283f3ea`, incl. null-device write hardening fix); platform claims limited to hosted Linux with macOS/Windows fail-closed by construction | | Security corrective | C001 remote enforcement admission + capability truthfulness | closed | `plans/closure/security-isolation-resource-remote-admission-corrective/001-status.md` | +| Optional Gregg telemetry | M001 default-off loopback adapter/cache | closed | `plans/closure/optional-gregg-host-telemetry/001-status.md` (implementation `ac55985`) | +| Optional Gregg telemetry | M002 authenticated node telemetry API/client | closed | `plans/closure/optional-gregg-host-telemetry/002-status.md` (implementation `5ccb1e6`); frozen contract `eggwork_core::NodeTelemetry` schema version 1, narrow `telemetry` grant, `NodeClient::telemetry`/`telemetry_for` | | Operations | M001 node operations | closed | `plans/closure/operations-distribution/001-status.md` | | Operations | M002 Eggup deployment/service integration | closed (resumed) | `plans/closure/operations-distribution/002-resumed-status.md` (implementation `d5722d9`, published `eggup-core`/`eggup-service` 0.1.1); historical pre-M007 blocker preserved immutably at `plans/closure/operations-distribution/002-status.md` | | Operations | M003 Eggpack producer packaging integration | closed | `plans/closure/operations-distribution/003-status.md` (implementation `012383b` plus hosted-run portability correctives `4b95443`/`8827ed4`; `release/eggpack/` producer configuration, generated `.github/workflows/release.yml`, CI drift guard, static release/deployment parity suite). Hosted evidence: run `36787942079`, all 20 jobs green across the five required targets; draft `eggwork v0.1.0` (release id `400502116`, 17 assets) staged, nothing published, tag unmoved by the workflow. | @@ -120,8 +135,10 @@ M007 is the current ready Eggwork implementation handoff. Closed downstream Code | Work | Status | Blocker / rationale | |---|---|---| +| Optional Gregg host telemetry M002 authenticated node API/client | **closed** | `plans/closure/optional-gregg-host-telemetry/002-status.md` (implementation `5ccb1e6`). The mTLS-authorized read-only projection is implemented, the contract is frozen, and the default-off no-Gregg execution is proven by an installed-release receipt. | | Foundation M004 Windows finite-process backend | **conditionally closed** | Implemented at `f41a8ae`; tree lifecycle qualified on hosted `windows-latest` (`plans/closure/foundation-execution-core/004-status.md`). Remaining evidence is the installed-release receipt, which needs a release containing M004 — a release-lineage action reserved for the maintainer. | -| Operations M004a qualification helper fixture isolation | **closed** | `plans/closure/operations-distribution/004a-status.md`. The fixture-isolation invariant is implemented and proven; the recorded `ETXTBSY` finding is re-dispositioned there as a host-level kernel window with measurements, not as a fixture defect. | +| Operations M004a qualification helper fixture isolation | **closed** | `plans/closure/operations-distribution/004a-status.md`. The fixture-isolation invariant is implemented and proven; the recorded `ETXTBSY` finding is re-dispositioned there as a host-level kernel window with measurements, not as a fixture defect. That residual was subsequently eliminated by M004b — see the addendum appended to the M004a record. | +| Operations M004b staged helper write-access corrective | **closed** | `plans/closure/operations-distribution/004b-status.md`. The residual `ETXTBSY` refusal M004a characterised is eliminated by construction: the staged helper is linked rather than copied, so the file the fixture executes is never written, and no copy path remains to fail. The mechanism is the inode's write access — `execve()` refuses an inode that is open for writing — read from the kernel rather than inferred, and the copy-and-commit barrier the first attempt proposed was itself refused 3 times in 32 stagings on CI. Two regression tests: one asserts the staged helper *is* the build output's inode, the other the one-time trust-mode normalisation. | | Operations M004 operational/release qualification | **conditionally closed** | `plans/closure/operations-distribution/004-status.md`. Foundation M004 has now implemented/native-qualified Windows child execution, but immutable installed-release evidence still needs a new candidate containing it. Windows SCM service hosting remains the substantive implementation gap under M007; public publication/bootstrap remains a maintainer action. | | Operations M005 reverse-connect relay | deferred (not unblocked) | M004 neither implements nor claims a remote connect/accept path, so it does not supply the interface M005 relies on. No immediate product need; stable identity/lease semantics already exist. | | Operations M006 PTY extension | deferred (not unblocked) | PTY capability streams are out of M004 scope. Requires a separate interactive ownership/attach design. | @@ -159,8 +176,12 @@ Operations M003 [CLOSED] ---------------------+--> Operations M004 [CONDITIONALL | Foundation M004 Windows Job Object runner [CONDITIONALLY CLOSED] <-+--> Windows child execution (release receipt outstanding) Operations M004a fixture isolation [CLOSED] <----------------------+--> deterministic qualification invariant +Operations M004b write-access staging [CLOSED] <--------------------+--> executable staged helper Operations M007 Windows service host [READY] <--------------------+--> Windows service management Operations release publication [HUMAN ACTION: §14] <----+--> public bootstrap evidence + +Optional Gregg M001 loopback adapter/cache [CLOSED] --> Optional Gregg M002 authenticated API/client [CLOSED] + --> CodeGG worker telemetry consumer [UNBLOCKED; separately registered] ``` Operations M002 is not a dependency of CodeGG M001. The canonical long-term roadmap already defines CodeGG Phase 7 as depending on Eggwork Phases 0-5, not completion of Phase 6 packaging. @@ -180,7 +201,7 @@ These are reviewed research baselines, not permanent dependency pins. | Eggup | published `v0.1.1` -> `881c95ff069d3d465a282cb6a495ba6fcb70cb6f`; current main reviewed `0f791324be406b9a07dd35c1c1121279bc38dcdb` | Eggwork remains pinned to registry `eggup-core`/`eggup-service` 0.1.1. That published service crate includes systemd/launchd/Windows SCM plus `commit_with_lifecycle`, whose `RecoveryRequired` contract suppresses automatic restart; newer main service work is not required for M002a/M004. | | Eggpack | current reviewed main `56ed7e747fd39e4d6a32a9f1fe3e09dd44355069`; Eggwork remains pinned to durable `32a0903936fcc283863e0bfb86151b13b4d75ce9` | producer authority; the pinned revision contains qualified M003e/f/g behavior and M003h reconciliation, and `eggpack ci check` is zero-drift. Windows byte determinism is product-owned and does not require an Eggpack change. Runtime Eggup-manifest consumer adoption remains separate. | | eggsact | `f1352101dab748066c788e65e21e1bf303cfe995` | prior-art evidence only: its product-owned MSVC `/BREPRO` + `/DEBUG:NONE` correction demonstrates the mechanism behind the same Windows mismatch; Eggwork must implement and qualify its own policy and does not depend on eggsact closure | -| Gregg | `5b2c7e8c67616f872070e2acdcce90790f750fbf` | telemetry/protocol patterns only; not an execution control plane | +| Gregg | `5b2c7e8c67616f872070e2acdcce90790f750fbf`; `gregg-protocol 1.0.15` published, reviewed 2026-10-19 | telemetry/protocol patterns only; not an execution control plane. M001 consumed the published `gregg-protocol` v2 types and its own `validate_payload_v2`; the published `v2.rs` is byte-identical to the reviewed working tree. No Gregg change was made. | Implementation agents MUST re-check current APIs at execution time. diff --git a/plans/subsystems/operations-distribution-roadmap.md b/plans/subsystems/operations-distribution-roadmap.md index 712c71b..0f9b4ce 100644 --- a/plans/subsystems/operations-distribution-roadmap.md +++ b/plans/subsystems/operations-distribution-roadmap.md @@ -1,6 +1,6 @@ # Operations and Distribution Roadmap -Status: active roadmap; M001-M003, M002a and M004a closed, M004 conditionally closed; M007 ready +Status: active roadmap; M001-M003, M002a, M004a and M004b closed, M004 conditionally closed; M007 ready Canonical authority: @@ -245,6 +245,76 @@ Closure summary: load-dependent kernel window around executing a just-written executable, reproducible outside Eggwork's spawn path. The finding is re-dispositioned there rather than closed by assertion. + **Superseded by M004b:** that characterisation was accurate about what was observed + and wrong about what it implied. The condition is per-inode and persistent, not a + microsecond-wide timing window, and it is eliminated by never writing the file that + is executed — the staged helper is linked, not copied. See + `plans/closure/operations-distribution/004b-status.md`. + +### M004b — Staged helper write-access corrective + +Class: corrective / test-infrastructure invariant + +Status: **closed** — `plans/closure/operations-distribution/004b-status.md` + +Implementation plan: + +- `plans/implementation/operations-distribution/004b-staged-helper-publication-durability-corrective.md` + +Objective: + +Eliminate the intermittent `ETXTBSY` refusal that M004a characterised but left open, +so that a Linux suite which stages a helper and immediately executes it cannot go red +at random. M004a is closed and preserved; this is the corrective that closes the +residual it recorded. + +Trigger: + +CI run `39306109740` failed the Landlock suite on the optional-Gregg telemetry +branch with `ExecutableFileBusy` at +`crates/eggwork-sandbox-helper/tests/landlock_runner.rs:471`. A characterisation that +leaves the suite able to go red is not a disposition. + +Closure summary: + +- The staged helper is no longer written. The shared staging path + (`crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs`) links the + Cargo-built helper into the fixture's private `0700` directory instead of + copying it, so the file the fixture executes is never opened for writing and + the kernel has no reason to refuse it. A file that is never written is + executable every time: 0 refusals in 1 920 attempts, against 35.78% for the + M004a copy-and-rename sequence, and 0 of 32 on CI. +- **There is no copy path left, and that is the point.** The milestone was first + closed with a copy-and-commit fallback; CI then refused that copy 3 times in + 32 stagings on the runner (`39316541191`), and the copy path was removed. A + copy is a file that was written, and the kernel refuses to execute an inode + that is open for writing — so a copy cannot be made safe by a barrier. +- The mechanism is read from the kernel rather than inferred: `execve()` calls + `exe_file_deny_write_access()`, which is `deny_write_access()`, and that + returns `-ETXTBSY` exactly when the inode's `i_writecount` is positive — + that is, when the inode is open for writing. The access is taken by every + write-open and released with the file's teardown, which is deferred. That is + why `fsync`, `O_DSYNC`, a sleep and a retry change nothing. +- A link carries the source's mode, so the build output's mode is normalised to + a trusted one once, before the first fixture exists. The change is + one-directional — it can only remove write permission for others — and the + build output's bytes are never touched. +- The refusal is per-inode and persistent, not a timing window: 100 immediate + retries of the same path all failed, so a retry or a sleep would not have + cleared it. +- `set_mode` and `replace_with_junk` publish a replacement instead of mutating + the inode, so no fixture mutates an inode it shares with another fixture or + with the Cargo-built helper. That is a stronger form of the M004a isolation + invariant than the one M004a recorded, and it is what supersedes M004a §10's + rejection of hard links. +- Two regression tests: one proves 32 parallel stagings are never refused *and* + that the staged helper is the build output's own inode, so a regression to + copying fails the test without needing a race to reproduce; the other covers + the trust-mode normalisation. +- No retry, no sleep, no durability barrier, no `O_TMPFILE`+`linkat`, no + trust-rule change, no production change. +- The M004a closure record is preserved as written; two additive addends mark + the residual as eliminated and point at this record. ### M007 — Windows service host diff --git a/plans/subsystems/optional-gregg-host-telemetry-roadmap.md b/plans/subsystems/optional-gregg-host-telemetry-roadmap.md new file mode 100644 index 0000000..48f766d --- /dev/null +++ b/plans/subsystems/optional-gregg-host-telemetry-roadmap.md @@ -0,0 +1,70 @@ +# Optional Gregg Host Telemetry — Subsystem Roadmap + +Status: closed — M001 and M002 both closed; the CodeGG worker-telemetry consumer is unblocked +Primary class: infrastructure / observability +Decision: `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` +Governing references: `plans/000-long-term-specification.md`, `plans/001-terminology-and-domain-model.md`, `plans/003-planning-process.md`, ADR-0001/0002/0005. +Downstream: `dbowm91/codegg: plans/subsystems/eggwork-worker-telemetry-and-targeting-roadmap.md`. + +## Purpose and ownership + +Reuse an already installed local greggd for **host-wide, advisory resource measurements**. Eggwork-server owns a default-off adapter/cache and a bounded mTLS-authenticated node telemetry response. Gregg remains unmodified and independently operated. Eggwork-runner alone owns process execution and resource enforcement. CodeGG or another consumer owns scheduling and placement. + +## Current baseline (2026-10-19) + +- `greggd` exposes `GET /v2/status` with timestamp, CPU, memory, optional load/swap/drive/disk I/O/network and capability flags (see `eggstack/gregg: docs/api.md` and `architecture/protocol.md`). Its listener is unauthenticated, configurable, and may otherwise bind to all interfaces: when deployed for Eggwork use, operator must bind it to loopback. +- Eggwork `NodeStatus` exposes node_id, draining, active_executions and `NodeCapabilities` (not host usage), `eggwork-core::ExecutionResult` exposes categorical resource setup outcomes (not quantitative per-attempt CPU/RSS). +- `eggwork-server` has mTLS principal resolution, operation authorization and local protective admission; `eggwork-client` is fixed-target and uses Eggfetch. +- M001 is closed: `eggwork-server` has a default-off loopback Gregg adapter, a normalized in-memory cache, and a single polling owner (`plans/closure/optional-gregg-host-telemetry/001-status.md`, implementation `ac55985`). The normalized observation is `eggwork_core::HostTelemetry`. +- M002 is closed: the frozen wire contract is `eggwork_core::NodeTelemetry` (schema version 1), served at `GET /v1/node/telemetry` behind a narrow `telemetry` grant, with `NodeClient::telemetry` / `telemetry_for` on the client (`plans/closure/optional-gregg-host-telemetry/002-status.md`, implementation `5ccb1e6`). `NodeStatus` and `NodeCapabilities` are unchanged, and no capability feature was added. +- No new scheduler, node discovery, global worker selection or control authority is justified. + +## Invariants and non-goals + +Keep the existing Eggwork transport/authorization, controller identity, lease fencing, resource guarantees, node-local admission, executable ownership and drain semantics. Gregg must require no code changes and must not become a subprocess supervisor. No live Gregg network API exposure to remote controllers; no unauthenticated Eggwork status extension. No fabricated zero/idle metrics, per-execution attribution, or automatic worker placement. + +## Dependency graph + +```text +greggd existing v2 API (external, no changes) + | + v + Eggwork M001 local read-only adapter/cache [CLOSED] + | + v + Eggwork M002 authenticated telemetry endpoint/client [CLOSED] + | + v + CodeGG worker telemetry consumer [interface-dependent; separately registered] +``` + +## Milestones + +**M001 — Optional loopback Gregg adapter and normalized cache (closed).** +Implementation: `plans/implementation/optional-gregg-host-telemetry/001-loopback-gregg-adapter.md`. +Closure: `plans/closure/optional-gregg-host-telemetry/001-status.md` (implementation `ac55985`). +Exit: zero-default-overhead; validated and bounded native Gregg v2 parsing (prefer existing `gregg-protocol` only if dependency impact is reasonable); typified snapshot with sampling/source/staleness/capability facts; no subprocesses; loopback-only; explicit unknown, warming, stale and invalid conditions. Production node execution remains unaffected. **Met.** `gregg-protocol` 1.0.15 was used: three added packages, no new dependency family, and the provider's own validation rules rather than a copy of them. The frozen normalized contract is `eggwork_core::HostTelemetry` with `TelemetryProviderState` and `TelemetryErrorCategory`. + +**M002 — Authorized Eggwork projection and fixed-target client method (closed).** +Implementation: `plans/implementation/optional-gregg-host-telemetry/002-authenticated-node-telemetry.md`. +Closure: `plans/closure/optional-gregg-host-telemetry/002-status.md` (implementation `5ccb1e6`). +Exit: an authorized controller reads a bounded sanitized snapshot through mTLS; an unauthorized principal is refused, and an older node is reported unsupported; no Gregg endpoint reachable or required remotely. Node status, capabilities, execution semantics and error authority unchanged. **Met.** The narrow `telemetry` grant is separate from `status`, so no existing grant widened; the route reads the M001 cache only, so a remote read never becomes a provider request; and the client refuses a response it cannot trust. + +## Cross-cutting concerns + +- Security: trust boundary terminates at Eggwork mTLS; Gregg loopback data is never enforcement evidence; capability-based authorization precedes any sensitive response. +- Compatibility: default off, additive opt-in config and response DTO; rollback by disabling provider. No database migration required for cached observations. +- Runtime: one loop per node at most, monotonic refresh/freshness deadlines, bounded CPU/network work, no spin if Gregg is down; avoid client-query-amplified Gregg requests. +- Platform: Gregg v2 optional OS fields accepted, no invented metrics. Windows/macOS/linux qualification must match actual hosted evidence. +- Observability: source, observed age, capability/field missingness and last error category; exclude raw host strings and command history. +- Risks: local spoofing, clock skew, unexpectedly huge JSON, SSRF/proxy/redirect, polling contention and exposure of operational metadata. + +## Deferred + +Shared Gregg collector crate, UDS authorization, time-series persistence, per-execution cgroup accounting, automatic selection and resource-aware reservations belong to independent decisions/workstreams. Revisit collector extraction only with measured footprint evidence. + +## Completion + +Both milestones closed with code/test receipts and verified default-off no-Gregg execution; the CodeGG consumer can depend on a stable, versioned authenticated response. No Gregg commits are created. + +**Met.** M001 closed at `ac55985` (`plans/closure/optional-gregg-host-telemetry/001-status.md`) and M002 closed at `5ccb1e6` (`plans/closure/optional-gregg-host-telemetry/002-status.md`). The frozen contract is `eggwork_core::NodeTelemetry`, schema version 1, documented in `architecture/protocol.md`. The default-off no-Gregg execution is proven twice: by the installed-release qualification receipt and by an installed-binary probe of the route itself. The CodeGG worker-telemetry consumer is unblocked and may now be registered against this contract.