From 43c88b63e9dbf09fd3b4fbd447bdf8374019560c Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:50:22 +0700 Subject: [PATCH 1/8] feat(runtime): drain on SIGTERM and expose Ballista's retry limits (#31) Verified on this branch (Ballista 55.0.0, static planner per #134), real binaries on 127.0.0.1: - `kill -TERM` on oxide-scheduler: status 143, every running query lost. Ballista's scheduler installs no handler (axum::serve, no shutdown). - `kill -TERM` on oxide-worker: exit 0. Ballista's executor already fences itself, tells the scheduler (which re-runs its tasks elsewhere) and waits for its tasks, but with no bound: a task that does not finish keeps the worker up until it is killed. The issue's "no signal handler" is true of the scheduler only. - No flag reached task_max_failures, stage_max_failures, the executor timeout or the heartbeat interval. Changes: - `shutdown` module: ShutdownSignal (SIGTERM/SIGINT, listening from startup so an early signal is held), Stopped { Drained, Abandoned }. - `cluster::run_scheduler_with_shutdown`: on the signal, new queries fail in the session builder ("this scheduler is shutting down ..."; it is called for every query and nothing a running one needs), the running ones are waited for up to --drain-timeout by polling the job state, plus a one-second linger so their clients hear they finished; then exit 0. - `cluster::run_executor_with_shutdown`: Ballista's own graceful stop, bounded by --drain-timeout; past it the worker exits 0 at once (process::exit: dropping the runtime would wait for the tasks). A second signal stops either at once. - Scheduler flags --task-max-failures, --stage-max-failures (0 refused, 1 = no retry), --worker-timeout (cluster::with_worker_timeout also sets Ballista's dead-worker check to a third of it, at most 15 s, and the no-worker grace to it, as Ballista's binary does), --drain-timeout (20). Worker flags --heartbeat-interval and --drain-timeout (20). Defaults are Ballista's (unit-tested), so a deployment that sets none is unchanged. Worker loss, measured (2 cpu workers x 2 tasks, 600k-row fixture, self-join on k, `kill -9` as the victim starts its first join task): - With Ballista's defaults the query came back WRONG in 9 of 12 runs (7 of 8 from a shell loop, 2 of 4 of the committed test): the 100 groups plus 13 of them again (two hash partitions twice), exit 0; the same query without a kill is byte-equal to embedded. - A rollback leaks the survivors' task slots: a cancelled task's status arrives once its stage is UnResolved, sum_vcores_for_statuses refunds 0 for it, and with no slot left the query waits for a new worker (one run: 670 s, ended when I started one). SIGTERM on a worker mid-query takes the same path: 2 of 2 runs hung. - With --stage-max-failures 1 the first failed fetch (Ballista retries it 3 times, 3 s apart) fails the query before any rollback, naming the worker's address; the next query runs on the worker left. Both bugs are in Ballista's scheduler, outside our hooks, so this documents them (README Cluster mode, STATUS decision, CHANGELOG known issue) and recommends --stage-max-failures 1 and stopping workers between queries. Tests (tests/cli.rs, real processes and signals, all on 127.0.0.1): - sigterm_drains_a_scheduler_and_exits_zero: a new query is refused naming the shutdown, the running join finishes equal to embedded, exit 0. - sigterm_stops_a_worker_within_its_drain_timeout_with_exit_zero: idle worker exits 0 at once and stops counting; a busy one with --drain-timeout 1 exits 0 after 1..10 s, logging the timeout. - a_query_that_loses_a_worker_fails_naming_it_when_stage_retries_are_off. - a_silent_worker_stops_counting_after_the_worker_timeout (a 5 s timeout over a 1 s heartbeat: Ballista keeps heartbeat times in whole seconds). - a_query_that_loses_a_worker_comes_back_with_the_right_rows: what the issue asked for; #[ignore]d as the reproduction of the Ballista bug (fails in about half its runs, not every one). - the_resilience_flags_appear_in_help; unit tests for the drain, the refusal, and the flags reaching SchedulerConfig. Broken to watch each go red: no drain bound (busy worker: no timeout line), draining never set (the new query ran), no drain wait (scheduler gone before the refusal), --stage-max-failures not applied (the query "recovered"), --heartbeat-interval not applied (live worker expired too: not ready 0/1), --worker-timeout not applied (dead worker still counted). Refs #148 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 19 + README.md | 10 + STATUS.md | 3 +- .../src/bin/oxide_scheduler.rs | 124 +++++- .../oxidelake-runtime/src/bin/oxide_worker.rs | 30 +- crates/oxidelake-runtime/src/cluster.rs | 174 +++++++- crates/oxidelake-runtime/src/lib.rs | 1 + crates/oxidelake-runtime/src/shutdown.rs | 231 +++++++++++ crates/oxidelake-runtime/tests/cli.rs | 388 +++++++++++++++++- docs/verification.md | 1 + 10 files changed, 960 insertions(+), 21 deletions(-) create mode 100644 crates/oxidelake-runtime/src/shutdown.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 494997a..c87d255 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,25 @@ 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 each) and `--worker-timeout` (seconds a silent worker still + counts, 180), and worker flag `--heartbeat-interval` (60); the defaults + are Ballista's, so a deployment that sets none behaves as before. **Known + issue, not fixed here:** on Ballista 55 a query that loses a worker in the + middle, killed or stopped, can return some groups twice with exit 0, or + wait until a new worker joins. Run the scheduler with + `--stage-max-failures 1`, which turns the common case into an error naming + the lost worker, and stop workers between queries (README, Cluster mode). + - **`operator_stats()` on `GpuFilterExec`, `GpuHashJoinExec`, `GpuAggregateExec` and `GpuVectorDistanceExec`** returns the counters that exec instance has reported to its telemetry hub (`None` before it diff --git a/README.md b/README.md index 9dfbc2c..ff7e98a 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,10 @@ 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, its scheduler runs the tasks it had elsewhere, and it exits 0 once they finish or `--drain-timeout` passes; keep that 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, then runs the stage again, up to `--stage-max-failures` times. 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`. + +**Ballista 55 does not recover a query from a lost worker reliably** (#31). With a worker killed, or stopped with `SIGTERM`, in the middle of a join, most of our runs either returned some groups twice, with exit 0, or never finished until a new worker joined, because the rollback loses track of the surviving workers' task slots. Until that is fixed upstream, run `oxide-scheduler --stage-max-failures 1`, which turns the common case, a failed fetch from the lost worker, into an error naming it; stop and restart workers between queries, not during them; and treat a query that ran while a worker was lost as suspect. + ### DataFrame API ```rust @@ -200,6 +204,10 @@ error, never a silent fallback. | `--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` | `4` | Times a stage may run again because a shuffle fetch failed, its input lost with a worker; `1` means no retry, and is the safe setting on Ballista 55 ([Cluster mode](#cluster-mode)). Ballista's `stage_max_failures`. | +| `--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` @@ -212,6 +220,8 @@ error, never a silent fallback. | `--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. | | `--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/STATUS.md b/STATUS.md index 0fd4d42..6ebbf70 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; with `--stage-max-failures 1` a worker killed mid-query fails the query naming it and the next query runs on the worker left; 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: Ballista 55 returns duplicated rows or hangs (#31, `#[ignore]`d reproduction in `tests/cli.rs`) | | 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` | | | @@ -91,6 +91,7 @@ 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: 9 of 12 runs (7 of 8 from a shell loop, 2 of 4 of the committed test) returned the 100 groups plus 13 of them again (two 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, outside OxideLake's hooks, so 0.3.0 documents them and recommends `--stage-max-failures 1`: a fetch from the lost worker then fails the query, naming it, before any rollback, and Ballista's 180-second heartbeat timeout is too slow to act first. The test of the recovery the issue asked for is committed `#[ignore]`d as the reproduction. 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/bin/oxide_scheduler.rs b/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs index 2f7f556..7ea919f 100644 --- a/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs +++ b/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs @@ -1,8 +1,12 @@ //! `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::shutdown::ShutdownSignal; use tracing_subscriber::EnvFilter; #[derive(Parser)] @@ -30,6 +34,53 @@ struct Cli { /// Address the metrics endpoint binds to. #[arg(long, default_value = "127.0.0.1", value_name = "HOST")] metrics_host: String, + /// 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 run again because a shuffle fetch failed, its input + /// lost with a worker, before its query fails; 1 means no retry + /// (Ballista's `stage_max_failures`). + #[arg(long, default_value_t = 4, 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 +94,10 @@ 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()?; + let target: BackendKind = match &cli.cluster_backend { Some(name) => name.parse()?, None => oxidelake_planner::cluster_target_from_env()?, }; @@ -55,7 +109,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 +151,64 @@ 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, so this changes nothing for a + /// scheduler that does not ask. + #[test] + fn the_defaults_are_ballistas() { + let ballista = SchedulerConfig::default(); + let config = config(&parse(&[]).unwrap(), BackendKind::CpuSimd); + assert_eq!(config.task_max_failures, ballista.task_max_failures); + assert_eq!(config.stage_max_failures, ballista.stage_max_failures); + 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..fec3f5d 100644 --- a/crates/oxidelake-runtime/src/bin/oxide_worker.rs +++ b/crates/oxidelake-runtime/src/bin/oxide_worker.rs @@ -1,8 +1,11 @@ //! `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::shutdown::{ShutdownSignal, Stopped}; use tracing_subscriber::EnvFilter; #[derive(Parser)] @@ -44,6 +47,16 @@ struct Cli { /// Address the metrics endpoint binds to. #[arg(long, default_value = "127.0.0.1", value_name = "HOST")] metrics_host: String, + /// 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 +70,9 @@ 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()?; // 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 +86,23 @@ 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; + 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..e2f9f8e 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,8 +28,8 @@ 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_server::SessionBuilder; @@ -50,6 +54,7 @@ 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}; fn ballista_error(err: impl std::fmt::Display) -> EngineError { EngineError::execution(format!("ballista: {err}")) @@ -266,6 +271,53 @@ pub fn scheduler_config(bind_host: &str, port: u16, target: BackendKind) -> Sche } } +/// 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 cluster = same_build_cluster(&config, Arc::clone(&draining)); + let jobs = cluster.job_state(); + Ok(Self { + serve: Box::pin(start_server(cluster, address, Arc::new(config))), + jobs, + draining, + }) + } +} + /// Runs a Ballista scheduler until it exits. /// /// The scheduler admits only workers of its own build (#92): one whose plan @@ -273,19 +325,68 @@ 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 { +/// state, with the cluster state admitting only workers of this build, 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) -> BallistaCluster { let state = Arc::new(SameBuildClusterState::default()); let session_builder = config .override_session_builder @@ -297,9 +398,9 @@ 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, ); @@ -358,6 +459,51 @@ 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. +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/lib.rs b/crates/oxidelake-runtime/src/lib.rs index b6f4e3a..9ed0d7e 100644 --- a/crates/oxidelake-runtime/src/lib.rs +++ b/crates/oxidelake-runtime/src/lib.rs @@ -13,6 +13,7 @@ pub mod dashboard; pub mod metrics; pub mod output; pub mod session; +pub mod shutdown; 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/tests/cli.rs b/crates/oxidelake-runtime/tests/cli.rs index 18de6b6..eb2f478 100644 --- a/crates/oxidelake-runtime/tests/cli.rs +++ b/crates/oxidelake-runtime/tests/cli.rs @@ -791,6 +791,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 { @@ -801,6 +804,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([ @@ -846,6 +850,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", @@ -853,7 +859,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", @@ -909,6 +915,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 { @@ -1079,3 +1161,307 @@ fn mixed_build_a_predict_worker_is_refused_by_a_default_scheduler() { assert!(stderr.contains("no worker it can use"), "{stderr}"); 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}"); + } + } +} + +/// A worker killed in the middle of a query, with stage retries off (#31): +/// the query fails within seconds naming the worker it lost, rather than +/// waiting for it, and the next query runs on the worker that is left. +/// +/// 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 `--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_when_stage_retries_are_off() { + 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", &["--stage-max-failures", "1"]); + 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"); + let (succeeded, _, stderr) = finish_sql(&cluster, "query", query, Duration::from_secs(120)); + assert!(!succeeded, "{stderr}"); + assert!(stderr.contains("has failed 1 times"), "{stderr}"); + let port = format!("127.0.0.1:{}", cluster.flight_port("w2")); + assert!( + stderr.contains(&port), + "the error names the lost worker, {port}:\n{stderr}" + ); + + 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(), after); +} + +/// What #31 asked for, and what Ballista 55 does not do: a query that loses +/// a worker while retries are allowed should come back with exactly the rows +/// it would have had. Run here (Ballista 55.0.0, the static planner #134 +/// requires, kill -9 as the worker starts its first join task), 9 runs in +/// 12 returned the 100 groups plus 13 of them a second time, exit 0: 7 of 8 +/// from a shell loop, 2 of 4 of this test. A lost worker's rollback can also +/// leave a surviving worker's task slots unreturned, so a query waits until +/// fresh capacity joins. Run by name to reproduce; it fails when either +/// happens, which is not every run. +#[test] +#[cfg(unix)] +#[ignore = "Ballista 55 can recover a query that lost a worker into duplicated rows (#31)"] +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", &[]); + 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); + + 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") + ); + // The query has no worker left; it is not what this test is about. + let mut query = query; + let _ = query.kill(); + let _ = query.wait(); +} + +/// `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() + ); +} diff --git a/docs/verification.md b/docs/verification.md index 2e22c87..52c7b05 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 `kill -9`ed mid-query under `--stage-max-failures 1` fails the query naming it; `--worker-timeout`/`--heartbeat-interval` decide who counts. Recovery with retries is `#[ignore]`d: Ballista 55 gets it wrong (#31) | | 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 From 190434c12198b1b14efb36379542206c4d4e5055 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:55:00 +0700 Subject: [PATCH 2/8] fix(runtime): refuse a cluster listener beyond a private network (#30) Verified on this branch: `oxide-scheduler --bind-host 0.0.0.0` started and listened on every interface without a word, although its port, like the workers', has no authentication or encryption (SECURITY.md: whoever connects can run queries that read any file a worker can read). The same held for --metrics-host. oxide-worker had no --bind-host at all: it listened where Ballista's ExecutorProcessConfig default puts it, 127.0.0.1, so a scheduler on another machine could not reach it. The first half of the issue, the enforced private-network posture; TLS and authentication are not built (see below), so #30 stays open for them. - `exposure` module: an address is Loopback, Private (RFC 1918, IPv6 unique-local, link-local; IPv4-mapped IPv6 judged as its IPv4) or Public (anything else, 0.0.0.0 and :: included, and the carrier-shared 100.64/10). check_listen_address refuses Public unless --allow-insecure-bind, judges a hostname by the widest address it resolves to, and refuses one that does not resolve. A bracketed IPv6 host ([::1]), the way the scheduler's and Ballista's `host:port` parsing needs one written, is judged without its brackets (broken once: [::1] was refused as a name that does not resolve). - oxide-scheduler and oxide-worker check --bind-host, and --metrics-host when --metrics-port is set, before anything listens, exit 1 naming the risk and the two ways out, and warn at startup whenever they listen beyond loopback. oxide-worker gains --bind-host (default 127.0.0.1, as before) under the same rule. - README (flag tables and a "Production deployments" paragraph) and SECURITY.md (trust model, the same paragraph word for word), CHANGELOG (Security), STATUS (decision). After: `oxide-scheduler --bind-host 0.0.0.0` exits 1 at once with "--bind-host 0.0.0.0 would listen where any network that routes to it can connect, and OxideLake's cluster ports have no authentication or encryption ... pass --allow-insecure-bind if a firewall or an authenticating proxy already decides who can connect (SECURITY.md)". Tests: a_public_or_wildcard_listener_is_refused_without_the_flag (assert_cmd: scheduler 0.0.0.0, ::, 203.0.113.7, public --metrics-host; worker 0.0.0.0 and public --metrics-host; both --help name the flag). Every case passes --port 1, which an unprivileged process cannot bind, so a regression fails on the bind instead of listening anywhere. Broken once (the check never refuses): red, the scheduler reached the bind and failed with "Permission denied". Unit tests classify the range edges (172.15/172.32, 192.169, 100.64, mapped addresses) and check the flag. No test listens beyond 127.0.0.1. Not done, proposed for the rest of #30: Ballista 55 can make its clients speak TLS (ballista.client.use_tls, plus an endpoint override for certificates) but serves the scheduler's port and the executors' gRPC port in plain text with no hook; only the executors' Flight service can be replaced. TLS therefore needs either an upstream server-side TLS option (tonic's ServerTlsConfig on create_grpc_server and the scheduler's listener) or a terminating proxy per port, with every OxideLake process told to dial TLS (use_tls on clients, the scheduler's use_tls for its proxy, the endpoint override for a private CA), tested against a local mTLS-terminating proxy. Refs #30 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 14 ++ README.md | 9 +- SECURITY.md | 16 +- STATUS.md | 3 +- .../src/bin/oxide_scheduler.rs | 21 +- .../oxidelake-runtime/src/bin/oxide_worker.rs | 25 ++- crates/oxidelake-runtime/src/exposure.rs | 197 ++++++++++++++++++ crates/oxidelake-runtime/src/lib.rs | 1 + crates/oxidelake-runtime/tests/cli.rs | 68 ++++++ 9 files changed, 342 insertions(+), 12 deletions(-) create mode 100644 crates/oxidelake-runtime/src/exposure.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index c87d255..c1e88cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -636,6 +636,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/README.md b/README.md index ff7e98a..c455145 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,8 @@ A scheduler admits only workers of its own build: the same OxideLake release, bu `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, its scheduler runs the tasks it had elsewhere, and it exits 0 once they finish or `--drain-timeout` passes; keep that 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, then runs the stage again, up to `--stage-max-failures` times. 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. + **Ballista 55 does not recover a query from a lost worker reliably** (#31). With a worker killed, or stopped with `SIGTERM`, in the middle of a join, most of our runs either returned some groups twice, with exit 0, or never finished until a new worker joined, because the rollback loses track of the surviving workers' task slots. Until that is fixed upstream, run `oxide-scheduler --stage-max-failures 1`, which turns the common case, a failed fetch from the lost worker, into an error naming it; stop and restart workers between queries, not during them; and treat a query that ran while a worker was lost as suspect. ### DataFrame API @@ -200,7 +202,8 @@ 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. | @@ -214,11 +217,13 @@ error, never a silent fallback. | 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. | diff --git a/SECURITY.md b/SECURITY.md index 91d4ff1..6069696 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -90,12 +90,16 @@ 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. + - **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 6ebbf70..8da21b9 100644 --- a/STATUS.md +++ b/STATUS.md @@ -91,7 +91,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: 9 of 12 runs (7 of 8 from a shell loop, 2 of 4 of the committed test) returned the 100 groups plus 13 of them again (two 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, outside OxideLake's hooks, so 0.3.0 documents them and recommends `--stage-max-failures 1`: a fetch from the lost worker then fails the query, naming it, before any rollback, and Ballista's 180-second heartbeat timeout is too slow to act first. The test of the recovery the issue asked for is committed `#[ignore]`d as the reproduction. 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. +- **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: 9 of 12 runs (7 of 8 from a shell loop, 2 of 4 of the committed test) returned the 100 groups plus 13 of them again (two 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, outside OxideLake's hooks, so 0.3.0 documents them and recommends `--stage-max-failures 1`: a fetch from the lost worker then fails the query, naming it, before any rollback, and Ballista's 180-second heartbeat timeout is too slow to act first. The test of the recovery the issue asked for is committed `#[ignore]`d as the reproduction. +- **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/bin/oxide_scheduler.rs b/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs index 7ea919f..fc8e1fb 100644 --- a/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs +++ b/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs @@ -6,6 +6,7 @@ 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; @@ -16,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. @@ -31,9 +35,15 @@ 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. @@ -97,6 +107,13 @@ async fn main() -> anyhow::Result<()> { // 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()?, diff --git a/crates/oxidelake-runtime/src/bin/oxide_worker.rs b/crates/oxidelake-runtime/src/bin/oxide_worker.rs index fec3f5d..5836720 100644 --- a/crates/oxidelake-runtime/src/bin/oxide_worker.rs +++ b/crates/oxidelake-runtime/src/bin/oxide_worker.rs @@ -5,6 +5,7 @@ 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; @@ -21,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, @@ -44,9 +53,15 @@ 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. @@ -73,6 +88,13 @@ async fn main() -> anyhow::Result<()> { // 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. @@ -95,6 +117,7 @@ async fn main() -> anyhow::Result<()> { cli.work_dir, ); 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?; 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 9ed0d7e..a36c2a9 100644 --- a/crates/oxidelake-runtime/src/lib.rs +++ b/crates/oxidelake-runtime/src/lib.rs @@ -9,6 +9,7 @@ mod admission; pub mod cluster; pub mod dashboard; +pub mod exposure; #[cfg(feature = "metrics")] pub mod metrics; pub mod output; diff --git a/crates/oxidelake-runtime/tests/cli.rs b/crates/oxidelake-runtime/tests/cli.rs index eb2f478..3922c70 100644 --- a/crates/oxidelake-runtime/tests/cli.rs +++ b/crates/oxidelake-runtime/tests/cli.rs @@ -1465,3 +1465,71 @@ fn a_silent_worker_stops_counting_after_the_worker_timeout() { 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}"); + } +} From 81fe0ede7d29cf28bc837a2919c98630ec0a1fd3 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:43:51 +0700 Subject: [PATCH 3/8] fix(runtime): stop retrying a stage whose worker was lost (#148) Ballista 55's recovery from a lost worker rolls back every stage that read the worker's shuffle output and runs it again, and in 55.0.0 that recovery returns duplicated rows with exit 0 (fixed upstream by apache/datafusion-ballista#2677, merged 2026-10-28, unreleased) or never finishes (the tasks the rollback cancels never return their slots; see apache/datafusion-ballista#2539 and #2698). Decision for 0.3.0: correctness over availability. Reproduction (this branch before this commit; debug build, deps at -O2): - fixture: `oxide gen-data --rows 600000 --row-group-rows 4096 --out D` (seed 42, zstd: D/t.parquet, 12,301,854 bytes, 16 scan partitions). - cluster on 127.0.0.1: `OXIDE_CLUSTER_BACKEND=cpu oxide-scheduler --port P` and two `oxide-worker --scheduler-host 127.0.0.1 --scheduler-port P --port F --grpc-port G --concurrent-tasks 2 --work-dir W`, RUST_LOG=info. - query: `oxide sql --cluster df://127.0.0.1:P --table t=D -q "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 < 200000 GROUP BY a.k ORDER BY a.k"` (four stages: 1 and 2 scan, 3 joins, 4 aggregates; embedded prints 100 groups, 104 lines). - the kill: `kill -9` on the second worker as soon as its log shows its first join task, `Execute task : [TID /3.0/.0]`, polled every 20 ms. - with Ballista's stage_max_failures 4: 12 of 15 runs (7 of 8 from a shell loop, 5 of 7 of the test) printed the 100 sorted groups plus 13 or 14 of them again (whole hash partitions twice), exit 0. The same query with no kill is byte-equal to embedded. - with --worker-timeout 10 and --heartbeat-interval 1 one run waited 670 s, until I started a third worker: the cancelled join task's status was "Ignored ... as the Stage ... is in UnResolved status", so sum_vcores_for_statuses refunded its slot to nobody. - `kill -TERM` instead of -9 hung in 2 of 2 runs, and still hung (150 s) with --stage-max-failures 1. Change: --stage-max-failures defaults to 1 (cluster::DEFAULT_STAGE_MAX_ FAILURES, also in cluster::scheduler_config). The first failed fetch from a lost worker, what usually happens first when a worker is killed, then fails the query, naming the worker's address. Ballista's own default is 4; an operator can raise it, and --help, README, SECURITY.md, STATUS and the CHANGELOG (Changed, with a migration line) say that brings the bug back. What this does NOT cover, said in the same places: only a failed fetch counts toward the limit. A worker stopped with SIGTERM, or silent past --worker-timeout, is rolled back through Ballista's ExecutorLost with count_to_failures = false, whatever the limit, so a query running then can still return duplicated rows or hang; the docs say to stop workers between queries. The next commit closes those paths. Tests: a_query_that_loses_a_worker_fails_naming_it now runs at the defaults (kill -9 as above): exit non-zero, empty stdout, the worker's Flight address in stderr ("Stage 3 has failed 1 times ... Error connecting to ... http://127.0.0.1:", about 11 s after the kill: Ballista retries the fetch 3 times, 3 s apart), and the next query equal to embedded. The #[ignore]d a_query_that_loses_a_worker_comes_back_with_the_ right_rows runs at --stage-max-failures 4 and points to #148 and apache/datafusion-ballista#2677; it failed 3 of 3 runs, as intended. The scheduler's unit test pins the default against Ballista's; set back to 4 it went red (left 4, right 1), and with the limit at 4 the kill test's query "recovered" instead of failing. Refs #148 Refs #31 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 26 ++++-- README.md | 6 +- SECURITY.md | 8 ++ STATUS.md | 4 +- .../src/bin/oxide_scheduler.rs | 27 ++++-- crates/oxidelake-runtime/src/cluster.rs | 17 +++- crates/oxidelake-runtime/tests/cli.rs | 84 +++++++++++-------- docs/verification.md | 2 +- 8 files changed, 116 insertions(+), 58 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c1e88cf..cdc1800 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,14 +20,10 @@ versions (0.x) may contain breaking changes; they are always listed under a 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 each) and `--worker-timeout` (seconds a silent worker still + 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, so a deployment that sets none behaves as before. **Known - issue, not fixed here:** on Ballista 55 a query that loses a worker in the - middle, killed or stopped, can return some groups twice with exit 0, or - wait until a new worker joins. Run the scheduler with - `--stage-max-failures 1`, which turns the common case into an error naming - the lost worker, and stop workers between queries (README, Cluster mode). + are Ballista's but for `--stage-max-failures`, which is 1 (#148, under + Changed). - **`operator_stats()` on `GpuFilterExec`, `GpuHashJoinExec`, `GpuAggregateExec` and `GpuVectorDistanceExec`** returns the counters @@ -464,6 +460,22 @@ 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 stage whose input was lost with 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). `--stage-max-failures` + now defaults to 1, so a failed fetch from a lost worker, what usually + happens first when a worker is killed, fails the query naming the worker. + It does not cover a worker that is stopped or goes silent mid-query: + Ballista rolls those back whatever the limit, so stop workers between + queries. **Migration:** a query that used to survive a killed 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). diff --git a/README.md b/README.md index c455145..73417f9 100644 --- a/README.md +++ b/README.md @@ -131,11 +131,11 @@ 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, its scheduler runs the tasks it had elsewhere, and it exits 0 once they finish or `--drain-timeout` passes; keep that 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, then runs the stage again, up to `--stage-max-failures` times. 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`. +`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; keep that under your supervisor's own limit (Kubernetes sends `SIGKILL` 30 s after `SIGTERM` by default). Stopping a worker while a query runs exposes that query to the rollback described below, so stop workers between queries. 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 (`--stage-max-failures`, below). 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. -**Ballista 55 does not recover a query from a lost worker reliably** (#31). With a worker killed, or stopped with `SIGTERM`, in the middle of a join, most of our runs either returned some groups twice, with exit 0, or never finished until a new worker joined, because the rollback loses track of the surviving workers' task slots. Until that is fixed upstream, run `oxide-scheduler --stage-max-failures 1`, which turns the common case, a failed fetch from the lost worker, into an error naming it; stop and restart workers between queries, not during them; and treat a query that ran while a worker was lost as suspect. +**Ballista 55 does not recover a query from a lost worker reliably** ([#148](https://github.com/vyncint/oxidelake/issues/148)). It rolls back every stage that read the lost worker's output and runs it again, and 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); the tasks it cancels never return their slots, so a query can also 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)). `oxide-scheduler --stage-max-failures` therefore defaults to 1: when a shuffle fetch from a lost worker fails, which is what usually happens first when a worker is killed mid-query, the query fails, naming the worker; run it again. Only a failed fetch counts toward that limit. A worker stopped with `SIGTERM`, or silent past `--worker-timeout`, is rolled back by Ballista whatever the limit, so a query running when that happens can still return duplicated rows or never finish: stop and restart workers between queries, not during them, and treat a query that ran while a worker was lost as suspect. Raising `--stage-max-failures` brings Ballista's stage retries back, with the bug. ### DataFrame API @@ -208,7 +208,7 @@ error, never a silent fallback. | `--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` | `4` | Times a stage may run again because a shuffle fetch failed, its input lost with a worker; `1` means no retry, and is the safe setting on Ballista 55 ([Cluster mode](#cluster-mode)). Ballista's `stage_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; it does not cover a worker that is stopped or goes silent ([#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. | diff --git a/SECURITY.md b/SECURITY.md index 6069696..456b07a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -100,6 +100,14 @@ not the query interface. **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 can still cost a query its correctness (#148).** + Ballista 55's recovery from a lost worker can return duplicated rows with + exit 0 (fixed upstream by apache/datafusion-ballista#2677, unreleased). + `--stage-max-failures` defaults to 1, so a failed fetch from a lost worker + fails the query instead; a worker stopped or silent mid-query is still + rolled back by Ballista whatever the limit, so stop workers between + queries. Raising the 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 8da21b9..5668667 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; `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; with `--stage-max-failures 1` a worker killed mid-query fails the query naming it and the next query runs on the worker left; 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: Ballista 55 returns duplicated rows or hangs (#31, `#[ignore]`d reproduction in `tests/cli.rs`) | +| `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; at the default `--stage-max-failures 1` a worker `kill -9`ed 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) | | a worker stopped or silent mid-query, or stage retries raised: Ballista 55 rolls the query back and can return duplicated rows or hang (#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` | | | @@ -91,7 +91,7 @@ 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: 9 of 12 runs (7 of 8 from a shell loop, 2 of 4 of the committed test) returned the 100 groups plus 13 of them again (two 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, outside OxideLake's hooks, so 0.3.0 documents them and recommends `--stage-max-failures 1`: a fetch from the lost worker then fails the query, naming it, before any rollback, and Ballista's 180-second heartbeat timeout is too slow to act first. The test of the recovery the issue asked for is committed `#[ignore]`d as the reproduction. +- **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: `stage_max_failures` defaults to 1, so a failed fetch from a lost worker fails the query, naming the worker's address, and Ballista's 180-second heartbeat timeout is too slow to act first. Only a failed fetch counts: a worker that is stopped, or silent past its timeout, is rolled back through `ExecutorLost` with `count_to_failures = false`, whatever the limit (a `SIGTERM` mid-query still hung, 150 s, at limit 1), so those paths stay exposed. 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/bin/oxide_scheduler.rs b/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs index fc8e1fb..33e19f8 100644 --- a/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs +++ b/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs @@ -49,10 +49,19 @@ struct Cli { /// 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 run again because a shuffle fetch failed, its input - /// lost with a worker, before its query fails; 1 means no retry - /// (Ballista's `stage_max_failures`). - #[arg(long, default_value_t = 4, value_name = "N", value_parser = at_least_one)] + /// 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; it does not cover a worker that is + /// stopped or goes silent (#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 @@ -198,14 +207,16 @@ mod tests { assert_eq!(config.no_executors_grace_period_seconds, 9); } - /// Unset, they are Ballista's own defaults, so this changes nothing for a - /// scheduler that does not ask. + /// 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() { + 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!(config.stage_max_failures, ballista.stage_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 diff --git a/crates/oxidelake-runtime/src/cluster.rs b/crates/oxidelake-runtime/src/cluster.rs index e2f9f8e..0d85f48 100644 --- a/crates/oxidelake-runtime/src/cluster.rs +++ b/crates/oxidelake-runtime/src/cluster.rs @@ -259,7 +259,21 @@ 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. +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(), @@ -267,6 +281,7 @@ 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() } } diff --git a/crates/oxidelake-runtime/tests/cli.rs b/crates/oxidelake-runtime/tests/cli.rs index 3922c70..245d618 100644 --- a/crates/oxidelake-runtime/tests/cli.rs +++ b/crates/oxidelake-runtime/tests/cli.rs @@ -1229,24 +1229,47 @@ fn the_resilience_flags_appear_in_help() { } } -/// A worker killed in the middle of a query, with stage retries off (#31): -/// the query fails within seconds naming the worker it lost, rather than -/// waiting for it, and the next query runs on the worker that is left. +/// What a client sees when a worker is lost in the middle of its query: +/// the query fails, prints no rows, and the error names the worker (#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, 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)); + assert!( + stderr.contains(&port), + "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 `--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. +/// 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_when_stage_retries_are_off() { +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", &["--stage-max-failures", "1"]); + 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); @@ -1259,37 +1282,26 @@ fn a_query_that_loses_a_worker_fails_naming_it_when_stage_retries_are_off() { starts_stage(JOIN_STAGE), ); cluster.signal(lost, "KILL"); - let (succeeded, _, stderr) = finish_sql(&cluster, "query", query, Duration::from_secs(120)); - assert!(!succeeded, "{stderr}"); - assert!(stderr.contains("has failed 1 times"), "{stderr}"); - let port = format!("127.0.0.1:{}", cluster.flight_port("w2")); - assert!( - stderr.contains(&port), - "the error names the lost worker, {port}:\n{stderr}" - ); - - 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(), after); + assert_the_query_fails_naming(&cluster, "w2", query, &after); } -/// What #31 asked for, and what Ballista 55 does not do: a query that loses -/// a worker while retries are allowed should come back with exactly the rows -/// it would have had. Run here (Ballista 55.0.0, the static planner #134 -/// requires, kill -9 as the worker starts its first join task), 9 runs in -/// 12 returned the 100 groups plus 13 of them a second time, exit 0: 7 of 8 -/// from a shell loop, 2 of 4 of this test. A lost worker's rollback can also -/// leave a surviving worker's task slots unreturned, so a query waits until -/// fresh capacity joins. Run by name to reproduce; it fails when either -/// happens, which is not every run. +/// 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 (#31)"] +#[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); @@ -1297,7 +1309,7 @@ fn a_query_that_loses_a_worker_comes_back_with_the_right_rows() { let query = slow_join(200_000); let expected = embedded_sql(&query, &table_arg); - let mut cluster = TestCluster::start(dir.path(), "cpu", &[]); + 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); diff --git a/docs/verification.md b/docs/verification.md index 52c7b05..c46cdc5 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -186,7 +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 `kill -9`ed mid-query under `--stage-max-failures 1` fails the query naming it; `--worker-timeout`/`--heartbeat-interval` decide who counts. Recovery with retries is `#[ignore]`d: Ballista 55 gets it wrong (#31) | +| 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 `kill -9`ed mid-query fails its query naming it, with no rows, 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 From 547fdc57917d4b5c44104792990c2e144d6cd055 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:47:32 +0700 Subject: [PATCH 4/8] fix(runtime): fail a query whose worker stops or goes silent (#148) The previous commit's --stage-max-failures 1 covers a failed shuffle fetch, what usually happens first when a worker is killed. It does not cover a worker that is stopped (SIGTERM: Ballista's executor_stopped) or that goes silent past --worker-timeout: those reach Ballista's ExecutorLost, which rolls the query back with count_to_failures = false, whatever the limit. Measured on the previous commit, same setup as there (fixture, two workers, the self-join, the signal as the worker's first join task starts): `kill -TERM` hung, killed by a 150 s timeout, no rows. Change, inside OxideLake's hooks only (no Ballista code copied): - oxide-scheduler builds Ballista's scheduler itself (create_scheduler + start_grpc_service, what start_server does) and keeps a handle to it. - worker_loss::WorkerLoss: every removal of a worker passes through our cluster state's remove_executor, and Ballista posts ExecutorLost only after it returns. There, after removing the worker, it cancel_job()s each running query with a finished task on that worker, so the cancellation is queued ahead of the rollback and Ballista's own abort refunds the task slots. A query whose tasks on the worker had finished nothing is left to Ballista: no stage is rolled back, the tasks run again elsewhere. - worker_loss::ReportingJobState: Ballista's in-memory job state, saving such a query's failure as "worker () was lost while this query ran, and it held shuffle output the query still needed ... (#148). Run the query again" where Ballista says "Cancelled". - --help, README, SECURITY.md, STATUS and the CHANGELOG now say every loss path fails the query; the in-process start_standalone cluster keeps Ballista's defaults (its builder hard-codes them, its workers live and die with the process). After, every case exits 1, prints no rows, and names the worker: - kill -TERM mid-join: at once; the stopped worker exits 0. - silent (kill -9, --worker-timeout 5, --heartbeat-interval 1): about 5 s after the kill, 2 runs of 2. - the #31 drain on a busy worker (the only worker, --drain-timeout 1): the query fails at once instead of waiting on Ballista's no-worker grace. In each case the next query on the workers left is byte-equal to embedded. Tests (tests/cli.rs, real processes on 127.0.0.1): a_query_whose_worker_stops_fails_naming_it, a_query_whose_worker_goes_silent_fails_naming_it, and the drain test sigterm_stops_a_worker_within_its_drain_timeout_with_exit_zero now also requires its query to fail naming the worker. Broken once (the hook not called): the stop and silent tests, "`query` was still running after 120s"; the drain test, "after 60s". With the reason not rewritten the client saw "Job ... failed: Cancelled". Refs #148 Refs #31 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 32 +-- README.md | 6 +- SECURITY.md | 12 +- STATUS.md | 4 +- crates/oxidelake-runtime/src/admission.rs | 29 +- .../src/bin/oxide_scheduler.rs | 9 +- crates/oxidelake-runtime/src/cluster.rs | 40 ++- crates/oxidelake-runtime/src/lib.rs | 1 + crates/oxidelake-runtime/src/worker_loss.rs | 255 ++++++++++++++++++ crates/oxidelake-runtime/tests/cli.rs | 80 +++++- docs/verification.md | 2 +- 11 files changed, 421 insertions(+), 49 deletions(-) create mode 100644 crates/oxidelake-runtime/src/worker_loss.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index cdc1800..12762bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,8 +22,8 @@ versions (0.x) may contain breaking changes; they are always listed under a `--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 (#148, under - Changed). + 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 @@ -460,20 +460,20 @@ 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 stage whose input was lost with 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). `--stage-max-failures` - now defaults to 1, so a failed fetch from a lost worker, what usually - happens first when a worker is killed, fails the query naming the worker. - It does not cover a worker that is stopped or goes silent mid-query: - Ballista rolls those back whatever the limit, so stop workers between - queries. **Migration:** a query that used to survive a killed worker now - fails; run it again. To get Ballista's stage retries back, pass +- **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, 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 diff --git a/README.md b/README.md index 73417f9..c165da6 100644 --- a/README.md +++ b/README.md @@ -131,11 +131,11 @@ 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; keep that under your supervisor's own limit (Kubernetes sends `SIGKILL` 30 s after `SIGTERM` by default). Stopping a worker while a query runs exposes that query to the rollback described below, so stop workers between queries. 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 (`--stage-max-failures`, below). 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`. +`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. -**Ballista 55 does not recover a query from a lost worker reliably** ([#148](https://github.com/vyncint/oxidelake/issues/148)). It rolls back every stage that read the lost worker's output and runs it again, and 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); the tasks it cancels never return their slots, so a query can also 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)). `oxide-scheduler --stage-max-failures` therefore defaults to 1: when a shuffle fetch from a lost worker fails, which is what usually happens first when a worker is killed mid-query, the query fails, naming the worker; run it again. Only a failed fetch counts toward that limit. A worker stopped with `SIGTERM`, or silent past `--worker-timeout`, is rolled back by Ballista whatever the limit, so a query running when that happens can still return duplicated rows or never finish: stop and restart workers between queries, not during them, and treat a query that ran while a worker was lost as suspect. Raising `--stage-max-failures` brings Ballista's stage retries back, with the bug. +**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; 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 @@ -208,7 +208,7 @@ error, never a silent fallback. | `--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; it does not cover a worker that is stopped or goes silent ([#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. | +| `--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. | diff --git a/SECURITY.md b/SECURITY.md index 456b07a..0c97e02 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -100,14 +100,12 @@ not the query interface. **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 can still cost a query its correctness (#148).** +- **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). - `--stage-max-failures` defaults to 1, so a failed fetch from a lost worker - fails the query instead; a worker stopped or silent mid-query is still - rolled back by Ballista whatever the limit, so stop workers between - queries. Raising the limit turns Ballista's stage retries, and the bug, - back on. + 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 5668667..dc62551 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; `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; at the default `--stage-max-failures 1` a worker `kill -9`ed 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) | | a worker stopped or silent mid-query, or stage retries raised: Ballista 55 rolls the query back and can return duplicated rows or hang (#148; `#[ignore]`d reproduction in `tests/cli.rs`; fixed upstream by apache/datafusion-ballista#2677, unreleased) | +| `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` | | | @@ -91,7 +91,7 @@ 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: `stage_max_failures` defaults to 1, so a failed fetch from a lost worker fails the query, naming the worker's address, and Ballista's 180-second heartbeat timeout is too slow to act first. Only a failed fetch counts: a worker that is stopped, or silent past its timeout, is rolled back through `ExecutorLost` with `count_to_failures = false`, whatever the limit (a `SIGTERM` mid-query still hung, 150 s, at limit 1), so those paths stay exposed. The recovery the issue asked for stays an `#[ignore]`d test at `--stage-max-failures 4`, to be enabled on a Ballista with #2677. +- **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 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 33e19f8..b098bfd 100644 --- a/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs +++ b/crates/oxidelake-runtime/src/bin/oxide_scheduler.rs @@ -52,10 +52,11 @@ struct Cli { /// 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; it does not cover a worker that is - /// stopped or goes silent (#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). + /// 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, diff --git a/crates/oxidelake-runtime/src/cluster.rs b/crates/oxidelake-runtime/src/cluster.rs index 0d85f48..797cee3 100644 --- a/crates/oxidelake-runtime/src/cluster.rs +++ b/crates/oxidelake-runtime/src/cluster.rs @@ -31,7 +31,7 @@ use ballista_executor::new_standalone_executor_from_builder; 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; @@ -43,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; @@ -55,6 +56,7 @@ 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}")) @@ -268,7 +270,8 @@ pub fn function_registry() -> BallistaFunctionRegistry { /// (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. +/// 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 @@ -323,10 +326,22 @@ impl Scheduler { .parse() .map_err(|e| EngineError::plan(format!("invalid scheduler bind address: {e}")))?; let draining = Arc::new(AtomicBool::new(false)); - let cluster = same_build_cluster(&config, Arc::clone(&draining)); + 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(start_server(cluster, address, Arc::new(config))), + serve: Box::pin(serve), jobs, draining, }) @@ -398,11 +413,16 @@ pub async fn run_scheduler_with_shutdown( } /// What `BallistaCluster::new_from_config` builds, in-memory cluster and job -/// state, with the cluster state admitting only workers of this build, 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) -> BallistaCluster { - let state = Arc::new(SameBuildClusterState::default()); +/// state, with the cluster state admitting only workers of this build and +/// 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() @@ -419,7 +439,7 @@ fn same_build_cluster(config: &SchedulerConfig, draining: Arc) -> Ba )), config_producer, ); - BallistaCluster::new(state, Arc::new(jobs)) + BallistaCluster::new(state, Arc::new(ReportingJobState::new(jobs, loss))) } /// Executor configuration with OxideLake's hooks installed. diff --git a/crates/oxidelake-runtime/src/lib.rs b/crates/oxidelake-runtime/src/lib.rs index a36c2a9..65579da 100644 --- a/crates/oxidelake-runtime/src/lib.rs +++ b/crates/oxidelake-runtime/src/lib.rs @@ -15,6 +15,7 @@ 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/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 245d618..10d51a2 100644 --- a/crates/oxidelake-runtime/tests/cli.rs +++ b/crates/oxidelake-runtime/tests/cli.rs @@ -1285,6 +1285,71 @@ fn a_query_that_loses_a_worker_fails_naming_it() { assert_the_query_fails_naming(&cluster, "w2", 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", 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", 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 @@ -1386,10 +1451,17 @@ fn sigterm_stops_a_worker_within_its_drain_timeout_with_exit_zero() { "{}", cluster.log("busy") ); - // The query has no worker left; it is not what this test is about. - let mut query = query; - let _ = query.kill(); - let _ = query.wait(); + // 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 diff --git a/docs/verification.md b/docs/verification.md index c46cdc5..e5e7a80 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -186,7 +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 `kill -9`ed mid-query fails its query naming it, with no rows, 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) | +| 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 naming it, with no rows, 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 From 23ae2cf973af34155c7e54b2a8bfda61cef281b9 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:52:36 +0700 Subject: [PATCH 5/8] test(runtime): pick cluster test ports below the ephemeral range `make test` on 61f455f failed a_query_that_loses_a_worker_fails_naming_it in wait_ready(2): w1 registered, then "Could not start built-in arrow flight server ... Address already in use (os error 98)" on the port free_port() had picked, and it stopped. An earlier full run failed another cluster test the same way. free_port() bound 127.0.0.1:0 and let the port go; that range (ip_local_port_range, 32768-60999 here) is where the kernel also takes source ports for outgoing connections, so on a busy machine a connection reused the port before the worker bound it. It now hands out ports from 20000-31999, which no one but this function hands out: below the ephemeral ranges of Linux (32768) and macOS (49152). Each call in the binary gets a different port, starting from an offset in the process id, and each is checked free by binding it. Two full runs of tests/cli.rs after: 24 passed, 3 ignored, then 23 passed and 1 failed for a different reason (the next commit). Refs #31 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- crates/oxidelake-runtime/tests/cli.rs | 34 +++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/oxidelake-runtime/tests/cli.rs b/crates/oxidelake-runtime/tests/cli.rs index 10d51a2..884a114 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) { From 33b385e0e29671e252ed68b87483a3d91c32964b Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:57:10 +0700 Subject: [PATCH 6/8] test(runtime): accept a broken shuffle stream as a killed worker's error A run of tests/cli.rs on a579a5a failed a_query_whose_worker_goes_silent_fails_naming_it although the query did what it should: it failed at once, printed no rows, and nothing hung. The error named no worker: "Job ... failed: Job failed due to stage 3 failed: Task failed due to runtime execution error: ... IpcError(\"... h2 protocol error: error reading a body from connection\" ... broken pipe)". The worker was killed while it was sending a shuffle block to a join task on the other worker; the broken stream is an execution error, not a failed fetch, so Ballista fails the stage at once whatever --stage-max-failures says, with no rollback, and its message carries no address. 1 run in about 8 of that test; the kill -9 test can meet it the same way. The tests' helper now takes how the worker was lost: a stopped worker (SIGTERM) keeps serving its shuffle data while it drains, and its query's error must name it; a killed one may also show as that broken stream. README, the CHANGELOG, STATUS and docs/verification.md said the error always names the worker; they now say when it does not. After: three full runs of tests/cli.rs, 24 passed, 3 ignored each. Refs #148 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 4 ++- README.md | 2 +- STATUS.md | 2 +- crates/oxidelake-runtime/tests/cli.rs | 37 ++++++++++++++++++++++----- docs/verification.md | 2 +- 5 files changed, 36 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12762bc..b021c3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -469,7 +469,9 @@ versions (0.x) may contain breaking changes; they are always listed under a `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, and `--stage-max-failures` defaults to 1, so + 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; diff --git a/README.md b/README.md index c165da6..5d85392 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ A scheduler admits only workers of its own build: the same OxideLake release, bu **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; 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. +**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 diff --git a/STATUS.md b/STATUS.md index dc62551..f87ef5e 100644 --- a/STATUS.md +++ b/STATUS.md @@ -91,7 +91,7 @@ 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 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. +- **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/tests/cli.rs b/crates/oxidelake-runtime/tests/cli.rs index 884a114..7ec5e9d 100644 --- a/crates/oxidelake-runtime/tests/cli.rs +++ b/crates/oxidelake-runtime/tests/cli.rs @@ -1253,16 +1253,39 @@ fn the_resilience_flags_appear_in_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 names the worker (#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, query: Child, then: &str) { +/// 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), + stderr.contains(&port) || broken_stream, "the error names the lost worker, {port}:\n{stderr}" ); let table_arg = format!("t={}", cluster.dir.display()); @@ -1306,7 +1329,7 @@ fn a_query_that_loses_a_worker_fails_naming_it() { starts_stage(JOIN_STAGE), ); cluster.signal(lost, "KILL"); - assert_the_query_fails_naming(&cluster, "w2", query, &after); + assert_the_query_fails_naming(&cluster, "w2", Lost::Killed, query, &after); } /// A worker stopped with `SIGTERM` in the middle of a query (#31, #148): @@ -1338,7 +1361,7 @@ fn a_query_whose_worker_stops_fails_naming_it() { 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", query, &after); + 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"), @@ -1371,7 +1394,7 @@ fn a_query_whose_worker_goes_silent_fails_naming_it() { starts_stage(JOIN_STAGE), ); cluster.signal(lost, "KILL"); - assert_the_query_fails_naming(&cluster, "w2", query, &after); + 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 diff --git a/docs/verification.md b/docs/verification.md index e5e7a80..3901aef 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -186,7 +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 naming it, with no rows, 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) | +| 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 From e49d599297f5629a5964ed7428843c5324405b92 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:57:10 +0700 Subject: [PATCH 7/8] test(runtime): signal an idle worker only once it listens A run of tests/cli.rs failed sigterm_stops_a_worker_within_its_drain_timeout_with_exit_zero with "an idle worker ignored SIGTERM". Its log: the scheduler had counted the worker (/readyz said 2) and the test sent SIGTERM at 09:53:12.823, but the worker's own registration finished at 12.849, and Ballista's executor starts listening for signals only after that. OxideLake's listener, which is installed at startup so an early signal is not fatal, saw it alone; Ballista never ran its graceful stop, and the worker exited 0 when its 20 s drain timeout passed, just after the test's 20 s wait. Passing the signal on to Ballista would mean raising it again through FFI, which this crate does not do outside allocator code, so the edge is documented on run_executor_with_shutdown instead: a signal in a worker's first fraction of a second stops it at the drain timeout, with exit 0, and the scheduler learns from the missed heartbeats. The test now waits for the worker's Flight server line, Ballista's last step before it listens, and 300 ms more. After: three full runs of tests/cli.rs, 24 passed, 3 ignored each. Refs #31 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- crates/oxidelake-runtime/src/cluster.rs | 6 ++++++ crates/oxidelake-runtime/tests/cli.rs | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/crates/oxidelake-runtime/src/cluster.rs b/crates/oxidelake-runtime/src/cluster.rs index 797cee3..b85c3b5 100644 --- a/crates/oxidelake-runtime/src/cluster.rs +++ b/crates/oxidelake-runtime/src/cluster.rs @@ -504,6 +504,12 @@ pub async fn run_executor(config: ExecutorProcessConfig) -> Result<(), EngineErr /// 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, diff --git a/crates/oxidelake-runtime/tests/cli.rs b/crates/oxidelake-runtime/tests/cli.rs index 7ec5e9d..aaef9b3 100644 --- a/crates/oxidelake-runtime/tests/cli.rs +++ b/crates/oxidelake-runtime/tests/cli.rs @@ -1454,6 +1454,14 @@ fn sigterm_stops_a_worker_within_its_drain_timeout_with_exit_zero() { 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"); From 3efcb959d41c93b65d73c8cc2cc39c2c9a02c5f5 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:15:27 +0700 Subject: [PATCH 8/8] ci: skip the lost-worker reproduction in the Metal on-device pass test-metal-device runs every #[ignore]d test in its graph, and a_query_that_loses_a_worker_comes_back_with_the_right_rows is the #[ignore]d reproduction of Ballista 55's rollback bug (#148): it fails until a Ballista release carries apache/datafusion-ballista#2677, which is why it is ignored. The macOS job ran it and went red (the query came back wrong, as the reproduction expects). Skipped by name, as mixed_build is for the same reason. Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- Makefile | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) 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