matra 0.3.0

NLP library: UDPipe structured parse, base text metrics, summarization, keyphrase extraction. Rust core with Python bindings.
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
//! `matra config show` and `matra config init`.
//!
//! Neither action touches the model or any input document, which is why
//! both are dispatched before the engine is built.

use std::io::Write;
use std::path::Path;

use serde_json::{Value, json};

use crate::config::{Config, ValueSource};

use super::{Cli, ConfigAction, Failure, Fallible, Outcome, write_envelope};

/// The defaults, embedded a second time so `config init` can write the
/// exact bytes the crate falls back to. It is the same file
/// `config::DEFAULT_TOML` reads, so the two cannot disagree.
const DEFAULT_TOML: &str = include_str!("../../config/default.toml");

pub(super) fn run(cli: &Cli, action: &ConfigAction, out: &mut dyn Write) -> Fallible<Outcome> {
    match action {
        ConfigAction::Show => show(cli, out),
        ConfigAction::Init { force } => init(cli, *force, out),
    }
}

// ---------------------------------------------------------------------------
// show
// ---------------------------------------------------------------------------

fn show(cli: &Cli, out: &mut dyn Write) -> Fallible<Outcome> {
    let cfg = super::resolve_config(cli)?;
    // `input` names what the command read, and is null when it read
    // nothing, as it is for `--skill`. A config file that is not there
    // was not read, and naming it anyway asserts a file this run never
    // saw: `config show --json` reported `/root/.config/matra/config.toml`
    // in a container where nothing had ever created it. The per-key
    // origins already say which values came from a file, so a null here
    // loses nothing and claims nothing.
    let read_from = config_file_read(&cfg);

    if cli.json {
        let mut object = serde_json::Map::new();
        for (key, source) in cfg.sources() {
            object.insert(
                key.to_string(),
                json!({
                    "value": value_of(&cfg, key)?,
                    "source": kind_of(&source),
                    "origin": origin_of(&source),
                }),
            );
        }
        write_envelope(out, "config", read_from.as_deref(), Value::Object(object))?;
        return Ok(Outcome::Found);
    }

    if cli.quiet {
        return Ok(Outcome::Found);
    }

    // One key per line, the value, then the origin as a comment, which is
    // the shape `cargo config get --show-origin` prints.
    for (key, source) in cfg.sources() {
        writeln!(
            out,
            "{key} = {} # {}",
            value_of(&cfg, key)?,
            describe(&source)
        )?;
    }
    Ok(Outcome::Found)
}

/// The config file this run actually read, if it read one.
///
/// A path that resolves is where a file would go, not evidence that one
/// is there. The question `config show` answers is what happened, so the
/// file has to exist to be named. A value sourced from the file is
/// stronger evidence still, and is checked first: the file was read if
/// something in the resolved configuration came out of it.
///
/// The fallback path comes off the configuration rather than off
/// `Config::config_file_path`, which reads the process environment. The
/// static answered about the machine the process is on rather than about
/// the configuration in hand, so this reported whatever
/// `~/.config/matra/config.toml` happened to exist even for a `Config`
/// built from an injected environment.
fn config_file_read(cfg: &Config) -> Option<String> {
    if let Some(path) = cfg.sources().find_map(|(_, source)| match source {
        ValueSource::File(path) => Some(path),
        _ => None,
    }) {
        return Some(path.display().to_string());
    }
    cfg.config_file()
        .filter(|path| path.exists())
        .map(|path| path.display().to_string())
}

