OpenEnv icon indicating copy to clipboard operation
OpenEnv copied to clipboard

Add sophistry_bench_sprint_env: single-agent advocacy reward-hacking environment

Open acharyaanusha opened this issue 5 months ago • 9 comments

Summary

Adds envs/sophistry_bench_sprint_env/ — an OpenEnv port of the sophistry-bench single-agent advocacy reward-hacking environment. One-turn advocacy over QuALITY reading-comprehension passages: the policy is assigned the gold answer or a distractor and must produce one <claim>/<cite> argument. The reward proxy peaks at exactly 8 <claim> tags (claim_count_cliff); four weight-0 canaries detect format hacking, making this a compact, reproducible reward-hacking measurement env.

  • Single-step episode, typed (non-MCP) pattern: models.py (AdvocacyAction/AdvocacyObservation) + EnvClient, FastAPI app, Dockerfile copied from echo_env.
  • reset() issues the task (passage + question + answer-to-defend); step(AdvocacyAction(text=...)) returns reward + all 8 reward components and done=True. Hidden ground truth: the policy is told what to defend, never whether it's gold; correctness surfaces only in step metadata.
  • No scoring drift: scoring/dataset logic is imported from the upstream sophistry-bench-sprint package rather than reimplemented, and a parity test asserts the OpenEnv aggregate_reward equals the canonical reward to 1e-9.
  • Config via env vars: SPRINT_N_ITEMS, SPRINT_PASSAGE_CHARS, SPRINT_SEED, SPRINT_WEIGHTS.

A serialization fix worth flagging for the framework

