bevy_agent_runner 0.0.2

Runner API that owns and steps controllable Bevy agent simulation apps.
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
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
//! App ownership, initialization, and live control operations.

use super::*;

#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema)]
/// Episode initialization policy. Defaults to seed zero, hybrid observations,
/// and an initial snapshot suitable for replay reconstruction.
pub struct ResetOptions {
    /// Optional replacement for the simulation's deterministic RNG seed.
    pub seed: Option<u64>,
    /// A mode supported by the game's observation catalog.
    pub observation_mode: ObservationMode,
    /// Whether reset retains a snapshot of the initial world.
    pub create_initial_snapshot: bool,
}

impl Default for ResetOptions {
    fn default() -> Self {
        Self {
            seed: Some(0),
            observation_mode: ObservationMode::Hybrid,
            create_initial_snapshot: true,
        }
    }
}

pub fn set_episode_done(world: &mut World, reason: impl Into<String>) {
    let mut episode = world.resource_mut::<EpisodeState>();
    episode.done = true;
    episode.reason = Some(reason.into());
}

pub fn clear_episode(world: &mut World) {
    *world.resource_mut::<EpisodeState>() = EpisodeState::default();
    *world.resource_mut::<RewardState>() = RewardState::default();
    let mut input = world.resource_mut::<CurrentInputFrame>();
    input.actions.clear();
    input.sources.clear();
    world.resource_mut::<AgentControlState>().last_action_count = 0;
}

impl AgentApp {
    /// Checks integration before lending a world to an owning runner.
    /// This performs no startup, reset, extraction, or world mutation.
    pub fn validate_world(world: &World) -> Result<()> {
        validate_runner_integration(world)
    }

    /// Builds an app and validates its integration without starting gameplay.
    pub fn new(build_app: impl FnOnce() -> App) -> Result<Self> {
        Self::from_app(build_app())
    }

    /// Finishes plugin setup and validates an existing, not-yet-running app.
    pub fn from_app(mut app: App) -> Result<Self> {
        app.finish();
        app.cleanup();
        validate_runner_integration(app.world())?;
        Ok(Self {
            app,
            started: false,
            reset_once: false,
        })
    }

    /// Wraps an app whose plugins have already been finished by an external
    /// runner. This is primarily used by main-thread integrations that lend
    /// their world to the synchronous control API for one request.
    pub fn from_running_app(app: App, reset_once: bool) -> Result<Self> {
        validate_runner_integration(app.world())?;
        Ok(Self {
            app,
            started: true,
            reset_once,
        })
    }

    pub fn into_app(self) -> App {
        self.app
    }

    #[must_use]
    pub const fn has_reset(&self) -> bool {
        self.reset_once
    }

    pub fn app(&self) -> &App {
        &self.app
    }

    pub fn app_mut(&mut self) -> &mut App {
        &mut self.app
    }

    pub fn world(&self) -> &World {
        self.app.world()
    }

    pub fn world_mut(&mut self) -> &mut World {
        self.app.world_mut()
    }

    pub fn step_frame(&mut self) {
        self.ensure_started();
        self.app.update();
    }

    pub fn current_tick(&self) -> u64 {
        self.app.world().resource::<SimClock>().tick
    }

    /// Schedules validated future input without starting or resetting the app.
    /// Rejected actions, sources, and ticks leave the queue unchanged.
    pub fn enqueue_action_at(
        &mut self,
        tick: u64,
        source: ActionSource,
        action: AgentAction,
    ) -> Result<()> {
        self.ensure_no_fault()?;
        schedule_action(self.app.world_mut(), tick, source, action)?;
        Ok(())
    }

