Skip to content

feat(experiments): add pluggable experiment lifecycle callback system - #423

Merged
Surya-5555 merged 6 commits into
ServiceNow:mainfrom
sriram687:feat/experiment-callbacks-system
Nov 18, 2026
Merged

Surya-5555 merged 6 commits into
ServiceNow:mainfrom
sriram687:feat/experiment-callbacks-system

Conversation

@sriram687

Copy link
Copy Markdown
Contributor

Experiment Lifecycle Callbacks

Closes #417

Summary

ExpArgs.run() now broadcasts structured events at five hook points, so researchers can attach monitoring, safety guardrails, and dashboard integrations without modifying any core loop code.

Motivation

As described in #417, the existing loop is a closed, synchronous black box. In practice this causes three problems:

Problem Impact
No live visibility Long multi-hour benchmark runs can't be monitored
No runtime safety guardrails Nothing stops runaway LLM token usage
No clean integration path Streaming to W&B, MLflow, Streamlit, etc. requires monkey-patching

Backward Compatibility

No existing behaviour changes. The callbacks field defaults to [], so CallbackList iterates over an empty list — zero overhead. All existing tests pass unchanged.

Verification

python -m black . --check                          →  95 files would be left unchanged.
pytest test_callbacks.py test_callbacks_cloud.py   →  60 passed in 2.38s

Usage Example

from browsergym.experiments import ExpArgs, EnvArgs
from browsergym.experiments.callbacks import ConsoleProgressCallback, BudgetLimitCallback

exp = ExpArgs(
agent_args=...,
env_args=EnvArgs(task_name="webarena.42", max_steps=30),
callbacks=[
ConsoleProgressCallback(),
BudgetLimitCallback(max_tokens=50_000),
],
)
exp.run()

PROOF OF WORK

Screenshot 2026-11-05 151525 Screenshot 2026-11-05 151512

…tLimitCallback)

- Add callbacks.py: AbstractCallback base, CallbackList dispatcher, ConsoleProgressCallback, BudgetLimitCallback
- Wire CallbackList into ExpArgs.run() at 5 lifecycle points (on_exp_start, on_step_start, on_action_selected, on_step_end, on_exp_end)
- Add callbacks field to ExpArgs dataclass (default=[]) -- 100% backward-compatible
- Export public API from experiments/__init__.py
- Add 24 unit tests in tests/experiments/test_callbacks.py (all passing)
…tream)

- Add WandbCallback: live experiment streaming to Weights & Biases
- Add MLflowCallback: experiment tracking for MLflow
- Add JsonlStreamCallback: live JSONL event streaming for web UIs and dashboards
- Add EpisodeAbortedError base exception to allow guardrails to safely abort episodes
- Add safe Windows fallback for console output in ConsoleProgressCallback
- Add 36 new unit tests in tests/experiments/test_callbacks_cloud.py (60/60 passing)
Copilot AI balanced review requested due to automatic review settings November 5, 2026 09:59

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@sriram687

Copy link
Copy Markdown
Contributor Author

@Surya-5555 kindly review the integrations.......!!!

@sriram687
sriram687 force-pushed the feat/experiment-callbacks-system branch 2 times, most recently from a0d208b to 5899276 Compare November 9, 2026 05:35
@sriram687
sriram687 force-pushed the feat/experiment-callbacks-system branch from 5899276 to 4a6f39b Compare November 15, 2026 04:26
@Surya-5555

Copy link
Copy Markdown
Collaborator

Hi @sriram687, thank you for proposing and implementing this callback system! The architecture is very clean, extensible, and well-documented.

Before this can be merged, there is one critical lifecycle bug in loop.py and a few smaller issues that need to be resolved:

  1. on_step_end is placed prematurely and skips the terminal step (loop.py:438):
    In ExpArgs.run(), _cbs.on_step_end(step_info, is_done=step_info.is_done) is currently called on line 438, which is before step_info.from_step(env, action, ...) executes the action in the environment (line 451).

    • This means on_step_end receives step_info before the environment has executed the action (reward is 0.0 or from the prior step).
    • More critically: when the action terminates the episode (step_info.terminated = True), the while loop condition while not step_info.is_done: terminates the loop immediately. As a result, on_step_end is never called for the final step. Callbacks never receive the final task reward or is_done=True.
    • Fix: Move _cbs.on_step_end(step_info, is_done=step_info.is_done) immediately after line 451 (step_info.from_step), and ensure _cbs.on_step_end(step_info, is_done=True) is also called if action is None triggers early break.
  2. Handle callbacks=None gracefully (callbacks.py:148):
    If a user explicitly passes ExpArgs(..., callbacks=None), CallbackList(None) executes list(None) on line 148, which raises an unhandled TypeError before the experiment begins. Please update CallbackList.__init__ to:

    self._callbacks = list(callbacks) if callbacks is not None else []
  3. Accumulate tokens on terminal step in BudgetLimitCallback (callbacks.py:384):
    if is_done: return returns early before line 390 adds step_tokens to self._cumulative_tokens. Please accumulate the tokens first so the final step's token consumption isn't dropped from the total.

  4. Accurate benchmark success metrics in WandbCallback and MLflowCallback:
    "final/success": int(not bool(err_msg)) marks any run without an unhandled Python exception as successful. In BrowserGym, task failure (reward 0.0) does not set err_msg. Please consider checking both not err_msg and self._cumulative_reward > 0.0 so failed benchmark episodes aren't logged as successful.

  5. Loop integration test:
    Please add an integration test that actually runs ExpArgs.run() with a callback attached and asserts that on_step_end is called with is_done=True on the final step.