/// The effective value behind one of [`Config::sources`]'s keys.
///
/// The unknown arm is loud rather than skipped: a key that `Config`
/// reports and this function does not know is a key `config show` would
/// silently omit, and a value nobody can see is a value nobody can
/// debug. The test below walks every key `Config` reports, so the gap
/// fails the suite rather than the user's terminal.
fn value_of(cfg: &Config, key: &str) -> Fallible<Value> {
    Ok(match key {
        "data_dir" => json!(cfg.data_dir().display().to_string()),
        "model_dir" => json!(cfg.model_dir().display().to_string()),
        "models.embedding" => json!(cfg.embedding_model()),
        "summary.n" => json!(cfg.summary_n()),
        "summary.method" => json!(cfg.summary_method()),
        "keyphrases.n" => json!(cfg.keyphrases_n()),
        "keyphrases.method" => json!(cfg.keyphrases_method()),
        "clusters.threshold" => json!(cfg.clusters_threshold()),
        other => {
            return Err(Failure::refused(
                "config_key_unrendered",
                format!(
                    "config show cannot render `{other}`: the key is resolved but has no reader here"
                ),
            ));
        }
    })
}

/// The origin, spelled for a person.
fn describe(source: &ValueSource) -> String {
    match source {
        ValueSource::Argument => "command line".to_string(),
        ValueSource::Environment(name) => format!("environment variable `{name}`"),
        ValueSource::File(path) => path.display().to_string(),
        ValueSource::Default => "default".to_string(),
    }
}

/// The origin's rung, spelled for a program. `#[non_exhaustive]` binds
/// outside the crate, not in here, so a new rung fails to compile until
/// it is named.
fn kind_of(source: &ValueSource) -> &'static str {
    match source {
        ValueSource::Argument => "argument",
        ValueSource::Environment(_) => "environment",
        ValueSource::File(_) => "file",
        ValueSource::Default => "default",
    }
}

/// What the rung points at: the variable name, the file path, or nothing.
fn origin_of(source: &ValueSource) -> Value {
    match source {
        ValueSource::Environment(name) => json!(name),
        ValueSource::File(path) => json!(path.display().to_string()),
        ValueSource::Argument | ValueSource::Default => Value::Null,
    }
}

// ---------------------------------------------------------------------------
// init
// ---------------------------------------------------------------------------

fn init(cli: &Cli, force: bool, out: &mut dyn Write) -> Fallible<Outcome> {
    let path = Config::config_file_path().ok_or_else(|| {
        Failure::refused(
            "no_config_file_location",
            "cannot locate a config file: set MATRA_CONFIG_FILE, XDG_CONFIG_HOME, or HOME",
        )
    })?;
    write_defaults(&path, force)?;

    let shown = path.display().to_string();
    if cli.json {
        write_envelope(out, "config", Some(&shown), json!({ "path": shown }))?;
    } else if !cli.quiet {
        writeln!(out, "{shown}")?;
    }
    Ok(Outcome::Found)
}

/// Write the shipped defaults to `path`, atomically.
///
/// The bytes land in a temporary file in the same directory and arrive
/// at `path` under one rename, so a concurrent reader sees either the
/// old file or the whole new one and never a half-written config.
///
/// Without `force` the arrival is a hard link instead, because
/// `hard_link` fails when the destination exists and `rename` does not.
/// Checking `exists()` and then renaming would leave a window in which
/// another process creates the file and this one silently destroys it;
/// the link closes that window in the kernel rather than narrowing it.
fn write_defaults(path: &Path, force: bool) -> Fallible<()> {
    // The early check exists for the message, not for the guarantee. The
    // guarantee is the link below.
    if !force && path.exists() {
        return Err(Failure::refused(
            "config_file_exists",
            format!(
                "{} already exists; pass --force to overwrite it",
                path.display()
            ),
        ));
    }

    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    std::fs::create_dir_all(parent)
        .map_err(|e| io_at("create the config directory", parent, &e))?;

    let temp = parent.join(format!(
        ".{}.{}.tmp",
        path.file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("config.toml"),
        std::process::id()
    ));
    // `create_new` refuses a leftover temp from a crashed run rather than
    // overwriting whatever is there.
    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&temp)
        .map_err(|e| io_at("create the temporary file", &temp, &e))?;
    let written = file
        .write_all(DEFAULT_TOML.as_bytes())
        .and_then(|()| file.sync_all());
    drop(file);
    if let Err(e) = written {
        let _ = std::fs::remove_file(&temp);
        return Err(io_at("write the config to", &temp, &e).into());
    }

    let arrived = if force {
        std::fs::rename(&temp, path)
    } else {
        std::fs::hard_link(&temp, path)
    };
    if let Err(e) = arrived {
        let _ = std::fs::remove_file(&temp);
        if e.kind() == std::io::ErrorKind::AlreadyExists {
            return Err(Failure::refused(
                "config_file_exists",
                format!(
                    "{} already exists; pass --force to overwrite it",
                    path.display()
                ),
            ));
        }
        return Err(io_at("move the config into place at", path, &e).into());
    }

    // `rename` consumed the temp; `hard_link` left it behind as a second
    // name for the same inode. Removing it is tidying after the fact,
    // not part of the arrival: the config is already at `path` and
    // already correct. Reporting a failure here would tell the caller
    // the write failed when it succeeded, which is the one thing an exit
    // code must never do. The cost of ignoring it is a stray dotfile
    // beside a working config, and `--force` overwrites it.
    if !force {
        let _ = std::fs::remove_file(&temp);
    }
    Ok(())
}