    /// Advances with `Noop` actions, stopping at terminal state and returning
    /// the last response. Zero ticks are rejected.
    pub fn fast_forward(&mut self, ticks: u64) -> Result<StepResponse<Observation>> {
        if ticks == 0 {
            return Err(anyhow!("fast_forward called with zero ticks"));
        }
        self.ensure_no_fault()?;
        self.ensure_started();
        self.ensure_reset()?;
        let start_tick = self.current_tick();
        let mut last = None;
        for completed in 0..ticks {
            let response = self.step(AgentAction::Noop).map_err(|error| {
                self.batch_failure("fast_forward", start_tick, completed as usize, error)
            })?;
            let done = response.done || response.truncated;
            last = Some(response);
            if done {
                break;
            }
        }
        last.ok_or_else(|| anyhow!("fast_forward called with zero ticks"))
    }

    /// Steps with a request-specific observation mode, collecting the tick response once.
    /// The persistent mode is restored even when stepping returns an error.
    pub fn step_with_observation_mode(
        &mut self,
        action: AgentAction,
        mode: ObservationMode,
    ) -> Result<StepResponse<Observation>> {
        self.validate_actions(std::slice::from_ref(&action))?;
        self.validate_external_source(&ActionSource::Agent)?;
        self.validate_observation_mode(&mode)?;
        self.ensure_no_fault()?;
        self.ensure_started();
        self.ensure_reset()?;
        let previous_mode = std::mem::replace(
            &mut self
                .app
                .world_mut()
                .resource_mut::<ObservationConfig>()
                .mode,
            mode,
        );
        let response = self.step(action);
        self.app
            .world_mut()
            .resource_mut::<ObservationConfig>()
            .mode = previous_mode;
        response
    }

    /// Fault gate: history corruption that failed rollback leaves a
    /// [`FaultState`] resource; all navigation/stepping is rejected until an
    /// explicit `reset` clears it (reset removes the resource).
    pub(super) fn ensure_no_fault(&self) -> Result<()> {
        if let Some(fault) = self.app.world().get_resource::<FaultState>() {
            return Err(anyhow!(
                "world is faulted ({}); reset before stepping",
                fault.message
            ));
        }
        Ok(())
    }

    pub fn reset_with_response(
        &mut self,
        options: ResetOptions,
    ) -> Result<ResetResponse<Observation>> {
        let observation = <Self as AgentEnvironment>::reset(self, options)?;
        let response = self.last_response()?;
        Ok(ResetResponse {
            tick: response.tick,
            observation,
            checksum: response.checksum,
            snapshot_id: response.info.snapshot_created,
            timeline_id: response.info.timeline_id,
            branch_id: response.info.branch_id,
        })
    }

    pub fn step_many_with_response(
        &mut self,
        actions: Vec<AgentAction>,
        include_responses: bool,
    ) -> Result<StepManyResponse<Observation>> {
        // Controller boundary: validate the whole batch BEFORE any
        // truncate/enqueue/advance so an invalid action rejects the batch
        // without partial stepping.
        self.validate_actions(&actions)?;
        if !actions.is_empty() {
            self.validate_external_source(&ActionSource::Agent)?;
            self.ensure_no_fault()?;
            self.ensure_started();
            self.ensure_reset()?;
        }
        let start_tick = self.current_tick();
        // Incremental aggregation: retain only requested observations
        // (last always, all only when `include_responses`), summing rewards
        // as we go instead of retaining then summing.
        let mut retained: Vec<StepResponse<Observation>> = Vec::new();
        if include_responses {
            retained.reserve(actions.len());
        }
        let mut steps = 0usize;
        let mut reward = 0.0f32;
        let mut observation: Option<Observation> = None;
        let mut done = false;
        let mut truncated = false;
        let mut info: Option<bevy_agent_core::StepInfo> = None;
        let mut checksum: Option<bevy_agent_core::EnvironmentChecksum> = None;
        let mut end_tick = start_tick;
        for action in actions {
            let response = self
                .step(action)
                .map_err(|error| self.batch_failure("step_many", start_tick, steps, error))?;
            let terminal = response.done || response.truncated;
            end_tick = response.tick;
            steps += 1;
            reward += response.reward;
            if !reward.is_finite() {
                return Err(self.batch_failure(
                    "step_many",
                    start_tick,
                    steps,
                    anyhow!("batch reward sum exceeds the finite float range"),
                ));
            }
            done = response.done;
            truncated = response.truncated;
            observation = Some(response.observation.clone());
            info = Some(response.info.clone());
            checksum = response.checksum.clone();
            if include_responses {
                retained.push(response);
            }
            if terminal {
                break;
            }
        }
        Ok(StepManyResponse {
            start_tick,
            end_tick,
            steps,
            observation,
            reward,
            done,
            truncated,
            info,
            checksum,
            responses: retained,
        })
    }

