Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(ai): keep plan_route's signature stable when tracing is on
The replay harness calls plan_route with eight arguments. A feature-only
extra parameter made that test fail to compile when decision-trace was
unified on, so the sink now lives in thread-local storage. perception_world
stays 6e52e721 with the feature off and on.

Co-authored-by: Andrew Brown <lazyxeon@users.noreply.github.com>
  • Loading branch information
cursoragent and lazyxeon committed Oct 15, 2026
commit 6ef72e75d50e82c28087f37dd19f3b300d6eabd5
4 changes: 0 additions & 4 deletions astraweave-ai/benches/htn_budget.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,6 @@ fn bench_htn_expansions(c: &mut Criterion) {
1,
&mut plan,
&mut budget,
#[cfg(feature = "decision-trace")]
&mut astraweave_ai::decision_trace::NullSink,
#[cfg(feature = "decision-trace")]
1u64,
);
if budget == before {
break;
Expand Down
76 changes: 9 additions & 67 deletions astraweave-ai/src/decision_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,63 +455,6 @@ fn outcome_byte(code: FailCode) -> u8 {
}
}

pub trait DecisionSink {
fn record(&mut self, record: &DecisionRecord);
fn amend_band(&mut self, entity_id: u64, tick: u64, band: u8) {
let _ = (entity_id, tick, band);
}
}

/// Sink that drops the record. The planner result does not read it.
pub struct NullSink;

impl DecisionSink for NullSink {
#[inline(always)]
fn record(&mut self, _record: &DecisionRecord) {}
}

impl DecisionSink for DecisionTrace {
fn record(&mut self, record: &DecisionRecord) {
let _ = self.push(record);
}

fn amend_band(&mut self, entity_id: u64, tick: u64, band: u8) {
DecisionTrace::amend_band(self, entity_id, tick, band);
}
}

/// One-record sink used by [`rerun`] so the live ring stays put.
pub struct CaptureSink {
pub record: DecisionRecord,
pub wrote: bool,
}

impl DecisionSink for CaptureSink {
fn record(&mut self, record: &DecisionRecord) {
self.record = *record;
self.wrote = true;
}
}

impl Default for CaptureSink {
fn default() -> Self {
Self {
record: DecisionRecord::EMPTY,
wrote: false,
}
}
}

impl CaptureSink {
#[must_use]
pub const fn new() -> Self {
Self {
record: DecisionRecord::EMPTY,
wrote: false,
}
}
}

