solo-storage 0.5.1

Solo: SQLite + SQLCipher persistence layer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
// SPDX-License-Identifier: Apache-2.0

//! Embedder implementations behind the `solo_core::Embedder` trait.
//!
//! Two impls live here:
//!
//!   - [`StubEmbedder`] — deterministic hash-based F32 embedder. Used in
//!     unit tests, integration tests, and as a placeholder until BGE-M3
//!     loading lands. Same input always produces the same vector; vectors
//!     are normalised to unit length so cosine similarity is well-defined.
//!
//!   - [`BgeM3Loader`] — file-discovery + config parsing for HuggingFace
//!     BGE-M3 model directories (`config.json`, `tokenizer.json`,
//!     `model.safetensors`). The actual forward pass via candle-core +
//!     candle-transformers + tokenizers lands in commit 1.4.b — until then,
//!     `BgeM3Loader::open` validates the model directory but the
//!     `Embedder` impl is intentionally not provided. Daemon-main wiring
//!     uses `StubEmbedder` in the interim.
//!
//! ## Why split 1.4 in half
//!
//! Live BGE-M3 inference is a substantial integration: candle-transformers
//! `xlm_roberta` (BGE-M3's base architecture) + the `tokenizers` crate +
//! a model-fetching path + the 1.2 GB weights file. Splitting the
//! integration from the API surface lets commit 1.5 (daemon main) start
//! immediately on the stub embedder and switch to BGE-M3 when 1.4.b lands.
//! Everything downstream of the `Embedder` trait stays untouched.

pub mod bge_m3;
pub mod bge_m3_inference;
pub mod ollama;
pub mod stub;

pub use bge_m3::{BgeM3Config, BgeM3Loader, BgeM3Manifest};
pub use bge_m3_inference::BgeM3Inference;
pub use ollama::{DEFAULT_OLLAMA_DIM, DEFAULT_OLLAMA_MODEL, OllamaEmbedder};
pub use stub::StubEmbedder;

use crate::config::EmbedderConfig;
use solo_core::{Embedder, Error, Result};

const ENV_EMBEDDER_KIND: &str = "SOLO_EMBEDDER";
const ENV_OLLAMA_BASE_URL: &str = "SOLO_OLLAMA_BASE_URL";
const ENV_OLLAMA_EMBED_MODEL: &str = "SOLO_OLLAMA_EMBED_MODEL";
const ENV_BGE_M3_DIR: &str = "SOLO_BGE_M3_DIR";

const DEFAULT_OLLAMA_BASE_URL: &str = "http://localhost:11434";

/// Deprecation warning emitted whenever the BGE-M3 code path runs in
/// v0.5.x.
///
/// **Duplicate of** `solo_cli::commands::BGE_M3_DEPRECATION_WARNING`.
/// The CLI copy stays in place for 6B; 6C may consolidate. v0.6.0 removes
/// the BGE-M3 path outright, dropping both copies. Keep the two strings
/// in lockstep until then — `download_model` (CLI-only) still uses its
/// copy, and the new env-driven storage path needs its own message
/// without crossing crate boundaries unnecessarily (see GitHub issue #1).
pub const BGE_M3_DEPRECATION_WARNING: &str = "\
WARNING: the BGE-M3 embedder is deprecated and will be removed in v0.6.0.\n\
\n\
The recommended replacement is OllamaEmbedder, landing in v0.5.1.\n\
Once v0.5.1 ships you will be able to switch with:\n\
\n\
  ollama pull nomic-embed-text\n\
  export SOLO_EMBEDDER=ollama\n\
  export SOLO_OLLAMA_EMBED_MODEL=nomic-embed-text\n\
\n\
(SOLO_EMBEDDER and SOLO_OLLAMA_EMBED_MODEL do not exist yet in v0.5.0\n\
— they ship with the OllamaEmbedder backend in v0.5.1.)\n\
\n\
See: https://github.com/CallMeJones/solo/issues/1";

