phoxal-bundle 0.59.1

Phoxal persisted runtime bundle schema, writer, reader, and integrity fence.
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
//! Runtime document, asset index, and invariant validation.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use phoxal_model::Robot;
use phoxal_model::component::capability::MotorCommand;
use phoxal_model::identity::CapabilityRef;
use phoxal_runtime_contract::identity::{ParticipantArtifactId, ParticipantId};
use phoxal_runtime_contract::metadata::{ParticipantContract, ParticipantRequirement};
use phoxal_runtime_contract::version::{CompatibilityLine, FrameworkVersion};
use serde::{Deserialize, Serialize};

use crate::{
    ASSETS_DIR, AssetIndex, BinaryReference, BundleError, BundlePath, DocumentError,
    RuntimeParticipant, SelectionError,
};

/// The scheduler policy persisted for one runtime participant instance.
///
/// This belongs to the compiled runtime bundle because it is a runtime
/// selection fact, not a process-contract/launch parser type.
#[derive(
    phoxal_macros::DescribeWire, Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize,
)]
#[serde(rename_all = "snake_case")]
pub enum ParticipantClock {
    /// Follow the host's boot-anchored real clock.
    Real,
    /// Follow the simulation world clock supplied by the runtime.
    Simulation,
    /// Do not schedule robot-time steps.
    Clockless,
}

impl fmt::Display for ParticipantClock {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Real => "real",
            Self::Simulation => "simulation",
            Self::Clockless => "clockless",
        })
    }
}

/// A schema-tagged persisted runtime document.
#[derive(phoxal_macros::DescribeWire, Clone, Debug, Serialize)]
#[serde(tag = "schema", deny_unknown_fields)]
pub enum RuntimeDocument {
    /// The first runtime bundle schema. Older/future schemas are refused
    /// rather than guessed at by a runtime process.
    #[serde(rename = "phoxal/runtime-bundle/v0")]
    V0(Runtime),
}

impl<'de> Deserialize<'de> for RuntimeDocument {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(tag = "schema", deny_unknown_fields)]
        enum Wire {
            #[serde(rename = "phoxal/runtime-bundle/v0")]
            V0(Runtime),
        }

        match Wire::deserialize(deserializer)? {
            Wire::V0(runtime) => Ok(Self::new(runtime)),
        }
    }
}

impl RuntimeDocument {
    /// Wrap one already-validated runtime document.
    #[must_use]
    pub const fn new(runtime: Runtime) -> Self {
        Self::V0(runtime)
    }

    /// The runtime payload.
    #[must_use]
    pub const fn runtime(&self) -> &Runtime {
        match self {
            Self::V0(runtime) => runtime,
        }
    }

    /// The canonical robot identity persisted by this document.
    #[must_use]
    pub fn robot_id(&self) -> &phoxal_model::identity::RobotId {
        self.runtime().robot.id()
    }

    /// The canonical compiled robot.
    #[must_use]
    pub fn robot(&self) -> &Robot {
        &self.runtime().robot
    }

    /// The one compatibility line validated for this execution.
    #[must_use]
    pub fn framework_line(&self) -> CompatibilityLine {
        self.runtime().framework_line()
    }

    /// The final participant set, in persisted order.
    #[must_use]
    pub fn participants(&self) -> &[RuntimeParticipant] {
        &self.runtime().participants
    }

    /// The reusable executable artifacts selected by participant instances.
    #[must_use]
    pub fn artifacts(&self) -> &BTreeMap<ParticipantArtifactId, BinaryReference> {
        &self.runtime().artifacts
    }

    /// Find the exact persisted participant selected by a process boundary.
    pub fn participant(&self, id: &ParticipantId) -> Result<&RuntimeParticipant, SelectionError> {
        self.participants()
            .iter()
            .find(|participant| participant.id == *id)
            .ok_or_else(|| SelectionError::Unknown {
                requested: id.clone(),
            })
    }
}

/// The persisted final runtime graph and all framework-owned runtime facts.
#[derive(phoxal_macros::DescribeWire, Clone, Debug, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Runtime {
    /// The complete canonical model. Its `id` is the sole persisted RobotId;
    /// there is no namespace or duplicate top-level identity field.
    pub(crate) robot: Robot,
    /// The reusable staged executables and their embedded compatibility
    /// contracts. Multiple participant instances may point to one entry.
    pub(crate) artifacts: BTreeMap<ParticipantArtifactId, BinaryReference>,
    /// The exact process instances the executor must launch, in final
    /// persisted form.
    pub(crate) participants: Vec<RuntimeParticipant>,
    /// The participant-readable asset index and integrity facts.
    pub(crate) assets: AssetIndex,
    /// Optional supervisor router configuration, kept as an indexed asset.
    pub(crate) router: Option<RuntimeRouterConfig>,
}

impl<'de> Deserialize<'de> for Runtime {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Wire {
            robot: Robot,
            artifacts: BTreeMap<ParticipantArtifactId, BinaryReference>,
            participants: Vec<RuntimeParticipant>,
            assets: AssetIndex,
            router: Option<RuntimeRouterConfig>,
        }

