hostbat 0.9.0

Generic deterministic module host: mount content-identified modules over a syncbat Core.
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
//! The host builder: mount content-identified modules, validate them against
//! each other, then lower the whole set into one `syncbat` runtime.
//!
//! `mount` performs the cross-module validation a single module cannot do alone
//! (id / operation / receipt-namespace / job-kind collisions) and re-verifies
//! each module's manifest hash against its declared parts (tamper detection).
//! `build` then **lowers** every module into a single [`syncbat::CoreBuilder`] —
//! it does not re-wrap it — composes the per-module guards into one routing
//! guard, attaches the receipt sink, and computes the host-composition
//! fingerprint.

use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

use batpak::store::{Spawn, ThreadSpawn};
use syncbat::{
    AdmissionDecision, AdmissionGuard, CoreBuilder, Ctx, EffectBackend, Handler, HandlerError,
    HandlerResult, OperationDescriptor, OperationEffectRow, ReceiptSink,
};

use crate::composition::CompositionSchemaBuilder;
use crate::descriptor::HookPhase;
use crate::error::HostError;
use crate::event_payload_binding::EventPayloadBinding;
use crate::host::{Host, HostHook, HostParts};
use crate::host_control_backend::{HostControlEffectBackend, HostController};
use crate::identity::{canonical_digest, HostFingerprint};
use crate::interface::compute_interface_fingerprint;
use crate::module::{BoxedJob, HostModule, HostModuleParts};
use crate::schema::{SchemaRegistry, SchemaRole};
use crate::subscription::SubscriptionDescriptor;
use crate::validating_effect_backend::ValidatingEffectBackend;

type BoxedGuard = Box<dyn AdmissionGuard + 'static>;
type BoxedHandler = Box<dyn Handler + 'static>;
type BoxedReceiptSink = Box<dyn ReceiptSink + 'static>;
type BoxedEffectBackend = Box<dyn EffectBackend + 'static>;
type BoxedHostController = Box<dyn HostController + 'static>;

/// Domain separator for the host-composition fingerprint.
const HOST_FINGERPRINT_DOMAIN: &str = "hostbat.host.v1";

/// Builder that mounts modules and lowers them into a runnable [`Host`].
pub struct HostBuilder {
    modules: Vec<HostModuleParts>,
    module_ids: BTreeSet<String>,
    operation_owners: BTreeMap<String, String>,
    operation_effect_rows: BTreeMap<String, OperationEffectRow>,
    receipt_namespaces: BTreeMap<String, String>,
    job_owners: BTreeMap<String, String>,
    subscription_owners: BTreeMap<String, String>,
    event_payload_bindings: BTreeMap<u16, (String, String)>,
    schemas: CompositionSchemaBuilder,
    spawn: Arc<dyn Spawn>,
    receipt_sink: Option<BoxedReceiptSink>,
    effect_backend: Option<BoxedEffectBackend>,
    host_control: Option<BoxedHostController>,
}

impl Default for HostBuilder {
    fn default() -> Self {
        Self {
            modules: Vec::new(),
            module_ids: BTreeSet::new(),
            operation_owners: BTreeMap::new(),
            operation_effect_rows: BTreeMap::new(),
            receipt_namespaces: BTreeMap::new(),
            job_owners: BTreeMap::new(),
            subscription_owners: BTreeMap::new(),
            event_payload_bindings: BTreeMap::new(),
            schemas: CompositionSchemaBuilder::default(),
            spawn: Arc::new(ThreadSpawn),
            receipt_sink: None,
            effect_backend: None,
            host_control: None,
        }
    }
}