Thanks again for the solid foundation and great design!

@sriram687
sriram687 force-pushed the feat/experiment-callbacks-system branch 2 times, most recently from 5fb6913 to 4a6f39b Compare November 17, 2026 16:10
- loop.py: move on_step_end to after from_step so reward/terminated
  are populated; call on_step_end(is_done=True) on action=None break path
- callbacks.py: CallbackList(None) no longer raises TypeError
- callbacks.py: BudgetLimitCallback accumulates tokens on terminal step
- callbacks.py: WandbCallback/MLflowCallback success metric now checks
  cumulative_reward > 0 in addition to no err_msg
- tests: add TestCallbackListNoneGraceful, TestBudgetLimitCallbackTerminalAccumulation,
  TestLoopOnStepEndFinalStep (29 tests total, all pass)
@sriram687
sriram687 force-pushed the feat/experiment-callbacks-system branch from 1c763e9 to 74e9ee7 Compare November 17, 2026 16:16
@sriram687
sriram687 force-pushed the feat/experiment-callbacks-system branch from b91af6f to 571946f Compare November 17, 2026 17:52
@Surya-5555

Copy link
Copy Markdown
Collaborator

Hi @sriram687, thanks for turning those fixes around so quickly!

While double-checking the updated loop.py wiring and callbacks, we caught a few remaining issues (the first actually surfaced from moving on_step_end down to line 453, sorry for not catching that nuance in the first pass!):

  1. on_step_end at loop.py:453 loses stats (tokens) and shifts step by +1: Because line 447 creates a fresh StepInfo(step + 1) before from_step(), stats (including n_token_agent_messages) stays on the previous StepInfo while reward and terminated land on the new one. As a result, step_info.stats at line 453 is always None, so BudgetLimitCallback always sees 0 tokens and never triggers, and step starts at 1 instead of 0. Please keep a reference to the previous StepInfo before line 447 and pass a combined StepInfo snapshot to on_step_end (taking step, action, agent_info, and stats from the previous object and obs, reward, raw_reward, terminated, truncated, profiling, and task_info from the new one) without mutating the objects saved to disk.

  2. ExpArgs.prepare() crashes on JsonlStreamCallback (loop.py:368-369): prepare() calls pickle.dump(self, f) to write exp_args.pkl, which raises a TypeError when JsonlStreamCallback holds sys.stdout or an open file handle. Please temporarily clear self.callbacks while dumping exp_args.pkl and restore it in a finally block.

  3. log_step_metrics=False zeroes final summaries (callbacks.py:532 and callbacks.py:718): In both WandbCallback.on_step_end and MLflowCallback.on_step_end, returning early when not self._log_step_metrics skips accumulating _cumulative_reward and _cumulative_tokens, causing on_exp_end to report 0 reward, 0 tokens, and success = 0. Please accumulate those counters first and only skip the per-step wandb.log / mlflow.log_metrics call when log_step_metrics is False.

  4. Real ExpArgs.prepare() + ExpArgs.run() test (test_callbacks.py:426): TestLoopOnStepEndFinalStep currently calls CallbackList.on_step_end() directly instead of executing ExpArgs.run(). Please update it to run ExpArgs.prepare(tmp_path) and ExpArgs.run() with a mocked agent (returning chat_messages) and mocked env (no browser needed), asserting that on_step_end receives both non-zero tokens and the final reward, that BudgetLimitCallback aborts a real run, and that JsonlStreamCallback passes prepare().

Once these are in and CI is green, this is ready to merge!

- loop.py: build merged _cb_snapshot so on_step_end receives both
  agent stats (step, action, agent_info, stats from prev step) and env
  result (obs, reward, terminated from new step); no disk objects mutated
- loop.py: pickle-safe prepare() — temporarily clears self.callbacks
  before pickle.dump, restores in finally; fixes JsonlStreamCallback crash
- callbacks.py: WandbCallback.on_step_end accumulates _cumulative_reward
  and _cumulative_tokens before the log_step_metrics guard so on_exp_end
  summaries are correct even when per-step logging is disabled
- callbacks.py: same fix for MLflowCallback.on_step_end
- tests: replace CallbackList-only simulation with real ExpArgs.prepare()
  + ExpArgs.run() integration tests asserting non-zero tokens, correct
  reward on terminal step, BudgetLimitCallback mid-episode abort, and
  JsonlStreamCallback surviving prepare() with callbacks restored
- 31 tests total, all pass; black 24.2.0 clean
@sriram687

Copy link
Copy Markdown
Contributor Author

@Surya-5555 kindly review!!!

@Surya-5555 Surya-5555 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for addressing all the feedback, @sriram687
LGTM, approving and merging now

@Surya-5555
Surya-5555 merged commit 62a678f into ServiceNow:main Nov 18, 2026
10 checks passed
@sriram687
sriram687 deleted the feat/experiment-callbacks-system branch November 18, 2026 05:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Proposal]: Add experiment lifecycle callbacks to ExpArgs in loop.py

3 participants