Coverage Report

Created: 2026-12-05 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
super-voice-daemon/src/stt_models/subprocess.rs
Line
Count
Source
1
// SPDX-License-Identifier: GPL-3.0-only
2
//! Host for STT backends shipped as sandboxed native subprocesses.
3
//!
4
//! [`SubprocessBackend`] provisions a backend's model files (downloading from
5
//! `HuggingFace` into the per-backend directory), has
6
//! [`super_engine_daemon::subprocess`] spawn the backend binary into a sandbox
7
//! and load the model, and presents the result through the daemon's
8
//! [`Transcribe`] trait. The sandbox, the socket and the `/v1` handshake are
9
//! the engine's; what is here is what a transcription backend is asked. The
10
//! backend itself is fully self-contained and shares no code with the daemon.
11
12
use std::path::Path;
13
use std::sync::Arc;
14
use std::time::Duration;
15
16
use anyhow::{Context, Result, anyhow};
17
use async_trait::async_trait;
18
use log::info;
19
use super_engine_daemon::subprocess::{self as engine, Start, json_headers};
20
use super_voice_shared::models::protocol::LoadProgress;
21
22
use super_voice_shared::utils::audio::{ResampleQuality, resample};
23
24
use crate::backend_headers::{self, Feature};
25
use crate::stt_models::backends::manifest::{FileSpec, Manifest};
26
use crate::stt_models::download::DownloadItem;
27
use crate::stt_models::transcribe::{
28
    ModelInfo, ModelInfoData, ModelState, Transcribe, dictation_context,
29
};
30
use super_voice_shared::models::contexts::{DictationContext, ExtraContext};
31
32
const SAMPLE_RATE: u32 = 16000;
33
34
/// A running, sandboxed subprocess backend usable as a [`Transcribe`] model.
35
pub struct SubprocessBackend {
36
    backend: engine::SubprocessBackend,
37
    model_id: String,
38
    info: ModelInfoData,
39
    /// The user's dictation context, whose headers the engine adds to every
40
    /// request, kept whole so a dictation's own can be added to it. `None`
41
    /// when the model takes no context.
42
    user_context: parking_lot::RwLock<Option<DictationContext>>,
43
}
44
45
impl SubprocessBackend {
46
    /// Provision the selected model, spawn the sandboxed backend, and load it.
47
    ///
48
    /// `backend_dir` holds `backend.toml` and the `entrypoint` binary; model
49
    /// files are downloaded into `<backend_dir>/<dest>`. `device_pref` is the
50
    /// resolved accelerator (`"cpu"`, `"cuda"`, `"rocm"`, `"metal"`,
51
    /// `"vulkan"`), or empty when none resolved, which leaves the backend to
52
    /// select for itself. `context_headers` are the already-formed
53
    /// `x-voice-secret-*` / `x-voice-option-*` pairs to inject on every
54
    /// request, each under its former name too.
55
    ///
56
    /// A model that declares `prepare_files` has those downloaded first. Its
57
    /// backend is then started and sent `POST /v1/prepare`, so it builds its
58
    /// GPU kernels while the rest of the files download, and the load after
59
    /// the download is an ordinary one.
60
    ///
61
    /// # Errors
62
    /// Returns an error if provisioning, spawning, or loading fails.
63
0
    pub async fn spawn(
64
0
        backend_dir: &Path,
65
0
        model_name: &str,
66
0
        device_pref: &str,
67
0
        tracker: Option<&Arc<crate::download_progress::DownloadProgressTracker>>,
68
0
        context_headers: Vec<(String, String)>,
69
0
    ) -> Result<Self> {
70
0
        let manifest = Manifest::load(backend_dir)?;
71
72
0
        let model = manifest
73
0
            .models
74
0
            .iter()
75
0
            .find(|m| m.name == model_name)
76
0
            .ok_or_else(|| anyhow!("model {model_name} not declared in backend.toml"))?;
77
78
        // Provision ONLY the selected model's files (lazy per model). The
79
        // tracker (when present) reports per-file and per-byte progress through
80
        // `DownloadStateManager` so the app's progress bar updates in
81
        // real time. Each file carries its own URL and destination; `parse`
82
        // already validated every `destination` as a safe relative path, so the
83
        // join below cannot escape the backend dir. The files a prepare reads
84
        // go first, in the order the manifest lists them.
85
0
        let (prepare_files, rest_files): (Vec<_>, Vec<_>) = model
86
0
            .files
87
0
            .iter()
88
0
            .partition(|spec| model.prepare_files.contains(&spec.destination));
89
        let item = |spec: &FileSpec| DownloadItem {
90
0
            url: spec.url.clone(),
91
0
            destination: backend_dir.join(&spec.destination),
92
0
            sha256: spec.sha256.clone(),
93
0
        };
94
0
        let prepare_items: Vec<_> = prepare_files.into_iter().map(item).collect();
95
0
        let rest_items: Vec<_> = rest_files.into_iter().map(item).collect();
96
0
        info!(
97
0
            "provisioning {model_name}: {} files into {}",
98
0
            prepare_items.len() + rest_items.len(),
99
0
            backend_dir.display()
100
        );
101
102
        // Once every file is on disk, spawning the sandboxed unit and loading
103
        // weights onto the device is the slow tail (tens of seconds for a
104
        // multi-GB model on GPU) but isn't byte-tracked — flip the tracker
105
        // to "loading_model" so the app swaps the full download
106
        // bar for a "Loading model into memory…" indicator instead of
107
        // freezing on a full bar.
108
0
        let mark_loading = || {
109
0
            if let Some(t) = tracker {
110
0
                t.mark_loading();
111
0
                t.broadcast_progress();
112
0
            }
113
0
        };
114
115
0
        let start = Start {
116
0
            backend_dir,
117
0
            entrypoint: &manifest.backend.entrypoint,
118
0
            model: model_name,
119
0
            provider: model.provider.as_deref(),
120
0
            devices: &model.supported_devices,
121
0
            device_pref,
122
0
            context_headers,
123
0
        };
124
0
        let mut backend = if model.prepare_files.is_empty() {
125
0
            provision(model_name, &rest_items, tracker, 0).await?;
126
0
            mark_loading();
127
0
            engine::SubprocessBackend::start(&super_voice_shared::SUPER_VOICE, start).await?
128
        } else {
129
0
            provision(model_name, &prepare_items, tracker, 0).await?;
130
            // Dropping the backend stops it, so a download that fails or is
131
            // cancelled below takes the prepare down with it.
132
            let backend =
133
0
                engine::SubprocessBackend::start(&super_voice_shared::SUPER_VOICE, start).await?;
134
0
            backend.prepare().await;
135
0
            provision(model_name, &rest_items, tracker, prepare_items.len()).await?;
136
0
            mark_loading();
137
0
            backend
138
        };
139
140
        // What the backend reports of its own load goes to the tracker, so the
141
        // card can say what the load is doing rather than sit on a full bar.
142
0
        let forward = tracker.map(|t| {
143
0
            move |load: LoadProgress| {
144
0
                t.set_load_progress(load);
145
0
                t.broadcast_progress();
146
0
            }
147
0
        });
148
0
        backend
149
            .load(
150
0
                forward
151
0
                    .as_ref()
152
0
                    .map(|f| f as &(dyn Fn(LoadProgress) + Send + Sync)),
153
            )
154
0
            .await?;
155
156
0
        let interval = model
157
0
            .processing_interval_ms
158
0
            .map_or_else(|| Duration::from_secs(2), Duration::from_millis);
159
0
        let info = ModelInfoData::new(
160
0
            model_name,
161
0
            manifest.backend.source.clone(),
162
0
            model.multilingual,
163
0
            model.is_online(),
164
0
            interval,
165
0
        );
166
167
0
        Ok(Self {
168
0
            backend,
169
0
            model_id: model_name.to_string(),
170
0
            info,
171
0
            user_context: parking_lot::RwLock::new(None),
172
0
        })
173
0
    }
174
175
    /// The user's dictation context the model was loaded with, which a
176
    /// dictation's own is added to. See [`BackendContext::context`].
177
    ///
178
    /// [`BackendContext::context`]: crate::stt_models::transcribe::BackendContext::context
179
    #[must_use]
180
0
    pub fn with_user_context(self, context: Option<DictationContext>) -> Self {
181
0
        *self.user_context.write() = context;
182
0
        self
183
0
    }
184
185
    /// The headers a model request carries: the JSON body, which model it is
186
    /// for, and a dictation's own context when it brought one. The engine
187
    /// sends a header the request names in place of the instance's, so that
188
    /// context replaces the user's for this request alone.
189
0
    fn model_headers(&self, extra: Option<&ExtraContext>) -> Vec<(String, String)> {
190
0
        let mut headers = json_headers();
191
0
        backend_headers::push(
192
0
            &mut headers,
193
0
            Feature::SpeechToText,
194
0
            "model",
195
0
            self.model_id.clone(),
196
0
        );
197
0
        if let Some(context) = dictation_context(self.user_context.read().as_ref(), extra) {
198
0
            backend_headers::push_context(&mut headers, &context);
199
0
        }
200
0
        headers
201
0
    }
202
}
203
204
/// Download `items` for `model_name`, numbering them from `first` on the
205
/// tracker so a load provisioned in two parts counts its files once.
206
0
async fn provision(
207
0
    model_name: &str,
208
0
    items: &[DownloadItem],
209
0
    tracker: Option<&Arc<crate::download_progress::DownloadProgressTracker>>,
210
0
    first: usize,
211
0
) -> Result<()> {
212
0
    crate::stt_models::download::download_files(items, tracker, first)
213
0
        .await
214
0
        .with_context(|| format!("provisioning {model_name}"))
215
0
}
216
217
impl ModelInfo for SubprocessBackend {
218
0
    fn info(&self) -> &ModelInfoData {
219
0
        &self.info
220
0
    }
221
}
222
223
impl ModelState for SubprocessBackend {
224
    /// Device label the backend reported at load time (e.g. `"cuda"`).
225
0
    fn device(&self) -> String {
226
0
        self.backend.device().to_string()
227
0
    }
228
}
229
230
#[async_trait]
231
impl Transcribe for SubprocessBackend {
232
    /// Swap the injected secret/option pairs. The next `/v1` request carries
233
    /// them; one already in flight keeps the set it was built with.
234
    ///
235
    /// `user_allowed_hosts` is ignored, and there is nothing here to ignore it
236
    /// with: the sandbox gives a subprocess backend no network, so it has no
237
    /// egress to authorize and `base_url` means nothing to it.
238
0
    fn reconfigure(&self, context: crate::stt_models::transcribe::BackendContext) {
239
0
        self.backend.set_context_headers(context.headers);
240
0
        *self.user_context.write() = context.context;
241
0
    }
242
243
    /// Stop the sandboxed backend asynchronously and remove the socket file.
244
    /// Called by the daemon before the
245
    /// [`LoadedModel`](crate::daemon::types::LoadedModel) is dropped — gives
246
    /// us a real `.await` instead of blocking the runtime in `Drop`. After
247
    /// this returns, the synchronous `Drop` path is a no-op and stays for
248
    /// crash paths and tests.
249
0
    async fn shutdown(&mut self) -> Result<()> {
250
        self.backend.shutdown().await;
251
        Ok(())
252
0
    }
253
254
    async fn transcribe_audio(
255
        &mut self,
256
        audio: &[f32],
257
        sample_rate: u32,
258
        language: Option<&str>,
259
        extra: Option<&ExtraContext>,
260
0
    ) -> Result<String> {
261
        // The daemon owns resampling; backends receive 16 kHz.
262
        let audio16 = resample(audio, sample_rate, SAMPLE_RATE, ResampleQuality::Fast)?;
263
        let body = crate::stt_models::v1::build_transcribe_body(&audio16, SAMPLE_RATE, language)?;
264
        let (status, resp) = self
265
            .backend
266
            .request("POST", "/v1/transcribe", &self.model_headers(extra), body)
267
            .await?;
268
        crate::stt_models::v1::parse_transcribe_response(status, &resp)
269
0
    }
270
271
    async fn process_text(
272
        &mut self,
273
        text: &str,
274
        language: Option<&str>,
275
        extra: Option<&ExtraContext>,
276
0
    ) -> Result<String> {
277
        let body = crate::stt_models::v1::build_process_body(text, language)?;
278
        let (status, resp) = self
279
            .backend
280
            .request("POST", "/v1/process", &self.model_headers(extra), body)
281
            .await?;
282
        crate::stt_models::v1::parse_process_response(status, &resp)
283
0
    }
284
}
285
286
/// Stop backends left behind by a previous daemon run. See
287
/// [`super_engine_daemon::subprocess::cleanup_orphans`].
288
200
pub async fn cleanup_orphan_units() {
289
200
    engine::cleanup_orphans(&super_voice_shared::SUPER_VOICE).await;
290
200
}