<span id="测试与提交工作流项目"></span>

# Test and Submit Workflow Projects

Collect a snapshot of the current project directory inside a workflow authoring task, send it to the server for compilation and testing, and submit a verified candidate for user review.

(sdk-ai-studio-workflow-project-flow)=
<span id="任务流程"></span>

## Task flow

1. Read a single in-memory snapshot of regular files under `workflow`, `operators`, and `tests` from the project directory.
2. Run candidate tests against that snapshot and confirm that the test report status reaches `completed`.
3. Submit the same file snapshot as a candidate and verify that compilation succeeds (`ok` is true) and `test_status` is `passed`.
4. Wait for the authoring task to emit the candidate artifact, then extract the task ID, artifact ID, and proposal ID for user review.

(sdk-ai-studio-workflow-project-prepare)=
<span id="准备"></span>

## Prerequisites

1. Complete the SDK installation and environment setup in [Use the SDK](../../../quickstart/ai-studio/sdk.md).
2. **Authoring task runtime**: run inside the active workflow authoring task environment and retain the injected `MOI_ENDPOINT`, `MOI_API_KEY`, `MOI_RUNTIME_AUTHORIZATION`, and `MOI_WORKSPACE_ID` variables; candidate submission validates the owning task and conversation scope.
3. **Project directory and test fixtures**: read the current workflow definition, custom operators, and test cases from the task's project directory while preserving unrelated nodes and settings. Candidate tests execute workflow nodes, so verify the authorized scope of any external write or message-sending steps beforehand.

(sdk-ai-studio-workflow-project-submit)=
<span id="测试当前快照并提交候选"></span>

## Test a snapshot and submit the candidate

Set the project root directory variable before running the example. The client reads local files once and sends the exact same snapshot to both the test call and the submission call so local edits cannot diverge between requests.

```bash
export WORKFLOW_PROJECT_DIR="/path/to/current/project"
```

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
import os
from pathlib import Path

from google.protobuf.json_format import MessageToDict
import moi_product_sdk as sdk

root = Path(os.environ["WORKFLOW_PROJECT_DIR"])
if root.is_symlink() or not root.is_dir():
    raise ValueError("Project root must be a regular directory")
files = {}
for name in ("workflow", "operators", "tests"):
    directory = root / name
    if not directory.exists() and name != "workflow":
        continue
    if directory.is_symlink() or not directory.is_dir():
        raise ValueError(f"Invalid project directory: {name}")
    for path in directory.rglob("*"):
        if path.is_symlink():
            raise ValueError(f"Symbolic link is not allowed: {path}")
        if path.is_file():
            files[path.relative_to(root).as_posix()] = path.read_bytes()
        elif not path.is_dir():
            raise ValueError(f"Non-regular file: {path}")
client = sdk.Client(
    os.environ["MOI_ENDPOINT"],
    sdk.with_api_key(os.environ["MOI_API_KEY"]),
    sdk.with_runtime_authorization(os.environ["MOI_RUNTIME_AUTHORIZATION"]),
)
workflows = client.workspace(os.environ["MOI_WORKSPACE_ID"]).workflows()
report = workflows.test_candidate(sdk.WorkflowCandidateTestRequest(project_files=files))
print("Test report:", MessageToDict(report, preserving_proto_field_name=True))
if report.status != "completed":
    raise SystemExit("Repair the project before submitting a candidate")
candidate = workflows.submit_candidate(sdk.WorkflowCandidateSubmitRequest(project_files=files))
print("Compiled:", candidate.ok, "Test status:", candidate.test_status)
print("Candidate:", candidate.candidate_id)
if not candidate.ok or candidate.test_status != "passed":
    raise SystemExit("Inspect candidate diagnostics and current test evidence")
print("Ready for review; no acceptance or deployment was performed.")
```

::::

::::{tab-item} Go
:sync: go

```go
package main

import (
	"context"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"

	sdk "github.com/matrixorigin/matrixflow/sdk/go-sdk"
	"google.golang.org/protobuf/encoding/protojson"
)

