Skip to content

Contributing to Ajax

This guide is for changing Ajax: setting up a checkout, where the code lives, how an agent trains, adding an agent or an extension, and the tests and checks a change goes through. To use Ajax, start with the README. CLAUDE.md holds the checks a change must pass and the refactoring rules; this guide does not repeat them. Bug reports and requests for an agent or a feature have a form each in the issues.

Development setup

uv installs a checkout with the versions in uv.lock, which CI tests, and pre-commit then runs ruff and mypy on every commit:

git clone https://github.com/YannBerthelot/Ajax.git
cd Ajax
uv sync
uv run pre-commit install

Prefix commands with uv run, or activate .venv. uv sync installs the runtime and the dev group; the other groups are opt-in (uv sync --group plane), and uv sync --no-default-groups installs the runtime alone:

Group Default What it adds
dev yes pytest, coverage, pre-commit, ruff, mypy, adastop, the probing environments the tests train on, and the playground, gymnasium, gymnasium-mjx, render and manifolds extras
wandb no the wandb extra
plane no TargetGym, for the Plane3DCircle scenario of the speed benchmark (benchmarks/perf_bench.py)
docs no MkDocs and its plugins, to build the documentation site

make docs builds the site as CI does (uv run --group docs mkdocs build --strict: a broken link, or a docstring naming a parameter the code does not have, fails it), and make docs-serve serves it at http://127.0.0.1:8000, rebuilt on save. The site needs only the docs group (uv sync --only-group docs): the API pages are read from the source, not imported.

Where things live

Architecture gives the overview. These are the pieces every agent shares:

