Skip to main content

waratah/
main.rs

1//! Waratah CLI: cluster orchestrator, RDF import, and local SPARQL tools.
2//!
3//! `waratah start` brings up the cluster on localhost: hexastore partitions
4//! **S**, **P**, **O** and the **string-registry** run as child processes,
5//! and this process becomes the stateless **compute** node behind an RDF4J
6//! HTTP facade. It daemonizes itself by default (logs under
7//! `{data_dir}/logs`, or the working directory for the memory backend);
8//! `--foreground` keeps it attached to the terminal. `waratah standalone`
9//! opens those storage bricks in this process instead of spawning children
10//! (no gRPC) and always runs in the foreground.
11//!
12//! `waratah import` streams an RDF file into RocksDB. Default spawns S/P/O +
13//! registry, loads over gRPC, then flushes (and optionally compacts).
14//! `--offline` writes in-process; `--connect` attaches to a running cluster.
15//!
16//! `waratah explain` prints a SPARQL query as parse-only SSE, Sparopt
17//! SSE/SPARQL, or a lowered plan (no cluster required).
18//!
19//! `waratah compact` flushes and full-range-compacts targets of an existing
20//! data-dir in-process, so rewritten SSTs pick up the current tuning
21//! (registry block size, stats collectors) without a re-import.
22
23mod affinity;
24mod blob;
25mod catalog;
26mod compact;
27mod config_dir;
28mod daemon;
29mod dev;
30mod error;
31mod geo;
32mod geo_upgrade;
33mod import;
34mod notebook;
35mod shutdown;
36mod standalone;
37mod temporal;
38mod text;
39
40use std::net::SocketAddr;
41use std::path::PathBuf;
42use std::process::ExitCode;
43
44use clap::{Parser, Subcommand};
45use mimalloc::MiMalloc;
46use waratah_compute::{DescribeMode, ExplainFormat, ExplainOptions, LogicalPlan};
47use waratah_router::ClusterConfig;
48use waratah_storage::{CommitTs, ingest_root_dir};
49use waratah_text::TextPluginConfig;
50
51use crate::compact::CompactTarget;
52use crate::dev::{Backend, DEFAULT_HTTP_ADDR, DevOptions};
53use crate::error::DevError;
54use crate::import::ImportOptions;
55
56/// Distributed RDF quadstore — CLI.
57#[derive(Parser)]
58#[command(name = "waratah", version, about, arg_required_else_help = true)]
59struct Cli {
60    /// Print compile-time build provenance (git describe, commit, toolchain)
61    /// and exit. `--version` prints the bare semver.
62    #[arg(long)]
63    build_info: bool,
64
65    #[command(subcommand)]
66    command: Option<Commands>,
67}
68
69#[derive(Subcommand)]
70// `Start(StartArgs)` dwarfs the other subcommands; this enum is constructed
71// once per invocation, so the padding is not worth boxing through clap.
72#[allow(clippy::large_enum_variant)]
73enum Commands {
74    /// Start S/P/O partitions, the string registry, and a compute node.
75    ///
76    /// Daemonized by default (logs under `{data_dir}/logs`, or the working
77    /// directory for the memory backend). `--foreground` stays attached to
78    /// the terminal.
79    Start(StartArgs),
80    /// Open S/P/O and the registry in this process (no child processes, no
81    /// gRPC) and run compute in the foreground.
82    Standalone(StandaloneArgs),
83    /// Stop a running cluster (SIGTERM via its pidfile) — storage children
84    /// and the notebook sidecar go with it.
85    Stop(StopArgs),
86    /// Stream an RDF file into a RocksDB data-dir (or a running cluster).
87    Import(ImportArgs),
88    /// Print SPARQL parse / Sparopt / planned algebra (no cluster required).
89    Explain(ExplainArgs),
90    /// Text index operations (text plugin).
91    Text {
92        #[command(subcommand)]
93        command: TextCommands,
94    },
95    /// Rebuild the S-axis named-graph catalog from existing SPOG data.
96    Catalog {
97        #[command(subcommand)]
98        command: CatalogCommands,
99    },
100    /// GeoSPARQL index maintenance (compute/offline side; the O partition
101    /// never runs the coverer).
102    Geo {
103        #[command(subcommand)]
104        command: GeoCommands,
105    },
106    /// Temporal index maintenance (partition-side walk).
107    Temporal {
108        #[command(subcommand)]
109        command: TemporalCommands,
110    },
111    /// Flush and compact targets of an existing RocksDB data-dir (offline).
112    Compact(CompactArgs),
113    /// Blob store maintenance (registry-side content-addressed store).
114    Blob {
115        #[command(subcommand)]
116        command: BlobCommands,
117    },
118}
119
120#[derive(Subcommand)]
121enum BlobCommands {
122    /// Integrity scan: index identity, segment record CRCs and payload
123    /// identity, orphan census. Opens the store through normal recovery
124    /// (like a registry open would), not a raw read-only pass.
125    Verify(BlobVerifyArgs),
126}
127
128#[derive(Parser)]
129struct BlobVerifyArgs {
130    /// RocksDB data directory whose `{data_dir}/main/blobs` is scanned.
131    #[arg(long)]
132    data_dir: PathBuf,
133}
134
135#[derive(Subcommand)]
136enum GeoCommands {
137    /// Wipe and recompute every O-axis S2 posting under the CURRENT coverer
138    /// config (required after changing `--geo-min-level` / `--geo-max-level`
139    /// / `--geo-max-cells`, or after a covering algorithm change).
140    RebuildIndex(GeoRebuildArgs),
141    /// Read-only per-level census of the O-axis S2 posting store: posting
142    /// counts by cell level, envelope coverage, and the stats histogram's
143    /// incidence mass (diagnoses geo window-estimate over-counting).
144    /// `--window <WKT>` adds the estimate-ladder decomposition and the
145    /// drain truth for one query window.
146    Census(GeoCensusArgs),
147}
148
149#[derive(clap::Args)]
150struct GeoRebuildArgs {
151    /// RocksDB data directory (`{data_dir}/main/o` is opened; blobs come
152    /// from `{data_dir}/main/blobs`).
153    #[arg(long)]
154    data_dir: PathBuf,
155}
156
157#[derive(clap::Args)]
158struct GeoCensusArgs {
159    /// RocksDB data directory (`{data_dir}/main/o` is opened read-only).
160    #[arg(long)]
161    data_dir: PathBuf,
162    /// Estimate + drain-truth decomposition for one query window given as
163    /// WKT (the same literal form a `geof:*` conjunct carries). The
164    /// covering uses the coverer flags below — the config the planner
165    /// would run under.
166    #[arg(long)]
167    window: Option<String>,
168    #[command(flatten)]
169    coverer: GeoCovererArgs,
170}
171
172#[derive(Subcommand)]
173enum TemporalCommands {
174    /// Wipe and recompute every O-axis temporal posting (partition-side
175    /// walk; required after changing the temporal covering params, and the
176    /// manual path for what compute startup auto-triggers when the epoch is
177    /// missing).
178    RebuildIndex(TemporalRebuildArgs),
179}
180
181#[derive(clap::Subcommand)]
182enum TextCommands {
183    /// Wipe and rebuild the O-axis text index from the hexastore (offline;
184    /// required after changing the analyzer or seed length, and the manual
185    /// repair path for what compute startup auto-builds when the epoch is
186    /// missing). The data dir must NOT be open by a running cluster (the
187    /// Tantivy directory is single-writer).
188    RebuildIndex(TextRebuildArgs),
189    /// Print the index sidecar's stored settings, trust state, and live
190    /// document count next to the resolved config.
191    Status(TextStatusArgs),
192}
193
194#[derive(clap::Args)]
195struct TextRebuildArgs {
196    /// RocksDB data directory (`{data_dir}/main/o` is opened in-process).
197    #[arg(long)]
198    data_dir: PathBuf,
199    /// Config directory for `{config-dir}/text.toml` (analyzer, seed
200    /// length). Without it the defaults apply.
201    #[arg(long)]
202    config_dir: Option<PathBuf>,
203}
204
205#[derive(clap::Args)]
206struct TextStatusArgs {
207    /// RocksDB data directory (`{data_dir}/main/o-text-index` is read).
208    #[arg(long)]
209    data_dir: PathBuf,
210    /// Config directory for `{config-dir}/text.toml`.
211    #[arg(long)]
212    config_dir: Option<PathBuf>,
213}
214
215#[derive(clap::Args)]
216struct TemporalRebuildArgs {
217    /// RocksDB data directory (`{data_dir}/main/o` is opened in-process).
218    #[arg(long)]
219    data_dir: PathBuf,
220    /// Minimum covering node level (temporal index).
221    #[arg(long, default_value_t = 0)]
222    temporal_min_level: u8,
223    /// Maximum covering node level (temporal index; instants bypass the
224    /// covering entirely).
225    #[arg(long, default_value_t = 110)]
226    temporal_max_level: u8,
227    /// Maximum nodes per interval (temporal index).
228    #[arg(long, default_value_t = 32)]
229    temporal_max_nodes: usize,
230}
231
232/// Process coverer configuration from CLI flags (v1: per-process; the
233/// cluster-uniform invariant is documented in ARCH.md §6).
234#[derive(Debug, Clone, Copy, clap::Args)]
235pub struct GeoCovererArgs {
236    /// Minimum S2 covering cell level (GeoSPARQL index).
237    #[arg(long, default_value_t = 0)]
238    geo_min_level: u8,
239    /// Maximum S2 covering cell level (points stay at the level-30 leaf).
240    #[arg(long, default_value_t = 24)]
241    geo_max_level: u8,
242    /// Maximum cells per covering (see `waratah_geo::covering` for why the
243    /// default sits above S2's own library default).
244    #[arg(long, default_value_t = 40)]
245    geo_max_cells: usize,
246    /// Planar edge densification step in degrees: polygon/line-string edges
247    /// longer than this are subdivided before the S2 covering, so the
248    /// geodesic candidate index is a superset of the planar (WKT) region.
249    /// `0`, `false`, `off`, or `no` disables; `true` selects the default.
250    /// Steps below 0.0001 are rejected — below the covering's own cell
251    /// resolution they buy no accuracy, only unbounded covering time.
252    /// Changing this requires `waratah geo rebuild-index`.
253    #[arg(long, default_value = "0.1", value_parser = parse_densify_step)]
254    geo_densify_step: f64,
255}
256
257/// Parse `--geo-densify-step`: a non-negative degree value (floored at
258/// [`waratah_geo::MIN_DENSIFY_STEP_DEG`]), or the words `false`/`0`
259/// (disable densification) / `true` (the default step).
260fn parse_densify_step(value: &str) -> Result<f64, String> {
261    match value.trim().to_ascii_lowercase().as_str() {
262        "false" | "off" | "no" => Ok(0.0),
263        "true" | "on" | "yes" => Ok(waratah_geo::DEFAULT_DENSIFY_STEP_DEG),
264        _ => {
265            let step: f64 = value.trim().parse().map_err(|_| {
266                format!(
267                    "invalid densify step {value:?}: expected a degree value (e.g. 0.1), 0, or false"
268                )
269            })?;
270            if !step.is_finite() {
271                return Err(format!("densify step must be a finite number, got {step}"));
272            }
273            if step < 0.0 {
274                return Err(format!("densify step must be >= 0.0, got {step}"));
275            }
276            if step != 0.0 && step < waratah_geo::MIN_DENSIFY_STEP_DEG {
277                let min = waratah_geo::MIN_DENSIFY_STEP_DEG;
278                return Err(format!(
279                    "densify step {step:e} is below the minimum {min} degrees — steps that fine \
280                     buy no accuracy beyond the covering's cell resolution and only inflate \
281                     covering time (use 0 to disable)"
282                ));
283            }
284            Ok(step)
285        }
286    }
287}
288
289impl GeoCovererArgs {
290    /// Apply onto the geo plugin's process config.
291    pub fn apply(self) {
292        waratah_geo::set_coverer_config(waratah_geo::CovererConfig {
293            min_level: self.geo_min_level,
294            max_level: self.geo_max_level,
295            max_cells: self.geo_max_cells,
296            densify_step_deg: self.geo_densify_step,
297        });
298    }
299}
300
301#[derive(Parser)]
302struct StopArgs {
303    /// Data dir of the cluster to stop; the pidfile is
304    /// `{data_dir}/waratah-dev.pid`. Without it, the working directory is
305    /// searched (`./waratah-dev.pid` — where a memory-backend daemon
306    /// writes its pidfile).
307    #[arg(long)]
308    data_dir: Option<PathBuf>,
309}
310
311#[derive(Subcommand)]
312enum CatalogCommands {
313    /// Scan SPOG and write Present for each distinct named graph (skip DefaultGraph).
314    Rebuild(CatalogRebuildArgs),
315}
316
317#[derive(Parser)]
318struct CatalogRebuildArgs {
319    /// RocksDB data directory (`{data_dir}/main/s` is opened).
320    #[arg(long)]
321    data_dir: PathBuf,
322}
323
324#[derive(Parser)]
325struct CompactArgs {
326    /// RocksDB data directory (`{data_dir}/main/{s,p,o,registry}` are opened).
327    #[arg(long)]
328    data_dir: PathBuf,
329
330    /// Targets to compact (s, p, o, registry; case-insensitive).
331    /// Default: all of them, sequentially.
332    #[arg(value_enum, value_name = "TARGET", ignore_case = true)]
333    targets: Vec<CompactTarget>,
334}
335
336#[derive(Clone, Copy, Debug, Default, clap::ValueEnum)]
337#[value(rename_all = "kebab-case")]
338enum ExplainFormatArg {
339    /// Level 0: parse-only Jena SSE.
340    #[default]
341    Sse,
342    /// Level 1: Sparopt + VALUES-into-UNION, Jena SSE.
343    #[value(alias = "optimized")]
344    Optimised,
345    /// Level 1 as SPARQL syntax.
346    #[value(alias = "optimized-sparql")]
347    OptimisedSparql,
348    /// Level 2: fully lowered plan, Jena-like SSE.
349    Planned,
350    /// Level 2 as best-effort SPARQL.
351    PlannedSparql,
352    /// Level 2 SSE plus row estimates, domains, and broadcast annotations.
353    #[value(alias = "estimates")]
354    Estimate,
355}
356
357impl From<ExplainFormatArg> for ExplainFormat {
358    fn from(format: ExplainFormatArg) -> Self {
359        match format {
360            ExplainFormatArg::Sse => Self::Sse,
361            ExplainFormatArg::Optimised => Self::Optimised,
362            ExplainFormatArg::OptimisedSparql => Self::OptimisedSparql,
363            ExplainFormatArg::Planned => Self::Planned,
364            ExplainFormatArg::PlannedSparql => Self::PlannedSparql,
365            ExplainFormatArg::Estimate => Self::Estimate,
366        }
367    }
368}
369
370#[derive(Clone, Debug, Default, clap::ValueEnum)]
371enum DescribeModeArg {
372    /// Outgoing plus incoming (skip blank incoming subjects). No bnode closure.
373    #[default]
374    Star,
375    /// Outgoing triples with blank-node object closure.
376    Cbd,
377    /// CBD plus all incoming triples, plus CBD of blank incoming subjects.
378    Scbd,
379}
380
381impl From<DescribeModeArg> for DescribeMode {
382    fn from(mode: DescribeModeArg) -> Self {
383        match mode {
384            DescribeModeArg::Star => DescribeMode::Star,
385            DescribeModeArg::Cbd => DescribeMode::Cbd,
386            DescribeModeArg::Scbd => DescribeMode::Scbd,
387        }
388    }
389}
390
391#[derive(Parser)]
392struct ImportArgs {
393    /// RDF file (Turtle, TriG, N-Triples, N-Quads, RDF/XML; `.gz` ok).
394    file: PathBuf,
395
396    /// RocksDB directory to write (created if missing; existing data is kept).
397    /// Required unless `--connect`.
398    #[arg(long, required_unless_present = "connect")]
399    data_dir: Option<PathBuf>,
400
401    /// Commit timestamp for every imported quad (default: current unix millis).
402    #[arg(long)]
403    timestamp: Option<u64>,
404
405    /// Force a full-range compaction after flush (online: once at the end).
406    /// Offline always compact after load so stats land in SST properties.
407    #[arg(long)]
408    compact: bool,
409
410    /// In-process load: no gRPC, exclusive with `--connect`.
411    #[arg(long, conflicts_with = "connect")]
412    offline: bool,
413
414    /// Attach to a running cluster via `--config`; do not spawn or kill children.
415    #[arg(long, conflicts_with = "offline")]
416    connect: bool,
417
418    /// Skip the write-ahead log for the hexastore and dictionary stores
419    /// (offline only). The blob index is excluded: its commits are
420    /// synchronous by design (durable locators are the segment tier's
421    /// durability contract), so this flag never applies to it.
422    #[arg(long, requires = "offline")]
423    disable_wal: bool,
424
425    /// Ingest via SstFileWriter (offline only; not implemented yet).
426    #[arg(long, requires = "offline")]
427    direct_sst: bool,
428
429    /// Static five-process address table (TOML); defaults to 127.0.0.1:7001-7005.
430    #[arg(long)]
431    config: Option<PathBuf>,
432
433    /// Directory holding `waratah-partition` / `waratah-registry`; defaults to this binary's.
434    #[arg(long)]
435    bin_dir: Option<PathBuf>,
436
437    /// Enable the text plugin for this import (see `waratah start
438    /// --with-text`). Also settable via `{config-dir}/text.toml`; the
439    /// fingerprint must match an existing index. Required before the
440    /// loader will stamp a text epoch on a fresh store.
441    #[arg(long)]
442    with_text: bool,
443
444    /// Config directory for `{config-dir}/text.toml` resolution.
445    #[arg(long)]
446    config_dir: Option<PathBuf>,
447}
448
449#[derive(Parser)]
450struct ExplainArgs {
451    /// SPARQL query to optimize (`SELECT`, `ASK`, `CONSTRUCT`, or `DESCRIBE`).
452    #[arg(long, short = 'q')]
453    query: String,
454
455    /// Output format.
456    #[arg(long, short = 'f', value_enum, default_value_t = ExplainFormatArg::Sse)]
457    format: ExplainFormatArg,
458
459    /// Pretty-print S-expression and `*-sparql` output.
460    #[arg(long, short = 'p')]
461    pretty: bool,
462
463    /// SPARQL default graph is the union of all named and unnamed graphs.
464    #[arg(long)]
465    default_union: bool,
466
467    /// Seat inner-join arms by the total seating cost so EXPLAIN shows the
468    /// seat a server started with `--seat-by-total-cost` would run.
469    #[arg(long)]
470    seat_by_total_cost: bool,
471}
472
473/// Flags shared by `waratah start` and `waratah standalone`: everything
474/// about serving queries. The spawn-only flags (`--config`, `--bin-dir`)
475/// live on [`StartArgs`] alone — the in-process standalone command has no
476/// children to address or binaries to locate.
477#[derive(clap::Args)]
478struct ServeArgs {
479    /// Configuration directory: where `cluster.toml`, `notebooks.toml`, and
480    /// (later) other config files are looked up.
481    ///
482    /// Defaults to the XDG search path — `~/.config/waratah` first, then
483    /// `/etc/waratah` (macOS: `~/Library/Application Support/waratah` then
484    /// `/Library/Application Support/waratah`; Windows: `%APPDATA%\waratah`
485    /// then `%PROGRAMDATA%\waratah`). Given explicitly, ONLY that directory
486    /// is searched.
487    #[arg(long)]
488    config_dir: Option<PathBuf>,
489
490    /// Persist partitions to RocksDB under this directory instead of memory.
491    #[arg(long)]
492    data_dir: Option<PathBuf>,
493
494    /// Load the weather/city demo dataset before serving queries.
495    #[arg(long)]
496    load_demo: bool,
497
498    /// Run one SPARQL query and exit instead of starting the HTTP server.
499    #[arg(long)]
500    query: Option<String>,
501
502    /// RDF4J HTTP listen address.
503    #[arg(long, default_value = DEFAULT_HTTP_ADDR)]
504    http: String,
505
506    /// Skip the RDF4J HTTP server and use the stdin SPARQL REPL instead.
507    #[arg(long)]
508    no_http: bool,
509
510    /// Log SPARQL query text, timings, and client-facing errors to stderr
511    /// (foreground) or debug.txt (daemonized).
512    #[arg(long)]
513    debug: bool,
514
515    /// Seat inner-join arms by the total seating cost (the `join-seat-shadow`
516    /// comparator promoted to decision) instead of the default `driver_cost`
517    /// rule. Divergent seats log as `join-seat-totals` at debug level.
518    #[arg(long)]
519    seat_by_total_cost: bool,
520
521    /// Benchmark switch: stamp `Semi` on joins whose only refusal is the
522    /// per-page cost verdict. The semantic semi gates (payload,
523    /// multiplicity, keys, specialized scans) still refuse. Used to A/B the
524    /// general semi build against the per-page road; not a production hint.
525    #[arg(long)]
526    force_semi: bool,
527
528    /// Disable slot comparison pushdown and the eager scan filter (the plan
529    /// FILTER alone decides). Diagnostic/benchmark switch: off is the
530    /// pre-feature path, with nothing stamped and no comparison on the wire.
531    /// Production leaves it on.
532    #[arg(long)]
533    no_eager_scan_filter: bool,
534
535    /// SPARQL DESCRIBE algorithm (default star).
536    #[arg(long, value_enum, default_value_t = DescribeModeArg::Star)]
537    describe_mode: DescribeModeArg,
538
539    /// SPARQL default graph is the union of all named and unnamed graphs.
540    #[arg(long)]
541    default_union: bool,
542
543    /// Strict SPARQL 1.1 adherence: gate Waratah's documented deviations
544    /// (gYear-family ordering comparisons become type errors, and future
545    /// deviations) behind spec-strict behavior.
546    #[arg(long)]
547    strict_sparql: bool,
548
549    /// Staging parent for HTTP ingest (uploads and operator-copied RDF).
550    ///
551    /// Files live in `{ingest_dir}/{repository}` (repository is `main`).
552    /// Defaults to `{data_dir}/ingest` when `--data-dir` is set, otherwise `./ingest`.
553    #[arg(long)]
554    ingest_dir: Option<PathBuf>,
555
556    /// Published query library for the console Query library
557    /// (`GET /waratah/repositories/{id}/queries`).
558    ///
559    /// One `<id>.rq` file (optional `<id>.toml` sidecar) per query, under
560    /// `{queries_dir}/{repository}`. Without it the endpoint answers `501`,
561    /// unless `--load-demo` publishes its built-in samples.
562    #[arg(long)]
563    queries_dir: Option<PathBuf>,
564
565    /// Root directory for query spill files (external ORDER BY runs, Grace
566    /// join partitions, parked pages, DISTINCT seen-sets).
567    ///
568    /// Defaults to `{data_dir}/spill` when `--data-dir` is set. Without a
569    /// data dir (memory backend) spill falls back to the system temp dir,
570    /// which is RAM-backed (tmpfs) on many Linux systems — spilled pages
571    /// then stay in RAM and a warning is logged.
572    #[arg(long)]
573    spill_dir: Option<PathBuf>,
574
575    /// Enable the Jupyter notebook service: a jupyter-server sidecar (one
576    /// per compute) reverse-proxied at `/jupyter`, WebSocket kernel
577    /// channels included. Requires the HTTP server.
578    #[arg(long)]
579    with_notebooks: bool,
580
581    /// Enable AI services: the LLM egress proxy at
582    /// `/waratah/ai/upstreams/*` (bring-your-own-key) and the
583    /// `/waratah/repositories/main/ai-context` schema endpoint. Also
584    /// settable as `[ai] enabled = true` in `{config-dir}/ai.toml`; when
585    /// no upstreams are declared there, the `zen` upstream is
586    /// preconfigured. Requires the HTTP server.
587    #[arg(long)]
588    with_ai: bool,
589
590    /// Enable the text plugin: Jena-style `FILTER text:query`, indexed
591    /// `STRSTARTS` / `STRENDS` / anchored `REGEX`, and a Tantivy index the
592    /// O partition maintains. Also settable as `enabled = true` in
593    /// `{config-dir}/text.toml`. Off by default (the index covers every
594    /// string literal, so always-on would change every deployment's write
595    /// latency and disk baseline). Changing `analyzer` or `seed_chars`
596    /// after a build requires an offline rebuild.
597    #[arg(long)]
598    with_text: bool,
599
600    /// Contents root for the notebook service.
601    ///
602    /// Defaults to `{data_dir}/notebooks` when `--data-dir` is set,
603    /// otherwise `./notebooks`.
604    #[arg(long)]
605    notebooks_dir: Option<PathBuf>,
606
607    /// Python interpreter for the sidecar; skips auto-provisioning.
608    ///
609    /// Default: a pinned venv auto-created at `{data_dir}/notebooks-venv`
610    /// on first start from `waratah_notebook/python/requirements.lock`.
611    #[arg(long)]
612    notebooks_python: Option<PathBuf>,
613
614    /// Loopback bind for the notebook sidecar (default `127.0.0.1:0`,
615    /// engine-assigned). Also settable as `bind` in `{config-dir}/notebooks.toml`.
616    #[arg(long)]
617    notebooks_bind: Option<String>,
618
619    /// Jupyter auth token (default: minted at startup).
620    #[arg(long)]
621    notebooks_token: Option<String>,
622
623    /// Kernel idle culling timeout in seconds (default 3600). Also settable
624    /// as `cull_idle_secs` in `{config-dir}/notebooks.toml`.
625    #[arg(long)]
626    notebooks_cull_idle_secs: Option<u64>,
627
628    /// GeoSPARQL S2 covering params (process-local; see `waratah geo
629    /// rebuild-index` for the rebuild requirement after changing them).
630    #[command(flatten)]
631    geo: GeoCovererArgs,
632}
633
634/// `waratah start`: the spawned-process cluster (gRPC between compute and
635/// S/P/O + registry), daemonized by default.
636#[derive(Parser)]
637struct StartArgs {
638    /// Five-process address table (TOML) at an explicit path.
639    ///
640    /// Without it, `{config-dir}/cluster.toml` is used when present
641    /// (see `--config-dir`); otherwise the 127.0.0.1:7001-7005 defaults.
642    #[arg(long)]
643    config: Option<PathBuf>,
644
645    /// Directory holding `waratah-partition` / `waratah-registry`; defaults to this binary's.
646    #[arg(long)]
647    bin_dir: Option<PathBuf>,
648
649    /// Stay attached to this terminal (the historical behavior). Without
650    /// it the cluster daemonizes: the command returns once the server is
651    /// up, stdout/stderr go to `{data_dir}/logs/output.txt` and
652    /// `error.txt` (working directory for the memory backend), and
653    /// `--debug` traces go to `debug.txt`. `--query` and `--no-http`
654    /// imply `--foreground` (one-shot queries and the REPL need this
655    /// terminal).
656    #[arg(long)]
657    foreground: bool,
658
659    /// Daemon-child marker (hidden): present only on the re-executed
660    /// detached process, carrying the status file path the readiness
661    /// handshake is written to. Never pass it by hand.
662    #[arg(long, hide = true)]
663    daemon_ready: Option<PathBuf>,
664
665    #[command(flatten)]
666    serve: ServeArgs,
667}
668
669/// `waratah standalone`: the same engines opened in-process, always
670/// foreground.
671#[derive(Parser)]
672struct StandaloneArgs {
673    #[command(flatten)]
674    serve: ServeArgs,
675}
676
677// This is when waratah-bin is run as a standalone process.
678// It causes compiled-in libs to be use mimalloc too.
679#[global_allocator]
680static GLOBAL: MiMalloc = MiMalloc;
681
682fn main() -> ExitCode {
683    // `--build-info` must answer before ANY process setup: plugin
684    // registration below can panic on a conflicting plugin set, and a
685    // provenance query must not be able to fail because of it.
686    let cli = Cli::parse();
687    if cli.build_info {
688        println!("{}", waratah_buildinfo::build_info());
689        return ExitCode::SUCCESS;
690    }
691    // Serve-core placement resolves BEFORE the runtime exists so the
692    // builder sees it: WARATAH_SERVE_CORES defaults to off — unset means
693    // off for every subcommand (see crate::affinity for the measured
694    // disconfirmation) — so an unset env builds the stock runtime and an
695    // unpinned storage worker pool; a core-list spec pins serving threads.
696    let serving = matches!(
697        cli.command,
698        Some(Commands::Start(_)) | Some(Commands::Standalone(_))
699    );
700    crate::affinity::init_serve_cores(serving);
701    // Storage worker pool: fixed-resident threads created once with a stable
702    // core placement, so the storage parallel walks (registry resolve, domain
703    // scans) do not inherit the calling thread's mask — under serve-core
704    // affinity a tokio worker is pinned to one core, and scoped walker threads
705    // inherited that single core and time-sliced it instead of running in
706    // parallel. Sized to the resolved serve set, or to the process's available
707    // parallelism for an unpinned serving process. Batch tools skip this and
708    // keep the scoped-thread fallback: they are already free to use every
709    // core, and an unpinned bulk import has no serve set to derive from.
710    if serving {
711        let serve_cores = crate::affinity::serve_core_set();
712        let width = serve_cores.as_ref().map_or_else(
713            || std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get),
714            crate::affinity::CoreSet::len,
715        );
716        // The executor's parallel sizing (Grace join worker count) reads
717        // this published width — a call-site available_parallelism() on a
718        // serve-core-pinned serving thread reports the ONE core of the
719        // caller's mask and collapses every parallel decision to serial.
720        // Batch tools skip this: their threads are unpinned, and
721        // waratah_compute falls back to available_parallelism().
722        waratah_compute::core_width::set_process_core_width(width);
723        waratah_storage::init_worker_pool(
724            serve_cores.as_ref().map(crate::affinity::CoreSet::cores),
725            width,
726        );
727    }
728    // Explicit runtime instead of `#[tokio::main]`: with a resolved serve
729    // core set, worker threads are sized to and pinned 1:1 onto it; without
730    // one, this builds the identical stock runtime.
731    crate::affinity::build_serve_runtime().block_on(run(cli))
732}
733
734async fn run(cli: Cli) -> ExitCode {
735    let Some(command) = cli.command else {
736        // Unreachable through the parser: `arg_required_else_help` prints
737        // help and exits for a bare invocation, and `--build-info` already
738        // returned above. Kept total so the match below stays honest; 2 is
739        // the conventional usage-error exit code.
740        return ExitCode::from(2);
741    };
742    // GeoSPARQL: vendored PROJ data. Then compose the plugin set on ONE
743    // host and install it exactly once, BEFORE any query is lowered
744    // (unregistered `geof:*` / `tf:*` / `text:query` errors in
745    // split_filter; both process registries are first-install-wins, so two
746    // self-installs would silently drop the second plugin). A conflicting
747    // plugin set is a deployment error — fail fast at startup. The text
748    // config resolves from the command's `--config-dir` / `--with-text`
749    // (all serving + import commands carry them).
750    geo::configure_proj_env();
751    // A malformed text config is a usage error: report and exit before any
752    // engine exists (the same contract as a bad --http or --config).
753    let text_plugin_config = match &command {
754        Commands::Start(args) => {
755            text_options(args.serve.config_dir.as_deref(), args.serve.with_text)
756        }
757        Commands::Standalone(args) => {
758            text_options(args.serve.config_dir.as_deref(), args.serve.with_text)
759        }
760        Commands::Import(args) => text_options(args.config_dir.as_deref(), args.with_text),
761        _ => Ok(TextPluginConfig::default()),
762    }
763    .unwrap_or_else(|error| {
764        eprintln!("waratah: {error}");
765        std::process::exit(2);
766    });
767    // An existing text index this build/config cannot adopt fails here, before
768    // the cluster (or an import) opens the store. A schema/fingerprint
769    // mismatch is not a query-time nuisance: the text documents precede every
770    // axis write, so it fails every insert, and this build never rebuilds the
771    // index automatically (the operator runs `waratah text rebuild-index`).
772    let text_preflight = match &command {
773        Commands::Start(args) => args.serve.data_dir.as_deref(),
774        Commands::Standalone(args) => args.serve.data_dir.as_deref(),
775        Commands::Import(args) if !args.connect => args.data_dir.as_deref(),
776        _ => None,
777    };
778    if let Some(data_dir) = text_preflight
779        && let Err(error) = text::preflight_index(&text_plugin_config, data_dir)
780    {
781        eprintln!("waratah: {error}");
782        return ExitCode::from(2);
783    }
784    let mut host = waratah_compute::PluginHost::new();
785    waratah_geo::register(&mut host)
786        .expect("geo plugin registration conflicts with another plugin");
787    waratah_temporal::register(&mut host)
788        .expect("temporal plugin registration conflicts with another plugin");
789    waratah_text::register(&mut host, &text_plugin_config)
790        .expect("text plugin registration conflicts with another plugin");
791    host.install_process_wide();
792    let result = match command {
793        Commands::Start(args) => start_command(args).await,
794        Commands::Standalone(args) => standalone_command(args).await,
795        Commands::Stop(args) => dev::stop(args.data_dir).await,
796        Commands::Import(args) => match import_options(args) {
797            Ok(options) => import::run(options).await,
798            Err(error) => Err(error),
799        },
800        Commands::Explain(args) => explain_query(&args),
801        Commands::Catalog { command } => match command {
802            CatalogCommands::Rebuild(args) => catalog::rebuild(args.data_dir),
803        },
804        Commands::Geo { command } => match command {
805            GeoCommands::RebuildIndex(args) => geo::rebuild(&args.data_dir),
806            GeoCommands::Census(args) => {
807                // The window's query covering reads the process coverer
808                // config — apply the flags before any derivation.
809                args.coverer.apply();
810                geo::census(&args.data_dir, args.window.as_deref())
811            }
812        },
813        Commands::Text { command } => match command {
814            TextCommands::RebuildIndex(args) => {
815                text::rebuild_offline(&args.data_dir, args.config_dir.as_deref())
816            }
817            TextCommands::Status(args) => {
818                text::status_offline(&args.data_dir, args.config_dir.as_deref())
819            }
820        },
821        Commands::Temporal { command } => match command {
822            TemporalCommands::RebuildIndex(args) => {
823                waratah_temporal::set_coverer_config(waratah_storage::DyadicCovererConfig {
824                    min_level: args.temporal_min_level,
825                    max_level: args.temporal_max_level,
826                    max_nodes: args.temporal_max_nodes,
827                });
828                temporal::rebuild_offline(&args.data_dir)
829            }
830        },
831        Commands::Compact(args) => compact::run(args.data_dir, &args.targets),
832        Commands::Blob { command } => match command {
833            BlobCommands::Verify(args) => blob::verify(args.data_dir),
834        },
835    };
836
837    match result {
838        Ok(()) => ExitCode::SUCCESS,
839        Err(error) => {
840            eprintln!("waratah: {error}");
841            ExitCode::FAILURE
842        }
843    }
844}
845
846fn explain_query(args: &ExplainArgs) -> Result<(), DevError> {
847    let options = ExplainOptions {
848        default_union: args.default_union,
849        seat_by_total_cost: args.seat_by_total_cost,
850        ..ExplainOptions::default()
851    };
852    let text =
853        LogicalPlan::explain_with(&args.query, args.format.into(), args.pretty, None, &options)?;
854    print!("{text}");
855    if !text.ends_with('\n') {
856        println!();
857    }
858    Ok(())
859}
860
861fn import_options(args: ImportArgs) -> Result<ImportOptions, DevError> {
862    let config = match &args.config {
863        Some(path) => ClusterConfig::from_toml_str(&std::fs::read_to_string(path)?)?,
864        None => ClusterConfig::local_dev(),
865    };
866    Ok(ImportOptions {
867        config,
868        data_dir: args.data_dir,
869        bin_dir: match args.bin_dir {
870            Some(dir) => dir,
871            None => std::env::current_exe()?
872                .parent()
873                .map(PathBuf::from)
874                .unwrap_or_else(|| PathBuf::from(".")),
875        },
876        file: args.file,
877        commit_ts: match args.timestamp {
878            Some(ts) => CommitTs(ts),
879            None => import::now_commit_ts(),
880        },
881        compact: args.compact,
882        offline: args.offline,
883        connect: args.connect,
884        disable_wal: args.disable_wal,
885        direct_sst: args.direct_sst,
886        text_config: text_options(args.config_dir.as_deref(), args.with_text)?,
887    })
888}
889
890/// Build [`DevOptions`] from the shared serve flags.
891///
892/// `config` is `Some` only for `waratah start` (its explicit `--config`
893/// address table); standalone always derives the ring from
894/// `{config-dir}/cluster.toml` or the local defaults. `bin_dir` likewise
895/// only matters when storage children are spawned. `standalone` selects the
896/// in-process client wiring inside `dev::start`.
897fn serve_options(
898    serve: &ServeArgs,
899    config: Option<PathBuf>,
900    bin_dir: Option<PathBuf>,
901    standalone: bool,
902) -> Result<DevOptions, DevError> {
903    // Coverer params are per-process in v1; ingests and query coverings on
904    // THIS process both use them (cluster-uniform invariant documented).
905    serve.geo.apply();
906    // Cluster addresses: explicit `--config` wins, then
907    // `{config-dir}/cluster.toml`, then the local_dev defaults.
908    let config = match config {
909        Some(path) => ClusterConfig::from_toml_str(&std::fs::read_to_string(path)?)?,
910        None => match config_dir::find(serve.config_dir.as_deref(), config_dir::files::CLUSTER) {
911            Some(path) => ClusterConfig::from_toml_str(&std::fs::read_to_string(path)?)?,
912            None => ClusterConfig::local_dev(),
913        },
914    };
915
916    let http = if serve.no_http {
917        None
918    } else {
919        Some(
920            serve
921                .http
922                .parse::<SocketAddr>()
923                .map_err(|source| DevError::InvalidHttpAddr {
924                    addr: serve.http.clone(),
925                    source,
926                })?,
927        )
928    };
929
930    let ingest_dir = serve
931        .ingest_dir
932        .clone()
933        .unwrap_or_else(|| ingest_root_dir(serve.data_dir.as_deref()));
934
935    // No data-dir-derived default on purpose: an unset `--queries-dir` must
936    // keep the endpoint unconfigured (`501`) so the console can show
937    // "this compute does not offer queries".
938    let queries_dir = serve.queries_dir.clone();
939
940    let spill_dir = serve
941        .spill_dir
942        .clone()
943        .or_else(|| serve.data_dir.as_ref().map(|dir| dir.join("spill")));
944
945    let notebooks = notebooks_options(serve, http)?;
946
947    let ai = ai_options(serve, http)?;
948
949    // Text config: resolved once more here (the run() composition already
950    // read the same file; both reads see the same deployment).
951    let text_config = text_options(serve.config_dir.as_deref(), serve.with_text)?;
952
953    Ok(DevOptions {
954        config,
955        backend: match serve.data_dir {
956            Some(ref path) => Backend::RocksDb(path.clone()),
957            None => Backend::Memory,
958        },
959        bin_dir: match bin_dir {
960            Some(dir) => dir,
961            None => std::env::current_exe()?
962                .parent()
963                .map(PathBuf::from)
964                .unwrap_or_else(|| PathBuf::from(".")),
965        },
966        load_demo: serve.load_demo,
967        query: serve.query.clone(),
968        http,
969        debug: serve.debug,
970        standalone,
971        describe_mode: serve.describe_mode.clone().into(),
972        default_union: serve.default_union,
973        seat_by_total_cost: serve.seat_by_total_cost,
974        force_semi: serve.force_semi,
975        eager_scan_filter: !serve.no_eager_scan_filter,
976        strict_sparql: serve.strict_sparql,
977        ingest_dir,
978        queries_dir,
979        spill_dir,
980        notebooks,
981        ai,
982        // Pidfile policy: every data-dir start writes one (a RocksDB data
983        // dir cannot host two live clusters anyway), and the daemon path
984        // forces it on for the memory backend too (working directory).
985        // Memory-backend foreground runs skip it.
986        pidfile: serve.data_dir.is_some(),
987        ready_file: None,
988        debug_file: None,
989        text_config: text_config.enabled.then_some(text_config),
990    })
991}
992
993/// Resolve the AI services options: CLI flag over `{config-dir}/ai.toml`
994/// over the disabled default. Enabled via `--with-ai` OR `[ai] enabled =
995/// true` in `ai.toml`. When the document declares no upstreams, the `zen`
996/// upstream is preconfigured (grevillea dev works out of the box, BYOK).
997fn ai_options(
998    serve: &ServeArgs,
999    http: Option<SocketAddr>,
1000) -> Result<Option<waratah_api::AiConfig>, DevError> {
1001    let toml = match config_dir::find(serve.config_dir.as_deref(), config_dir::files::AI) {
1002        Some(path) => {
1003            println!("ai config: {}", path.display());
1004            Some(waratah_api::AiToml::from_toml_str(
1005                &std::fs::read_to_string(path)?,
1006            )?)
1007        }
1008        None => None,
1009    };
1010    let config = waratah_api::AiConfig::resolve(serve.with_ai, toml)?;
1011    if config.is_some() && http.is_none() {
1012        return Err(DevError::AiWithoutHttp);
1013    }
1014    Ok(config)
1015}
1016
1017/// Resolve the text plugin config: `--with-text` OR `enabled = true` in
1018/// `{config-dir}/text.toml`. The file also carries the analyzer and seed
1019/// length; the flag alone takes the defaults. A parse/validate failure is
1020/// a deployment error (fail fast, before any engine exists).
1021fn text_options(
1022    config_dir: Option<&std::path::Path>,
1023    with_text: bool,
1024) -> Result<TextPluginConfig, DevError> {
1025    let file = config_dir::find(config_dir, config_dir::files::TEXT);
1026    let config = match &file {
1027        Some(path) => {
1028            let text = std::fs::read_to_string(path)?;
1029            match TextPluginConfig::from_toml(&text) {
1030                Ok(config) => {
1031                    println!("text config: {}", path.display());
1032                    config
1033                }
1034                Err(error) => {
1035                    return Err(DevError::Backend(format!(
1036                        "invalid text config at {path:?}: {error}"
1037                    )));
1038                }
1039            }
1040        }
1041        None => TextPluginConfig {
1042            enabled: false,
1043            ..TextPluginConfig::default()
1044        },
1045    };
1046    if with_text && !config.enabled {
1047        return Ok(TextPluginConfig {
1048            enabled: true,
1049            ..config
1050        });
1051    }
1052    Ok(config)
1053}
1054
1055/// `waratah start`: validate the invocation synchronously (so usage errors
1056/// surface before anything is backgrounded), then either run in the
1057/// foreground or hand the cluster to the daemon machinery.
1058async fn start_command(args: StartArgs) -> Result<(), DevError> {
1059    // The one-shot query and the stdin REPL need the calling terminal, so
1060    // they imply --foreground regardless of the flag.
1061    let interactive = args.serve.query.is_some() || args.serve.no_http;
1062    match args.daemon_ready {
1063        Some(status_path) => {
1064            // We are the re-executed daemon child: same arguments plus the
1065            // hidden marker. Rebuild the options (the parent already
1066            // validated them) and report readiness through the status file.
1067            let options = serve_options(&args.serve, args.config, args.bin_dir, false)?;
1068            daemon::run_child(status_path, options).await
1069        }
1070        _ if args.foreground || interactive => {
1071            if interactive && !args.foreground {
1072                eprintln!(
1073                    "note: --query / --no-http imply --foreground (one-shot queries and the REPL need this terminal)"
1074                );
1075            }
1076            let options = serve_options(&args.serve, args.config, args.bin_dir, false)?;
1077            dev::start(options).await
1078        }
1079        None => {
1080            // Build (and drop) the options here first: a bad --config, an
1081            // unparseable --http, or a notebook misconfiguration must fail
1082            // in the caller's terminal, not inside a detached child.
1083            let options = serve_options(&args.serve, args.config.clone(), args.bin_dir, false)?;
1084            let http = options.http.ok_or_else(|| {
1085                DevError::Daemon("daemonized start requires the HTTP server".to_owned())
1086            })?;
1087            let plan = daemon::DetachPlan {
1088                data_dir: args.serve.data_dir.clone(),
1089                http,
1090                debug: options.debug,
1091            };
1092            daemon::run_detached(plan).await
1093        }
1094    }
1095}
1096
1097/// `waratah standalone`: the in-process engines, always foreground.
1098async fn standalone_command(args: StandaloneArgs) -> Result<(), DevError> {
1099    let mut options = serve_options(&args.serve, None, None, true)?;
1100    options.pidfile = args.serve.data_dir.is_some();
1101    dev::start(options).await
1102}
1103
1104/// Resolve the notebook-service options: CLI flags over
1105/// `{config-dir}/notebooks.toml` over data-dir-derived defaults. Enabled via
1106/// `--with-notebooks` OR `enabled = true` in `notebooks.toml`.
1107fn notebooks_options(
1108    args: &ServeArgs,
1109    http: Option<SocketAddr>,
1110) -> Result<Option<waratah_notebook::NotebookOptions>, DevError> {
1111    let toml = match config_dir::find(args.config_dir.as_deref(), config_dir::files::NOTEBOOKS) {
1112        Some(path) => {
1113            println!("notebooks config: {}", path.display());
1114            Some(waratah_notebook::NotebooksToml::from_toml_str(
1115                &std::fs::read_to_string(path)?,
1116            )?)
1117        }
1118        None => None,
1119    };
1120    let enabled = args.with_notebooks
1121        || toml
1122            .as_ref()
1123            .and_then(|table| table.enabled)
1124            .unwrap_or(false);
1125    if !enabled {
1126        return Ok(None);
1127    }
1128    let http = http.ok_or(DevError::NotebooksWithoutHttp)?;
1129    let bind =
1130        match args.notebooks_bind.as_deref() {
1131            Some(text) => Some(text.parse::<SocketAddr>().map_err(|source| {
1132                DevError::InvalidNotebooksBind {
1133                    addr: text.to_owned(),
1134                    source,
1135                }
1136            })?),
1137            None => None,
1138        };
1139    let data_dir = args.data_dir.as_deref();
1140    let defaults = waratah_notebook::NotebookDefaults {
1141        dir: waratah_storage::notebooks_root_dir(data_dir),
1142        // The generated config carries the token; it must live beside the
1143        // cluster, never in a shared temp path other instances clobber.
1144        runtime_dir: waratah_storage::notebooks_runtime_dir(data_dir),
1145        venv_dir: waratah_storage::notebooks_venv_dir(data_dir),
1146        engine_http: http,
1147    };
1148    let cli = waratah_notebook::NotebookCli {
1149        dir: args.notebooks_dir.clone(),
1150        python: args.notebooks_python.clone(),
1151        bind,
1152        token: args.notebooks_token.clone(),
1153        cull_idle_secs: args.notebooks_cull_idle_secs,
1154    };
1155    Ok(Some(waratah_notebook::NotebookOptions::resolve(
1156        cli,
1157        toml,
1158        defaults,
1159        waratah_storage::MAIN_REPOSITORY_ID.to_owned(),
1160    )?))
1161}
1162
1163/// Test-only plugin composition for this binary's unit tests: the SAME
1164/// composed set production builds (geo + temporal + text, one host, one
1165/// process-wide install), so two test modules' self-installs cannot race
1166/// over the first-wins process registries. The text config is the default
1167/// analyzer/seed length ENABLED — `TextPluginConfig::default()` itself is
1168/// disabled, and `register` no-ops for a disabled config.
1169#[cfg(test)]
1170pub(crate) mod test_support {
1171    pub(crate) fn install_composed() {
1172        static INSTALLED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
1173        INSTALLED.get_or_init(|| {
1174            let mut host = waratah_compute::PluginHost::new();
1175            waratah_geo::register(&mut host)
1176                .expect("geo plugin registration conflicts with another plugin");
1177            waratah_temporal::register(&mut host)
1178                .expect("temporal plugin registration conflicts with another plugin");
1179            waratah_text::register(
1180                &mut host,
1181                &waratah_text::TextPluginConfig {
1182                    enabled: true,
1183                    // Test composition indexes arbitrary `http://ex/`
1184                    // predicates, so it opts out of the built-in allowlist.
1185                    predicates: Vec::new(),
1186                    ..waratah_text::TextPluginConfig::default()
1187                },
1188            )
1189            .expect("text plugin registration conflicts with another plugin");
1190            host.install_process_wide();
1191        });
1192    }
1193}
1194
1195#[cfg(test)]
1196mod densify_step_tests {
1197    use super::parse_densify_step;
1198
1199    #[test]
1200    fn the_clap_default_string_matches_the_library_default() {
1201        // `default_value = "0.1"` and the parser's `true` arm are two
1202        // spellings of one default — this test is what keeps them tied.
1203        assert_eq!(
1204            parse_densify_step("0.1").unwrap(),
1205            parse_densify_step("true").unwrap()
1206        );
1207        assert_eq!(
1208            parse_densify_step("true").unwrap(),
1209            waratah_geo::DEFAULT_DENSIFY_STEP_DEG
1210        );
1211    }
1212
1213    #[test]
1214    fn disable_words_and_zero_all_disable() {
1215        for spelling in ["0", "false", "FALSE", "False", "off", "NO", " 0 "] {
1216            assert_eq!(
1217                parse_densify_step(spelling).unwrap(),
1218                0.0,
1219                "disable spelling {spelling:?} must parse to 0.0"
1220            );
1221        }
1222    }
1223
1224    #[test]
1225    fn floor_is_inclusive_and_enforced() {
1226        assert_eq!(
1227            parse_densify_step("1e-4").unwrap(),
1228            waratah_geo::MIN_DENSIFY_STEP_DEG
1229        );
1230        for step in ["9.9e-5", "1e-5", "1e-300"] {
1231            let message = parse_densify_step(step).unwrap_err();
1232            assert!(
1233                message.contains("below the minimum"),
1234                "step {step:?} must be rejected as sub-floor, got: {message}"
1235            );
1236        }
1237    }
1238
1239    #[test]
1240    fn malformed_and_non_finite_values_error() {
1241        for spelling in ["-1", "-0.5", "nan", "NaN", "inf", "-inf", "abc", ""] {
1242            assert!(
1243                parse_densify_step(spelling).is_err(),
1244                "malformed or non-finite step {spelling:?} must be rejected"
1245            );
1246        }
1247    }
1248
1249    #[test]
1250    fn ordinary_values_pass_through_with_trim() {
1251        assert_eq!(parse_densify_step(" 0.2 ").unwrap(), 0.2);
1252        assert_eq!(parse_densify_step("+0.5").unwrap(), 0.5);
1253        assert_eq!(parse_densify_step("1").unwrap(), 1.0);
1254    }
1255}