Skip to main content

waratah/
dev.rs

1//! Local cluster orchestrator: S, P, O, string-registry, and compute.
2//!
3//! `waratah start` spawns the four storage-side processes from their own
4//! binaries (`waratah-partition`, `waratah-registry`) at the addresses in the
5//! static [`ClusterConfig`], then runs the compute coordinator in this process
6//! behind an RDF4J HTTP facade (`waratah_api`) by default. It daemonizes
7//! itself unless `--foreground` is given (see `crate::daemon`).
8//!
9//! `waratah standalone` skips spawn: this process opens
10//! [`waratah_partition::PartitionService`] ×3 and
11//! [`waratah_registry::RegistryService`] and injects them into compute (same
12//! SPARQL / HTTP session, no gRPC). Always foreground.
13//!
14//! Nothing here is a production supervisor — restarts, health checks, and
15//! address discovery belong to the gossip/etcd work in Phase 10.
16
17use std::io::{self, Write};
18use std::net::SocketAddr;
19use std::path::{Path, PathBuf};
20use std::process::{Child, Command};
21use std::sync::Arc;
22use std::time::{Duration, Instant};
23
24use oxrdf::{Literal, NamedNode};
25use oxrdfio::{RdfFormat, RdfSerializer};
26use tokio::io::{AsyncBufReadExt, BufReader};
27use waratah_api::{AppState, QueryDebug, ServerQuery, console_is_stub, console_missing_worker};
28use waratah_compute::{
29    ComputeNode, DescribeMode, HexastoreCatalog, HexastoreFlush, HexastoreInsert, HexastoreScan,
30    HexastoreStats, QueryResults, RetryPolicy, StringRegister, StringRegistryFlush, StringResolve,
31};
32use waratah_proto::pb;
33use waratah_proto::{HexastoreClient, StringRegistryClient};
34use waratah_router::{ClusterConfig, RegistryNodeId};
35use waratah_storage::{
36    CommitTs, GraphName, MAIN_REPOSITORY_ID, PartitionAxis, Quad, SnapshotId, ingest_staging_dir,
37    queries_repo_dir,
38};
39
40use crate::error::DevError;
41use crate::notebook::NotebookSession;
42use crate::shutdown::ShutdownWatch;
43
44/// Commit timestamp of the demo load (Phase 8 assigns these from a TSO).
45const DEMO_COMMIT_TS: CommitTs = CommitTs(1);
46
47/// How long to wait for a spawned process to accept connections.
48const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
49
50/// Default RDF4J HTTP listen address (`/rdf4j` under this host:port).
51pub const DEFAULT_HTTP_ADDR: &str = "127.0.0.1:8080";
52
53/// Pidfile name: next to the data dir when one is set, otherwise in the
54/// working directory (memory-backend daemons). `waratah stop` reads it to
55/// SIGTERM us.
56const DEV_PID_FILE: &str = "waratah-dev.pid";
57
58/// How long outstanding HTTP work gets to drain after the shutdown signal
59/// before remaining connections (kernel websockets) are force-closed.
60/// Kept well under `waratah stop`'s SIGKILL deadline so the sidecar's own
61/// graceful kernel shutdown (waratah_notebook `SHUTDOWN_GRACE`) still gets
62/// to run.
63const HTTP_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
64
65/// Backend for the spawned hexastore partitions.
66#[derive(Debug, Clone)]
67pub enum Backend {
68    /// In-memory hexastore: fast, discarded on exit.
69    Memory,
70    /// RocksDB under `path/{repository}/{axis}` (repository is `main`).
71    RocksDb(PathBuf),
72}
73
74/// Options for [`start`].
75#[derive(Debug, Clone)]
76pub struct DevOptions {
77    /// Addresses of all five processes.
78    pub config: ClusterConfig,
79    /// Storage backend for the partitions.
80    pub backend: Backend,
81    /// Directory holding `waratah-partition` and `waratah-registry`.
82    pub bin_dir: PathBuf,
83    /// Load the weather/city demo dataset after connecting.
84    pub load_demo: bool,
85    /// Run one query and exit instead of starting the HTTP server / REPL.
86    pub query: Option<String>,
87    /// RDF4J HTTP listen address. `None` skips the HTTP server (REPL only).
88    pub http: Option<SocketAddr>,
89    /// Log SPARQL query text, timings, and client-facing errors to stderr.
90    pub debug: bool,
91    /// Open S/P/O and the registry in this process instead of spawning children.
92    pub standalone: bool,
93    /// SPARQL DESCRIBE algorithm (`star` default).
94    pub describe_mode: DescribeMode,
95    /// SPARQL default graph is the union of all graphs when no `FROM` list.
96    pub default_union: bool,
97    /// Seat inner-join arms by the total seating cost (the
98    /// `join-seat-shadow` comparator promoted to decision).
99    pub seat_by_total_cost: bool,
100    /// Benchmark switch: stamp `Semi` past a `PerPage` cost verdict.
101    pub force_semi: bool,
102    /// Compute-side eager scan filter (`--no-eager-scan-filter` disables it).
103    pub eager_scan_filter: bool,
104    /// Strict SPARQL 1.1 adherence mode (gates the documented deviations —
105    /// e.g. gYear-family ordering comparisons become type errors).
106    pub strict_sparql: bool,
107    /// Staging directory for the `/waratah/.../ingest` HTTP API.
108    pub ingest_dir: PathBuf,
109    /// Root of the per-repository published query library (`--queries-dir`).
110    /// `None` = the queries endpoint answers `501`, unless `--load-demo`
111    /// falls back to the built-in demo queries.
112    pub queries_dir: Option<PathBuf>,
113    /// Root directory for per-query spill files (`None` = `std::env::temp_dir`).
114    pub spill_dir: Option<PathBuf>,
115    /// Notebook sidecar options (`--with-notebooks` / `notebooks.toml`).
116    /// `None` = feature disabled.
117    pub notebooks: Option<waratah_notebook::NotebookOptions>,
118    /// AI services options (`--with-ai` / `ai.toml`). `None` = feature
119    /// disabled (every AI route answers `501`).
120    pub ai: Option<waratah_api::AiConfig>,
121    /// Daemon-child readiness handshake: `run_session` writes `ready` to
122    /// this file right before the serve loop; the spawner polls it. `None`
123    /// on every foreground path.
124    pub ready_file: Option<PathBuf>,
125    /// File-backed debug-sink target (daemon child + `--debug`): query
126    /// text, timings, and execution traces go here instead of stderr.
127    /// `None` = stderr (today's foreground behavior).
128    pub debug_file: Option<PathBuf>,
129    /// Write the pidfile (next to the data dir, or in the working
130    /// directory for the memory backend). Foreground one-shot runs skip it;
131    /// every daemonized start sets it.
132    pub pidfile: bool,
133    /// Text plugin config (enabled = the startup build runs when the epoch
134    /// is missing, and the rewrites gate on the stamped epoch + fingerprint).
135    pub text_config: Option<waratah_text::TextPluginConfig>,
136}
137
138/// Spawn the storage-side processes (unless the `waratah standalone`
139/// command set `options.standalone`), then run compute.
140pub async fn start(mut options: DevOptions) -> Result<(), DevError> {
141    if let Some(http) = options.http {
142        options.config = options.config.with_advertised_urls(
143            format!("http://{http}/rdf4j/"),
144            format!("http://{http}/waratah/"),
145        );
146    }
147    write_pidfile(&options)?;
148    // `--query` never mounts the HTTP server, so a sidecar would have
149    // nothing to proxy and a first-start pip would be pure waste.
150    let notebooks = if options.query.is_none() {
151        // The sidecar warms up in the background (venv provisioning can
152        // take minutes on first start); its readiness shows up on
153        // `GET /waratah/notebooks` and in the cluster view.
154        NotebookSession::start(&options)?
155    } else {
156        if options.notebooks.is_some() {
157            eprintln!("note: --query ignores --with-notebooks (no HTTP server to proxy)");
158        }
159        if options.ai.is_some() {
160            eprintln!("note: --query ignores --with-ai (no HTTP server to proxy)");
161        }
162        None
163    };
164    let shutdown = ShutdownWatch::install();
165    // Every fallible step below funnels through this block so an early
166    // error still stops the sidecar gracefully (SIGTERM → kernel cleanup)
167    // instead of relying on the handle's hard-kill Drop.
168    let result = async {
169        if options.standalone {
170            let (compute, warm) = crate::standalone::open_compute(&options)?;
171            let compute = compute
172                .with_describe_mode(options.describe_mode)
173                .with_default_union(options.default_union)
174                .with_seat_by_total_cost(options.seat_by_total_cost)
175                .with_force_semi(options.force_semi)
176                .with_eager_scan_filter(options.eager_scan_filter)
177                .with_spill_root(options.spill_dir.clone());
178            println!("compute coordinator ready (in-process storage)");
179            run_session(
180                compute,
181                &options,
182                notebooks.as_ref(),
183                &shutdown,
184                WarmGate {
185                    warm: Some(warm),
186                    warnings: Vec::new(),
187                },
188            )
189            .await
190        } else {
191            let mut cluster = SpawnedCluster::spawn(&options)?;
192            let session = async {
193                let compute = ComputeNode::connect(&options.config, RetryPolicy::default_dev())
194                    .await?
195                    .with_describe_mode(options.describe_mode)
196                    .with_default_union(options.default_union)
197                    .with_seat_by_total_cost(options.seat_by_total_cost)
198                    .with_force_semi(options.force_semi)
199                    .with_eager_scan_filter(options.eager_scan_filter)
200                    .with_spill_root(options.spill_dir.clone());
201                // Hold startup until every storage child's cache-walk finishes
202                // (or outlives the max wait and is reported stuck): /health
203                // coming up is the benchmark's start signal, and first queries
204                // must not race the warm pass.
205                let warnings = wait_cluster_warm(&options.config).await?;
206                println!(
207                    "compute coordinator ready ({} processes)",
208                    options.config.process_count()
209                );
210                run_session(
211                    compute,
212                    &options,
213                    notebooks.as_ref(),
214                    &shutdown,
215                    WarmGate {
216                        warm: None,
217                        warnings,
218                    },
219                )
220                .await
221            }
222            .await;
223            cluster.shutdown();
224            session
225        }
226    }
227    .await;
228    if let Some(notebooks) = notebooks {
229        notebooks.stop().await;
230    }
231    remove_pidfile(&options);
232    result
233}
234
235/// `waratah stop [--data-dir DIR]`: SIGTERM the orchestrator recorded in
236/// `{data_dir}/waratah-dev.pid` (or `./waratah-dev.pid` without a data
237/// dir — where memory-backend daemons put it) — its signal handler kills
238/// the storage children and the notebook sidecar's process group — wait,
239/// then SIGKILL as a last resort.
240pub async fn stop(data_dir: Option<PathBuf>) -> Result<(), DevError> {
241    let pid_file = pidfile_path(data_dir.as_deref());
242    let text = std::fs::read_to_string(&pid_file).map_err(|_| {
243        DevError::DevStop(format!(
244            "no pidfile at {} — `waratah start` writes one next to --data-dir \
245             (or into the working directory for a memory-backend daemon)",
246            pid_file.display()
247        ))
248    })?;
249    let pid: libc::pid_t = text
250        .trim()
251        .parse()
252        .map_err(|_| DevError::DevStop(format!("pidfile {} is not a pid", pid_file.display())))?;
253    if pid == std::process::id() as libc::pid_t {
254        return Err(DevError::DevStop(
255            "pidfile names this process; refusing to stop ourselves".to_owned(),
256        ));
257    }
258    // SAFETY: kill(2) with SIGTERM to a pid read from our own pidfile.
259    if unsafe { libc::kill(pid, libc::SIGTERM) } != 0 {
260        return Err(DevError::DevStop(format!(
261            "could not signal pid {pid}: {}",
262            std::io::Error::last_os_error()
263        )));
264    }
265    // Signal → HTTP drain (5s) → sidecar graceful kernel shutdown (8s):
266    // 20s leaves margin over that worst case.
267    let deadline = Instant::now() + Duration::from_secs(20);
268    while Instant::now() < deadline {
269        if !process_alive(pid) {
270            println!("cluster (pid {pid}) stopped");
271            return Ok(());
272        }
273        tokio::time::sleep(Duration::from_millis(100)).await;
274    }
275    eprintln!("cluster (pid {pid}) did not exit within 20s; sending SIGKILL");
276    // SAFETY: kill(2) with SIGKILL to the same checked pid.
277    unsafe { libc::kill(pid, libc::SIGKILL) };
278    Ok(())
279}
280
281/// Whether `pid` has a live process. Signal-0 probe plus a zombie check:
282/// an exited-but-unreaped child (its parent has not `wait`ed yet) still
283/// answers `kill(pid, 0)`, which would make `waratah stop` wait out its
284/// whole deadline on a process that is already gone.
285fn process_alive(pid: libc::pid_t) -> bool {
286    if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat"))
287        && let Some(rest) = stat.rsplit(')').next()
288        && rest.trim_start().starts_with('Z')
289    {
290        return false;
291    }
292    // No /proc entry (or non-Linux): fall back to the existence probe.
293    // SAFETY: signal 0 checks existence without delivering anything.
294    unsafe { libc::kill(pid, 0) == 0 }
295}
296
297fn data_dir(options: &DevOptions) -> Option<&Path> {
298    match &options.backend {
299        Backend::RocksDb(path) => Some(path),
300        Backend::Memory => None,
301    }
302}
303
304/// Directory the pidfile lives in: the data dir when one is set, otherwise
305/// the working directory (memory-backend daemons write one there so
306/// `waratah stop` without `--data-dir` can find them).
307fn pidfile_dir(options: &DevOptions) -> PathBuf {
308    match data_dir(options) {
309        Some(dir) => dir.to_path_buf(),
310        None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
311    }
312}
313
314/// Full pidfile path for a data-dir choice: `{data_dir}/waratah-dev.pid`,
315/// or `./waratah-dev.pid` for the memory backend.
316pub(crate) fn pidfile_path(data_dir: Option<&Path>) -> PathBuf {
317    match data_dir {
318        Some(dir) => dir.join(DEV_PID_FILE),
319        None => std::env::current_dir()
320            .unwrap_or_else(|_| PathBuf::from("."))
321            .join(DEV_PID_FILE),
322    }
323}
324
325/// Remove `path` only when it still names `pid` — never a file that has
326/// been overwritten by (or always belonged to) another cluster. A pidfile
327/// IS the `waratah stop` handle, so deleting someone else's leaves their
328/// live cluster unstoppable. Returns whether a file was removed.
329pub(crate) fn remove_pidfile_if_names(path: &Path, pid: libc::pid_t) -> bool {
330    match std::fs::read_to_string(path) {
331        Ok(text) if text.trim() == pid.to_string() => std::fs::remove_file(path).is_ok(),
332        _ => false,
333    }
334}
335
336/// Claim the pidfile for this process. Refuses the start when the file
337/// already names a LIVE foreign pid: overwriting it would leave that
338/// cluster with no `waratah stop` handle. A stale file (dead pid, or our
339/// own pid from a restarted run) is overwritten.
340fn write_pidfile(options: &DevOptions) -> Result<(), DevError> {
341    if !options.pidfile {
342        return Ok(());
343    }
344    let path = pidfile_path(data_dir(options));
345    if let Ok(text) = std::fs::read_to_string(&path)
346        && let Ok(pid) = text.trim().parse::<u32>()
347        && pid != std::process::id()
348        && process_alive(pid as libc::pid_t)
349    {
350        return Err(DevError::PidfileInUse { path, pid });
351    }
352    // The standalone path creates the data dir later (open_compute); the
353    // pidfile must exist before that for `waratah stop` to find a live
354    // cluster. Write failures stay best-effort: a run without a pidfile
355    // still serves.
356    if let Err(error) = std::fs::create_dir_all(pidfile_dir(options)) {
357        eprintln!(
358            "could not create {}: {error}",
359            pidfile_dir(options).display()
360        );
361        return Ok(());
362    }
363    if let Err(error) = std::fs::write(&path, std::process::id().to_string()) {
364        eprintln!("could not write {}: {error}", path.display());
365    }
366    Ok(())
367}
368
369/// Whether another `waratah` server is already serving THIS data dir: the
370/// pidfile there names a live pid that is not ours. The pidfile is the
371/// existing cross-process channel (`waratah start` and `standalone` write
372/// one and remove it on exit), so a live foreign pid is a server on the
373/// same storage. A memory backend shares no storage — each process owns
374/// its store — so `None` finds nothing to detect. Our own pid is the
375/// pidfile this process just wrote, not a peer.
376fn another_server_using_storage(data_dir: Option<&Path>) -> bool {
377    let Some(dir) = data_dir else {
378        return false;
379    };
380    let Ok(text) = std::fs::read_to_string(pidfile_path(Some(dir))) else {
381        return false;
382    };
383    let Ok(pid) = text.trim().parse::<u32>() else {
384        return false;
385    };
386    pid != std::process::id() && process_alive(pid as libc::pid_t)
387}
388
389fn remove_pidfile(options: &DevOptions) {
390    if !options.pidfile {
391        return;
392    }
393    // Pid-checked: a run whose pidfile was overwritten by another start
394    // (refused runs cannot overwrite anymore, but older files might name
395    // someone else) must never delete the survivor's stop handle.
396    remove_pidfile_if_names(
397        &pidfile_path(data_dir(options)),
398        std::process::id() as libc::pid_t,
399    );
400}
401
402/// Log the resolved spill root and warn when spilled pages would stay in RAM.
403///
404/// `std::env::temp_dir` is tmpfs-backed on many Linux systems, so the
405/// memory-pressure relief that spilling exists to provide silently
406/// disappears there — surface it at startup instead of at first OOM.
407fn log_spill_root(spill_root: Option<&Path>) {
408    match spill_root {
409        Some(root) => {
410            println!("spill root: {}", root.display());
411            if is_tmpfs(root) {
412                eprintln!(
413                    "WARN: spill root {} is tmpfs-backed; spilled pages will remain in RAM. \
414                     Set --spill-dir to a disk-backed path.",
415                    root.display()
416                );
417            }
418        }
419        None => {
420            eprintln!(
421                "WARN: no spill root configured (memory backend); query spill files go to {} \
422                 which may be RAM-backed (tmpfs) — spilled pages will remain in RAM. \
423                 Use --data-dir or --spill-dir for disk-backed spill.",
424                std::env::temp_dir().display()
425            );
426        }
427    }
428}
429
430/// Whether `path` sits on a tmpfs mount (Linux only; other platforms report
431/// false and skip the check).
432#[cfg(target_os = "linux")]
433fn is_tmpfs(path: &Path) -> bool {
434    use std::ffi::CString;
435    let Ok(cpath) = CString::new(path.as_os_str().as_encoded_bytes()) else {
436        return false;
437    };
438    let mut stat: libc::statfs = unsafe { std::mem::zeroed() };
439    // SAFETY: `cpath` outlives the call and `stat` is a valid, zeroed
440    // `statfs` that statfs fills in.
441    let rc = unsafe { libc::statfs(cpath.as_ptr(), &mut stat) };
442    // f_type is __fsword_t (i32 on 32-bit archs, i64 on 64-bit); TMPFS_MAGIC
443    // is c_long/c_uint accordingly, so cast through the same word type.
444    rc == 0 && stat.f_type == libc::TMPFS_MAGIC as libc::__fsword_t
445}
446
447#[cfg(not(target_os = "linux"))]
448fn is_tmpfs(_path: &Path) -> bool {
449    false
450}
451
452/// Startup cache-warm gating handed to a session: the shared tracker
453/// (standalone mode; `/health` returns 503 with the pending walk names until
454/// it drains) plus any orchestrator warnings (RPC mode; a child walk outlived
455/// the readiness wait). Both surface in the `/health` body.
456pub(crate) struct WarmGate {
457    warm: Option<std::sync::Arc<waratah_storage::WarmState>>,
458    warnings: Vec<String>,
459}
460
461impl WarmGate {
462    /// `--query` / REPL have no `/health` to gate, so wait for the warm walks
463    /// here instead — past the max wait the stuck warning fires (stderr, once)
464    /// and the session proceeds without a full warm.
465    async fn wait_ready(&self) {
466        let Some(warm) = &self.warm else {
467            return;
468        };
469        while !warm.is_done() {
470            if warm.stuck_warning().is_some() {
471                return;
472            }
473            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
474        }
475    }
476}
477
478async fn run_session<H, R>(
479    mut compute: ComputeNode<H, R>,
480    options: &DevOptions,
481    notebooks: Option<&NotebookSession>,
482    shutdown: &ShutdownWatch,
483    warm_gate: WarmGate,
484) -> Result<(), DevError>
485where
486    H: HexastoreInsert
487        + HexastoreScan
488        + HexastoreCatalog
489        + HexastoreFlush
490        + HexastoreStats
491        + waratah_compute::HexastoreAdmin
492        + waratah_compute::HexastoreAxisHeadStats
493        + waratah_compute::HexastoreGeo
494        + Clone
495        + Send
496        + Sync
497        + 'static,
498    R: StringRegister
499        + StringResolve
500        + StringRegistryFlush
501        + waratah_compute::BlobStoreClient
502        + waratah_compute::RegistryAdmin
503        + Clone
504        + Send
505        + Sync
506        + 'static,
507{
508    /// How long compute startup waits for a partition-side index rebuild to
509    /// stamp its epoch before continuing UNINDEXED (the residual path answers
510    /// correctly but slowly). A wedged rebuild lease also breaks the wait via
511    /// the Describe in-progress flag.
512    const REBUILD_WAIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30 * 60);
513
514    log_spill_root(compute.spill_root());
515
516    // Strict SPARQL mode gates the documented deviations (read at query
517    // preparation; new queries only).
518    if options.strict_sparql {
519        waratah_compute::strict_sparql::set_strict_sparql(true);
520        println!("strict-sparql mode: documented deviations are gated off");
521    }
522
523    if options.load_demo {
524        let quads = demo_dataset();
525        let result = compute.insert_quads(&quads, DEMO_COMMIT_TS).await?;
526        println!(
527            "loaded {} quads at commit_ts={} ({} registry entries)",
528            result.quads, DEMO_COMMIT_TS.0, result.registered
529        );
530        compute.flush_memtables().await?;
531        println!("flushed memtables on S/P/O");
532    }
533
534    // Pull S/P/O `waratah.stats` into the planner cache. Required when attaching
535    // to an existing data-dir (offline import already compacted sketches into
536    // SSTs); also covers `--load-demo` after the flush above. An empty store
537    // yields an empty profile and the planner keeps bound-slot placeholders.
538    let profile = compute.refresh_stats().await?;
539    println!(
540        "rolled up sketch profile ({} puts observed on preferred axis)",
541        profile.total_puts
542    );
543
544    // Best-effort geo-index epoch read from the O partition's Describe: a
545    // failure (client without admin surface, partition down) leaves `None`,
546    // and the planner treats a missing epoch as trusted — the geo plugin is
547    // always on in deployment, so the index is incrementally valid from
548    // store creation until the first `waratah geo rebuild-index` stamps it.
549    if let Ok(describe) = compute
550        .queries()
551        .hexastore()
552        .describe(PartitionAxis::O)
553        .await
554    {
555        compute.set_geo_index_epoch(describe.geo_index_epoch);
556        if let Some(epoch) = describe.geo_index_epoch {
557            println!("geo rebuild-index epoch: {epoch}");
558        }
559    }
560
561    // Temporal index: UNTRUSTED until its rebuild epoch exists (temporal
562    // literals predate the plugin). First startup with the plugin on a
563    // store that never rebuilt: trigger the O partition's rebuild and BLOCK
564    // until the epoch lands — starting computes serve nothing in that
565    // window (the partition itself keeps serving); later starts find the
566    // epoch and open immediately. A trigger failure (partition down) logs
567    // and continues UNINDEXED: the temporal rewrite stays off and the
568    // residual path answers, which is correct but slow.
569    let temporal_config = waratah_temporal::ingest_coverer_config();
570    match compute
571        .queries()
572        .hexastore()
573        .describe(PartitionAxis::O)
574        .await
575    {
576        Ok(describe) => {
577            compute.set_temporal_index_epoch(describe.temporal_index_epoch);
578            match describe.temporal_index_epoch {
579                Some(epoch) => println!("temporal rebuild-index epoch: {epoch}"),
580                None => {
581                    println!(
582                        "temporal index epoch missing; auto-rebuild starting (startup blocks until it lands)"
583                    );
584                    match compute
585                        .queries()
586                        .hexastore()
587                        .rebuild_temporal_index(temporal_config)
588                        .await
589                    {
590                        Ok((started, already_in_progress)) => {
591                            if already_in_progress {
592                                println!("rebuild already in progress; waiting for the epoch");
593                            } else if started {
594                                println!("rebuild started on the O partition");
595                            }
596                            // Bounded wait: break when the epoch lands, when
597                            // the partition reports the rebuild ENDED without
598                            // stamping (failed walk — waiting longer cannot
599                            // help), on an absolute timeout (a wedged lease),
600                            // or on probe errors. Every non-epoch exit
601                            // continues UNINDEXED: the untrusted gate keeps
602                            // the residual path answering, correctly but
603                            // slowly.
604                            let deadline = std::time::Instant::now() + REBUILD_WAIT_TIMEOUT;
605                            loop {
606                                if std::time::Instant::now() >= deadline {
607                                    eprintln!(
608                                        "warning: temporal auto-rebuild did not finish within {:?}; continuing UNINDEXED",
609                                        REBUILD_WAIT_TIMEOUT
610                                    );
611                                    break;
612                                }
613                                tokio::time::sleep(std::time::Duration::from_millis(250)).await;
614                                match compute
615                                    .queries()
616                                    .hexastore()
617                                    .describe(PartitionAxis::O)
618                                    .await
619                                {
620                                    Ok(describe) => match describe.temporal_index_epoch {
621                                        Some(epoch) => {
622                                            compute.set_temporal_index_epoch(Some(epoch));
623                                            println!(
624                                                "temporal rebuild-index complete (epoch {epoch})"
625                                            );
626                                            break;
627                                        }
628                                        None => {
629                                            if !describe.temporal_rebuild_in_progress {
630                                                eprintln!(
631                                                    "warning: temporal rebuild ended without stamping an epoch; continuing UNINDEXED (run `waratah temporal rebuild-index`)"
632                                                );
633                                                break;
634                                            }
635                                            continue;
636                                        }
637                                    },
638                                    Err(error) => {
639                                        eprintln!(
640                                            "warning: temporal auto-rebuild wait failed ({error}); continuing UNINDEXED"
641                                        );
642                                        break;
643                                    }
644                                }
645                            }
646                        }
647                        Err(error) => {
648                            eprintln!(
649                                "warning: temporal auto-rebuild trigger failed ({error}); continuing UNINDEXED"
650                            );
651                        }
652                    }
653                }
654            }
655        }
656        Err(error) => {
657            eprintln!("warning: temporal epoch probe failed ({error}); continuing UNINDEXED");
658        }
659    }
660
661    // Geo index: UNTRUSTED until its rebuild epoch exists. First startup
662    // with the plugin on a store that never rebuilt (or holds plugin-less
663    // ingested geometries): trigger the upgrade/rebuild, DRIVE it from this
664    // compute (the walk is not partition-owned), and block until the epoch
665    // lands. Concurrent starters do not drive — they wait on Describe; a
666    // driver that dies leaves a stale lease the next attempt takes over.
667    // Every non-epoch exit continues UNINDEXED (the residual `geof:*` path
668    // answers, correct but slow).
669    let geo_report = match compute
670        .queries()
671        .hexastore()
672        .describe(PartitionAxis::O)
673        .await
674    {
675        Ok(describe) => {
676            compute.set_geo_index_epoch(describe.geo_index_epoch);
677            match describe.geo_index_epoch {
678                Some(epoch) => {
679                    println!("geo rebuild-index epoch: {epoch}");
680                    None
681                }
682                None => {
683                    println!(
684                        "geo index epoch missing; auto-upgrade/rebuild starting (startup blocks until it lands)"
685                    );
686                    match crate::geo_upgrade::drive_geo_upgrade(
687                        compute.queries().hexastore(),
688                        compute.queries().registry(),
689                    )
690                    .await
691                    {
692                        Ok(Some(report)) => {
693                            println!("geo index upgrade done: {}", report.summary());
694                            match compute
695                                .queries()
696                                .hexastore()
697                                .describe(PartitionAxis::O)
698                                .await
699                            {
700                                Ok(describe) => describe.geo_index_epoch,
701                                Err(_) => None,
702                            }
703                        }
704                        // Another compute holds the lease: bounded wait on
705                        // Describe (same exits as the temporal loop).
706                        Ok(None) => {
707                            let deadline = std::time::Instant::now() + REBUILD_WAIT_TIMEOUT;
708                            loop {
709                                if std::time::Instant::now() >= deadline {
710                                    eprintln!(
711                                        "warning: geo auto-rebuild did not finish within {:?}; continuing UNINDEXED",
712                                        REBUILD_WAIT_TIMEOUT
713                                    );
714                                    break None;
715                                }
716                                tokio::time::sleep(std::time::Duration::from_millis(250)).await;
717                                match compute
718                                    .queries()
719                                    .hexastore()
720                                    .describe(PartitionAxis::O)
721                                    .await
722                                {
723                                    Ok(describe) => match describe.geo_index_epoch {
724                                        Some(epoch) => break Some(epoch),
725                                        None => {
726                                            if !describe.geo_rebuild_in_progress {
727                                                eprintln!(
728                                                    "warning: geo rebuild ended without stamping an epoch; continuing UNINDEXED (run `waratah geo rebuild-index`)"
729                                                );
730                                                break None;
731                                            }
732                                            continue;
733                                        }
734                                    },
735                                    Err(error) => {
736                                        eprintln!(
737                                            "warning: geo auto-rebuild wait failed ({error}); continuing UNINDEXED"
738                                        );
739                                        break None;
740                                    }
741                                }
742                            }
743                        }
744                        Err(error) => {
745                            eprintln!(
746                                "warning: geo auto-upgrade failed ({error}); continuing UNINDEXED"
747                            );
748                            None
749                        }
750                    }
751                }
752            }
753        }
754        Err(error) => {
755            eprintln!("warning: geo epoch probe failed ({error}); continuing UNINDEXED");
756            None
757        }
758    };
759    // Stamp whatever the upgrade settled on (None keeps the untrusted gate).
760    compute.set_geo_index_epoch(geo_report);
761
762    // Text index (when the plugin is enabled): read the epoch AND fingerprint
763    // from the O partition's Describe, and compare the fingerprint against
764    // this process's config — a mismatch means the documents were built by
765    // other settings and `text:query` must hard-fail until an offline rebuild
766    // re-stamps the epoch. Missing epoch → drive the startup build (geo
767    // lease shape, compute-driven walk) and block until it lands; every
768    // non-epoch exit continues UNINDEXED (the exact residual path answers,
769    // and `text:query` keeps failing with the repair hint).
770    if let Some(text_config) = options.text_config.clone() {
771        let fingerprint = text_config.fingerprint();
772        match compute
773            .queries()
774            .hexastore()
775            .describe(PartitionAxis::O)
776            .await
777        {
778            Ok(describe) => {
779                compute.set_text_index_state(
780                    describe.text_index_epoch,
781                    describe.text_index_fingerprint.clone(),
782                );
783                match describe.text_index_epoch {
784                    Some(epoch) if describe.text_index_fingerprint == fingerprint => {
785                        println!(
786                            "text rebuild-index epoch: {epoch} ({} docs, analyzer {}, seed {})",
787                            describe.text_index_terms, text_config.analyzer, text_config.seed_chars
788                        );
789                    }
790                    Some(_epoch) => {
791                        return Err(DevError::Backend(format!(
792                            "the text index was built with {} but this process requires {fingerprint}. \
793                             This build never rebuilds it automatically: stop the cluster and run \
794                             `waratah text rebuild-index --data-dir <data-dir>` (it rebuilds from \
795                             the hexastore), or remove the index directory and re-import",
796                            describe.text_index_fingerprint
797                        )));
798                    }
799                    None => {
800                        // The startup build is a WIPE build. A peer already
801                        // serving this data dir makes that unsafe: a document
802                        // committed just before the wipe's delete loses its
803                        // index entry while its row becomes visible (the doc
804                        // RPC acks before the axis inserts), and the stamp
805                        // gate counts only registry misses and oversized
806                        // lexicals — it cannot see the gap. Refuse the start
807                        // instead: stop the other server first (its own
808                        // startup build covers the store), or rebuild offline.
809                        if another_server_using_storage(data_dir(options)) {
810                            return Err(DevError::Backend(
811                                "cannot create text index while another compute node \
812                                 is using this storage; stop the other server first \
813                                 (its startup build covers the store), or run \
814                                 `waratah text rebuild-index` offline"
815                                    .to_owned(),
816                            ));
817                        }
818                        println!(
819                            "text index epoch missing; auto-build starting (startup blocks until it lands)"
820                        );
821                        let allow = text_config.predicate_allowlist();
822                        match waratah_text::drive_text_rebuild(
823                            compute.queries().hexastore(),
824                            compute.queries().registry(),
825                            &text_config.analyzer,
826                            text_config.seed_chars as u32,
827                            &fingerprint,
828                            allow.as_ref(),
829                            // Startup build: a WIPE build — refused above
830                            // when a peer is already serving this data dir
831                            // (the doc-loss window it guards), and a
832                            // crashed partial build is redone from scratch
833                            // on the next start.
834                            true,
835                        )
836                        .await
837                        {
838                            Ok(Some(report)) => {
839                                println!("text index build done: {}", report.summary());
840                                if let Ok(describe) = compute
841                                    .queries()
842                                    .hexastore()
843                                    .describe(PartitionAxis::O)
844                                    .await
845                                {
846                                    compute.set_text_index_state(
847                                        describe.text_index_epoch,
848                                        describe.text_index_fingerprint.clone(),
849                                    );
850                                }
851                            }
852                            // Another compute holds the lease: bounded wait on
853                            // Describe (same exits as the temporal loop).
854                            Ok(None) => {
855                                let deadline = std::time::Instant::now() + REBUILD_WAIT_TIMEOUT;
856                                loop {
857                                    if std::time::Instant::now() >= deadline {
858                                        eprintln!(
859                                            "warning: text auto-build did not finish within {:?}; continuing UNINDEXED",
860                                            REBUILD_WAIT_TIMEOUT
861                                        );
862                                        break;
863                                    }
864                                    tokio::time::sleep(std::time::Duration::from_millis(250)).await;
865                                    match compute
866                                        .queries()
867                                        .hexastore()
868                                        .describe(PartitionAxis::O)
869                                        .await
870                                    {
871                                        Ok(describe) => match describe.text_index_epoch {
872                                            Some(epoch) => {
873                                                compute.set_text_index_state(
874                                                    Some(epoch),
875                                                    describe.text_index_fingerprint.clone(),
876                                                );
877                                                println!(
878                                                    "text rebuild-index complete (epoch {epoch})"
879                                                );
880                                                break;
881                                            }
882                                            None => {
883                                                if !describe.text_rebuild_in_progress {
884                                                    eprintln!(
885                                                        "warning: text build ended without stamping an epoch; continuing UNINDEXED (run `waratah text rebuild-index`)"
886                                                    );
887                                                    break;
888                                                }
889                                                continue;
890                                            }
891                                        },
892                                        Err(error) => {
893                                            eprintln!(
894                                                "warning: text auto-build wait failed ({error}); continuing UNINDEXED"
895                                            );
896                                            break;
897                                        }
898                                    }
899                                }
900                            }
901                            Err(error) => {
902                                eprintln!(
903                                    "warning: text auto-build failed ({error}); continuing UNINDEXED"
904                                );
905                            }
906                        }
907                    }
908                }
909            }
910            Err(error) => {
911                eprintln!("warning: text epoch probe failed ({error}); continuing UNINDEXED");
912            }
913        }
914    }
915
916    // Debug sink: the daemon child redirects query/trace logging into
917    // debug.txt (truncated each start); every foreground path keeps stderr.
918    let (debug, debug_target) = match &options.debug_file {
919        Some(path) => {
920            let file = std::fs::OpenOptions::new()
921                .create(true)
922                .write(true)
923                .truncate(true)
924                .open(path)?;
925            let handle = std::sync::Arc::new(std::sync::Mutex::new(file));
926            (
927                QueryDebug::to_file(handle),
928                format!("file {}", path.display()),
929            )
930        }
931        None => (QueryDebug::from_enabled(options.debug), "stderr".to_owned()),
932    };
933    if options.debug {
934        eprintln!(
935            "SPARQL debug logging enabled (query text, timing, and client errors on {debug_target})"
936        );
937    }
938
939    match &options.query {
940        Some(sparql) => {
941            warm_gate.wait_ready().await;
942            run_query(&compute, sparql, &debug).await
943        }
944        None => match options.http {
945            Some(addr) => {
946                spawn_compute_admin(options)?;
947                if console_is_stub() {
948                    eprintln!(
949                        "warning: Waratah console is a build-time stub (no grevillea dist-console was embedded). \
950                         Run `pnpm build:console` in grevillea or set WARATAH_CONSOLE_DIST and rebuild."
951                    );
952                } else if console_missing_worker() {
953                    eprintln!(
954                        "warning: embedded console has no sw.js, so SPARQL graph downloads will fail. \
955                         Run `pnpm build:console` in grevillea and rebuild waratah."
956                    );
957                }
958                println!("Waratah console:  http://{addr}/");
959                println!("RDF4J REST API:   http://{addr}/rdf4j/");
960                println!("  protocol:       http://{addr}/rdf4j/protocol");
961                println!("  repository:     http://{addr}/rdf4j/repositories/main");
962                println!(
963                    "  explain:        http://{addr}/rdf4j/repositories/main/explain?query=..."
964                );
965                println!("  cluster:        http://{addr}/waratah/cluster");
966                println!("  health:         http://{addr}/waratah/health");
967                if notebooks.is_some() {
968                    println!(
969                        "  notebooks:      http://{addr}/jupyter (status: http://{addr}/waratah/notebooks)"
970                    );
971                }
972                if let Some(ai) = &options.ai {
973                    let upstreams = ai
974                        .upstreams
975                        .iter()
976                        .map(|upstream| upstream.id.as_str())
977                        .collect::<Vec<_>>()
978                        .join(", ");
979                    println!("  ai:             http://{addr}/waratah/ai (upstreams: {upstreams})");
980                }
981                let staging = ingest_staging_dir(&options.ingest_dir, MAIN_REPOSITORY_ID);
982                std::fs::create_dir_all(&staging)?;
983                println!("  ingest:         http://{addr}/waratah/repositories/main/ingest");
984                println!("  ingest-dir:     {}", staging.display());
985                match &options.queries_dir {
986                    Some(dir) => {
987                        println!(
988                            "  queries:        http://{addr}/waratah/repositories/main/queries"
989                        );
990                        let repo_dir = queries_repo_dir(dir, MAIN_REPOSITORY_ID);
991                        println!("  queries-dir:    {}", repo_dir.display());
992                        // The directory is never auto-created: a mistyped
993                        // `--queries-dir` would otherwise 404 forever with
994                        // no server-side hint.
995                        if !repo_dir.is_dir() {
996                            eprintln!(
997                                "warning: queries-dir {} does not exist; \
998                                 /queries will answer 404 until it does",
999                                repo_dir.display()
1000                            );
1001                        }
1002                    }
1003                    None if options.load_demo => {
1004                        println!(
1005                            "  queries:        http://{addr}/waratah/repositories/main/queries"
1006                        );
1007                        println!("  queries-dir:    (built-in demo queries)");
1008                    }
1009                    None => {}
1010                }
1011                // Bind BEFORE the readiness handshake: a bind failure
1012                // (address in use) must surface as an ordinary startup
1013                // error — an `error:` line the spawner reads while it is
1014                // still polling — never as a ready-reported daemon that
1015                // dies during teardown.
1016                let listener = waratah_api::bind_http(addr).await?;
1017                // Daemonization handshake: `ready` goes out once startup is
1018                // complete (children up, demo loaded, sketch rollup done,
1019                // index auto-rebuilds settled) and the HTTP socket is
1020                // bound; the serve loop begins immediately after. A first
1021                // boot's auto-rebuilds can make the gap between daemon
1022                // spawn and this line long; the spawner reports "still
1023                // starting" on its readiness timeout and progress lives in
1024                // the redirected output/error logs.
1025                if let Some(status) = &options.ready_file {
1026                    crate::daemon::report_ready(status);
1027                }
1028                let mut app_state = AppState::new(compute)
1029                    .with_query_debug(debug)
1030                    .with_ingest_dir(options.ingest_dir.clone())
1031                    .with_warm_state(warm_gate.warm.clone())
1032                    .with_startup_warnings(warm_gate.warnings.clone());
1033                // Query library: an explicit `--queries-dir` wins over the
1034                // built-in demo samples; with neither, requests answer 501.
1035                app_state = match options.queries_dir.clone() {
1036                    Some(dir) => app_state.with_queries_dir(dir),
1037                    None if options.load_demo => app_state.with_inline_queries(demo_queries()),
1038                    None => app_state,
1039                };
1040                if let Some(notebooks) = notebooks {
1041                    app_state = app_state.with_notebooks(notebooks.state.clone());
1042                }
1043                if let Some(ai) = &options.ai {
1044                    app_state =
1045                        app_state.with_ai(Arc::new(waratah_api::AiService::new(ai.clone())));
1046                }
1047                serve_http_until(listener, app_state, shutdown).await?;
1048                Ok(())
1049            }
1050            None => {
1051                warm_gate.wait_ready().await;
1052                spawn_compute_admin(options)?;
1053                repl(&compute, &debug, shutdown).await
1054            }
1055        },
1056    }
1057}
1058
1059/// Serve HTTP on an already-bound listener until the listener fails or
1060/// shutdown is signalled, then give outstanding requests a bounded drain
1061/// before force-closing what is left.
1062///
1063/// Kernel WebSocket tunnels live for hours and never "finish", so an
1064/// unbounded graceful drain would hang exit forever; after
1065/// [`HTTP_DRAIN_TIMEOUT`] the serve future is dropped, which closes the
1066/// remaining connections.
1067async fn serve_http_until<C>(
1068    listener: tokio::net::TcpListener,
1069    state: AppState<C>,
1070    shutdown: &ShutdownWatch,
1071) -> Result<(), DevError>
1072where
1073    C: waratah_api::ComputeBackend + Clone + Send + Sync + 'static,
1074{
1075    let server = waratah_api::serve_bound_with_shutdown(listener, state, shutdown.triggered());
1076    tokio::pin!(server);
1077    tokio::select! {
1078        result = &mut server => return result.map_err(DevError::from),
1079        _ = shutdown.triggered() => {}
1080    }
1081    match tokio::time::timeout(HTTP_DRAIN_TIMEOUT, &mut server).await {
1082        Ok(result) => result.map_err(DevError::from),
1083        Err(_elapsed) => {
1084            eprintln!("forcing HTTP connections closed (open kernel channels do not drain)");
1085            Ok(())
1086        }
1087    }
1088}
1089
1090fn spawn_compute_admin(options: &DevOptions) -> Result<(), DevError> {
1091    let addr = options.config.compute();
1092    let service = waratah_compute::ComputeAdminService::new(
1093        std::sync::Arc::new(options.config.clone()),
1094        options.describe_mode,
1095        options.default_union,
1096    )?
1097    .with_standalone(options.standalone);
1098    // Bind before spawn. A failure here (address in use) must stop startup;
1099    // the task only runs after the socket is held.
1100    let incoming = waratah_compute::bind_compute_admin(addr)?;
1101    println!("compute gRPC Describe/Health listening on {addr}");
1102    tokio::spawn(async move {
1103        if let Err(error) = waratah_compute::serve_compute_admin_incoming(incoming, service).await {
1104            eprintln!("compute gRPC server stopped: {error}");
1105        }
1106    });
1107    Ok(())
1108}
1109
1110async fn run_query<H, R>(
1111    compute: &ComputeNode<H, R>,
1112    sparql: &str,
1113    debug: &QueryDebug,
1114) -> Result<(), DevError>
1115where
1116    H: HexastoreScan + HexastoreCatalog + waratah_compute::HexastoreGeo + Send + Sync,
1117    R: StringResolve + waratah_compute::BlobStoreClient + Send + Sync,
1118{
1119    let span = debug.received(sparql);
1120    let ctx = debug.query_context(&span, compute.queries().context(SnapshotId::latest()));
1121    match compute.query_with(sparql, &ctx).await {
1122        Ok(results) => {
1123            span.finished(results.len());
1124            print_query_results(&results)?;
1125            io::stdout().flush()?;
1126            Ok(())
1127        }
1128        Err(error) => {
1129            span.fail_msg(&error);
1130            Err(error.into())
1131        }
1132    }
1133}
1134
1135/// Read one query per line from stdin until EOF, `quit`, or shutdown signal.
1136async fn repl<H, R>(
1137    compute: &ComputeNode<H, R>,
1138    debug: &QueryDebug,
1139    shutdown: &ShutdownWatch,
1140) -> Result<(), DevError>
1141where
1142    H: HexastoreScan + HexastoreCatalog + waratah_compute::HexastoreGeo + Send + Sync,
1143    R: StringResolve + waratah_compute::BlobStoreClient + Send + Sync,
1144{
1145    let mut lines = BufReader::new(tokio::io::stdin()).lines();
1146    eprintln!("enter one SPARQL query per line; `quit` or EOF to stop");
1147    loop {
1148        eprint!("waratah> ");
1149        io::stderr().flush()?;
1150        let line = tokio::select! {
1151            line = lines.next_line() => line,
1152            _ = shutdown.triggered() => break,
1153        };
1154        let Some(line) = line? else {
1155            break;
1156        };
1157        let query = line.trim();
1158        if query.is_empty() {
1159            continue;
1160        }
1161        if matches!(query, "quit" | "exit") {
1162            break;
1163        }
1164        let span = debug.received(query);
1165        let ctx = debug.query_context(&span, compute.queries().context(SnapshotId::latest()));
1166        match compute.query_with(query, &ctx).await {
1167            Ok(results) => {
1168                span.finished(results.len());
1169                if let Err(error) = print_query_results(&results) {
1170                    eprintln!("error: {error}");
1171                }
1172                io::stdout().flush()?;
1173            }
1174            Err(error) => {
1175                span.fail_msg(&error);
1176                eprintln!("error: {error}");
1177            }
1178        }
1179    }
1180    Ok(())
1181}
1182
1183fn print_query_results(results: &QueryResults) -> Result<(), DevError> {
1184    match results {
1185        QueryResults::Solutions { .. } | QueryResults::Boolean(_) => {
1186            print!("{}", results.to_tsv());
1187        }
1188        QueryResults::Graph { triples } => {
1189            let mut serializer =
1190                RdfSerializer::from_format(RdfFormat::Turtle).for_writer(Vec::new());
1191            for triple in triples {
1192                let quad = Quad {
1193                    subject: triple.subject.clone(),
1194                    predicate: triple.predicate.clone(),
1195                    object: triple.object.clone(),
1196                    graph_name: GraphName::DefaultGraph,
1197                };
1198                serializer.serialize_quad(&quad)?;
1199            }
1200            let bytes = serializer.finish()?;
1201            print!("{}", String::from_utf8_lossy(&bytes));
1202        }
1203    }
1204    Ok(())
1205}
1206
1207/// Child processes, killed when this value is dropped.
1208pub(crate) struct SpawnedCluster {
1209    children: Vec<(String, Child)>,
1210}
1211
1212impl SpawnedCluster {
1213    pub(crate) fn spawn(options: &DevOptions) -> Result<Self, DevError> {
1214        let mut cluster = Self {
1215            children: Vec::new(),
1216        };
1217        // When a serve core set is resolved, confine every child to it at
1218        // exec time (crate::affinity::confine_child): the child's whole
1219        // thread population — tonic workers, blocking pools, RocksDB
1220        // background compaction — inherits the mask instead of floating
1221        // across arbitrary cores.
1222        let serve_cores = crate::affinity::serve_core_set();
1223
1224        for axis in PartitionAxis::ALL {
1225            let addr = options.config.hexastore(axis)?;
1226            let mut command = Command::new(binary(&options.bin_dir, "waratah-partition"));
1227            if let Some(set) = &serve_cores {
1228                crate::affinity::confine_child(&mut command, set);
1229            }
1230            command
1231                .arg("--axis")
1232                .arg(axis.as_str())
1233                .arg("--listen")
1234                .arg(addr.to_string());
1235            match &options.backend {
1236                Backend::Memory => {
1237                    command.arg("--memory");
1238                }
1239                Backend::RocksDb(path) => {
1240                    command.arg("--data-dir").arg(path);
1241                }
1242            }
1243            // The O partition may self-create the text index on the first
1244            // `PutTextIndex` when the plugin is enabled but the startup
1245            // build never landed: writes keep working (new rows carry
1246            // documents), `text:query` keeps failing until a real walk
1247            // stamps the epoch. Only the O axis serves the text index.
1248            if axis == PartitionAxis::O
1249                && let Some(text) = &options.text_config
1250            {
1251                command
1252                    .arg("--text-analyzer")
1253                    .arg(&text.analyzer)
1254                    .arg("--text-seed-chars")
1255                    .arg(text.seed_chars.to_string())
1256                    .arg("--text-fingerprint")
1257                    .arg(text.fingerprint());
1258            }
1259            if options.debug {
1260                // Per-page streamed-scan timings on the child's stderr
1261                // (inherited).
1262                command.arg("--trace");
1263            }
1264            cluster.push(format!("hexastore-{axis}"), addr, command)?;
1265        }
1266
1267        let addr = options.config.registry(RegistryNodeId(0))?;
1268        let mut command = Command::new(binary(&options.bin_dir, "waratah-registry"));
1269        if let Some(set) = &serve_cores {
1270            crate::affinity::confine_child(&mut command, set);
1271        }
1272        command.arg("--listen").arg(addr.to_string());
1273        if let Backend::RocksDb(path) = &options.backend {
1274            command.arg("--data-dir").arg(path);
1275        }
1276        if options.debug {
1277            // Per-subbatch resolve timings on the child's stderr (inherited).
1278            command.arg("--trace");
1279        }
1280        cluster.push("string-registry".to_owned(), addr, command)?;
1281
1282        Ok(cluster)
1283    }
1284
1285    fn push(
1286        &mut self,
1287        name: String,
1288        addr: SocketAddr,
1289        mut command: Command,
1290    ) -> Result<(), DevError> {
1291        let child = command.spawn().map_err(|source| DevError::Spawn {
1292            program: format!("{:?}", command.get_program()),
1293            source,
1294        })?;
1295        self.children.push((name.clone(), child));
1296        wait_until_listening(&name, addr)?;
1297        println!("{name} listening on {addr}");
1298        Ok(())
1299    }
1300
1301    pub(crate) fn shutdown(&mut self) {
1302        for (name, child) in &mut self.children {
1303            if let Err(error) = child.kill() {
1304                eprintln!("could not stop {name}: {error}");
1305            }
1306            let _ = child.wait();
1307        }
1308        self.children.clear();
1309    }
1310}
1311
1312impl Drop for SpawnedCluster {
1313    fn drop(&mut self) {
1314        self.shutdown();
1315    }
1316}
1317
1318fn binary(bin_dir: &Path, name: &str) -> PathBuf {
1319    bin_dir.join(format!("{name}{}", std::env::consts::EXE_SUFFIX))
1320}
1321
1322/// Poll `addr` until the process accepts a connection or the timeout expires.
1323fn wait_until_listening(name: &str, addr: SocketAddr) -> Result<(), DevError> {
1324    let deadline = Instant::now() + STARTUP_TIMEOUT;
1325    while Instant::now() < deadline {
1326        if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok() {
1327            return Ok(());
1328        }
1329        std::thread::sleep(Duration::from_millis(50));
1330    }
1331    Err(DevError::StartupTimeout {
1332        process: name.to_owned(),
1333        addr,
1334    })
1335}
1336
1337/// Poll every storage child's `Health` RPC until its cache-warm walk finishes
1338/// (`warm_ready`), so the HTTP server — and the benchmark's start signal —
1339/// only comes up after first queries can no longer race the warm pass.
1340///
1341/// Past [`waratah_storage::WARM_MAX_WAIT`] a stuck walk stops blocking: warn
1342/// on stderr and return the pending names as startup warnings, which the
1343/// session surfaces through `/health`. Poll errors (a child briefly busy)
1344/// count as not-ready and keep the loop going until the deadline.
1345async fn wait_cluster_warm(config: &ClusterConfig) -> Result<Vec<String>, DevError> {
1346    // Build one client per child; `health()` is a cheap unary RPC.
1347    let mut clients: Vec<(String, WarmProbe)> = Vec::new();
1348    for axis in PartitionAxis::ALL {
1349        let addr = config.hexastore(axis)?;
1350        let client = HexastoreClient::connect(format!("http://{addr}"))
1351            .await
1352            .map_err(|source| DevError::Spawn {
1353                program: format!("hexastore-{} health client", axis.as_str()),
1354                source: std::io::Error::other(source.to_string()),
1355            })?;
1356        clients.push((
1357            format!("axis-{}", axis.as_str()),
1358            WarmProbe::Hexastore(client),
1359        ));
1360    }
1361    let registry_addr = config.registry(RegistryNodeId(0))?;
1362    let registry_client = StringRegistryClient::connect(format!("http://{registry_addr}"))
1363        .await
1364        .map_err(|source| DevError::Spawn {
1365            program: "string-registry health client".to_owned(),
1366            source: std::io::Error::other(source.to_string()),
1367        })?;
1368    clients.push(("registry".to_owned(), WarmProbe::Registry(registry_client)));
1369
1370    let deadline = Instant::now() + waratah_storage::WARM_MAX_WAIT;
1371    loop {
1372        let mut pending: Vec<String> = Vec::new();
1373        for (name, probe) in &mut clients {
1374            let ready = match probe {
1375                WarmProbe::Hexastore(client) => client
1376                    .health(pb::HealthRequest {})
1377                    .await
1378                    .map(|response| response.into_inner().warm_ready)
1379                    .unwrap_or(false),
1380                WarmProbe::Registry(client) => client
1381                    .health(pb::HealthRequest {})
1382                    .await
1383                    .map(|response| response.into_inner().warm_ready)
1384                    .unwrap_or(false),
1385            };
1386            if !ready {
1387                pending.push(name.clone());
1388            }
1389        }
1390        if pending.is_empty() {
1391            return Ok(Vec::new());
1392        }
1393        if Instant::now() >= deadline {
1394            eprintln!(
1395                "warning: cache-warm stuck for {:?}; pending: {pending:?} — starting without a full warm",
1396                waratah_storage::WARM_MAX_WAIT
1397            );
1398            return Ok(vec![format!("cache-warm stuck; pending: {pending:?}")]);
1399        }
1400        tokio::time::sleep(Duration::from_millis(200)).await;
1401    }
1402}
1403
1404/// One storage child's `Health` probe (the two tonic client types differ, so
1405/// the poll matches on which it holds).
1406enum WarmProbe {
1407    Hexastore(HexastoreClient<tonic::transport::Channel>),
1408    Registry(StringRegistryClient<tonic::transport::Channel>),
1409}
1410
1411/// Built-in query library published under `--load-demo` when no
1412/// `--queries-dir` is configured. Every query returns rows over
1413/// [`demo_dataset`], so the console Query library works out of the box.
1414/// Entries keep this declaration order on the wire (the `(order, id)` sort
1415/// belongs to the directory source, not the inline one).
1416pub fn demo_queries() -> Vec<ServerQuery> {
1417    fn query(id: &str, name: &str, description: &str, body: &str) -> ServerQuery {
1418        ServerQuery {
1419            id: id.to_owned(),
1420            name: name.to_owned(),
1421            description: Some(description.to_owned()),
1422            query: format!("PREFIX ex: <http://ex/>\n{body}"),
1423        }
1424    }
1425
1426    vec![
1427        query(
1428            "people",
1429            "People",
1430            "Every ex:Person with its name",
1431            "SELECT ?person ?name WHERE {\n  ?person a ex:Person ;\n        ex:name ?name .\n}\nORDER BY ?name\n",
1432        ),
1433        query(
1434            "cities",
1435            "Cities by weather",
1436            "Cities and the weather recorded for them",
1437            "SELECT ?city ?weather WHERE {\n  ?city a ex:City ;\n        ex:hasWeather ?weather .\n}\nORDER BY ?city\n",
1438        ),
1439        query(
1440            "people-and-weather",
1441            "People and weather",
1442            "Where each person lives and what the weather is there",
1443            "SELECT ?person ?weather WHERE {\n  ?person ex:livesIn ?city .\n  ?city ex:hasWeather ?weather .\n}\nORDER BY ?person\n",
1444        ),
1445    ]
1446}
1447
1448/// Weather/city dataset behind the demo `SELECT`, extended with the
1449/// schema triples the AI-context endpoint demonstrates against: an
1450/// `rdfs:label` on every subject and a two-level `rdfs:subClassOf`
1451/// hierarchy (`Person → Agent → Thing`, `City → Place → Thing`). The
1452/// parent classes deliberately have no instances — they surface only via
1453/// the transitive `superClasses` closure, which is exactly the shape the
1454/// endpoint must get right.
1455pub fn demo_dataset() -> Vec<Quad> {
1456    fn iri(local: &str) -> NamedNode {
1457        NamedNode::new(format!("http://ex/{local}")).expect("valid demo IRI")
1458    }
1459    fn label(local: &str, text: &str) -> Quad {
1460        Quad::new(
1461            iri(local),
1462            oxrdf::vocab::rdfs::LABEL,
1463            Literal::from(text),
1464            GraphName::DefaultGraph,
1465        )
1466    }
1467    fn sub_class_of(child: &str, parent: &str) -> Quad {
1468        Quad::new(
1469            iri(child),
1470            oxrdf::vocab::rdfs::SUB_CLASS_OF,
1471            iri(parent),
1472            GraphName::DefaultGraph,
1473        )
1474    }
1475
1476    vec![
1477        Quad::new(
1478            iri("alice"),
1479            oxrdf::vocab::rdf::TYPE,
1480            iri("Person"),
1481            GraphName::DefaultGraph,
1482        ),
1483        Quad::new(
1484            iri("alice"),
1485            iri("name"),
1486            Literal::from("Alice"),
1487            GraphName::DefaultGraph,
1488        ),
1489        Quad::new(
1490            iri("bob"),
1491            oxrdf::vocab::rdf::TYPE,
1492            iri("Person"),
1493            GraphName::DefaultGraph,
1494        ),
1495        Quad::new(
1496            iri("bob"),
1497            iri("name"),
1498            Literal::from("Bob"),
1499            GraphName::DefaultGraph,
1500        ),
1501        Quad::new(
1502            iri("brisbane"),
1503            oxrdf::vocab::rdf::TYPE,
1504            iri("City"),
1505            GraphName::DefaultGraph,
1506        ),
1507        Quad::new(
1508            iri("hobart"),
1509            oxrdf::vocab::rdf::TYPE,
1510            iri("City"),
1511            GraphName::DefaultGraph,
1512        ),
1513        Quad::new(
1514            iri("alice"),
1515            iri("livesIn"),
1516            iri("brisbane"),
1517            GraphName::DefaultGraph,
1518        ),
1519        Quad::new(
1520            iri("bob"),
1521            iri("livesIn"),
1522            iri("hobart"),
1523            GraphName::DefaultGraph,
1524        ),
1525        Quad::new(
1526            iri("brisbane"),
1527            iri("hasWeather"),
1528            Literal::from("Sunny"),
1529            GraphName::DefaultGraph,
1530        ),
1531        Quad::new(
1532            iri("hobart"),
1533            iri("hasWeather"),
1534            Literal::from("Cold"),
1535            GraphName::DefaultGraph,
1536        ),
1537        // Schema: subclass hierarchy (parents have no instances on
1538        // purpose — see the doc comment).
1539        sub_class_of("Person", "Agent"),
1540        sub_class_of("Agent", "Thing"),
1541        sub_class_of("City", "Place"),
1542        sub_class_of("Place", "Thing"),
1543        // Labels for every subject: instances, classes, and predicates.
1544        label("alice", "Alice"),
1545        label("bob", "Bob"),
1546        label("brisbane", "Brisbane"),
1547        label("hobart", "Hobart"),
1548        label("Person", "Person"),
1549        label("City", "City"),
1550        label("Agent", "Agent"),
1551        label("Place", "Place"),
1552        label("Thing", "Thing"),
1553        label("name", "name"),
1554        label("livesIn", "lives in"),
1555        label("hasWeather", "has weather"),
1556    ]
1557}
1558
1559#[cfg(test)]
1560mod tests {
1561    use super::*;
1562
1563    #[test]
1564    fn demo_dataset_matches_the_architecture_example() {
1565        let quads = demo_dataset();
1566        assert_eq!(quads.len(), 26);
1567        assert!(
1568            quads
1569                .iter()
1570                .any(|quad| quad.object == Literal::from("Sunny").into())
1571        );
1572    }
1573
1574    #[test]
1575    fn demo_queries_have_unique_ids_and_bodies() {
1576        let queries = demo_queries();
1577        assert_eq!(queries.len(), 3);
1578        let mut ids: Vec<&str> = queries.iter().map(|query| query.id.as_str()).collect();
1579        ids.sort_unstable();
1580        let unique = ids.len();
1581        ids.dedup();
1582        assert_eq!(ids.len(), unique, "demo query ids must be unique");
1583        for query in &queries {
1584            assert!(!query.name.is_empty());
1585            assert!(query.query.starts_with("PREFIX ex: <http://ex/>"));
1586            assert!(query.query.contains("SELECT"));
1587            // WHERE block closes before a trailing solution modifier.
1588            assert!(query.query.contains("}\nORDER BY ?"));
1589        }
1590    }
1591
1592    #[test]
1593    fn binary_paths_sit_next_to_the_orchestrator() {
1594        let path = binary(Path::new("/opt/waratah"), "waratah-partition");
1595        assert!(path.starts_with("/opt/waratah"));
1596        assert!(
1597            path.file_name()
1598                .unwrap()
1599                .to_string_lossy()
1600                .starts_with("waratah-partition")
1601        );
1602    }
1603
1604    #[test]
1605    fn tmpfs_detection_flags_dev_shm_and_missing_paths() {
1606        // /dev/shm is tmpfs by Linux convention. /tmp must not be asserted on:
1607        // it is disk-backed on several distros.
1608        #[cfg(target_os = "linux")]
1609        if Path::new("/dev/shm").exists() {
1610            assert!(is_tmpfs(Path::new("/dev/shm")));
1611        }
1612        assert!(!is_tmpfs(Path::new("/waratah-no-such-spill-path")));
1613    }
1614
1615    #[test]
1616    fn another_server_detection_reads_the_data_dir_pidfile() {
1617        // A memory backend shares no storage: each process owns its store,
1618        // so there is nothing to detect even with a pidfile around.
1619        assert!(!another_server_using_storage(None));
1620
1621        let dir = std::env::temp_dir().join(format!("waratah-m1-detect-{}", std::process::id()));
1622        std::fs::create_dir_all(&dir).unwrap();
1623        let pid_file = dir.join(DEV_PID_FILE);
1624
1625        // Our own pid is the pidfile this process just wrote — not a peer.
1626        std::fs::write(&pid_file, std::process::id().to_string()).unwrap();
1627        assert!(!another_server_using_storage(Some(&dir)));
1628
1629        // Unparseable content: no detection.
1630        std::fs::write(&pid_file, "not-a-pid").unwrap();
1631        assert!(!another_server_using_storage(Some(&dir)));
1632
1633        // A live foreign pid is a serving peer. The test runner (this
1634        // process's parent) is guaranteed alive and is not us; the stat
1635        // parse mirrors `process_alive`'s zombie check (split after `comm`).
1636        #[cfg(target_os = "linux")]
1637        {
1638            let stat = std::fs::read_to_string("/proc/self/stat").unwrap();
1639            let after_comm = stat.rsplit(')').next().unwrap();
1640            let ppid: u32 = after_comm
1641                .split_whitespace()
1642                .nth(1)
1643                .expect("ppid follows the state field")
1644                .parse()
1645                .unwrap();
1646            std::fs::write(&pid_file, ppid.to_string()).unwrap();
1647            assert!(
1648                another_server_using_storage(Some(&dir)),
1649                "a live foreign pid in the data dir's pidfile is a peer (ppid {ppid})"
1650            );
1651        }
1652
1653        // No pidfile: nothing known (fresh dir, or a stopped cluster).
1654        std::fs::remove_file(&pid_file).unwrap();
1655        assert!(!another_server_using_storage(Some(&dir)));
1656        std::fs::remove_dir(&dir).ok();
1657    }
1658}