src/ajax/
├── agents/base.py       ActorCritic: environment and network setup, extensions=, train()
├── agents/families.py   declared agents: fields as hyperparameters, the replay, incremental, on-policy, own-iteration and own-replay families
├── agents/loop.py       TrainLoop, the shared loop (brax's forced resets included)
├── agents/update_steps.py  critic_step, actor_step, compute_gradients, gradient_step, apply_gradients_clipped_together, run_if, the target update
├── agents/minibatch.py  the on-policy rollout split, minibatches and epochs
├── agents/critics.py    the Q-critics' regression (continuous and discrete actions)
├── agents/diagnostics.py  KL, explained variance, policy std
├── agents/recurrent.py  replay buffers and R2D2-style sequence replay for memory=, and PPO's networks with or without memory
├── agents/cloning.py    the behaviour-cloning loss and fit (CloningPretrain's)
├── extensions/base.py   Extension, ExtensionStack, ExtensionContext, the phases
├── environments/interaction.py  collect_experience: act, step and store
├── perf_utils.py        build_resumable_train: initialise or resume, then one jitted scan;
│                        build_chunked_train: the same in chunks, evaluating between them
├── log.py, evaluate.py  when to evaluate and log; the evaluation episodes
├── state.py             BaseAgentState, Transition, the configuration dataclasses
└── checkpoint.py        save_checkpoint, restore_into

Agent anatomy. Every agent but TDMPC2MultiTask is a declared agent: one file, src/ajax/agents/<AGENT>/<AGENT>.py, with its hyperparameters as dataclass fields, its init and update, its equations, and its state and metrics. A family of agents/families.py builds the rest: the constructor, the run config, the replay or the rollouts, the train function. The world models' folders also hold their maths by role: DreamerV3's networks, world model, actor-critic, learner, optimiser, replay and configuration; TD-MPC2's networks, one update (core.py), optimisers, planner, replay and configuration. TDMPC2MultiTask imports TD-MPC2's instead of copying them and, offline and off the families, keeps its own host loop (TDMPC2MultiTask.py) and train function (train_TDMPC2MultiTask.py). A variant imports its parent's equations from the parent's file (the lineage rule, below): APO PPO's, and TQC, REDQ, ASAC, RVI-SAC, CrossQ and AVG SAC's.

The shared training loop

The agents share one loop, TrainLoop, so collecting experience, waiting for learning_starts, applying the extensions, evaluating, logging and resuming work the same way everywhere and are fixed in one place (Architecture walks through it). An agent supplies only its algorithm:

  • init(key) -> agent_state: a fresh state. One-shot pretraining (behaviour cloning) is an extension's, on a key the loop splits off.
  • update(...) -> (agent_state, aux): one update. aux holds the metrics as flax dataclasses nested exactly one level, as TD3's AuxiliaryLogs(policy=..., value=...), logged as value/critic_loss; the logger expects that shape.

and picks one of two iterations:

  • loop.off_policy(init, update, learning_starts, ...) (the replay agents and AVG): each iteration collects one step per environment, then, from learning_starts, runs update(agent_state, transition) and folds the extensions' post_update. Before learning_starts the actions are uniform and the metrics have the update's structure, filled with NaN, which the logger drops.
  • loop.on_policy(init, update, n_steps, ...) (PPO, APO, REINFORCE, PQN): each iteration collects an n_steps rollout per environment from the agent state agent_state_at_rollout_start, then runs update(agent_state, rollout, agent_state_at_rollout_start) and folds post_update. A recurrent agent replays the rollout from that state's memory.

The loop does the rest: init and the extensions' initial state and pre-training (ExtensionStack.apply_init) on a fresh run, the given state on a resumed one, then the iterations in build_resumable_train's jitted scan. With logging, build_chunked_train runs them in chunks and evaluates and logs between chunks, every log_frequency steps (with eval_metrics). The world models (DreamerV3 and TDMPC2) give off_policy their own collect, n_updates (a train ratio, a burst) and Evaluation; UDRL runs its own iteration on TrainLoop.train, and APG and the offline TDMPC2MultiTask call build_resumable_train themselves, with fresh_state and the post_update fold.

ActorCritic.train runs the seeds at once (jax.vmap) and returns (state, evaluations): each logged key's values per seed and evaluation, kept whether or not a backend records them (only a backend starts the logging worker). With logging_config=None it does not evaluate and returns (state, None); APG returns every update's metrics instead. initial_state=state continues a run.

Continuous agents act in [-1, 1]; never scale to the env's bounds yourself. Every Ajax env step maps the action onto them (agent_action_to_env), and ActorCritic reads an expert, written in env units, in the same [-1, 1] (ExpertInAgentUnits): replay, losses and extensions see one unit.

Random keys

A key comes from a name, not from its turn in line, so a run that differs by one flag, option or extension draws every other number as before (ajax.random_keys). An agent keeps two streams, its updates' (agent_state.rng) and its collection's (collector_state.rng), each advanced once per update or collection step, carry first, for one step key (split_carry_first(rng, 1), get_keys_and_new_state()). Any other key of a step is derived from the step's: by a name registered in NAMES (derive_key), or by its index in an inner loop (fold_index). A key that exists only under a flag, an option, a condition, a count or an extension is derived, never drawn from a stream. tests/test_repo_hygiene.py refuses a fold_in at a literal index (it is a split's key) and counts the keys handed out by position (a jax.random.split, or a stream advance handing out more than one key): a new one fails, so advance a stream with split_carry_first(rng, 1) and derive its other keys.

Extensions

An extension is a research feature (an expert to learn from, an exploration rule, an extra loss term, a measurement) that plugs into any agent without changing it, so an agent's surface stays its algorithm's hyperparameters plus extensions=() (see CLAUDE.md, "Extensions are self-contained"). The extensions guide lists the ones Ajax ships, and Writing an extension shows how to write one.

An extension is a frozen dataclass subclassing Extension. It holds its own settings and overrides only the phases it touches (Extension phases lists them, with what each receives); the other phases keep their defaults, which change nothing. An agent applies a phase of its ExtensionStack in list order with one helper per phase (apply_reward, apply_on_target, compute_extensions_critic_loss, compute_extensions_actor_loss, apply_post_update; the loop calls apply_init and apply_eval_metrics), which builds the ExtensionContext (step, rng, total_steps) and threads the extensions' state. On an empty stack a helper changes nothing (a loss term is 0.0), so an agent without extensions traces nothing extra and never guards a call.

Every agent lists the phases it folds in supported_extension_phases: the shared loop's LOOP_PHASES (in ajax.agents.loop) plus those its update folds. An extension implementing any other phase is rejected when the agent is built instead of being silently ignored; tests/probing/test_extensions.py checks the phases on the agents with test-only extensions of known effect. An agent also declares in phase_batch_keys the keys its folds put in the extensions' batches beyond the common ones (COMMON_BATCH_KEYS, in ajax/extensions/base.py): an agent on critic_step and actor_step declares their sets (REPLAY_BATCH_KEYS, or TARGET_KEYS, CRITIC_LOSS_KEYS and ACTOR_STEP_KEYS with its own rows'), plus any it adds. An extension reading an undeclared key is refused when the agent is built.

What changes during training lives in agent_state.ext_state (one entry per extension), never on self: extensions are static arguments of the compiled program, so they stay hashable and unchanged. An extension that needs what the agent builds (environment, network config, buffer, discount) overrides bind_to_agent(**agent_context) to return a new instance holding it, as MCPretrain does; a declared agent's family binds the stack to the keys of the agent's extension_context (DeclaredAgent.make_context).

Adding an agent

Boilerplate goes in the shared code; the algorithm goes in one file, so a reader can follow the agent's file (<AGENT>/<AGENT>.py for a declared agent) like the paper's pseudocode. Lineage rule: an agent imports from another agent only when it is a variant of that agent's algorithm (REDQ of SAC, APO of PPO), and then only the parent's equations. Anything else two agents share (an init, a network, a loss helper, an exploration schedule) goes to a shared module: agents/update_steps.py, agents/minibatch.py, agents/critics.py, agents/diagnostics.py, networks/. A shared module imports no agent. tests/agents/test_agent_imports.py holds the lineages and each parent's equations, and fails on any other cross-agent import. Use critic_step (a replay critic step), actor_step (an actor step), gradient_step (an optimiser step), compute_gradients (a loss's gradients) and apply_gradients_clipped_together (two networks stepped on one clip) from agents/update_steps.py rather than writing your own.

A new agent FOO declares itself on a family of agents/families.py:

Family For an agent that As Read first
ReplayAgent learns from a replay SAC, TD3, REDQ, ASAC, RVI-SAC, CrossQ, TQC, IQL, DQN, DAgger agents/IQL/IQL.py
IncrementalAgent updates on each step as it comes, without a replay AVG agents/AVG/AVG.py
OnPolicyAgent learns from rollouts PPO, APO, REINFORCE, PQN agents/PPO/PPO.py, and the on-policy family below
OwnIterationAgent runs an iteration of its own UDRL, APG the own-iteration family below
OwnReplayAgent stores rows in a replay of its own, sized for each call DreamerV3, TD-MPC2 the own-replay family below

Start with a tracer bullet. Get the thinnest path working end to end first: rollout, update, logging, checkpoint and one passing probe, on the simplest config, in the real loop and in CI. Then add paper fidelity one piece at a time, each with its conformance check or probe. The steps below list what an agent needs; this is the order to build it in.

1. FOO/FOO.py, the one file. Its hyperparameters are the fields of a dataclass, declared once with the paper's defaults: the family generates the constructor (keyword-only after env_id), logs the run config, builds the optimisers, the replay and the train function (ReplayAgent.make_train, on loop.off_policy; an on-policy agent's is OnPolicyAgent.make_train, on loop.on_policy). The file reads top-down: the class, its equations in the order update calls them, then its state and metrics. The template below is a replay agent's; an on-policy agent's file has the same parts.