/// Central, env-driven [`Embedder`] constructor.
///
/// **Precedence (highest to lowest)**:
///
/// 1. `SOLO_EMBEDDER=ollama` → [`OllamaEmbedder`] using
///    `SOLO_OLLAMA_BASE_URL` (default `http://localhost:11434`) and
///    `SOLO_OLLAMA_EMBED_MODEL` (default
///    [`DEFAULT_OLLAMA_MODEL`] = `nomic-embed-text`). Dim is hardcoded
///    to [`DEFAULT_OLLAMA_DIM`] = 768 for 6B; sub-step 6D will swap
///    this to a `solo init`-time probe persisted in `solo.config.toml`.
/// 2. `SOLO_EMBEDDER=bge-m3` → BGE-M3 inference via
///    [`BgeM3Loader::open`]. Requires `SOLO_BGE_M3_DIR` pointing at a
///    HuggingFace BAAI/bge-m3 model directory. Emits the deprecation
///    warning to stderr.
/// 3. `SOLO_EMBEDDER` unset, `SOLO_BGE_M3_DIR` set → legacy
///    auto-detection: BGE-M3 with deprecation warning. Preserves the
///    v0.5.0 behaviour exercised by [`crate::embedder::BgeM3Loader`]
///    so users with an existing BGE-M3 install don't see a behaviour
///    change when 6B lands.
/// 4. Nothing set → [`StubEmbedder::default_stub`] (`stub` / `v1` / 32).
///
/// **`SOLO_EMBEDDER` with any other value** is an error
/// ([`Error::InvalidInput`]).
///
/// ## Why this lives in `solo-storage`
///
/// `solo-cli::commands::common::build_embedder` predates this entry
/// point and reads `&SoloConfig` to preserve the persisted Stub
/// identity (BGE-M3 name/version/dim from `solo.config.toml`). 6C
/// will rewrite that CLI builder as a thin wrapper over this
/// function — at which point the Stub branch here may grow an
/// `Option<&SoloConfig>` parameter, or 6C will rebuild the Stub
/// post-construction. For 6B, the storage builder is parameterless
/// and returns `default_stub()`; the divergence is documented and
/// not exercised by the CLI yet.
///
/// ## Errors
///
/// Returns `Err` if:
///   - `SOLO_EMBEDDER` is set to an unknown value,
///   - `SOLO_EMBEDDER=bge-m3` is set but `SOLO_BGE_M3_DIR` is not,
///   - the BGE-M3 model directory is missing or malformed (see
///     [`BgeM3Loader::open`]),
///   - the HTTP client for Ollama cannot be built.
pub fn build_embedder_from_env() -> Result<Box<dyn Embedder>> {
    let kind = std::env::var(ENV_EMBEDDER_KIND).ok();

    match kind.as_deref() {
        Some("ollama") => build_ollama_from_env(),
        Some("bge-m3") => {
            emit_bge_m3_deprecation();
            build_bge_m3_from_env()
        }
        Some(other) if !other.is_empty() => Err(Error::invalid_input(format!(
            "Unknown {ENV_EMBEDDER_KIND} value: {other:?}. \
             Expected one of: ollama, bge-m3."
        ))),
        // Empty string or unset → fall through to legacy auto-detection.
        _ => {
            if std::env::var_os(ENV_BGE_M3_DIR).is_some() {
                emit_bge_m3_deprecation();
                build_bge_m3_from_env()
            } else {
                Ok(Box::new(StubEmbedder::default_stub()))
            }
        }
    }
}

fn build_ollama_from_env() -> Result<Box<dyn Embedder>> {
    let base_url = std::env::var(ENV_OLLAMA_BASE_URL)
        .ok()
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| DEFAULT_OLLAMA_BASE_URL.to_string());
    let model = std::env::var(ENV_OLLAMA_EMBED_MODEL)
        .ok()
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| DEFAULT_OLLAMA_MODEL.to_string());
    // 6B: hardcode dim. 6D probes at `solo init` and persists.
    let embedder = OllamaEmbedder::new(base_url, model, DEFAULT_OLLAMA_DIM)?;
    Ok(Box::new(embedder))
}

fn build_bge_m3_from_env() -> Result<Box<dyn Embedder>> {
    let dir = std::env::var(ENV_BGE_M3_DIR).map_err(|_| {
        Error::invalid_input(format!(
            "{ENV_BGE_M3_DIR} not set — required for SOLO_EMBEDDER=bge-m3. \
             Point it at a HuggingFace BAAI/bge-m3 model directory \
             (config.json + tokenizer.json + model.safetensors)."
        ))
    })?;
    let loader = BgeM3Loader::open(&dir)?;
    loader.into_embedder()
}

