Skip to main content

RolloutGatewayMixin

Opt-in mixin that replaces CliAgentEnv’s client-side interception with a server-side gateway path, allowing agents to communicate directly with prime-rl’s rollout gateway.
RolloutGatewayMixin is experimental and subject to breaking changes. The API may change in future releases.

Overview

When the gateway is active, agents talk directly to prime-rl’s rollout gateway through a Prime Tunnel. The environment only manages sandbox lifecycle and fetches the trajectory after completion. When inactive, it falls through to CliAgentEnv’s standard interception path. Key differences from standard CliAgentEnv:
  • Agent makes API calls directly to the gateway server (not intercepted by local proxy)
  • Environment registers/unregisters rollouts with the gateway
  • Trajectory is fetched from the gateway after agent completion
  • Requires prime-rl’s rollout gateway to be running

Method Resolution Order (MRO)

The mixin should be placed before CliAgentEnv in the inheritance chain.

Usage

Basic Setup

Disabling Gateway Mode

Attributes

bool
default:"True"
Toggle gateway mode. When True, uses server-side gateway. When False, falls through to CliAgentEnv interception.
int
default:"8000"
Port where the rollout gateway server is listening.

Methods

init_gateway

Initialize gateway resources. Call in __init__ when use_gateway=True.
int
default:"8000"
Port for the rollout gateway server.
float
default:"21600.0"
HTTP timeout for gateway requests (6 hours by default).
Initializes:
  • HTTP client with configured timeout
  • Tunnel management dict
  • Tunnel lock for thread-safe access
  • Tunnel monitor task reference

init_interception

Overrides CliAgentEnv.init_interception(). Only calls parent implementation when use_gateway=False.

register_rollout

Registers the rollout with the gateway server.
State
required
Current rollout state.
Sends to gateway:
  • Model name
  • Sampling parameters
  • Max turns
  • Max sequence length
Endpoint: POST /v1/rollouts/{rollout_id}/register

unregister_rollout

Unregisters the rollout from the gateway server.
State
required
Current rollout state.
Endpoint: POST /v1/rollouts/{rollout_id}/unregister

fetch_trajectory

Fetches the trajectory from the gateway after agent completion.
State
required
Current rollout state. Updated with trajectory data.
Updates state with:
  • trajectory: List of conversation turns
  • prompt: Final prompt messages
  • completion: Final completion messages
  • is_truncated: Whether any turn was truncated
Endpoint: GET /v1/rollouts/{rollout_id}/trajectory

build_env_vars

Override to set OPENAI_BASE_URL from rollout_base_url in gateway mode.
State
required
Current rollout state.
Returns: Environment variables dict with:
  • OPENAI_BASE_URL: Points to gateway rollout endpoint
  • OPENAI_MODEL: Model name from state
  • OPENAI_TIMEOUT: Set to “600”
  • OPENAI_REQUEST_TIMEOUT: Set to “600”
  • HTTPX_TIMEOUT: Set to “600”
  • Plus any variables from self.environment_vars

get_gateway_tunnel_url

Get or create a Prime Tunnel for the gateway connection. Automatically restarts dead tunnels.
str | None
default:"None"
Local address for the tunnel. Required when starting first tunnel or when multiple tunnels are active.
Returns: Tunnel URL (e.g., "https://xxx.prime-tunnel.com"). Behavior:
  • Creates new tunnel if none exists for local_addr
  • Reuses existing tunnel if alive
  • Restarts dead tunnels automatically
  • Starts health monitor on first tunnel creation

start_agent

Starts the agent command as a background job. In gateway mode, skips the background completion monitoring task (handled by wait_for_agent_completion).
State
required
Current rollout state.
Updates state:
  • background_job: Background job handle
  • agent_start_time: Start timestamp
  • agent_completed: Set to False

poll_job_completion

Polls until background job completes, capturing output and monitoring tunnel health.
State
required
Current rollout state.
str
required
Prime Sandbox ID.
required
Background job handle from sandbox client.
Updates state on completion:
  • agent_exit_code: Process exit code
  • agent_stdout: Captured stdout
  • agent_stderr: Captured stderr
Raises:
  • TunnelError if tunnel dies during polling

wait_for_agent_completion

Waits for agent completion with timeout.
State
required
Current rollout state.
Updates state:
  • agent_completed: Set to True when done
  • agent_timed_out: Set to True if timeout exceeded

rollout

Main rollout method. When use_gateway=True, orchestrates gateway-based rollout. Otherwise, delegates to parent CliAgentEnv.rollout().
RolloutInput
required
Rollout input data.
Client
required
LLM client (base URL used to determine gateway URL).
str
required
Model identifier.
SamplingArgs | None
default:"None"
Sampling parameters.
Returns: Final rollout state. Gateway mode flow:
  1. Initialize state
  2. Register rollout with gateway
  3. Resolve tunnel local address
  4. Start or reuse Prime Tunnel
  5. Create sandbox with OPENAI_BASE_URL pointing to gateway
  6. Start agent
  7. Wait for agent completion
  8. Fetch trajectory from gateway
  9. Cleanup (unregister, destroy sandbox)

teardown_gateway

Teardown hook that closes HTTP client, stops tunnels, and cancels health monitor. Decorated with @vf.teardown to run automatically. Cleans up:
  • HTTP client connection
  • All active Prime Tunnels
  • Tunnel health monitor task

State Keys

Gateway mode adds these state keys:
str
Unique identifier for the rollout (format: "rollout_{uuid}").
str
Base URL of the gateway server (derived from client base URL).
str
Full rollout endpoint URL: {tunnel_url}/v1/rollouts/{rollout_id}.
str
Prime Tunnel URL.
str
Local address for tunnel connection.
str | None
Prime Tunnel ID for debugging.
Plus all state keys from CliAgentEnv:
str
Prime Sandbox ID.
Background job handle.
bool
Whether agent process finished.
int
Agent process exit code.
str
Captured stdout.
str
Captured stderr.
bool
Whether agent exceeded timeout.

Tunnel Health Monitoring

The mixin automatically monitors tunnel health in the background:
  • Runs every 30 seconds by default
  • Detects dead tunnels via tunnel.is_running
  • Automatically restarts dead tunnels
  • Logs frpc output for debugging
  • Started lazily on first tunnel creation
  • Cancelled on teardown

Error Handling

Tunnel Errors

Gateway Errors

Cleanup Guarantees

The mixin ensures cleanup even on errors:
  • Unregister rollout (if registered)
  • Destroy sandbox (if created)
  • Errors during cleanup are logged but don’t raise
  • Any cleanup error is captured in state["error"]

Logging

The mixin provides detailed structured logging:
Log stages:
  • stage=start: Rollout initiated
  • stage=register_rollout: Gateway registration
  • stage=resolve_tunnel_local_addr: Tunnel address resolution
  • stage=start_tunnel: Tunnel creation
  • stage=create_sandbox: Sandbox provisioning
  • stage=start_agent: Agent launch
  • stage=wait_for_agent_completion: Agent monitoring
  • stage=fetch_trajectory: Trajectory retrieval
  • stage=tunnel_died: Tunnel failure
  • stage=agent_completed: Agent exit
  • stage=finish: Rollout completion

Advanced Example

When to Use Gateway Mode

Use gateway when:
  • Running distributed rollouts with prime-rl’s gateway server
  • Need server-side trajectory management
  • Want centralized rollout coordination
  • Prefer gateway-managed model inference
Use standard interception when:
  • Running local rollouts without gateway infrastructure
  • Need client-side interception for debugging
  • Want simpler setup without gateway dependencies

See Also