@dataclass(kw_only=True, eq=False, repr=False)  # literal: the API docs read it
class FOO(GradientClipping, ExpertGuided, ReplayAgent):
    """FOO (Author et al., year): the paper's algorithm box, each line one
    function below."""

    gamma: float = 0.99
    tau: float = 0.005
    reward_scale: float = 1.0
    buffer_size: int = int(1e6)
    batch_size: int = 256
    learning_starts: int = int(1e4)

    def init(self, key, context):
        training_key, init_key, collector_key, evaluation_key = jax.random.split(key, 4)
        actor_state, critic_state = context.make_actor_critic(
            init_key, continuous=True, action_value=True, num_critics=2
        )
        return FOOState(
            rng=training_key, eval_rng=evaluation_key, actor_state=actor_state,
            critic_state=critic_state,
            collector_state=context.make_collector(collector_key),
        )

    def update(self, agent_state, context):
        sample_key, critic_key, actor_key, agent_state = (
            agent_state.get_keys_and_new_state(3)
        )
        batch, _ = sample_replay(agent_state, context.buffer, sample_key)
        target = compute_foo_target(agent_state, batch, self.gamma, self.reward_scale)
        critic_state, critic_aux, _, critic_metrics = update_steps.critic_step(
            agent_state, batch, target,
            partial(compute_foo_value_loss, agent_state.critic_state, batch),
            context.extensions, critic_key, context.total_timesteps,
            rewards=batch.reward, dones=batch.terminated,
            gamma=self.gamma, reward_scale=self.reward_scale,
        )
        actor_state, actor_aux, _, actor_metrics = update_steps.actor_step(
            agent_state, partial(compute_foo_policy_loss, agent_state),
            context.extensions, actor_key, context.total_timesteps,
            batch, agent_state.critic_state,
        )
        agent_state = agent_state.replace(
            actor_state=actor_state,
            critic_state=critic_state.soft_update(tau=self.tau),
            n_updates=agent_state.n_updates + 1,
        )
        metrics = merge_metrics(critic_metrics, actor_metrics)
        return agent_state, AuxiliaryLogs(
            value=critic_aux, policy=actor_aux, extensions=metrics
        )

    # The contract, unannotated (an annotation would make it a field).
    name = "FOO"
    capabilities = frozenset({"actor", "discounted", "off_policy", "q_critic", "replay"})