/// Emit the deprecation warning to stderr at most once per process.
/// `Once::call_once` matches the CLI-side guard so the message doesn't
/// spam logs across repeated calls (a future caller — `solo doctor`,
/// for instance — could invoke this multiple times).
fn emit_bge_m3_deprecation() {
    static WARNED: std::sync::Once = std::sync::Once::new();
    WARNED.call_once(|| {
        eprintln!("{BGE_M3_DEPRECATION_WARNING}");
    });
}

/// Resolve the [`EmbedderConfig`] that `solo init` should persist to
/// `solo.config.toml`, based on the same env-var precedence as
/// [`build_embedder_from_env`].
///
/// Precedence (matches `build_embedder_from_env` exactly):
///
/// 1. `SOLO_EMBEDDER=ollama` → probe Ollama for the real dim via
///    [`OllamaEmbedder::probe_dim`] and return
///    `{ name: "ollama:<model>", version: "v1", dim: <probed>, dtype: "f32" }`.
///    **Fails fast** with a clear, operator-actionable error if the probe
///    fails (Ollama not running, model not pulled, wrong base URL).
///    Persisting a guess would only push the failure to `solo daemon` /
///    first write, where the dim check in `build_embedder` (6C) would
///    surface a less helpful error.
/// 2. `SOLO_EMBEDDER=bge-m3`, or `SOLO_EMBEDDER` unset + `SOLO_BGE_M3_DIR`
///    set → BGE-M3 identity (`BAAI/bge-m3`, `v1`, 1024, `f32`). No I/O —
///    the constants here must match
///    [`crate::embedder::bge_m3::BGE_M3_DIM`] and friends; the daemon-
///    side `build_embedder` (6C) revalidates dim against the real
///    loader.
/// 3. Nothing set → stub identity (`stub`, `v1`, 32, `f32`). Matches
///    [`StubEmbedder::default_stub`].
///
/// `SOLO_EMBEDDER` with an unknown value is an error
/// ([`Error::InvalidInput`]) — same shape as `build_embedder_from_env`.
///
/// Why this lives in `solo-storage` next to `build_embedder_from_env`:
/// the two functions encode the **same precedence rules**. Keeping them
/// adjacent makes it harder for a future change to drift only one of
/// them. The CLI (`solo init`) calls this before invoking
/// `solo_storage::init(params)` so the persisted identity matches the
/// runtime embedder the daemon will later construct.
pub async fn probe_embedder_config_from_env() -> Result<EmbedderConfig> {
    let kind = std::env::var(ENV_EMBEDDER_KIND).ok();

    match kind.as_deref() {
        Some("ollama") => probe_ollama_config_from_env().await,
        Some("bge-m3") => {
            emit_bge_m3_deprecation();
            Ok(bge_m3_identity())
        }
        Some(other) if !other.is_empty() => Err(Error::invalid_input(format!(
            "Unknown {ENV_EMBEDDER_KIND} value: {other:?}. \
             Expected one of: ollama, bge-m3."
        ))),
        // Empty string or unset → fall through to legacy auto-detection.
        _ => {
            if std::env::var_os(ENV_BGE_M3_DIR).is_some() {
                emit_bge_m3_deprecation();
                Ok(bge_m3_identity())
            } else {
                Ok(stub_identity())
            }
        }
    }
}

