Skip to content

feat(runner): auto-register for sidecar deployments + fix context window tool calls - #165

Merged
risjai merged 2 commits into
masterfrom
rjain/runner-auto-register-and-context-fix
May 10, 2026
Merged

risjai merged 2 commits into
masterfrom
rjain/runner-auto-register-and-context-fix

Conversation

@risjai

@risjai risjai commented May 10, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Runner auto-registration for sidecar deployments: RunnerConfig.auto_register() POSTs to /api/runners on startup with retry logic (10 attempts, 2s delay). Activated via REWIND_RUNNER_AUTO_REGISTER=1 env var. Solves the emptyDir bootstrap problem where each pod restart creates a fresh SQLite DB — runner registrations are lost and a pre-provisioned K8s secret token never matches the new DB. With auto-register, the runner self-registers on every startup and uses the returned token directly.

  • Context window renders tool calls: MessageView was silently dropping assistant messages that had tool_calls/tool_invocations but empty content (standard behavior when an LLM decides to call a tool instead of responding with text). The dashboard showed a blank ASSISTANT bubble. Now the Rust backend passes through tool_calls/tool_invocations fields, and the React frontend renders them as styled function-name + arguments blocks.

Changes

File What
python/rewind_agent/runner.py RunnerConfig.auto_register() classmethod + from_env() fallback to auto-register when REWIND_RUNNER_AUTO_REGISTER=1
crates/rewind-web/src/api.rs MessageView gains optional tool_calls / tool_invocations fields; extract_messages keeps empty-content messages that carry tool call data
web/src/components/StepDetailPanel.tsx ContextWindowView renders tool_calls/tool_invocations as violet-styled blocks with function name + pretty-printed args

Context

Discovered during ray-agent sidecar deployment in dev1. The replay flow was fully wired (webhook handler, HMAC verification, dispatch) but:

  1. Runners couldn't persist across pod restarts (emptyDir → fresh DB → token mismatch)
  2. Successful replays showed blank assistant bubbles in the context window because tool-call-only messages were dropped

Test plan

  • cargo check --package rewind-web passes
  • Verify context window shows tool call blocks (not blank) for assistant messages with tool_invocations
  • Set REWIND_RUNNER_AUTO_REGISTER=1 with REWIND_URL pointing to a running server — verify runner appears in /api/runners
  • Verify retry logic by starting the agent before the rewind server (should succeed after sidecar starts)
  • Verify from_env() still works with explicit REWIND_RUNNER_TOKEN (no regression)

Made with Cursor

…dow tool calls

Two related fixes discovered during ray-agent sidecar deployment:

1. **Runner auto-registration** (`python/rewind_agent/runner.py`):
   Added `RunnerConfig.auto_register()` that POSTs to `/api/runners`
   on startup with retry logic. Activated via `REWIND_RUNNER_AUTO_REGISTER=1`.
   Solves the emptyDir bootstrap problem where each pod restart creates
   a fresh SQLite DB, losing runner registrations — the token from a
   pre-provisioned K8s secret never matches the new DB. With auto-register,
   the runner self-registers on every startup and uses the returned token
   directly.

2. **Context window renders tool calls** (`api.rs` + `StepDetailPanel.tsx`):
   `MessageView` was dropping assistant messages that had `tool_calls`/
   `tool_invocations` but empty `content` (standard behavior when an LLM
   decides to call a tool). The context window showed a blank ASSISTANT
   bubble. Now the backend passes through `tool_calls`/`tool_invocations`
   fields, and the frontend renders them as styled function-name + args
   blocks.

Co-authored-by: Cursor <[email protected]>
@vercel

vercel Bot commented May 10, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
rewind Ready Ready Preview, Comment May 10, 2026 9:58am

@risjai risjai left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: feat(runner): auto-register + tool-call rendering

Overview

Two unrelated but well-scoped fixes:

  1. Auto-register — solves the emptyDir bootstrap problem cleanly via a documented env-var opt-in. Retry logic is appropriate for sidecar startup ordering.
  2. Tool-call rendering — small backend pass-through + nicely-styled frontend block. Fixes the silent "blank assistant bubble" UX bug.

Code quality is good; the changes are surgical and the docstrings explain the why. Ship-blocker concerns are mostly around production hardening of the auto-register path.