        let wire = Wire::deserialize(deserializer)?;
        Self::new(
            wire.robot,
            wire.artifacts,
            wire.participants,
            wire.assets,
            wire.router,
        )
        .map_err(serde::de::Error::custom)
    }
}

impl Runtime {
    /// Construct the complete in-memory runtime document, validating its
    /// cross-field invariants exactly once.
    pub fn new(
        robot: Robot,
        artifacts: BTreeMap<ParticipantArtifactId, BinaryReference>,
        participants: Vec<RuntimeParticipant>,
        assets: AssetIndex,
        router: Option<RuntimeRouterConfig>,
    ) -> Result<Self, DocumentError> {
        let runtime = Self {
            robot,
            artifacts,
            participants,
            assets,
            router,
        };
        runtime.validate()?;
        Ok(runtime)
    }

    /// The canonical compiled robot.
    #[must_use]
    pub const fn robot(&self) -> &Robot {
        &self.robot
    }

    /// The reusable executable artifacts retained by this runtime.
    #[must_use]
    pub fn artifacts(&self) -> &BTreeMap<ParticipantArtifactId, BinaryReference> {
        &self.artifacts
    }

    /// The final participant set, in persisted order.
    #[must_use]
    pub fn participants(&self) -> &[RuntimeParticipant] {
        &self.participants
    }

    /// The participant-readable asset index.
    #[must_use]
    pub const fn assets(&self) -> &AssetIndex {
        &self.assets
    }

    /// Optional router configuration selected by build tooling.
    #[must_use]
    pub const fn router(&self) -> Option<&RuntimeRouterConfig> {
        self.router.as_ref()
    }

    /// The one compatibility line every launched participant was built on.
    ///
    /// This is the line, not a version, because that is all the document can
    /// honestly promise: validation proves the selected artifacts share a
    /// line, and they may have been built from different trains on it. The
    /// exact train behind each artifact stays readable through
    /// [`Self::artifacts`], which is where a provenance report or a diagnostic
    /// reads it from.
    ///
    /// Runtime construction proves this invariant and every valid runtime has
    /// a brain participant, so the lookup cannot fail after validation.
    #[must_use]
    #[expect(
        clippy::expect_used,
        reason = "Runtime is constructible only after validation proves at least one selected participant and its artifact"
    )]
    pub fn framework_line(&self) -> CompatibilityLine {
        self.participants
            .first()
            .and_then(|participant| self.artifacts.get(&participant.artifact))
            .map(|artifact| artifact.contract().framework.compatibility_line())
            .expect("validated runtime has a selected participant artifact")
    }

    fn validate(&self) -> Result<(), DocumentError> {
        if self.participants.len() > crate::MAX_RUNTIME_PARTICIPANTS {
            return Err(DocumentError::TooManyParticipants {
                count: self.participants.len(),
            });
        }
        let mut ids = BTreeSet::new();
        let mut artifact_paths = BTreeSet::new();
        let mut validators = BTreeMap::new();
        for (id, artifact) in &self.artifacts {
            artifact.validate(id)?;
            if artifact.contract().kind == phoxal_runtime_contract::metadata::ParticipantKind::Brain
            {
                if id.as_str() != "brain" {
                    return Err(DocumentError::BrainArtifactId { actual: id.clone() });
                }
                if artifact.path().as_str() != "bin/brain" {
                    return Err(DocumentError::BrainArtifactPath {
                        actual: artifact.path().clone(),
                    });
                }
            }
            if !artifact_paths.insert(artifact.path.clone()) {
                return Err(DocumentError::DuplicateBinary {
                    path: artifact.path.clone(),
                });
            }
            let validator =
                jsonschema::validator_for(&artifact.contract.config_schema).map_err(|error| {
                    DocumentError::InvalidConfigSchema {
                        artifact: id.clone(),
                        error: error.to_string(),
                    }
                })?;
            validate_requirement(artifact.contract(), id, &self.robot)?;
            validators.insert(id, validator);
        }
        let mut referenced_artifacts = BTreeSet::new();
        let mut brain = None;
        let mut simulator_count = 0_u8;
        let mut framework: Option<FrameworkVersion> = None;
        for participant in &self.participants {
            let artifact = self.artifacts.get(&participant.artifact).ok_or_else(|| {
                DocumentError::UnknownArtifact {
                    participant: participant.id.clone(),
                    artifact: participant.artifact.clone(),
                }
            })?;
            let validator = validators.get(&participant.artifact).ok_or_else(|| {
                DocumentError::UnknownArtifact {
                    participant: participant.id.clone(),
                    artifact: participant.artifact.clone(),
                }
            })?;
            participant.validate(&self.robot, artifact, validator)?;
            // One execution runs one compatibility line. Artifacts may have
            // been built from different trains on that line, because trains on
            // one line speak the same contracts; a bundle spanning two lines
            // has no valid launch. The first selected artifact's train is kept
            // as the reported one so the diagnostic names a stable side.
            let artifact_framework = artifact.contract().framework;
            let expected = *framework.get_or_insert(artifact_framework);
            if !expected.is_compatible_with(artifact_framework) {
                return Err(DocumentError::MixedFrameworkLine {
                    artifact: participant.artifact.clone(),
                    expected,
                    actual: artifact_framework,
                });
            }
            if artifact.contract().kind == phoxal_runtime_contract::metadata::ParticipantKind::Brain
            {
                if participant.id.as_str() != "brain" {
                    return Err(DocumentError::BrainIdMismatch {
                        actual: participant.id.clone(),
                    });
                }
                if brain.replace(participant.id.clone()).is_some() {
                    return Err(DocumentError::DuplicateBrain);
                }
            }
            if artifact.contract().kind
                == phoxal_runtime_contract::metadata::ParticipantKind::Simulator
            {
                simulator_count = simulator_count.saturating_add(1);
            }
            referenced_artifacts.insert(participant.artifact.clone());
            if !ids.insert(participant.id.clone()) {
                return Err(DocumentError::DuplicateParticipant {
                    id: participant.id.clone(),
                });
            }
        }
        if brain.is_none() {
            return Err(DocumentError::MissingBrain);
        }
        if self.robot.clock() == phoxal_model::Clock::Simulated {
            match simulator_count {
                0 => return Err(DocumentError::MissingSimulator),
                1 => {}
                _ => return Err(DocumentError::DuplicateSimulator),
            }
        }
        if let Some(artifact) = self
            .artifacts
            .keys()
            .find(|id| !referenced_artifacts.contains(*id))
        {
            return Err(DocumentError::UnusedArtifact {
                artifact: artifact.clone(),
            });
        }
        self.assets.validate()?;
        if let Some(router) = &self.router {
            router.validate(&self.assets)?;
        }
        Ok(())
    }
}

