Repository navigation
v0.5.0 — Improved harness
[0.5.0] – 2026-09-19
Breaking changes
-
TrialReport::absorb_metricsno longer overwrites a harness-owned metric
name; a caller reporting the harness's own measurements must switch to the
newabsorb_harness_metrics(resolves #1118, ADR 0079). Previously
absorb_metricswas 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 underagent/<name>
instead of<name>, with<name>listed in the new
TrialReport::displaced_metricsfield, and onetracing::warn!line at the
collision. If yourTrialimplementation 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_metricsinstead; 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.TrialReportalso gains a newpub displaced_metrics: Vec<String>field,
which breaks any external struct-literal construction ofTrialReport
(TrialReport { .. }without going throughTrialReport::new). No in-repo
construction is affected — every call site already goes through::new.
JSON reports gain adisplaced_metricskey; this is tolerant in both
directions. Nodeny_unknown_fieldsexists 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.jsoncheckpoint written by an earlier binary — which has no
displaced_metricskey at all — still resumes correctly under this
version, decoding to an empty vec. -
BenchEnv,BenchStep, andBenchErrorare removed fromrlevo-core,
along with therlevo_benchmarks::envshim 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_suitenow binds on it
directly and infersD/SD/ADfrom theSuite<E>you pass, so no
adapter and no turbofish are needed.SnapshotBase<R, Obs, Rew>supplies
theSnapshotimpl.BenchAdapteris 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_trialsandGenerationTrial. Metrics are typed, so the
singlef64rewardBenchStepcarried is no longer a constraint.
Errors that arrived as
BenchError::{Reset, Step}now arrive as
EnvironmentErrordirectly; the variant tag was redundant with call-site
context.Evaluator::run_suitekeeps 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, whileObservation/Action— what actually
differs between environments — survived it), and ADR 0076 replaced it with
theTrialseam. - An episodic environment: implement
-
ReplayBufferErrorloses itsTensorConversionError(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 exhaustivematchon 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:
ReplayBufferErrordoes not deriveserde, so no wire or config format
changes. (Other types inreplay/—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), keepingInvalidActionandPolyak.
PpoAgentErrorandPpgAgentErrordropTensorConversionFailed(String),
InvalidConfig(String)andIo(#[from] std::io::Error), keeping
Environmentand so becoming one variant wide. Twenty-four variants in
total, none of which any code in this workspace ever constructed. Migration:
as above, an exhaustivematchneeds 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 aReplayBufferErroror anstd::io::Errorinto an agent error no
longer compiles — no such site exists in this workspace, and for
ReplayBufferErrornone is possible (see below). No persisted data is
involved: none of the eight derivesserde. -
AgentStats<T>'s fourpubfields become private, behind#[must_use]
accessors (resolves #407).total_episodes,total_steps,best_scoreand
recent_historyare now read throughtotal_episodes(),total_steps(),
best_score()andrecent_history(), andrecent_history.len()becomes
recent_len(); the bound itself is readable aswindow_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 apubfield let any external callerpush_backpast the window,
or advancetotal_episodeswithout touching the history and desync the
lifetime counters from it.docs/rules.md§3 lists precisely this shape of
bound forHistoryandReplayStrategy("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::newbecomes fallible and is no longerconst: 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-environmentsbelow). The old signature waspub const fn -> Selfand
documented its own indices as unvalidated, which left the type's one real
invariant — the oneObservable::projectdereferences 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.expectreads
as the assertion it is. The loss ofconstis the sharper break:newcan no
longer initialize aconstorstaticitem, and noconst fncan 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_statenow uses, rather than laundering an unreachable
error path back to the caller. No persisted data is affected:
PixelGridStatederives onlyDebug, Clone— it has noserdederive — so
no checkpoint, replay buffer, or config format contains one.
rlevo-metrics-registry
Added
-
The canonical
skipped_updatesrow (for #346, ADR 0072). ADR 0056's
FiniteLossGuardskipsbackward()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 isRl/
PerUpdate, unit"updates",LowerIsBetter, placed immediately after
n_updatesbecause 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 oflog_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 norlevo-benchmarkschange. 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 as0, 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 isreturn/-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_reservedandmetrics::core::GENERATIONS
(for #1118, ADR 0079).is_harness_reserved(name: &str) -> boolis 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).GENERATIONSis the newpub const
key ("generations")GenerationTrialnow 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 adebug_assert!on reward finiteness. In release it compiled away
and the trial completed with aNaNorinfreturn/mean; in debug it
panicked intorun_trials'catch_unwind, whose handler replaces the trial
with a freshTrialReportmarkederrored— discarding every episode the
trial had already completed — and underfail_fastaborted the rest of the
suite. The assertion guarded nothing either way:total_reward += rewardran
unconditionally in both profiles. It is replaced by a per-trial count, one
summarytracing::warn!naming the environment and the total, and the
return/non_finite_stepscounter 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_metricswas last-writer-wins, and both
trial shapes —EpisodicTrialand the previously-untested
GenerationTrial— absorbed agent/probe output after their own
measurements, so an agent emittingreturn/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_metricsnow re-homes a
colliding key toagent/<name>, records the original key in the new
displaced_metricsfield (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 properGENERATIONSmetric-key constant, replacing a raw
string literal, and the same collision test coverageEpisodicTrialalready
had.Why the existing test missed this: ADR 0078's own
agent_metrics_are_absorbed_after_the_harness_countertest asserted, by
name, that an agent naming the exact keyreturn/non_finite_stepsshould
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 toabsorb_metrics' contract and needs its
own ADR, not a test edit." This is that ADR; the test is now inverted (and
renamedan_agent_cannot_overwrite_the_harness_non_finite_count) to assert
the harness value survives.GenerationTrialhad no collision test at all
before this change.
rlevo-core
Added
-
config::at_mostandConstraintKind::TooLarge, the upper-bound
counterparts to the existingat_least/TooSmallpair (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 everyusizecapacity field in the
workspace was validated on one side only.TooLargeis a new variant on an
existing enum and nothing in the workspace matchesConstraintKind
exhaustively, so no caller breaks. -
util::checked_combinations, a fallible counterpart tocombinations
returningOption<u64>(for #927).combinationshas to answer something
for arguments whose binomial coefficient is simply not representable, and the
only honest answers are a panic or anOption; callers that count
configurations from sizes they did not choose themselves now have the
non-panicking one. It returnsSome(0)fork > nexactly ascombinations
does, so it is a drop-in for every input the infallible helper accepts.
Changed
-
The
Rewardtrait now states its finiteness obligation, and says what the
framework does when it is broken (resolves #1115, ADR 0078). The trait
requiredInto<f32>and said nothing at all aboutNaNor 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;ScalarRewardand
Environment::step'sRewardTypegain pointers to it. No runtime check is
added, and none is deferred —Rewardis a trait, so validating one
concrete implementor closes nothing for an environment that ships its own. -
The
agentmodule'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 inlib.rssaidv0.1.x, thepub mod agentdoc
comment saidv0.3.x, and both the module's own header inagent.rsand the
crateREADME.mdsaidv0.1.0— while the workspace has been on0.4.0for
some time, so every one of them was stale regardless of which you believed.
The stamps are deleted rather than corrected to0.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.mdloses a hardcoded0.1.0for the same reason,
stating the workspace-inheritance mechanism instead of the value it currently
carries.
Fixed
-
util::combinationsreturned wrong counts — silently, in release — for
binomial coefficients that fit comfortably in au64(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 underu64::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.
Sweepingn < 200, 2603(n, k)pairs whose exact value is representable
came back corrupted this way.The fix accumulates in
u128over theC(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;combinationspanics only when the exact result exceeds
u64::MAX(first atn = 68, whereC(68, 31)and up no longer fit), a
contract now stated in its# Panics
section and in thedocs/rules.mdpanic table. The signature is unchanged.
Note that the fix rejected in the issue thread — boltingchecked_mulonto
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 atn = 63. Every
assertion sat far inside the safe regionn <= 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 contradictedabsorb_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 makingabsorb
actually accumulate was rejected: every metric name that collides in
practice (wall_clock_seconds,return/mean,generations,
success_rate) is aMetric::Scalar, not aCounter, so accumulation
would not touch the collisions that matter; it would also break
absorb's idempotence under repeated calls, andTrialReporthas 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.rsgates door-unlocking onagent.carrying
andunlock_pickup.rsgates episode success on it, sodoor_key,
unlock, andunlock_pickuphad 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_carriednow writes
the agent's own view cell asSome(agent.carrying.unwrap_or(Entity::Empty)),
called frommask_viewafter the occlusion dispatch, mirroring canonical
Minigrid'sgen_obs_gridorder (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 onEntity::Emptywith 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],GoToDoorObservationstays[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
Goaland
Lavaare both passable and the agent steps onto them before the
terminal match fires, the agent's own view cell now readsEmpty
(empty-handed) instead ofGoal/Lavaon 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_gridstate 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_validhad encoded exactly the missing
predicate since the type was written, and had zero production callers —
Observable::projectnever consulted it, andimpl 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 directprojectcall.Why the existing tests missed it:
is_valid_rejects_out_of_rangeasserted
the predicate on an out-of-range state but never projected one, and every
projecttest 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 onlyDebug, Cloneand has noserde. The real exposure was the
public unvalidatednew, which is why the fix is the fallible constructor
recorded under Breaking changes.)paint_cellis now total incell: adebug_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-usizetarget, a largecellmakes 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::resetandstepadditionally 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 finiteu8-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 pastproject, and the debug assertions
are the only thing that makes it loud.
Added
-
pixel_grid::CELL_COUNT_U32,CELL_COUNTas theu32that 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
whatis_validdid before, on the hot projection path. It replaces the
conversions inis_validand ininitial_state's fixed-placement branch; the
remainingu32::try_fromsites #545 lists convert sampled or computed
usizecell indices, notCELL_COUNT, so that issue is only partly closed.
New public API, so nothing breaks. -
Grid::try_setandGridError, a non-panicking way to write a cell whose
coordinates come from data rather than from a literal (resolves #864, #862).
Grid::setpanics 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.
ButGridis publicly re-exported, so that reasoning protects only callers
inside this workspace; a downstream layout loader had no total write path at
all.setnow delegates totry_set, giving the bounds check one home, and
GridErrorconverts intoConfigErrorandEnvironmentErrorso areset()
can?straight through it. The issue proposed-> bool; that was rejected
becausetry_*meansResulteverywhere else in the workspace,boolhere
is reserved for predicates likein_bounds, and wideningbooltoResult
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 existingx/yfields malleable: a downstream
OutOfBounds { x, y, .. }binds them by name, so the position-newtype
collapse #863 proposes stays a semver-major change.Grid::newnow rejects a
width * heightthat wraps — which would otherwise build a backing store
shorter than the grid's own extent, leavingindexfree 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.
BothGrid::new's andGrid::set's panic contracts are now listed in the
panic-contracts table indocs/rules.md. -
GridAction::try_from_indexandimpl TryFrom<usize> for GridAction, the
fallible counterpart to the trait's panickingfrom_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 throughtry_from_indexand keeps its documented panic verbatim,
and gained the# Panicssection it was missing. Aconstassertion ties the
explicit discriminants toACTION_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,
andusize::MAXcases that pin it). -
try_from_indexandimpl TryFrom<usize>forBlackjackAction,
TaxiAction,FrozenLakeActionandCliffWalkingAction(resolves #954,
#951, #971, #1093). Prospective hardening, not a live defect: the panic was
and remains the documentedDiscreteAction::from_indexcontract
(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 withUniform::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 forTaxiAction
(South 0, North 1, East 2, West 3 — neither alphabetical nor compass order)
and for the fact thatCliffWalkingAction(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 thegamesmodule,
the monomorphicSuite<E>limitation, and theBenchAdapterScalarReward
bound in terms of "v0.1" / "v0.2" / "a future milestone" —lib.rs'sgames
module doc, the crateREADME.md's Games heading and body, thebench::suites
andbench::adaptermodule headers, and thechess::environmentand
connect_fourplaceholders. The workspace has been on0.4.0since the last
release, so all of them were already false. As in therlevo-coreagent
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
Environmentimpls 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, asdocs/rules.md§9 and §12 require: thegames
module allow, which carried no pointer at all, names #1101, and the two
Rapier3DWorldaccessors —add_ground_colliderandbodies, 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 warningswithout--all-targets:
the latter compiles the test cfg, wheredead_codedoes not fire at all, and
so reports success no matter which allows are present.
rlevo-evolution
Fixed
-
A
NaNfitness 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 rawNaNwas 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 scoutlimit
($\text{pop_size} \cdot \text{genome_dim}/2$ — hundreds of generations for realistic configs);
Cuckoo escaped via abandonment, but never atp_a = 0, a valid configuration
the suite already exercises. All nine metaheuristictellimpls 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_hostseeds from$-\infty$ and compares with>, so aNaNcan neither
win a champion scan nor seed one, andbest()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.rssanitized on
the read (argtop3_max) but stored the raw value, andaco_r.rssanitized
for its archive ranking but then re-read the unsanitized vector when
materializingarchive_fitness, so aNaNsurvived 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
throughEvolutionaryHarness::step, which sanitizes beforetell, and the
convergence-style assertions that do exercise these algorithms pass happily
while a slot is frozen. The newnan_fitness_does_not_latch_without_harness
tests — one per algorithm, the bypass twin of the existing
nan_fitness_survives_harness— driveinit → ask → telldirectly and assert
on the cache rather than on convergence.Only callers who drive
Strategy::telldirectly were exposed; harness-driven
runs were never affected, and on that path the change is a provable no-op
(sanitize_fitnessis idempotent).Strategyis 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 enteringtell, not the cache it is compared against, so aNaN
placed directly into a state's fitness vector via thepub*State::try_new
constructors (orPsoState'spubfields) still freezes that slot. -
mean_fitnessstill reported$+\infty$ for a population of optimal
individuals (resolves the metrics half of #132). ADR 0034 maps a$+\infty$
fitness tof32::MAXand states that, because the clamped value is finite, it
"cannot blow amean,variance, or reward to$+\infty$ ". That guarantee did not
hold:f32::MAXpassesis_finite()and so joins the running total, and
f32::MAX + f32::MAXsaturates straight back tof32::INFINITY. Two
individuals legitimately pegging the objective in one generation were enough
to report an infinite mean.StrategyMetrics::from_host_fitnessnow
accumulates inf64and 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 thef32total 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 singlef32::MAXin the
sum is exactly the case that does not overflow. The defect needed two. -
A
NaNat index 0 permanently stranded the champion genome in GA,
binary GA, and EP (resolves the champion-tracking half of #132).
update_bestinalgorithms/ga.rs,algorithms/ga_binary.rsand
algorithms/ep.rsseeded its scan withbest_f = fitness[0]and compared
with>. Every comparison against aNaNseed is false, so the scan kept
index 0 and the champion-write guardbest_f > state.best_fitnessnever
fired — while the caller advancedstate.best_fitnessfrom the sanitising
StrategyMetrics. The two fields desynchronised:best_fitnessratcheted up
to the real winner,best_genomestayedNone, and because the ratchet was
now high, every later generation failed the guard too.Strategy::best()
returnedNonefor the rest of the run. All three now sanitise into a local
buffer and order withtotal_cmp, matching the fix already carried by
algorithms/gp_cgp.rsand satisfying ADR 0034's requirement that every
champion-write site hold the per-site correctness floor.Only callers who drive
Strategy::telldirectly could reach this —
EvolutionaryHarness::stepsanitises beforetell, so harness-driven runs
were never exposed.Strategyis public and re-exported in the umbrella
prelude, and the existing tests all went through the harness.es_classical.rs
andde.rswere checked and are unaffected: both delegate toargmax_host,
which seeds at$-\infty$ and isNaN-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 themean_fitnessdefect
above, at a site that fix could not reach:speciateandallocate_offspring
inneuroevolution/species.rsnever route through
StrategyMetrics::from_host_fitness, so widening that accumulator left these
two untouched. Both summed sanitized fitness into anf32, and two members
clamped tof32::MAXsaturate the total to$+\infty$ .The population-wide blast radius comes from
allocate_offspringinheriting
the infinity. Itsif total <= 0.0guard does not fire, because$+\infty > 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}$ , andNaN as usizesaturates to0in
Rust. Every floored share lands on zero, so the largest-remainder
reconciliation hands out allpop_sizeseats 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::tellsanitizes and then calls
speciateunconditionally, and it is NEAT's only entry point, so any
objective that can return$+\infty$ twice reaches this on the normal path.allocate_offspring'stotalalso overflows independently of the first
defect — three species whose adjusted sums are each individually finite still
saturate their total — so both accumulators needed widening, andtotal
staysf64rather than narrowing back.The blind spot was inherited too.
test_speciate_sanitizes_nan_and_inf_fitness
passes, and is correct: it covers the raw-NaNpath, which ADR 0034 genuinely
fixed. But it places a single$+\infty$ member in a species, and onef32::MAXin
a sum is precisely the case that does not overflow. The new tests pin exact
count vectors rather than asserting the total sums topop_size— that
weaker assertion holds on the buggy code, and is what let this through. -
shaping::z_scorereturned 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_scoreispub
but has no in-workspace caller yet. It squares its centred terms, so a member
atf32::MAXoverflowed its own squared term to$+\infty$ atN = 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 returnedNaNinstead. 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
f64widening the sibling fixes used:
Tensor::sum()accumulates inB::FloatElem, which the backend fixes, and
reaching anf64accumulator would force the device→host round-trip ADR 0034
introducedsanitize_fitness_tensorto avoid.z_scorenow 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$ /NaNutilities. 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 amean,variance, or reward
to$+\infty$ " has been corrected wherever it was stated (ADR 0069). It was false —
f32::MAXis finite, so it joins a sum — and it was the direct cause of
#132, #1062, and thez_scoredefect above: in each case the author read the
rule, sanitized correctly, and then accumulated inf32because the
documentation said the clamp made that safe. The claim is corrected in the
sanitize_fitnessrustdoc (the tooltip at ~90 call sites, and the surface that
misled thespeciateauthor), inrules.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 inf64and narrows at most once, afterwards; ordering,
comparison and argmax are excluded, since saturation is order-preserving. Two
pub(crate)primitives,sanitized_meanandsanitized_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 mentionsanitize_fitnessand would have gone green
through both #132 and #1062.
rlevo-reinforcement-learning
Fixed
-
SumTree::newsilently 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 thenleaf_base * 2, and the workspace
root declares no[profile]section — so release inherits
overflow-checks = falseand both operations wrap. Measured with
rustc -O: a capacity of2^62 + 1yieldednodes.len() == 0, and anything
above2^63wrappedleaf_baseto0as well. Release therefore returned
aSumTreewhose 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 unboundedwith_capacitycalls
inHistory::new,UniformReplay::newandPrioritizedReplay::neware 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 of2^30below the smallest capacity that wraps. It is enforced
throughValidatewherever aResultalready 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 recoverableConstraintKind::TooLarge
instead of dying; and as a widenedassert!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 fallibletry_newwere both rejected, matching the #190/#191 precedent
— measured,try_reserve_exactrecovers only theusize::MAXarm, which
already unwinds as a catchable panic.The issue's own premise is corrected in passing.
Vec::with_capacitydoes
not uniformly abort:usize::MAXraises a catchablecapacity overflow
panic, andwith_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, becauseoverflow-checkspanics there for its own reasons. The
newtest_sum_tree_new_rejects_capacities_that_wrapped_in_releasetherefore
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 to0wherever
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 fromv_min/v_maxand 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()accumulatedtotal_episodesand
total_stepswith plain+=, and the workspace root declares no[profile]
section — so release inheritsoverflow-checks = falseand both counters wrap
to0atusize::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
nowsaturating_add, and the accessor docs state the resulting contract — a
counter pinned atusize::MAXmeans "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 werepub: any caller could write
stats.total_steps = usize::MAX - 1and make the very nextrecord()
overflow, no long run required. Privatizing them closed that vector, leaving
only honest accumulation — roughly1.8e19steps 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 hasoverflow-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 testentirely. 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).FiniteLossGuardwarns 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 forFiniteRewardGuard— 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 runningskipped
count and re-warns on the 1st, 10th, 100th, … skip, each line carrying the
running total, adoptingFiniteRewardGuard'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 readwarning_fired(), aboolthat is
trueafter the first skip and staystrueno 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)]andpub(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== 0is not.
Added
-
UniformReplayConfig, and a fallibleUniformReplay::from_config/
ReplayKind::uniform_from_configbeside the panickingnew. Uniform
replay was the only buffer with no config type: its capacity travelled as a
bareusizeon 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::newto abort the process insideVecDeque::with_capacity
instead of returningConfigError. 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 andreplay_buffer_capacityfield
named, with theConstraintKindpassed 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 onvalidate()happening to be called before the buffer is built.
UniformReplay::new(capacity)survives for literals, on the samenew/
try_newdiscriminatorImportanceExponentandPriorityalready 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.rsis therefore a source-text
guard rather than a behavioural test: it fails on a hand-written
at_most(.., MAX_BUFFER_CAPACITY)underalgorithms/, 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). TheFixedentry
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, soskipped_updates()is both;
DdpgAgentaddsskipped_critic_updates()/skipped_actor_updates();
Td3AgentandSacAgentaddskipped_critic_1_updates()/
skipped_critic_2_updates()/skipped_actor_updates();PpoAgentadds
skipped_policy_updates()/skipped_value_updates();PpgAgentadds
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_updatesand the new
skipped_updatesmetric row carry the same relationship into the record. -
DdpgAgent::critic_updates()(for #346). Unrelated-looking, and exposed by
the work above: DDPG trackedcritic_updatesas a private field with no
accessor, unlikeSacAgentandTd3Agent, 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. -
AgentStatsis 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:AgentStatsis 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_scoreandAgentStats::non_finite_episodes
(resolves #1078, ADR 0071). An earlier review claimed "NaNpermanently
poisonsbest_score"; that claim was refuted, and #1078 opens by conceding
it —record()folds the score withf32::max, which discards aNaN
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, andbest_scoreis 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 theavg_scorecase #409 was about, which recovers
within onewindow_sizeas the offending episode rolls out. The existing
tests missed it because the twoNaNtests pinf32::max's discarding
behaviour in both operand positions and were read as covering "non-finite
scores"; they coverNaNonly, and$+\infty$ is the one non-finite value
f32::maxpropagates rather than discards. Nothing else gated it either —
rlevo-test-support'sassert_reachesandassert_improves_over_random
both readavg_scoreand neverbest_score, so a latched$+\infty$ survives a
fully green suite. It is also more reachable than it looks: ADR 0065's
FiniteRewardGuardrefuses to store a non-finite per-step reward, but all
eight training loops still accumulateepisode_reward += reward_f32
unconditionally and by design (ADR 0065 §Decision 4), so a single$+\infty$
environment reward reachesrecord()on a fully guarded agent with
dropped_transitions()reading 1 — and separately, a long episode of
entirely finite rewards can saturate thef32accumulator with no
non-finite reward anywhere anddropped_transitions()reading zero.
best_scoreis 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 overis_finite()scores
(Noneuntil something finite is recorded), andnon_finite_episodes()
counts the episodes it excluded. The predicate isis_finite()rather than
#409's!is_nan()for a reason sharper than the mean's:f32::maxalready
discardsNaNfor free, so a!is_nan()version of this accessor would be
indistinguishable frombest_scoreat every input except the one that
motivated the issue.non_finite_episodes()parallelstotal_episodes()and
is a monotone lifetime counter that never heals — deliberately unlike
non_finite_recent_len(), which parallelsrecent_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::MAXalongsidetotal_episodes/total_steps. -
AgentStats::finite_avg_scoreandAgentStats::non_finite_recent_len
(resolves #409, ADR 0070). #409 asked foravg_scoreto filterNaNout of
its mean; that change is rejected —avg_scoreis 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 intoepisode_rewardunconditionally, so the reported
curve — not justdropped_transitions()— surfaces a poisoned run, and
rlevo-test-support'sassert_improves_over_random/assert_reachesboth
gate a run's convergence check on that same value being finite; filtering
it there would let aNaN-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 nextwindow_sizeepisodes,
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_countinrlevo-evolution(ADR
0034 §Decision 4):finite_avg_score()returns the mean over the window's
finite entries (Nonewhen the window is empty or every entry is
non-finite), andnon_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 isis_finite(), deliberately stronger than #409's proposed
!is_nan():episode_rewardis anf32accumulator over a whole episode,
and a long episode of entirely finite per-step rewards can saturate it to
$\pm\infty$ with noNaNanywhere 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
-
AgentStatsnow 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 readingrecord(). It gains a runnable
example showing both halves, and in-source unit tests for the two edges the
existing suite left open: an emptyAgentStats(no average, no best) and
eviction at exactlywindow_size, the off-by-one the previous tests
straddled without pinning. -
experience.rsnow says it is not the replay integration path (for #392).
A reader landing onExperienceTuplehad no signal that it,History,
HistoryRepresentationandSufficientStatisticare zero-consumer ADR 0003
roadmap markers rather than the type family an agent writes transitions
into —crate::replay::Transitionis 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
Historycontracts that were previously legible only from the source are
now written down. Indexing panics atidx >= len()andget()is the
fallible alternative — documented on theindexmethod and listed in
docs/rules.md§4 alongsideHistory::new, which §4 requires of every panic
site. Andtrace()is an O(n) deep clone of every stored transition, not a
view; read-only callers should reach foriter(). The suggested
as_trace()/&VecDequereshaping was declined:iter()already serves the
borrowed case, and returning a reference would pinVecDequeinto the public
API in exchange for renaming a method with no callers.
Removed
-
Two
ReplayBufferErrorvariants that advertised failure modes the replay
seam cannot have (resolves #411).TensorConversionError(String)and
BatchError(String)were residue of the pre-ADR-0050TrainingBatch, which
assembled tensors inside the buffer. ADR 0050 §3 moved that out — a
ReplayStrategy"never sees aTensor, aBackend, or a device" — and
sampleis 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, inreplay/or in thememory.rsit 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 soUniformReplay"is not
made to carry an error variant it could never produce"; and it is consistent
withSampledBatch::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 againstTensorConversionFailed(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_withandact_greedy_withall return a
bare action, not aResult, so the host-read that could fail has no channel
to return through. What is there instead is
.expect("actor output is f32")— an.expecton a named invariant, which
is the formdocs/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 aString, since
§4 prefers structured variants and names that type as the tensor-op domain; a
re-introducedStringpayload would reproduce exactly the defect this entry
closes.Buffer(#[from] ReplayBufferError)was unreachable by design. Every
learn_stepwrites
let Ok(batch) = self.buffer.sample(..) else { return Ok(None) };, and after
the removal above the only variantsamplecan 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 nosave,load,Recorderorstd::fsanywhere under
algorithms/, and ADR 0014 defers checkpointing to Tier D. On PPO and PPG,
InvalidConfig(String)duplicated validation another type already performs —
newreturnsrlevo_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.PpoAgentErrorandPpgAgentErrorare
left one variant wide, which is the honest width —Environmentis 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.