func main() {
	root := os.Getenv("WORKFLOW_PROJECT_DIR")
	info, err := os.Lstat(root)
	if err != nil {
		panic(err)
	}
	if !info.IsDir() {
		panic("Project root must be a regular directory")
	}
	files := map[string][]byte{}
	for _, name := range []string{"workflow", "operators", "tests"} {
		directory := filepath.Join(root, name)
		if _, err := os.Lstat(directory); err != nil {
			if os.IsNotExist(err) && name != "workflow" {
				continue
			}
			panic(err)
		}
		err = filepath.WalkDir(directory, func(path string, entry fs.DirEntry, walkErr error) error {
			if walkErr != nil {
				return walkErr
			}
			if entry.IsDir() {
				return nil
			}
			if !entry.Type().IsRegular() {
				return fmt.Errorf("Non-regular file: %s", path)
			}
			relative, err := filepath.Rel(root, path)
			if err != nil {
				return err
			}
			files[filepath.ToSlash(relative)], err = os.ReadFile(path)
			return err
		})
		if err != nil {
			panic(err)
		}
	}
	client, err := sdk.New(os.Getenv("MOI_ENDPOINT"),
		sdk.WithAPIKey(os.Getenv("MOI_API_KEY")),
		sdk.WithRuntimeAuthorization(os.Getenv("MOI_RUNTIME_AUTHORIZATION")))
	if err != nil {
		panic(err)
	}
	defer client.Close()
	workspace, err := client.Workspace(os.Getenv("MOI_WORKSPACE_ID"))
	if err != nil {
		panic(err)
	}
	workflows := workspace.Workflows()
	ctx := context.Background()
	report, err := workflows.TestCandidate(ctx, &sdk.WorkflowCandidateTestRequest{ProjectFiles: files})
	if err != nil {
		panic(err)
	}
	encoded, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(report)
	if err != nil {
		panic(err)
	}
	fmt.Println("Test report:", string(encoded))
	if report.GetStatus() != "completed" {
		panic("Repair the project before submitting a candidate")
	}
	candidate, err := workflows.SubmitCandidate(ctx, &sdk.WorkflowCandidateSubmitRequest{ProjectFiles: files})
	if err != nil {
		panic(err)
	}
	fmt.Println("Compiled:", candidate.GetOk(), "Test status:", candidate.GetTestStatus())
	fmt.Println("Candidate:", candidate.GetCandidateId())
	if !candidate.GetOk() || candidate.GetTestStatus() != "passed" {
		panic("Inspect candidate diagnostics and current test evidence")
	}
	fmt.Println("Ready for review; no acceptance or deployment was performed.")
}
```

::::

:::::

Only authored files under `workflow`, `operators`, and `tests` are sent; platform-generated test evidence and reference files are maintained by the server. Successful compilation, a finished test request (`completed`), and a passed candidate (`passed`) represent distinct stages; rerun tests and submit a fresh snapshot whenever project files change.

(sdk-ai-studio-workflow-project-review)=
<span id="读取候选产物并交由用户审阅"></span>

## Read the candidate artifact for user review

Candidate submission returns the current candidate identifier and test projection without accepting or deploying the workflow. Wait for the owning authoring task to finish and emit its candidate artifact, then read the task ID, artifact ID, and confirmation proposal ID from that artifact (downstream acceptance uses the artifact ID, whereas `candidate_id` identifies the compiled snapshot).

A single test case is for targeted diagnosis only; inspect the full test suite, node execution coverage, and candidate test status together before presenting the candidate for approval. When tests use scratch databases, volumes, or tables, prepare, inspect, or reset the test scratch scope by task ID through the workflow service.

(sdk-ai-studio-workflow-project-next)=
<span id="下一步"></span>

## Next steps

- [Confirm and Publish Workflow Proposals](确认并发布工作流方案.md#sdk-ai-studio-workflow-proposal-publish)
- [Inspect and Restore Workflow History](查看和恢复工作流历史.md#sdk-ai-studio-workflow-history-list)
