Skip to content

v0.5.0 — Improved harness

Choose a tag to compare

@anthonytorlucci anthonytorlucci released this 19 Sep 15:14
· 239 commits to main since this release

[0.5.0] – 2026-09-19

Breaking changes

  • TrialReport::absorb_metrics no longer overwrites a harness-owned metric
    name; a caller reporting the harness's own measurements must switch to the
    new absorb_harness_metrics
    (resolves #1118, ADR 0079). Previously
    absorb_metrics was last-writer-wins: an agent or probe emitting a
    harness-owned key (return/mean, wall_clock_seconds, generations, any
    return//episode_length//throughput/-prefixed name, …) silently
    replaced the harness's own value with no error, no warning, and no record —
    the resulting report was byte-identical to one where the harness had
    genuinely measured that value. This is a breaking behavioural change with
    no compile error
    : absorb_metrics' signature is unchanged, so a call site
    relying on the old override keeps compiling and simply stops overwriting.
    The symptom to look for is a metric now appearing under agent/<name>
    instead of <name>, with <name> listed in the new
    TrialReport::displaced_metrics field, and one tracing::warn! line at the
    collision. If your Trial implementation reports measurements the trial
    itself made (episode returns, step counts, wall-clock time, generation
    counts) — not something an agent or probe handed back — call
    absorb_harness_metrics instead; it keeps the old unchecked,
    last-writer-wins behaviour and is the privileged path new harness-owned
    measurements should use. Agent- and probe-sourced metrics keep calling
    absorb_metrics, unchanged.

    TrialReport also gains a new pub displaced_metrics: Vec<String> field,
    which breaks any external struct-literal construction of TrialReport
    (TrialReport { .. } without going through TrialReport::new). No in-repo
    construction is affected — every call site already goes through ::new.
    JSON reports gain a displaced_metrics key; this is tolerant in both
    directions. No deny_unknown_fields exists anywhere in the workspace, so an
    older reader parsing a report produced by this version ignores the new key
    rather than failing, and #[serde(default)] on the field means an existing
    .ckpt.json checkpoint written by an earlier binary — which has no
    displaced_metrics key at all — still resumes correctly under this
    version, decoding to an empty vec.

  • BenchEnv, BenchStep, and BenchError are removed from rlevo-core,
    along with the rlevo_benchmarks::env shim module and the crate-root
    rlevo_benchmarks::{BenchEnv, BenchError, BenchStep} re-export (ADR 0077).
    Nothing in the workspace implemented or used them by the time they were
    deleted. Migration depends on what the type is:

    • An episodic environment: implement
      rlevo_core::environment::Environment<D, SD, AD> with
      RewardType = ScalarReward. Evaluator::run_suite now binds on it
      directly and infers D/SD/AD from the Suite<E> you pass, so no
      adapter and no turbofish are needed. SnapshotBase<R, Obs, Rew> supplies
      the Snapshot impl. BenchAdapter is deleted; envs are registered as
      themselves.
    • A self-paced loop (an evolutionary generation stepper, say): implement
      rlevo_core::evaluation::GenerationProbe — begin(), then
      advance() -> Option<Metrics> until the budget is spent — and drive it with
      Evaluator::run_trials and GenerationTrial. Metrics are typed, so the
      single f64 reward BenchStep carried is no longer a constraint.

    Errors that arrived as BenchError::{Reset, Step} now arrive as
    EnvironmentError directly; the variant tag was redundant with call-site
    context. Evaluator::run_suite keeps its name, argument order, and
    behaviour, and gains three inferred const parameters.

    Background: ADR 0075 found the trait's object-safety rationale unsound (its
    erasure was on the rank axis, while Observation/Action — what actually
    differs between environments — survived it), and ADR 0076 replaced it with
    the Trial seam.

  • ReplayBufferError loses its TensorConversionError(String) and
    BatchError(String) variants, and becomes #[non_exhaustive]
    (resolves
    #411). Neither variant was constructible in practice — no code in this
    workspace or its predecessor ever built one — so the only code a removal can
    break is an exhaustive match on the enum. Add a wildcard arm; the
    #[non_exhaustive] attribute now requires one anyway, and in exchange a
    future variant stops being a breaking change. No persisted data is involved:
    ReplayBufferError does not derive serde, so no wire or config format
    changes. (Other types in replay/ — PrioritizedReplayConfig,
    UniformReplayConfig, PrioritizedReplaySettings, Priority,
    ImportanceExponent — do derive it, and are untouched.)

  • All eight agent error enums lose their unconstructed variants and become
    #[non_exhaustive]
    (resolves #1070, and subsumes #467 and #484). The six
    off-policy enums — DqnAgentError, C51AgentError, QrDqnAgentError,
    DdpgAgentError, Td3AgentError, SacAgentError — drop
    TensorConversionFailed(String), Buffer(#[from] ReplayBufferError) and
    Io(#[from] std::io::Error), keeping InvalidAction and Polyak.
    PpoAgentError and PpgAgentError drop TensorConversionFailed(String),
    InvalidConfig(String) and Io(#[from] std::io::Error), keeping
    Environment and so becoming one variant wide. Twenty-four variants in
    total, none of which any code in this workspace ever constructed. Migration:
    as above, an exhaustive match needs a wildcard arm, which
    #[non_exhaustive] now requires anyway and which buys future variants for
    free. The three #[from] impls go with their variants, so a ? that
    converted a ReplayBufferError or an std::io::Error into an agent error no
    longer compiles — no such site exists in this workspace, and for
    ReplayBufferError none is possible (see below). No persisted data is
    involved: none of the eight derives serde.

  • AgentStats<T>'s four pub fields become private, behind #[must_use]
    accessors
    (resolves #407). total_episodes, total_steps, best_score and
    recent_history are now read through total_episodes(), total_steps(),
    best_score() and recent_history(), and recent_history.len() becomes
    recent_len(); the bound itself is readable as window_size(), which was not
    reachable before at all. One wrinkle worth calling out, because the compiler
    reports it as a type error rather than a missing field:
    let history = &agent.stats().recent_history; becomes
    let history = agent.stats().recent_history(); — the & is dropped, since
    the accessor already returns a reference.

    The invariant at stake is recent_history.len() <= window_size. record()
    has always maintained it, popping the front before pushing once the window is
    full — but a pub field let any external caller push_back past the window,
    or advance total_episodes without touching the history and desync the
    lifetime counters from it. docs/rules.md §3 lists precisely this shape of
    bound for History and ReplayStrategy ("len() never exceeds capacity")
    among the invariants a type must enforce rather than merely document; §2's
    Struct Field Encapsulation rule (ADR 0055) names the remedy this entry
    applies — private fields, #[must_use] read accessors named after the field.

    No test could have caught this, and the reason is the point. All 19 call sites
    across 10 files — nine integration suites and production code at
    algorithms/ppo/train.rs:297 — only ever
    read these fields, which the accessors still permit; nothing anywhere in the
    workspace ever wrote to one. A test can only observe a missing guard by
    tripping it, so the defect was unreachable from inside this repository and
    reachable only by a downstream user of the published crate. (The issue itself
    understates the surface as a single three-line test site; the verified figure
    is the 19/10 above, and the migration is read-only at every one of them.)

  • PixelGridState::new becomes fallible and is no longer const: it is now
    pub fn new(agent: u32, goal: u32) -> Result<Self, StateError>, rejecting any
    cell index >= CELL_COUNT (resolves #542, with the panic itself recorded under
    rlevo-environments below). The old signature was pub const fn -> Self and
    documented its own indices as unvalidated, which left the type's one real
    invariant — the one Observable::project dereferences the pixel buffer with —
    enforced nowhere. Validating at the only public construction path mirrors
    ContextualBanditObservation::new, the existing precedent in this crate.

    Migration is a .expect("…") or a ? at each call site; the workspace's own
    sites are literal-index test and benchmark fixtures, where an .expect reads
    as the assertion it is. The loss of const is the sharper break: new can no
    longer initialize a const or static item, and no const fn can call it.
    Where the indices are construction-provably in range and the state is built
    inside this crate, the struct literal remains available and is what
    PixelGridEnv::initial_state now uses, rather than laundering an unreachable
    error path back to the caller. No persisted data is affected:
    PixelGridState derives only Debug, Clone — it has no serde derive — so
    no checkpoint, replay buffer, or config format contains one.

rlevo-metrics-registry

Added

  • The canonical skipped_updates row (for #346, ADR 0072). ADR 0056's
    FiniteLossGuard skips backward() and the optimizer step whenever a loss
    comes back non-finite, so a run can discard an arbitrary fraction of its
    gradient updates while every other reported number — reward, loss, n_updates
    — stays plausible. Until now that fraction was not a metric at all, only a log
    line, so it never reached a plot or a saved run. The row is Rl /
    PerUpdate, unit "updates", LowerIsBetter, placed immediately after
    n_updates because the pair is only meaningful read together: applied updates
    are $\text{n_updates} - \text{skipped_updates}$. It is cumulative, not per-interval — a
    per-interval count would be a function of log_every, a logging parameter,
    which would make two runs of the same configuration incomparable purely
    because one logged more often. Per ADR 0015's registry promise, adding the row
    is the whole integration: the live benchmarks TUI and the on-disk record pick
    it up with no rlevo-benchmarks change. The descriptor set is additive and
    nothing matches it exhaustively, so no consumer breaks.

rlevo-benchmarks

Added

  • metrics::core::RETURN_NON_FINITE_STEPS, the metric key
    return/non_finite_steps (for #1115, ADR 0078). Emitted on every trial,
    including as 0, so a consumer can tell "this trial saw no non-finite
    rewards" from "this build of the harness does not report the quantity". It
    counts steps, not episodes — a poisoned return records that an episode was
    affected, never how many of its steps were — and is return/-prefixed so a
    free-form agent metric cannot collide with it. It reaches the JSON report; the
    TUI and the static-HTML report read a different channel and surface the
    warning line instead.

  • metrics::core::is_harness_reserved and metrics::core::GENERATIONS
    (for #1118, ADR 0079). is_harness_reserved(name: &str) -> bool is the
    public predicate behind the re-homing described below — it reports whether
    a metric name belongs to a harness-owned prefix (return/,
    episode_length/, throughput/, agent/) or exact key (success_rate,
    wall_clock_seconds, generations). GENERATIONS is the new pub const
    key ("generations") GenerationTrial now uses in place of a raw string
    literal.

Fixed

  • A benchmark trial produced a different artefact depending on whether the
    binary was built in debug or release
    (resolves #1115). EpisodicTrial::run
    carried a debug_assert! on reward finiteness. In release it compiled away
    and the trial completed with a NaN or inf return/mean; in debug it
    panicked into run_trials' catch_unwind, whose handler replaces the trial
    with a fresh TrialReport marked errored — discarding every episode the
    trial had already completed — and under fail_fast aborted the rest of the
    suite. The assertion guarded nothing either way: total_reward += reward ran
    unconditionally in both profiles. It is replaced by a per-trial count, one
    summary tracing::warn! naming the environment and the total, and the
    return/non_finite_steps counter above; accumulation stays raw, so a poisoned
    return is still reported rather than quietly repaired. ADR 0078 records the
    reasoning, including why a counter and not a log line alone.

  • An agent- or probe-emitted metric could silently overwrite a harness
    measurement, with no error, no warning, and no record
    (resolves #1118,
    ADR 0079). TrialReport::absorb_metrics was last-writer-wins, and both
    trial shapes — EpisodicTrial and the previously-untested
    GenerationTrial — absorbed agent/probe output after their own
    measurements, so an agent emitting return/mean, wall_clock_seconds,
    generations, or any other harness-owned key replaced the harness's own
    value; the resulting report was indistinguishable from one where the
    harness genuinely measured that value. absorb_metrics now re-homes a
    colliding key to agent/<name>, records the original key in the new
    displaced_metrics field (see Breaking changes, above), and warns once per
    collision. Harness-owned measurements move to the new privileged
    absorb_harness_metrics. agent/ is itself reserved, so an agent cannot
    place a metric directly in the re-homing landing zone. GenerationTrial
    also gains a proper GENERATIONS metric-key constant, replacing a raw
    string literal, and the same collision test coverage EpisodicTrial already
    had.

    Why the existing test missed this: ADR 0078's own
    agent_metrics_are_absorbed_after_the_harness_counter test asserted, by
    name, that an agent naming the exact key return/non_finite_steps should
    win over the harness's own count — it pinned the defect as a contract
    rather than catching it, and its own commentary said as much: reversing the
    assertion "would be a change to absorb_metrics' contract and needs its
    own ADR, not a test edit." This is that ADR; the test is now inverted (and
    renamed an_agent_cannot_overwrite_the_harness_non_finite_count) to assert
    the harness value survives. GenerationTrial had no collision test at all
    before this change.

rlevo-core

Added

  • config::at_most and ConstraintKind::TooLarge, the upper-bound
    counterparts to the existing at_least / TooSmall pair (for #404). The
    validation helpers could express "a count must be at least n" but had no way
    to express a ceiling at all, which is why every usize capacity field in the
    workspace was validated on one side only. TooLarge is a new variant on an
    existing enum and nothing in the workspace matches ConstraintKind
    exhaustively, so no caller breaks.

  • util::checked_combinations, a fallible counterpart to combinations
    returning Option<u64> (for #927). combinations has to answer something
    for arguments whose binomial coefficient is simply not representable, and the
    only honest answers are a panic or an Option; callers that count
    configurations from sizes they did not choose themselves now have the
    non-panicking one. It returns Some(0) for k > n exactly as combinations
    does, so it is a drop-in for every input the infallible helper accepts.

Changed

  • The Reward trait now states its finiteness obligation, and says what the
    framework does when it is broken
    (resolves #1115, ADR 0078). The trait
    required Into<f32> and said nothing at all about NaN or infinities, while
    four sites downstream each handled one differently. A new # Finiteness
    section states that implementors should yield finite values and enumerates
    what each layer actually does when they do not; ScalarReward and
    Environment::step's RewardType gain pointers to it. No runtime check is
    added, and none is deferred
    — Reward is a trait, so validating one
    concrete implementor closes nothing for an environment that ships its own.

  • The agent module's documentation no longer names the version it is empty
    in
    (resolves #936). Every doc site describing the placeholder module carried
    a version stamp, and between them they gave three different answers: the
    crate-level module map in lib.rs said v0.1.x, the pub mod agent doc
    comment said v0.3.x, and both the module's own header in agent.rs and the
    crate README.md said v0.1.0 — while the workspace has been on 0.4.0 for
    some time, so every one of them was stale regardless of which you believed.
    The stamps are deleted rather than corrected to 0.4.x: a version number in
    prose about an unimplemented module carries no information a reader can act
    on, and keeping one only guarantees the next release bump re-falsifies each
    copy. All of them now read "while the unified agent trait hierarchy
    stabilizes", which is the condition that actually governs when the module
    fills in. docs/rules.md loses a hardcoded 0.1.0 for the same reason,
    stating the workspace-inheritance mechanism instead of the value it currently
    carries.

Fixed

  • util::combinations returned wrong counts — silently, in release — for
    binomial coefficients that fit comfortably in a u64
    (resolves #927,
    closes #933). The naive loop multiplied before dividing, so its intermediate
    product overflowed long before the answer did, and in release builds that
    overflow wrapped instead of panicking. C(66, 33) is
    7_219_428_434_016_265_740, well under u64::MAX
    (18_446_744_073_709_551_615), yet the helper returned
    128_965_714_594_187_190 — a plausible-looking number some $56\times$ too small,
    with nothing to distinguish it from a correct one.
    Sweeping n < 200, 2603 (n, k) pairs whose exact value is representable
    came back corrupted this way.

    The fix accumulates in u128 over the C(n - k + i, i) recurrence, whose
    every partial result is an exact integer, and reduces by the symmetry
    C(n, k) == C(n, n - k) first. Every representable coefficient is now
    computed; combinations panics only when the exact result exceeds
    u64::MAX (first at n = 68, where C(68, 31) and up no longer fit), a
    contract now stated in its # Panics
    section and in the docs/rules.md panic table. The signature is unchanged.
    Note that the fix rejected in the issue thread — bolting checked_mul onto
    the naive loop — would have panicked on all 2603 of those pairs rather than
    computing them.

    Why the existing tests missed it: the largest case they covered was
    C(54, 6), and the first intermediate overflow happens at n = 63. Every
    assertion sat far inside the safe region n <= 62, so the coverage was not
    merely thin near the boundary — it never approached it. A "does it panic?"
    test would not have helped either, since release builds wrap rather than
    panic; the new regression tests pin exact values.

  • Metric::Counter's rustdoc contradicted absorb_metrics' actual
    behaviour
    (part of #1118, ADR 0079). The variant's doc described a count
    "the harness may accumulate across trials"; absorb_metrics (and the new
    absorb_harness_metrics, rlevo-benchmarks) never accumulated — they
    insert, replacing whichever value previously occupied that key. ADR 0078
    recorded the tension without resolving it. Fixing it by making absorb
    actually accumulate was rejected: every metric name that collides in
    practice (wall_clock_seconds, return/mean, generations,
    success_rate) is a Metric::Scalar, not a Counter, so accumulation
    would not touch the collisions that matter; it would also break
    absorb's idempotence under repeated calls, and TrialReport has no scope
    wider than one trial for "across trials" to describe. The doc was corrected
    instead, delegating the emission-cadence contract to
    MetricsProvider::emit's existing drain-and-reset rule rather than
    restating it a second time on the variant — the first draft of this fix
    wrote a competing "running total to date" sentence that contradicted
    emit's rule four lines below it in the same file.

rlevo-environments

Fixed

  • The agent's carried item never reached the grid observation; the agent's
    own view cell reported the world entity it stood on instead
    (resolves
    #1027, ADR 0073). dynamics.rs gates door-unlocking on agent.carrying
    and unlock_pickup.rs gates episode success on it, so door_key,
    unlock, and unlock_pickup had reward and transition dynamics that
    depended on hand state the policy's own observation never carried in any
    form — a policy could not condition on "am I holding the key" from what it
    saw, only infer it from action history. grid::stamp_carried now writes
    the agent's own view cell as Some(agent.carrying.unwrap_or(Entity::Empty)),
    called from mask_view after the occlusion dispatch, mirroring canonical
    Minigrid's gen_obs_grid order (slice → rotate → occlude → stamp the
    carried object).

    Why the existing per-env occlusion tests missed this: every one of
    them compares two emitted observations — occluded against see-through —
    cell by cell, so the agent's own cell moves identically on both sides of
    the comparison and no assertion could ever see the difference between
    "world entity" and "hand." Separately, every existing fixture starts the
    agent standing on Entity::Empty with an empty hand, which is exactly the
    one case where the old code and the fix produce the same byte — the
    defect was invisible to both dimensions the coverage varied along.

    Tensor shape and the serde wire format are unchanged (GridObservation
    stays [7, 7, 3], GoToDoorObservation stays [7, 7, 4], no struct
    gains a field), so any rollout or replay buffer recorded before this
    change still deserialises without error — it is silently wrong rather
    than loudly wrong, having recorded the world under the agent instead of
    its hand.

    One more consequence worth calling out on its own: because Goal and
    Lava are both passable and the agent steps onto them before the
    terminal match fires, the agent's own view cell now reads Empty
    (empty-handed) instead of Goal/Lava on the terminal frame of eight
    goal-reaching and three lava environments, whether or not anything is
    carried. This changes observed bytes but breaks no compilation and no
    persisted format, so it is recorded here rather than under Breaking
    changes, whose entries above are all compile-time API breaks.

  • Projecting a pixel_grid state with an out-of-range cell index aborted the
    process
    (resolves #542). PixelGridState::new(25, 0).project() panicked with
    range end index 1203 out of range for slice of length 1200: paint_cell
    computed a pixel block from a cell index nothing had range-checked and wrote
    past the end of the frame. State::is_valid had encoded exactly the missing
    predicate since the type was written, and had zero production callers —
    Observable::project never consulted it, and impl Sensor<3, 1, 1>, added
    later by the ADR 0047 migration, inherited the same gap, which made the panic
    reachable through the environment's own emission path rather than only through
    a direct project call.

    Why the existing tests missed it: is_valid_rejects_out_of_range asserted
    the predicate on an out-of-range state but never projected one, and every
    project test used in-range indices. The predicate was covered; the code it
    was supposed to protect was not — no test ever put the two together, which is
    the only way the gap could have shown up. (The issue speculated the bad state
    would arrive from "a deserialized checkpoint." It cannot: PixelGridState
    derives only Debug, Clone and has no serde. The real exposure was the
    public unvalidated new, which is why the fix is the fallible constructor
    recorded under Breaking changes.)

    paint_cell is now total in cell: a debug_assert! fires in debug builds,
    and an early return placed ahead of the divide leaves the block unpainted in
    release instead of writing out of bounds. The placement matters beyond the
    panic — on a 32-bit-usize target, a large cell makes the row arithmetic
    wrap and can land the write back inside the buffer, silently corrupting a
    pixel belonging to a valid cell; per-write bounds checks would not close that.
    PixelGridEnv::reset and step additionally assert
    self.state.is_valid() in debug builds, immediately after writing the state
    and before the sensor call, so a broken transition is reported at the
    environment boundary rather than inside the renderer.

    The cost of totality is worth stating plainly. The degraded frame omits the
    agent block, which is an absence marker no valid state can produce (the agent
    is painted last and unconditionally), so it is at least not mistakable for a
    legitimate observation the way a clamped index would be — but it is still a
    full-size frame of finite u8-derived values, so ADR 0067's non-finite
    replay-ingestion drop does not catch it. Nothing downstream rejects it. In a
    release build the failure is silent past project, and the debug assertions
    are the only thing that makes it loud.

Added

  • pixel_grid::CELL_COUNT_U32, CELL_COUNT as the u32 that cell indices
    are actually stored in (part of #545). It exists so a range check on an index
    is a plain comparison against a compile-time constant rather than a
    u32::try_from(CELL_COUNT).expect(…) re-evaluated on every call — which is
    what is_valid did before, on the hot projection path. It replaces the
    conversions in is_valid and in initial_state's fixed-placement branch; the
    remaining u32::try_from sites #545 lists convert sampled or computed
    usize cell indices, not CELL_COUNT, so that issue is only partly closed.
    New public API, so nothing breaks.

  • Grid::try_set and GridError, a non-panicking way to write a cell whose
    coordinates come from data rather than from a literal (resolves #864, #862).
    Grid::set panics out of bounds, which is the right contract for the literal
    and derived coordinates every in-tree environment uses — each one calls
    Grid::new(config.size, …) with the same config field its coordinates derive
    from, so a larger config builds a larger grid and the write stays in range.
    But Grid is publicly re-exported, so that reasoning protects only callers
    inside this workspace; a downstream layout loader had no total write path at
    all. set now delegates to try_set, giving the bounds check one home, and
    GridError converts into ConfigError and EnvironmentError so a reset()
    can ? straight through it. The issue proposed -> bool; that was rejected
    because try_* means Result everywhere else in the workspace, bool here
    is reserved for predicates like in_bounds, and widening bool to Result
    on public API later would be a breaking change. Both the enum and its variant
    are #[non_exhaustive], which reserves the right to add variants and fields
    and stops downstream struct-literal construction — but note it does not
    make the existing x/y fields malleable: a downstream
    OutOfBounds { x, y, .. } binds them by name, so the position-newtype
    collapse #863 proposes stays a semver-major change. Grid::new now rejects a
    width * height that wraps — which would otherwise build a backing store
    shorter than the grid's own extent, leaving index free to run past it. A
    single absurd dimension (Grid::new(1, usize::MAX)) does not wrap and still
    fails later inside the allocation; bounding grid size is the caller's job.
    Both Grid::new's and Grid::set's panic contracts are now listed in the
    panic-contracts table in docs/rules.md.

  • GridAction::try_from_index and impl TryFrom<usize> for GridAction, the
    fallible counterpart to the trait's panicking from_index (resolves #813,
    #829, #831). Every current caller pre-clamps its index, so nothing was
    reachable — but the only constructor was one that panics, which is the wrong
    default for an index arriving from a policy network's argmax. from_index
    now routes through try_from_index and keeps its documented panic verbatim,
    and gained the # Panics section it was missing. A const assertion ties the
    explicit discriminants to ACTION_COUNT, so adding a variant without bumping
    the constant is now a compile error rather than a runtime surprise — the
    previous round-trip test was self-referential and passed under a shuffled
    variant order (#815, #819, #835 add the literal-binding, literal-to_index,
    and usize::MAX cases that pin it).

  • try_from_index and impl TryFrom<usize> for BlackjackAction,
    TaxiAction, FrozenLakeAction and CliffWalkingAction
    (resolves #954,
    #951, #971, #1093). Prospective hardening, not a live defect: the panic was
    and remains the documented DiscreteAction::from_index contract
    (rlevo-core/src/action.rs:117-123), and the sole in-tree caller
    (rlevo-examples/examples/toy_text/report_toy_text_with_client.rs:68)
    pre-clamps its index with Uniform::new(0, ACTION_COUNT) at line 61. What was actually wrong is that all four
    impls carried no doc comment at all — so the panic was undocumented at the
    point a reader would look for it — and there was no non-panicking path for an
    index that arrives from data (a replay log, a deserialized trajectory, a
    mis-sized policy head) rather than from a trusted computation. from_index
    keeps its panic and its exact message, now routed through the fallible
    constructor; the additions are purely additive and no caller needs to migrate.
    The pre-existing coverage missed the gap because it was a self-referential
    round-trip (from_index(to_index(a)) == a), which passes unchanged under a
    shuffled variant order and so pinned nothing about the wire format. Literal
    index-binding assertions now pin it, which matters most for TaxiAction
    (South 0, North 1, East 2, West 3 — neither alphabetical nor compass order)
    and for the fact that CliffWalkingAction (Up, Right, Down, Left) and
    FrozenLakeAction (Left, Down, Right, Up) deliberately use different
    orders, so a well-meaning cross-file "harmonization" would silently corrupt an
    action space.

Changed

  • The crate's documentation no longer names the version its unfinished work
    arrives in
    (resolves #1098). Six doc sites promised the games module,
    the monomorphic Suite<E> limitation, and the BenchAdapter ScalarReward
    bound in terms of "v0.1" / "v0.2" / "a future milestone" — lib.rs's games
    module doc, the crate README.md's Games heading and body, the bench::suites
    and bench::adapter module headers, and the chess::environment and
    connect_four placeholders. The workspace has been on 0.4.0 since the last
    release, so all of them were already false. As in the rlevo-core agent
    fix (#936), the numbers are deleted rather than corrected: a version stamp in
    prose about unimplemented work carries nothing a reader can act on, and every
    release bump re-falsifies each copy — which is exactly what happened. Each
    site now states the condition that actually governs when the gap closes (the
    Environment impls landing; Suite<E> being monomorphic; a non-scalar-reward
    env actually existing).

    The #[allow(dead_code)] stubs now point at live tracking issues rather than
    a milestone that has passed, as docs/rules.md §9 and §12 require: the games
    module allow, which carried no pointer at all, names #1101, and the two
    Rapier3DWorld accessors — add_ground_collider and bodies, both reachable
    only from #[cfg(test)] today — name #1102. Those three stay: each is
    independently load-bearing, and dropping any one of them fails a -D warnings
    build.

    A fourth allow, on chess::observations::current_board, is removed. It
    suppressed nothing — the module-level allow already covered that method, so
    deleting it leaves the crate clean. Note that verifying this needs
    cargo clippy -p rlevo-environments -- -D warnings without --all-targets:
    the latter compiles the test cfg, where dead_code does not fire at all, and
    so reports success no matter which allows are present.

rlevo-evolution

Fixed

  • A NaN fitness permanently froze one individual in the metaheuristic
    family, silently shrinking the population by one
    (resolves #131). ABC, Bat,
    Cuckoo Search and PSO keep a persistent per-slot fitness cache and accept a
    candidate only when it beats the cached value. The raw NaN was latched into
    that cache at the gen-0 bootstrap, and every subsequent comparison against it
    is false — so the slot became a zombie the algorithm could never replace. Bat
    and PSO have no reset mechanism at all, so the freeze was
    permanent-until-restart; ABC escaped only via the scout limit
    ($\text{pop_size} \cdot \text{genome_dim}/2$ — hundreds of generations for realistic configs);
    Cuckoo escaped via abandonment, but never at p_a = 0, a valid configuration
    the suite already exercises. All nine metaheuristic tell impls now sanitize
    the fitness vector once, where it is pulled to host, so the bootstrap seed and
    the accept-store are both covered by one call.

    The issue was filed as leader/global-best poisoning; it is not that.
    argmax_host seeds from $-\infty$ and compares with >, so a NaN can neither
    win a champion scan nor seed one, and best() was correct throughout — which
    is precisely why the frozen slot went unnoticed: the run's reported optimum
    stayed right while the search quietly ran a member short. Two files were
    missed by the original triage in the other direction. gwo.rs sanitized on
    the read (argtop3_max) but stored the raw value, and aco_r.rs sanitized
    for its archive ranking but then re-read the unsanitized vector when
    materializing archive_fitness, so a NaN survived at the archive tail. Both
    had been declared clean on the strength of their read-side guard alone.

    No existing test could have caught this. The NaN-safety coverage all runs
    through EvolutionaryHarness::step, which sanitizes before tell, and the
    convergence-style assertions that do exercise these algorithms pass happily
    while a slot is frozen. The new nan_fitness_does_not_latch_without_harness
    tests — one per algorithm, the bypass twin of the existing
    nan_fitness_survives_harness — drive init → ask → tell directly and assert
    on the cache rather than on convergence.

    Only callers who drive Strategy::tell directly were exposed; harness-driven
    runs were never affected, and on that path the change is a provable no-op
    (sanitize_fitness is idempotent). Strategy is public and re-exported in the
    umbrella prelude, so this is the ADR 0034 decision-3 bypass hole, now closed at
    the per-site floor rather than left to the chokepoint above it.

    One route remains open and is tracked separately as #1064: this sanitizes the
    fitness entering tell, not the cache it is compared against, so a NaN
    placed directly into a state's fitness vector via the pub *State::try_new
    constructors (or PsoState's pub fields) still freezes that slot.

  • mean_fitness still reported $+\infty$ for a population of optimal
    individuals
    (resolves the metrics half of #132). ADR 0034 maps a $+\infty$
    fitness to f32::MAX and states that, because the clamped value is finite, it
    "cannot blow a mean, variance, or reward to $+\infty$". That guarantee did not
    hold: f32::MAX passes is_finite() and so joins the running total, and
    f32::MAX + f32::MAX saturates straight back to f32::INFINITY. Two
    individuals legitimately pegging the objective in one generation were enough
    to report an infinite mean. StrategyMetrics::from_host_fitness now
    accumulates in f64 and narrows once, after the division — the accumulator's
    width, not the clamp, is what carries the guarantee. This also removes the
    ~1 ULP-per-addition drift the f32 total accrued over a large population.
    Because the chokepoint is shared, every evolutionary strategy was affected,
    not only the EA-root family #132 names.

    The existing coverage could not have caught this: the one $+\infty$ regression test
    passed a slice with a single infinite member, and a single f32::MAX in the
    sum is exactly the case that does not overflow. The defect needed two.

  • A NaN at index 0 permanently stranded the champion genome in GA,
    binary GA, and EP
    (resolves the champion-tracking half of #132).
    update_best in algorithms/ga.rs, algorithms/ga_binary.rs and
    algorithms/ep.rs seeded its scan with best_f = fitness[0] and compared
    with >. Every comparison against a NaN seed is false, so the scan kept
    index 0 and the champion-write guard best_f > state.best_fitness never
    fired — while the caller advanced state.best_fitness from the sanitising
    StrategyMetrics. The two fields desynchronised: best_fitness ratcheted up
    to the real winner, best_genome stayed None, and because the ratchet was
    now high, every later generation failed the guard too. Strategy::best()
    returned None for the rest of the run. All three now sanitise into a local
    buffer and order with total_cmp, matching the fix already carried by
    algorithms/gp_cgp.rs and satisfying ADR 0034's requirement that every
    champion-write site hold the per-site correctness floor.

    Only callers who drive Strategy::tell directly could reach this —
    EvolutionaryHarness::step sanitises before tell, so harness-driven runs
    were never exposed. Strategy is public and re-exported in the umbrella
    prelude, and the existing tests all went through the harness. es_classical.rs
    and de.rs were checked and are unaffected: both delegate to argmax_host,
    which seeds at $-\infty$ and is NaN-safe under >.

  • Two $+\infty$ fitnesses anywhere in a NEAT population erased fitness-proportional
    offspring apportionment for every species, not just the one holding them

    (resolves #1062). This is the same overflow as the mean_fitness defect
    above, at a site that fix could not reach: speciate and allocate_offspring
    in neuroevolution/species.rs never route through
    StrategyMetrics::from_host_fitness, so widening that accumulator left these
    two untouched. Both summed sanitized fitness into an f32, and two members
    clamped to f32::MAX saturate the total to $+\infty$.

    The population-wide blast radius comes from allocate_offspring inheriting
    the infinity. Its if total <= 0.0 guard does not fire, because $+\infty &gt; 0$.
    Healthy species then compute $\text{pop_size} \times \text{finite}/\infty = 0.0$; the poisoned one
    computes $\text{pop_size} \times \infty/\infty = \text{NaN}$, and NaN as usize saturates to 0 in
    Rust. Every floored share lands on zero, so the largest-remainder
    reconciliation hands out all pop_size seats round-robin — a species holding
    a $100\times$ fitness advantage went from 27 of 30 seats to 10, exactly the even
    split NEAT's speciation exists to avoid. Unlike #132's champion desync, no
    unusual usage is required: NeatStrategy::tell sanitizes and then calls
    speciate unconditionally, and it is NEAT's only entry point, so any
    objective that can return $+\infty$ twice reaches this on the normal path.

    allocate_offspring's total also overflows independently of the first
    defect — three species whose adjusted sums are each individually finite still
    saturate their total — so both accumulators needed widening, and total
    stays f64 rather than narrowing back.

    The blind spot was inherited too. test_speciate_sanitizes_nan_and_inf_fitness
    passes, and is correct: it covers the raw-NaN path, which ADR 0034 genuinely
    fixed. But it places a single $+\infty$ member in a species, and one f32::MAX in
    a sum is precisely the case that does not overflow. The new tests pin exact
    count vectors rather than asserting the total sums to pop_size — that
    weaker assertion holds on the buggy code, and is what let this through.

  • shaping::z_score returned an all-zero vector — a silent zero ES gradient —
    for any population containing a single saturated member.
    Found while
    generalising the two fixes above into ADR 0069, and latent: z_score is pub
    but has no in-workspace caller yet. It squares its centred terms, so a member
    at f32::MAX overflowed its own squared term to $+\infty$ at N = 1, before any
    accumulation — no accumulator width would have helped. $\text{var} = +\infty$ drove
    $\text{std} = +\infty$ and collapsed every output element to $\pm 0.0$. An entirely saturated
    population returned NaN instead. Both are finite-looking, panic-free, and
    exactly the shape of failure that gets mistaken for a converged run.

    The remedy could not be the f64 widening the sibling fixes used:
    Tensor::sum() accumulates in B::FloatElem, which the backend fixes, and
    reaching an f64 accumulator would force the device→host round-trip ADR 0034
    introduced sanitize_fitness_tensor to avoid. z_score now divides the
    population by its own max-abs magnitude before reducing, bounding every squared
    term. That is strictly stronger than widening would have been — it also holds
    on a narrower element type, where the old formula overflowed at fitness $\approx$ 256 —
    and z-scoring is invariant to a positive rescale, so ordinary inputs move by at
    most a few ULP.

    A $-\infty$ member still yields $+\infty$/NaN utilities. That behaviour is unchanged,
    pre-existing, and deliberately left alone here rather than folded into an
    overflow fix; it is tracked as #1068 and pinned by a test marked "Pin, not a
    fix".

Changed

  • The rule that a sanitized $+\infty$ "cannot blow a mean, variance, or reward
    to $+\infty$" has been corrected wherever it was stated
    (ADR 0069). It was false —
    f32::MAX is finite, so it joins a sum — and it was the direct cause of
    #132, #1062, and the z_score defect above: in each case the author read the
    rule, sanitized correctly, and then accumulated in f32 because the
    documentation said the clamp made that safe. The claim is corrected in the
    sanitize_fitness rustdoc (the tooltip at ~90 call sites, and the surface that
    misled the speciate author), in rules.md, in a coevolution test's doc
    comment, and via an annotation on ADR 0034's index row. ADR 0034 itself is
    unedited — its decision stands and only its justification was wrong.

    ADR 0069 records the corollary as a binding rule: a reduction over sanitized
    fitness accumulates in f64 and narrows at most once, afterwards; ordering,
    comparison and argmax are excluded, since saturation is order-preserving. Two
    pub(crate) primitives, sanitized_mean and sanitized_sum, give the rule a
    name at the call site, and three rescale-invariance property tests enforce it
    behaviourally — a source-text guard was rejected because two of the four
    mis-widened sites never mention sanitize_fitness and would have gone green
    through both #132 and #1062.

rlevo-reinforcement-learning

Fixed

  • SumTree::new silently built a corrupt priority index in release builds,
    and every caller-supplied buffer capacity was unbounded above
    (resolves
    #404). The prioritized-replay index sizes itself with
    capacity.next_power_of_two() and then leaf_base * 2, and the workspace
    root declares no [profile] section — so release inherits
    overflow-checks = false and both operations wrap. Measured with
    rustc -O: a capacity of 2^62 + 1 yielded nodes.len() == 0, and anything
    above 2^63 wrapped leaf_base to 0 as well. Release therefore returned
    a SumTree whose node array was empty, deferring the failure to an unrelated
    index panic at sample time, while debug builds panicked honestly at
    construction. A constructor whose contract differs between profiles is the
    more serious half of this issue; the reported unbounded with_capacity calls
    in History::new, UniformReplay::new and PrioritizedReplay::new are the
    other half.

    Both are closed by one documented ceiling, MAX_BUFFER_CAPACITY (2^32) —
    three orders of magnitude above the largest published replay buffers and a
    factor of 2^30 below the smallest capacity that wraps. It is enforced
    through Validate wherever a Result already existed
    (PrioritizedReplayConfig, the six agents' replay_buffer_capacity, and
    PPO's previously-unchecked $\text{num_envs} \cdot \text{num_steps}$ product), so every
    config-driven path now returns a recoverable ConstraintKind::TooLarge
    instead of dying; and as a widened assert! in the infallible constructors
    (History::new, UniformReplay::new, SumTree::new, AgentStats::new, and
    RolloutBuffer::new, which had no guard at either end and multiplied
    $\text{capacity} \cdot \text{action_dim}$ unchecked). No signature changes: try_reserve_exact
    and a fallible try_new were both rejected, matching the #190/#191 precedent
    — measured, try_reserve_exact recovers only the usize::MAX arm, which
    already unwinds as a catchable panic.

    The issue's own premise is corrected in passing. Vec::with_capacity does
    not uniformly abort: usize::MAX raises a catchable capacity overflow
    panic, and with_capacity(1 << 45) — 256 TiB — simply succeeded under macOS
    overcommit. The abort is the other-allocator case, and the guard is what makes
    the failure deterministic across all of them.

    No existing test could have caught either half. Every capacity test in the
    crate pinned the lower bound (History::new(0), UniformReplay::new(0),
    SumTree::new(0), AgentStats::new(0)), leaving the upper end entirely
    unexercised — and the sum-tree wrap is invisible in debug, the profile the
    suite runs in, because overflow-checks panics there for its own reasons. The
    new test_sum_tree_new_rejects_capacities_that_wrapped_in_release therefore
    asserts on the guard's panic message rather than merely that a panic
    occurred, so it stays red in both profiles against an unguarded constructor.

  • A non-finite target quantile survived terminal transitions in QR-DQN's
    Bellman backup
    (resolves #357). QR-DQN builds its target inline rather than
    through the shared helper, and it still computed the backup by scaling the
    bootstrap term: $\text{rewards} + (1 - \text{terminated}),\theta_{target},\gamma$. Because IEEE-754
    gives $\text{NaN} \cdot 0.0 = \text{NaN}$ (as does $\infty \cdot 0.0$), a poisoned quantile anywhere
    in the target network's output for the bootstrap action contaminated the
    target on exactly the samples where the terminal convention says the
    bootstrap must vanish — samples whose correct value, the reward alone, is
    known with certainty. The term is now genuinely masked to 0 wherever
    terminated == 1.0, so a terminal target is the reward regardless of what
    the next-state estimate holds.

    This corrects the record as well as the code. The #192 entry under 0.4.0
    below states that "C51 and QR-DQN never used this helper (they mask in their
    own projection step)". That is false for QR-DQN: it did not mask, it scaled,
    and this is the fix for the gap that sentence denied. C51 genuinely is
    unaffected, for a reason worth stating precisely so nobody patches it on a
    pattern match — its $(1 - \text{terminated})$ factor multiplies the fixed atom
    support
    , finite by construction from v_min/v_max and asserted so, never
    a network output.

    This is hardening, not a repair of live divergence: the expression cannot
    originate a non-finite value, only preserve one, and for all-finite inputs
    the masked form is numerically identical, so no algorithm's behaviour
    changes. The known upstream NaN sources (#184, #173) are both closed, so
    there is no live trigger today. No test could have caught it, and the reason
    is the interesting part: the backup was an inline expression in the middle of
    learn_step, with no seam a test could reach. Lifting it into a named
    function is what made the poisoned case testable at all, and the five new
    tests cover it. Four sit on the helper — including that masking stays
    per-row, leaving a non-finite quantile on a non-terminal row for the
    finite-loss guard rather than silently scrubbing a real divergence. The
    fifth runs through the agent and pins the backed-up target numerically in
    the reported loss, because the call site passes reward and terminal mask as
    two (B, 1) tensors the compiler cannot tell apart: without it, transposing
    them was a silent change.

  • AgentStats's two lifetime counters wrapped in release instead of
    saturating
    (resolves #408). record() accumulated total_episodes and
    total_steps with plain +=, and the workspace root declares no [profile]
    section — so release inherits overflow-checks = false and both counters wrap
    to 0 at usize::MAX, while debug panics. Neither profile is acceptable at
    this site: nothing branches on these counters — they are read for progress
    reporting — so a wrap does not fail, it reports, handing whoever is watching
    a monotone quantity that just went backwards with no signal at all. Both are
    now saturating_add, and the accessor docs state the resulting contract — a
    counter pinned at usize::MAX means "at least this many", not "exactly this
    many".

    This is hardening rather than a live risk, and #407 is the reason. Before it
    landed, the four fields were pub: any caller could write
    stats.total_steps = usize::MAX - 1 and make the very next record()
    overflow, no long run required. Privatizing them closed that vector, leaving
    only honest accumulation — roughly 1.8e19 steps on a 64-bit host. The issue
    body concedes as much.

    No existing test drove a counter anywhere near the boundary, and a test that
    merely asserted "it didn't panic" would have been vacuous: the dev profile the
    suite runs in has overflow-checks = on, so it panics on the unfixed code
    for a reason unrelated to the fix, and the release-only wrap is invisible to
    cargo test entirely. The two new regression tests therefore assert the
    saturated value at each counter, which is red in both profiles against +=.

  • Under a latch, a run silently lost gradient updates and only the very first
    skip was ever logged
    (resolves #346, ADR 0072, partially superseding ADR
    0056 §1 and §3). FiniteLossGuard warns once per site and then goes quiet for
    the rest of the run, so a run discarding 1% of its updates and one discarding
    40% produced byte-identical logs: one line each. That is the failure mode ADR
    0065 named for FiniteRewardGuard — the loud divergence reads as a silent
    one, and the operator's only remaining evidence is a curve that has stopped
    improving for no visible reason. The guard now carries a running skipped
    count and re-warns on the 1st, 10th, 100th, … skip, each line carrying the
    running total, adopting FiniteRewardGuard's decade schedule verbatim so the
    two guards read the same way in one log. Operator-visible: anyone grepping
    for the old single-occurrence signature should expect the per-site volume to
    rise from at most 1 line to at most about 7 over a realistic run — the message
    is bounded logarithmically, not per skip, so a pathologically diverging run
    still cannot flood the log.

    The skip itself is unchanged and remains ungated: it fires on every
    non-finite loss, never on the warning schedule (ADR 0056 §3, reaffirmed by
    ADR 0072). Only the reporting was latched; no update that used to be applied
    is now skipped, or the reverse.

    The existing tests could not catch it, and the reason is why the counter
    exists. All 19 agent-side assertions read warning_fired(), a bool that is
    true after the first skip and stays true no matter how many follow — so
    the latch was not merely uncovered, it was the only thing observable, and
    "the guard fired" and "the guard fired 4000 times" were the same assertion.
    warning_fired() is deleted (it was #[cfg(test)] and pub(crate), so this
    is a private-item removal, not a breaking change) and those 19 assertions
    become exact-value assertions on the new counters — a strengthening in both
    directions, since the old !warning_fired() was satisfiable by an
    already-fired latch while == 0 is not.

Added

  • UniformReplayConfig, and a fallible UniformReplay::from_config /
    ReplayKind::uniform_from_config beside the panicking new.
    Uniform
    replay was the only buffer with no config type: its capacity travelled as a
    bare usize on six agent configs, each of which hand-wrote the same
    config::nonzero + config::at_most(.., MAX_BUFFER_CAPACITY) pair in its own
    validate(). Six copies of one predicate, with nothing keeping them in sync —
    a seventh off-policy agent that copied five of the six lines would have left
    UniformReplay::new to abort the process inside VecDeque::with_capacity
    instead of returning ConfigError. The predicate now lives once, in
    UniformReplayConfig::validate; the six agents delegate to it and relabel the
    error so callers still see their own config and replay_buffer_capacity field
    named, with the ConstraintKind passed through unchanged. Agent config field
    types, builder setters, and error identity are all unchanged — this is
    additive.

    The six agents now construct through from_config, so correctness no longer
    rests on validate() happening to be called before the buffer is built.
    UniformReplay::new(capacity) survives for literals, on the same new /
    try_new discriminator ImportanceExponent and Priority already use.

    Why the existing tests missed it: every agent did validate correctly, so no
    test could fail. The defect was duplication — invisible to any test of current
    behaviour, and only observable as the seventh agent someone has not written
    yet. tests/replay_capacity_single_source_guard.rs is therefore a source-text
    guard rather than a behavioural test: it fails on a hand-written
    at_most(.., MAX_BUFFER_CAPACITY) under algorithms/, and separately on an
    agent that builds a replay buffer through an infallible constructor — the
    worse drift, since dropping the check entirely also satisfies the first rule.

  • Per-loss-site skip accessors on all eight agents, and skipped_updates
    emitted from every train loop
    (resolves #346, ADR 0072). The Fixed entry
    above makes a skip loggable; these make it readable at runtime, which is
    what a caller needs to gate a run, a sweep, or a test on. Twenty-two
    accessors, one per loss site plus an aggregate on each multi-site agent: DQN,
    C51 and QR-DQN have a single site, so skipped_updates() is both;
    DdpgAgent adds skipped_critic_updates() / skipped_actor_updates();
    Td3Agent and SacAgent add skipped_critic_1_updates() /
    skipped_critic_2_updates() / skipped_actor_updates(); PpoAgent adds
    skipped_policy_updates() / skipped_value_updates(); PpgAgent adds
    skipped_policy_updates() / skipped_value_updates() /
    skipped_aux_value_updates() / skipped_aux_total_updates(). Per-site rather
    than one lumped total because the sites diverge independently and for
    different reasons — a critic blowing up is a different diagnosis from an actor
    blowing up — and the aggregate is what the metric emits.

    These pair with ADR 0059's gradient_updates() / critic_updates(), which
    advance unconditionally, including on a skip: those count attempts, so
    the applied-update count is $\text{attempts} - \text{skipped}$, and neither number means
    what a reader expects without the other. n_updates and the new
    skipped_updates metric row carry the same relationship into the record.

  • DdpgAgent::critic_updates() (for #346). Unrelated-looking, and exposed by
    the work above: DDPG tracked critic_updates as a private field with no
    accessor, unlike SacAgent and Td3Agent, which both expose theirs. So DDPG
    alone had a numerator (skipped_critic_updates()) with no publicly readable
    denominator — the $\text{applied} = \text{attempts} - \text{skipped}$ identity was unevaluable on
    exactly one of the eight agents. Additive; it restores parity across the
    off-policy family.

  • AgentStats is deliberately untouched by all of the above. #346's title
    proposed putting the skip counter there, and that is a scope error worth
    recording so it is not re-proposed: AgentStats is episode-scoped — it
    records one row per finished episode — while a loss skip is per-update, per
    loss site
    , and several sites can skip within a single episode on agents that
    update more than once per step. There is no rate at which the two can be
    reconciled without inventing one. Adding the field would also have fired ADR
    0071 §Reopen trigger 1. The counter lives on the guard, is read through the
    agent, and reaches the record as a metric; the stats type keeps its meaning.

  • AgentStats::finite_best_score and AgentStats::non_finite_episodes
    (resolves #1078, ADR 0071). An earlier review claimed "NaN permanently
    poisons best_score"; that claim was refuted, and #1078 opens by conceding
    it — record() folds the score with f32::max, which discards a NaN
    operand in either position. What it
    does not discard is $+\infty$, which it propagates from either position because
    $+\infty$ compares greater than every finite value, and best_score is never
    evicted by the sliding window. One $+\infty$ episode therefore pins the accessor
    at $+\infty$ for the agent's entire remaining lifetime, with no self-healing at
    all — strictly worse than the avg_score case #409 was about, which recovers
    within one window_size as the offending episode rolls out. The existing
    tests missed it because the two NaN tests pin f32::max's discarding
    behaviour in both operand positions and were read as covering "non-finite
    scores"; they cover NaN only, and $+\infty$ is the one non-finite value
    f32::max propagates rather than discards. Nothing else gated it either —
    rlevo-test-support's assert_reaches and assert_improves_over_random
    both read avg_score and never best_score, so a latched $+\infty$ survives a
    fully green suite. It is also more reachable than it looks: ADR 0065's
    FiniteRewardGuard refuses to store a non-finite per-step reward, but all
    eight training loops still accumulate episode_reward += reward_f32
    unconditionally and by design (ADR 0065 §Decision 4), so a single $+\infty$
    environment reward reaches record() on a fully guarded agent with
    dropped_transitions() reading 1 — and separately, a long episode of
    entirely finite rewards can saturate the f32 accumulator with no
    non-finite reward anywhere and dropped_transitions() reading zero.
    best_score is nevertheless byte-for-byte unchanged: $+\infty$ genuinely is the
    maximum score observed, and filtering it under that name would report a
    number the run contradicts — the same fabrication ADR 0061 rules out and ADR
    0070 refused for the mean. Two additive accessors close the gap instead:
    finite_best_score() returns the lifetime maximum over is_finite() scores
    (None until something finite is recorded), and non_finite_episodes()
    counts the episodes it excluded. The predicate is is_finite() rather than
    #409's !is_nan() for a reason sharper than the mean's: f32::max already
    discards NaN for free, so a !is_nan() version of this accessor would be
    indistinguishable from best_score at every input except the one that
    motivated the issue. non_finite_episodes() parallels total_episodes() and
    is a monotone lifetime counter that never heals — deliberately unlike
    non_finite_recent_len(), which parallels recent_len(), is derived per
    call, and returns to zero once the window rolls past; the two disagree on a
    run that went bad early and recovered, and that disagreement is the point.
    Unlike the #409 change, this one does add state: a lifetime maximum cannot
    be derived from a window that evicted the record which set it. ADR 0070
    declined a stored counter because it would need decrementing on eviction; a
    lifetime counter has no eviction coupling to get wrong. It saturates at
    usize::MAX alongside total_episodes/total_steps.

  • AgentStats::finite_avg_score and AgentStats::non_finite_recent_len
    (resolves #409, ADR 0070). #409 asked for avg_score to filter NaN out of
    its mean; that change is rejected — avg_score is byte-for-byte unchanged,
    and the non-finite score it transits is a recorded contract (ADR 0065
    §Decision 4): a training loop deliberately accumulates a non-finite
    per-step reward into episode_reward unconditionally, so the reported
    curve — not just dropped_transitions() — surfaces a poisoned run, and
    rlevo-test-support's assert_improves_over_random/assert_reaches both
    gate a run's convergence check on that same value being finite; filtering
    it there would let a NaN-poisoned run silently pass a threshold it never
    met. What #409 actually found is real, just misdiagnosed: the crate offered
    no reporting counterpart for a caller drawing a learning curve, where one
    bad episode should not blank the mean for the next window_size episodes,
    and the accepted contract that transiting is fine lived only inside a
    #[cfg(test)] doc comment — not in the rustdoc, not on docs.rs — which is
    how #409 came to be filed asserting the opposite of what the code already
    did. Two additive accessors close both gaps, mirroring
    StrategyMetrics::mean_fitness/broken_count in rlevo-evolution (ADR
    0034 §Decision 4): finite_avg_score() returns the mean over the window's
    finite entries (None when the window is empty or every entry is
    non-finite), and non_finite_recent_len() reports how many entries it
    excluded — shipped as a pair, since a hardened mean without its exclusion
    count is the same silent sanitization ADR 0065 already refuses. The
    predicate is is_finite(), deliberately stronger than #409's proposed
    !is_nan(): episode_reward is an f32 accumulator over a whole episode,
    and a long episode of entirely finite per-step rewards can saturate it to
    $\pm\infty$ with no NaN anywhere and no reward-ingestion guard on that path —
    !is_nan() would let that value straight into a mean advertised as
    hardened.

  • utils::compute_target_quantiles, the rank-2 sibling of
    compute_target_q_values, backing up a whole (B, N) quantile vector per
    sample instead of a single bootstrap value. Introduced by the #357 fix above;
    it is public for the same reason its rank-1 sibling is, and its docs carry
    the terminal-bootstrap convention, the masking rationale, and the C51
    exclusion so both forms of the convention are findable from one place.

Changed

  • AgentStats now demonstrates its window contract instead of asserting it in
    prose
    (for #407). The type carried no doc example, so the one behaviour a
    caller has to internalise — the recent window evicts, the lifetime counters
    never do — was discoverable only by reading record(). It gains a runnable
    example showing both halves, and in-source unit tests for the two edges the
    existing suite left open: an empty AgentStats (no average, no best) and
    eviction at exactly window_size, the off-by-one the previous tests
    straddled without pinning.

  • experience.rs now says it is not the replay integration path (for #392).
    A reader landing on ExperienceTuple had no signal that it, History,
    HistoryRepresentation and SufficientStatistic are zero-consumer ADR 0003
    roadmap markers rather than the type family an agent writes transitions
    into — crate::replay::Transition is the live stored-transition model, and
    nothing in the module said so. That mistake is exactly the complaint #188
    raised, and ADR 0050 §9 answered it by promising the pointer in these module
    docs while deliberately leaving the code untouched — the doc pointer was
    the deliverable, and it never landed, so the module has read as the
    integration path ever since. The module docs now carry the signpost and
    name #95 as the issue that decides whether the four items survive at all.

    Two History contracts that were previously legible only from the source are
    now written down. Indexing panics at idx >= len() and get() is the
    fallible alternative — documented on the index method and listed in
    docs/rules.md §4 alongside History::new, which §4 requires of every panic
    site. And trace() is an O(n) deep clone of every stored transition, not a
    view; read-only callers should reach for iter(). The suggested
    as_trace()/&VecDeque reshaping was declined: iter() already serves the
    borrowed case, and returning a reference would pin VecDeque into the public
    API in exchange for renaming a method with no callers.

Removed

  • Two ReplayBufferError variants that advertised failure modes the replay
    seam cannot have
    (resolves #411). TensorConversionError(String) and
    BatchError(String) were residue of the pre-ADR-0050 TrainingBatch, which
    assembled tensors inside the buffer. ADR 0050 §3 moved that out — a
    ReplayStrategy "never sees a Tensor, a Backend, or a device" — and
    sample is the seam's only fallible method, so after the rewrite there was
    nowhere left for either variant to be returned from. Neither was ever
    constructed, in replay/ or in the memory.rs it replaced.

    No test could have caught this, and none was missing: nothing behaved
    incorrectly. The defect was the API surface itself. Read as an error domain,
    the enum told an implementor that a strategy may fail at tensor conversion or
    batch assembly, which is precisely the boundary ADR 0050 §3 draws — so the
    issue's suggested remedy of a typed #[from] rlevo_core::base::TensorConversionError
    payload was rejected: it would have handed out-of-crate implementors ?
    ergonomics for the crossing, advertising it as supported.

    This mirrors the reasoning already recorded on ReplayStrategy::sample, where
    ADR 0051 §2 kept a bad-$\beta$ variant out of the enum so UniformReplay "is not
    made to carry an error variant it could never produce"; and it is consistent
    with SampledBatch::weighted, which treats the one real batch-assembly
    failure (weights.len() != ids.len()) as a deliberate panic rather than an
    Err. The enum's rustdoc now carries this rationale, so the absence reads as
    a decision rather than an oversight.

    The same shape one layer up — TensorConversionFailed(String), declared and
    unconstructed on all eight agent error enums — is not fixed in this entry
    and was filed as #1070, which the next entry resolves. It is deliberately a separate call: agents are where
    staging happens, so deletion is not automatically the right remedy there.

  • Twenty-four agent error variants that advertised failure modes the agents
    cannot reach
    (resolves #1070 — the deferral recorded in the entry above —
    and subsumes #467 and #484, which are per-agent slices of the same finding).
    The issue was filed against TensorConversionFailed(String) on all eight
    enums; verifying it turned up two more dead shapes on the same family, plus a
    third on PPO and PPG. Three arguments, one per shape.

    TensorConversionFailed(String) is unconstructible by signature, not by
    accident. act, act_greedy, act_with and act_greedy_with all return a
    bare action, not a Result, so the host-read that could fail has no channel
    to return through. What is there instead is
    .expect("actor output is f32") — an .expect on a named invariant, which
    is the form docs/rules.md §4 sanctions for a read that cannot fail by
    construction. So the issue's second candidate remedy, wiring the staging
    sites to return the variant, is not a fix to this enum at all: it is a change
    to four public signatures, which #317 explicitly defers. The first candidate,
    #[from]-ing the core error, fails for the same reason — there is nothing to
    convert into a return value from a function that does not return one. Each
    enum's rustdoc now records that when #317 lands the variant must come back as
    #[from] rlevo_core::base::TensorConversionError, not as a String, since
    §4 prefers structured variants and names that type as the tensor-op domain; a
    re-introduced String payload would reproduce exactly the defect this entry
    closes.

    Buffer(#[from] ReplayBufferError) was unreachable by design. Every
    learn_step writes
    let Ok(batch) = self.buffer.sample(..) else { return Ok(None) };, and after
    the removal above the only variant sample can produce is
    InsufficientData — which means "skip this learn step", not "the step
    failed". Propagating it would misreport a warm-up buffer as an error.

    Io(#[from] std::io::Error) anticipated checkpointing that does not exist:
    there is no save, load, Recorder or std::fs anywhere under
    algorithms/, and ADR 0014 defers checkpointing to Tier D. On PPO and PPG,
    InvalidConfig(String) duplicated validation another type already performs —
    new returns rlevo_core::config::ConfigError, so a bad config is rejected
    before an agent exists and never reaches the agent's own error type.

    As with ReplayBufferError, no test could have caught this and none was
    missing: nothing behaved incorrectly. The defect was the API surface. Read as
    an error domain, these enums told a caller that action selection may fail,
    which the signatures say it cannot. PpoAgentError and PpgAgentError are
    left one variant wide, which is the honest width — Environment is the only
    failure their train loops surface. No new ADR is written; the rationale lives
    in each enum's rustdoc, so the absence reads as a decision rather than an
    oversight, and #[non_exhaustive] keeps the door open at no cost. The bar
    for reopening it is a real construction site, not an anticipated failure
    mode.