subc-daemon 0.54.12

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
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
//! Recovery retains running views, but never imports rejected store authority.

use super::*;

impl OwnerState {
    pub(super) fn queue_anchor_hints(&mut self) {
        self.anchor_hints.extend(self.anchor_waiters.drain());
        if !self.anchor_hints.is_empty() {
            // Wake only for recovered anchor hints, not whenever the configuration
            // owner's mutex is released. Unrelated wakes can disrupt the supervisor's
            // sequence of recording an exited child and allowing its replacement.
            self.anchor_notify.notify_one();
        }
    }
}

impl ApprovedDaemonConfiguration {
    pub(crate) fn identity(&self) -> ApprovalIdentity {
        ApprovalIdentity {
            generation: self.generation,
            approval_digest: self.approval_digest.clone(),
            authority_incarnation: self.authority_incarnation.clone(),
        }
    }
    pub(crate) fn generation(&self) -> u64 {
        self.generation
    }

    pub(crate) fn configuration(
        &self,
    ) -> Result<(
        crate::daemon_config::DaemonConfig,
        crate::daemon_config::ActivityConfig,
    )> {
        let bytes = self.daemon.bytes.as_deref().ok_or_else(GateError::stale)?;
        let doc = std::str::from_utf8(bytes).map_err(|_| GateError::stale())?;
        let path = self.daemon.path.as_deref().ok_or_else(GateError::stale)?;
        crate::daemon_config::parse_with_activity(doc, std::path::Path::new(path))
            .map_err(|error| GateError::new("invalid_daemon_config", error.to_string()))
    }

    pub(crate) fn module_entry(
        &self,
        module: &str,
    ) -> Result<crate::daemon_config::ConfiguredModule> {
        self.configuration()?
            .0
            .modules
            .into_iter()
            .find(|entry| entry.module_id == module)
            .ok_or_else(GateError::stale)
    }

    pub(crate) fn changes_entry(&self, module: &str) -> bool {
        self.changed_entries.contains(module)
    }
}

impl RuntimeOwner {
    pub(crate) fn authority_exit_retry_generation(&self) -> Result<Option<u64>> {
        Ok(self.lock()?.authority_exit)
    }
    pub(crate) fn pending_authority_exit(&self) -> Result<Option<u64>> {
        let mut state = self.lock()?;
        if state.authority_exit.is_some() && state.store_read(ConfigStore::delivery_ready).is_ok() {
            Ok(state.authority_exit)
        } else {
            Ok(None)
        }
    }
    pub(crate) fn is_recovering(&self) -> bool {
        if self.inner.is_poisoned() {
            return true;
        }
        self.published
            .read()
            .map(|cache| cache.is_recovering())
            .unwrap_or(true)
    }

    pub(crate) fn refuses_control_in_recovery(&self) -> bool {
        self.polled_snapshot()
            .map(|snapshot| snapshot.refuses_control_in_recovery)
            .unwrap_or(true)
    }

    /// Verify the store off the request path. A changed store is published
    /// along with the other configuration views before the owner is released.
    pub(crate) fn check_recovery(&self) -> Result<bool> {
        let mut state = self.lock()?;
        let _ = state.store_read(ConfigStore::check);
        Ok(Published::control_recovery(
            &state.store,
            state.recovery_exit_hold,
        ))
    }

    pub(crate) fn poll_store_integrity(&self) -> Result<()> {
        crate::forwarding::assert_forwarding_unlocked("the configuration owner's state");
        let mut state = self.inner.lock().map_err(|_| {
            GateError::new("config_unavailable", "configuration owner lock is poisoned")
        })?;
        let before = store_witness(&state.store);
        state.store.poll_integrity();
        if store_witness(&state.store) != before {
            // An unchanged fingerprint needs no owner maintenance. An observed
            // transition must publish before this same mutex guard is released.
            let mut guard = OwnerGuard::new(state, self);
            guard.changed = true;
        }
        Ok(())
    }