/// Probe Ollama for the embedding dim of `(base_url, model)` and build
/// the [`EmbedderConfig`] to persist. Reads `SOLO_OLLAMA_BASE_URL` +
/// `SOLO_OLLAMA_EMBED_MODEL` with the same defaults as
/// `build_ollama_from_env`.
///
/// Fail-fast error message includes the upstream `reqwest` error plus
/// three operator-facing options (start Ollama, point at a different
/// base URL, switch embedder backend).
async fn probe_ollama_config_from_env() -> Result<EmbedderConfig> {
    let base_url = std::env::var(ENV_OLLAMA_BASE_URL)
        .ok()
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| DEFAULT_OLLAMA_BASE_URL.to_string());
    let model = std::env::var(ENV_OLLAMA_EMBED_MODEL)
        .ok()
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| DEFAULT_OLLAMA_MODEL.to_string());

    // Construct with the documented placeholder dim. `probe_dim`
    // bypasses the embedder's strict dim check, so the placeholder
    // doesn't affect correctness — the real dim comes from the server.
    let probe = OllamaEmbedder::new(base_url.clone(), model.clone(), DEFAULT_OLLAMA_DIM)?;
    let dim = probe.probe_dim().await.map_err(|e| {
        Error::embedder(format!(
            "Failed to probe the Ollama embedder's dimension at `solo init`.\n\
             Tried to embed a sentinel via {base_url}/api/embeddings using model `{model}`.\n\
             Upstream error: {e}\n\
             \n\
             Options:\n  \
             - Start Ollama: `ollama serve` (or check that the daemon is running)\n  \
             - Pull the model: `ollama pull {model}`\n  \
             - Point at a different base URL: SOLO_OLLAMA_BASE_URL=<url>\n  \
             - Use a different embedder: unset SOLO_EMBEDDER (falls back to stub) \
             or point SOLO_BGE_M3_DIR at a local model directory.\n  \
             \n\
             Then re-run `solo init`."
        ))
    })?;

    Ok(EmbedderConfig {
        name: format!("ollama:{model}"),
        version: "v1".into(),
        dim: dim as u32,
        dtype: "f32".into(),
    })
}

/// Static BGE-M3 identity. Same shape as
/// [`crate::init::default_embedder`] today; centralised here so the
/// probe path and the legacy default stay in lockstep.
fn bge_m3_identity() -> EmbedderConfig {
    EmbedderConfig {
        name: crate::embedder::bge_m3::BGE_M3_NAME.into(),
        version: crate::embedder::bge_m3::BGE_M3_VERSION.into(),
        dim: crate::embedder::bge_m3::BGE_M3_DIM as u32,
        dtype: "f32".into(),
    }
}

/// Static stub identity. Matches [`StubEmbedder::default_stub`]'s
/// (name, version, dim) so the persisted config + the runtime stub
/// agree.
fn stub_identity() -> EmbedderConfig {
    let stub = StubEmbedder::default_stub();
    EmbedderConfig {
        name: stub.name().to_string(),
        version: stub.version().to_string(),
        dim: stub.dim() as u32,
        dtype: "f32".into(),
    }
}

#[cfg(test)]
mod build_from_env_tests {
    //! Tests for [`build_embedder_from_env`].
    //!
    //! Env vars are process-global mutable state. The cargo test runner
    //! parallelises tests within a binary, so we serialise these cases
    //! through a module-level `Mutex`. Mirrors the pattern in
    //! `solo-cli::commands::common::ollama_overrides_tests`.
    //!
    //! NOTE: the BGE-M3 branches are tested via `Err` paths only —
    //! constructing a real `BgeM3Loader` would require a fake model
    //! directory with the right files, which `bge_m3::tests` already
    //! covers. Here we want to verify *that the BGE-M3 branch is
    //! selected*, which we can prove by setting `SOLO_BGE_M3_DIR` to a
    //! non-existent path and checking the error surfaces from
    //! `BgeM3Loader::open` rather than from a Stub or Ollama
    //! construction.
    use super::*;
    use std::sync::Mutex;

    static ENV_LOCK: Mutex<()> = Mutex::new(());

    const ALL_VARS: &[&str] = &[
        ENV_EMBEDDER_KIND,
        ENV_OLLAMA_BASE_URL,
        ENV_OLLAMA_EMBED_MODEL,
        ENV_BGE_M3_DIR,
    ];

    /// Drops the env vars on Drop so a panicking test doesn't leak
    /// state into subsequent cases. Caller must hold `ENV_LOCK`.
    struct EnvGuard;
    impl Drop for EnvGuard {
        fn drop(&mut self) {
            // SAFETY: caller holds ENV_LOCK, so no other thread is
            // concurrently reading or writing these vars.
            for k in ALL_VARS {
                unsafe { std::env::remove_var(k) };
            }
        }
    }

