Repository navigation
fix(showcase/starters): restore /api/health accuracy across 15 degraded agent starters - #4096
Merged
Merged
Conversation
jpr5
requested review from
marthakelly,
mme,
ranst91 and
tylerslaton
as code owners
April 19, 2026 15:20
Contributor
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
jpr5
force-pushed
the
fix/showcase-starters-health-restore
branch
from
April 19, 2026 15:33
9a9a746 to
3d51b62
Compare
…I mount shadow
Python FastAPI showcase starters were registering an @app.get("/health")
handler BEFORE app.mount("/", ...) (or the adapter's equivalent catch-all).
Starlette's Mount at "/" is a prefix match that swallows every subsequent
request including /health, so the decorated handler never fired and the
Next.js /api/health probe saw a non-JSON agent response and flagged the
starter as "degraded".
Install a HealthMiddleware (BaseHTTPMiddleware) that short-circuits
GET /health above the routing layer, which runs before any Mount can
claim the path. The agent mount is kept intact so AG-UI traffic at / is
unaffected.
Affects 10 Python agent starters: ag2, agno, claude-sdk-python,
crewai-crews, google-adk, langroid, llamaindex, ms-agent-python,
pydantic-ai, strands.
…uffer stderr
The entrypoint.sh template used `cmd 2>&1 | sed 's/^/[agent] /' &`
followed by `AGENT_PID=\$!`. After a pipeline, `\$!` points to the LAST
command in the pipe (the `sed` process), not the agent. Every subsequent
`kill -0 \$AGENT_PID` and `wait -n \$AGENT_PID` was therefore monitoring
`sed`, which stays alive until its stdin closes — long after the agent has
crashed. Railway restarts the container mid-loop; the health probe sees
`{status: "degraded", agent: "down"}` for a few seconds during each cycle.
A second, compounding bug: `sed` buffers by default, and Python agents
buffer their own stdout, so a stack trace emitted during module import
could sit in userspace memory until the pipe closed — by which point the
log was discarded and the real cause of the crash was lost.
Fix both by switching to bash process substitution:
cmd &> >(awk '{print "[agent] " \$0; fflush()}') &
AGENT_PID=\$!
Process substitution does not create a pipeline, so `\$!` remains the
agent's PID. `awk` with `fflush()` flushes each prefixed line to the
container log immediately. Also export `PYTHONUNBUFFERED=1` at the
entrypoint level so Python-based agents don't buffer before awk.
Applies to all 17 starters (python, langgraph-python, langgraph-fastapi,
langgraph-typescript, mastra, typescript, java/spring-ai, csharp/
ms-agent-dotnet). Done once in generate-starters.ts + the template +
regenerated entrypoint.sh files.
…imports generate-starters.ts rewrites relative imports to absolute for langgraph starters because langgraph_cli loads modules standalone rather than as packages. The rewrite was flat: from .X import ... -> from <agentDir>.X import ... For a file at <agentDir>/tools/get_weather.py, `from .types import ...` resolves to `tools.types` — the CURRENT package — not `<agentDir>.types`. The flat rewrite dropped the `tools` segment and produced: ModuleNotFoundError: No module named 'src.agents.types' at startup. The agent crashed during module import; the entrypoint pipe swallowed the traceback (see previous commit for the pipe bug); the 2-3s sleep guard happened to fire while `sed` was still alive; and Railway's /api/health probe reported `agent: "error"`. Make the rewrite subdir-aware: compute the file's containing Python package from its relative path under agentDest, and prepend that to the relative import target. So `from .types import ...` inside `src/agents/tools/get_weather.py` becomes `from src.agents.tools.types import ...`. langgraph-python has the same broken imports in its tools/__init__.py but doesn't crash at runtime because main.py doesn't import from tools (dead path). Regenerating fixes the dead code too.
agent_server.py now calls app.add_middleware(HealthMiddleware) to serve
/health above the routing layer (restores starter health accuracy after
create_strands_app's catch-all at "/" shadowed @app.get("/health")).
Both _FakeFastAPI stubs — in tests/python/conftest.py and
tests/python/test_instrumentor_patch.py::test_agent_server_module_installs_patch —
only covered the decorator surface (get/post/put/delete/patch). When the
test execs agent_server.py verbatim under the stub, add_middleware raises
AttributeError and fails Python unit tests (3.12). The 3.10 matrix skips
strands (ag_ui_strands requires >=3.12) so the regression only showed
under 3.12.
Mirror the stub's API with a no-op add_middleware so the module loads
cleanly; the patched ThreadingInstrumentor assertion is still the
invariant under test.
- Regenerate agno starter to pick up agno>=2.5.17 (from #4095) - Ratchet validate-pins fail-baseline hash to match new FAIL set (count unchanged at 110; hash rotates because agno Dojo/showcase pair now reflects the SDK upgrade)
jpr5
force-pushed
the
fix/showcase-starters-health-restore
branch
from
April 19, 2026 16:00
564ec26 to
de586ec
Compare
4 of 6 tasks
jpr5
added a commit
that referenced
this pull request
Apr 19, 2026
…ir crashes (#4099) ## Summary **Root cause:** PR #4092 replaced a blanket `RUN chown -R app:app /app` with per-COPY `COPY --chown=app:app` lines. That covers the copied files, but `WORKDIR /app` at the top of the runner stage creates `/app` as root BEFORE the `app` user exists, and `COPY --chown=` only reassigns the copied files — not the parent dir. Result: `/app` stays owned by root. **Symptom:** `starter-mastra` deploy CRASHED on Railway with: ``` Error: EACCES: permission denied, mkdir '/app/.mastra' ``` `npx mastra dev` tries to create its cache dir under CWD at runtime as user `app`, and fails. **Likely co-victims:** any starter whose runtime invokes a Node CLI that writes to CWD. `starter-langgraph-typescript` (uses `@langchain/langgraph-cli dev`) fits the exact same signature — same class of bug, would have hit the same wall once traffic forced a cache write. **Fix:** add `RUN chown app:app /app` immediately before `USER app` in all four Dockerfile templates (typescript, python, dotnet, java), applied uniformly to all 17 generated starters via `showcase/scripts/generate-starters.ts`. Surgical, cheap, idempotent. ## Evidence — local docker build + run **starter-mastra:** ``` $ docker exec starter-mastra-test ls -la /app | head drwxr-xr-x 1 app app 4096 . ← WORKDIR now owned by app drwxr-xr-x 1 root root 4096 .. drwxr-xr-x 4 app app 4096 .mastra ← created successfully by mastra dev ... $ curl http://localhost:13010/api/health {"status":"ok","integration":"mastra","agent":"ok",...} ← HTTP 200 ``` **starter-langgraph-typescript:** ``` $ docker ps --filter name=starter-langgraph-ts-test starter-langgraph-ts-test Up 8 minutes ← stable, not crashlooping $ docker exec starter-langgraph-ts-test touch /app/test-write && echo OK OK $ curl http://localhost:13020/api/health {"status":"degraded","integration":"langgraph-typescript","agent":"down",...} ← HTTP 503 (dummy key) — NOT a crash ``` ## Scope - 17 starter Dockerfiles regenerated - 4 template Dockerfiles updated (the source of truth) - Generator TS untouched — the fix is purely in the Dockerfile templates that the generator copies verbatim - `showcase/scripts` vitest: 1073/1073 green ## Test plan - [x] `pnpm run generate-starters` regenerates without errors - [x] `pnpm test` in `showcase/scripts` — 1073 tests green - [x] `docker build` + `docker run` starter-mastra — container stays up, `/api/health` 200 - [x] `docker build` + `docker run` starter-langgraph-typescript — container stays up 8+ min, `/api/health` 503 degraded (expected on dummy key) - [ ] Railway redeploy of starter-mastra after merge — expect container to boot and reach `running` - [ ] Railway redeploy of starter-langgraph-typescript after merge — expect container to boot and reach `running` Independent of #4096 — branched from `origin/main`, no dependency.
zeekay
pushed a commit
to Dream-AI-4444/CopilotKit
that referenced
this pull request
Sep 11, 2026
…ed agent starters (CopilotKit#4096) ## Summary 15 of 17 showcase starters were reporting `{status: "degraded", agent: "error" | "down"}` from `/api/health`. Root-caused to two compounding bugs that hid each other. ### Cause 1 — FastAPI route shadowed by mount catch-all Python FastAPI starters registered `@app.get("/health")` but then installed an AG-UI adapter at `/` (either `app.mount("/", stream.build_asgi())` or `add_agent_framework_fastapi_endpoint(path="/")`). Starlette's `Mount` at `/` is a prefix match and swallows every subsequent request including `/health`, so the decorated handler never fired and the runtime saw a non-JSON agent response and flagged the starter as "degraded". Repro (reduced, before): ```python app = FastAPI() app.mount("/", mounted) # or adapter that mounts at "/" @app.get("/health") def health(): return {"status": "ok"} # curl /health -> "agent-saw:/health" (wrong — mount won) ``` Fix: install a `HealthMiddleware` (BaseHTTPMiddleware) that short-circuits `GET /health` above the routing layer, which runs before any Mount can claim the path. Agent mount stays intact so AG-UI traffic at `/` is unaffected. Applies to 10 Python agent starters: ag2, agno, claude-sdk-python, crewai-crews, google-adk, langroid, llamaindex, ms-agent-python, pydantic-ai, strands. ### Cause 2 — `$!` after a pipeline points to `sed`, not the agent The entrypoint template used: ```bash cmd 2>&1 | sed 's/^/[agent] /' & AGENT_PID=$! ``` After a pipeline, `$!` is the last command (`sed`), not the agent. Every `kill -0 $AGENT_PID` and `wait -n $AGENT_PID` therefore monitored `sed`, which stays alive until its stdin closes — long after the agent crashed. Compounding that, `sed` buffers by default and Python agents buffer their own stdout, so a stack trace at crash time was discarded when the pipe closed. Fix: process substitution instead of pipeline, plus `PYTHONUNBUFFERED=1` at the entrypoint level: ```bash cmd &> >(awk '{print "[agent] " $0; fflush()}') & AGENT_PID=$! ``` Process substitution doesn't create a pipeline, so `$!` stays the agent's PID. `awk` with `fflush()` line-flushes prefixed output immediately. Applied to all 17 starters via `generate-starters.ts` + the template. ### Cause 2a — hidden langgraph-fastapi crash `generate-starters.ts` rewrites relative imports to absolute for langgraph starters (langgraph_cli loads modules standalone, not as packages). The rewrite was flat: `from .X import ...` -> `from <agentDir>.X import ...`. For a file at `<agentDir>/tools/get_weather.py`, `from .types import ...` resolves to `tools.types` (the CURRENT package), not `<agentDir>.types`. The flat rewrite dropped the `tools` segment and produced: ``` ModuleNotFoundError: No module named 'src.agents.types' ``` at import time. The agent crashed; the `sed` pipe bug swallowed the traceback; the 2-3s sleep guard caught the window while `sed` was still alive; `/api/health` reported `agent: "error"`. Fix: make the rewrite subdir-aware — compute the file's containing Python package from its relative path under `agentDest` and prepend that to the relative import target. So `from .types import ...` inside `src/agents/tools/get_weather.py` becomes `from src.agents.tools.types import ...`. langgraph-python had the same broken imports in `tools/__init__.py` but doesn't crash at runtime because `main.py` doesn't import from `tools` (dead path). Regenerating fixes the dead code too. ## Verification ### Middleware logic (reduced reproduction) ```python # With HealthMiddleware installed above the routing layer: app = FastAPI() app.add_middleware(HealthMiddleware) app.mount("/", mounted) c.get("/health") # 200 {"status": "ok"} <- short-circuited c.get("/anything") # 200 agent-saw:/anything <- reaches mount c.get("/") # 200 agent-saw:/ <- reaches mount ``` ### Tests - `showcase/scripts` vitest: 1061/1061 passing - `generate-starters.test.ts` (258) and `starter-consistency.test.ts` (306) both still green — no test updates required ### Starters touched - Cause 1 (HealthMiddleware): ag2, agno, claude-sdk-python, crewai-crews, google-adk, langroid, llamaindex, ms-agent-python, pydantic-ai, strands (10) - Cause 2 (entrypoint PID): all 17 starters via generator + template - Cause 2a (langgraph import): langgraph-fastapi (crash path), langgraph-python (dead path) ## Commits 1. `fix(showcase/starters): serve /health via middleware to bypass FastAPI mount shadow` — Cause 1 2. `fix(showcase/starters): capture real agent PID in entrypoint.sh + unbuffer stderr` — Cause 2 3. `fix(showcase/starters/langgraph-fastapi): correct src.agents.tools.* imports` — Cause 2a ## Test plan - [ ] Docker build + run ag2: `curl -i http://localhost:3000/api/health` returns 200 `{"status":"ok",...}` - [ ] Docker build + run langgraph-fastapi: health OK, agent imports succeed, no ModuleNotFoundError in logs - [ ] Docker build + run langgraph-typescript: health OK (entrypoint-only fix) - [ ] Post-merge Railway: monitor all 17 starter health endpoints return `status: "ok"` after redeploy - [ ] Post-merge: inspect logs for any starter that still reports `degraded` — with awk+fflush+PYTHONUNBUFFERED, the real import/crash error should now surface in container logs ## Safety notes - No `.github/workflows/*.yml` edits - No force-push, no amend - Author: Jordan Ritter <[email protected]> - Do NOT merge until reviewer approves
zeekay
pushed a commit
to Dream-AI-4444/CopilotKit
that referenced
this pull request
Sep 11, 2026
…ir crashes (CopilotKit#4099) ## Summary **Root cause:** PR CopilotKit#4092 replaced a blanket `RUN chown -R app:app /app` with per-COPY `COPY --chown=app:app` lines. That covers the copied files, but `WORKDIR /app` at the top of the runner stage creates `/app` as root BEFORE the `app` user exists, and `COPY --chown=` only reassigns the copied files — not the parent dir. Result: `/app` stays owned by root. **Symptom:** `starter-mastra` deploy CRASHED on Railway with: ``` Error: EACCES: permission denied, mkdir '/app/.mastra' ``` `npx mastra dev` tries to create its cache dir under CWD at runtime as user `app`, and fails. **Likely co-victims:** any starter whose runtime invokes a Node CLI that writes to CWD. `starter-langgraph-typescript` (uses `@langchain/langgraph-cli dev`) fits the exact same signature — same class of bug, would have hit the same wall once traffic forced a cache write. **Fix:** add `RUN chown app:app /app` immediately before `USER app` in all four Dockerfile templates (typescript, python, dotnet, java), applied uniformly to all 17 generated starters via `showcase/scripts/generate-starters.ts`. Surgical, cheap, idempotent. ## Evidence — local docker build + run **starter-mastra:** ``` $ docker exec starter-mastra-test ls -la /app | head drwxr-xr-x 1 app app 4096 . ← WORKDIR now owned by app drwxr-xr-x 1 root root 4096 .. drwxr-xr-x 4 app app 4096 .mastra ← created successfully by mastra dev ... $ curl http://localhost:13010/api/health {"status":"ok","integration":"mastra","agent":"ok",...} ← HTTP 200 ``` **starter-langgraph-typescript:** ``` $ docker ps --filter name=starter-langgraph-ts-test starter-langgraph-ts-test Up 8 minutes ← stable, not crashlooping $ docker exec starter-langgraph-ts-test touch /app/test-write && echo OK OK $ curl http://localhost:13020/api/health {"status":"degraded","integration":"langgraph-typescript","agent":"down",...} ← HTTP 503 (dummy key) — NOT a crash ``` ## Scope - 17 starter Dockerfiles regenerated - 4 template Dockerfiles updated (the source of truth) - Generator TS untouched — the fix is purely in the Dockerfile templates that the generator copies verbatim - `showcase/scripts` vitest: 1073/1073 green ## Test plan - [x] `pnpm run generate-starters` regenerates without errors - [x] `pnpm test` in `showcase/scripts` — 1073 tests green - [x] `docker build` + `docker run` starter-mastra — container stays up, `/api/health` 200 - [x] `docker build` + `docker run` starter-langgraph-typescript — container stays up 8+ min, `/api/health` 503 degraded (expected on dummy key) - [ ] Railway redeploy of starter-mastra after merge — expect container to boot and reach `running` - [ ] Railway redeploy of starter-langgraph-typescript after merge — expect container to boot and reach `running` Independent of CopilotKit#4096 — branched from `origin/main`, no dependency.
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
15 of 17 showcase starters were reporting
{status: "degraded", agent: "error" | "down"}from/api/health. Root-caused to two compounding bugs that hid each other.Cause 1 — FastAPI route shadowed by mount catch-all
Python FastAPI starters registered
@app.get("/health")but then installed an AG-UI adapter at/(eitherapp.mount("/", stream.build_asgi())oradd_agent_framework_fastapi_endpoint(path="/")). Starlette'sMountat/is a prefix match and swallows every subsequent request including/health, so the decorated handler never fired and the runtime saw a non-JSON agent response and flagged the starter as "degraded".Repro (reduced, before):
Fix: install a
HealthMiddleware(BaseHTTPMiddleware) that short-circuitsGET /healthabove the routing layer, which runs before any Mount can claim the path. Agent mount stays intact so AG-UI traffic at/is unaffected.Applies to 10 Python agent starters: ag2, agno, claude-sdk-python, crewai-crews, google-adk, langroid, llamaindex, ms-agent-python, pydantic-ai, strands.
Cause 2 —
$!after a pipeline points tosed, not the agentThe entrypoint template used:
After a pipeline,
$!is the last command (sed), not the agent. Everykill -0 $AGENT_PIDandwait -n $AGENT_PIDtherefore monitoredsed, which stays alive until its stdin closes — long after the agent crashed. Compounding that,sedbuffers by default and Python agents buffer their own stdout, so a stack trace at crash time was discarded when the pipe closed.Fix: process substitution instead of pipeline, plus
PYTHONUNBUFFERED=1at the entrypoint level:Process substitution doesn't create a pipeline, so
$!stays the agent's PID.awkwithfflush()line-flushes prefixed output immediately.Applied to all 17 starters via
generate-starters.ts+ the template.Cause 2a — hidden langgraph-fastapi crash
generate-starters.tsrewrites relative imports to absolute for langgraph starters (langgraph_cli loads modules standalone, not as packages). The rewrite was flat:from .X import ...->from <agentDir>.X import .... For a file at<agentDir>/tools/get_weather.py,from .types import ...resolves totools.types(the CURRENT package), not<agentDir>.types. The flat rewrite dropped thetoolssegment and produced:at import time. The agent crashed; the
sedpipe bug swallowed the traceback; the 2-3s sleep guard caught the window whilesedwas still alive;/api/healthreportedagent: "error".Fix: make the rewrite subdir-aware — compute the file's containing Python package from its relative path under
agentDestand prepend that to the relative import target. Sofrom .types import ...insidesrc/agents/tools/get_weather.pybecomesfrom src.agents.tools.types import ....langgraph-python had the same broken imports in
tools/__init__.pybut doesn't crash at runtime becausemain.pydoesn't import fromtools(dead path). Regenerating fixes the dead code too.Verification
Middleware logic (reduced reproduction)
Tests
showcase/scriptsvitest: 1061/1061 passinggenerate-starters.test.ts(258) andstarter-consistency.test.ts(306) both still green — no test updates requiredStarters touched
Commits
fix(showcase/starters): serve /health via middleware to bypass FastAPI mount shadow— Cause 1fix(showcase/starters): capture real agent PID in entrypoint.sh + unbuffer stderr— Cause 2fix(showcase/starters/langgraph-fastapi): correct src.agents.tools.* imports— Cause 2aTest plan
curl -i http://localhost:3000/api/healthreturns 200{"status":"ok",...}status: "ok"after redeploydegraded— with awk+fflush+PYTHONUNBUFFERED, the real import/crash error should now surface in container logsSafety notes
.github/workflows/*.ymledits