Skip to content

Commit 377db66

Browse files
author
roberttwang
committed
fix(sop): stream artifact handoffs and settle transfer failures
1 parent 91332e3 commit 377db66

38 files changed

Lines changed: 1579 additions & 277 deletions

‎docs/deployment.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,12 @@ The upstream process roles remain `-role api`, `-role worker` and `-role all`. A
191191

192192
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.
193193

194+
SOP deliverables support up to 20 MiB per file. Runner 0.13.0 and later transfer
195+
declared files separately from the task completion report, so several files
196+
can be handed off together. Installations with automatic Runner updates
197+
enabled receive the bundled version after the platform release. Older Runners
198+
keep their 1 MiB inline upload limit until they update.
199+
194200
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.
195201

196202
The installer checks the helper destinations against the staged macOS binary and installs the required Gate MCP helpers before replacing an installed Runner. When the existing Runner has a working Docker helper, an upgrade requires a compatible helper at the new Runner's configured path before replacing the binary and restarting the service. Relative templates in the installed launchd configuration use the job's working directory. The installer and updater validate the Linux executable's format, architecture, and load segments before replacing it. Custom installs keep a compatible existing helper. A Runner built from a local checkout can build its companion from that checkout. A download URL with an `{os}` placeholder can supply both binaries when used as the Runner's download source.
@@ -220,8 +226,9 @@ For an external MySQL deployment, review that migration and check column existen
220226
Compose runs `migrations/042_run_artifacts_content_mediumtext.sql` before the
221227
platform starts, including during `./start.sh pull`. The native development
222228
script runs the same migration against its Compose database. It widens an existing
223-
`run_artifacts.content` column from `TEXT` to `MEDIUMTEXT` for the 1 MiB artifact
224-
contract and preserves existing data, character set, collation and nullability.
229+
`run_artifacts.content` column from `TEXT` to `MEDIUMTEXT` for inline artifacts
230+
and preserves existing data, character set, collation and nullability. Larger
231+
files use separate chunk tables added at platform startup.
225232
For a deployment using an external MySQL server and no Compose startup, run this
226233
SQL file in the deployment's database upgrade step before starting the new binary.
227234
If the Compose migration fails, review `docker compose --profile platform logs

‎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
@@ -265,6 +265,7 @@ type Artifact struct {
265265
Size int64 `json:"size"`
266266
SHA256 string `json:"sha256"`
267267
Content string `json:"content"`
268+
BlobID string `json:"-"`
268269
// RepositoryDir records which run repository workspace the artifact was
269270
// collected from (empty = run workspace root, where SOP deliverables live).
270271
RepositoryDir string `json:"repositoryDir,omitempty"`

‎internal/domain/runner.go‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,15 @@ func (r Runner) SupportsCodeBuddyBaseURL() bool {
153153
// when checking out repositories for a native workspace. Older runners clone fully.
154154
const RunnerVersionRepositoryCache = "0.12.0"
155155

156+
// RunnerVersionArtifactTransfer introduced task-scoped streaming for SOP files.
157+
const RunnerVersionArtifactTransfer = "0.13.0"
158+
159+
const RunnerResultReportError = "执行结果回传失败"
160+
161+
func (r Runner) SupportsArtifactTransfer() bool {
162+
return versionAtLeast(r.RunnerVersion, RunnerVersionArtifactTransfer)
163+
}
164+
156165
func (r Runner) SupportsSharedPush() bool {
157166
return versionAtLeast(r.RunnerVersion, RunnerVersionSharedPush)
158167
}
@@ -567,6 +576,7 @@ type RunnerInvocation struct {
567576
// move a missing output file found elsewhere in the workspace into
568577
// place, as the control plane does for its own sandboxes.
569578
ReportOutputs bool `json:"reportOutputs,omitempty"`
579+
ArtifactTransfer bool `json:"artifactTransfer,omitempty"`
570580
OutputFiles []string `json:"outputFiles,omitempty"`
571581
RecoverOutputs bool `json:"recoverOutputs,omitempty"`
572582
HumanContext string `json:"humanContext,omitempty"`
@@ -668,17 +678,22 @@ func (inv *RunnerInvocation) GitSSHRemotes() []string {
668678

669679
// RunnerInputFile is one file written into the task workspace before a run.
670680
type RunnerInputFile struct {
671-
Path string `json:"path"`
672-
Content string `json:"content"`
681+
Path string `json:"path"`
682+
Content string `json:"content,omitempty"`
683+
ArtifactID string `json:"artifactId,omitempty"`
684+
SHA256 string `json:"sha256,omitempty"`
685+
Restore bool `json:"restore,omitempty"`
673686
}
674687

675688
// RunnerTaskOutputs is what a runner reports about the task workspace after
676689
// an invocation or script.
677690
type RunnerTaskOutputs struct {
678691
// Files maps a workspace-relative OutputFiles path to its content. Missing
679692
// files and non-regular files are absent; oversized ones are in TooLarge.
680-
Files map[string]string `json:"files,omitempty"`
681-
TooLarge []string `json:"tooLarge,omitempty"`
693+
Files map[string]string `json:"files,omitempty"`
694+
TooLarge []string `json:"tooLarge,omitempty"`
695+
FileBlobs map[string]ArtifactBlob `json:"fileBlobs,omitempty"`
696+
FileErrors map[string]string `json:"fileErrors,omitempty"`
682697
// Patches maps a repository checkout dir ("" is the workspace root) to
683698
// its repository-patch inventory. Unchanged checkouts are absent.
684699
Patches map[string]string `json:"patches,omitempty"`

‎internal/engine/artifacts.go‎

Lines changed: 102 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"crypto/sha256"
77
"errors"
88
"fmt"
9+
"io"
910
"io/fs"
1011
"os"
1112
"os/exec"
@@ -22,7 +23,7 @@ const maxArtifactBytes = 1 << 20
2223
// clock tick.
2324
var artifactSeq atomic.Uint64
2425

25-
func materializeInputs(workspace string, wf domain.WorkflowDefinition, node domain.WorkflowNode, run domain.Run) (string, error) {
26+
func materializeInputs(workspace string, wf domain.WorkflowDefinition, node domain.WorkflowNode, run domain.Run, open ...func(string) (io.ReadCloser, error)) (string, error) {
2627
sources := map[string]bool{}
2728
for _, edge := range wf.Edges {
2829
if edge.Target == node.ID {
@@ -53,33 +54,9 @@ func materializeInputs(workspace string, wf domain.WorkflowDefinition, node doma
5354
fmt.Fprintf(&manifest, "## %s / repository-patch (%s)\n\nNo full diff is stored. The run workspace is the source of truth.\n\n%s\n\n", artifact.NodeID, artifact.RepositoryDir, summary)
5455
continue
5556
}
56-
nodeSegment := safePathSegment(nodeControlKey(run, artifact.NodeID))
57-
controlSegments := []string{"inputs", nodeSegment}
58-
if artifact.RepositoryDir != "" {
59-
controlSegments = append(controlSegments, safePathSegment(artifact.RepositoryDir))
60-
}
61-
inputDir, err := runtime.EnsureControlDirectory(workspace, controlSegments...)
62-
if err != nil {
63-
return "", err
64-
}
65-
fileName := safePathSegment(artifact.Name) + extensionFor(artifact.MediaType)
6657
rel := artifactInputRelPath(run, artifact)
67-
target := filepath.Join(inputDir, fileName)
68-
if info, err := os.Lstat(target); err == nil {
69-
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
70-
return "", fmt.Errorf("artifact input path is not a regular file: %s", target)
71-
}
72-
if err := os.Chmod(target, 0o600); err != nil {
73-
return "", err
74-
}
75-
} else if err != nil && !os.IsNotExist(err) {
76-
return "", err
77-
}
78-
if err := os.WriteFile(target, []byte(artifact.Content), 0o600); err != nil {
79-
return "", err
80-
}
81-
if err := os.Chmod(target, 0o444); err != nil {
82-
return "", err
58+
if err := materializeOneInput(workspace, rel, artifact, open); err != nil {
59+
return "", fmt.Errorf("写入交接输入 %s:%w", rel, err)
8360
}
8461
writeInputManifestEntry(&manifest, artifact, rel)
8562
}
@@ -91,6 +68,38 @@ func materializeInputs(workspace string, wf domain.WorkflowDefinition, node doma
9168
return strings.TrimSpace(manifest.String()), nil
9269
}
9370

71+
func materializeOneInput(workspace, rel string, artifact domain.Artifact, open []func(string) (io.ReadCloser, error)) error {
72+
if len(open) == 0 {
73+
return runtime.WriteArtifactInput(workspace, rel, "", strings.NewReader(artifact.Content))
74+
}
75+
body, err := open[0](artifact.ID)
76+
if err != nil {
77+
return err
78+
}
79+
defer body.Close()
80+
return runtime.WriteArtifactInput(workspace, rel, artifact.SHA256, body)
81+
}
82+
83+
// Patches and legacy handoff transcripts are inspected as text. All ordinary
84+
// deliverables can be opened directly by the workspace that consumes them.
85+
func (e *Engine) loadHandoffText(run *domain.Run, wf domain.WorkflowDefinition, nodeID string) {
86+
direct := make(map[string]bool)
87+
for _, edge := range wf.Edges {
88+
if edge.Target == nodeID {
89+
direct[edge.Source] = true
90+
}
91+
}
92+
for i, artifact := range run.Artifacts {
93+
handoff := run.WorkflowSnapshot.GroupSOPHandoff != nil && artifact.NodeID == groupSOPHandoffNode
94+
if !handoff && !(artifact.Name == "repository-patch" && direct[artifact.NodeID]) {
95+
continue
96+
}
97+
if stored, ok := e.repo.Artifact(run.ID, artifact.ID); ok {
98+
run.Artifacts[i].Content = stored.Content
99+
}
100+
}
101+
}
102+
94103
// artifactInputRelPath is where an upstream artifact is mounted for the
95104
// consuming node, relative to the run workspace.
96105
func artifactInputRelPath(run domain.Run, artifact domain.Artifact) string {
@@ -103,7 +112,7 @@ func artifactInputRelPath(run domain.Run, artifact domain.Artifact) string {
103112
}
104113

105114
func writeInputManifestEntry(manifest *strings.Builder, artifact domain.Artifact, rel string) {
106-
fmt.Fprintf(manifest, "## %s / %s\n\n- path: `%s`\n- sha256: `%s`\n- bytes: %d\n\nRead this file; the body is not inlined in the prompt.\n\n", artifact.NodeID, artifact.Name, rel, artifact.SHA256, len(artifact.Content))
115+
fmt.Fprintf(manifest, "## %s / %s\n\n- path: `%s`\n- sha256: `%s`\n- bytes: %d\n\nRead this file; the body is not inlined in the prompt.\n\n", artifact.NodeID, artifact.Name, rel, artifact.SHA256, max(artifact.Size, int64(len(artifact.Content))))
107116
}
108117

109118
// recoverMisplacedArtifacts copies required deliverables into the sandbox when
@@ -135,7 +144,7 @@ func recoverMisplacedArtifacts(workspace, hostLocalPath string, node domain.Work
135144
continue
136145
}
137146
info, err := os.Stat(src)
138-
if err != nil || info.IsDir() || info.Size() > maxArtifactBytes {
147+
if err != nil || !info.Mode().IsRegular() || info.Size() > domain.MaxSOPArtifactBytes {
139148
continue
140149
}
141150
data, err := os.ReadFile(src)
@@ -203,7 +212,7 @@ func removeUntrackedHostLeak(host, path string) {
203212
}
204213

205214
func (e *Engine) freezeAvailableArtifacts(runID string, node domain.WorkflowNode, workspace string, reported *reportedOutputs, output string) {
206-
current, ok := e.repo.RunState(runID)
215+
current, ok := e.repo.RunProgress(runID)
207216
if !ok {
208217
return
209218
}
@@ -222,9 +231,11 @@ func (e *Engine) freezeAvailableArtifacts(runID string, node domain.WorkflowNode
222231
if err != nil || len(artifacts) == 0 {
223232
return
224233
}
225-
e.updateRun(runID, func(r *domain.Run) {
234+
if !e.updateRunAt(runID, false, func(r *domain.Run) {
226235
r.Artifacts = append(r.Artifacts, artifacts...)
227-
})
236+
}) {
237+
return
238+
}
228239
for _, artifact := range artifacts {
229240
e.observe(runID, node.ID, domain.TelemetryEvent{Category: "artifact", Name: "artifact.published", Phase: "finish", Message: artifact.Name, Attributes: map[string]any{"artifactId": artifact.ID, "path": artifact.Path, "mediaType": artifact.MediaType, "size": artifact.Size, "sha256": artifact.SHA256}})
230241
}
@@ -252,16 +263,11 @@ func validateArtifactOutputs(outputs nodeOutputs, run domain.Run, node domain.Wo
252263
if contract.Name == "" || !ok {
253264
return fmt.Errorf("invalid artifact %q path %q", contract.Name, contract.Path)
254265
}
255-
if _, err := outputs.readFile(rel); err != nil {
256-
switch {
257-
case errors.Is(err, fs.ErrNotExist) && !contract.Required:
258-
continue
259-
case errors.Is(err, errOutputNotRegular):
260-
return fmt.Errorf("%s (%s) is not a regular file", contract.Name, rc.WorkspaceDir)
261-
case errors.Is(err, errOutputTooLarge):
262-
return fmt.Errorf("%s exceeds %d bytes", contract.Name, maxArtifactBytes)
263-
}
264-
return fmt.Errorf("%s (%s): %w", contract.Name, rc.WorkspaceDir, err)
266+
if !contract.Required {
267+
continue
268+
}
269+
if err := checkArtifactOutput(outputs, rel); err != nil {
270+
return fmt.Errorf("%s (%s): %w", contract.Name, rel, err)
265271
}
266272
}
267273
}
@@ -276,7 +282,12 @@ func collectArtifactsBestEffort(workspace string, run domain.Run, node domain.Wo
276282
return collectArtifactsMode(workspaceOutputs(workspace), run, node, output, true)
277283
}
278284

279-
func collectArtifactsMode(outputs nodeOutputs, run domain.Run, node domain.WorkflowNode, output string, bestEffort bool) ([]domain.Artifact, error) {
285+
func collectArtifactsMode(outputs nodeOutputs, run domain.Run, node domain.WorkflowNode, output string, bestEffort bool, warnings ...func(string)) ([]domain.Artifact, error) {
286+
warn := func(message string) {
287+
if len(warnings) != 0 {
288+
warnings[0](message)
289+
}
290+
}
280291
attempt := 0
281292
if nr := run.Nodes[node.ID]; nr != nil {
282293
attempt = nr.Attempt
@@ -302,28 +313,26 @@ func collectArtifactsMode(outputs nodeOutputs, run domain.Run, node domain.Workf
302313
}
303314
return nil, fmt.Errorf("invalid artifact %q path %q", contract.Name, contract.Path)
304315
}
305-
clean := filepath.Clean(contract.Path)
306-
content, err := outputs.readFile(rel)
307-
if err != nil {
308-
if bestEffort || errors.Is(err, fs.ErrNotExist) && !contract.Required {
309-
continue
310-
}
311-
if errors.Is(err, errOutputTooLarge) {
312-
return nil, fmt.Errorf("%s exceeds %d bytes", contract.Name, maxArtifactBytes)
313-
}
314-
return nil, fmt.Errorf("%s (%s): %w", contract.Name, rc.WorkspaceDir, err)
316+
mediaType := contract.MediaType
317+
if mediaType == "" {
318+
mediaType = "text/markdown"
315319
}
316-
if len(content) > maxArtifactBytes {
317-
if bestEffort {
320+
artifact := newArtifact(run.ID, node.ID, attempt, contract.Name, filepath.Clean(contract.Path), mediaType, nil)
321+
content, blob, err := collectOutputFile(outputs, rel, artifact.ID)
322+
if err != nil {
323+
if bestEffort || !contract.Required {
324+
if !bestEffort && !errors.Is(err, fs.ErrNotExist) {
325+
warn(fmt.Sprintf("跳过可选产物 %s(%s):%s", contract.Name, rel, err))
326+
}
318327
continue
319328
}
320-
return nil, fmt.Errorf("%s exceeds %d bytes", contract.Name, maxArtifactBytes)
329+
return nil, fmt.Errorf("%s (%s): %w", contract.Name, rel, err)
321330
}
322-
mediaType := contract.MediaType
323-
if mediaType == "" {
324-
mediaType = "text/markdown"
331+
if blob.ID != "" {
332+
artifact.BlobID, artifact.Size, artifact.SHA256 = blob.ID, blob.Size, blob.SHA256
333+
} else {
334+
setArtifactBody(&artifact, content)
325335
}
326-
artifact := newArtifact(run.ID, node.ID, attempt, contract.Name, clean, mediaType, content)
327336
artifact.RepositoryDir = rc.WorkspaceDir
328337
out = append(out, artifact)
329338
}
@@ -337,9 +346,7 @@ func collectArtifactsMode(outputs nodeOutputs, run domain.Run, node domain.Workf
337346
for _, rc := range patchTargets {
338347
patch, err := outputs.repositoryPatch(rc.WorkspaceDir)
339348
if err != nil {
340-
if !bestEffort {
341-
return nil, err
342-
}
349+
warn(fmt.Sprintf("跳过仓库变更清单 %s:%s", rc.WorkspaceDir, err))
343350
continue
344351
}
345352
if len(patch) == 0 {
@@ -362,6 +369,29 @@ func collectArtifactsMode(outputs nodeOutputs, run domain.Run, node domain.Workf
362369
return out, nil
363370
}
364371

372+
func reportedArtifactBlob(outputs nodeOutputs, rel string) (domain.ArtifactBlob, bool) {
373+
if reported, ok := outputs.(*reportedOutputs); ok {
374+
return reported.artifactBlob(rel)
375+
}
376+
return domain.ArtifactBlob{}, false
377+
}
378+
379+
func requiredNodeArtifacts(node domain.WorkflowNode, artifacts []domain.Artifact) []domain.Artifact {
380+
required := make(map[string]bool)
381+
for _, contract := range node.ArtifactOutputs {
382+
if contract.Required {
383+
required[contract.Name] = true
384+
}
385+
}
386+
var out []domain.Artifact
387+
for _, artifact := range artifacts {
388+
if required[artifact.Name] {
389+
out = append(out, artifact)
390+
}
391+
}
392+
return out
393+
}
394+
365395
func latestInputArtifacts(artifacts []domain.Artifact, direct, prior map[string]bool) []domain.Artifact {
366396
// Dedup by (node, repository, name, path): multi-repository runs emit one
367397
// repository-patch artifact per repository sharing the same logical name
@@ -409,9 +439,16 @@ func artifactPromptBody(artifact domain.Artifact) string {
409439
}
410440

411441
func newArtifact(runID, nodeID string, attempt int, name, path, mediaType string, content []byte) domain.Artifact {
412-
sum := sha256.Sum256(content)
413442
now := time.Now().UTC()
414-
return domain.Artifact{ID: fmt.Sprintf("artifact-%d-%d", now.UnixNano(), artifactSeq.Add(1)), RunID: runID, NodeID: nodeID, Attempt: attempt, Name: name, Path: path, MediaType: mediaType, Size: int64(len(content)), SHA256: fmt.Sprintf("%x", sum), Content: string(content), CreatedAt: now}
443+
art := domain.Artifact{ID: fmt.Sprintf("artifact-%d-%d", now.UnixNano(), artifactSeq.Add(1)), RunID: runID, NodeID: nodeID, Attempt: attempt, Name: name, Path: path, MediaType: mediaType, CreatedAt: now}
444+
setArtifactBody(&art, content)
445+
return art
446+
}
447+
448+
func setArtifactBody(art *domain.Artifact, content []byte) {
449+
art.Size = int64(len(content))
450+
art.SHA256 = fmt.Sprintf("%x", sha256.Sum256(content))
451+
art.Content = string(content)
415452
}
416453

417454
func appendArtifact(run *domain.Run, nodeID string, attempt int, name, path, mediaType string, content []byte) {

0 commit comments

Comments
 (0)