    fn fresh_env() -> EnvGuard {
        // Pre-clean in case a previous test panicked before its
        // EnvGuard's Drop fired. SAFETY: ENV_LOCK held by caller.
        for k in ALL_VARS {
            unsafe { std::env::remove_var(k) };
        }
        EnvGuard
    }

    /// `Result::expect_err` requires `Debug` on the Ok side; `dyn
    /// Embedder` doesn't implement Debug (and we don't want to add it
    /// to the trait just for tests). This helper unwraps to the Err
    /// or panics with a clear message.
    fn expect_err(result: Result<Box<dyn Embedder>>, msg: &str) -> Error {
        match result {
            Ok(_) => panic!("expected Err: {msg}"),
            Err(e) => e,
        }
    }

    #[test]
    fn env_falls_back_to_stub_when_nothing_set() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        let e = build_embedder_from_env().expect("nothing set → stub");
        assert_eq!(e.name(), "stub");
        assert_eq!(e.version(), "v1");
        // `default_stub()` is 32-dim; if that constant changes,
        // update here. Keeps a regression-guard on the default.
        assert_eq!(e.dim(), 32);
    }

    #[test]
    fn env_picks_ollama_when_kind_is_ollama() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        // SAFETY: lock held; no concurrent reader/writer.
        unsafe { std::env::set_var(ENV_EMBEDDER_KIND, "ollama") };
        let e = build_embedder_from_env().expect("ollama branch");
        // Default model is nomic-embed-text → name is
        // "ollama:nomic-embed-text".
        assert_eq!(e.name(), "ollama:nomic-embed-text");
        assert_eq!(e.dim(), DEFAULT_OLLAMA_DIM);
    }

    #[test]
    fn env_ollama_uses_custom_base_url_and_model() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        unsafe {
            std::env::set_var(ENV_EMBEDDER_KIND, "ollama");
            std::env::set_var(ENV_OLLAMA_BASE_URL, "http://my-host:31000");
            std::env::set_var(ENV_OLLAMA_EMBED_MODEL, "mxbai-embed-large");
        };
        let e = build_embedder_from_env().expect("custom ollama");
        // Identity reflects the override.
        assert_eq!(e.name(), "ollama:mxbai-embed-large");
        // We can't inspect base_url through the trait, but we
        // verified the impl propagates it in
        // `ollama::tests::base_url_trailing_slashes_are_trimmed`
        // and friends. Here we trust the OllamaEmbedder constructor.
    }

    #[test]
    fn env_ollama_empty_base_url_falls_back_to_default() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        unsafe {
            std::env::set_var(ENV_EMBEDDER_KIND, "ollama");
            std::env::set_var(ENV_OLLAMA_BASE_URL, "");
        };
        let e = build_embedder_from_env().expect("empty base url ok");
        assert_eq!(e.name(), "ollama:nomic-embed-text");
    }

    #[test]
    fn env_unknown_kind_errors_cleanly() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        unsafe { std::env::set_var(ENV_EMBEDDER_KIND, "bogus") };
        let err = expect_err(
            build_embedder_from_env(),
            "unknown kind must error, not panic",
        );
        let msg = format!("{err}");
        assert!(
            msg.contains("bogus"),
            "error should name the offending value: {msg}"
        );
        assert!(
            msg.contains("ollama") && msg.contains("bge-m3"),
            "error should list valid options: {msg}"
        );
    }

    #[test]
    fn env_bge_m3_explicit_requires_dir() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        // Explicit bge-m3 kind but no SOLO_BGE_M3_DIR.
        unsafe { std::env::set_var(ENV_EMBEDDER_KIND, "bge-m3") };
        let err = expect_err(
            build_embedder_from_env(),
            "bge-m3 without SOLO_BGE_M3_DIR must error",
        );
        let msg = format!("{err}");
        assert!(
            msg.contains(ENV_BGE_M3_DIR),
            "error should mention SOLO_BGE_M3_DIR: {msg}"
        );
    }

    #[test]
    fn env_bge_m3_branch_selected_when_dir_set_and_no_kind() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        // No SOLO_EMBEDDER, but SOLO_BGE_M3_DIR points at a bad path
        // → legacy auto-detection chooses BGE-M3, then BgeM3Loader::open
        // errors. The fact that we see a BGE-M3-flavoured error
        // (rather than a Stub success) proves the branch was taken.
        unsafe { std::env::set_var(ENV_BGE_M3_DIR, "C:/definitely/not/a/real/path/xyz123") };
        let err = expect_err(
            build_embedder_from_env(),
            "bad BGE-M3 dir must error",
        );
        let msg = format!("{err}");
        assert!(
            msg.to_ascii_lowercase().contains("bge-m3"),
            "error should be BGE-M3-flavoured (branch selected): {msg}"
        );
    }

    #[test]
    fn env_bge_m3_explicit_branch_selected_when_dir_set_to_bad_path() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        unsafe {
            std::env::set_var(ENV_EMBEDDER_KIND, "bge-m3");
            std::env::set_var(ENV_BGE_M3_DIR, "C:/definitely/not/a/real/path/xyz123");
        };
        let err = expect_err(
            build_embedder_from_env(),
            "bad BGE-M3 dir under explicit kind must error",
        );
        let msg = format!("{err}");
        assert!(
            msg.to_ascii_lowercase().contains("bge-m3"),
            "error should be BGE-M3-flavoured: {msg}"
        );
    }

    #[test]
    fn env_empty_kind_string_falls_through_to_legacy() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        // Empty SOLO_EMBEDDER + nothing else → stub (legacy with
        // nothing set). Guards against an operator who did
        // `export SOLO_EMBEDDER=` (clearing the value but not the
        // var) accidentally tripping the unknown-kind error.
        unsafe { std::env::set_var(ENV_EMBEDDER_KIND, "") };
        let e = build_embedder_from_env().expect("empty kind = unset");
        assert_eq!(e.name(), "stub");
    }
}

