diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c7e845..dcf10fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,21 @@ versions (0.x) may contain breaking changes; they are always listed under a ### Added +- **Graceful shutdown, Ballista's retry limits, and what losing a worker + does** (#31). `oxide-scheduler` handled no signal: `SIGTERM` killed it + (status 143) with every query it was running. It now refuses new queries + on `SIGTERM` or `SIGINT`, saying it is shutting down, gives the running + ones up to `--drain-timeout` (20 s) to finish, and exits 0. + `oxide-worker` already stopped gracefully through Ballista (no new tasks, + its scheduler runs its tasks elsewhere, then it waits for them) but waited + for ever; `--drain-timeout` now bounds the wait, and it exits 0 either + way. A second signal stops either at once. New scheduler flags + `--task-max-failures` and `--stage-max-failures` (Ballista's retry + limits, 4 and 1) and `--worker-timeout` (seconds a silent worker still + counts, 180), and worker flag `--heartbeat-interval` (60); the defaults + are Ballista's but for `--stage-max-failures`, which is 1 so that a lost + worker fails its queries instead of being retried (#148, under Changed). + - **`operator_stats()` on `GpuFilterExec`, `GpuHashJoinExec`, `GpuAggregateExec` and `GpuVectorDistanceExec`** returns the counters that exec instance has reported to its telemetry hub (`None` before it @@ -457,6 +472,24 @@ versions (0.x) may contain breaking changes; they are always listed under a partition coalescing are therefore not available on an OxideLake cluster until the placement rule can run inside the adaptive planner. +- **A cluster no longer retries a query that loses a worker** (#148). + Ballista 55 recovers such a query by rolling back the stages that read the + lost worker's output and running them again, and in 55.0.0 that recovery + is not safe: a self-join that lost a worker mid-flight came back with 13 + or 14 of its 100 groups twice, exit 0, in 12 runs of 15 (fixed upstream by + apache/datafusion-ballista#2677, unreleased), and a worker stopped with + `SIGTERM` mid-query left it hanging (apache/datafusion-ballista#2539, + #2698). `oxide-scheduler` now fails a query that held output on a worker + it loses, whether killed, stopped or silent past `--worker-timeout`, with + an error naming the worker (one killed in the middle of a transfer shows + as a broken shuffle stream instead), and `--stage-max-failures` defaults + to 1, so + a failed fetch from a lost worker ends the query too; a query whose tasks + on that worker had not finished anything still runs them again elsewhere. + **Migration:** a query that used to survive losing a worker now fails; + run it again. To get Ballista's stage retries back, pass + `--stage-max-failures 4`, which brings the bug back with them. + ### Fixed - **Cluster mode returns the right rows for `NOT IN (subquery)`** (#91). @@ -672,6 +705,20 @@ versions (0.x) may contain breaking changes; they are always listed under a current releases no longer pull the unmaintained `pin-utils` (RUSTSEC-2026-0441). +- **A cluster process refuses to listen beyond a private network** + (#30). The scheduler's and workers' ports have no authentication or + encryption, and `oxide-scheduler --bind-host 0.0.0.0` started without a + word. Now `oxide-scheduler` and `oxide-worker` exit 1 when `--bind-host` + or `--metrics-host` is a public address or every address (`0.0.0.0`, + `::`), naming the risk and the way out: bind a loopback or private address + (10/8, 172.16/12, 192.168/16, fc00::/7), or pass `--allow-insecure-bind` + when a firewall or an authenticating proxy already decides who connects. + Either logs a warning whenever it listens beyond loopback. `oxide-worker + --bind-host` is new: the worker listened on `127.0.0.1` only, so a + scheduler on another machine could not reach it. TLS and authentication + are not built yet; README and SECURITY.md say what a production + deployment must put in front of the ports. + - **Three "unmaintained" notices are accepted, with their reasons**: `chrono` (RUSTSEC-2026-0543) and `chrono-tz` (RUSTSEC-2026-0555), which are arrow 59's date/time and timezone support under every DataFusion and diff --git a/Makefile b/Makefile index 788e131..215e2f2 100644 --- a/Makefile +++ b/Makefile @@ -120,10 +120,14 @@ test-metal: ## Metal package tests and macOS PTY tests with one dependency graph # named with the prefix for exactly this. `--skip mixed_build` likewise: those # #[ignore]d cli tests need the other-build workers that only # `make test-mixed-build` builds (it runs them in CI), and fail loudly without -# them. The conformance suite is what this target is for. +# them. `--skip a_query_that_loses_a_worker_comes_back` too: that #[ignore]d +# cli test is the reproduction of Ballista 55's lost-worker rollback (#148), +# kept to show the bug is still there, so it is expected to fail until a +# Ballista release carries the fix. The conformance suite is what this +# target is for. test-metal-device: ## reuse the Metal test graph for on-device conformance @if swift -e 'import Metal; exit(MTLCreateSystemDefaultDevice() == nil ? 1 : 0)' 2>/dev/null; then \ - OXIDE_BACKEND=metal $(CARGO) test $(METAL_TEST_ARGS) -- --ignored --skip termlens_cli --skip mixed_build; \ + OXIDE_BACKEND=metal $(CARGO) test $(METAL_TEST_ARGS) -- --ignored --skip termlens_cli --skip mixed_build --skip a_query_that_loses_a_worker_comes_back; \ else \ echo "No Metal device on this runner — on-device conformance skipped."; \ fi diff --git a/README.md b/README.md index 7ee445f..0fe3792 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,12 @@ The end-to-end test in `crates/oxidelake-runtime/tests/cli.rs` spawns exactly th A scheduler admits only workers of its own build: the same OxideLake release, built with `predict` if and only if the scheduler is. `cuda` and `metal` do not count, so a default-build scheduler with `--features cuda` workers is a supported cluster. A worker of another build is refused when it registers and exits non-zero naming both builds, and a query sent to a cluster whose workers were all refused fails at once with the same reason. The check guards against a mismatched deployment, not against an attacker: a worker declares its own build ([SECURITY.md](https://github.com/vyncint/oxidelake/blob/main/SECURITY.md)). +`SIGTERM` or `SIGINT` stops either binary gracefully, and a second signal stops it at once. A scheduler refuses new queries, saying it is shutting down, gives the running ones up to `--drain-timeout` to finish, and exits 0. A worker takes no new tasks and exits 0 once its running ones finish or `--drain-timeout` passes, and a query that held its output fails, naming it (below); keep the timeout under your supervisor's own limit (Kubernetes sends `SIGKILL` 30 s after `SIGTERM` by default). A worker that dies without a word is presumed lost once the scheduler's `--worker-timeout` passes with no heartbeat from it (the worker's `--heartbeat-interval`, which must be well under the timeout). Until then a query holding tasks on it waits, unless a shuffle fetch from it fails first: Ballista retries a fetch three times, three seconds apart, and then the query fails. The scheduler's port serves Ballista's `/healthz` (always `ok`) and `/readyz` (`ready: N executors registered`, or 503 before the first); a worker serves nothing over HTTP except `--metrics-port`. + +**Production deployments.** The cluster's ports (the scheduler's one port for gRPC, REST and probes, each worker's Flight and gRPC ports, and any `--metrics-port`) have no authentication and no encryption: whoever can connect can run queries, and a query can read any file a worker can read. Keep them on a network that only the cluster's own hosts and trusted clients can reach, such as a private subnet or a VPN, behind a firewall. `oxide-scheduler` and `oxide-worker` refuse to listen on a public address, or on every address (`0.0.0.0`, `::`), unless `--allow-insecure-bind` says that something else, such as that firewall, already decides who can connect, and they log a warning whenever they listen beyond loopback. TLS and authentication in OxideLake itself are tracked in #30. + +**A query that loses a worker fails, naming it** ([#148](https://github.com/vyncint/oxidelake/issues/148)). Ballista 55 would recover such a query by rolling back every stage that read the lost worker's output and running it again, and that recovery is not safe: the rolled-back stage keeps its partial outputs, so in our runs most such queries came back with some groups twice, with exit 0 (fixed upstream by [apache/datafusion-ballista#2677](https://github.com/apache/datafusion-ballista/pull/2677), merged after 55.0.0 and not yet released), and the tasks it cancels never return their slots, so a query can wait for capacity that does not come back (see [apache/datafusion-ballista#2539](https://github.com/apache/datafusion-ballista/issues/2539) and [#2698](https://github.com/apache/datafusion-ballista/issues/2698)). So `oxide-scheduler` fails any query that held output on a worker it loses, killed, stopped with `SIGTERM`, or silent past `--worker-timeout`, and `--stage-max-failures` defaults to 1, so a failed fetch from a lost worker ends the query too. The error names the worker, unless the worker was killed in the middle of sending shuffle data, which Ballista reports as a broken stream that fails the query just as cleanly; either way, run the query again. A query whose tasks on the lost worker had not finished anything is not failed: those tasks run again elsewhere. Raising `--stage-max-failures` brings Ballista's stage retries back, with the bug. + ### DataFrame API ```rust @@ -197,22 +203,31 @@ error, never a silent fallback. | Knob | Default | What it does | | --- | --- | --- | -| `--bind-host` | `127.0.0.1` | Address to bind. | +| `--bind-host` | `127.0.0.1` | Address to bind: loopback or private (10/8, 172.16/12, 192.168/16, fc00::/7). A public address or every address (`0.0.0.0`, `::`) is refused without `--allow-insecure-bind`, because the port is unauthenticated. | +| `--allow-insecure-bind` | off | Accepts a public or wildcard `--bind-host`/`--metrics-host`. Only when a firewall or an authenticating proxy already decides who can connect ([Production deployments](#cluster-mode)). | | `--port` | `50050` | gRPC port. | | `--cluster-backend` | `$OXIDE_CLUSTER_BACKEND`, then `cpu` | The capability the cluster declares, which is what placement rewrites against. | | `--metrics-port` / `--metrics-host` | off / `127.0.0.1` | As for the worker. A scheduler plans but does not execute, so its counters are empty; the endpoint exists so every process is scraped the same way. | +| `--task-max-failures` | `4` | Times one task may fail before its query fails; `1` means no retry. A task lost with its worker runs again elsewhere without counting. Ballista's `task_max_failures`. | +| `--stage-max-failures` | `1` | Times a stage may fail because a shuffle fetch failed, its input lost with a worker, before its query fails. The default ends the query at the first such failure, naming the worker; a worker that is stopped or goes silent fails its queries whatever this says ([#148](https://github.com/vyncint/oxidelake/issues/148), [Cluster mode](#cluster-mode)). Raising it turns on Ballista 55's re-run of the stage, which can return duplicated rows with exit 0 or never finish. Ballista's `stage_max_failures`, whose own default is 4. | +| `--worker-timeout` | `180` | Seconds without a heartbeat before a worker is presumed lost and its tasks run elsewhere. A query holding tasks on a dead worker waits this long. | +| `--drain-timeout` | `20` | On `SIGTERM`/`SIGINT`, new queries are refused and the running ones get this many seconds to finish; then the scheduler exits 0. | ### `oxide-worker` | Knob | Default | What it does | | --- | --- | --- | | `--scheduler-host` / `--scheduler-port` | `localhost` / `50050` | The scheduler to join. | +| `--bind-host` | `127.0.0.1` | Address the Flight and gRPC ports bind, under the scheduler's rule: loopback or private, anything else only with `--allow-insecure-bind`. The scheduler connects back to the address it sees the worker connect from, so bind the interface that faces it. | +| `--allow-insecure-bind` | off | As for the scheduler. | | `--port` | `50051` | Arrow Flight port for shuffle data. | | `--grpc-port` | `50052` | gRPC control port. | | `--concurrent-tasks` | available parallelism | Tasks run at once. | | `--work-dir` | a temporary directory | Where shuffle files go. | -| `--metrics-port` / `--metrics-host` | off / `127.0.0.1` | Serve Prometheus metrics at `/metrics` (needs `--features metrics`). Unauthenticated: bind it on a private interface. Without the feature the flag is refused, never ignored. | +| `--metrics-port` / `--metrics-host` | off / `127.0.0.1` | Serve Prometheus metrics at `/metrics` (needs `--features metrics`). Unauthenticated, so `--metrics-host` follows the `--bind-host` rule. Without the feature the flag is refused, never ignored. | | `--backend` | `$OXIDE_BACKEND`, then detected | The backend this worker executes on. Selected before the first task, so it reaches the operators; a backend the machine cannot provide is a startup error. | +| `--heartbeat-interval` | `60` | Seconds between heartbeats to the scheduler; keep it well under the scheduler's `--worker-timeout`. | +| `--drain-timeout` | `20` | On `SIGTERM`/`SIGINT`, no new tasks are taken (the scheduler runs this worker's tasks elsewhere) and the running ones get this many seconds to finish; then the worker exits 0. | ### Environment diff --git a/SECURITY.md b/SECURITY.md index 91d4ff1..0c97e02 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -90,12 +90,22 @@ OxideLake is an analytical engine intended to run **on infrastructure you control**. Its security boundary is the machine or private network it runs on, not the query interface. -- **Cluster mode has no authentication or transport encryption in v1.** - `oxide-scheduler` and `oxide-worker` speak plain gRPC and Arrow Flight and - will execute any plan a connected client submits, including reading any file - the worker process can read. Both bind to `127.0.0.1` by default; expose them - only on a trusted private network (or behind a mutually authenticated - proxy). TLS/auth is tracked as out of scope for v1 in `STATUS.md`. +- **Cluster mode has no authentication or transport encryption yet, so the + network is the boundary, and the binaries hold it.** `oxide-scheduler` and + `oxide-worker` speak plain gRPC and Arrow Flight and will execute any plan + a connected client submits, including reading any file the worker process + can read. Both bind to `127.0.0.1` by default, accept a private address, + and refuse a public one, or every address at once, unless + `--allow-insecure-bind` is given (#30). + + **Production deployments.** The cluster's ports (the scheduler's one port for gRPC, REST and probes, each worker's Flight and gRPC ports, and any `--metrics-port`) have no authentication and no encryption: whoever can connect can run queries, and a query can read any file a worker can read. Keep them on a network that only the cluster's own hosts and trusted clients can reach, such as a private subnet or a VPN, behind a firewall. `oxide-scheduler` and `oxide-worker` refuse to listen on a public address, or on every address (`0.0.0.0`, `::`), unless `--allow-insecure-bind` says that something else, such as that firewall, already decides who can connect, and they log a warning whenever they listen beyond loopback. TLS and authentication in OxideLake itself are tracked in #30. + +- **A lost worker fails its queries rather than risk wrong rows (#148).** + Ballista 55's recovery from a lost worker can return duplicated rows with + exit 0 (fixed upstream by apache/datafusion-ballista#2677, unreleased), so + `oxide-scheduler` fails a query that held output on a worker it loses, and + `--stage-max-failures` defaults to 1. Raising that limit turns Ballista's + stage retries, and the bug, back on. - **Workers trust their scheduler.** Physical plans arrive over the network and are decoded by `OxidePhysicalCodec`. Payloads are validated (magic, version, column indices, types, dimensions, a cap on predicate size) so a malformed diff --git a/STATUS.md b/STATUS.md index 08be698..0c4d5f5 100644 --- a/STATUS.md +++ b/STATUS.md @@ -45,7 +45,7 @@ Filled in as phases complete. Every component goes under exactly one column — | `HardwarePlacementRule` (Filter/Projection, HashJoin, SortMergeJoin, Aggregate lowering) | planner tests vs plain DataFusion results; `EXPLAIN` tags | | rewrites are the same on GPU machines; only execution differs | | `OxidePhysicalCodec` (magic-prefixed postcard payloads, Ballista codec delegation) | round-trip tests; exercised end to end by the cluster test | | | | Ballista cluster mode (`start_standalone`, scheduler/executor wrappers, `OxideSession::connect`) | in-process scheduler + 2 executors, 5 queries equal embedded, and every `Gpu*Exec` the cluster's `EXPLAIN` shows for them ran on an executor (the process-wide hub as witness, #134); `NOT IN (subquery)` with NULL keys on both sides equals embedded on a `cpu` cluster (#91) | | multi-machine deployment, GPU executors | -| `oxide`, `oxide-scheduler`, `oxide-worker` binaries | `--help` smoke test; a real `oxide-scheduler` refuses a worker whose plan fingerprint is not its own and a query then fails at once naming it (#92); `make test-mixed-build`: a `--features cuda` worker runs a default scheduler's GPU plans, a `--features predict` worker is refused and exits non-zero | | | +| `oxide`, `oxide-scheduler`, `oxide-worker` binaries | `--help` smoke test; a real `oxide-scheduler` refuses a worker whose plan fingerprint is not its own and a query then fails at once naming it (#92); `make test-mixed-build`: a `--features cuda` worker runs a default scheduler's GPU plans, a `--features predict` worker is refused and exits non-zero; `SIGTERM` drains a real scheduler (a new query is refused saying why, the running one finishes with the embedded rows, exit 0) and stops a worker within `--drain-timeout` with exit 0, idle or busy; a worker killed, stopped with `SIGTERM`, or silent past `--worker-timeout` mid-query fails its query with exit 1 and no rows, naming it, and the next query runs on the worker left with the embedded rows (#148); a killed worker stops counting after `--worker-timeout` while one with a short `--heartbeat-interval` keeps counting (#31) | | recovery from a worker lost mid-query with stage retries raised: Ballista 55 returns duplicated rows or hangs (#148, `#[ignore]`d reproduction in `tests/cli.rs`; fixed upstream by apache/datafusion-ballista#2677, unreleased) | | TUI state machine, pure `render`, four panels | unit tests + `TestBackend`/`insta` snapshots | | | | `oxidelake-tui-demo` binary on a real PTY (raw mode, alternate screen, DEC 2026 frames, SIGWINCH) | termlens end-to-end tests, executed here | | | | `l2_distance` / `cosine_distance` SQL UDFs (coercion, nulls, reference equality) | unit tests in `oxidelake-compute::udf` | | | @@ -92,6 +92,8 @@ Resolved 2026-11-11 for the Ballista 55 bump (`cargo tree`, 593 crates in `Cargo - A filter or join DataFusion planned with an empty projection (`COUNT(*)`) is lowered with one column the device reads anyway, the first predicate column or the probe key, under a `ProjectionExec` with no expressions that keeps only the row count (#87). - **Ballista's adaptive planner is off on every OxideLake cluster (#134).** Ballista 55 turned it on by default, and `AdaptivePlanner` rebuilds the session with Ballista's own physical optimizer rules in place of the session's, with no hook to add one: the 55 bump left GPU-targeted clusters executing no `Gpu*Exec` at all while `EXPLAIN` (planned statically) still showed them, and the equality test stayed green because a `Gpu*Exec` and the CPU path agree by construction. `cluster::session_config()` sets `ballista.planner.adaptive.enabled = false` and `build_session_state` forces it, since a client's settings are applied before the session builder runs. The equality test now also requires every operator the cluster's `EXPLAIN` names to have run on an executor. Revisit when Ballista's adaptive planner can carry extra rules. - **A scheduler admits only workers of its own build (#92).** The plan fingerprint (#42) was checked only when a worker decoded a `Gpu*Exec` payload, inside a task launch: Ballista 54 retried that launch for ever, Ballista 55 fails the job with "task could not be prepared or was rejected by executor" and leaves the reason in the worker's log, and a `cpu`-target cluster never checked at all. Ballista's registration carries nothing free-form but the executor id, so `oxide-worker` puts its fingerprint there (`oxl<8 hex>-`) and `oxide-scheduler` runs Ballista's in-memory cluster state behind a check of it (`admission::SameBuildClusterState`). A query on a cluster whose workers were all refused fails in the scheduler's session builder, the first place that sees every query; a cluster that has refused nobody keeps Ballista's behaviour of waiting for its first worker. The fingerprint stopped counting `cuda` and `metal` at the same time: they change where an operator runs, not what a plan says. This is a guard against a mismatched deployment, not authentication: a worker declares its own fingerprint. +- **Ballista 55 does not recover a query from a lost worker reliably (#31, found 2026-11-18).** Two `cpu` workers of two tasks, the 600k-row fixture, a self-join on `k`, one worker `kill -9`ed as its first join task starts: 12 of 15 runs (7 of 8 from a shell loop, 5 of 7 of the committed test) returned the 100 groups plus 13 or 14 of them again (whole hash partitions twice), exit 0, while a run with no kill is byte-equal to embedded. The rollback also loses the surviving workers' task slots: a cancelled task's status arrives after its stage went back to `UnResolved`, so `sum_vcores_for_statuses` refunds nothing for it, and a query whose survivors lost every slot waits until a new worker joins (one run: 670 s, ended by adding a worker). `SIGTERM` on a worker mid-query takes the same path (2 of 2 runs hung). Both are in Ballista's scheduler (#148): the duplicated outputs are fixed upstream by apache/datafusion-ballista#2677, merged 2026-10-28 after 55.0.0 and unreleased, and apache/datafusion-ballista#2539 and #2698 look like the stuck tasks. Decision for 0.3.0, correctness over availability: a lost worker fails its queries. `stage_max_failures` defaults to 1, so a failed fetch from a lost worker fails the query, naming the worker's address. That alone does not cover a worker that is stopped or goes silent: Ballista then rolls back through `ExecutorLost`, with `count_to_failures = false`, whatever the limit (a `SIGTERM` mid-query still hung, 150 s, at limit 1). So `oxide-scheduler` builds Ballista's scheduler itself (`create_scheduler` + `start_grpc_service`), and its cluster state, which every removal passes through before Ballista posts `ExecutorLost`, cancels each running query with a finished task on the removed worker (`worker_loss::WorkerLoss`); the job state then saves that query's failure with a reason naming the worker and #148 where Ballista says "Cancelled". The cancellation is queued ahead of the rollback, and Ballista's own abort refunds the task slots. A worker killed in the middle of sending a shuffle block can show instead as Ballista's broken-stream error (`IpcError ... error reading a body from connection`), which names no worker but fails the stage at once with no rollback (1 run in about 8 of the silent-worker test). A query whose tasks there had finished nothing is left alone: no stage is rolled back, its tasks run again (the next query after a loss is byte-equal to embedded). The recovery the issue asked for stays an `#[ignore]`d test at `--stage-max-failures 4`, to be enabled on a Ballista with #2677. +- **The network is the boundary, and the binaries hold it (#30, first half).** `oxide-scheduler` and `oxide-worker` refuse to listen on a public address or on every address (`exposure::check_listen_address`) unless `--allow-insecure-bind`, and warn whenever they listen beyond loopback; private means RFC 1918, IPv6 unique-local and link-local, and the carrier-shared 100.64/10 counts as public. `oxide-worker` gained `--bind-host` with it: Ballista's executor default of `127.0.0.1` was all it could listen on, so no scheduler on another machine could reach a worker. TLS and authentication are still to build: Ballista 55 can make its clients speak TLS (`ballista.client.use_tls`, and an endpoint override for certificates), but serves the scheduler's port and the executors' gRPC port in plain text with no hook to change that (only the executors' Flight service can be replaced), so it needs an upstream change or a terminating proxy in front of each port. The scheduler's graceful shutdown is OxideLake's own (Ballista's scheduler handled no signal): new queries fail in the session builder, which the scheduler calls for every query and for nothing a running one needs, and the queries already running are waited for by polling the job state, plus a one-second linger so their clients hear that they finished. - The dashboard renders a `DashboardModel` (telemetry snapshot + column profiles) through a pure `render(state, model, frame)`; the demo binary feeds a fixed fixture and repaints only on input/resize (no clock), which is what makes the PTY snapshots reproducible. Repaints are bracketed in DEC 2026 synchronized updates so termlens `wait_frame` never sees a torn frame. diff --git a/crates/oxidelake-runtime/src/admission.rs b/crates/oxidelake-runtime/src/admission.rs index 40ea015..6f508c8 100644 --- a/crates/oxidelake-runtime/src/admission.rs +++ b/crates/oxidelake-runtime/src/admission.rs @@ -29,6 +29,8 @@ use ballista_scheduler::state::task_manager::JobInfoCache; use datafusion::error::DataFusionError; use oxidelake_planner::codec::{PLAN_FINGERPRINT, build_description}; +use crate::worker_loss::WorkerLoss; + /// Starts the build tag in an `oxide-worker`'s executor id. const BUILD_TAG: &str = "oxl"; @@ -95,14 +97,24 @@ fn is_active(heartbeat: &ExecutorHeartbeat) -> bool { /// /// Every other method is Ballista's own: this is the in-memory state that /// `BallistaCluster::new_from_config` would have built, with one check in -/// front of the two ways a worker's metadata enters it. +/// front of the two ways a worker's metadata enters it, and one notice on +/// the way out: a removed worker's queries are failed before Ballista can +/// roll them back (#148, [`WorkerLoss`]). #[derive(Default)] pub(crate) struct SameBuildClusterState { inner: InMemoryClusterState, refusals: Mutex>, + loss: Arc, } impl SameBuildClusterState { + pub(crate) fn new(loss: Arc) -> Self { + Self { + loss, + ..Self::default() + } + } + fn admit(&self, metadata: &ExecutorMetadata) -> Result<()> { let Some(why) = refusal(metadata) else { return Ok(()); @@ -183,8 +195,21 @@ impl ClusterState for SameBuildClusterState { self.inner.save_executor_heartbeat(heartbeat).await } + // Every removal, whatever its cause, comes through here, and Ballista + // posts the event that rolls the worker's queries back only after this + // returns. The worker is removed first, so the cancellation that follows + // cannot reach it: it is being lost, and Ballista's own clean-up does not + // reach it either. async fn remove_executor(&self, executor_id: &str) -> Result<()> { - self.inner.remove_executor(executor_id).await + let address = self + .inner + .get_executor_metadata(executor_id) + .await + .map(|worker| format!("{}:{}", worker.host, worker.port)) + .unwrap_or_else(|_| "address unknown".to_owned()); + let removed = self.inner.remove_executor(executor_id).await; + self.loss.lost(executor_id, &address).await; + removed } fn executor_heartbeats(&self) -> HashMap { diff --git a/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs b/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs index 2f7f556..b098bfd 100644 --- a/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs +++ b/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs @@ -1,8 +1,13 @@ //! `oxide-scheduler` — a Ballista scheduler with OxideLake's placement rule and plan codec. +use std::time::Duration; + +use ballista_scheduler::config::SchedulerConfig; use clap::Parser; use oxidelake_core::BackendKind; use oxidelake_runtime::cluster; +use oxidelake_runtime::exposure::{check_listen_address, warn_unless_loopback}; +use oxidelake_runtime::shutdown::ShutdownSignal; use tracing_subscriber::EnvFilter; #[derive(Parser)] @@ -12,7 +17,10 @@ use tracing_subscriber::EnvFilter; about = "OxideLake scheduler (Apache DataFusion Ballista)" )] struct Cli { - /// Address to bind. + /// Address to bind: loopback or private (10/8, 172.16/12, 192.168/16, + /// fc00::/7). The port has no authentication or encryption, so a public + /// address, or every address (0.0.0.0, ::), needs + /// `--allow-insecure-bind`. #[arg(long, default_value = "127.0.0.1")] bind_host: String, /// gRPC port. @@ -27,9 +35,72 @@ struct Cli { /// interface, as the Ballista ports already are. #[arg(long, value_name = "PORT")] metrics_port: Option, - /// Address the metrics endpoint binds to. + /// Address the metrics endpoint binds to, held to the same rule as + /// `--bind-host`. #[arg(long, default_value = "127.0.0.1", value_name = "HOST")] metrics_host: String, + /// Listen on a public address, or on every address, although the ports + /// have no authentication or encryption: say so only when a firewall or + /// an authenticating proxy already decides who can connect (SECURITY.md). + #[arg(long)] + allow_insecure_bind: bool, + /// Times one task may fail before its query fails; 1 means no retry + /// (Ballista's `task_max_failures`). A task lost with its worker is run + /// again elsewhere without counting. + #[arg(long, default_value_t = 4, value_name = "N", value_parser = at_least_one)] + task_max_failures: usize, + /// Times a stage may fail because a shuffle fetch failed, its input lost + /// with a worker, before its query fails (Ballista's + /// `stage_max_failures`). The default, 1, fails the query at the first + /// such failure, naming the worker; a worker that is stopped or goes + /// silent fails its queries whatever this says (#148). Raising it turns + /// on Ballista 55's re-run of the stage, which can return duplicated rows + /// with exit 0 or never finish (fixed upstream by + /// apache/datafusion-ballista#2677, unreleased). + #[arg( + long, + default_value_t = cluster::DEFAULT_STAGE_MAX_FAILURES, + value_name = "N", + value_parser = at_least_one + )] + stage_max_failures: usize, + /// Seconds a worker may go without a heartbeat before it is presumed lost + /// and its tasks run elsewhere. Until then a query holding tasks on a dead + /// worker waits. Keep it well above the workers' `--heartbeat-interval`. + #[arg( + long, + default_value_t = cluster::DEFAULT_WORKER_TIMEOUT.as_secs(), + value_name = "SECS", + value_parser = clap::value_parser!(u64).range(1..) + )] + worker_timeout: u64, + /// On SIGTERM or SIGINT, refuse new queries and give the running ones + /// this long to finish, then exit 0. A second signal exits at once. + #[arg(long, default_value_t = 20, value_name = "SECS")] + drain_timeout: u64, +} + +/// A retry limit of zero would mean what one means, so it is refused rather +/// than given a second spelling. +fn at_least_one(value: &str) -> Result { + match value.parse::() { + Ok(0) => Err("must be at least 1 (1 means no retry)".to_owned()), + Ok(n) => Ok(n), + Err(e) => Err(e.to_string()), + } +} + +/// The scheduler `cli` asks for, planning for `target`. +fn config(cli: &Cli, target: BackendKind) -> SchedulerConfig { + let config = cluster::with_worker_timeout( + cluster::scheduler_config(&cli.bind_host, cli.port, target), + Duration::from_secs(cli.worker_timeout), + ); + SchedulerConfig { + task_max_failures: cli.task_max_failures, + stage_max_failures: cli.stage_max_failures, + ..config + } } #[tokio::main] @@ -43,7 +114,17 @@ async fn main() -> anyhow::Result<()> { .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr())) .init(); let cli = Cli::parse(); - let target: BackendKind = match cli.cluster_backend { + // Before anything is served, so a stop request during startup is held + // for the shutdown below rather than killing the process. + let signal = ShutdownSignal::listen()?; + // Before anything listens: the ports are unauthenticated, so where they + // listen is the whole of the security boundary (#30). + let exposure = check_listen_address("--bind-host", &cli.bind_host, cli.allow_insecure_bind)?; + if cli.metrics_port.is_some() { + check_listen_address("--metrics-host", &cli.metrics_host, cli.allow_insecure_bind)?; + } + warn_unless_loopback("the scheduler", &cli.bind_host, exposure); + let target: BackendKind = match &cli.cluster_backend { Some(name) => name.parse()?, None => oxidelake_planner::cluster_target_from_env()?, }; @@ -55,7 +136,12 @@ async fn main() -> anyhow::Result<()> { "admitting workers of this build only" ); serve_metrics(cli.metrics_port, &cli.metrics_host).await?; - cluster::run_scheduler(cluster::scheduler_config(&cli.bind_host, cli.port, target)).await?; + cluster::run_scheduler_with_shutdown( + config(&cli, target), + signal, + Duration::from_secs(cli.drain_timeout), + ) + .await?; Ok(()) } @@ -92,3 +178,66 @@ async fn serve_metrics(port: Option, _host: &str) -> anyhow::Result<()> { ), } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn parse(args: &[&str]) -> Result { + Cli::try_parse_from(std::iter::once("oxide-scheduler").chain(args.iter().copied())) + } + + /// The flags reach the configuration Ballista's scheduler runs with (#31). + #[test] + fn the_retry_and_timeout_flags_reach_the_scheduler() { + let cli = parse(&[ + "--task-max-failures", + "2", + "--stage-max-failures", + "1", + "--worker-timeout", + "9", + ]) + .unwrap(); + let config = config(&cli, BackendKind::CpuSimd); + assert_eq!(config.task_max_failures, 2); + assert_eq!(config.stage_max_failures, 1); + assert_eq!(config.executor_timeout_seconds, 9); + assert_eq!(config.expire_dead_executor_interval_seconds, 3); + assert_eq!(config.no_executors_grace_period_seconds, 9); + } + + /// Unset, they are Ballista's own defaults, save one: a stage is not run + /// again after a lost worker's shuffle output could not be fetched + /// (#148), where Ballista would try 4 times. + #[test] + fn the_defaults_are_ballistas_but_a_lost_worker_is_not_retried() { + let ballista = SchedulerConfig::default(); + let config = config(&parse(&[]).unwrap(), BackendKind::CpuSimd); + assert_eq!(config.task_max_failures, ballista.task_max_failures); + assert_eq!(ballista.stage_max_failures, 4, "Ballista's default moved"); + assert_eq!(config.stage_max_failures, 1); + assert_eq!( + config.executor_timeout_seconds, + ballista.executor_timeout_seconds + ); + assert_eq!( + config.expire_dead_executor_interval_seconds, + ballista.expire_dead_executor_interval_seconds + ); + assert_eq!( + config.no_executors_grace_period_seconds, + ballista.no_executors_grace_period_seconds + ); + } + + #[test] + fn a_zero_retry_limit_or_timeout_is_refused() { + for flag in ["--task-max-failures", "--stage-max-failures"] { + let err = parse(&[flag, "0"]).err().expect(flag).to_string(); + assert!(err.contains("1 means no retry"), "{err}"); + } + assert!(parse(&["--worker-timeout", "0"]).is_err()); + } +} diff --git a/crates/oxidelake-runtime/src/bin/oxide_worker.rs b/crates/oxidelake-runtime/src/bin/oxide_worker.rs index ac65a4c..5836720 100644 --- a/crates/oxidelake-runtime/src/bin/oxide_worker.rs +++ b/crates/oxidelake-runtime/src/bin/oxide_worker.rs @@ -1,8 +1,12 @@ //! `oxide-worker` — a Ballista executor that can run OxideLake's `Gpu*Exec` operators. +use std::time::Duration; + use clap::Parser; use oxidelake_core::BackendKind; use oxidelake_runtime::cluster; +use oxidelake_runtime::exposure::{check_listen_address, warn_unless_loopback}; +use oxidelake_runtime::shutdown::{ShutdownSignal, Stopped}; use tracing_subscriber::EnvFilter; #[derive(Parser)] @@ -18,6 +22,14 @@ struct Cli { /// Scheduler port. #[arg(long, default_value_t = 50050)] scheduler_port: u16, + /// Address the Flight and gRPC ports bind: loopback or private (10/8, + /// 172.16/12, 192.168/16, fc00::/7). They have no authentication or + /// encryption, so a public address, or every address (0.0.0.0, ::), + /// needs `--allow-insecure-bind`. The scheduler connects back to the + /// address it sees this worker connect from, so bind the interface that + /// faces the scheduler. + #[arg(long, default_value = "127.0.0.1")] + bind_host: String, /// Arrow Flight port for shuffle data. #[arg(long, default_value_t = 50051)] port: u16, @@ -41,9 +53,25 @@ struct Cli { /// interface, as the Ballista ports already are. #[arg(long, value_name = "PORT")] metrics_port: Option, - /// Address the metrics endpoint binds to. + /// Address the metrics endpoint binds to, held to the same rule as + /// `--bind-host`. #[arg(long, default_value = "127.0.0.1", value_name = "HOST")] metrics_host: String, + /// Listen on a public address, or on every address, although the ports + /// have no authentication or encryption: say so only when a firewall or + /// an authenticating proxy already decides who can connect (SECURITY.md). + #[arg(long)] + allow_insecure_bind: bool, + /// Seconds between this worker's heartbeats. The scheduler presumes a + /// worker lost after its `--worker-timeout` (180 s by default) without + /// one, so keep this well below that. + #[arg(long, default_value_t = 60, value_name = "SECS", value_parser = clap::value_parser!(u64).range(1..))] + heartbeat_interval: u64, + /// On SIGTERM or SIGINT, take no new tasks and give the running ones this + /// long to finish, then exit 0; the scheduler runs them again elsewhere. + /// A second signal exits at once. + #[arg(long, default_value_t = 20, value_name = "SECS")] + drain_timeout: u64, } #[tokio::main] @@ -57,6 +85,16 @@ async fn main() -> anyhow::Result<()> { .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr())) .init(); let cli = Cli::parse(); + // Before the worker joins, so a stop request during startup is held for + // the shutdown below rather than killing the process. + let signal = ShutdownSignal::listen()?; + // Before anything listens: the ports are unauthenticated, so where they + // listen is the whole of the security boundary (#30). + let exposure = check_listen_address("--bind-host", &cli.bind_host, cli.allow_insecure_bind)?; + if cli.metrics_port.is_some() { + check_listen_address("--metrics-host", &cli.metrics_host, cli.allow_insecure_bind)?; + } + warn_unless_loopback("this worker", &cli.bind_host, exposure); // Selected before anything runs: operators read the memoised // `local_backend()`, so a choice made after the first task would be // accepted and then ignored. @@ -70,15 +108,24 @@ async fn main() -> anyhow::Result<()> { "worker backend" ); serve_metrics(cli.metrics_port, &cli.metrics_host).await?; - cluster::run_executor(cluster::executor_config( + let mut config = cluster::executor_config( &cli.scheduler_host, cli.scheduler_port, cli.port, cli.grpc_port, cli.concurrent_tasks, cli.work_dir, - )) - .await?; + ); + config.executor_heartbeat_interval_seconds = cli.heartbeat_interval; + config.bind_host = cli.bind_host; + let stopped = + cluster::run_executor_with_shutdown(config, signal, Duration::from_secs(cli.drain_timeout)) + .await?; + if stopped == Stopped::Abandoned { + // Returning would drop the runtime, which waits for the tasks still + // running: the very wait the drain timeout bounds. + std::process::exit(0); + } Ok(()) } diff --git a/crates/oxidelake-runtime/src/cluster.rs b/crates/oxidelake-runtime/src/cluster.rs index d4f1f12..b85c3b5 100644 --- a/crates/oxidelake-runtime/src/cluster.rs +++ b/crates/oxidelake-runtime/src/cluster.rs @@ -8,8 +8,12 @@ //! tests and the CLI. use std::any::Any; +use std::future::Future; use std::net::SocketAddr; +use std::pin::Pin; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; use ballista_core::extension::{ SessionConfigExt, ballista_aggregate_functions, ballista_scalar_functions, @@ -24,10 +28,10 @@ use ballista_core::utils::{default_config_producer, default_session_builder}; use ballista_core::{ConfigProducer, RuntimeProducer}; use ballista_executor::executor_process::{ExecutorProcessConfig, start_executor_process}; use ballista_executor::new_standalone_executor_from_builder; -use ballista_scheduler::cluster::BallistaCluster; use ballista_scheduler::cluster::memory::InMemoryJobState; +use ballista_scheduler::cluster::{BallistaCluster, JobState}; use ballista_scheduler::config::SchedulerConfig; -use ballista_scheduler::scheduler_process::start_server; +use ballista_scheduler::scheduler_process::{create_scheduler, start_grpc_service}; use ballista_scheduler::scheduler_server::SessionBuilder; use ballista_scheduler::standalone::new_standalone_scheduler_with_builder; use ballista_scheduler::state::session_manager::share_file_statistics_cache; @@ -39,6 +43,7 @@ use datafusion::execution::runtime_env::RuntimeEnvBuilder; use datafusion::execution::session_state::SessionState; use datafusion::prelude::SessionConfig; use datafusion_proto::physical_plan::PhysicalExtensionCodec; +use datafusion_proto::protobuf::{LogicalPlanNode, PhysicalPlanNode}; use oxidelake_compute::oxide_udfs; use oxidelake_core::{BackendKind, EngineError}; use oxidelake_planner::codec::build_description; @@ -50,6 +55,8 @@ use oxidelake_storage::{ use crate::admission::{ REFUSED, SameBuildClusterState, failing_without_a_usable_worker, tagged_executor_id, }; +use crate::shutdown::{ShutdownSignal, Stopped, drain, refusing_while_draining, unfinished_jobs}; +use crate::worker_loss::{ReportingJobState, WorkerLoss}; fn ballista_error(err: impl std::fmt::Display) -> EngineError { EngineError::execution(format!("ballista: {err}")) @@ -254,7 +261,22 @@ pub fn function_registry() -> BallistaFunctionRegistry { registry } -/// Scheduler configuration with OxideLake's hooks installed. +/// How many failed attempts a stage may have before its query fails, unless +/// told otherwise: one, so a stage whose shuffle input was lost with a +/// worker is never run again (#148). +/// +/// Ballista's default is 4, and every retry rolls the stage back, which in +/// Ballista 55 can return some rows twice with exit 0 or never finish +/// (apache/datafusion-ballista#2677, unreleased after 55.0.0, and #2539, +/// #2698). At 1 the first failed fetch fails the query, naming the worker. +/// Only a failed fetch counts: Ballista rolls back a worker that is stopped, +/// or silent past its timeout, whatever this says, which is why +/// [`run_scheduler`] also fails a lost worker's queries itself. +pub const DEFAULT_STAGE_MAX_FAILURES: usize = 1; + +/// Scheduler configuration with OxideLake's hooks installed, failing a query +/// whose shuffle input was lost with a worker +/// ([`DEFAULT_STAGE_MAX_FAILURES`]). pub fn scheduler_config(bind_host: &str, port: u16, target: BackendKind) -> SchedulerConfig { SchedulerConfig { bind_host: bind_host.to_owned(), @@ -262,10 +284,70 @@ pub fn scheduler_config(bind_host: &str, port: u16, target: BackendKind) -> Sche override_session_builder: Some(session_builder(target)), override_config_producer: Some(config_producer()), override_physical_codec: Some(oxide_codec()), + stage_max_failures: DEFAULT_STAGE_MAX_FAILURES, ..SchedulerConfig::default() } } +/// How long a scheduler waits on a silent worker unless told otherwise: +/// Ballista's `executor_timeout_seconds`. +pub const DEFAULT_WORKER_TIMEOUT: Duration = Duration::from_secs(180); + +/// Sets how long a worker may go without a heartbeat before `config`'s +/// scheduler presumes it lost and re-runs its tasks elsewhere (#31), in +/// whole seconds, at least one. +/// +/// Until then a worker that died holding tasks holds its query too, unless a +/// shuffle fetch from it fails first. Ballista checks for silent workers on +/// a fixed 15-second tick, which would make a timeout shorter than that a +/// fiction; the tick here is a third of the timeout, never more than 15 +/// seconds. A query left with no worker at all fails after the same timeout +/// again, as Ballista's own scheduler binary arranges it. +pub fn with_worker_timeout(mut config: SchedulerConfig, timeout: Duration) -> SchedulerConfig { + let seconds = timeout.as_secs().max(1); + config.executor_timeout_seconds = seconds; + config.expire_dead_executor_interval_seconds = (seconds / 3).clamp(1, 15); + config.no_executors_grace_period_seconds = seconds; + config +} + +type SchedulerServe = Pin> + Send>>; + +/// A scheduler ready to serve, with what a shutdown needs to reach. +struct Scheduler { + serve: SchedulerServe, + jobs: Arc, + draining: Arc, +} + +impl Scheduler { + fn new(config: SchedulerConfig) -> Result { + let address: SocketAddr = format!("{}:{}", config.bind_host, config.bind_port) + .parse() + .map_err(|e| EngineError::plan(format!("invalid scheduler bind address: {e}")))?; + let draining = Arc::new(AtomicBool::new(false)); + let loss = Arc::new(WorkerLoss::default()); + let cluster = same_build_cluster(&config, Arc::clone(&draining), Arc::clone(&loss)); + let jobs = cluster.job_state(); + // What Ballista's `start_server` does, keeping hold of the scheduler + // so a lost worker's queries can be failed through it (#148). + let serve = async move { + config.validate()?; + tracing::info!(%address, "Ballista scheduler listening"); + let scheduler = + create_scheduler::(cluster, Arc::new(config)) + .await?; + loss.attach(scheduler.clone()); + start_grpc_service(address, scheduler).await + }; + Ok(Self { + serve: Box::pin(serve), + jobs, + draining, + }) + } +} + /// Runs a Ballista scheduler until it exits. /// /// The scheduler admits only workers of its own build (#92): one whose plan @@ -273,20 +355,74 @@ pub fn scheduler_config(bind_host: &str, port: u16, target: BackendKind) -> Sche /// cluster whose workers were all refused fails at once with the reason, /// where Ballista would hold it for a worker that is never coming. pub async fn run_scheduler(config: SchedulerConfig) -> Result<(), EngineError> { - let address: SocketAddr = format!("{}:{}", config.bind_host, config.bind_port) - .parse() - .map_err(|e| EngineError::plan(format!("invalid scheduler bind address: {e}")))?; - let cluster = same_build_cluster(&config); - start_server(cluster, address, Arc::new(config)) - .await - .map_err(ballista_error) + Scheduler::new(config)?.serve.await.map_err(ballista_error) +} + +/// Runs a scheduler like [`run_scheduler`] until `signal`, then stops it +/// gracefully (#31): a query sent from then on fails at once saying the +/// scheduler is shutting down, and the queries already running get up to +/// `drain_timeout` to finish before this returns. A second signal stops it at +/// once. Ballista's scheduler keeps every query in memory, so whatever is +/// still running when this returns fails. +pub async fn run_scheduler_with_shutdown( + config: SchedulerConfig, + mut signal: ShutdownSignal, + drain_timeout: Duration, +) -> Result { + let Scheduler { + mut serve, + jobs, + draining, + } = Scheduler::new(config)?; + let first = tokio::select! { + served = &mut serve => return served.map(|()| Stopped::Drained).map_err(ballista_error), + first = signal.recv() => first, + }; + draining.store(true, Ordering::SeqCst); + tracing::info!( + signal = first, + running = unfinished_jobs(jobs.as_ref()).await, + drain_timeout_s = drain_timeout.as_secs_f64(), + "shutting down: refusing new queries and waiting for the running ones" + ); + // The server keeps serving while the queries drain: their clients still + // poll it for their status. + tokio::select! { + served = &mut serve => served.map(|()| Stopped::Drained).map_err(ballista_error), + unfinished = drain(jobs.as_ref(), drain_timeout) => Ok(if unfinished == 0 { + tracing::info!("every running query finished; scheduler stopped"); + Stopped::Drained + } else { + tracing::warn!( + unfinished, + drain_timeout_s = drain_timeout.as_secs_f64(), + "the drain timeout passed with queries still running; they fail as this \ + scheduler stops" + ); + Stopped::Abandoned + }), + second = signal.recv() => { + tracing::warn!( + signal = second, + unfinished = unfinished_jobs(jobs.as_ref()).await, + "a second signal: stopping now, and the queries still running fail" + ); + Ok(Stopped::Abandoned) + } + } } /// What `BallistaCluster::new_from_config` builds, in-memory cluster and job /// state, with the cluster state admitting only workers of this build and -/// the session builder failing a query that no admitted worker can run. -fn same_build_cluster(config: &SchedulerConfig) -> BallistaCluster { - let state = Arc::new(SameBuildClusterState::default()); +/// failing a lost worker's queries through `loss` (#148), the job state +/// saying why, and the session builder failing a query that no admitted +/// worker can run and, once `draining` is set, every new query (#31). +fn same_build_cluster( + config: &SchedulerConfig, + draining: Arc, + loss: Arc, +) -> BallistaCluster { + let state = Arc::new(SameBuildClusterState::new(Arc::clone(&loss))); let session_builder = config .override_session_builder .clone() @@ -297,13 +433,13 @@ fn same_build_cluster(config: &SchedulerConfig) -> BallistaCluster { .unwrap_or_else(|| Arc::new(default_config_producer)); let jobs = InMemoryJobState::new( config.scheduler_id.clone(), - share_file_statistics_cache(failing_without_a_usable_worker( - session_builder, - Arc::clone(&state), + share_file_statistics_cache(refusing_while_draining( + failing_without_a_usable_worker(session_builder, Arc::clone(&state)), + draining, )), config_producer, ); - BallistaCluster::new(state, Arc::new(jobs)) + BallistaCluster::new(state, Arc::new(ReportingJobState::new(jobs, loss))) } /// Executor configuration with OxideLake's hooks installed. @@ -358,6 +494,57 @@ pub async fn run_executor(config: ExecutorProcessConfig) -> Result<(), EngineErr }) } +/// Runs an executor like [`run_executor`], and once `signal` comes, gives it +/// at most `drain_timeout` to stop (#31). +/// +/// Ballista's executor sees the same signal and stops gracefully on its own: +/// it takes no new tasks, tells the scheduler, which re-runs the tasks it was +/// running elsewhere, and waits for those tasks to finish. That wait has no +/// bound, so a task that does not finish would keep the worker alive until it +/// is killed. When the bound passes, or a second signal comes, this returns +/// [`Stopped::Abandoned`] and the caller should exit without waiting for the +/// tasks still running. +/// +/// Ballista's executor starts listening only once it has registered, a +/// fraction of a second after the worker starts. A signal that arrives +/// before that is seen here alone: the worker then stops when the drain +/// timeout passes, still with exit 0, and the scheduler learns it is gone +/// from its missed heartbeats. +pub async fn run_executor_with_shutdown( + config: ExecutorProcessConfig, + mut signal: ShutdownSignal, + drain_timeout: Duration, +) -> Result { + let executor = run_executor(config); + tokio::pin!(executor); + let first = tokio::select! { + stopped = &mut executor => return stopped.map(|()| Stopped::Drained), + first = signal.recv() => first, + }; + tracing::info!( + signal = first, + drain_timeout_s = drain_timeout.as_secs_f64(), + "stopping: taking no new tasks, and waiting for the running ones, which the scheduler \ + re-runs elsewhere" + ); + tokio::select! { + drained = tokio::time::timeout(drain_timeout, &mut executor) => match drained { + Ok(stopped) => stopped.map(|()| Stopped::Drained), + Err(_) => { + tracing::warn!( + drain_timeout_s = drain_timeout.as_secs_f64(), + "the drain timeout passed with tasks still running: stopping without them" + ); + Ok(Stopped::Abandoned) + } + }, + second = signal.recv() => { + tracing::warn!(signal = second, "a second signal: stopping without the running tasks"); + Ok(Stopped::Abandoned) + } + } +} + /// Starts an in-process scheduler plus `executors` executors on ephemeral /// localhost ports and returns the scheduler address. Everything runs on the /// current tokio runtime and stops with it. diff --git a/crates/oxidelake-runtime/src/exposure.rs b/crates/oxidelake-runtime/src/exposure.rs new file mode 100644 index 0000000..59e1942 --- /dev/null +++ b/crates/oxidelake-runtime/src/exposure.rs @@ -0,0 +1,197 @@ +//! Where a cluster process may listen (#30). +//! +//! The scheduler's and the workers' ports have no authentication and no +//! encryption: anyone who can reach them can run a query, and a query can +//! read any file the worker process can read. Until OxideLake has TLS and +//! authentication, the private network is the boundary, and this module +//! holds a process to it: a listener on a public address, or on every +//! address at once (`0.0.0.0`, `::`), is refused unless the operator says, +//! with `--allow-insecure-bind`, that something else (a firewall, an +//! authenticating proxy) already decides who can connect. + +use std::net::{IpAddr, ToSocketAddrs}; + +use oxidelake_core::EngineError; + +/// The flag that accepts a listener the private network does not enclose. +pub const ALLOW_INSECURE_BIND: &str = "--allow-insecure-bind"; + +/// What a listening address is exposed to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum Exposure { + /// This machine only. + Loopback, + /// A private network: RFC 1918, IPv6 unique-local, or link-local. + Private, + /// Any network that routes to it, which may be the internet; also every + /// interface at once (`0.0.0.0`, `::`), public ones included. + Public, +} + +/// What listening on `ip` exposes a port to. +pub fn exposure(ip: IpAddr) -> Exposure { + // An IPv4-mapped IPv6 address is the IPv4 address it carries. + let ip = match ip { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4), + v4 => v4, + }; + if ip.is_loopback() { + return Exposure::Loopback; + } + let private = match ip { + IpAddr::V4(v4) => v4.is_private() || v4.is_link_local(), + IpAddr::V6(v6) => v6.is_unique_local() || v6.is_unicast_link_local(), + }; + if private { + Exposure::Private + } else { + Exposure::Public + } +} + +/// Checks that listening on `host` (given as `flag`) keeps the port off any +/// public network, unless `allow_insecure` (#30). Returns the widest +/// exposure among the addresses `host` names, so the caller can say where +/// it listens. +/// +/// A host that resolves to several addresses is judged by the widest, and +/// one that does not resolve is an error: an address that cannot be checked +/// is not one to listen on. +pub fn check_listen_address( + flag: &str, + host: &str, + allow_insecure: bool, +) -> Result { + // `[::1]` is how an IPv6 address is written beside a port, and how the + // scheduler and Ballista's executor need it, since they parse + // `host:port`; the brackets are not part of the address. + let bare = host + .strip_prefix('[') + .and_then(|inner| inner.strip_suffix(']')) + .unwrap_or(host); + let widest = (bare, 0) + .to_socket_addrs() + .map_err(|e| EngineError::plan(format!("{flag} {host}: {e}")))? + .map(|addr| exposure(addr.ip())) + .max_by_key(|exposure| *exposure as u8) + .ok_or_else(|| EngineError::plan(format!("{flag} {host} names no address")))?; + if widest == Exposure::Public && !allow_insecure { + return Err(EngineError::plan(format!( + "{flag} {host} would listen where any network that routes to it can connect, and \ + OxideLake's cluster ports have no authentication or encryption: whoever reaches \ + them can run queries that read any file this process can read. Listen on a \ + loopback or private address (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, \ + fc00::/7), or pass {ALLOW_INSECURE_BIND} if a firewall or an authenticating \ + proxy already decides who can connect (SECURITY.md)" + ))); + } + Ok(widest) +} + +/// Logs, once at startup, that `what` listens beyond this machine (#30). +pub fn warn_unless_loopback(what: &str, host: &str, exposure: Exposure) { + match exposure { + Exposure::Loopback => {} + Exposure::Private => tracing::warn!( + host, + "{what} listens on a private network without authentication or encryption: \ + every host that reaches it can run queries" + ), + Exposure::Public => tracing::warn!( + host, + "{what} listens beyond any private network without authentication or \ + encryption, as {ALLOW_INSECURE_BIND} allows: whatever reaches it can run queries" + ), + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn of(ip: &str) -> Exposure { + exposure(ip.parse().unwrap()) + } + + #[test] + fn loopback_and_private_networks_are_told_apart_from_public_ones() { + for ip in ["127.0.0.1", "127.255.0.9", "::1", "::ffff:127.0.0.1"] { + assert_eq!(of(ip), Exposure::Loopback, "{ip}"); + } + for ip in [ + "10.0.0.1", + "10.255.255.255", + "172.16.0.1", + "172.31.255.254", + "192.168.1.20", + "169.254.3.4", + "fd12:3456::1", + "fc00::1", + "fe80::1", + "::ffff:192.168.1.20", + ] { + assert_eq!(of(ip), Exposure::Private, "{ip}"); + } + // The edges of the private ranges, every interface at once, and the + // shared (carrier) range, which is other customers' network too. + for ip in [ + "0.0.0.0", + "::", + "8.8.8.8", + "172.15.255.255", + "172.32.0.0", + "192.169.0.1", + "11.0.0.1", + "100.64.0.1", + "2001:4860:4860::8888", + "::ffff:8.8.8.8", + ] { + assert_eq!(of(ip), Exposure::Public, "{ip}"); + } + } + + #[test] + fn a_public_listener_needs_the_flag_and_a_private_one_does_not() { + assert_eq!( + check_listen_address("--bind-host", "127.0.0.1", false).unwrap(), + Exposure::Loopback + ); + assert_eq!( + check_listen_address("--bind-host", "localhost", false).unwrap(), + Exposure::Loopback + ); + assert_eq!( + check_listen_address("--bind-host", "10.1.2.3", false).unwrap(), + Exposure::Private + ); + assert_eq!( + check_listen_address("--bind-host", "[::1]", false).unwrap(), + Exposure::Loopback + ); + assert_eq!( + check_listen_address("--bind-host", "[fd00::7]", false).unwrap(), + Exposure::Private + ); + for host in ["0.0.0.0", "::", "[::]", "203.0.113.7"] { + let err = check_listen_address("--bind-host", host, false) + .unwrap_err() + .to_string(); + assert!(err.contains(&format!("--bind-host {host}")), "{err}"); + assert!(err.contains(ALLOW_INSECURE_BIND), "{err}"); + assert_eq!( + check_listen_address("--bind-host", host, true).unwrap(), + Exposure::Public + ); + } + } + + #[test] + fn an_address_that_cannot_be_checked_is_refused() { + let err = check_listen_address("--bind-host", "no such host .invalid", true) + .unwrap_err() + .to_string(); + assert!(err.contains("--bind-host no such host .invalid"), "{err}"); + } +} diff --git a/crates/oxidelake-runtime/src/lib.rs b/crates/oxidelake-runtime/src/lib.rs index b6f4e3a..65579da 100644 --- a/crates/oxidelake-runtime/src/lib.rs +++ b/crates/oxidelake-runtime/src/lib.rs @@ -9,10 +9,13 @@ mod admission; pub mod cluster; pub mod dashboard; +pub mod exposure; #[cfg(feature = "metrics")] pub mod metrics; pub mod output; pub mod session; +pub mod shutdown; +mod worker_loss; pub use output::OutputFormat; pub use oxidelake_compute::udf; diff --git a/crates/oxidelake-runtime/src/shutdown.rs b/crates/oxidelake-runtime/src/shutdown.rs new file mode 100644 index 0000000..1d7d3f6 --- /dev/null +++ b/crates/oxidelake-runtime/src/shutdown.rs @@ -0,0 +1,231 @@ +//! Stopping a scheduler or a worker without dropping work on the floor (#31). +//! +//! Ballista's executor already handles `SIGTERM` and `SIGINT`: it stops taking +//! tasks, tells the scheduler (which re-runs the tasks it was running +//! elsewhere), waits for those tasks, and returns. It does not bound that +//! wait, so a worker whose task does not finish ignores `SIGTERM` until it is +//! killed. Ballista's scheduler handles neither signal: `SIGTERM` killed it +//! with every query it was running, and their clients saw a dropped +//! connection. This module supplies the signal, the bound, and the +//! scheduler's half: refuse new queries, wait for the running ones, exit. + +use std::io; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use ballista_core::serde::protobuf::job_status; +use ballista_scheduler::cluster::JobState; +use ballista_scheduler::scheduler_server::SessionBuilder; +use datafusion::error::DataFusionError; +use tokio::time::Instant; + +/// What a client is told when it sends a query to a scheduler that is +/// shutting down. +pub(crate) const SHUTTING_DOWN: &str = "this scheduler is shutting down: it finishes the \ + queries it is running and takes no new ones; send this query to another scheduler, or \ + again once this one has restarted"; + +/// How long a drained scheduler stays up after its last query finished, so +/// that query's client learns it did: the final status reaches a client over +/// its status stream, or at its next poll, 50 ms apart. +const LINGER: Duration = Duration::from_secs(1); + +/// How often a draining scheduler looks at its queries. +const POLL: Duration = Duration::from_millis(100); + +/// How a scheduler or a worker stopped. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum Stopped { + /// It finished what it was running, or had nothing running. + Drained, + /// It stopped with work still running, because the drain timeout passed + /// or a second signal came. A worker's scheduler re-runs that work + /// elsewhere; a scheduler's running queries fail. + Abandoned, +} + +/// The signals that ask a process to stop: `SIGTERM` (an orchestrator, +/// `kill`) and `SIGINT` (Ctrl-C). +/// +/// Listening starts when this is made, not when it is first awaited, so a +/// signal that arrives while the scheduler or worker is still starting is +/// held rather than killing the process. +#[derive(Debug)] +pub struct ShutdownSignal { + #[cfg(unix)] + terminate: tokio::signal::unix::Signal, + #[cfg(unix)] + interrupt: tokio::signal::unix::Signal, +} + +impl ShutdownSignal { + /// Starts listening. Must be called inside a Tokio runtime. + pub fn listen() -> io::Result { + #[cfg(unix)] + { + use tokio::signal::unix::{SignalKind, signal}; + Ok(Self { + terminate: signal(SignalKind::terminate())?, + interrupt: signal(SignalKind::interrupt())?, + }) + } + #[cfg(not(unix))] + { + Ok(Self {}) + } + } + + /// Resolves on the next signal and names it. + pub async fn recv(&mut self) -> &'static str { + #[cfg(unix)] + { + tokio::select! { + _ = self.terminate.recv() => "SIGTERM", + _ = self.interrupt.recv() => "SIGINT", + } + } + #[cfg(not(unix))] + { + // Ctrl-C is the one stop request Windows delivers this way; the + // project does not support Windows, but must still compile there. + match tokio::signal::ctrl_c().await { + Ok(()) => "Ctrl-C", + Err(_) => std::future::pending().await, + } + } + } +} + +/// Wraps `builder` so that, once `draining` is set, a new query fails at once +/// saying the scheduler is shutting down. The scheduler builds a session for +/// every query it is sent and for nothing a running query needs, so this +/// turns away new work without touching the queries being drained. +pub(crate) fn refusing_while_draining( + builder: SessionBuilder, + draining: Arc, +) -> SessionBuilder { + Arc::new(move |config| { + if draining.load(Ordering::SeqCst) { + Err(DataFusionError::Execution(SHUTTING_DOWN.to_owned())) + } else { + builder(config) + } + }) +} + +/// How many queries `jobs` holds that have not finished: queued, being +/// planned, or running. +pub(crate) async fn unfinished_jobs(jobs: &dyn JobState) -> usize { + // Ballista's in-memory `get_jobs` returns the *completed* jobs, so the + // unfinished ones are counted from every job's status instead. + let Ok(ids) = jobs.get_all_jobs().await else { + return 0; + }; + let mut unfinished = 0; + for id in ids { + let finished = matches!( + jobs.get_job_status(&id).await, + Ok(Some(ballista_core::serde::protobuf::JobStatus { + status: Some(job_status::Status::Successful(_) | job_status::Status::Failed(_)), + .. + })) + ); + if !finished { + unfinished += 1; + } + } + unfinished +} + +/// Waits until `jobs` has had no unfinished query for [`LINGER`], or until +/// `timeout` has passed, and returns how many were still unfinished. +pub(crate) async fn drain(jobs: &dyn JobState, timeout: Duration) -> usize { + let deadline = Instant::now() + timeout; + let mut idle_since: Option = None; + loop { + let unfinished = unfinished_jobs(jobs).await; + let now = Instant::now(); + if unfinished == 0 { + let since = *idle_since.get_or_insert(now); + if now.duration_since(since) >= LINGER { + return 0; + } + } else { + idle_since = None; + } + if now >= deadline { + return unfinished; + } + tokio::time::sleep(POLL.min(deadline - now)).await; + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use ballista_scheduler::cluster::memory::InMemoryJobState; + use datafusion::prelude::SessionConfig; + + fn job_state() -> InMemoryJobState { + InMemoryJobState::new( + "scheduler", + Arc::new(ballista_core::utils::default_session_builder), + Arc::new(SessionConfig::new), + ) + } + + #[test] + fn a_draining_scheduler_refuses_a_new_query_by_saying_so() { + let draining = Arc::new(AtomicBool::new(false)); + let builder: SessionBuilder = Arc::new(ballista_core::utils::default_session_builder); + let builder = refusing_while_draining(builder, Arc::clone(&draining)); + builder(SessionConfig::new()).expect("not draining yet"); + draining.store(true, Ordering::SeqCst); + let err = builder(SessionConfig::new()).unwrap_err().to_string(); + assert!(err.contains("shutting down"), "{err}"); + } + + // Real time, with the lower bounds exact and the upper ones loose: Tokio's + // paused clock needs its `test-util` feature, which this workspace does + // not build. + + /// A queued query holds the drain until the timeout, and the count says + /// so; once it is finished the drain ends after the linger. + #[tokio::test] + async fn the_drain_waits_for_an_unfinished_query_and_no_longer() { + let jobs = job_state(); + jobs.accept_job(&"job-1".into(), "q", 0).unwrap(); + assert_eq!(unfinished_jobs(&jobs).await, 1); + let started = Instant::now(); + assert_eq!(drain(&jobs, Duration::from_millis(400)).await, 1); + let waited = started.elapsed(); + assert!(waited >= Duration::from_millis(400), "{waited:?}"); + assert!(waited < Duration::from_secs(5), "{waited:?}"); + + jobs.fail_unscheduled_job(&"job-1".into(), "planning failed".to_owned()) + .await + .unwrap(); + assert_eq!( + unfinished_jobs(&jobs).await, + 0, + "a failed query is finished" + ); + let started = Instant::now(); + assert_eq!(drain(&jobs, Duration::from_secs(30)).await, 0); + let waited = started.elapsed(); + assert!(waited >= LINGER, "{waited:?}"); + assert!(waited < Duration::from_secs(10), "{waited:?}"); + } + + #[tokio::test] + async fn a_zero_drain_timeout_stops_at_once() { + let jobs = job_state(); + jobs.accept_job(&"job-1".into(), "q", 0).unwrap(); + let started = Instant::now(); + assert_eq!(drain(&jobs, Duration::ZERO).await, 1); + assert!(started.elapsed() < Duration::from_secs(1)); + } +} diff --git a/crates/oxidelake-runtime/src/worker_loss.rs b/crates/oxidelake-runtime/src/worker_loss.rs new file mode 100644 index 0000000..3b4b93e --- /dev/null +++ b/crates/oxidelake-runtime/src/worker_loss.rs @@ -0,0 +1,255 @@ +//! A query that loses a worker fails, naming the worker, instead of being +//! rolled back and run again (#148). +//! +//! When a worker goes (killed, stopped with `SIGTERM`, or silent past the +//! scheduler's `--worker-timeout`), Ballista 55 rolls back every stage that +//! read the worker's shuffle output and runs it again. That recovery is not +//! safe in 55.0.0: the rolled-back stage keeps its partial outputs, so some +//! rows can come back twice with exit 0 (fixed upstream by +//! apache/datafusion-ballista#2677, merged after 55.0.0 and not released), +//! and the tasks it cancels never return their slots, so the query can wait +//! for capacity that never comes back (see apache/datafusion-ballista#2539 +//! and #2698). Correctness comes first: a query that held output on a lost +//! worker fails instead, and says which worker it lost. +//! +//! Every way Ballista removes a worker passes through the cluster state's +//! `remove_executor`, and Ballista posts the event that starts the rollback +//! only after that returns. The cluster state calls [`WorkerLoss::lost`] +//! there, which puts a cancellation of each affected query ahead of the +//! rollback in the scheduler's event queue, and the job state then reports +//! this module's reason where Ballista would say "Cancelled". A query whose +//! tasks on that worker had not finished any (just launched, or a launch +//! that failed) is left to Ballista: nothing of theirs was kept, so no stage +//! is rolled back, and those tasks simply run again elsewhere. +//! +//! The other way Ballista meets a lost worker, a shuffle fetch from it +//! failing, happens before the worker is removed; `--stage-max-failures` +//! (default 1) decides that one. + +use std::collections::{HashSet, VecDeque}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; + +use async_trait::async_trait; +use ballista_core::error::Result; +use ballista_core::serde::protobuf::{JobStatus, SuccessfulTask, job_status, task_status}; +use ballista_core::{JobId, JobStatusSubscriber}; +use ballista_scheduler::cluster::memory::InMemoryJobState; +use ballista_scheduler::cluster::{JobState, JobStateEventStream}; +use ballista_scheduler::scheduler_server::SchedulerServer; +use ballista_scheduler::state::execution_graph::{ExecutionGraph, ExecutionGraphBox}; +use ballista_scheduler::state::execution_stage::ExecutionStage; +use datafusion::prelude::{SessionConfig, SessionContext}; +use datafusion_proto::protobuf::{LogicalPlanNode, PhysicalPlanNode}; + +/// The scheduler `oxide-scheduler` runs. +pub(crate) type Scheduler = SchedulerServer; + +/// How many failed queries' reasons are kept until their final status is +/// saved: bounded, so a reason whose query raced to an end of its own cannot +/// accumulate. +const REMEMBERED_REASONS: usize = 64; + +/// The tracking issue every message points to. +pub(crate) const ISSUE: &str = "#148"; + +/// Fails the queries a lost worker held output for (see the module docs). +#[derive(Default)] +pub(crate) struct WorkerLoss { + scheduler: OnceLock, + reasons: Mutex>, +} + +impl WorkerLoss { + /// Hands over the scheduler once it exists; until then a lost worker + /// cannot have held anything, and nothing is done. + pub(crate) fn attach(&self, scheduler: Scheduler) { + let _ = self.scheduler.set(scheduler); + } + + /// `worker` (reachable at `address`) is being removed: cancel every + /// running query that holds finished output on it, before Ballista's + /// rollback can run. + pub(crate) async fn lost(&self, worker: &str, address: &str) { + let Some(scheduler) = self.scheduler.get() else { + return; + }; + let jobs = scheduler.state.task_manager.get_running_job_cache(); + for (job_id, info) in jobs.iter() { + if !held_output(info.execution_graph.read().await.as_ref(), worker) { + continue; + } + let reason = format!( + "worker {worker} ({address}) was lost while this query ran, and it held shuffle \ + output the query still needed. OxideLake fails the query rather than let \ + Ballista 55 run those stages again: that recovery can return duplicated rows \ + or never finish ({ISSUE}). Run the query again" + ); + tracing::warn!(job = %job_id, "{reason}"); + self.remember(job_id.clone(), reason); + if let Err(err) = scheduler.cancel_job(job_id.clone()).await { + tracing::error!(job = %job_id, "could not fail the query: {err}"); + } + } + } + + fn remember(&self, job_id: JobId, reason: String) { + let mut reasons = self.reasons.lock().unwrap_or_else(PoisonError::into_inner); + if reasons.len() >= REMEMBERED_REASONS { + reasons.pop_front(); + } + reasons.push_back((job_id, reason)); + } + + /// Why this module failed `job_id`, once: the job state reports it in + /// place of Ballista's "Cancelled". + fn take_reason(&self, job_id: &JobId) -> Option { + let mut reasons = self.reasons.lock().unwrap_or_else(PoisonError::into_inner); + let index = reasons.iter().position(|(id, _)| id == job_id)?; + reasons.remove(index).map(|(_, reason)| reason) + } +} + +/// Whether a task of `graph` finished on `worker`, so that losing the worker +/// loses output a stage may read. +fn held_output(graph: &dyn ExecutionGraph, worker: &str) -> bool { + graph.stages().values().any(|stage| { + let tasks = match stage { + ExecutionStage::Running(stage) => &stage.task_infos, + ExecutionStage::Successful(stage) => &stage.task_infos, + _ => return false, + }; + tasks.iter().any(|task| { + matches!( + &task.task_status, + task_status::Status::Successful(SuccessfulTask { executor_id, .. }) + if executor_id == worker + ) + }) + }) +} + +fn is_failed(status: &JobStatus) -> bool { + matches!(status.status, Some(job_status::Status::Failed(_))) +} + +/// Ballista's in-memory job state, saving a query that [`WorkerLoss`] failed +/// with the reason it failed rather than "Cancelled". Everything else is +/// Ballista's own. +pub(crate) struct ReportingJobState { + inner: InMemoryJobState, + loss: Arc, +} + +impl ReportingJobState { + pub(crate) fn new(inner: InMemoryJobState, loss: Arc) -> Self { + Self { inner, loss } + } +} + +#[async_trait] +impl JobState for ReportingJobState { + fn accept_job(&self, job_id: &JobId, job_name: &str, queued_at: u64) -> Result<()> { + self.inner.accept_job(job_id, job_name, queued_at) + } + + fn pending_job_number(&self) -> usize { + self.inner.pending_job_number() + } + + async fn submit_job( + &self, + job_id: JobId, + graph: &ExecutionGraphBox, + subscriber: Option, + ) -> Result<()> { + self.inner.submit_job(job_id, graph, subscriber).await + } + + async fn get_jobs(&self) -> Result> { + self.inner.get_jobs().await + } + + async fn get_all_jobs(&self) -> Result> { + self.inner.get_all_jobs().await + } + + async fn get_job_status(&self, job_id: &JobId) -> Result> { + self.inner.get_job_status(job_id).await + } + + async fn get_execution_graph(&self, job_id: &JobId) -> Result> { + self.inner.get_execution_graph(job_id).await + } + + async fn save_job(&self, job_id: &JobId, graph: &ExecutionGraphBox) -> Result<()> { + if is_failed(graph.status()) + && let Some(reason) = self.loss.take_reason(job_id) + { + let mut graph = graph.cloned(); + graph.fail_job(reason); + return self.inner.save_job(job_id, &graph).await; + } + self.inner.save_job(job_id, graph).await + } + + async fn fail_unscheduled_job(&self, job_id: &JobId, reason: String) -> Result<()> { + self.inner.fail_unscheduled_job(job_id, reason).await + } + + async fn remove_job(&self, job_id: &JobId) -> Result<()> { + self.inner.remove_job(job_id).await + } + + async fn try_acquire_job(&self, job_id: &JobId) -> Result> { + self.inner.try_acquire_job(job_id).await + } + + async fn job_state_events(&self) -> Result { + self.inner.job_state_events().await + } + + async fn create_or_update_session( + &self, + session_id: &str, + config: &SessionConfig, + ) -> Result> { + self.inner + .create_or_update_session(session_id, config) + .await + } + + async fn remove_session(&self, session_id: &str) -> Result<()> { + self.inner.remove_session(session_id).await + } + + fn produce_config(&self) -> SessionConfig { + self.inner.produce_config() + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + #[test] + fn a_reason_is_given_once_and_the_kept_ones_are_bounded() { + let loss = WorkerLoss::default(); + loss.remember("job-1".into(), "lost w2".to_owned()); + assert_eq!( + loss.take_reason(&"job-1".into()).as_deref(), + Some("lost w2") + ); + assert_eq!(loss.take_reason(&"job-1".into()), None); + for i in 0..2 * REMEMBERED_REASONS { + loss.remember(format!("job-{i}").as_str().into(), format!("r{i}")); + } + assert_eq!(loss.reasons.lock().unwrap().len(), REMEMBERED_REASONS); + assert_eq!(loss.take_reason(&"job-0".into()), None, "the oldest went"); + let last = 2 * REMEMBERED_REASONS - 1; + assert!( + loss.take_reason(&format!("job-{last}").as_str().into()) + .is_some() + ); + } +} diff --git a/crates/oxidelake-runtime/tests/cli.rs b/crates/oxidelake-runtime/tests/cli.rs index 407e409..c813825 100644 --- a/crates/oxidelake-runtime/tests/cli.rs +++ b/crates/oxidelake-runtime/tests/cli.rs @@ -189,12 +189,36 @@ impl Drop for ClusterGuard { } } +/// A port on 127.0.0.1 that nothing listens on, for a process this test is +/// about to start. +/// +/// Not port 0's choice: the kernel hands out source ports for outgoing +/// connections from that same range (`ip_local_port_range`, 32768-60999 on +/// Linux, 49152 and up on macOS), so a port taken from there and released +/// was at times reused by some connection on a busy machine before the +/// worker meant to bind it had started, and the worker died with "Address +/// already in use" (twice under `make test`, 2026-11-18). Below that range +/// no one hands ports out but this function, which gives each call in this +/// binary a different one, from an offset in the process id so that two +/// test binaries running at once seldom meet, and checks it is free. fn free_port() -> u16 { - TcpListener::bind("127.0.0.1:0") - .unwrap() - .local_addr() - .unwrap() - .port() + use std::sync::atomic::{AtomicU32, Ordering}; + const LOW: u32 = 20_000; + const SPAN: u32 = 12_000; + static NEXT: AtomicU32 = AtomicU32::new(u32::MAX); + let _ = NEXT.compare_exchange( + u32::MAX, + std::process::id() % SPAN, + Ordering::SeqCst, + Ordering::SeqCst, + ); + for _ in 0..SPAN { + let port = u16::try_from(LOW + NEXT.fetch_add(1, Ordering::SeqCst) % SPAN).unwrap(); + if TcpListener::bind(("127.0.0.1", port)).is_ok() { + return port; + } + } + panic!("no free port in {LOW}..{}", LOW + SPAN) } fn wait_for_port(port: u16, what: &str) { @@ -825,6 +849,9 @@ struct TestCluster { dir: std::path::PathBuf, scheduler_port: u16, processes: Vec<(String, Child)>, + /// Each worker's Arrow Flight port, which is how a failed shuffle fetch + /// names the worker it could not reach. + flight_ports: Vec<(String, u16)>, } impl TestCluster { @@ -835,6 +862,7 @@ impl TestCluster { dir: dir.to_owned(), scheduler_port, processes: Vec::new(), + flight_ports: Vec::new(), }; let scheduler = StdCommand::new(env!("CARGO_BIN_EXE_oxide-scheduler")) .args([ @@ -880,6 +908,8 @@ impl TestCluster { /// for: a refused worker never opens its ports for long. fn spawn_worker(&mut self, name: &str, bin: &Path, args: &[&str]) -> usize { let work_dir = self.dir.join(format!("{name}-shuffle")); + let flight_port = free_port(); + self.flight_ports.push((name.to_owned(), flight_port)); let worker = StdCommand::new(bin) .args([ "--scheduler-host", @@ -887,7 +917,7 @@ impl TestCluster { "--scheduler-port", &self.scheduler_port.to_string(), "--port", - &free_port().to_string(), + &flight_port.to_string(), "--grpc-port", &free_port().to_string(), "--concurrent-tasks", @@ -943,6 +973,82 @@ impl TestCluster { } } +impl TestCluster { + /// Sends `signal` (`TERM`, `KILL`, …) to process `index`. + fn signal(&self, index: usize, signal: &str) { + let pid = self.processes[index].1.id().to_string(); + let sent = StdCommand::new("kill") + .args([&format!("-{signal}"), &pid]) + .status() + .unwrap(); + assert!(sent.success(), "kill -{signal} {pid}"); + } + + /// Waits until `name`'s log has a line `matches` accepts, up to `limit`. + fn wait_log(&self, name: &str, what: &str, limit: Duration, matches: impl Fn(&str) -> bool) { + let deadline = Instant::now() + limit; + while !self.log(name).lines().any(&matches) { + assert!( + Instant::now() < deadline, + "{name} never logged {what} within {limit:?}\n{}", + self.logs() + ); + std::thread::sleep(Duration::from_millis(20)); + } + } + + fn flight_port(&self, name: &str) -> u16 { + self.flight_ports + .iter() + .find_map(|(worker, port)| (worker == name).then_some(*port)) + .unwrap() + } + + /// `oxide sql --cluster` in the background, writing `/.out` + /// and `/.log`, for a query that is to be interrupted. + fn spawn_sql(&self, name: &str, query: &str, table_arg: &str) -> Child { + StdCommand::new(assert_cmd::cargo::cargo_bin("oxide")) + .args([ + "sql", + "-q", + query, + "--table", + table_arg, + "--cluster", + &self.url(), + ]) + .stdout(File::create(self.dir.join(format!("{name}.out"))).unwrap()) + .stderr(self.log_file(name)) + .spawn() + .unwrap() + } +} + +/// Reaps a background query (or kills it after `limit`), and returns whether +/// it succeeded with its stdout and stderr. +fn finish_sql( + cluster: &TestCluster, + name: &str, + mut child: Child, + limit: Duration, +) -> (bool, String, String) { + let status = wait_exit(&mut child, limit); + if status.is_none() { + let _ = child.kill(); + let _ = child.wait(); + } + let stdout = + std::fs::read_to_string(cluster.dir.join(format!("{name}.out"))).unwrap_or_default(); + let stderr = cluster.log(name); + let status = status.unwrap_or_else(|| { + panic!( + "`{name}` was still running after {limit:?}\n{stderr}\n{}", + cluster.logs() + ) + }); + (status.success(), stdout, stderr) +} + impl Drop for TestCluster { fn drop(&mut self) { for (_, process) in &mut self.processes { @@ -1114,6 +1220,493 @@ fn mixed_build_a_predict_worker_is_refused_by_a_default_scheduler() { assert!(started.elapsed() < Duration::from_secs(30)); } +// --- resilience: worker loss, retry limits, SIGTERM (#31) ------------------- + +/// A query slow enough to stop a process in the middle of: a self-join that +/// fans out on `k` (about 6,000 rows a key), whose `id` bound sets the work. +/// Ballista runs it in four stages, two scans, the join ([`JOIN_STAGE`]) and +/// the final aggregate, and the join's 16 tasks run in waves on two workers +/// of two tasks each, so a worker stopped as its first join task starts +/// leaves join tasks still to run that read its shuffle output. +fn slow_join(rows: u64) -> String { + format!( + "SELECT a.k, COUNT(*) AS n, SUM(a.v + b.v) AS sv FROM t a JOIN t b ON a.k = b.k \ + WHERE a.id < {rows} GROUP BY a.k ORDER BY a.k" + ) +} + +const JOIN_STAGE: usize = 3; + +/// Whether `line` is Ballista's executor starting a task of `stage` (its +/// first attempt): `Execute task : [TID /./.]`. +fn starts_stage(stage: usize) -> impl Fn(&str) -> bool { + let needle = format!("/{stage}.0/"); + move |line| line.contains("Execute task") && line.contains(&needle) +} + +fn embedded_sql(query: &str, table_arg: &str) -> String { + let assert = oxide() + .args(["sql", "-q", query, "--table", table_arg]) + .assert() + .success(); + String::from_utf8(assert.get_output().stdout.clone()).unwrap() +} + +fn this_worker() -> std::path::PathBuf { + std::path::PathBuf::from(env!("CARGO_BIN_EXE_oxide-worker")) +} + +/// The knobs are documented in the README tables, so they must be +/// discoverable from `--help` (#31). +#[test] +fn the_resilience_flags_appear_in_help() { + for (bin, flags) in [ + ( + "oxide-scheduler", + &[ + "--task-max-failures", + "--stage-max-failures", + "--worker-timeout", + "--drain-timeout", + ][..], + ), + ( + "oxide-worker", + &["--heartbeat-interval", "--drain-timeout"][..], + ), + ] { + let assert = Command::cargo_bin(bin) + .unwrap() + .arg("--help") + .assert() + .success(); + let help = String::from_utf8(assert.get_output().stdout.clone()).unwrap(); + for flag in flags { + assert!(help.contains(flag), "{bin} --help lacks {flag}\n{help}"); + } + } +} + +/// How a worker was lost, which decides what its query's error can say. +#[derive(Clone, Copy, PartialEq)] +enum Lost { + /// Stopped with `SIGTERM`: it keeps serving its shuffle data while it + /// drains, and OxideLake fails the query naming it. + Stopped, + /// Killed: a fetch from it fails and the error names its address, + /// unless it died in the middle of sending a shuffle block to a task + /// still running, when Ballista reports that broken stream instead + /// (`IpcError ... error reading a body from connection`). That error + /// carries no address, but it fails the stage at once, with no + /// rollback, so the query still fails cleanly (1 run in about 8 of the + /// silent-worker test, 2026-11-18). + Killed, +} + +/// What a client sees when a worker is lost in the middle of its query: +/// the query fails, prints no rows, and the error says why (#31, #148). +/// Then the next query runs on the workers left, with the right rows. +fn assert_the_query_fails_naming( + cluster: &TestCluster, + worker: &str, + how: Lost, + query: Child, + then: &str, +) { + let (succeeded, stdout, stderr) = finish_sql(cluster, "query", query, Duration::from_secs(120)); + assert!(!succeeded, "{stderr}\n{}", cluster.logs()); + assert_eq!(stdout, "", "no rows are printed for a failed query"); + let port = format!("127.0.0.1:{}", cluster.flight_port(worker)); + let broken_stream = how == Lost::Killed && stderr.contains("IpcError"); + assert!( + stderr.contains(&port) || broken_stream, + "the error names the lost worker, {port}:\n{stderr}" + ); + let table_arg = format!("t={}", cluster.dir.display()); + let output = cluster.sql(QUERY, &table_arg); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stderr), + cluster.logs() + ); + assert_eq!(String::from_utf8(output.stdout).unwrap(), then); +} + +/// A worker killed in the middle of a query (#31): with the scheduler's +/// defaults the query fails within seconds naming the worker it lost, +/// rather than running the lost work again (#148). +/// +/// The join tasks still to run cannot fetch the dead worker's shuffle +/// output; Ballista retries each fetch three times, three seconds apart, +/// then fails the stage, and the default `--stage-max-failures 1` makes +/// that the query's end. Ballista's 180-second wait on the dead worker's +/// heartbeat is far longer than that, so it never decides the outcome here. +#[test] +#[cfg(unix)] +fn a_query_that_loses_a_worker_fails_naming_it() { + let dir = tempfile::tempdir().unwrap(); + gen_data(dir.path(), 600_000); + let table_arg = format!("t={}", dir.path().display()); + let after = embedded_sql(QUERY, &table_arg); + + let mut cluster = TestCluster::start(dir.path(), "cpu", &[]); + cluster.spawn_worker("w1", &this_worker(), &[]); + let lost = cluster.spawn_worker("w2", &this_worker(), &[]); + cluster.wait_ready(2); + + let query = cluster.spawn_sql("query", &slow_join(200_000), &table_arg); + cluster.wait_log( + "w2", + "a join task", + Duration::from_secs(120), + starts_stage(JOIN_STAGE), + ); + cluster.signal(lost, "KILL"); + assert_the_query_fails_naming(&cluster, "w2", Lost::Killed, query, &after); +} + +/// A worker stopped with `SIGTERM` in the middle of a query (#31, #148): +/// the worker exits 0, and the query fails at once naming it. Ballista +/// would have rolled the query back and run the lost work again, which on +/// 55.0.0 hung in both runs tried; OxideLake fails the query before that +/// rollback can start. +#[test] +#[cfg(unix)] +fn a_query_whose_worker_stops_fails_naming_it() { + let dir = tempfile::tempdir().unwrap(); + gen_data(dir.path(), 600_000); + let table_arg = format!("t={}", dir.path().display()); + let after = embedded_sql(QUERY, &table_arg); + + let mut cluster = TestCluster::start(dir.path(), "cpu", &[]); + cluster.spawn_worker("w1", &this_worker(), &[]); + let stopped = cluster.spawn_worker("w2", &this_worker(), &[]); + cluster.wait_ready(2); + + let query = cluster.spawn_sql("query", &slow_join(200_000), &table_arg); + cluster.wait_log( + "w2", + "a join task", + Duration::from_secs(120), + starts_stage(JOIN_STAGE), + ); + cluster.signal(stopped, "TERM"); + let status = wait_exit(&mut cluster.processes[stopped].1, Duration::from_secs(60)) + .unwrap_or_else(|| panic!("the stopped worker did not exit\n{}", cluster.logs())); + assert_eq!(status.code(), Some(0), "{}", cluster.logs()); + assert_the_query_fails_naming(&cluster, "w2", Lost::Stopped, query, &after); + let stderr = cluster.log("query"); + assert!( + stderr.contains("was lost while this query ran") && stderr.contains("#148"), + "OxideLake's reason, not Ballista's \"Cancelled\":\n{stderr}" + ); +} + +/// A worker that goes silent in the middle of a query (#31, #148): once +/// `--worker-timeout` passes without its heartbeat the query fails naming +/// it, here before any shuffle fetch from it has run out of retries. With +/// Ballista's recovery the same run returned duplicated rows. +#[test] +#[cfg(unix)] +fn a_query_whose_worker_goes_silent_fails_naming_it() { + let dir = tempfile::tempdir().unwrap(); + gen_data(dir.path(), 600_000); + let table_arg = format!("t={}", dir.path().display()); + let after = embedded_sql(QUERY, &table_arg); + + let mut cluster = TestCluster::start(dir.path(), "cpu", &["--worker-timeout", "5"]); + cluster.spawn_worker("w1", &this_worker(), &["--heartbeat-interval", "1"]); + let lost = cluster.spawn_worker("w2", &this_worker(), &["--heartbeat-interval", "1"]); + cluster.wait_ready(2); + + let query = cluster.spawn_sql("query", &slow_join(200_000), &table_arg); + cluster.wait_log( + "w2", + "a join task", + Duration::from_secs(120), + starts_stage(JOIN_STAGE), + ); + cluster.signal(lost, "KILL"); + assert_the_query_fails_naming(&cluster, "w2", Lost::Killed, query, &after); +} + +/// What #31 asked for, and what Ballista 55.0.0 does not do: with stage +/// retries raised to Ballista's own default of 4, a query that loses a +/// worker should come back with exactly the rows it would have had. It +/// does not, which is why OxideLake's default is 1 (#148): the rolled-back +/// stage keeps its partial outputs, fixed upstream by +/// apache/datafusion-ballista#2677 (merged after 55.0.0, unreleased), and +/// the tasks the rollback cancels never return their slots, so a query can +/// wait for capacity that does not come back (see +/// apache/datafusion-ballista#2539 and #2698). Measured with this setup +/// (`kill -9` as the worker starts its first join task): 12 runs in 15 +/// returned the 100 groups plus 13 or 14 of them a second time, exit 0, +/// 7 of 8 from a shell loop and 5 of 7 of this test. Run by name to reproduce; it +/// fails when either happens, which is not every run. Remove the `ignore` +/// once the chain is on a Ballista with the fix. +#[test] +#[cfg(unix)] +#[ignore = "Ballista 55 can recover a query that lost a worker into duplicated rows (#148)"] +fn a_query_that_loses_a_worker_comes_back_with_the_right_rows() { + let dir = tempfile::tempdir().unwrap(); + gen_data(dir.path(), 600_000); + let table_arg = format!("t={}", dir.path().display()); + let query = slow_join(200_000); + let expected = embedded_sql(&query, &table_arg); + + let mut cluster = TestCluster::start(dir.path(), "cpu", &["--stage-max-failures", "4"]); + cluster.spawn_worker("w1", &this_worker(), &[]); + let lost = cluster.spawn_worker("w2", &this_worker(), &[]); + cluster.wait_ready(2); + let running = cluster.spawn_sql("query", &query, &table_arg); + cluster.wait_log( + "w2", + "a join task", + Duration::from_secs(120), + starts_stage(JOIN_STAGE), + ); + cluster.signal(lost, "KILL"); + let (succeeded, stdout, stderr) = + finish_sql(&cluster, "query", running, Duration::from_secs(300)); + assert!(succeeded, "{stderr}"); + assert_eq!(stdout, expected, "{}", cluster.logs()); +} + +/// `SIGTERM` stops a worker within its `--drain-timeout`, with exit 0 (#31). +/// An idle worker stops at once, and the scheduler stops counting it. A +/// worker running join tasks far longer than its timeout stops when the +/// timeout passes, leaving them to the scheduler; without the bound it +/// waited for them, however long they took. +#[test] +#[cfg(unix)] +fn sigterm_stops_a_worker_within_its_drain_timeout_with_exit_zero() { + let dir = tempfile::tempdir().unwrap(); + gen_data(dir.path(), 600_000); + let table_arg = format!("t={}", dir.path().display()); + let mut cluster = TestCluster::start(dir.path(), "cpu", &[]); + let idle = cluster.spawn_worker("idle", &this_worker(), &[]); + let busy = cluster.spawn_worker("busy", &this_worker(), &["--drain-timeout", "1"]); + cluster.wait_ready(2); + // Ballista's executor listens for the signal only once it is up, just + // after it has registered; the Flight server's line is its last step + // before that. A signal sent earlier is seen by OxideLake alone, and the + // worker then waits out its drain timeout (`run_executor_with_shutdown`). + cluster.wait_log("idle", "that it is up", Duration::from_secs(60), |line| { + line.contains("arrow flight server listening") + }); + std::thread::sleep(Duration::from_millis(300)); + + let started = Instant::now(); + cluster.signal(idle, "TERM"); + let status = wait_exit(&mut cluster.processes[idle].1, Duration::from_secs(20)) + .unwrap_or_else(|| panic!("an idle worker ignored SIGTERM\n{}", cluster.logs())); + assert_eq!(status.code(), Some(0), "{}", cluster.logs()); + assert!( + started.elapsed() < Duration::from_secs(10), + "{:?}", + started.elapsed() + ); + cluster.wait_ready(1); + + // Every row joins about 6,000 others: each of the 16 join tasks is a + // sixteenth of 3.6 billion rows, about five seconds on the machine this + // was written on, so a task outlasts the one-second bound with room. + let query = cluster.spawn_sql("query", &slow_join(600_000), &table_arg); + cluster.wait_log( + "busy", + "a join task", + Duration::from_secs(120), + starts_stage(JOIN_STAGE), + ); + let started = Instant::now(); + cluster.signal(busy, "TERM"); + let status = + wait_exit(&mut cluster.processes[busy].1, Duration::from_secs(30)).unwrap_or_else(|| { + panic!( + "a busy worker outlived its drain timeout\n{}", + cluster.logs() + ) + }); + let took = started.elapsed(); + assert_eq!(status.code(), Some(0), "{}", cluster.logs()); + assert!( + took >= Duration::from_secs(1) && took < Duration::from_secs(10), + "stopped after {took:?}\n{}", + cluster.log("busy") + ); + assert!( + cluster.log("busy").contains("drain timeout passed"), + "{}", + cluster.log("busy") + ); + // A worker draining in the middle of a query must not lead that query + // into Ballista's rollback (#148): the query fails at once, naming the + // worker, rather than waiting for one that is never coming back. + let (succeeded, stdout, stderr) = finish_sql(&cluster, "query", query, Duration::from_secs(60)); + assert!(!succeeded, "{stderr}"); + assert_eq!(stdout, "", "no rows are printed for a failed query"); + let port = format!("127.0.0.1:{}", cluster.flight_port("busy")); + assert!( + stderr.contains("was lost while this query ran") && stderr.contains(&port), + "{stderr}" + ); +} + +/// `SIGTERM` stops a scheduler gracefully (#31): a query sent from then on +/// is refused saying why, the query already running finishes with the right +/// rows, and the scheduler then exits 0. It used to die of the signal +/// (status 143) and take the running query with it. +#[test] +#[cfg(unix)] +fn sigterm_drains_a_scheduler_and_exits_zero() { + let dir = tempfile::tempdir().unwrap(); + gen_data(dir.path(), 600_000); + let table_arg = format!("t={}", dir.path().display()); + let query = slow_join(200_000); + let expected = embedded_sql(&query, &table_arg); + + let mut cluster = TestCluster::start(dir.path(), "cpu", &["--drain-timeout", "120"]); + cluster.spawn_worker("w1", &this_worker(), &[]); + cluster.spawn_worker("w2", &this_worker(), &[]); + cluster.wait_ready(2); + let running = cluster.spawn_sql("running", &query, &table_arg); + cluster.wait_log( + "scheduler", + "the query's job", + Duration::from_secs(120), + |line| line.contains("Job submitted"), + ); + cluster.signal(0, "TERM"); + cluster.wait_log( + "scheduler", + "that it is shutting down", + Duration::from_secs(20), + |line| line.contains("shutting down") && line.contains("running=1"), + ); + + let refused = cluster.sql("SELECT COUNT(*) FROM t", &table_arg); + let stderr = String::from_utf8_lossy(&refused.stderr); + assert!(!refused.status.success(), "{stderr}"); + assert!(stderr.contains("shutting down"), "{stderr}"); + + let (succeeded, stdout, stderr) = + finish_sql(&cluster, "running", running, Duration::from_secs(120)); + assert!(succeeded, "{stderr}\n{}", cluster.logs()); + assert_eq!(stdout, expected); + let status = wait_exit(&mut cluster.processes[0].1, Duration::from_secs(30)) + .unwrap_or_else(|| panic!("the scheduler did not exit\n{}", cluster.logs())); + assert_eq!(status.code(), Some(0), "{}", cluster.logs()); + assert!( + cluster + .log("scheduler") + .contains("every running query finished"), + "{}", + cluster.log("scheduler") + ); +} + +/// `--worker-timeout` and `--heartbeat-interval` reach the processes (#31): +/// a worker killed while idle stops counting once the timeout passes, and +/// the live one, heartbeating more often than that, keeps counting. With +/// Ballista's 60-second heartbeat the live one would be presumed lost too; +/// with its 180-second timeout the dead one would still count. The timeout +/// is five heartbeats, not two: Ballista keeps heartbeat times in whole +/// seconds, and this test shares the machine with joins. +#[test] +#[cfg(unix)] +fn a_silent_worker_stops_counting_after_the_worker_timeout() { + let dir = tempfile::tempdir().unwrap(); + let mut cluster = TestCluster::start(dir.path(), "cpu", &["--worker-timeout", "5"]); + cluster.spawn_worker("w1", &this_worker(), &["--heartbeat-interval", "1"]); + let lost = cluster.spawn_worker("w2", &this_worker(), &["--heartbeat-interval", "1"]); + cluster.wait_ready(2); + let killed = Instant::now(); + cluster.signal(lost, "KILL"); + cluster.wait_ready(1); + assert!( + killed.elapsed() < Duration::from_secs(20), + "{:?}", + killed.elapsed() + ); + // Twice the timeout later, the live worker still counts. + std::thread::sleep(Duration::from_secs(10)); + let body = http_get(cluster.scheduler_port, "/readyz").unwrap_or_default(); + assert!( + body.contains("ready: 1 executors registered"), + "{body}\n{}", + cluster.logs() + ); +} + +// --- where cluster processes may listen (#30) ------------------------------- + +/// A scheduler or worker asked to listen on a public address, or on every +/// address, without `--allow-insecure-bind` refuses before it listens, and +/// says what to do (#30). The ports are unauthenticated, so this is the +/// whole of the security boundary until OxideLake has TLS and auth. +/// +/// Port 1 keeps a regression from exposing anything while this runs: an +/// unprivileged process cannot bind it, so a scheduler that skipped the +/// check would fail on the bind, with another message, instead of +/// listening on every interface. +#[test] +fn a_public_or_wildcard_listener_is_refused_without_the_flag() { + let refusals = [ + ( + "oxide-scheduler", + &["--bind-host", "0.0.0.0", "--port", "1"][..], + ), + ("oxide-scheduler", &["--bind-host", "::", "--port", "1"][..]), + ( + "oxide-scheduler", + &["--bind-host", "203.0.113.7", "--port", "1"][..], + ), + ( + "oxide-scheduler", + &[ + "--port", + "1", + "--metrics-port", + "1", + "--metrics-host", + "0.0.0.0", + ][..], + ), + ( + "oxide-worker", + &["--bind-host", "0.0.0.0", "--port", "1", "--grpc-port", "1"][..], + ), + ( + "oxide-worker", + &["--metrics-port", "1", "--metrics-host", "203.0.113.7"][..], + ), + ]; + for (bin, args) in refusals { + let assert = Command::cargo_bin(bin) + .unwrap() + .args(args) + .timeout(Duration::from_secs(30)) + .assert() + .failure(); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).unwrap(); + assert!( + stderr.contains("--allow-insecure-bind") && stderr.contains("no authentication"), + "{bin} {args:?}: {stderr}" + ); + } + for bin in ["oxide-scheduler", "oxide-worker"] { + let assert = Command::cargo_bin(bin) + .unwrap() + .arg("--help") + .assert() + .success(); + let help = String::from_utf8(assert.get_output().stdout.clone()).unwrap(); + assert!(help.contains("--allow-insecure-bind"), "{bin}\n{help}"); + assert!(help.contains("--bind-host"), "{bin}\n{help}"); + } +} + /// `gen-data --special-floats` writes every IEEE special value into `v`, and /// a Float64 filter over them returns the same rows planned for the CPU /// (DataFusion's own `FilterExec`) as for CUDA (`GpuFilterExec`: the CPU diff --git a/docs/verification.md b/docs/verification.md index 63d374e..7530ea4 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -186,6 +186,7 @@ OXIDE_BACKEND=cuda cargo test -p oxidelake-compute --features cuda -- --ignored | TUI saved screens | `oxidelake-tui/tests/termlens_cli.rs` | `termlens-cli` on the committed `.snap` files — `render`, and `diff`'s 0/1/2 exit codes (`#[ignore]`d; `make test-termlens-cli`) | | Shipped TUI binary | `oxidelake-runtime/tests/oxide_tui_pty.rs` | `oxide tui` in a PTY: the same frame `oxidelake-tui` snapshots, and no log line on the grid | | CLI end-to-end | `oxidelake-runtime/tests/cli.rs` | `assert_cmd` on `oxide` — `gen-data` output verified by an independent `parquet`-crate read; spawned `oxide-scheduler` + `oxide-worker` must print byte-identical `--cluster` results | +| Resilience | `oxidelake-runtime/tests/cli.rs` | real processes and signals: `SIGTERM` drains a scheduler (new query refused, running one equal to embedded, exit 0) and stops a worker within `--drain-timeout` (exit 0); a worker killed, stopped or silent mid-query fails its query with no rows, naming the worker (or, killed mid-transfer, the broken stream), and the next query is right (#148); `--worker-timeout`/`--heartbeat-interval` decide who counts. Recovery with retries raised is `#[ignore]`d: Ballista 55 gets it wrong (#148) | | Mixed builds | `oxidelake-runtime/tests/cli.rs` | a real `oxide-scheduler` refuses a worker whose plan fingerprint is not its own, and a query then fails at once naming it; with `make test-mixed-build`, a `--features cuda` worker runs a default scheduler's GPU plans and a `--features predict` one is refused (`#[ignore]`d otherwise) | ## Updating STATUS.md