# FOO's equations, in the order update calls them; a function returning a
# loss or a target value starts with compute_.
def compute_foo_target(agent_state, batch, gamma, reward_scale): ...  # -> target
def compute_foo_value_loss(critic, batch, params, target): ...  # -> (loss, aux)
def compute_foo_policy_loss(agent_state, params): ...  # -> (loss, aux, pi_mean)


@struct.dataclass(kw_only=True)
class FOOState(BaseAgentState):
    """FOO carries only actor + critic + collector."""

A declared agent has no <AGENT>Config: its fields are its configuration.

init splits the run's key on the agent's own layout, which its pins hold. update_steps.critic_step applies on_target and critic_loss; its keywords are what the target used (dones: where it cut the bootstrap). update_steps.actor_step applies actor_loss; its keywords are the rows the extensions read. Both derive the extensions' keys from the step's (Randomness), so the agent's own random stream is the same with or without extensions.

The train context. init and update take a TrainContext (agents/families.py) as context: what one train() call gives the agent beyond its fields, which are fixed once it is built. It holds the env and the network and optimiser configs (make_actor_critic builds the networks on them), the extensions bound to the run, the replay buffer, how to build the collector (make_collector), the horizon, whether the run is recurrent and the residual-action hook. Other libraries keep these as attributes of the agent (SB3) or in closures (PureJaxRL); here they are passed explicitly, so one agent trains any number of runs and a test calls init or update alone on agent.make_context(n).

An agent writes init(key, context) and update(agent_state, context) (an on-policy agent's update(agent_state, rollout, agent_state_at_rollout_start, context)), and may add these hooks; each is a no-op on the family, which does its own part outside them, so none calls super(). A hook that builds an object is named make_ (the family's own: make_context, make_collector, make_replay_buffer), one that declares settings is a noun read as a property of the agent (actor_critic_args, optimizer_settings), and the others say what they do:

  • check() refuses arguments before anything is built;
  • actor_critic_args() returns ActorCritic arguments the paper fixes or derives from the fields (initialisations, heads; CrossQ's learning rates and widths); it may only fill a field the caller left None (TypeError otherwise), as PPO's encoder_kernel_init does;
  • optimizer_settings() returns the OptimizerConfig settings of the reference's optimiser (its Adam's eps, its betas): the family sets none, so an agent states its reference's;
  • setup() derives or checks what needs the built env and networks (IQL's value optimiser, PPO's rollout split checks), after the family has built the replay;
  • choose_behaviour(context) replaces collection's action pipeline.

The family reads some fields by name. ReplayAgent requires buffer_size, batch_size and learning_starts; an agent claiming the discounted capability declares gamma and reward_scale, which the evaluation's value estimate reads (construction refuses it otherwise); expert_policy (the ExpertGuided mixin) is the agent's expert; and every field named like an ActorCritic.__init__ argument (actor_learning_rate, critic_architecture, ...) reaches it, so a misspelt one is a field that reaches nothing. The shared knobs an algorithm takes beyond those every agent takes are mixins (GradientClipping, ObservationNormalization, RewardNormalization, ExpertGuided), and RecurrentReplayAgent adds memory= with R2D2's sequence replay. Once built, an agent's fields are fixed: dataclasses.replace(agent, gamma=0.9) builds another.