impl HostBuilder {
    /// Create an empty host builder backed by the production [`ThreadSpawn`].
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Use a custom [`Spawn`] backend for the supervisor (e.g. a deterministic
    /// test scheduler). Replaces the default [`ThreadSpawn`].
    #[must_use]
    pub fn spawn_with(mut self, spawn: Arc<dyn Spawn>) -> Self {
        self.spawn = spawn;
        self
    }

    /// Attach the receipt sink the composed runtime records into.
    #[must_use]
    pub fn receipt_sink<S>(mut self, sink: S) -> Self
    where
        S: ReceiptSink + 'static,
    {
        self.receipt_sink = Some(Box::new(sink));
        self
    }

    /// Attach the runtime-owned effect backend operations append through.
    ///
    /// Operations append events only via `Ctx`, which performs the append
    /// through this backend; without it bound, an `append_event` call fails
    /// closed instead of reaching a store the runtime did not mediate.
    #[must_use]
    pub fn effect_backend<B>(mut self, backend: B) -> Self
    where
        B: EffectBackend + 'static,
    {
        self.effect_backend = Some(Box::new(backend));
        self
    }

    /// Attach the controller that performs a `Control` operation's declared host
    /// controls.
    ///
    /// `Control` operations reach host authority only via `Ctx`, which performs
    /// the identified control through this controller; without it bound, a
    /// `use_host_control` call fails closed instead of touching the host. The
    /// composed host-control backend layers OUTER over any [`effect_backend`],
    /// so the store axes still flow through that inner backend.
    ///
    /// [`effect_backend`]: Self::effect_backend
    #[must_use]
    pub fn host_control<C>(mut self, controller: C) -> Self
    where
        C: HostController + 'static,
    {
        self.host_control = Some(Box::new(controller));
        self
    }

    /// Mount a module, validating it against everything already mounted.
    ///
    /// # Errors
    /// A [`HostError`] collision variant if the module's id, any operation,
    /// receipt namespace, or job kind clashes with a mounted module; or
    /// [`HostError::ModuleHashMismatch`] if the module's manifest does not match
    /// its declared parts.
    pub fn mount(mut self, module: HostModule) -> Result<Self, HostError> {
        if !module.manifest().verify_hash()? {
            return Err(HostError::ModuleHashMismatch {
                module: module.manifest().id().to_owned(),
            });
        }

        let parts = module.into_parts();
        let id = parts.manifest.id().to_owned();

        if !self.module_ids.insert(id.clone()) {
            return Err(HostError::DuplicateModuleId { id });
        }
        for descriptor in parts.manifest.operations() {
            let name = descriptor.name().to_owned();
            if let Some(existing_row) = self.operation_effect_rows.get(&name) {
                if existing_row != descriptor.effect_row() {
                    return Err(HostError::EffectConflict {
                        operation: name,
                        module: id,
                    });
                }
                return Err(HostError::DuplicateOperation {
                    operation: name,
                    module: id,
                });
            }
            self.operation_owners.insert(name.clone(), id.clone());
            self.operation_effect_rows
                .insert(name, descriptor.effect_row().clone());
        }
        for namespace in parts.manifest.receipt_namespaces() {
            if self
                .receipt_namespaces
                .insert(namespace.to_owned(), id.clone())
                .is_some()
            {
                return Err(HostError::DuplicateReceiptNamespace {
                    namespace: namespace.to_owned(),
                    module: id,
                });
            }
        }
        for descriptor in parts.manifest.jobs() {
            if self
                .job_owners
                .insert(descriptor.kind.clone(), id.clone())
                .is_some()
            {
                return Err(HostError::DuplicateJobKind {
                    kind: descriptor.kind.clone(),
                    module: id,
                });
            }
        }
        for descriptor in parts.manifest.subscriptions() {
            let subscription_id = descriptor.id().as_str().to_owned();
            if self
                .subscription_owners
                .insert(subscription_id.clone(), id.clone())
                .is_some()
            {
                return Err(HostError::DuplicateSubscriptionId {
                    id: subscription_id,
                    module: id,
                });
            }
        }
        for binding in parts.manifest.event_payload_bindings() {
            let kind = binding.kind_raw();
            let schema_ref = binding.payload_schema_ref().to_owned();
            if let Some((first_module, first_schema_ref)) = self.event_payload_bindings.get(&kind) {
                if first_schema_ref == &schema_ref {
                    return Err(HostError::DuplicateEventPayloadBinding {
                        kind,
                        module: id.clone(),
                    });
                }
                return Err(HostError::EventPayloadBindingConflict {
                    kind,
                    first_module: first_module.clone(),
                    first_schema_ref: first_schema_ref.clone(),
                    second_module: id.clone(),
                    second_schema_ref: schema_ref,
                });
            }
            self.event_payload_bindings
                .insert(kind, (id.clone(), schema_ref));
        }
        // Aggregate this module's schemas into the composition, failing closed on
        // a cross-module identity collision with a differing canonical encoding.
        for descriptor in parts.manifest.schemas() {
            self.schemas.add(&id, descriptor)?;
        }

        self.modules.push(parts);
        Ok(self)
    }

    /// Lower the mounted modules into a runnable [`Host`].
    ///
    /// # Errors
    /// [`HostError::EmptyHost`] if nothing is mounted; [`HostError::ModuleCoherence`]
    /// if a declared operation has no handler; [`HostError::Build`] if the lowered
    /// `syncbat` runtime does not validate; or [`HostError::CanonicalEncoding`] if
    /// the fingerprint cannot be sealed.
    pub fn build(self) -> Result<Host, HostError> {
        if self.modules.is_empty() {
            return Err(HostError::EmptyHost);
        }

        let fingerprint = compute_fingerprint(&self.modules)?;
        let composition_schemas = self.schemas.seal()?;
        validate_subscription_payload_schemas(&self.modules, &composition_schemas)?;
        validate_event_payload_bindings(&self.modules, &composition_schemas)?;
        let interface_fingerprint =
            compute_interface_fingerprint(&self.modules, &composition_schemas)?;
        let schema_registry = SchemaRegistry::from_descriptors(
            composition_schemas
                .schemas()
                .map(|entry| entry.descriptor().clone()),
        );

        let lowered = lower_modules(self.modules, &schema_registry)?;
        let mut core_builder = lowered.core_builder;
        if !lowered.guard.is_empty() {
            core_builder.admission_guard(lowered.guard);
        }
        if let Some(sink) = self.receipt_sink {
            core_builder.receipt_sink_boxed(sink);
        } else {
            // The core builder fails closed without a receipt sink. A host that
            // was assembled without one explicitly records no receipts; opt out
            // here so the absence is a stated choice rather than a silent drop.
            core_builder.without_receipts();
        }
        // The store-effect backend, schema-validated at the append boundary. The
        // host-control layer wraps this OUTER so store axes still flow through it.
        let inner_backend: Option<BoxedEffectBackend> = self.effect_backend.map(|backend| {
            Box::new(ValidatingEffectBackend::new(
                backend,
                collect_event_payload_binding_map(&lowered.event_payload_bindings),
                schema_registry.clone(),
            )) as BoxedEffectBackend
        });
        if let Some(controller) = self.host_control {
            let host_control_backend = HostControlEffectBackend::new(inner_backend, controller);
            core_builder.effect_backend_boxed(Box::new(host_control_backend));
        } else if let Some(inner) = inner_backend {
            core_builder.effect_backend_boxed(inner);
        }

        let mut startup = lowered.startup;
        let mut shutdown = lowered.shutdown;
        let mut operation_descriptors = lowered.operation_descriptors;
        let mut subscriptions = lowered.subscriptions;
        let mut event_payload_bindings = lowered.event_payload_bindings;

        // Global deterministic hook order: (order, module-id, name). Module ids
        // are unique, so this is a total order with no cross-module ambiguity.
        startup.sort_by(|a, b| a.order_key().cmp(&b.order_key()));
        shutdown.sort_by(|a, b| a.order_key().cmp(&b.order_key()));
        operation_descriptors.sort_by(|a, b| a.name().cmp(b.name()));
        subscriptions.sort_by(|(a_id, a), (b_id, b)| {
            a_id.cmp(b_id)
                .then_with(|| a.id().as_str().cmp(b.id().as_str()))
        });
        event_payload_bindings.sort_by(|(a_id, a), (b_id, b)| {
            a_id.cmp(b_id).then_with(|| a.kind_raw().cmp(&b.kind_raw()))
        });

        let core = core_builder.build()?;
        Ok(Host::new(HostParts {
            core,
            supervisor: crate::supervisor::Supervisor::new(self.spawn),
            fingerprint,
            interface_fingerprint,
            operations: operation_descriptors,
            subscriptions,
            event_payload_bindings,
            composition_schemas,
            schema_registry,
            startup,
            shutdown,
            job_factories: lowered.job_factories,
        }))
    }
}

struct LoweredModules {
    core_builder: CoreBuilder,
    guard: CompositeGuard,
    startup: Vec<HostHook>,
    shutdown: Vec<HostHook>,
    job_factories: BTreeMap<String, BoxedJob>,
    operation_descriptors: Vec<OperationDescriptor>,
    subscriptions: Vec<(String, SubscriptionDescriptor)>,
    event_payload_bindings: Vec<(String, EventPayloadBinding)>,
}

fn lower_modules(
    modules: Vec<HostModuleParts>,
    schema_registry: &SchemaRegistry,
) -> Result<LoweredModules, HostError> {
    let mut core_builder = CoreBuilder::new();
    let mut guard = CompositeGuard::default();
    let mut startup: Vec<HostHook> = Vec::new();
    let mut shutdown: Vec<HostHook> = Vec::new();
    let mut job_factories: BTreeMap<String, BoxedJob> = BTreeMap::new();
    let mut operation_descriptors: Vec<OperationDescriptor> = Vec::new();
    let mut subscriptions: Vec<(String, SubscriptionDescriptor)> = Vec::new();
    let mut event_payload_bindings: Vec<(String, EventPayloadBinding)> = Vec::new();

    for parts in modules {
        let HostModuleParts {
            manifest,
            mut handlers,
            guard: module_guard,
            hooks,
            jobs,
        } = parts;
        let module_id = manifest.id().to_owned();

        let mut operation_names = Vec::new();
        for descriptor in manifest.operations() {
            let name = descriptor.name().to_owned();
            let handler = handlers.remove(&name).ok_or_else(|| {
                HostError::coherence(&module_id, format!("operation {name:?} has no handler"))
            })?;
            let handler =
                SchemaValidatingHandler::new(descriptor, schema_registry.clone(), handler);
            core_builder.register_boxed(descriptor.clone(), Box::new(handler))?;
            operation_descriptors.push(descriptor.clone());
            operation_names.push(name);
        }
        if let Some(module_guard) = module_guard {
            guard.add(operation_names, module_guard);
        }
        for (descriptor, hook) in hooks {
            let entry = HostHook::new(module_id.clone(), descriptor, hook);
            match entry.phase() {
                HookPhase::Startup => startup.push(entry),
                HookPhase::Shutdown => shutdown.push(entry),
            }
        }
        for (kind, body) in jobs {
            job_factories.insert(kind, body);
        }
        for descriptor in manifest.subscriptions() {
            subscriptions.push((module_id.clone(), descriptor.clone()));
        }
        for binding in manifest.event_payload_bindings() {
            event_payload_bindings.push((module_id.clone(), binding.clone()));
        }
    }

    Ok(LoweredModules {
        core_builder,
        guard,
        startup,
        shutdown,
        job_factories,
        operation_descriptors,
        subscriptions,
        event_payload_bindings,
    })
}

fn collect_event_payload_binding_map(
    bindings: &[(String, EventPayloadBinding)],
) -> BTreeMap<u16, String> {
    bindings
        .iter()
        .map(|(_module, binding)| (binding.kind_raw(), binding.payload_schema_ref().to_owned()))
        .collect()
}

fn validate_event_payload_bindings(
    modules: &[HostModuleParts],
    composition_schemas: &crate::composition::HostCompositionManifest,
) -> Result<(), HostError> {
    for parts in modules {
        let module_id = parts.manifest.id();
        for binding in parts.manifest.event_payload_bindings() {
            let reference = binding.payload_schema_ref();
            let matches = composition_schemas
                .schemas()
                .filter_map(|entry| {
                    let schema = entry.descriptor();
                    if schema.id().as_str() == reference
                        && schema.role() == SchemaRole::EventPayload
                    {
                        Some(schema)
                    } else {
                        None
                    }
                })
                .collect::<Vec<_>>();
            match matches.as_slice() {
                [_descriptor] => {}
                _ => {
                    return Err(HostError::EventPayloadBindingSchemaMissing {
                        module: module_id.to_owned(),
                        kind: binding.kind_raw(),
                        reference: reference.to_owned(),
                    });
                }
            }
        }
    }
    Ok(())
}

fn validate_subscription_payload_schemas(
    modules: &[HostModuleParts],
    composition_schemas: &crate::composition::HostCompositionManifest,
) -> Result<(), HostError> {
    for parts in modules {
        let module_id = parts.manifest.id();
        for descriptor in parts.manifest.subscriptions() {
            let role = descriptor.required_payload_role();
            let reference = descriptor.payload_schema_ref();
            let matches = composition_schemas
                .schemas()
                .filter_map(|entry| {
                    let schema = entry.descriptor();
                    if schema.id().as_str() == reference && schema.role() == role {
                        Some(schema)
                    } else {
                        None
                    }
                })
                .collect::<Vec<_>>();
            match matches.as_slice() {
                [_descriptor] => {}
                _ => {
                    return Err(HostError::SubscriptionPayloadSchemaMissing {
                        module: module_id.to_owned(),
                        subscription: descriptor.id().as_str().to_owned(),
                        reference: reference.to_owned(),
                        role: role.as_str().to_owned(),
                    });
                }
            }
        }
    }
    Ok(())
}

struct SchemaValidatingHandler {
    operation: String,
    input_schema_ref: String,
    output_schema_ref: String,
    registry: SchemaRegistry,
    inner: BoxedHandler,
}

impl SchemaValidatingHandler {
    fn new(
        descriptor: &OperationDescriptor,
        registry: SchemaRegistry,
        inner: BoxedHandler,
    ) -> Self {
        Self {
            operation: descriptor.name().to_owned(),
            input_schema_ref: descriptor.input_schema_ref().to_owned(),
            output_schema_ref: descriptor.output_schema_ref().to_owned(),
            registry,
            inner,
        }
    }
}

impl Handler for SchemaValidatingHandler {
    fn handle(&mut self, input: &[u8], cx: &mut Ctx<'_>) -> HandlerResult {
        self.registry
            .validate(&self.input_schema_ref, SchemaRole::OperationInput, input)
            .map_err(|error| {
                HandlerError::invalid_input(format!(
                    "operation {} input schema validation failed: {error}",
                    self.operation
                ))
            })?;
        let output = self.inner.handle(input, cx)?;
        self.registry
            .validate(
                &self.output_schema_ref,
                SchemaRole::OperationOutput,
                &output,
            )
            .map_err(|error| {
                HandlerError::failed(format!(
                    "operation {} output schema validation failed: {error}",
                    self.operation
                ))
            })?;
        Ok(output)
    }
}

fn compute_fingerprint(modules: &[HostModuleParts]) -> Result<HostFingerprint, HostError> {
    let mut entries: Vec<FingerprintEntry> = modules
        .iter()
        .map(|parts| FingerprintEntry {
            module_id: parts.manifest.id().to_owned(),
            module_digest: *parts.manifest.digest().bytes(),
        })
        .collect();
    entries.sort_by(|a, b| a.module_id.cmp(&b.module_id));
    let view = FingerprintView {
        domain: HOST_FINGERPRINT_DOMAIN,
        modules: entries,
    };
    canonical_digest(&view).map(HostFingerprint)
}

#[derive(serde::Serialize)]
struct FingerprintEntry {
    module_id: String,
    module_digest: [u8; 32],
}

#[derive(serde::Serialize)]
struct FingerprintView {
    domain: &'static str,
    modules: Vec<FingerprintEntry>,
}

/// Routes each operation to the guard of the module that declared it. Operations
/// from modules with no guard are admitted.
#[derive(Default)]
struct CompositeGuard {
    route: BTreeMap<String, usize>,
    guards: Vec<BoxedGuard>,
}

impl CompositeGuard {
    fn add(&mut self, operations: Vec<String>, guard: BoxedGuard) {
        let index = self.guards.len();
        self.guards.push(guard);
        for operation in operations {
            self.route.insert(operation, index);
        }
    }

    fn is_empty(&self) -> bool {
        self.guards.is_empty()
    }
}

impl AdmissionGuard for CompositeGuard {
    fn admit(
        &self,
        descriptor: &OperationDescriptor,
        input: &[u8],
        cx: &mut Ctx<'_>,
    ) -> AdmissionDecision {
        match self.route.get(descriptor.name()) {
            Some(&index) => self.guards[index].admit(descriptor, input, cx),
            None => AdmissionDecision::Admit,
        }
    }
}