    /// Validates a whole batch against the action catalog, rejecting the batch
    /// on the first invalid action.
    pub fn validate_actions(&self, actions: &[AgentAction]) -> Result<()> {
        let catalog = self
            .app
            .world()
            .get_resource::<AgentActionCatalog>()
            .ok_or_else(|| anyhow!("missing AgentActionCatalog"))?;
        for action in actions {
            validate_action_against_catalog(catalog, action)
                .map_err(|error| anyhow!("InvalidAction: {error}"))?;
        }
        Ok(())
    }

    pub(super) fn ensure_started(&mut self) {
        if self.started {
            return;
        }
        self.app.update();
        self.started = true;
    }

    pub(super) fn ensure_reset(&mut self) -> Result<()> {
        if !self.reset_once {
            let mode = self
                .app
                .world()
                .resource::<ObservationConfig>()
                .mode
                .clone();
            let _ = self.reset(ResetOptions {
                observation_mode: mode,
                ..ResetOptions::default()
            })?;
        }
        Ok(())
    }

    pub(super) fn run_one_agent_tick(&mut self) -> Result<()> {
        run_agent_tick(self.app.world_mut())?;
        Ok(())
    }

    pub(super) fn last_response(&self) -> Result<StepResponse<Observation>> {
        self.app
            .world()
            .resource::<LastStepResponse>()
            .0
            .clone()
            .ok_or_else(|| anyhow!("agent tick produced no StepResponse"))
    }

    pub(super) fn step_with_source(
        &mut self,
        action: AgentAction,
        source: ActionSource,
    ) -> Result<StepResponse<Observation>> {
        self.validate_actions(std::slice::from_ref(&action))?;
        self.validate_external_source(&source)?;
        self.ensure_no_fault()?;
        self.ensure_started();
        self.ensure_reset()?;
        self.app
            .world()
            .resource::<EpisodeState>()
            .ensure_not_terminal()?;
        self.reject_paused_or_inspect_only()?;
        // Post-restore stepping policy: stepping after a `restore_tick` into
        // recorded future ticks on the same branch explicitly diverges, so the
        // stale future beyond the current tick is truncated first. Forking via
        // `branch` is the non-destructive alternative; truncation here is the
        // documented explicit-diverge behavior.
        self.app.world().resource::<SimClock>().validate()?;
        let next_tick = self.current_tick() + 1;
        validate_clock_tick(next_tick)?;
        bevy_agent_core::validate_next_tick(self.app.world())?;
        if let Some(recorder) = self.app.world().get_resource::<ReplayRecorder>() {
            recorder
                .validate_truncation(
                    self.app.world().resource::<Timeline>(),
                    self.app.world().resource::<AgentControlState>().branch_id,
                    self.current_tick(),
                )
                .map_err(anyhow::Error::msg)?;
        }
        let tick_before = self.current_tick();
        let result = (|| {
            self.enforce_diverge_truncation()?;
            self.enqueue_action_at(next_tick, source, action)?;
            self.run_one_agent_tick()?;
            // Caller-side checkpoint bookkeeping (the snapshot crate owns
            // creation/pruning): mirror any new automatic checkpoints into the
            // replay log, honor `checkpoint_on_terminal`, and make sure the
            // response reports a snapshot created on this same tick.
            self.sync_auto_checkpoints()?;
            self.maybe_terminal_checkpoint()?;
            self.patch_snapshot_created();
            self.last_response()
        })();
        result.map_err(|error| self.mutation_failed("step", tick_before, error))
    }