The on-policy family. OnPolicyAgent.make_train runs loop.on_policy: each iteration collects n_steps per env, then calls update(agent_state, rollout, agent_state_at_rollout_start, context) on the (n_steps, n_envs) rollout and the agent state it was collected from (a recurrent agent replays the rollout from its memories). The family requires n_steps, n_epochs and num_minibatches, reads brax's num_resets_per_eval and num_evals where an agent declares them, and adds the evaluation_options() hook (APO's avg_reward_mode). agents/minibatch.py runs the passes (run_epochs); PPO's choose_rollout_split returns the RolloutSplit that says how its rollout is cut and where the advantages are computed, while APO and PQN shuffle single steps. PPO never asks whether its networks have memory: agents/recurrent.py's compute_rollout_values (the values GAE reads), get_policy_on_minibatch and predict_values_on_minibatch (the networks in its losses) run a network with memory over its sequences and one without as an ordinary forward pass. ImageObservations adds the CNN encoder's fields; train_offline refuses an on-policy agent.

The own-iteration family. OwnIterationAgent.make_train runs loop.train on the agent's own iteration: iterate(agent_state, context) acts and learns its way and applies the extensions' post_update where its order puts it, report(agent_state, aux) gives the training metrics an evaluation logs, evaluation_metrics(agent_state, key, context, num_episode_test) its policy's, and steps_per_iteration(context) the env steps one iteration takes. A train call's options go to configure_call(context, n_iterations, ...), which returns the call's context and how a resumed state is transformed (APG's schedule and optimiser rebuild); an agent returning every iteration's output (returns_iterations, APG's per-update metrics) says what it is in iteration_output. train_offline refuses it.

The own-replay family. OwnReplayAgent runs loop.off_policy on the agent's own tick. Once train has checked the call (a horizon that ends before it is refused), its prepare_call asks prepare_replay(start_tick, end_tick, agent_state) for the call's replay (sized for the call, a resumed state's replay moved into it), which make_train puts in context.buffer. Each tick, collect(agent_state, tick, context) stores one row per env, count_updates(agent_state, tick, context) gives the updates of the absolute tick (DreamerV3's train ratio, TD-MPC2's seed-phase burst) and update(agent_state, tick, context) runs one; report and evaluation_metrics are as in the own-iteration family. An agent may count its ticks its own way (count_ticks), restart what it logs after each log (make_after_log) and check a finished call (check_run, TD-MPC2's refusal of terminations). It assumes the row collector: a resumed run starts at the tick of the rows it counted. train_offline refuses it.

Do not add a field for a feature (use_critic_blend=True, ...): it belongs on an extension.