Key concerns (see inline)

  • Bearer auth missing on POST /api/runners — auto-register will 401 against any server with auth_token set on AppState. Sidecar deployments may have auth on. Either pass an env-provided bearer or document the unauth assumption.
  • SSRF guard requires server-side env coordination — the default webhook_url=http://127.0.0.1:8000/... is rejected by validate_export_endpoint unless the server has REWIND_ALLOW_LOOPBACK_WEBHOOKS=1. Worth a doc note next to the env var docs.
  • Blocking sleep + sync HTTP in auto_register — fine if from_env() is called at module load, but called inside a running event loop it freezes everything for up to 20s.
  • HTTPError is retried, not surfaced — server-side 4xx (e.g. SSRF rejection) silently burns 10 retries instead of failing fast with the response body.
  • No test coverage for auto_register or the new extract_messages branch (empty content + tool_calls).

Minor

  • tool_calls and tool_invocations parallel handling is reasonable, but worth a one-line comment in api.rs explaining which provider populates which.
  • argsDisplay typing — schema says arguments: string but the try/catch handles object. Either widen the type or drop the catch.

Strengths

  • Backward-compat: from_env() with explicit REWIND_RUNNER_TOKEN still works exactly as before.
  • Auto-register on every startup with unique runner IDs is the right model — no stale-token recovery dance.
  • Frontend gracefully handles (empty) messages instead of crashing or rendering nothing.
  • #[serde(skip_serializing_if = "Option::is_none")] keeps the wire format clean for non-tool messages.

req = urllib.request.Request(
url, data=payload, method="POST",
headers={"Content-Type": "application/json"},
)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Missing Authorization header. POST /api/runners is bearer-protected when AppState::auth_token is Some (see crates/rewind-web/src/auth.rs::auth_middleware). In any production sidecar deployment with auth enabled, this request will 401 and auto_register() will burn through all 10 retries before RuntimeError-ing.

Suggest reading REWIND_AUTH_TOKEN (or a dedicated REWIND_BEARER_TOKEN) from env and adding Authorization: Bearer <token> to the headers — auto-register fixes the runner token bootstrap, but the operator bearer still needs to authenticate the registration request itself.

name=os.environ.get("REWIND_RUNNER_NAME", "auto"),
webhook_url=os.environ.get(
"REWIND_RUNNER_WEBHOOK_URL",
"http://127.0.0.1:8000/rewind-webhook",

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

SSRF guard interaction. runners.rs::register_runner calls validate_export_endpoint which rejects loopback/private IPs by default. The default webhook_url=http://127.0.0.1:8000/rewind-webhook here will be refused unless the server has REWIND_ALLOW_LOOPBACK_WEBHOOKS=1 set.

This is the right default for sidecar deployments (where pod-local loopback is legitimate), but please call out the dual env-var requirement in the docstring or in docs/runners.md — operators who only flip the client-side flag will hit a confusing 400 from the server.

"(retrying in %.1fs)",
attempt, max_retries, e, retry_delay,
)
_time.sleep(retry_delay)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Blocks the event loop if called from async context. _time.sleep + sync urllib.request.urlopen in a classmethod that's invoked from from_env() is fine at module-load time, but if RunnerConfig.from_env() is called inside a running asyncio loop (e.g. FastAPI @app.on_event("startup") or any async def setup hook), the loop freezes for up to ~20s while retries play out.

Either (a) note in the docstring that this is sync-blocking and must be called pre-loop, or (b) consider an async variant for callers in async contexts.

"(attempt %d/%d)",
runner_id, name, attempt, max_retries,
)
return cls(auth_token=raw_token, rewind_base_url=base_url)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Retries swallow HTTPError details. urlopen raises HTTPError (a subclass of URLError) on 4xx/5xx, so a server-side 400 (e.g. SSRF rejection or invalid webhook_url) gets silently retried 10 times before the final RuntimeError reports just last_err. Branching on HTTPError first, reading e.read(), and either failing fast (4xx) or surfacing the response body in the error would shorten debugging dramatically — the difference between "connection refused, server starting" (retry) and "loopback webhook rejected" (fail now) is night and day for the operator.

