Skip to content

fix(showcase/starters): restore /api/health accuracy across 15 degraded agent starters - #4096

Merged
jpr5 merged 6 commits into
mainfrom
fix/showcase-starters-health-restore
Apr 19, 2026
Merged

jpr5 merged 6 commits into
mainfrom
fix/showcase-starters-health-restore

Conversation

@jpr5

@jpr5 jpr5 commented Apr 19, 2026

Copy link
Copy Markdown
Contributor

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):

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:

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:

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)

# 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

@vercel

vercel Bot commented Apr 19, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Deployment Actions Updated (UTC)
chat-with-your-data Ready Ready Preview, Comment Apr 19, 2026 4:03pm
docs Ready Ready Preview, Comment Apr 19, 2026 4:03pm
form-filling Ready Ready Preview, Comment Apr 19, 2026 4:03pm
research-canvas Ready Ready Preview, Comment Apr 19, 2026 4:03pm
travel Ready Ready Preview, Comment Apr 19, 2026 4:03pm

Request Review

@jpr5
jpr5 force-pushed the fix/showcase-starters-health-restore branch from 9a9a746 to 3d51b62 Compare April 19, 2026 15:33
@vercel
vercel Bot temporarily deployed to Preview – form-filling April 19, 2026 15:42 Inactive
@vercel
vercel Bot temporarily deployed to Preview – chat-with-your-data April 19, 2026 15:42 Inactive
jpr5 and others added 4 commits April 19, 2026 08:57
…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.
jpr5 added 2 commits April 19, 2026 08:57
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
jpr5 force-pushed the fix/showcase-starters-health-restore branch from 564ec26 to de586ec Compare April 19, 2026 16:00
@jpr5
jpr5 merged commit 692c57d into main Apr 19, 2026
13 checks passed
@jpr5
jpr5 deleted the fix/showcase-starters-health-restore branch April 19, 2026 17:39
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

5 active deployments
Preview – research-canvas — de586ece Deployed Apr 19, 2026 by vercel[bot]
Preview – travel — de586ece Deployed Apr 19, 2026 by vercel[bot]
Preview – docs — de586ece Deployed Apr 19, 2026 by vercel[bot]
Preview – form-filling — de586ece Deployed Apr 19, 2026 by vercel[bot]
Preview – chat-with-your-data — de586ece Deployed Apr 19, 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