#[must_use]
pub fn tick_from_time(t: f32) -> u64 {
if t.is_finite() && t >= 0.0 {
Expand Down Expand Up @@ -570,7 +513,7 @@ pub fn record_rule(
plan: &astraweave_core::PlanIntent,
) {
let _ = trace.bind(entity_id);
trace.record(&grid_record(
let _ = trace.push(&grid_record(
entity_id,
tick,
PlannerId::Rule as u8,
Expand All @@ -583,7 +526,7 @@ pub fn record_rule(

pub fn record_utility(trace: &mut DecisionTrace, entity_id: u64, tick: u64, snap: &WorldSnapshot) {
let _ = trace.bind(entity_id);
trace.record(&utility_decision(entity_id, tick, snap));
let _ = trace.push(&utility_decision(entity_id, tick, snap));
}

fn grid_record(
Expand Down Expand Up @@ -821,7 +764,9 @@ fn rerun_htn(
};
let mut plan = AgentPlan::empty();
let mut budget = htn::HTN_EXPANSIONS_PER_TICK as u32;
let mut capture = CaptureSink::default();
let mut capture = DecisionTrace::new();
let _ = capture.bind(sample.record.entity_id);
let _guard = htn::attach_trace(&mut capture, sample.record.entity_id);
plan_route(
view.tiles,
view.scratch,
Expand All @@ -831,14 +776,11 @@ fn rerun_htn(
sample.record.tick,
&mut plan,
&mut budget,
&mut capture,
sample.record.entity_id,
);
if capture.wrote {
capture.record
} else {
DecisionRecord::EMPTY
}
capture
.find_tick(sample.record.entity_id, sample.record.tick)
.copied()
.unwrap_or(DecisionRecord::EMPTY)
}

fn snapshot_from_perceived(tick: u64, perceived: &PerceivedView, goal: u16) -> WorldSnapshot {
Expand Down
14 changes: 5 additions & 9 deletions astraweave-ai/src/ecs_ai_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,16 +316,12 @@ fn sys_spatial_tick(world: &mut ecs::World) {
let mut scratch = astraweave_nav::NavScratch::new();
let sim_tick = tick.clock;
tick.clock = tick.clock.saturating_add(1);
#[cfg(not(feature = "decision-trace"))]
crate::htn::tick_agents(tick, &mut scratch, sim_tick);
#[cfg(feature = "decision-trace")]
{
if let Some(ref mut trace) = held {
crate::htn::tick_agents(tick, &mut scratch, sim_tick, trace.as_mut());
} else {
let mut null = crate::decision_trace::NullSink;
crate::htn::tick_agents(tick, &mut scratch, sim_tick, &mut null);
}
#[cfg(feature = "decision-trace")]
let _guard = held
.as_mut()
.map(|trace| crate::htn::attach_trace(trace.as_mut(), 0));
crate::htn::tick_agents(tick, &mut scratch, sim_tick);
}
#[cfg(feature = "decision-trace")]
if let Some(held) = held {
Expand Down
136 changes: 104 additions & 32 deletions astraweave-ai/src/htn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,14 +211,103 @@ pub fn fill_observation(tiles: &NavTiles, buf: &mut ObservationBuf) {
}
}

#[cfg(feature = "decision-trace")]
std::thread_local! {
static TRACE_ACTIVE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static TRACE_ENTITY: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
static TRACE_HOLDER: std::cell::RefCell<Option<crate::decision_trace::DecisionTrace>> =
const { std::cell::RefCell::new(None) };
}

/// Swaps `trace` into thread-local storage until the guard drops.
///
/// `plan_route` keeps the same eight arguments with the feature on or off,
/// so the replay harness compiles either way and writes the same plan bytes.
/// With the feature off this function does not exist, and `plan_route` does
/// not touch the thread local.
#[cfg(feature = "decision-trace")]
pub struct TraceGuard {
trace: *mut crate::decision_trace::DecisionTrace,
Comment on lines +229 to +230

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Tie the guard lifetime to the trace borrow

TraceGuard stores a raw pointer but carries no lifetime, so safe code can call attach_trace(&mut trace, ...), move or drop trace, and then drop the guard. Its Drop implementation will dereference the pointer to the moved/dropped value, potentially causing use-after-free or a double free. Encode the mutable borrow in TraceGuard<'a> (or avoid the raw pointer) and add the required Miri/Kani coverage for this unsafe path. .github/copilot-instructions.mdL248-L252

Useful? React with 👍 / 👎.

prev_active: bool,
prev_entity: u64,
}

#[cfg(feature = "decision-trace")]
#[must_use]
pub fn attach_trace(
trace: &mut crate::decision_trace::DecisionTrace,
entity_id: u64,
) -> TraceGuard {
let prev_active = TRACE_ACTIVE.with(|cell| cell.replace(true));
let prev_entity = TRACE_ENTITY.with(|cell| cell.replace(entity_id));
let trace_ptr = trace as *mut crate::decision_trace::DecisionTrace;
swap_holder(trace);
TraceGuard {
trace: trace_ptr,
prev_active,
prev_entity,
}
}

#[cfg(feature = "decision-trace")]
fn swap_holder(trace: &mut crate::decision_trace::DecisionTrace) {
TRACE_HOLDER.with(|cell| {
let mut slot = cell.borrow_mut();
if slot.is_none() {
*slot = Some(crate::decision_trace::DecisionTrace::new());
}
if let Some(held) = slot.as_mut() {
std::mem::swap(trace, held);
}
});
}

#[cfg(feature = "decision-trace")]
impl Drop for TraceGuard {
fn drop(&mut self) {
if !self.trace.is_null() {
// SAFETY: `attach_trace` created this pointer from the caller's
// `&mut DecisionTrace`, and this guard is dropped before that
// borrow ends. The swap returns the caller's rings.
unsafe { swap_holder(&mut *self.trace) }
}
TRACE_ACTIVE.with(|cell| cell.set(self.prev_active));
TRACE_ENTITY.with(|cell| cell.set(self.prev_entity));
}
}

#[cfg(feature = "decision-trace")]
fn set_trace_entity(entity_id: u64) {
TRACE_ENTITY.with(|cell| cell.set(entity_id));
}

#[cfg(feature = "decision-trace")]
fn emit_record(record: &crate::decision_trace::DecisionRecord) {
if !TRACE_ACTIVE.with(|cell| cell.get()) {
return;
}
TRACE_HOLDER.with(|cell| {
if let Some(trace) = cell.borrow_mut().as_mut() {
let _ = trace.push(record);
}
Comment on lines +289 to +292

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bind each spatial agent before emitting its record

When sys_spatial_tick is given a freshly inserted DecisionTrace, it attaches the trace with entity 0 and tick_agents only changes TRACE_ENTITY; no spatial agent is ever bound. Because DecisionTrace::push rejects unknown entity IDs, this call silently drops every HTN record unless the caller independently pre-bound all agents, so inserting the advertised ECS resource alone produces an empty spatial trace. Bind the current entity before pushing, as the grid tracing path already does.

Useful? React with 👍 / 👎.

});
}

#[cfg(feature = "decision-trace")]
fn emit_band(entity_id: u64, tick: u64, band: u8) {
if !TRACE_ACTIVE.with(|cell| cell.get()) {
return;
}
TRACE_HOLDER.with(|cell| {
if let Some(trace) = cell.borrow_mut().as_mut() {
trace.amend_band(entity_id, tick, band);
}
});
}

/// Advance every agent. Sort key is `(band, entity_id)`.
#[allow(clippy::needless_range_loop)]
pub fn tick_agents(
tick: &mut SpatialTick,
scratch: &mut NavScratch,
sim_tick: u64,
#[cfg(feature = "decision-trace")] sink: &mut dyn crate::decision_trace::DecisionSink,
) {
pub fn tick_agents(tick: &mut SpatialTick, scratch: &mut NavScratch, sim_tick: u64) {
let wlen = tick.weaving_len as usize;
let hlen = tick.hazard_len as usize;
let mut weave_buf = [WeaveEffectHook {
Expand Down Expand Up @@ -281,6 +370,8 @@ pub fn tick_agents(
agent.ticks_since_plan = agent.ticks_since_plan.saturating_add(1);
match band {
0 if agent.ticks_since_plan >= REPLAN_TICKS || agent.plan.len == 0 => {
#[cfg(feature = "decision-trace")]
set_trace_entity(agent.entity_id);
plan_route(
nav,
scratch,
Expand All @@ -290,17 +381,15 @@ pub fn tick_agents(
sim_tick,
&mut agent.plan,
&mut budget,
#[cfg(feature = "decision-trace")]
sink,
#[cfg(feature = "decision-trace")]
agent.entity_id,
);
agent.plan.band = 0;
agent.ticks_since_plan = 0;
#[cfg(feature = "decision-trace")]
sink.amend_band(agent.entity_id, sim_tick, 0);
emit_band(agent.entity_id, sim_tick, 0);
}
1 => {
#[cfg(feature = "decision-trace")]
set_trace_entity(agent.entity_id);
plan_route(
nav,
scratch,
Expand All @@ -310,15 +399,11 @@ pub fn tick_agents(
sim_tick,
&mut agent.plan,
&mut budget,
#[cfg(feature = "decision-trace")]
sink,
#[cfg(feature = "decision-trace")]
agent.entity_id,
);
agent.plan.band = 1;
agent.ticks_since_plan = 0;
#[cfg(feature = "decision-trace")]
sink.amend_band(agent.entity_id, sim_tick, 1);
emit_band(agent.entity_id, sim_tick, 1);
}
2 if agent.plan.len == 0 => {
agent.plan.slots[0] = ActionSlot::MoveTo {
Expand All @@ -341,7 +426,7 @@ pub fn tick_agents(
&crate::decision_trace::AltList::new(),
0,
);
sink.record(&record);
emit_record(&record);
}
}
_ => {
Expand All @@ -363,8 +448,6 @@ pub fn plan_route(
sim_tick: u64,
out: &mut AgentPlan,
budget: &mut u32,
#[cfg(feature = "decision-trace")] sink: &mut dyn crate::decision_trace::DecisionSink,
#[cfg(feature = "decision-trace")] entity_id: u64,
) {
#[cfg(feature = "decision-trace")]
clear_alts();
Expand Down Expand Up @@ -427,10 +510,11 @@ pub fn plan_route(
let perceived = perceived_for_route(tiles, pos_milli);
Comment on lines +508 to +510

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Emit a record for the no-path wait branch

When query_path returns fewer than two waypoints, plan_route writes a 500 ms Wait action and returns before reaching this newly added emission block. Tracing therefore reports no decision for no-path or already-at-goal ticks instead of recording the actual wait plan. Route all plan exits through the emitter or emit the wait record before that return.

Useful? React with 👍 / 👎.

let alts = copy_alts();
let score = route_score(tiles, out);
let entity_id = TRACE_ENTITY.with(|cell| cell.get());
let record = crate::decision_trace::route_record(
entity_id, sim_tick, 0, pos_milli, out, perceived, &alts, score,
);
sink.record(&record);
emit_record(&record);
}
}

Expand Down Expand Up @@ -824,10 +908,6 @@ mod tests {
1,
&mut plan,
&mut budget,
#[cfg(feature = "decision-trace")]
&mut crate::decision_trace::NullSink,
#[cfg(feature = "decision-trace")]
1u64,
);
if budget == before {
break;
Expand Down Expand Up @@ -857,10 +937,6 @@ mod tests {
1,
&mut plan,
&mut budget,
#[cfg(feature = "decision-trace")]
&mut crate::decision_trace::NullSink,
#[cfg(feature = "decision-trace")]
1u64,
);
let before = move_cell(&plan);
tiles.mark(astraweave_nav::nav_change_from_kind(
Expand All @@ -880,10 +956,6 @@ mod tests {
31,
&mut plan,
&mut budget,
#[cfg(feature = "decision-trace")]
&mut crate::decision_trace::NullSink,
#[cfg(feature = "decision-trace")]
1u64,
);
let after = move_cell(&plan);
assert!(before < 8, "bridge path cell {before}");
Expand Down
6 changes: 2 additions & 4 deletions astraweave-ai/tests/decision_trace_alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ fn traced_plan_route_allocates_nothing_after_warmup() {
for tick in 0..4u64 {
let mut budget = 64u32;
let mut plan = AgentPlan::empty();
let _guard = astraweave_ai::htn::attach_trace(&mut trace, 1);
plan_route(
&tiles,
&mut scratch,
Expand All @@ -34,14 +35,13 @@ fn traced_plan_route_allocates_nothing_after_warmup() {
tick,
&mut plan,
&mut budget,
&mut trace,
1,
);
}

reset_allocs();
let mut budget = 64u32;
let mut plan = AgentPlan::empty();
let _guard = astraweave_ai::htn::attach_trace(&mut trace, 1);
plan_route(
&tiles,
&mut scratch,
Expand All @@ -51,8 +51,6 @@ fn traced_plan_route_allocates_nothing_after_warmup() {
4,
&mut plan,
&mut budget,
&mut trace,
1,
);
assert_eq!(allocs(), 0, "traced plan_route allocated");
assert!(trace.count_of(1) > 4);
Expand Down
Loading