#[cfg(test)]
mod probe_config_from_env_tests {
    //! Tests for [`probe_embedder_config_from_env`] — the sub-step 6D
    //! init-time identity resolver. Shares the same process-global env
    //! var concern as `build_from_env_tests`, with its own lock so the
    //! two suites don't deadlock when both run in parallel.
    use super::*;
    use std::sync::Mutex;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    static ENV_LOCK: Mutex<()> = Mutex::new(());

    const ALL_VARS: &[&str] = &[
        ENV_EMBEDDER_KIND,
        ENV_OLLAMA_BASE_URL,
        ENV_OLLAMA_EMBED_MODEL,
        ENV_BGE_M3_DIR,
    ];

    struct EnvGuard;
    impl Drop for EnvGuard {
        fn drop(&mut self) {
            for k in ALL_VARS {
                // SAFETY: caller holds ENV_LOCK.
                unsafe { std::env::remove_var(k) };
            }
        }
    }

    fn fresh_env() -> EnvGuard {
        for k in ALL_VARS {
            // SAFETY: caller holds ENV_LOCK.
            unsafe { std::env::remove_var(k) };
        }
        EnvGuard
    }

    /// Build a `dim`-element f32 fixture for the mock-Ollama response.
    fn fixture(dim: usize, seed: u32) -> Vec<f32> {
        (0..dim)
            .map(|i| ((seed.wrapping_add(i as u32)) as f32) * 1e-3)
            .collect()
    }

    #[tokio::test]
    async fn probes_ollama_dim_when_kind_is_ollama() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();