still be starting when the main container initializes. Safe
to call on every startup — duplicate names are allowed
(each gets a unique ID + token).
"""

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Worth noting in the docstring: auto-registering on every pod restart leaks Active runner rows in the DB. With emptyDir (the actual target use case) the DB resets so it's a non-issue. With persistent storage, runner rows accumulate forever — eventually you'd want a TTL, a stable-name upsert path, or a startup-time cleanup. Not a blocker for v1, but mention the constraint.

Some(MessageView { role, content })
let tool_calls = m.get("tool_calls").cloned();
let tool_invocations = m.get("tool_invocations").cloned();
if content.is_empty() && tool_calls.is_none() && tool_invocations.is_none() {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Subtle behavioral change worth flagging: previously, a message whose content field is null or absent (e.g. some Anthropic tool-use blocks) returned None and got dropped. Now content defaults to String::new() and the message is kept iff it carries tool_calls/tool_invocations. That's the intended fix.

Double-check OpenAI-spec tool role messages still extract correctly — they carry their result in content (string) and should hit the as_str() branch on line 303, but the test suite doesn't exercise this path explicitly.

#[serde(skip_serializing_if = "Option::is_none")]
tool_calls: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
tool_invocations: Option<serde_json::Value>,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Both tool_calls (OpenAI / Anthropic recent format) and tool_invocations (Vercel AI SDK / streaming format) are passed through as opaque serde_json::Value. A one-line comment explaining which provider/format populates which would help future readers — without context, the duplication looks accidental.

Comment thread web/src/components/StepDetailPanel.tsx Outdated
interface ContextMessage {
role: string
content: string
tool_calls?: { function: { name: string; arguments: string } }[]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Type widening: arguments is declared string, but the runtime code on line 367 handles the case where it's already an object (JSON.stringify(tc.function.arguments, null, 2)). Either widen to string | Record<string, unknown> to match reality, or trust the type and drop the object branch. Right now the type lies.

Comment thread web/src/components/StepDetailPanel.tsx Outdated
</div>
))}
{messages.map((msg, i) => {
const toolCalls = msg.tool_calls || msg.tool_invocations

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Minor: msg.tool_calls || msg.tool_invocations silently picks one. If a future provider sends both (or one is [] and the other has content), this can render misleadingly. Consider msg.tool_calls?.length ? msg.tool_calls : msg.tool_invocations to skip empty arrays.

- auto_register: send Authorization bearer when REWIND_AUTH_TOKEN is set
- auto_register: fail fast on HTTP 4xx/5xx, only retry connection errors
- auto_register: docstring warns about sync-blocking, SSRF env-var, row leakage
- api.rs: doc comments explain tool_calls vs tool_invocations provider formats
- StepDetailPanel: widen ToolCallEntry.arguments type, prefer non-empty array
- Rust track: 0.14.9 → 0.14.10 (Cargo.toml, Cargo.lock, rewind_cli.py,
  python-mcp/pyproject.toml 0.13.8→0.13.9, rewind_mcp_cli.py)
- Python SDK track: 0.15.3 → 0.15.4 (pyproject.toml, __init__.py)

Co-authored-by: Cursor <[email protected]>

@risjai risjai left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

All review comments addressed cleanly in adc047c:

  • ✅ Bearer auth wired via REWIND_AUTH_TOKEN (sent as Authorization: Bearer …)
  • ✅ SSRF/loopback dual-env-var requirement documented in the docstring .. note::
  • ✅ Sync-blocking nature called out in .. warning:: block
  • ✅ HTTPError short-circuits the retry loop and surfaces the response body — no more 10×20s burn on 4xx
  • ✅ Row-leakage caveat for persistent-storage deployments noted
  • ✅ api.rs doc comments distinguish tool_calls (OpenAI/Anthropic) vs tool_invocations (LLM Gateway/Vercel)
  • ✅ ToolCallEntry.arguments widened to string | Record<string, unknown> to match runtime
  • ✅ Empty-array guard via ?.length ? … : null ensures we don't render a stray empty branch

Exception-ordering is correct (HTTPError before URLError since it's a subclass).

Version bumps look right per project CLAUDE.md rules — all 5 Rust-track files (Cargo.toml, Cargo.lock, rewind_cli.py, python-mcp/pyproject.toml, rewind_mcp_cli.py) and both Python-SDK files (python/pyproject.toml, __init__.py) updated together.

LGTM. Remember the post-merge checklist: GitHub Release tag for the Rust binaries, then publish PyPI from python/ and python-mcp/.

@risjai
risjai merged commit 95a242a into master May 10, 2026
6 checks passed
@risjai
risjai deleted the rjain/runner-auto-register-and-context-fix branch May 10, 2026 10:11

This branch was successfully deployed

1 active deployment
Preview — adc047cd Deployed May 10, 2026 by vercel[bot]
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.

1 participant