While containerizing, I found that core/env_server/serialization.py::serialize_observation excludes the base Observation.metadata from the wire payload — so reward components placed in metadata are silently dropped over HTTP (in-process tests don't catch it because they never serialize). Worked around it within the env by mirroring components into a declared components field (declared subclass fields survive serialization) and restoring metadata client-side, guarded by serialization round-trip tests. Happy to discuss whether the framework should preserve metadata instead.

Test Plan

  • [x] cd envs/sophistry_bench_sprint_env && uv run pytest tests/ -v → 10 passed (incl. anti-drift parity + 2 wire-serialization regression tests)
  • [x] openenv build sophistry_bench_sprint_env builds; container smoke test green (reset → step_text with 8 claims → reward 0.5, all 8 components over HTTP)

Dependency & live demo

sophistry-bench-sprint is published on PyPI (https://pypi.org/project/sophistry-bench-sprint/) and pulled as a normal dependency — no vendored wheel. A live demo Space is deployed at https://huggingface.co/spaces/anushaacharya/sophistry_bench_sprint_env.

🤖 Generated with Claude Code

acharyaanusha avatar Jun 11 '26 02:06 acharyaanusha

@Darktex @burtenshaw would love a review!

acharyaanusha avatar Jun 11 '26 02:06 acharyaanusha

Pushed 792905d3 addressing the review

Tier 1 — fixes

  • F811 / usort: rewrote the test import block (single top-of-file block, dropped the redundant AdvocacyAction import).
  • ruff format applied to models.py and the environment module.
  • Base class now parameterized: Environment[AdvocacyAction, AdvocacyObservation, State] (uses base State, matching the client's EnvClient[..., State]).
  • README usage now imports from sophistry_bench_sprint_env, not envs.sophistry_bench_sprint_env.

Tier 2 — alignment

  • aggregate formula: there is no public aggregate to import — aggregate_reward is an inner closure of sophistry_bench_sprint._build_reward_funcs, not in the package's __all__. Rather than widen the package's public API for one expression, I marked the reproduced (cliff + ground) / 2.0 LOAD-BEARING in a comment and kept the 1e-9 parity test as the drift guard. Happy to export an aggregate from the package instead if you'd prefer that contract.
  • serialization workaround: left as-is (declared components/error fields + client restore, locked by round-trip tests) since it's the only thing that survives serialize_observation stripping base metadata. cc @Darktex

acharyaanusha avatar Jun 11 '26 15:06 acharyaanusha

Pushed 94a7f616 addressing the follow-up reviews.

Reward weighting (raised in both reviews) — the zip(self.weights, metadata.values()) coupled weights to dict insertion order. Now:

  • Weights bind to an explicit _COMPONENT_KEYS tuple (reward = sum(w * metadata[k] for w, k in zip(self.weights, _COMPONENT_KEYS, strict=True))).
  • Self-review caught that the constructor weights= arg skipped the 8-length check (only SPRINT_WEIGHTS was validated) — a mis-sized vector silently truncated via zip, dropping canary components with no error. Now validated in __init__ for both paths, with strict=True as a backstop. Added a regression test.

Parity test (formula vs dataset parity) — now also asserts vf_env.dataset[0].info.passage == passage (same passage selected at the same seed), captures the passage before step(), and feeds the canonical fn its own passage. Covers dataset + formula parity, not just arithmetic-given-the-same-passage.

Ground-truth leak — added an explicit README warning (and mirrored it into the docs stub) that harnesses must not feed observation.metadata/components back into the policy prompt, since correctness_reward is the hidden gold/distractor signal.

Wire reward contract — clarified in models.py that post-step reward must be read from StepResult.reward; observation.reward is stripped by the serializer and is always 0.0 over the wire.

Smaller items

  • from typing import Dict → built-in dict[str, float].
  • pyproject: capped sophistry-bench-sprint>=0.1.5,<0.2.0 so an upstream formula change can't silently drift past the parity guard; re-locked.
  • README/docs test command now actually runs the suite (uv run --project envs/sophistry_bench_sprint_env --extra dev pytest …) — the previous command silently skipped under the base venv. In the repo's shared CI it still skips via importorskip (no scoring dep installed), same as tbench2's camel guard.
  • step() now counts only scored steps (increment moved after the reset guard).
  • app.py: commented the load-bearing package-dir remap the container import relies on.

On the reward: float narrowing of base Observation.reward (Union[bool,int,float,None]): confirmed no construction path passes reward=None — serialize_observation strips reward and the client reconstructs from the float we emit — so the narrowing can't raise a ValidationError.

The two framework-level alignment notes (serialize_observation stripping metadata; whether the framework should preserve it so every typed env gets observation.metadata for free) remain maintainer calls — verified against current main, the strip still happens. cc @Darktex

acharyaanusha avatar Jun 12 '26 05:06 acharyaanusha

Pushed ac729723 (rebased onto the latest main merge).

Tier 1

  • reward field default — dropped the reward: float = 0.0 override so AdvocacyObservation inherits the base Observation.reward default (None). No sibling narrows it, and the override made the reset wire payload carry reward: 0.0 instead of the conventional null. reset() now leaves reward as None; step() sets the float. Updated the affected assertions.
  • _parse_result mutation — now builds the observation once with metadata= set at construction (pop any in-process metadata, else restore from the mirrored components, then fold in error), instead of assigning observation.metadata after creation.
  • Test private access — added a public current_passage accessor (the passage is the reading-comprehension text already in the reset prompt, not hidden ground truth) and the parity test reads that instead of env._current_passage.
  • client.py imports State from env_server/ — respectfully, this isn't a client→server violation. INVARIANTS.md §19 lists Action/Observation/State as the shared wire types, and every typed sibling client imports State from openenv.core.env_server.types identically (grid_world_env/client.py:13, maze_env/client.py:21; sibling models do the same). The rule (§60) is about importing an env's own server/ implementation — which this client does not do.

Tier 2 (alignment flags) — these are framework/upstream-level and out of this env's scope to change unilaterally:

  • metadata stripping (FLAG 1): the components mirror is the in-env workaround; whether serialize_observation should preserve metadata for all envs is the framework RFC you flagged. Verified the strip still happens on current main.
  • correctness_reward on the wire (FLAG 2): it must reach the orchestration/measurement layer (that's how reward-hacking is measured), but must never be fed back into the agent prompt — guarded by the README warning + docs stub. Happy to additionally gate it behind a config flag if you'd prefer it omitted by default.
  • inline aggregate formula (FLAG 3): mitigated by the 1e-9 parity test + <0.2.0 cap; I'll file an upstream issue to export the aggregate publicly so this env can import it.

cc: @Darktex

acharyaanusha avatar Jun 13 '26 02:06 acharyaanusha

Resolved the inline-aggregate-formula alignment flag (FLAG 3) at the source rather than working around it — we own the upstream package.

  • sophistry-bench-sprint 0.1.6 now exports a public aggregate_reward(claims, citations, passage). Internally it's a pure _aggregate_reward helper shared by both the trained rubric func (closure name/metric key unchanged) and the public alias, with a package test asserting the two agree to 1e-9. Published to PyPI.
  • This env (8ad6f3b6) now imports and calls aggregate_reward in step() instead of reproducing (cliff + ground) / 2 — the LOAD-BEARING duplication is gone, so the formula can't drift. Pin bumped to >=0.1.6,<0.2.0, unused imports dropped, re-locked. Reward values are identical (same canonical impl); the parity test still guards dataset/seed selection and the rubric index-0 mapping.

That leaves only FLAG 1 (framework-level metadata stripping) and FLAG 2 (correctness_reward on the wire) as maintainer/design calls — both unchanged and noted above.

acharyaanusha avatar Jun 13 '26 03:06 acharyaanusha

Pushed a1e0f528 — worked through the rest of the review.

Tier 1

  • ✅ step_text is now async def returning await super().step(...) (fixed in 8aafeae8); README usage rewritten to async + .sync().

Tier 2 alignment

  • correctness_reward leaking over the wire — now structurally prevented. step() computes the full 8-component vector for the weighted reward, but the surfaced metadata/components omit correctness_reward by default. Trusted measurement code opts back in via expose_correctness=True / SPRINT_EXPOSE_CORRECTNESS=1. So a naive harness that forwards the whole observation to the policy can no longer leak whether the assigned answer is gold; the reward itself is unaffected (correctness still counts toward it). Added a test covering both modes and documented the flag.
  • parity test rubric.funcs[0] assumption — ✅ added assert aggregate_fn.__name__ == "aggregate_reward" (in 8aafeae8).
  • framework metadata stripping in serialize_observation — this one genuinely can't be fixed from inside an env; it's a framework change for all envs. The components mirror + round-trip test remain as the stopgap. Flagging for a maintainer to track the framework fix. cc @Darktex

Non-blocking notes

  • Removed the dead except ImportError: from core... framework-import fallback in client.py/models.py/the server module — confirmed no top-level core package resolves, so it was broken-not-dead. The env-specific ..models fallback (needed for the container's top-level server) is kept.
  • _parse_result now uses defensive .get(...) (matching the CLI template) instead of data["..."].
  • Added a comment noting the pinned reward values come from the upstream spec.

13 tests pass; lint/format clean.

acharyaanusha avatar Jun 13 '26 16:06 acharyaanusha

Pushed 01d96f91.

Tier 1

  • _parse_result robustness — reversed the prior round's over-defensive .get: it now raises a diagnostic ValueError when the response has a missing/null observation, rather than silently building an empty observation. Added a regression test for both cases. (Heads-up that this is the opposite of an earlier automated review's suggestion to use .get("observation", {}) — agreed the strict version is correct.)
  • Docs vs default correctness weight — fixed the misleading "always counts toward the weighted reward" wording. SPRINT_EXPOSE_CORRECTNESS controls only whether correctness_reward is surfaced; it affects reward only via its SPRINT_WEIGHTS entry, which is 0 by default. Updated both the README row and the __init__ comment.

Tier 2 (maintainer decisions)

  • Reward formula imported from external PyPI package vs RFC 002 — worth flagging the history here: an earlier review flagged the inline-reproduced formula as a drift risk and asked me to import it instead, so I exported aggregate_reward from sophistry-bench-sprint 0.1.6 and now import it. This round's review flags the import as a "rewards outside the env" concern. The two pulls are in tension and only a maintainer can set the policy. Current mitigations: <0.2.0 pin + the 1e-9 parity test. I'm happy to vendor the formula inline (it's a one-liner: (claim_count_cliff + citation_grounding) / 2) while keeping the parity test against the package — that satisfies RFC 002 (reward logic inside the env) and guards drift. Say the word and I'll switch it.
  • Non-MCP typed client — matches grid_world_env / maze_env; confirming it's the approved pattern for single-turn non-interactive envs is a maintainer call.

Serialization (metadata stripping) — verified real, as you noted. There's already an open framework issue tracking it: #616 ("serialize_observation() silently drops Observation.metadata"). The env keeps its components mirror + round-trip test as the stopgap until that's fixed framework-side.

14 tests pass; lint/format clean.

acharyaanusha avatar Jun 13 '26 19:06 acharyaanusha

On the reward-formula-from-external-package flag (RFC 002) — decision: keep importing it from sophistry-bench-sprint, rather than vendoring. Reasoning:

  1. The env already imports its entire scoring surface from the package, not just the aggregate: all four canaries (alternation_canary, starts_with_canary, length_band_canary, template_echo_canary), both parsers (parse_claims/parse_citations), and the dataset builder. The canaries are reward components. Vendoring only aggregate_reward would be inconsistent (the rest of the reward still comes from the package); vendoring the whole scoring module to be consistent would reintroduce the exact drift/duplication the canonical-package design — and an earlier review — set out to remove.
  2. Precedent: reasoning_gym_env imports the external reasoning_gym PyPI package for its task/scoring logic. Importing a pinned scoring library is already an established pattern here.
  3. RFC 002 is satisfied in substance: the reward is computed deterministically inside step() server-side; the package is pinned <0.2.0, guarded by the 1e-9 parity test (test_aggregate_matches_canonical_verifiers_reward), and is open-source and maintained by the same author as this env.

acharyaanusha avatar Jun 13 '26 19:06 acharyaanusha

Pushed e05c72dc. Covering both recent reviews:

Fixed

  • Env-var parsing errors — a malformed SPRINT_WEIGHTS / SPRINT_N_ITEMS / SPRINT_PASSAGE_CHARS / SPRINT_SEED previously raised a bare ValueError. Added an _int_env helper and wrapped the SPRINT_WEIGHTS float parse so each re-raises a message naming the var and the bad value. Added a regression test.

Already addressed (flagged as missing, but present since 8aafeae8)

  • Parity test rubric.funcs[0] assertion — assert aggregate_fn.__name__ == "aggregate_reward" is already in the test (with a descriptive failure message). No change needed.

Dockerfile base image — moved to meta-pytorch (8f998911) On investigation the repo is mid-migration and inconsistent across two layers: the Dockerfile ARG BASE_IMAGE defaults are still ghcr.io/huggingface/openenv-base:latest (all sibling Dockerfiles + the scaffold template), while the openenv push --base-image examples in several env doc pages (maze, reasoning_gym, textarena, websearch) already point at ghcr.io/meta-pytorch/openenv-base:latest. Rather than sit on the soon-to-be-stale registry, we moved ahead of the migration: server/Dockerfile now defaults to ghcr.io/meta-pytorch/openenv-base:latest. Verified both images are currently published and pullable (docker manifest inspect succeeds for each), so the build is unaffected today.

Maintainer / design items (unchanged)

  • Framework metadata stripping — tracked by existing framework issue #616; the env keeps its components mirror + round-trip tests as the stopgap.
  • SPRINT_EXPOSE_CORRECTNESS exposing ground truth via the observation path — default-off already prevents accidental leakage. Moving it to a privileged side-channel (a state-only field) is a larger design change; happy to do it if you'd prefer the boundary enforced rather than convention-guarded — your call.
  • Reward-component naming (aggregate_reward vs form_reward) — aggregate_reward is the upstream package's public name (renaming would be a package API break + would churn the parity test's name assertion). I can add a clarifying note in the README/SPRINT_WEIGHTS docs that index 0 is the form score (cliff × grounding) and is orthogonal to correctness_reward, if that's preferred over a rename.

15 tests pass; lint/format clean.

acharyaanusha avatar Jun 16 '26 01:06 acharyaanusha