2. Export and document. Import it in src/ajax/__init__.py and add it to __all__. Give it a page under docs/algorithms/ (and in mkdocs.yml's nav), and name it where the documentation lists the agents: the README's Agents section, the algorithms index, the docs home and the memory table, which tests/test_readme.py holds to __all__, and the marked lists that tests/test_docs_agent_sets.py holds to the code.

3. Tests and benchmark. tests/agents/FOO/: the maths on hand-computed values. tests/agents/test_agent_contract.py: a row, so FOO builds, refuses what it cannot act in and folds extensions on tiny runs. tests/probing/: presets in agents.py, then the cases that fit (test_framework.py fails while an exported agent has none). tests/agents/test_agent_pins.py: a tiny run's fingerprint, so a later restructuring can show it changed nothing. benchmarks/agent_bench.py: an entry in AGENTS and a baseline (see Performance).

Adding an extension

Add an extension, never a flag or a keyword on an agent. Start with a tracer bullet: the smallest phase that does something visible, on one agent, with one probe cell. Then build out the rest one piece at a time.

  1. Pick the phases from Extension phases and check that the agents you target fold them (their supported_extension_phases). If one does not, adding the fold to that agent is a change of its own, and the agent still must not know about your extension.
  2. Write the dataclass in src/ajax/extensions/<topic>.py, its settings as fields. This one counts updates and logs the count; it runs as is:
from dataclasses import dataclass

import jax.numpy as jnp

from ajax import PPO
from ajax.extensions.base import Extension
from ajax.logging import LoggingConfig


@dataclass(frozen=True)
class UpdateCounter(Extension):
    """Counts the updates and logs the count at each evaluation."""

    name: str = "update-counter"

    def init_state(self, agent_state, rng):
        return jnp.asarray(0)

    def post_update(self, agent_state, ext_state, context):
        return agent_state, ext_state + 1

    def eval_metrics(self, agent_state, ext_state, rng, context):
        # A float: the steps that do not evaluate log NaN in its place.
        return {"Counter/updates": ext_state.astype(jnp.float32)}


agent = PPO("CartPole-v1", n_envs=4, n_steps=128, extensions=(UpdateCounter(),))
logging = LoggingConfig(log_frequency=1_024, backends=())
state, evaluations = agent.train(seed=[0, 1], n_timesteps=4_096, logging_config=logging)
print(state.ext_state[0])  # the updates each seed made, one per rollout of 512 steps: [8 8]
print(evaluations["Counter/updates"])  # a row per seed: [[2. 4. 6. 8.] [2. 4. 6. 8.]]
  1. Test it in tests/extensions/: the feature fires and does what its paper says (a metric appears, a term moves the loss the right way).

Callable hooks. A few Optional[Callable] keywords predate extensions and stay: TD3's action_pipeline (AjaxExperiments' TD3 variants), DQN's td_target_fn and td_loss_fn and PQN's td_loss_fn (Double DQN and Huber, which their agents' tests run). tests/modules/test_hook_composition.py pins them. Add none.

Testing

Two kinds of tests check the code, each answering its own question (Testing is the full guide):

  • Unit tests (tests/<area>/, tests/agents/<AGENT>/) check one component against an exact contract, with no learning. Where agents or extensions share a contract, the test is generic (tests/agents/test_*_contract.py, tests/extensions/test_phase_contract.py, ...): it runs every one of them, and a new one fails it until it joins.
  • Probing tests (tests/probing) train an agent briefly on a tiny generic environment whose answer is known, and check only what learning shows: the right value, the right action, the right count.

Every test names the realistic bug it would catch, in its name or docstring. If you cannot name one, do not write the test. When a concern deserves protection, add a planted fault and make sure a test catches it.

A setting copied from a reference implementation (an ordering, a default, a constant) may have a test, which cites the reference. Whether a setting should follow the reference is for code review. Pins record what a tiny run produces today, so a restructuring can show it changed nothing: tests/agents/test_agent_pins.py (tiny runs' fingerprints), tests/agents/test_agent_surface.py (every public name the agent modules define, and each agent's run config), tests/extensions/test_sac_extensions_equivalence.py and tests/test_downstream_api.py (the names downstream projects import). The fingerprints hold to 1e-3 across platforms; on one machine, uv run python -m tests.exact_pins record DIR, then compare DIR after the change, shows a restructuring bitwise: every leaf of tiny runs' final states, their logged evaluations and the text of their training programs' jaxprs. Slow tests (@pytest.mark.slow) are the long trainings.

The tests come in two tiers. The fast tier is the tests not marked slow: every pull request must pass it. A fast test may run a tiny training, of at most 128 gradient steps: tests/conftest.py counts each test's gradient steps (the larger of the agent's update count and each train state's step) and fails a fast test past the line (AJAX_FAST_MAX_UPDATES); a test that trains belongs in tests/probing, or is marked slow. It also times each test and lists those past 30 s (AJAX_FAST_MAX_SECONDS) without failing them: compiles, not trainings, set those times. The slow tier is everything that trains: tests/probing, which tests/conftest.py marks slow but for the harness's own checks, and the tests marked slow elsewhere; a workflow of its own runs it (below).

Every directory of tests/ that holds Python files is a package (an empty __init__.py; tests/test_repo_hygiene.py checks it), so tests import shared helpers by their full name: from tests.agents.extension_stubs import CounterExt. The benchmark scripts the tests import are on the path through pythonpath in pyproject.toml.

uv run pytest --collect-only -q   # everything imports and collects
uv run pytest tests/agents/TD3    # the tests of what you changed
uv run pytest -m "not slow" -n auto   # the fast tier, a worker per core
make ci       # the pull-request gate: ci-precommit, ci-test, ci-conformance, docs
make ci-all   # the gate and the slow tier (ci-slow)

The make targets hide the GPU (CPU_ENV) so tests never compete with a running experiment; elsewhere set JAX_PLATFORMS=cpu while a GPU is busy.

CI (ci.yml) runs on CPU for every pull request and push to main: pre-commit, the fast tier in six shards under coverage (at least 90%, combined), the conformance checks and the strict docs build. Lint and Test, the one check branch protection requires, passes only when all of them passed. The Slow tier workflow (slow.yml) runs everything that trains, on x86, the platform most users train on: daily on main when main changed, by hand, and on a pull request each time the label run-slow-tier is added. A pull request that changes how an agent trains gets the label before it merges. How CI splits the suite gives the jobs and their shards; make file-durations and make durations refresh the recorded times the shards are split by.

The probing tests

A unit test checks a contract; it cannot show that an agent learns what it should. A probe trains an agent on a tiny problem whose answer is known exactly (a value, a best action, a count) and compares what it learned with the right answer and named wrong ones (a discount applied twice), so a failure names the mistake. The probing framework describes the harness, its verdict over seeds, calibration and digests. A known bug stays visible as a strict xfail naming the defect, never as a looser tolerance.

A planted fault (tests/probing/faults/<family>.jsonl) quotes the source it edits, so any change under src/ajax can break one: such a change runs tests/probing/test_framework.py locally before the push (text and collection only, no training). As the gate runs no probe, every fault names in its fast field the fast tests that catch it, measured by planting it in a scratch copy and running the fast tests that execute its lines (uv run python -m tests.fault_catches SCRATCH [FAMILY ...]). A new fault comes with its fast catch, and JAX_PLATFORMS=cpu uv run python -m tests.probing.faults SCRATCH ID shows each node it lists failing on an assertion, not crashing (Planted faults).

Performance

CLAUDE.md ("Performance no-regression guardrail") sets the rule; here is the check. benchmarks/agent_bench.py times a fixed run per agent; --compare fails when one is slower than --tol (10% by default) against a baseline. Capturing requires --out, so a quick check never overwrites the baseline.

export JAX_PLATFORMS=cpu
uv run python benchmarks/agent_bench.py --only TD3 --out benchmarks/my_change.jsonl
uv run python benchmarks/agent_bench.py --compare benchmarks/agent_baseline.jsonl benchmarks/my_change.jsonl

Dependencies and releases

Ajax is a library: pyproject.toml says which versions work, and uv.lock fixes the ones CI and development use. Users' installers never read the lock.

  • Floors only. Each lower bound is the oldest version Ajax works with. Raise it when Ajax needs something newer or an older version is known to break, with a comment saying why. Add an upper bound only after a known break, with its reason, and remove it once Ajax is fixed.
  • The ranges are tested. The Compatibility workflow (compat.yml) runs the tests not marked slow every Monday, and on pull requests that change the dependencies, twice without the lock: at the newest versions allowed, on the newest Python, and with every direct dependency at its floor (uv sync --resolution lowest-direct), on the oldest. Each runs split across six runners by file, from the recorded times CI's test shards use. A third job installs Ajax without extras or groups and trains a gymnax agent (tests/test_core_install.py).
  • The lock is refreshed monthly by Dependabot (dependabot.yml), the JAX stack in one pull request.
  • Python: 3.12 and newer, the versions JAX supports. A version goes when JAX drops it.
  • Releases. Versions follow semantic versioning; before 1.0, a breaking change (a raised floor, a removed keyword) bumps the minor version. A release is an entry in CHANGELOG.md and a vX.Y.Z tag on main, which downstream projects can pin. Public names change by expand then contract (CLAUDE.md, rule 10). Tags come only from the Release workflow (release.yml, by hand, with the version), on main's head. Each job needs the one before it:
    • check: the CHANGELOG entry, pyproject's version, no tag yet;
    • slow: the slow tier green on that commit, run first if needed;
    • compat: the Compatibility jobs (newest and floors) green on that commit, run each time;
    • package (package.yml): the wheel and the sdist built once and checked, then the wheel installed in fresh environments outside the checkout, on Python 3.12 and 3.14: the README and docs examples run against it (tests/doc_examples.py, the docs tests' extraction), and each extra, installed alone, runs its smoke test (tests/release_smoke.py). Pull requests that change the packaging run it too;
    • tag vX.Y.Z, then publish those same files to PyPI as ajax-rl (trusted publishing, no token);
    • github-release: the GitHub Release of the tag, its notes the version's CHANGELOG entry, the published files attached;
    • docs: the site's version X.Y, the one it opens on (docs-deploy.yml; main's is the site's dev version);
    • verify: ajax-rl==X.Y.Z installed from PyPI, retried for up to 20 minutes, runs the README's examples; a failure opens an issue.

Style

Pre-commit (.pre-commit-config.yaml) runs on every commit and in CI: ruff lint with rules I F E W B C RUF ARG (ARG, unused arguments, is off under tests/), ruff-format (settings in pyproject.toml), and mypy on everything but benchmarks/, run in the project's environment (uv run mypy) so it sees jax and flax.