Skip to main content

sim_logic/application/runtime/
reports.rs

1//! Public frame inputs, outcomes, lifecycle records, and error contracts.
2
3use std::{error::Error, fmt, time::Duration};
4
5use sim_engine::LogicalViewport;
6
7use crate::{
8    ExtractionError,
9    commands::CommandBatchError,
10    component::ComponentApprovalError,
11    identity::{WorldFactoryId, WorldGeneration},
12    input::{InputCollectionError, InputEvent},
13    system::{Stage, SystemRunFailure, SystemSetupError},
14    time::{DroppedFixedTime, FixedFramePlan, TimeAdvanceError},
15    transition::{ConvergentTransitionWarning, TransitionRejection},
16    world::WorldBuildError,
17};
18
19/// Immutable inputs for one shared core application frame.
20pub struct FrameRequest<'a> {
21    elapsed: Duration,
22    events: &'a [InputEvent],
23    viewport: LogicalViewport,
24}
25
26impl<'a> FrameRequest<'a> {
27    /// Creates one frame request from wall time, physical events, and a
28    /// validated logical viewport.
29    pub const fn new(
30        elapsed: Duration,
31        events: &'a [InputEvent],
32        viewport: LogicalViewport,
33    ) -> Self {
34        Self {
35            elapsed,
36            events,
37            viewport,
38        }
39    }
40
41    /// Returns the unscaled wall delta supplied to the frame.
42    pub const fn elapsed(&self) -> Duration {
43        self.elapsed
44    }
45
46    /// Returns the physical events supplied by the caller.
47    ///
48    /// The runner validates the complete slice against its frozen input limit
49    /// before accepting the frame or changing logical input state.
50    pub const fn events(&self) -> &'a [InputEvent] {
51        self.events
52    }
53
54    /// Returns the validated logical viewport shared with a desktop adapter.
55    pub const fn viewport(&self) -> LogicalViewport {
56        self.viewport
57    }
58}
59
60/// Failure before any World System or canonical time/input state was changed.
61#[derive(Debug)]
62pub enum BeginFrameRejection {
63    /// The application-frame identity counter is exhausted.
64    FrameIdentityExhausted,
65    /// Physical input collection rejected the complete event batch.
66    Input(InputCollectionError),
67    /// Wall-time scaling or accumulation was not representable.
68    Time(TimeAdvanceError),
69}
70
71impl fmt::Display for BeginFrameRejection {
72    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
73        match self {
74            Self::FrameIdentityExhausted => {
75                formatter.write_str("application frame identity space is exhausted")
76            }
77            Self::Input(error) => write!(formatter, "frame input was rejected: {error}"),
78            Self::Time(error) => write!(formatter, "frame time was rejected: {error}"),
79        }
80    }
81}
82
83impl Error for BeginFrameRejection {
84    fn source(&self) -> Option<&(dyn Error + 'static)> {
85        match self {
86            Self::Input(error) => Some(error),
87            Self::Time(error) => Some(error),
88            Self::FrameIdentityExhausted => None,
89        }
90    }
91}
92
93/// Failure while preparing an isolated World candidate.
94#[derive(Debug)]
95pub enum CandidateFailure {
96    /// The requested handle is not registered by this application.
97    InvalidFactory,
98    /// The next never-reused World generation cannot be issued.
99    GenerationExhausted,
100    /// The frozen component set could not be installed in the candidate.
101    Components(ComponentApprovalError),
102    /// The registered factory rejected candidate construction.
103    Factory(WorldBuildError),
104    /// A managed System used a forbidden Bevy access path.
105    SystemSetup(SystemSetupError),
106    /// Candidate Startup could not run.
107    StartupSystem(SystemRunFailure),
108    /// Candidate Startup's structural batch was rejected.
109    StartupCommands(CommandBatchError),
110    /// Candidate Startup requested another World before installation.
111    StartupTransition,
112    /// The resulting candidate was not a valid renderable World.
113    Extraction(ExtractionError),
114    /// A required private runtime Resource disappeared during preparation.
115    RuntimeInvariant,
116}
117
118impl fmt::Display for CandidateFailure {
119    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
120        match self {
121            Self::InvalidFactory => formatter.write_str("World factory handle is not registered"),
122            Self::GenerationExhausted => {
123                formatter.write_str("World generation identity space is exhausted")
124            }
125            Self::Components(error) => write!(formatter, "component registry failed: {error}"),
126            Self::Factory(error) => write!(formatter, "World factory failed: {error}"),
127            Self::SystemSetup(error) => write!(formatter, "System setup failed: {error}"),
128            Self::StartupSystem(error) => write!(formatter, "Startup failed: {error}"),
129            Self::StartupCommands(error) => write!(formatter, "Startup Commands failed: {error}"),
130            Self::StartupTransition => {
131                formatter.write_str("Startup cannot request World replacement in this slice")
132            }
133            Self::Extraction(error) => write!(formatter, "candidate extraction failed: {error}"),
134            Self::RuntimeInvariant => {
135                formatter.write_str("candidate is missing a private runtime Resource")
136            }
137        }
138    }
139}
140
141impl Error for CandidateFailure {
142    fn source(&self) -> Option<&(dyn Error + 'static)> {
143        match self {
144            Self::Components(error) => Some(error),
145            Self::Factory(error) => Some(error),
146            Self::SystemSetup(error) => Some(error),
147            Self::StartupSystem(error) => Some(error),
148            Self::StartupCommands(error) => Some(error),
149            Self::Extraction(error) => Some(error),
150            Self::InvalidFactory
151            | Self::GenerationExhausted
152            | Self::StartupTransition
153            | Self::RuntimeInvariant => None,
154        }
155    }
156}
157
158/// Failure to freeze an Application into a runnable headless core.
159#[derive(Debug)]
160pub enum RunnerBuildError {
161    /// The initial factory handle is foreign, stale, or missing.
162    InvalidInitialFactory,
163    /// Input configuration could not initialize.
164    Input(InputCollectionError),
165    /// The bounded lifecycle trace could not reserve its frozen capacity.
166    LifecycleTraceAllocation {
167        /// Requested record capacity.
168        limit: usize,
169    },
170    /// A FixedUpdate or FrameUpdate System requests a type that was not
171    /// registered on the Application builder.
172    MissingApplicationResource {
173        /// Rust type name used only for diagnostics.
174        resource: &'static str,
175        /// Stage containing the first registered requirement.
176        stage: Stage,
177        /// Rust System type name used only for diagnostics.
178        system: &'static str,
179    },
180    /// Private Application Resource staging failed an internal invariant.
181    ApplicationResourceInvariant,
182    /// Initial World preparation failed before an active World existed.
183    InitialWorld(CandidateFailure),
184}
185
186impl fmt::Display for RunnerBuildError {
187    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
188        match self {
189            Self::InvalidInitialFactory => {
190                formatter.write_str("initial World factory is not registered by this application")
191            }
192            Self::Input(error) => write!(formatter, "input initialization failed: {error}"),
193            Self::LifecycleTraceAllocation { limit } => write!(
194                formatter,
195                "failed to reserve lifecycle trace capacity of {limit} records"
196            ),
197            Self::MissingApplicationResource {
198                resource,
199                stage,
200                system,
201            } => write!(
202                formatter,
203                "{stage:?} System `{system}` requests unregistered Application Resource `{resource}`"
204            ),
205            Self::ApplicationResourceInvariant => formatter
206                .write_str("Application Resource staging failed a private runtime invariant"),
207            Self::InitialWorld(error) => write!(formatter, "initial World failed: {error}"),
208        }
209    }
210}
211
212impl Error for RunnerBuildError {
213    fn source(&self) -> Option<&(dyn Error + 'static)> {
214        match self {
215            Self::Input(error) => Some(error),
216            Self::InitialWorld(error) => Some(error),
217            Self::InvalidInitialFactory
218            | Self::LifecycleTraceAllocation { .. }
219            | Self::MissingApplicationResource { .. }
220            | Self::ApplicationResourceInvariant => None,
221        }
222    }
223}
224
225/// An observable World lifecycle boundary.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum LifecycleEvent {
228    /// A validated candidate became the active World.
229    WorldEnter,
230    /// An active World was logically retired before destruction.
231    WorldExit,
232}
233
234/// One application-owned lifecycle trace record.
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub struct LifecycleRecord {
237    pub(super) event: LifecycleEvent,
238    pub(super) generation: WorldGeneration,
239    pub(super) factory: WorldFactoryId,
240}
241
242impl LifecycleRecord {
243    /// Returns the recorded lifecycle boundary.
244    pub const fn event(self) -> LifecycleEvent {
245        self.event
246    }
247
248    /// Returns the World generation involved in the boundary.
249    pub const fn generation(self) -> WorldGeneration {
250        self.generation
251    }
252
253    /// Returns the factory that constructed the generation.
254    pub const fn factory(self) -> WorldFactoryId {
255        self.factory
256    }
257}
258
259/// Invalid opaque data in a transition request batch.
260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub enum TransitionRequestFailure {
262    /// The target factory is foreign, stale, or absent.
263    InvalidFactory,
264    /// The intent token is foreign, stale, already consumed, or not live in
265    /// this delivery stage.
266    InvalidIntent,
267}
268
269/// Transition result for one completed application frame.
270#[derive(Debug)]
271pub enum FrameTransition {
272    /// No replacement was processed. This also applies when application exit
273    /// suppressed replacement requests in the same committed command batch.
274    None,
275    /// Valid requests failed deterministic arbitration.
276    Rejected(TransitionRejection),
277    /// A request contained a stale or foreign opaque handle.
278    Invalid(TransitionRequestFailure),
279    /// The selected target failed while still isolated; the old World remains
280    /// active and the reserved generation is burned.
281    PreparationFailed {
282        /// Selected target factory.
283        target: WorldFactoryId,
284        /// Exact preparation failure.
285        error: CandidateFailure,
286    },
287    /// A validated candidate replaced the old World irreversibly.
288    Committed {
289        /// Retired generation.
290        old: WorldGeneration,
291        /// Installed generation.
292        new: WorldGeneration,
293        /// Factory used to construct `new`.
294        target: WorldFactoryId,
295        /// Diagnostic when independent intents converged on `target`.
296        warning: Option<ConvergentTransitionWarning>,
297    },
298}
299
300/// Failure after at least part of an application frame may have changed the
301/// active World or consumed fixed time.
302#[derive(Debug)]
303pub enum FrameFailure {
304    /// A FixedUpdate or FrameUpdate System could not run.
305    System {
306        /// Stage that stopped.
307        stage: Stage,
308        /// Exact managed System failure.
309        error: SystemRunFailure,
310    },
311    /// A whole structural command batch was rejected.
312    Commands {
313        /// Stage whose batch was discarded.
314        stage: Stage,
315        /// Exact batch failure.
316        error: CommandBatchError,
317    },
318    /// Fixed-time cleanup could not be represented.
319    Time(TimeAdvanceError),
320    /// CPU extraction rejected the new snapshot atomically.
321    Extraction(ExtractionError),
322    /// A required private runtime Resource disappeared.
323    RuntimeInvariant,
324}
325
326impl fmt::Display for FrameFailure {
327    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
328        match self {
329            Self::System { stage, error } => {
330                write!(formatter, "{stage:?} System failed: {error}")
331            }
332            Self::Commands { stage, error } => {
333                write!(formatter, "{stage:?} Commands failed: {error}")
334            }
335            Self::Time(error) => write!(formatter, "fixed-time cleanup failed: {error}"),
336            Self::Extraction(error) => write!(formatter, "render extraction failed: {error}"),
337            Self::RuntimeInvariant => {
338                formatter.write_str("a private frame runtime invariant was violated")
339            }
340        }
341    }
342}
343
344impl Error for FrameFailure {
345    fn source(&self) -> Option<&(dyn Error + 'static)> {
346        match self {
347            Self::System { error, .. } => Some(error),
348            Self::Commands { error, .. } => Some(error),
349            Self::Time(error) => Some(error),
350            Self::Extraction(error) => Some(error),
351            Self::RuntimeInvariant => None,
352        }
353    }
354}
355
356/// Diagnostics for a completed application frame.
357#[derive(Debug)]
358pub struct LogicFrameReport {
359    pub(super) frame_index: u64,
360    pub(super) timing: FixedFramePlan,
361    pub(super) fixed_ticks_attempted: u32,
362    pub(super) spawned: usize,
363    pub(super) despawned: usize,
364    pub(super) exit_requested: bool,
365    pub(super) transitions_suppressed_by_exit: usize,
366    pub(super) dropped_for_transition: Option<DroppedFixedTime>,
367    pub(super) transition: FrameTransition,
368    pub(super) extracted_generation: Option<WorldGeneration>,
369    pub(super) failure: Option<FrameFailure>,
370}
371
372impl LogicFrameReport {
373    /// Returns the accepted application-frame index.
374    pub const fn frame_index(&self) -> u64 {
375        self.frame_index
376    }
377
378    /// Returns bounded fixed-work planning and catch-up drops.
379    pub const fn timing(&self) -> FixedFramePlan {
380        self.timing
381    }
382
383    /// Returns the number of fixed ticks that began, including a failed tick.
384    pub const fn fixed_ticks_attempted(&self) -> u32 {
385        self.fixed_ticks_attempted
386    }
387
388    /// Returns managed entities spawned by committed stage batches.
389    pub const fn spawned(&self) -> usize {
390        self.spawned
391    }
392
393    /// Returns managed entities despawned by committed stage batches.
394    pub const fn despawned(&self) -> usize {
395        self.despawned
396    }
397
398    /// Returns whether a committed stage batch requested application exit.
399    ///
400    /// Desktop honors this by ending its event loop without presenting another
401    /// frame. A headless host decides when to stop its own driving loop.
402    pub const fn exit_requested(&self) -> bool {
403        self.exit_requested
404    }
405
406    /// Returns replacement requests ignored because exit took precedence.
407    pub const fn transitions_suppressed_by_exit(&self) -> usize {
408        self.transitions_suppressed_by_exit
409    }
410
411    /// Returns whole ticks discarded because a stopped transition was rejected.
412    pub const fn dropped_for_transition(&self) -> Option<DroppedFixedTime> {
413        self.dropped_for_transition
414    }
415
416    /// Returns the frame's transition result.
417    pub const fn transition(&self) -> &FrameTransition {
418        &self.transition
419    }
420
421    /// Returns the generation published by successful CPU extraction.
422    pub const fn extracted_generation(&self) -> Option<WorldGeneration> {
423        self.extracted_generation
424    }
425
426    /// Returns a post-begin failure, if the frame stopped early or extraction
427    /// was rejected.
428    pub const fn failure(&self) -> Option<&FrameFailure> {
429        self.failure.as_ref()
430    }
431}
432
433/// Result of one call to [`HeadlessRunner::advance_frame`](crate::headless::HeadlessRunner::advance_frame).
434#[derive(Debug)]
435#[expect(
436    clippy::large_enum_variant,
437    reason = "keeping the hot-path frame report inline avoids one allocation per frame"
438)]
439pub enum FrameOutcome {
440    /// BeginFrame rejected all inputs before canonical runtime state changed.
441    Rejected(BeginFrameRejection),
442    /// BeginFrame succeeded; inspect the report because later failures do not
443    /// imply rollback.
444    Advanced(LogicFrameReport),
445}