Skip to content

Commit 6f3f0b8

Browse files
Robert0622roberttwangroberttwangclaudecodex
authored
Prevent SOP runs from hanging after artifact write failures (#1301)
* fix(engine): settle rejected SOP artifact writes * fix(deploy): apply artifact storage migration before startup * fix(sop): stream artifact handoffs and settle transfer failures * fix(engine): load referenced artifact bodies for prompt placeholders Agent invocations now read run progress without artifact bodies, so {{artifact.<node>.<name>}} was replaced with an empty string. Load the stored body of each referenced artifact before substitution. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix(engine): poll run progress without reading artifact bodies The claim loop and child SOP wait loop re-read run state every few seconds or 200 ms. RunState now hydrates chunked files of up to 20 MiB, so these loops read every archived body on each tick. Poll with RunProgress and read the child's bodies once when it finishes. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix(runners): claim tasks without sorting their payloads A legacy runner receives its input files inline, so a queued task payload can carry more than a megabyte. Sorting whole runner_tasks rows then exceeds MySQL's default 256 KiB sort buffer (error 1038), every claim for that provider fails and the SOP stays queued. Claims and the task list now sort only narrow columns and load payloads by ID. The route sweep also covers the /api aliases of the Runner file transfer endpoints, which keeps e2e route coverage above the 85% gate. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix(web): keep large and binary deliverables out of the in-page preview Deliverables can now be 20 MiB, but the preview dialogs read the whole body into the page and render it as text. A 20 MiB binary froze the run page for about 34 seconds, and the download button re-encoded the decoded text, so binary files were corrupted. Show a download hint instead of a preview for binary types and files above 5 MiB, and download the original bytes through the artifact URL. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix(runs): keep the original extension when a deliverable is downloaded The artifact response named every non-Markdown and non-JSON deliverable .txt, so a binary file published by a SOP was saved as a text file. Name it after the source path and fall back to the artifact name. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix(web): keep the artifact download control a button The preview dialog's download control became a link, which broke its button role and the focus order the approvals queue test relies on. Keep the button and download the original bytes from the artifact URL. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix(web): detect binary deliverables by content before previewing A deliverable declared without a media type is stored as text/markdown, so a small zip or other binary file was still rendered as garbage. Check the body instead of the declared type: NUL bytes or a mostly undecodable start show the download hint, while text types such as NDJSON keep previewing. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix(engine): retry failed node state after a MySQL deadlock * fix(web): avoid fetching known binary artifacts for preview * test: keep artifact installer fixture compatible with LOOP migration * fix(engine): keep auto-reject when a failed node's terminal write errors Only a lost or held run lease skips the auto-reject now. Other write errors (lock wait timeout, transient store failures, an exhausted deadlock budget) still call Reject, which reloads the run and resets the node with its upstream, so the run no longer hangs in running with nobody executing the node. Deadlock retries reuse the repo's six-attempt RetryDeadlock budget. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix: retry failed SOP state writes without losing rework diagnostics --------- Co-authored-by: roberttwang <roberttwang@tencent.com> Co-authored-by: roberttwang <u_dc6754cd1ee5@users.noreply.local> Co-authored-by: Claude Code <noreply@anthropic.com> Co-authored-by: Codex <codex@users.noreply.github.com>
1 parent 78cdab4 commit 6f3f0b8

55 files changed

Lines changed: 2446 additions & 293 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎chatbot/src/RichContent.jsx‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -538,13 +538,24 @@ export function Attachment({ attachment, sessionId, onOpen }) {
538538
</>
539539
);
540540
}
541+
// Larger files are offered for download instead of being read into the page.
542+
const PREVIEW_MAX_BYTES = 5 * 1024 * 1024;
543+
// Deliverables without a declared type are stored as Markdown, so the body
544+
// decides: NUL bytes or a mostly undecodable start mean binary content.
545+
function looksBinary(content) {
546+
if (content.includes("\u0000")) return true;
547+
const head = content.slice(0, 65536);
548+
return (head.match(/\uFFFD/g) || []).length > head.length * 0.1;
549+
}
541550
export function ArtifactPreview({ artifact }) {
542551
const [text, setText] = useState("");
543552
const [error, setError] = useState("");
544553
const [mode, setMode] = useState("preview");
545554
const readable =
546555
!artifact?.mimeType ||
547556
/^(text\/|application\/(json|javascript|xml))/.test(artifact.mimeType);
557+
const oversized =
558+
Boolean(artifact?.url) && (artifact?.size || 0) > PREVIEW_MAX_BYTES;
548559
// An attached HTML file (e.g. a demo from the workspace) previews in the same
549560
// script-only sandbox as an html code block.
550561
const kind =
@@ -577,7 +588,7 @@ export function ArtifactPreview({ artifact }) {
577588
current = false;
578589
};
579590
}
580-
if (artifact?.url && readable)
591+
if (artifact?.url && readable && !oversized)
581592
fetch(artifact.url)
582593
.then((r) => {
583594
if (!r.ok) throw Error("文件读取失败");
@@ -592,10 +603,12 @@ export function ArtifactPreview({ artifact }) {
592603
return () => {
593604
current = false;
594605
};
595-
}, [artifact?.id, artifact?.url, artifact?.localDataUrl, readable]);
606+
}, [artifact?.id, artifact?.url, artifact?.localDataUrl, readable, oversized]);
596607
if (!artifact) return null;
597608
const source = artifact.url ? text : (artifact.content ?? text);
598-
const hasSource = typeof source === "string" && source.length > 0 && !error;
609+
const binary = Boolean(artifact.url) && looksBinary(text);
610+
const hasSource =
611+
typeof source === "string" && source.length > 0 && !error && !binary;
599612
const isMarkdown =
600613
artifact.mimeType?.startsWith("text/markdown") ||
601614
["markdown", "md"].includes(artifact.language?.toLowerCase());
@@ -695,6 +708,10 @@ export function ArtifactPreview({ artifact }) {
695708
src={artifact.url}
696709
alt={artifact.name}
697710
/>
711+
) : oversized ? (
712+
<p className="muted">文件较大,不在页面内预览,可通过右上角下载查看。</p>
713+
) : binary ? (
714+
<p className="muted">此类型文件可通过右上角下载查看。</p>
698715
) : mode === "source" && canPreview ? (
699716
<pre className="artifact-source">
700717
<code>{source}</code>

‎chatbot/tests/components.test.jsx‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,51 @@ describe("content and panels", () => {
216216
globalThis.fetch = originalFetch;
217217
});
218218

219+
test("offers oversized text artifacts for download instead of loading them", async () => {
220+
const originalFetch = globalThis.fetch;
221+
globalThis.fetch = vi.fn(async () => ({ ok: true, text: async () => "body" }));
222+
render(
223+
<>
224+
<ArtifactPreview artifact={{
225+
id: "big",
226+
name: "big.log",
227+
mimeType: "text/plain",
228+
url: "/big.log",
229+
size: 6 * 1024 * 1024,
230+
}} />
231+
<ArtifactPreview artifact={{
232+
id: "small",
233+
name: "small.log",
234+
mimeType: "text/plain",
235+
url: "/small.log",
236+
size: 1024,
237+
}} />
238+
</>,
239+
);
240+
expect(await screen.findByText("body")).toBeInTheDocument();
241+
expect(screen.getByText("文件较大,不在页面内预览,可通过右上角下载查看。")).toBeInTheDocument();
242+
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
243+
expect(globalThis.fetch).toHaveBeenCalledWith("/small.log");
244+
globalThis.fetch = originalFetch;
245+
});
246+
247+
test("offers binary content declared as Markdown for download", async () => {
248+
const originalFetch = globalThis.fetch;
249+
globalThis.fetch = vi.fn(async () => ({ ok: true, text: async () => "PK\u0003\u0004\u0000\u0000garbage" }));
250+
render(
251+
<ArtifactPreview artifact={{
252+
id: "zip",
253+
name: "pkg.zip",
254+
mimeType: "text/markdown",
255+
url: "/pkg.zip",
256+
size: 2048,
257+
}} />,
258+
);
259+
expect(await screen.findByText("此类型文件可通过右上角下载查看。")).toBeInTheDocument();
260+
expect(screen.queryByText(/garbage/)).not.toBeInTheDocument();
261+
globalThis.fetch = originalFetch;
262+
});
263+
219264
test("previews an attached HTML file in the script-only sandbox", async () => {
220265
const user = userEvent.setup();
221266
const originalFetch = globalThis.fetch;

‎compose.yaml‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,25 @@ services:
1717
interval: 2s
1818
timeout: 3s
1919
retries: 60
20+
artifact-migration:
21+
profiles: [platform]
22+
# Upgrade existing volumes before the platform starts. Fresh schemas are created by the platform.
23+
image: mysql:8.4
24+
entrypoint: ["sh", "-ec"]
25+
command:
26+
- exec mysql -h mysql -u loopforge loopforge < /migrations/042_run_artifacts_content_mediumtext.sql
27+
environment:
28+
MYSQL_PWD: ${LOOPFORGE_DB_PASSWORD:?Run scripts/configure.sh first}
29+
volumes:
30+
- type: bind
31+
source: ./migrations/042_run_artifacts_content_mediumtext.sql
32+
target: /migrations/042_run_artifacts_content_mediumtext.sql
33+
read_only: true
34+
bind:
35+
create_host_path: false
36+
depends_on:
37+
mysql:
38+
condition: service_healthy
2039
platform:
2140
profiles: [platform]
2241
# Published release stack: never builds. Bump the pinned tag (here and in
@@ -76,6 +95,8 @@ services:
7695
depends_on:
7796
mysql:
7897
condition: service_healthy
98+
artifact-migration:
99+
condition: service_completed_successfully
79100
healthcheck:
80101
test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/health', timeout=2).close()"]
81102
interval: 3s

‎docs/deployment.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,12 @@ The upstream process roles remain `-role api`, `-role worker` and `-role all`. A
242242

243243
Personal runners are connected from the execution-machine page with a short-lived binding code. The installer is served at `/runners/install.sh`. `AGENTFLOW_RUNNER_BINARY` can point to binaries with `{os}` and `{arch}` substitutions. Container images bundle Linux/macOS amd64/arm64 runner and gate binaries. Native source installations can build on demand with Go.
244244

245+
SOP deliverables support up to 20 MiB per file. Runner 0.13.0 and later transfer
246+
declared files separately from the task completion report, so several files
247+
can be handed off together. Installations with automatic Runner updates
248+
enabled receive the bundled version after the platform release. Older Runners
249+
keep their 1 MiB inline upload limit until they update.
250+
245251
The machine owner can use **Settings → Execution machines → Shared projects** to grant access to one or more projects where they are the owner or a member with write access. Members with write access can select a compatible shared machine for a new conversation. **Use in this project** sets a default for that user and project. Each new turn on a shared machine requires a current grant and project write access for both the machine owner and the sender. Removing a grant clears the saved project defaults that pointed to the machine.
246252

247253
Docker workspaces on macOS use a Linux Runner executable for Git credentials and MCP calls. The installer chooses the architecture of the installed macOS Runner, including Intel binaries running under Rosetta. For a universal Runner on Apple Silicon it installs the arm64 helpers and adds the amd64 helpers when available. Foreground starts and the command printed by `--no-start` select the native arm64 slice, including from a Rosetta shell. On Intel Macs the installer installs the amd64 helpers. By default, it places the helpers next to the host binary. A Runner-side `AGENTFLOW_RUNNER_BINARY` template with `{os}` selects the installation and runtime path. To install both helpers, use `{arch}` and give each architecture a distinct destination. The installer saves the template for upgrades and includes it in launchd and in the startup command printed by `--no-start`. Helper paths must resolve to files separate from the macOS Runner.
@@ -275,6 +281,17 @@ For an external MySQL deployment, review that migration and check column existen
275281
| Required manual upgrade migrations | `009_bot_interactions_utf8mb4.sql`, `036_git_http_credentials.sql` | Follow each migration's timing and prerequisites. [Migrating existing GitHub credentials](#migrating-existing-github-credentials) |
276282
| Optional backfills and rewrites of existing rows | `016_public_optional_repositories.sql`, `021_assistant_session_sources.sql` | Run them if the installation needs the converted rows |
277283

284+
Compose runs `migrations/042_run_artifacts_content_mediumtext.sql` before the
285+
platform starts, including during `./start.sh pull`. The native development
286+
script runs the same migration against its Compose database. It widens an existing
287+
`run_artifacts.content` column from `TEXT` to `MEDIUMTEXT` for inline artifacts
288+
and preserves existing data, character set, collation and nullability. Larger
289+
files use separate chunk tables added at platform startup.
290+
For a deployment using an external MySQL server and no Compose startup, run this
291+
SQL file in the deployment's database upgrade step before starting the new binary.
292+
If the Compose migration fails, review `docker compose --profile platform logs
293+
artifact-migration`, resolve the database error and rerun the upgrade.
294+
278295
### Migrating existing sandboxes to inline assets
279296

280297
For a published Compose release, check out the target release and run `./start.sh pull`. If other API or worker processes share the Compose database, stop them first. After pulling the images, the command checks that the target image supports inline Dockerfiles and that the database still has a legacy asset table. When both conditions hold, it stops the platform, saves a database dump in `.local/loopforge-before-041.*/loopforge.sql`, and runs 041 before starting the new platform. An empty database or one whose legacy tables are already gone skips 041.

‎e2e/api/30-runs.test.mjs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,22 @@ test('approval gate: reject reworks upstream in the same workspace, approve comp
8888
assert.equal(summary?.status, 'succeeded');
8989
});
9090

91+
test('evaluation waits for the run to finish and leaves no partial history', async () => {
92+
const workflow = await createWorkflow('eval-approval', [script('prepare', 'echo ready'), approval('gate', 'prepare')]);
93+
const { id } = await startRun(workflow);
94+
await waitRun(id, run => nodeStatus(run, 'gate') === 'waiting_approval');
95+
96+
const path = `/api/runs/${id}`;
97+
await post(`${path}/eval`, {}, { expect: 409 });
98+
assert.deepEqual(await get(`${path}/eval`), { runId: id, status: '' });
99+
assert.deepEqual(await get(`${path}/evals`), []);
100+
await get(`${path}/eval/stream`, { expect: 404 });
101+
await post(`${path}/eval/apply`, { recommendationIds: ['missing'] }, { expect: 404 });
102+
103+
await post(`${path}/approve`, { nodeId: 'gate' });
104+
await waitRun(id, run => run.status === 'succeeded');
105+
});
106+
91107
test('failed script: retry from the node succeeds on the second attempt', {
92108
todo: 'POST /api/runs/:id/retry tears the failed attempt\'s sandbox down inside the request (docker rm -f of the agentflow-run-*-scripts sidecar, up to dockerTeardownTimeout=60s); under nested Docker that rm hangs, so the call outlives the 60s client timeout',
93109
}, async () => {

‎e2e/api/90-route-sweep.test.mjs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ test('runner task plane requires a runner session', async () => {
146146
['POST', `/api/runners/tasks/${MISSING}/start`], ['POST', `/api/runners/tasks/${MISSING}/lease/renew`],
147147
['GET', `/api/runners/tasks/${MISSING}/events`], ['POST', `/api/runners/tasks/${MISSING}/events`],
148148
['POST', `/api/runners/tasks/${MISSING}/complete`], ['GET', `/api/runners/tasks/${MISSING}/control`],
149+
['GET', `/api/runners/tasks/${MISSING}/input-file?path=plan.md`], ['PUT', `/api/runners/tasks/${MISSING}/output-file?path=plan.md`],
149150
['POST', '/runners/tasks/claim'], ['GET', `/runners/tasks/${MISSING}/control`],
150151
['POST', `/runners/previews/${MISSING}/complete`], ['PUT', `/runners/previews/${MISSING}/content`],
151152
];
@@ -178,6 +179,7 @@ test('runner management: register, heartbeat, runtime status, run limit, unknown
178179
for (const [method, path] of [
179180
['GET', `/api/runners/tasks/${MISSING}`], ['POST', `/api/runners/tasks/${MISSING}/start`],
180181
['POST', `/api/runners/tasks/${MISSING}/lease/renew`], ['GET', `/api/runners/tasks/${MISSING}/control`],
182+
['GET', `/api/runners/tasks/${MISSING}/input-file?path=plan.md`], ['PUT', `/api/runners/tasks/${MISSING}/output-file?path=plan.md`],
181183
]) {
182184
await status(method, path, method === 'GET' ? undefined : {}, [400, 403, 404, 409], session);
183185
}

‎internal/domain/artifact_blob.go‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package domain
2+
3+
import (
4+
"crypto/sha256"
5+
"encoding/hex"
6+
"errors"
7+
)
8+
9+
const MaxSOPArtifactBytes = 20 << 20
10+
const MaxInlineRunnerArtifactBytes = 1 << 20
11+
12+
var ErrArtifactTooLarge = errors.New("artifact exceeds the file size limit")
13+
14+
type ArtifactBlob struct {
15+
ID string `json:"id"`
16+
Size int64 `json:"size"`
17+
SHA256 string `json:"sha256"`
18+
}
19+
20+
func RunnerOutputBlobID(taskID, path string) string {
21+
sum := sha256.Sum256([]byte(taskID + "\x00" + path))
22+
return hex.EncodeToString(sum[:])
23+
}

‎internal/domain/run.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,7 @@ type Artifact struct {
281281
Size int64 `json:"size"`
282282
SHA256 string `json:"sha256"`
283283
Content string `json:"content"`
284+
BlobID string `json:"-"`
284285
// RepositoryDir records which run repository workspace the artifact was
285286
// collected from (empty = run workspace root, where SOP deliverables live).
286287
RepositoryDir string `json:"repositoryDir,omitempty"`

‎internal/domain/runner.go‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,15 @@ func (r Runner) SupportsProjectCredentials() bool {
242242
return versionAtLeast(r.RunnerVersion, RunnerVersionProjectCredentials)
243243
}
244244

245+
// RunnerVersionArtifactTransfer introduced task-scoped streaming for SOP files.
246+
const RunnerVersionArtifactTransfer = "0.13.0"
247+
248+
const RunnerResultReportError = "执行结果回传失败"
249+
250+
func (r Runner) SupportsArtifactTransfer() bool {
251+
return versionAtLeast(r.RunnerVersion, RunnerVersionArtifactTransfer)
252+
}
253+
245254
// RunnerVersionConversationSOPWorkspace discovers nested conversation checkouts
246255
// and prepares them inside the SOP sandbox while preserving local work.
247256
const RunnerVersionConversationSOPWorkspace = "0.12.3"
@@ -684,6 +693,7 @@ type RunnerInvocation struct {
684693
// move a missing output file found elsewhere in the workspace into
685694
// place, as the control plane does for its own sandboxes.
686695
ReportOutputs bool `json:"reportOutputs,omitempty"`
696+
ArtifactTransfer bool `json:"artifactTransfer,omitempty"`
687697
OutputFiles []string `json:"outputFiles,omitempty"`
688698
RecoverOutputs bool `json:"recoverOutputs,omitempty"`
689699
HumanContext string `json:"humanContext,omitempty"`
@@ -788,17 +798,22 @@ func (inv *RunnerInvocation) GitSSHRemotes() []string {
788798

789799
// RunnerInputFile is one file written into the task workspace before a run.
790800
type RunnerInputFile struct {
791-
Path string `json:"path"`
792-
Content string `json:"content"`
801+
Path string `json:"path"`
802+
Content string `json:"content,omitempty"`
803+
ArtifactID string `json:"artifactId,omitempty"`
804+
SHA256 string `json:"sha256,omitempty"`
805+
Restore bool `json:"restore,omitempty"`
793806
}
794807

795808
// RunnerTaskOutputs is what a runner reports about the task workspace after
796809
// an invocation or script.
797810
type RunnerTaskOutputs struct {
798811
// Files maps a workspace-relative OutputFiles path to its content. Missing
799812
// files and non-regular files are absent; oversized ones are in TooLarge.
800-
Files map[string]string `json:"files,omitempty"`
801-
TooLarge []string `json:"tooLarge,omitempty"`
813+
Files map[string]string `json:"files,omitempty"`
814+
TooLarge []string `json:"tooLarge,omitempty"`
815+
FileBlobs map[string]ArtifactBlob `json:"fileBlobs,omitempty"`
816+
FileErrors map[string]string `json:"fileErrors,omitempty"`
802817
// Patches maps a repository checkout dir ("" is the workspace root) to
803818
// its repository-patch inventory. Unchanged checkouts are absent.
804819
Patches map[string]string `json:"patches,omitempty"`

0 commit comments

Comments
 (0)