/// Validate one artifact's static topology requirement against the canonical
/// robot once, independently of how many runtime instances select it.
pub(crate) fn validate_requirement(
    contract: &ParticipantContract,
    artifact: &ParticipantArtifactId,
    robot: &Robot,
) -> Result<(), DocumentError> {
    let Some(requirement) = contract.requirement else {
        return Ok(());
    };
    match requirement {
        ParticipantRequirement::DifferentialDriveVelocity => {
            let phoxal_model::robot::KinematicConfig::Differential {
                left_actuators,
                right_actuators,
                ..
            } = robot.motion().kinematic()
            else {
                return Err(DocumentError::RequirementKinematicsMismatch {
                    artifact: artifact.clone(),
                    requirement,
                    actual: robot.motion().kinematic().kind(),
                });
            };
            validate_drive_side(artifact, "left_actuators", left_actuators, robot)?;
            validate_drive_side(artifact, "right_actuators", right_actuators, robot)
        }
    }
}

fn validate_drive_side(
    artifact: &ParticipantArtifactId,
    side: &'static str,
    actuators: &[CapabilityRef],
    robot: &Robot,
) -> Result<(), DocumentError> {
    if actuators.is_empty() {
        return Err(DocumentError::RequirementActuatorListEmpty {
            artifact: artifact.clone(),
            side,
        });
    }
    for reference in actuators {
        let (motor, _) = robot.require_motor(reference).map_err(|error| {
            DocumentError::RequirementActuatorInvalid {
                artifact: artifact.clone(),
                actuator: reference.clone(),
                error: error.to_string(),
            }
        })?;
        if motor.command != MotorCommand::Velocity {
            return Err(DocumentError::RequirementMotorModeMismatch {
                artifact: artifact.clone(),
                actuator: reference.clone(),
                expected: MotorCommand::Velocity,
                actual: motor.command,
            });
        }
    }
    Ok(())
}

/// A normalized reference to optional router configuration.
#[derive(phoxal_macros::DescribeWire, Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RuntimeRouterConfig {
    /// The config is an indexed asset, never an arbitrary filesystem path.
    path: BundlePath,
}

impl RuntimeRouterConfig {
    /// Construct router configuration pointing at one bundle asset.
    #[must_use]
    pub const fn new(path: BundlePath) -> Self {
        Self { path }
    }

    /// The indexed asset path containing the router configuration.
    #[must_use]
    pub const fn path(&self) -> &BundlePath {
        &self.path
    }

    fn validate(&self, assets: &AssetIndex) -> Result<(), DocumentError> {
        if !self.path.starts_with_directory(ASSETS_DIR) {
            return Err(DocumentError::RouterOutsideAssets {
                path: self.path.clone(),
            });
        }
        if !assets.entries.iter().any(|entry| entry.path == self.path) {
            return Err(DocumentError::RouterMissingAsset {
                path: self.path.clone(),
            });
        }
        Ok(())
    }
}

/// Decode the one schema-tagged document retained in an installed bundle.
pub(crate) fn decode(bytes: &[u8]) -> Result<RuntimeDocument, BundleError> {
    serde_json::from_slice(bytes).map_err(BundleError::from)
}