Repository navigation
fix(showcase/ms-agent-python): keep the user's prompt on the multimodal PDF turn - #6159
Conversation
…al PDF turn The multimodal PDF turn dropped the user's question out of the final outbound user message, so the model was handed a document dump with no question attached. Against aimock's strict mode that surfaced as `503 no_fixture_match` on turn 2 (turn 1, the image, passed); against a real LLM it would have silently answered the wrong thing. Root cause is a serialisation mismatch, not a fixture gap. `agent_framework_openai._chat_completion_client._prepare_message_for_openai` emits ONE OpenAI message per `Content` — it builds a fresh `args` dict on every iteration of its content loop. `_PdfFlattenChatMiddleware` appended the flattened `[Attached document]` text as a SECOND text `Content` beside the prompt, so one logical user turn serialised to two consecutive user messages: prompt-only, then document-only. Anything reading "the current user turn" off the tail of the list saw only the document. Merge the flattened document INTO the message's existing prompt text content instead, so the turn stays a single text content and serialises to a single user message reading `"<prompt>\n[Attached document]\n<body>"`. langgraph-python's equivalent agent is green precisely because LangChain keeps multiple text parts inside one message rather than splitting them. The merge copies the prompt `Content` rather than mutating it: the middleware restores the original `contents` list after the model call, and that restore only undoes the list swap — an in-place mutation would leak the raw PDF body into the AG-UI MESSAGES_SNAPSHOT and render it in the user's chat bubble. Also dedupe identical flattened blocks. The page's `LegacyConverterShim` appends a legacy `binary` mirror alongside every modern attachment part, so the same PDF arrives twice and its body was being sent to the model twice. No fixture change: the existing `userMessage` match key is correct and is what the corrected request shape satisfies.
Production Digest-Pinning AuditAll 41 services digest-pinned. Run 2026-07-25 23:56:00 PDT — 0 finding(s). |
@copilotkit/a2ui-renderer
@copilotkit/agentcore-runner
@copilotkit/angular
@copilotkit/channels
@copilotkit/channels-core
@copilotkit/channels-discord
@copilotkit/channels-intelligence
@copilotkit/channels-slack
@copilotkit/channels-teams
@copilotkit/channels-telegram
@copilotkit/channels-ui
@copilotkit/channels-whatsapp
@copilotkit/core
@copilotkit/react-core
@copilotkit/react-native
@copilotkit/react-textarea
@copilotkit/react-ui
@copilotkit/runtime
@copilotkit/runtime-client-gql
@copilotkit/sdk-js
@copilotkit/shared
@copilotkit/sqlite-runner
@copilotkit/voice
@copilotkit/vue
@copilotkit/web-components
@copilotkit/web-inspector
commit: |
Blocked on a CI-only failure introduced by main, not by this PRUpdating this branch onto This is not a defect in the fix. The same tests passed on the pre-update head Root cause: commit
The Image builds are unaffected — Suggested fix (not applied here — it touches a shared workflow): add a scoped LFS fetch to the - name: Fetch LFS demo assets
run: git lfs pull --include="showcase/integrations/*/public/demo-files/*"Please avoid "skip the test if the PDF looks like a pointer" — that would silently stop exercising the real The other three Wave 3 PRs (#6162, #6161, #6158) were green and have been merged. This one is held until CI is green. |
PR #6163 converted showcase/integrations/*/public/demo-files/* to Git LFS. showcase_validate.yml's python-unit-tests job checks out without LFS, so the working tree holds 129-byte pointer text instead of the real assets. The new ms-agent-python multimodal test is the first Python test to read those bytes: pypdf reads the pointer, extracts nothing, and the test fails with "real pypdf text extraction produced nothing". Fetch only the demo-file assets (40 objects, ~320 KB) rather than setting lfs: true, which would pull all ~248 tracked objects (~475 MB, including 13-26 MB README gifs) into a 2-4 minute job under a 10 minute cap. A job that hits timeout-minutes reports 'cancelled' -- neither success nor failure -- and silently suppresses alerting, so the timeout margin is worth protecting. The repo is public, so LFS downloads resolve anonymously and the pull works with persist-credentials: false. A post-pull %PDF- header check fails the step immediately if the pull ever no-ops, instead of surfacing minutes later as a misleading pytest assertion.
|
Size Change: 0 B Total Size: 1.19 MB ℹ️ View Unchanged
|
…nnot overwrite a newer one (#6174) ## The race, with evidence Three PRs merged within 34 seconds on 2026-07-26. `Showcase: Build & Push` has **no concurrency group** (deliberately), so all three ran simultaneously and raced to push the same `:latest` tags. | run | commit | PR | start → end | |---|---|---|---| | `30190815370` | `7b28934387` | #6162 | 06:18:05 → 06:29:44 | | `30190823203` | `59f275eedc` | #6161 | 06:18:21 → 06:29:44 | | `30190831480` | `db75a04837` | #6158 | 06:18:39 → **06:29:13** ← newest, finished FIRST | The newest commit finished first, so the older builds overwrote its `:latest`. Per-service job completion times — older beating newer on every shared slot: | service | newer (`db75a04837`) | older (`59f275eedc`) | older won by | |---|---|---|---| | `shell-dashboard` | 06:25:33 | 06:25:34 | +1s | | `showcase-harness` | 06:27:51 | 06:27:55 | +4s | | `shell` | 06:27:17 | 06:27:28 | +11s | | `shell-dojo` | 06:25:10 | 06:25:26 | +16s | **All three runs reported `success`.** Staging served pre-#6158 code while CI, the redeploy gate and deploy verification all looked clean. Same failure class as #6171: a success that doesn't mean what it says. ## What I verified in YAML vs took on trust Verified by reading the files / querying the API: - **Tagging** — `showcase_build.yml` pushed `:latest` **and** `:${{ github.sha }}` in one `depot/build-push-action` step, in both the `build` and `build-starters` matrices. **A per-commit sha tag already existed**; confirmed in GHCR (`showcase-shell-dashboard` has digests tagged `db75a04837…`, `59f275eedc…`, `d28384a2eb…`). - **Nothing serialized the pushes.** No concurrency group; confirmed the header comment states this is intentional. - **Deploy consumes `:latest`** — `verify-railway-image-refs.ts` is the SSOT assertion: staging is `ghcr.io/copilotkit/<repo>:latest` (mutable), **prod is `ghcr.io/copilotkit/<repo>@sha256:<digest>` (already immutably pinned)**. So this race is **staging-only**; prod was never exposed. - **`Showcase: Verify Deploy` structurally cannot catch it.** It is a health probe; it asserts no digest or commit provenance anywhere. Its #6171 per-commit concurrency key is about *which run verifies*, not *what image is running*. A stale-but-healthy service passes. - **The racing runs build DISJOINT service sets** (see below) — I pulled the actual job lists. Taken on trust: nothing material. The issue description matched the API on every point I checked. ## Why NOT a concurrency group `detect-changes` builds a **per-push, path-filtered** matrix, so concurrent runs build overlapping but **non-identical** service sets: - `7b28934387` → ag2, agno, built-in-agent, claude-sdk-python, claude-sdk-typescript, crewai-crews, langgraph-fastapi, langgraph-python, langroid, llamaindex, mastra, pydantic-ai, shell-docs, spring-ai, strands (**15**) - `db75a04837` → crewai-crews, llamaindex, shell, shell-dashboard, shell-docs, shell-dojo, showcase-harness (**7**) `cancel-in-progress: true` would have cancelled the `7b28934387` run and the ~10 services **only it builds would never have shipped** — trading a stale-image bug for a never-shipped bug. Per [GitHub's docs](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#concurrency), `cancel-in-progress: false` is no better: *"Any previously pending job or workflow in the concurrency group will be canceled"* — with three rapid merges the **middle** commit's build is dropped outright. GitHub also does not guarantee FIFO ordering of queued runs. Concurrent runs here are **not redundant**, so they must not be cancelled. **Re the #6171 interaction:** this design does **not** use `cancel-in-progress`, so no build is ever superseded-and-cancelled and the cancelled-slot notifier is never tripped by this change. That interaction stays theoretical — deliberately. ## The design Make the one shared mutable resource monotonic instead of serializing the fleet. 1. The build step pushes **only** the immutable `:<sha>` tag, plus an `org.opencontainers.image.revision` label. 2. A guard resolves the commit behind the current `:latest`, asks GitHub `compare/<theirs>...<ours>`, and advances `:latest` (registry-side retag, no pull) **unless ours is `behind`** — i.e. `:latest` already holds a descendant and moving it would roll staging back. **Fails open by design.** No `:latest` yet, unlabelled legacy image, unreachable API, diverged history → advance. A stuck `:latest` is the very failure being fixed, so it declines only on *positive proof* of regression. **Placement:** in `redeploy-staging` / `redeploy-staging-starters`, immediately before the Railway pull that consumes `:latest` — not per build slot. Those jobs already have Node (build slots do **not**, so per-slot would mean an unpinned `npx tsx` fetch on ~50 parallel runners), and deciding right before the pull makes the window as narrow as possible. The image list is the **same matrix ∩ build-success intersection** that decides what gets redeployed, so a failed build can never move a tag. Also adds `showcase_build.yml` to `showcase_validate.yml`'s trigger paths — the new test asserts against that file's live text, and without the path a PR re-adding `:latest` would never run the test that catches it. ## Tradeoffs / what stays open - **Residual sub-second TOCTOU.** GHCR has no compare-and-swap on tags, so two runs reading `:latest` simultaneously could still both advance. This narrows the window from the whole build (~10 min) to inspect→retag. Fully closing it means retiring the mutable staging tag and pinning staging to digests the way prod already is — a change to the Railway image-ref SSOT contract, not a workflow change. **Recommended follow-up.** - **The guard is inert for one build per image.** Today's `:latest` images carry no labels (verified: `showcase-shell-dashboard:latest` has no `Labels` at all), so the first post-merge build fails open and advances unconditionally — same as today. Protection starts from the second build of each image. - Failure to retag exits non-zero, redding the redeploy job and stopping the deploy. That is intended: redeploying against a tag that did not move is exactly the silent false green being fixed. ## Proof **Red/green on the live YAML.** `advance-latest-tag.test.ts` parses the real `showcase_build.yml` (extending #6171's `redeploy-guard.test.ts` pattern). Reverting the workflow to its pre-fix state: **14 failed / 23 passed**. With the fix: **37 passed**. Full `showcase/scripts` suite: **2382 passed, 73 files**. **The load-bearing predicate, verified live against the real incident commits:** ``` compare/db75a04837...59f275e => behind (older run arriving late → DECLINE) compare/59f275eedc...db75a04 => ahead (newer run → advance) compare/db75a04837...db75a04 => identical ``` **Label reading, verified against a real multi-platform registry image** — `docker buildx imagetools inspect ghcr.io/astral-sh/uv:latest` piped through `extractRevisionLabel()` returns `3010295ae7ff572de459987ad70db315a62ecd61`, matching `jq` exactly. The platform-keyed shape is handled. **Shell/jq transforms** exercised directly, including the empty-CSV edge case (empty → empty, step skipped by its `if:`). **Lint:** `actionlint` finding counts byte-identical to the pre-change baseline (no new findings; the 11 pre-existing are unrelated). `zizmor --min-severity low` with the repo config: **no findings**. **Typecheck:** both new files are in `showcase/scripts/tsconfig.json`'s include set and produce **zero** errors. Worth stating plainly: `nx run-many -t check-types` **does not reach `showcase/scripts`** — the project isn't in the nx graph and has no `check-types` target (there are 9 pre-existing type errors in sibling files, which is how I confirmed it). So the typecheck above is mine, not CI's. The *tests* are gated: `showcase_validate.yml` runs bare `pnpm exec vitest run` in `showcase/scripts`, which auto-discovers the new file. ### What I could NOT prove **I did not construct a real concurrent race on scratch branches.** Doing it faithfully needs two builds pushing the same GHCR repo with controlled finish ordering, which means merging to `main` — the only branch the build workflow triggers on. No run IDs for a live race demonstration; I am not implying one. Unproven until this runs on main: that `docker buildx imagetools create` retags cleanly under the runner's GHCR credentials, and that `npx tsx` behaves in the redeploy jobs (it is already the established invocation there — `redeploy-env.ts` — so this is low risk, not zero). ## Normal single-merge builds are unaffected No concurrency group is added, so nothing queues or cancels. A lone merge finds `:latest` at its own parent → `ahead` → advances, exactly as before. Cost is one `imagetools inspect` + one `gh api` + one registry-side retag per built service, in a job that already exists — no extra job, no extra checkout, no change to build parallelism. --- Branched from `db75a04837`; #6156/#6159 landed after, so this will need main merged in before it goes green. Probable conflict with the concurrent `git lfs pull` work in `showcase_validate.yml` — my edit there is only the top-level `on: paths:` list, so it should merge cleanly, but flagging it.
d6:ms-agent-python/multimodalhas been red in staging and prod since 2026-05-30. Turn 1 (image) passes; turn 2 (PDF) fails. This fixes it — without touching the fixture, because the fixture was never the problem.The verbatim turn-2 error
Backend (
showcase-ms-agent-python), and reproduced locally:Surfaced in the browser as
An internal error has occurred while streaming events., with the probe reportingfailure_turn: 2,turns_completed: 1.Request-shape diagnosis
This reads like a fixture gap and is not one. I pulled the actual outbound request off the local aimock's
GET /__aimock/journalduring a failing run. Turn 2, verbatim (bodies elided):One logical user turn arrived as three separate user messages, and the last one carries only the flattened document — the question is nowhere in it. That is why aimock's strict mode refused it:
userMessageis a substring match against the last user turn, and the last user turn was a PDF dump.Root cause:
agent_framework_openaiemits one OpenAI message perContent._chat_completion_client._prepare_message_for_openaibuilds a freshargsdict on every iteration of its content loop, so a userMessagecarrying[prompt_text, flattened_doc_text]serialises to two consecutive user messages — prompt-only, then document-only._PdfFlattenChatMiddlewarewas appending the flattened[Attached document]text as a second textContentbeside the prompt, which is exactly the shape that gets split.Two corroborating details that make the mechanism airtight:
getLastUserTextinrouter.ts, whose comment documents this exact MS Agent Framework behavior). The image turn's split-off trailing message has no text at all, so aimock falls back to the prompt message and matches. The PDF turn's trailing message does have text — the document — so there is nothing to skip past.langgraph-pythonis green doing the identical[Attached document]flattening: LangChain keeps multiple text parts inside one message rather than splitting them into separate messages.This is a product bug, not a mock artefact. Against a real LLM it would not 503 — the model would just answer the wrong thing, because the question is buried behind a document dump instead of being the current turn.
The fix
showcase/integrations/ms-agent-python/src/agents/multimodal_agent.py"<prompt>\n[Attached document]\n<body>".Contentrather than mutating it. This is load-bearing: the middleware restores the originalcontentslist aftercall_next, and that restore only undoes the list swap — an in-place mutation would leak the raw PDF body into the AG-UIMESSAGES_SNAPSHOTand render a wall of PDF text in the user's chat bubble. There is a test for this.LegacyConverterShimappends a legacybinarymirror alongside every modern attachment part, so the same PDF reached the middleware twice and its body was being sent to the model twice (visible as the duplicated[6]/[7]above). Now emitted once.Post-fix outbound turn 2, same journal endpoint:
One user message, prompt intact, document intact, emitted once.
The fixture is untouched
The existing
userMessagematch key was always correct; the corrected request shape is what satisfies it. Relaxing or re-recording the fixture to match the broken request was an explicit non-goal — it would have made the cell actively certify a model that never sees the user's question.Same-pattern audit
_PdfFlattenChatMiddlewareis the onlyChatMiddlewareinms-agent-python, and the only place in the integration that constructsContentor reassignsmessage.contents(grepforChatMiddleware/Content.from_text/.contents =acrosssrc/returns hits in this one file only). No second instance of the pattern to fix.ms-agent-pythonis the only MS-Agent-Framework Python integration doing PDF flattening —ms-agent-dotnethas a multimodal e2e spec but no Python agent. The other[Attached document]implementations (langgraph-python,langgraph-fastapi,agno,claude-sdk-python,langroid,pydantic-ai,langgraph-typescript,built-in-agent) run on frameworks that do not split a message's contents into separate wire messages, so they are not exposed to this. The upstream one-message-per-Contentbehavior is pinned by a dedicated test, so if it ever changes we find out by that test failing rather than by a silent regression.shared/symlink (git ls-files -s→100644). No shared code touched;validate-shared-symlinks.tsconfirms no new erosion.Red / green / control
All three on the real probe surface, from a clean worktree at
origin/main38613623f4.RED — before the change
Evidence the outbound request lacked the prompt — aimock journal from that run, 8 entries,
200,503,503,503,200,503,503,503(2 attempts × 3 retries on turn 2):GREEN — after the change, fixture unchanged
Both turns pass. aimock journal for that run: 2 entries, statuses
200,200(down from 8 entries with six 503s — no retries needed). The fixture was not modified;git diff origin/main -- showcase/aimock/is empty and the diff is two files, both undershowcase/integrations/ms-agent-python/.CONTROL — an already-green integration, same command, same stack
Local harness, shared probe, shared frontend and fixtures are all sound — the red was specific to this integration.
Covering test
showcase/integrations/ms-agent-python/tests/python/test_multimodal_pdf_prompt.py— 7 tests. Not fakes: each one drives the real_PdfFlattenChatMiddlewareand then the realOpenAIChatCompletionClient._prepare_message_for_openai, and asserts against the actual OpenAI wire payload. The PDF is the bundledpublic/demo-files/sample.pdfthrough realpypdf, and the prompt asserted on is read out of the real aimock fixture rather than hardcoded, so the test fails if either side drifts.Test-level red→green (stash the source change, keep the tests):
with the primary failure reading:
Coverage: prompt survives to the final user turn; the turn stays one user message; the upstream one-message-per-
Contentsplit is pinned; originalcontentsrestored and the promptContentnot mutated; duplicate mirror parts flattened once; attachment-only turn still flattens; image turn left byte-identical.Pre-push
validate-parity.ts20/20 pass ·validate-shared-symlinks.tsno new erosion ·aimock-fixtures.test.ts842 pass · fulltests/python/suite 13 pass · lefthooklint-fix+commitlintclean · Python lines ≤88 cols matching the file's existing style · no lockfile churn, two files in the diff.Scope
One cell, one middleware, one integration. The other five red
multimodalcells from the same sweep have five different root causes and are not addressed here.🤖 Generated with Claude Code
https://claude.ai/code/session_01PYdjeveT8Xof9TyHWMLoJr