        // Mock Ollama returning a 768-dim vector (matches
        // nomic-embed-text). Probe should pick this up regardless of
        // the OllamaEmbedder's placeholder dim.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/embeddings"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "embedding": fixture(768, 1)
            })))
            .expect(1)
            .mount(&server)
            .await;

        unsafe {
            std::env::set_var(ENV_EMBEDDER_KIND, "ollama");
            std::env::set_var(ENV_OLLAMA_BASE_URL, server.uri());
            // Leave SOLO_OLLAMA_EMBED_MODEL unset → default model.
        };

        let cfg = probe_embedder_config_from_env()
            .await
            .expect("probe should succeed against mock");
        assert_eq!(cfg.name, format!("ollama:{}", DEFAULT_OLLAMA_MODEL));
        assert_eq!(cfg.version, "v1");
        assert_eq!(cfg.dim, 768);
        assert_eq!(cfg.dtype, "f32");
    }

    #[tokio::test]
    async fn probe_picks_up_non_default_dim_from_mock_response() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();

        // Mock returns a 1024-dim vector (matches mxbai-embed-large).
        // The persisted dim must reflect the actual response, not the
        // 768 placeholder the OllamaEmbedder was constructed with.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/embeddings"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "embedding": fixture(1024, 99)
            })))
            .expect(1)
            .mount(&server)
            .await;

        unsafe {
            std::env::set_var(ENV_EMBEDDER_KIND, "ollama");
            std::env::set_var(ENV_OLLAMA_BASE_URL, server.uri());
            std::env::set_var(ENV_OLLAMA_EMBED_MODEL, "mxbai-embed-large");
        };

        let cfg = probe_embedder_config_from_env().await.expect("probe ok");
        assert_eq!(cfg.name, "ollama:mxbai-embed-large");
        assert_eq!(cfg.dim, 1024, "probed dim must override the 768 placeholder");
    }

    #[tokio::test]
    async fn probe_fails_clearly_when_ollama_unreachable() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();

        unsafe {
            std::env::set_var(ENV_EMBEDDER_KIND, "ollama");
            // Point at a port that nothing is listening on. Loopback
            // refusal is fast on every supported platform.
            std::env::set_var(ENV_OLLAMA_BASE_URL, "http://127.0.0.1:1");
        };

        let err = probe_embedder_config_from_env()
            .await
            .expect_err("unreachable Ollama must error");
        let msg = format!("{err}");
        // Operator-actionable fragments — the error is meant to read
        // like a runbook entry.
        assert!(
            msg.contains("Failed to probe the Ollama embedder"),
            "missing top-line context: {msg}"
        );
        assert!(
            msg.contains("ollama serve") && msg.contains("ollama pull"),
            "missing remediation hints: {msg}"
        );
        assert!(
            msg.contains("SOLO_OLLAMA_BASE_URL"),
            "missing alt-URL hint: {msg}"
        );
        assert!(
            msg.contains("SOLO_BGE_M3_DIR") || msg.contains("SOLO_EMBEDDER"),
            "missing backend-switch hint: {msg}"
        );
    }

    #[tokio::test]
    async fn returns_stub_identity_when_no_env_set() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        let cfg = probe_embedder_config_from_env().await.expect("ok");
        assert_eq!(cfg.name, "stub");
        assert_eq!(cfg.version, "v1");
        assert_eq!(cfg.dim, 32);
        assert_eq!(cfg.dtype, "f32");
    }

    #[tokio::test]
    async fn returns_bge_m3_identity_when_bge_m3_dir_set() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        // We only care that the BGE-M3 *identity* is selected — we
        // don't construct a loader (that would require a real model
        // directory). Set SOLO_BGE_M3_DIR to any path; this code path
        // doesn't open it.
        unsafe { std::env::set_var(ENV_BGE_M3_DIR, "C:/not/a/real/model/dir") };
        let cfg = probe_embedder_config_from_env().await.expect("ok");
        assert_eq!(cfg.name, "BAAI/bge-m3");
        assert_eq!(cfg.version, "v1");
        assert_eq!(cfg.dim, 1024);
        assert_eq!(cfg.dtype, "f32");
    }

    #[tokio::test]
    async fn returns_bge_m3_identity_when_kind_is_explicit_bge_m3() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        // Unlike `build_embedder_from_env`, the probe path does NOT
        // need SOLO_BGE_M3_DIR for the identity branch — it returns
        // constants without touching the filesystem. The daemon-side
        // build_embedder is where the directory-required check fires.
        unsafe { std::env::set_var(ENV_EMBEDDER_KIND, "bge-m3") };
        let cfg = probe_embedder_config_from_env().await.expect("ok");
        assert_eq!(cfg.name, "BAAI/bge-m3");
        assert_eq!(cfg.dim, 1024);
    }

    #[tokio::test]
    async fn unknown_kind_errors_with_options_listed() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let _g = fresh_env();
        unsafe { std::env::set_var(ENV_EMBEDDER_KIND, "bogus") };
        let err = probe_embedder_config_from_env()
            .await
            .expect_err("unknown kind must error");
        let msg = format!("{err}");
        assert!(msg.contains("bogus"));
        assert!(msg.contains("ollama") && msg.contains("bge-m3"));
    }
}