/// A filesystem failure that names the operation and the path.
///
/// The counterpart of the functions of the same name in
/// `nlp/udpipe.rs` and `embed/model2vec.rs`, and it exists for the same
/// reason: `io error: Permission denied (os error 13)` was the whole
/// message a failed `config init` produced, with the directory sitting
/// in a variable one line away. The library writes this sentence once,
/// in the crate-private `IoContext::cannot`, which also makes the path a
/// detail; boundary rule 7 keeps `src/cli/` to the public surface, so
/// this copy writes the sentence again and its error carries no `path`
/// detail.
fn io_at(operation: &str, path: &Path, error: &std::io::Error) -> crate::domain::Error {
    crate::domain::Error::Io(std::io::Error::new(
        error.kind(),
        format!("cannot {operation} {}: {error}", path.display()),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Every key `Config` resolves must have a reader in `value_of`.
    /// Adding a key to the config without teaching `config show` how to
    /// print it fails here, not in a user's terminal.
    #[test]
    fn every_resolved_key_can_be_rendered() {
        let cfg = Config::from_sources(
            |key| match key {
                "HOME" => Some("/tmp/matra-test-home".to_string()),
                _ => None,
            },
            None,
        )
        .expect("defaults resolve");
        for (key, _) in cfg.sources() {
            value_of(&cfg, key).unwrap_or_else(|e| panic!("{key}: {e}"));
        }
    }

    #[test]
    fn an_unknown_key_is_loud() {
        let cfg = Config::from_sources(
            |key| match key {
                "HOME" => Some("/tmp/matra-test-home".to_string()),
                _ => None,
            },
            None,
        )
        .expect("defaults resolve");
        assert!(value_of(&cfg, "not.a.key").is_err());
    }

    /// Regression (review of #77): the fallback path comes off the
    /// configuration, not off `Config::config_file_path`, which reads
    /// the process environment. A file at the injected environment's
    /// path is named even when it supplied no value; before this, the
    /// answer was about whatever file the machine running the test
    /// happened to have, so this test passed on a clean machine and
    /// failed for anyone who had run `matra config init`.
    #[test]
    fn the_named_file_is_the_one_this_configuration_would_read() {
        let dir = tempfile::tempdir().expect("temp dir");
        let expected = dir.path().join(".config").join("matra").join("config.toml");
        std::fs::create_dir_all(expected.parent().expect("a parent")).expect("config dir");
        // Empty, so it exists and supplies nothing: the fallback is the
        // only branch that can name it.
        std::fs::write(&expected, b"").expect("config file");

        let cfg = Config::from_sources(
            |key| match key {
                "HOME" => Some(dir.path().display().to_string()),
                _ => None,
            },
            Some(""),
        )
        .expect("defaults resolve");

        assert!(
            cfg.sources()
                .all(|(_, source)| !matches!(source, ValueSource::File(_))),
            "an empty file supplies no value, so only the fallback can name it"
        );
        assert_eq!(config_file_read(&cfg), Some(expected.display().to_string()));
    }

    /// Regression: `config show --json` used to put the resolved config
    /// path in `input` whether or not a file was there, so a container
    /// that had never run `config init` was told it had a config file at
    /// a path nothing had created. `input` names what was read. The
    /// injected `HOME` is the whole environment this consults, so the
    /// answer does not depend on the machine running the test.
    #[test]
    fn no_config_file_means_no_config_file_in_the_envelope() {
        let dir = tempfile::tempdir().expect("temp dir");
        let home = dir.path().join("home");
        std::fs::create_dir_all(&home).expect("home");
        let cfg = Config::from_sources(
            |key| match key {
                "HOME" => Some(home.display().to_string()),
                _ => None,
            },
            None,
        )
        .expect("defaults resolve");

        assert_eq!(
            config_file_read(&cfg),
            None,
            "nothing was read, so nothing is named"
        );
    }

    /// The other half: a file that did supply a value is named, and it
    /// is named as the file that supplied it rather than as the path
    /// where one could live.
    #[test]
    fn a_config_file_that_supplied_a_value_is_named() {
        let dir = tempfile::tempdir().expect("temp dir");
        let expected = dir.path().join(".config").join("matra").join("config.toml");
        let cfg = Config::from_sources(
            |key| match key {
                "HOME" => Some(dir.path().display().to_string()),
                _ => None,
            },
            Some("[summary]\nn = 7\n"),
        )
        .expect("resolve with a file");

        assert_eq!(
            config_file_read(&cfg),
            Some(expected.display().to_string()),
            "the file that supplied a value is the file that was read"
        );
    }

    #[test]
    fn defaults_written_once_and_refused_twice() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("nested").join("config.toml");

        write_defaults(&path, false).expect("first write");
        assert_eq!(
            std::fs::read_to_string(&path).expect("read back"),
            DEFAULT_TOML
        );

        let refused = write_defaults(&path, false).expect_err("second write refused");
        assert!(refused.to_string().contains("--force"), "{refused}");

        write_defaults(&path, true).expect("forced write");
        assert_eq!(
            std::fs::read_to_string(&path).expect("read back"),
            DEFAULT_TOML
        );
    }

    /// The temp file is an implementation detail and must not survive the
    /// call, on either the taken or the refused path.
    #[test]
    fn no_temp_file_is_left_behind() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("config.toml");
        write_defaults(&path, false).expect("first write");
        let _ = write_defaults(&path, false);

        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
            .expect("list")
            .filter_map(|e| e.ok())
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|name| name.ends_with(".tmp"))
            .collect();
        assert!(leftovers.is_empty(), "left behind: {leftovers:?}");
    }

    /// Regression (0.2.1): a filesystem failure names the operation and
    /// the path. `create_dir_all` was called bare, so an unwritable
    /// config directory produced `matra: Permission denied (os error
    /// 13)` and nothing else, with the directory one line away in a
    /// variable.
    ///
    /// The fixture is a file where a directory has to be, which fails
    /// the same way on every platform and for every user, including
    /// root. A chmod fixture would need a unix gate and would still
    /// pass vacuously in a container that runs as root.
    #[test]
    fn a_filesystem_failure_names_the_operation_and_the_path() {
        let dir = tempfile::tempdir().expect("temp dir");
        let blocked = dir.path().join("not-a-directory");
        std::fs::write(&blocked, b"x").expect("write the blocker");
        let path = blocked.join("matra").join("config.toml");

        let err = write_defaults(&path, false).expect_err("the directory cannot be created");
        let message = err.to_string();

        assert!(
            message.contains("create the config directory"),
            "names the operation: {message}"
        );
        assert!(
            message.contains(&blocked.join("matra").display().to_string()),
            "names the path: {message}"
        );
    }
}