Repository navigation
feat(runner): auto-register for sidecar deployments + fix context window tool calls - #165
Conversation
…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]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
risjai
left a comment
There was a problem hiding this comment.
Review: feat(runner): auto-register + tool-call rendering
Overview
Two unrelated but well-scoped fixes:
- Auto-register — solves the emptyDir bootstrap problem cleanly via a documented env-var opt-in. Retry logic is appropriate for sidecar startup ordering.
- 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 withauth_tokenset onAppState. 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 byvalidate_export_endpointunless the server hasREWIND_ALLOW_LOOPBACK_WEBHOOKS=1. Worth a doc note next to the env var docs. - Blocking sleep + sync HTTP in
auto_register— fine iffrom_env()is called at module load, but called inside a running event loop it freezes everything for up to 20s. HTTPErroris 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_registeror the newextract_messagesbranch (empty content + tool_calls).
Minor
tool_callsandtool_invocationsparallel handling is reasonable, but worth a one-line comment inapi.rsexplaining which provider populates which.argsDisplaytyping — schema saysarguments: stringbut the try/catch handles object. Either widen the type or drop the catch.
Strengths
- Backward-compat:
from_env()with explicitREWIND_RUNNER_TOKENstill 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"}, | ||
| ) |
There was a problem hiding this comment.
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", |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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). | ||
| """ |
There was a problem hiding this comment.
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() { |
There was a problem hiding this comment.
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>, |
There was a problem hiding this comment.
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.
| interface ContextMessage { | ||
| role: string | ||
| content: string | ||
| tool_calls?: { function: { name: string; arguments: string } }[] |
There was a problem hiding this comment.
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.
| </div> | ||
| ))} | ||
| {messages.map((msg, i) => { | ||
| const toolCalls = msg.tool_calls || msg.tool_invocations |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
All review comments addressed cleanly in adc047c:
- ✅ Bearer auth wired via
REWIND_AUTH_TOKEN(sent asAuthorization: Bearer …) - ✅ SSRF/loopback dual-env-var requirement documented in the docstring
.. note:: - ✅ Sync-blocking nature called out in
.. warning::block - ✅
HTTPErrorshort-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.rsdoc comments distinguishtool_calls(OpenAI/Anthropic) vstool_invocations(LLM Gateway/Vercel) - ✅
ToolCallEntry.argumentswidened tostring | Record<string, unknown>to match runtime - ✅ Empty-array guard via
?.length ? … : nullensures 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/.
Summary
Runner auto-registration for sidecar deployments:
RunnerConfig.auto_register()POSTs to/api/runnerson startup with retry logic (10 attempts, 2s delay). Activated viaREWIND_RUNNER_AUTO_REGISTER=1env 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:
MessageViewwas silently dropping assistant messages that hadtool_calls/tool_invocationsbut emptycontent(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 throughtool_calls/tool_invocationsfields, and the React frontend renders them as styled function-name + arguments blocks.Changes
python/rewind_agent/runner.pyRunnerConfig.auto_register()classmethod +from_env()fallback to auto-register whenREWIND_RUNNER_AUTO_REGISTER=1crates/rewind-web/src/api.rsMessageViewgains optionaltool_calls/tool_invocationsfields;extract_messageskeeps empty-content messages that carry tool call dataweb/src/components/StepDetailPanel.tsxContextWindowViewrenderstool_calls/tool_invocationsas violet-styled blocks with function name + pretty-printed argsContext
Discovered during ray-agent sidecar deployment in dev1. The replay flow was fully wired (webhook handler, HMAC verification, dispatch) but:
Test plan
cargo check --package rewind-webpassestool_invocationsREWIND_RUNNER_AUTO_REGISTER=1withREWIND_URLpointing to a running server — verify runner appears in/api/runnersfrom_env()still works with explicitREWIND_RUNNER_TOKEN(no regression)Made with Cursor