    pub(crate) fn authority_exit_configuration(
        &self,
        generation: u64,
    ) -> Result<
        Option<(
            crate::daemon_config::DaemonConfig,
            crate::daemon_config::ActivityConfig,
            bool,
            ApprovedDaemonConfiguration,
        )>,
    > {
        let mut state = self.lock()?;
        if state.authority_exit != Some(generation) {
            return Ok(None);
        }
        state.store.delivery_ready()?;
        let authority_incarnation = state.authority_incarnation.clone();
        let body = state.store.body()?;
        let layer = body
            .generations
            .get(&generation)
            .and_then(|entry| entry.delivery.as_ref())
            .and_then(|snapshot| snapshot.daemon.as_ref())
            .ok_or_else(|| {
                GateError::new("config_unavailable", "approved exit has no daemon snapshot")
            })?;
        let stamped = body.stamped;
        let mut approved = ApprovedDaemonConfiguration {
            generation,
            approval_digest: body.generations[&generation].generation.plan_digest.clone(),
            authority_incarnation,
            daemon: std::sync::Arc::new(layer.clone()),
            changed_entries: BTreeSet::new(),
        };
        let (config, activity) = approved.configuration()?;
        approved.changed_entries = config
            .modules
            .iter()
            .filter(|module| state.reconciled_entries.get(&module.module_id) != Some(module))
            .map(|module| module.module_id.clone())
            .collect();
        Ok(Some((config, activity, stamped, approved)))
    }

    /// Record each completed entry before waiting on the next module. A retry
    /// must not undo a runtime override made after an earlier successful step.
    pub(crate) fn daemon_entry_reconciled(
        &self,
        approved: &ApprovedDaemonConfiguration,
        module: &str,
    ) -> Result<()> {
        let mut state = self.lock()?;
        if !Self::authority_exit_matches(&state, approved) {
            return Err(GateError::stale());
        }
        let changed = if let Some(entry) = approved
            .configuration()?
            .0
            .modules
            .into_iter()
            .find(|entry| entry.module_id == module)
        {
            state
                .reconciled_entries
                .insert(module.to_owned(), entry.clone())
                != Some(entry)
        } else {
            state.reconciled_entries.remove(module).is_some()
        };
        drop(state);
        if changed {
            self.notify_delivery_changed();
        }
        Ok(())
    }

    /// Release admission only after all committed-exit reconciliation succeeds.
    pub(crate) fn complete_authority_exit(
        &self,
        approved: &ApprovedDaemonConfiguration,
    ) -> Result<()> {
        let mut state = self.lock()?;
        if !Self::authority_exit_matches(&state, approved) {
            return Err(GateError::stale());
        }
        // Actors created under an exit hold may not have been observed by the
        // coordinator yet. Normal approvals must not revive unrelated stopped
        // or failed actors whose daemon entries did not change.
        let unstamped = state.store.loaded_admission_state().0 == StoreState::Unstamped;
        if state.recovery_exit_hold || unstamped {
            let modules =
                crate::config_gate::GateSnapshot::from_store(&state.store.body()?.approved)?
                    .modules();
            state.admission_releases.extend(modules);
        }
        state.authority_exit = None;
        state.stamp_channel_cutover = false;
        state.recovery_exit_hold = false;
        drop(state);
        if unstamped {
            self.retire_unstamped_bindings();
        }
        Ok(())
    }

    fn authority_exit_matches(state: &OwnerState, approved: &ApprovedDaemonConfiguration) -> bool {
        state.authority_exit == Some(approved.generation)
            && std::sync::Arc::ptr_eq(
                &state.authority_incarnation,
                &approved.authority_incarnation,
            )
            && state
                .store
                .loaded_admission_state()
                .1
                .generations
                .get(&approved.generation)
                .is_some_and(|entry| entry.generation.plan_digest == approved.approval_digest)
    }

    pub(crate) fn current_approval_identity(
        &self,
        generation: u64,
    ) -> Result<Option<ApprovalIdentity>> {
        let mut state = self.lock()?;
        let authority_incarnation = state.authority_incarnation.clone();
        let body = state.store.body()?;
        Ok((body.stamped && body.last_generation == generation)
            .then(|| body.generations.get(&generation))
            .flatten()
            .map(|entry| ApprovalIdentity {
                generation,
                approval_digest: entry.generation.plan_digest.clone(),
                authority_incarnation,
            }))
    }

    /// Tag a terminal exit with the retained approval even if its store is now
    /// unverified. This identity only prevents a same-approval restart; it never
    /// supplies a launch command or admits a process from unverified contents.
    pub(crate) fn terminal_exit_approval_identity(&self) -> Result<Option<ApprovalIdentity>> {
        let state = self.lock()?;
        let body = state.store.loaded_admission_state().1;
        Ok(body
            .generations
            .get(&body.last_generation)
            .map(|entry| ApprovalIdentity {
                generation: body.last_generation,
                approval_digest: entry.generation.plan_digest.clone(),
                authority_incarnation: state.authority_incarnation.clone(),
            }))
    }

    /// Test helper that loads the current approved configuration before completing
    /// its exit. Production callers must carry their original approved configuration.
    #[cfg(test)]
    pub(crate) fn complete_authority_exit_for_test(&self, generation: u64) -> Result<()> {
        let approved = self
            .authority_exit_configuration(generation)?
            .ok_or_else(GateError::stale)?
            .3;
        self.complete_authority_exit(&approved)
    }