    fn validate_external_source(&self, source: &ActionSource) -> Result<()> {
        self.reject_paused_or_inspect_only()?;
        if !self
            .app
            .world()
            .resource::<AgentControlState>()
            .mode
            .accepts_source(source)
        {
            return Err(anyhow!(
                "action source {source:?} is rejected by the current control mode"
            ));
        }
        Ok(())
    }

    /// External stepping (`step`/`step_many`/`fast_forward`) is rejected while
    /// the control mode is behavioral-only. Internal reconstruction
    /// (`restore`/`restore_tick`/`branch`) bypasses `step_with_source` and may
    /// still rebuild state. Returns before any action is enqueued so the tick is
    /// left unchanged.
    pub(super) fn reject_paused_or_inspect_only(&self) -> Result<()> {
        let mode = self
            .app
            .world()
            .resource::<AgentControlState>()
            .mode
            .clone();
        match mode {
            ControlMode::Paused => Err(anyhow!(
                "cannot step while control mode is Paused; resume before stepping"
            )),
            ControlMode::InspectOnly => Err(anyhow!(
                "cannot step while control mode is InspectOnly; switch modes before stepping"
            )),
            _ => Ok(()),
        }
    }

    pub(super) fn step_many_impl(
        &mut self,
        actions: Vec<AgentAction>,
    ) -> Result<Vec<StepResponse<Observation>>> {
        self.validate_actions(&actions)?;
        if !actions.is_empty() {
            self.validate_external_source(&ActionSource::Agent)?;
        }
        let mut responses = Vec::new();
        for action in actions {
            let response = self.step(action)?;
            let done = response.done || response.truncated;
            responses.push(response);
            if done {
                break;
            }
        }
        Ok(responses)
    }

    pub(super) fn validate_observation_mode(&self, mode: &ObservationMode) -> Result<()> {
        self.app
            .world()
            .resource::<bevy_agent_core::AgentObservationCatalog>()
            .validate_mode(mode)?;
        Ok(())
    }

    pub(super) fn observe_impl(&mut self, mode: ObservationMode) -> Result<Observation> {
        self.ensure_no_fault()?;
        self.validate_observation_mode(&mode)?;
        self.ensure_started();
        self.ensure_reset()?;
        collect_observation_with_mode(self.app.world_mut(), mode)?;
        Ok(self.last_response()?.observation)
    }
}

/// Validate optional history plugins together with the shared core contract.
fn validate_runner_integration(world: &World) -> Result<()> {
    validate_integration(world)?;
    if world.contains_resource::<ReplayRecorder>() != world.contains_resource::<Timeline>() {
        return Err(anyhow!(
            "ReplayRecorder and Timeline must be installed together"
        ));
    }
    if let Some(timeline) = world.get_resource::<Timeline>() {
        timeline
            .ancestors_bounded(timeline.current_branch())
            .map_err(anyhow::Error::msg)?;
        let control = world.resource::<AgentControlState>();
        if control.timeline_id != timeline.timeline_id()
            || control.branch_id != timeline.current_branch()
        {
            return Err(anyhow!("control identity disagrees with active timeline"));
        }
        let log = world.resource::<ReplayRecorder>().log();
        // Live owners validate complete history on admission. Construction
        // checks readiness without rescanning accumulated records; lending a
        // running world must remain independent of its recording length.
        if log.timeline_topology.is_empty()
            || log.active_branch.is_none()
            || log.manifest.schema_version != bevy_agent_replay::REPLAY_SCHEMA_VERSION
        {
            return Err(anyhow!("replay owner is not initialized"));
        }
    }
    if world.contains_resource::<SnapshotStore>()
        && (!world.contains_resource::<bevy_agent_snapshot::SnapshotRegistry>()
            || !world.contains_resource::<SnapshotPolicy>())
    {
        return Err(anyhow!(
            "snapshot support requires SnapshotRegistry and SnapshotPolicy"
        ));
    }
    if world
        .get_resource::<SnapshotPolicy>()
        .is_some_and(|policy| policy.max_snapshot_bytes == 0)
    {
        return Err(anyhow!("snapshot byte budget must be positive"));
    }
    Ok(())
}