From d50914e4c75a26681c4bf8d4c479a815c8b08bfd Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 01:43:34 +0000 Subject: [PATCH] control edge follows flysim's stops and starts; large request bodies match direct N1: flysim.service Wants= flycontrol-edge.service and the edge gets an ExecCondition on FLY_CONTROL_VIA (no [Install]), the pattern flyedge uses, so fly-loop-reset's stop and start brings :7401 back in bus mode and the edge stays skipped in direct mode. lint.sh checks the wiring and runs the condition; runbook and flybus.md updated (no enable step). N2: a request body over 48 KiB of JSON travels as a sealed request artifact, so the edge answers what direct answers instead of 503 INVALID_ENVELOPE. parity test covers 49 KB to 300 KB bodies on /chat, /stimulate and /reward plus an unparseable large body. --- docs/design/flybus.md | 10 ++-- infra/docs/runbook.md | 21 +++++---- infra/tests/lint.sh | 33 ++++++++++++- infra/units/flycontrol-edge.service | 44 ++++++++++-------- infra/units/flysim.service | 5 ++ .../flysim/crates/fly-control-edge/src/lib.rs | 37 ++++++++++++++- .../crates/fly-control-edge/tests/parity.rs | 46 +++++++++++++++++++ .../flysim/crates/flysim/src/controlbus.rs | 44 ++++++++++++++++-- 8 files changed, 203 insertions(+), 37 deletions(-) diff --git a/docs/design/flybus.md b/docs/design/flybus.md index 8233e73..00807e4 100644 --- a/docs/design/flybus.md +++ b/docs/design/flybus.md @@ -247,7 +247,9 @@ agent (fly) of it. Each method's payload and outcome: code is the outcome's vocabulary, not transport. A bus caller reads `429 {retryAfterMs}` as an HTTP caller does, so the edge needs no table of its own. - **Requests** carry the body as the caller sent it (`request` is absent when it was empty or - not JSON), so validation stays in `control::handle`. An unknown payload field is a 400. A + not JSON), so validation stays in `control::handle`. A `request` over 48 KiB of JSON travels as + a sealed `request` artifact with `requestArtifact: true` in the payload, so a large body gets + the answer direct mode gives it, not an envelope error (`tests/parity.rs`). An unknown payload field is a 400. A method the service does not have is a 404. Neither reaches the loop. - **Concurrency.** Each service has 16 queued and 16 in flight (`controlbus::SERVICE_CONFIG`). The router dispatches FIFO per service. The host answers each request in a task of its own, so @@ -375,8 +377,10 @@ above are already addressed per agent, so the amendments are to the HTTP shapes, - `bus_dir` (`FLY_BUS_DIR`, `/run/fly/bus`) as for the feed. Sockets are `control-edge.sock` and `control/{stage,bridge,watchdog,operator}.sock`. Stale sockets are removed at start. With control on the bus, the router's `max_clients` and `max_services` are the feed's plus 8. -- `flycontrol-edge.service` is off by default and in no target. It is `After=` and - `Requires=flysim.service`, gets the page's CPUs from the cpuset plan, and exports its own +- `flycontrol-edge.service` has no `[Install]` section: `flysim.service` `Wants=` it, and its + `ExecCondition=` on `FLY_CONTROL_VIA` skips it in direct mode (EDGE-02's pattern for + `flyedge`), so every start of flysim, `fly-loop-reset`'s stop and start included, brings + `:7401` back. It is `After=` and `Requires=flysim.service`, gets the page's CPUs from the cpuset plan, and exports its own counters on loopback `:9103` (`fly_control_edge_bus_connected`, `_calls_total`, `_call_failures_total`, `_cancelled_total`, `_bus_lost_total`, `_bind_failures_total`). - The edge binds `:7401` only once the services answer. When the bus goes away it unbinds and diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index b8e0072..3103baa 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -821,11 +821,11 @@ box keeps serving `:7401` directly until step 2. pct exec $CTID -- grep -E '^FLY_(CONTROL|FEED)_VIA=' /etc/fly/fly.env # FLY_CONTROL_VIA=bus pct exec $CTID -- curl -s 127.0.0.1:7401/status | jq '.frame, .status, .checkpoint' pct exec $CTID -- curl -s -X POST 127.0.0.1:7401/checkpoint # a fresh generation to restart from -# 2. The switch: flysim stops binding :7401 and registers the services; the edge binds :7401 once -# they answer. Between the two, :7401 refuses connections, exactly as during any flysim restart. -pct exec $CTID -- systemctl enable flycontrol-edge.service +# 2. The switch: flysim stops binding :7401 and registers the services; the edge (Wants= of +# flysim.service, started with it because fly.env says bus) binds :7401 once they answer. +# Between the two, :7401 refuses connections, exactly as during any flysim restart. +# There is nothing to enable: the unit has no [Install] section. pct exec $CTID -- systemctl restart flysim.service -pct exec $CTID -- systemctl start flycontrol-edge.service # 3. Verify. pct exec $CTID -- ss -ltnp | grep ':7401' # users:(("fly-control-edg"... pct exec $CTID -- curl -s 127.0.0.1:7401/healthz # {"status":"ok"} @@ -843,16 +843,18 @@ pct exec $CTID -- curl -s 127.0.0.1:7410/health | jq . # the bridg - **Watchdog.** With `FLY_CONTROL_VIA=bus`, check 1 reads flysim's own `/healthz` on `:9101`, so a dead edge never restarts the fly. Check 1b restarts `flycontrol-edge` alone when `:7401` fails while flysim is healthy (the sudoers file grants exactly that restart). -- **Restarts.** `systemctl restart flysim.service` (the unstick rule, `fly-runtime`, the ladder) - restarts the edge with it (`Requires=`). A crash-restart of flysim needs nothing: the edge +- **Restarts.** `flysim.service` has `Wants=flycontrol-edge.service` and the edge has `Requires=` + on flysim plus an `ExecCondition=` on `FLY_CONTROL_VIA`, so the edge follows flysim in bus mode + and stays off ("skipped", not failed) in direct mode. A `restart`, and a `stop` then `start` + (`fly-loop-reset`, `fly-reset-to-milestone`, the milestone-reset rung of the unstick rule) all + bring `:7401` back with flysim; nothing needs a separate `start` of the edge. A crash-restart of flysim needs nothing: the edge unbinds `:7401`, reconnects every 500 ms and binds again once the new services answer. **Rollback** (any time, no release change): ``` pct exec $CTID -- sed -i 's/^FLY_CONTROL_VIA=.*/FLY_CONTROL_VIA=direct/' /etc/fly/fly.env -pct exec $CTID -- systemctl disable --now flycontrol-edge.service -pct exec $CTID -- systemctl restart flysim.service # binds :7401 itself again +pct exec $CTID -- systemctl restart flysim.service # binds :7401 itself; the edge is skipped pct exec $CTID -- curl -s 127.0.0.1:7401/healthz # then set FLY_CONTROL_VIA=direct in the env file too, or the next 05-deploy.sh writes bus back. ``` @@ -865,6 +867,9 @@ pct exec $CTID -- curl -s 127.0.0.1:7401/healthz - **If the edge cannot bind** (`fly_control_edge_bind_failures_total` rising, "the control port cannot be bound" in its journal), flysim is still in direct mode. `fly.env` says bus but flysim was not restarted after the deploy. Restart flysim (step 2). +- **Upgrading a container that had the edge enabled** (before this wiring): an + old `fly.target.wants/flycontrol-edge.service` symlink is harmless (the condition decides), but + run `systemctl disable flycontrol-edge.service` once so `systemctl is-enabled` says what is true. ## CPU partition (cpuset) diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index 3ddcb7d..fb54a08 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -517,7 +517,7 @@ fi # writes the default. The watchdog's use of FLY_CONTROL_VIA is driven for real # further down, next to check 2's. # --------------------------------------------------------------------------- -echo "--- flycontrol-edge.service: off by default, after and bound to flysim ---" +echo "--- flycontrol-edge.service: follows flysim in bus mode, skipped in direct mode ---" CEDGE_UNIT="$INFRA_DIR/units/flycontrol-edge.service" if [ ! -f "$CEDGE_UNIT" ]; then fail "units/flycontrol-edge.service is missing" @@ -537,12 +537,41 @@ else grep -qE '^Environment=FLY_CONTROL_BIND=127\.0\.0\.1:7401$' "$CEDGE_UNIT" \ && pass "flycontrol-edge.service binds the contract's loopback :7401" \ || fail "flycontrol-edge.service FLY_CONTROL_BIND must be 127.0.0.1:7401 (docs/control-api.md)" + # N1 (review of CTRL-01): Requires= alone stops the edge with flysim but never starts it + # again, so fly-loop-reset's stop and start left :7401 dead. flysim Wants= it, and the + # unit's own ExecCondition= decides by FLY_CONTROL_VIA (EDGE-02's pattern for flyedge). + grep -qE '^Wants=.*\bflycontrol-edge\.service\b' "$INFRA_DIR/units/flysim.service" \ + && pass "flysim.service Wants=flycontrol-edge.service (every flysim start brings the edge up in bus mode)" \ + || fail "flysim.service must Want flycontrol-edge.service: a stop and start of flysim (fly-loop-reset) would leave :7401 dead" + if grep -qE '^\[Install\]' "$CEDGE_UNIT"; then + fail "flycontrol-edge.service has an [Install] section; flysim's Wants= is what starts it" + else + pass "flycontrol-edge.service has no [Install] section" + fi + cond="$(sed -nE "s/^ExecCondition=\/bin\/sh -c '(.*)'\$/\1/p" "$CEDGE_UNIT")" + if [ -z "$cond" ]; then + fail "flycontrol-edge.service needs an ExecCondition= on FLY_CONTROL_VIA" + else + # Run the condition as systemd would ($$ is systemd's escape for a literal $). + cond="${cond//\$\$/\$}" + cond_bad="" + for v in "" direct Direct junk; do + FLY_CONTROL_VIA="$v" sh -c "$cond" && cond_bad="$cond_bad [$v->runs]" + done + env -u FLY_CONTROL_VIA sh -c "$cond" && cond_bad="$cond_bad [unset->runs]" + for v in bus Bus BUS; do + FLY_CONTROL_VIA="$v" sh -c "$cond" || cond_bad="$cond_bad [$v->skipped]" + done + [ -z "$cond_bad" ] \ + && pass "flycontrol-edge.service ExecCondition= runs only for FLY_CONTROL_VIA=bus (any case); direct, unset and junk skip" \ + || fail "flycontrol-edge.service ExecCondition= wrong for:$cond_bad" + fi grep -qE '^Environment=FLY_CONTROL_EDGE_METRICS_ADDR=127\.0\.0\.1:' "$CEDGE_UNIT" \ && pass "flycontrol-edge.service keeps its metrics on loopback" \ || fail "flycontrol-edge.service FLY_CONTROL_EDGE_METRICS_ADDR must be a 127.0.0.1 address" fi if target_pulls "$INFRA_DIR/units/fly.target" | grep -qx 'flycontrol-edge.service'; then - fail "fly.target pulls flycontrol-edge.service in; it must stay off until the operator enables it" + fail "fly.target pulls flycontrol-edge.service in; flysim.service Wants= it, the condition decides" else pass "fly.target does not pull flycontrol-edge.service in" fi diff --git a/infra/units/flycontrol-edge.service b/infra/units/flycontrol-edge.service index f0b1dd3..718a865 100644 --- a/infra/units/flycontrol-edge.service +++ b/infra/units/flycontrol-edge.service @@ -2,26 +2,31 @@ # # The control API (http://127.0.0.1:7401, docs/control-api.md) served from # flysim's control services on the bus (docs/design/flybus.md, "Control over -# the bus"; services/flysim/crates/fly-control-edge). DISABLED BY DEFAULT: it -# is in no target's Wants=/Requires= and 07-enable.sh does not enable it. -# With FLY_CONTROL_VIA=direct (the default, written into /etc/fly/fly.env by -# 05-deploy.sh) flysim binds 127.0.0.1:7401 itself and this unit has nothing -# to do. The switch and the way back are infra/docs/runbook.md, "Control over -# the bus"; in short: +# the bus"; services/flysim/crates/fly-control-edge). Whether it runs is decided +# by one line, FLY_CONTROL_VIA in /etc/fly/fly.env (05-deploy.sh writes it from +# the env file's FLY_CONTROL_VIA, default `direct`): # -# on: FLY_CONTROL_VIA=bus in the env file, 05-deploy.sh, then -# systemctl enable flycontrol-edge.service; systemctl restart flysim.service -# (flysim stops binding :7401; the edge binds it once the services answer) -# back: FLY_CONTROL_VIA=direct, 05-deploy.sh, systemctl disable --now -# flycontrol-edge.service, systemctl restart flysim.service +# direct flysim binds 127.0.0.1:7401 itself. ExecCondition= below fails, so +# this unit starts as "skipped" (inactive, no failure, no restart). +# bus flysim registers the control services on its router and leaves +# :7401 to this unit. +# +# flysim.service has Wants= on this unit, so EVERY start of flysim (the unstick +# rule's restart, fly-loop-reset's stop and start, fly-reset-to-milestone, a +# crash-restart, a reboot through fly.target) starts the edge in bus mode and +# skips it in direct mode; fly.env alone decides, and flysim and the edge can +# never disagree. This unit is in no target and has no [Install] section: +# `systemctl enable` has nothing to do. The switch and the way back are +# infra/docs/runbook.md, "Control over the bus": edit FLY_CONTROL_VIA, run +# 05-deploy.sh, restart flysim. # # Ordering: flysim owns the router (/run/fly/bus, shared with the feed when # that rides the bus too), so it starts first and the edge follows it. -# Requires= makes an explicit stop or restart of flysim (the unstick rule's -# restart and fly-runtime's switch included) stop or restart the edge with -# it. A crash-restart of flysim is covered by the -# edge itself: it unbinds :7401 and reconnects every 500 ms, so to every -# client it looks exactly like flysim restarting. The edge holds no state. +# Requires= makes an explicit stop or restart of flysim stop or restart the +# edge with it (and Wants= on the other side brings it back after a plain +# start). A crash-restart of flysim is covered by the edge itself: it unbinds +# :7401 and reconnects every 500 ms, so to every client it looks exactly like +# flysim restarting. The edge holds no state. [Unit] Description=flycontrol-edge: the control API served from flysim's control services on the bus After=flysim.service @@ -40,11 +45,12 @@ Environment=FLY_CONTROL_BIND=127.0.0.1:7401 Environment=FLY_BUS_DIR=/run/fly/bus # Its own /metrics and /healthz. Loopback only. Environment=FLY_CONTROL_EDGE_METRICS_ADDR=127.0.0.1:9103 +# Only in bus mode. EnvironmentFile= is the same fly.env flysim reads, so this is the value +# flysim started with (flysim reads it case-insensitively, so does this). Exit 1 means +# "skip": the unit goes inactive without failing and without being restarted. +ExecCondition=/bin/sh -c 'case "$$FLY_CONTROL_VIA" in [Bb][Uu][Ss]) ;; *) exit 1;; esac' ExecStart=/opt/fly/current/fly-control-edge Restart=always RestartSec=2 # Small JSON requests; an /events page is the largest thing it ever holds. MemoryMax=128M - -[Install] -WantedBy=fly.target diff --git a/infra/units/flysim.service b/infra/units/flysim.service index dd0f6c0..b538312 100644 --- a/infra/units/flysim.service +++ b/infra/units/flysim.service @@ -14,6 +14,11 @@ [Unit] Description=flysim: the fly brain, emulator, and control/feed APIs After=network.target +# Every start of flysim starts the control edge when fly.env says FLY_CONTROL_VIA=bus, and skips +# it in direct mode (units/flycontrol-edge.service decides): a stop and start of flysim +# (fly-loop-reset, fly-reset-to-milestone) would otherwise leave :7401 dead, because the edge's +# Requires= stops it with flysim but does not bring it back. +Wants=flycontrol-edge.service StartLimitIntervalSec=300 StartLimitBurst=5 diff --git a/services/flysim/crates/fly-control-edge/src/lib.rs b/services/flysim/crates/fly-control-edge/src/lib.rs index c9f7344..ba876f7 100644 --- a/services/flysim/crates/fly-control-edge/src/lib.rs +++ b/services/flysim/crates/fly-control-edge/src/lib.rs @@ -18,6 +18,7 @@ //! Failures on the bus side map onto the 503s direct mode answers for the same failure (the //! words are `flysim::control::unavailable`), so a client cannot tell which side was in trouble. +use std::io::Write as _; use std::net::SocketAddr; use std::path::PathBuf; use std::sync::Arc; @@ -171,9 +172,26 @@ impl BusBackend { } else { Some(COMMAND_TIMEOUT + DEADLINE_MARGIN) }; - let (family, method, payload) = controlbus::encode_request(&request); + let (family, method, mut payload) = controlbus::encode_request(&request); let service = self.service(family); - let mut pending = match self.client.call(&service, None, method, payload, &[]).await { + // A body over the envelope travels as an artifact, so a large request gets the answer + // direct mode gives it. + let sealed = match controlbus::take_out_of_line_request(&mut payload) { + None => None, + Some(bytes) => match seal(&self.client, &bytes, "application/json").await { + Ok(artifact) => Some(artifact), + Err(error) => return self.failed(&error), + }, + }; + let attachments: Vec<(&str, &flybus::Artifact)> = sealed + .iter() + .map(|artifact| (controlbus::REQUEST_ARTIFACT, artifact)) + .collect(); + let mut pending = match self + .client + .call(&service, None, method, payload, &attachments) + .await + { Ok(pending) => pending, Err(error) => return self.failed(&error), }; @@ -233,6 +251,21 @@ impl ControlBackend for BusBackend { } } +async fn seal( + client: &Client, + bytes: &[u8], + content_type: &str, +) -> Result { + let mut writer = client + .artifacts() + .allocate(bytes.len() as u64, content_type) + .await?; + writer + .write_all(bytes) + .map_err(|error| BusError::new(ErrorCode::StoreFailure, error.to_string()))?; + writer.seal().await +} + /// The reply a client gets for a request the bus did not deliver, in the words direct mode uses /// for the same failure. pub fn bus_failure(error: &BusError) -> ControlReply { diff --git a/services/flysim/crates/fly-control-edge/tests/parity.rs b/services/flysim/crates/fly-control-edge/tests/parity.rs index 2a48aa8..368879c 100644 --- a/services/flysim/crates/fly-control-edge/tests/parity.rs +++ b/services/flysim/crates/fly-control-edge/tests/parity.rs @@ -296,6 +296,52 @@ async fn a_large_events_page_rides_as_an_artifact_and_still_matches() { assert_eq!(rig.bus.router.stats().artifacts, 0); } +/// A request body over flybus's 65,536-byte envelope (N2): the edge carries it as an artifact and +/// the answer is the one direct mode gives, whatever it is, for every body endpoint. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_request_body_over_the_envelope_gets_directs_answer() { + let rig = rig(|_| {}).await; + let mut cases = Vec::new(); + for size in [49_000usize, 70_000, 300_000] { + let text = "x".repeat(size); + for uri in ["/chat", "/stimulate", "/reward"] { + cases.push(json_case( + Method::POST, + uri, + json!({"by": "viewer", "source": "points", "text": text, "message": text, "reason": text}), + )); + } + } + // Over the limit and not JSON at all: direct's 400 either way. + cases.push(raw(Method::POST, "/chat", &"{".repeat(100_000))); + let mut codes = Vec::new(); + for (method, uri, content_type, body) in &cases { + let direct = exchange(rig.direct(), method, uri, *content_type, body).await; + let edge = exchange(rig.via_edge(), method, uri, *content_type, body).await; + assert_eq!( + direct, + edge, + "{method} {uri} ({} bytes): direct {} {:?} vs edge {} {:?}", + body.len(), + direct.status, + String::from_utf8_lossy(&direct.body), + edge.status, + String::from_utf8_lossy(&edge.body) + ); + assert!( + !String::from_utf8_lossy(&edge.body).contains("INVALID_ENVELOPE"), + "{uri}: {:?}", + String::from_utf8_lossy(&edge.body) + ); + codes.push(direct.status.as_u16()); + } + eprintln!("large-body statuses: {codes:?}"); + assert_eq!(rig.metrics.call_failures.load(Ordering::Relaxed), 0); + // Every request artifact was released once read. + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(rig.bus.router.stats().artifacts, 0); +} + /// The running edge over real sockets: the whole HTTP/1.1 response equals flysim's own listener's, /// `date` aside, for a request of every kind. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] diff --git a/services/flysim/crates/flysim/src/controlbus.rs b/services/flysim/crates/flysim/src/controlbus.rs index fe3df27..40a77cc 100644 --- a/services/flysim/crates/flysim/src/controlbus.rs +++ b/services/flysim/crates/flysim/src/controlbus.rs @@ -56,6 +56,10 @@ pub const PREFIX: &str = "fly.control."; pub const INLINE_MAX: usize = 48 * 1024; /// The attachment name of an out-of-line body. pub const BODY_ARTIFACT: &str = "body"; +/// The attachment name of an out-of-line request body: a `request` JSON value larger than +/// [`INLINE_MAX`] travels as this artifact, and the payload says so with `requestArtifact: true`. +/// The direct API takes bodies up to the HTTP layer's own limit, so the bus must too. +pub const REQUEST_ARTIFACT: &str = "request"; /// Per-service bounds. A full service refuses with `BACKPRESSURE` (the edge's 503 "queue is /// full") instead of queueing without limit; each family has its own, so a stuck checkpoint /// cannot hold up `/status`. @@ -443,6 +447,18 @@ pub fn encode_request(request: &ControlRequest) -> (Family, &'static str, Map) -> Option> { + let bytes = serde_json::to_vec(payload.get("request")?).ok()?; + if bytes.len() <= INLINE_MAX { + return None; + } + payload.remove("request"); + payload.insert("requestArtifact".to_owned(), Value::Bool(true)); + Some(bytes) +} + /// Why a bus request could not be read: answered as a control-API reply. #[derive(Debug, Clone, PartialEq)] pub struct Undecodable(pub ControlReply); @@ -635,10 +651,32 @@ pub async fn serve(router: &Router, state: AppState, scope: &Scope) -> Result Result, ControlReply> { + let mut payload = request.payload().clone(); + if payload.remove("requestArtifact").is_none() { + return Ok(payload); + } + let bytes = match request.artifact(REQUEST_ARTIFACT) { + Ok(artifact) => artifact.read_all().await, + Err(error) => Err(error), + } + .map_err(|error| { + ControlReply::error(400, format!("the request body could not be read: {error}")) + })?; + let value = serde_json::from_slice(&bytes) + .map_err(|error| ControlReply::error(400, format!("the request body is not JSON: {error}")))?; + payload.insert("request".to_owned(), value); + Ok(payload) +} + async fn answer(client: &Client, state: &AppState, family: Family, request: Request) { - let reply = match decode_request(family, request.method(), request.payload()) { - Ok(decoded) => crate::control::handle(state, decoded).await, - Err(Undecodable(reply)) => reply, + let reply = match request_payload(&request).await { + Err(reply) => reply, + Ok(payload) => match decode_request(family, request.method(), &payload) { + Ok(decoded) => crate::control::handle(state, decoded).await, + Err(Undecodable(reply)) => reply, + }, }; let (outcome, out_of_line) = encode_reply(&reply); let result = match out_of_line {