    pub(super) fn retire_unstamped_bindings(&self) {
        // The store mutex must already be released: image checks hold the
        // program-launch mutex while recording refusals, and retirement takes
        // that same program-launch mutex to release retained Windows handles.
        for retire in self
            .binding_retirements
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .values()
        {
            retire();
        }
    }

    pub(crate) fn take_unstamp_hint(&self, connection: ConnectionId) -> Result<bool> {
        let mut state = self.lock()?;
        // Test before removing: an absent hint leaves the owner unchanged.
        Ok(state.authority_exit.is_none()
            && state.store.loaded_admission_state().0 == StoreState::Unstamped
            && state.unstamp_hints.contains(&connection)
            && state.unstamp_hints.remove(&connection))
    }

    /// Remember only a refusal returned to an opted-in connection. Recovery may
    /// race the reply, in which case the connection needs its wakeup immediately.
    pub(crate) fn anchor_pending_served(&self, connection: ConnectionId) -> Result<()> {
        let mut state = self.lock()?;
        if state.declarations.contains_key(&connection) {
            if state.store.status().anchor_pending {
                state.anchor_waiters.insert(connection);
            } else {
                let inserted = state.anchor_hints.insert(connection);
                drop(state);
                if inserted {
                    self.notify_delivery_changed();
                }
            }
        }
        Ok(())
    }

    pub(crate) fn take_anchor_hint(&self, connection: ConnectionId) -> Result<Option<u64>> {
        let mut state = self.lock()?;
        if state.store_read(ConfigStore::status).anchor_pending
            || !state.anchor_hints.contains(&connection)
            || !state.anchor_hints.remove(&connection)
        {
            return Ok(None);
        }
        let Some((module, _)) = state.declarations.get(&connection) else {
            return Ok(None);
        };
        let (store_state, body) = state.store.loaded_admission_state();
        if store_state == crate::config_store::StoreState::Unstamped {
            return Ok(Some(0));
        }
        Ok(Some(
            body.versions
                .iter()
                .find(|(tuple, _)| &tuple.module == module && tuple.project.is_none())
                .and_then(|(_, versions)| versions.active.or(versions.pending))
                .unwrap_or(0),
        ))
    }
}

pub(super) fn active_view(
    state: &OwnerState,
    module: &str,
    declaration: &ConfigDeclareRequest,
    request: &subc_protocol::config::ConfigGetRequest,
) -> Result<subc_protocol::config::ConfigGetReply> {
    let body = state.store.loaded_admission_state().1;
    let generation = body
        .versions
        .iter()
        .find(|(tuple, _)| tuple.module == module && tuple.project.is_none())
        .and_then(|(_, versions)| versions.active)
        .ok_or_else(|| GateError::new("config_gated", "no in-memory active view in recovery"))?;
    if request.attempt.is_some() || request.generation.is_some_and(|id| id != generation) {
        return Err(GateError::new(
            "config_gated",
            "recovery serves only the in-memory active view",
        ));
    }
    let delivery = body
        .generations
        .get(&generation)
        .and_then(|entry| entry.delivery.as_ref())
        .ok_or_else(|| GateError::new("config_gated", "active delivery is unavailable"))?;
    if delivery.declarations.get(module) != Some(declaration) {
        return Err(GateError::new(
            "config_gated",
            "active declaration does not match",
        ));
    }
    let mut view = delivery
        .modules
        .get(module)
        .cloned()
        .ok_or_else(|| GateError::new("config_gated", "active view is unavailable"))?;
    view.generation = generation;
    view.status = ConfigStatus::Active;
    view.attempt = None;
    Ok(subc_protocol::config::ConfigGetReply::new(Some(view), None))
}

pub(super) fn changed_file_views(
    owner: &RuntimeOwner,
    state: &mut OwnerState,
    current: &CapturedConfiguration,
) -> Vec<ConnectionId> {
    let connections: Vec<_> = state
        .active_declarations
        .iter()
        .map(|(module, connection)| (module.clone(), *connection))
        .collect();
    connections
        .into_iter()
        .filter_map(|(module, connection)| {
            let next = &current.modules.get(&module)?.view;
            let old = owner
                .module_get_locked(
                    state,
                    connection,
                    &module,
                    subc_protocol::config::ConfigGetRequest::new(),
                    false,
                )
                .ok();
            let old = old.and_then(|reply| reply.active.or(reply.pending));
            (old.is_none_or(|old| old.layers != next.layers)).then_some(connection)
        })
        .collect()
}