Files
pipelines/internal/server/session_export_test.go
T
alan 3bfb3d6b44 Fix decide-after-finish refusal and run size loop data race
A run stays in r.active after finishRunState persists its terminal status
until its goroutine finishes notifying, so a decision in that window was
refused as "already active". decide now refuses only runs whose terminal
state is not yet durable; a finished run gets ResolveDecision's
already-decided / not-waiting answer, and an executing run is still refused.

Tests overwrote runner.artifactsRoot after Handler/newRunner had started
background goroutines (sizeLoop, session export jobs) that read it. The
root is now fixed at construction through newRunnerAt, which
HandlerWithOptions uses for Options.ArtifactsRoot, and tests configure it
there instead of mutating the field afterwards.
2026-11-01 18:58:14 +00:00

250 lines
9.4 KiB
Go

package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// sessionExportBody is a minimal native export envelope with a user and an
// assistant turn, used by the fake CLI below.
const sessionExportBody = `{"info":{"id":"ses_run"},"messages":[` +
`{"info":{"id":"m1","role":"user"},"text":"do the task"},` +
`{"info":{"id":"m2","role":"assistant"},"parts":[` +
`{"type":"text","text":"done"},` +
`{"type":"tool","name":"shell","state":{"status":"completed","input":{"cmd":"ls"},"content":[{"type":"text","text":"output here"}]}}]}]}`
// sessionExportCLI isolates both the authenticated V2 API and legacy CLI.
// Neither export transport may fall through to the operator's real service.
func sessionExportCLI(t *testing.T) {
t.Helper()
path := filepath.Join(t.TempDir(), "opencode")
script := "#!/bin/sh\n" +
"[ \"$1\" = export ] && shift || { [ \"$1\" = session ] && [ \"$2\" = export ] && shift 2 || exit 8; }\n" +
"[ \"$1\" = ses_run ] || exit 9\n" +
"cat <<'EOF'\n" + sessionExportBody + "\nEOF\n"
if err := os.WriteFile(path, []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_OPENCODE", path)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, password, ok := r.BasicAuth()
if !ok || user != "opencode" || password != "fixture-password" {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != "GET" || r.URL.Path != "/api/experimental/session/ses_run/export" || r.URL.Query().Get("sanitize") != "false" {
t.Errorf("unexpected export operation: %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"data":`+sessionExportBody+`}`)
}))
t.Cleanup(srv.Close)
localExportService(t, srv.URL)
t.Setenv(opencode.EndpointEnvKey, "http://127.0.0.1:1")
t.Setenv(opencode.EndpointPasswordFileEnvKey, "")
t.Setenv(opencode.EndpointUsernameEnvKey, "")
}
func localExportService(t *testing.T, endpoint string) {
t.Helper()
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
state := t.TempDir()
t.Setenv(opencode.OpenCodeServiceStateEnvKey, state)
if err := os.Mkdir(filepath.Join(state, "opencode"), 0700); err != nil {
t.Fatal(err)
}
data, _ := json.Marshal(map[string]string{"url": endpoint, "password": "fixture-password"})
if err := os.WriteFile(filepath.Join(state, "opencode", "service.json"), data, 0600); err != nil {
t.Fatal(err)
}
}
// sessionExportRunner runs one stage that records a session for the run, so the
// runner's post-stage export has an owner to read. The export seam is supplied by
// the caller; ready gates the stage until the test has captured the run id.
func sessionExportRunner(t *testing.T, backend string, seam func(stage.SessionExportRequest) (stage.SessionExportResult, error)) (*runHandler, *pipeline.Store, int64) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
store, err := pipeline.Open(filepath.Join(t.TempDir(), "session.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { store.Close() })
if _, err := store.Submit(ctx, "session-export", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, err := store.List(ctx)
if err != nil {
t.Fatal(err)
}
handler := HandlerWithOptions(ctx, Options{ArtifactsRoot: t.TempDir()}, store).(*runHandler)
t.Cleanup(func() { cancel(); WaitRuns(handler) })
if seam != nil {
handler.runner.exportSession = func(_ context.Context, request stage.SessionExportRequest) (stage.SessionExportResult, error) {
return seam(request)
}
}
ready := make(chan struct{})
var runID int64
handler.runner.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
<-ready
if err := handler.runner.store.RunSession(ctx, runID, 1, "ses_run", false, backend, ""); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
run, err := handler.runner.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "session", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
runID = run.ID
close(ready)
handler.runner.wg.Wait()
return handler, store, run.ID
}
// TestRunnerExportsTheHTMLSessionIntoArtifactsAndServesIt proves the real export
// path writes the one html session file into the step's artifacts directory,
// lists it with an artifact URL and serves it 200, without changing the step's
// status, outcome or target, and produces no legacy session.md.
func TestRunnerExportsTheHTMLSessionIntoArtifactsAndServesIt(t *testing.T) {
sessionExportCLI(t)
handler, store, runID := sessionExportRunner(t, "v2", nil)
detail, err := store.GetRun(context.Background(), runID)
if err != nil {
t.Fatal(err)
}
if detail.Status != "succeeded" || len(detail.Steps) != 1 {
t.Fatalf("unexpected run: %+v", detail)
}
step := detail.Steps[0]
if step.Status != "completed" || step.Outcome != "success" {
t.Fatalf("export changed the stage result: %+v", step)
}
if len(step.Transcript) > 32<<10 || strings.Contains(step.Transcript, "do the task") || strings.Contains(step.Transcript, "session.md") {
t.Fatalf("transcript was changed by the export: %q", step.Transcript)
}
if step.SessionExport == nil || step.SessionExport.SessionID != "ses_run" || step.SessionExport.Source != "native_export" {
t.Fatalf("export evidence missing: %+v", step.SessionExport)
}
if step.SessionExport.HTML != "session.html" || step.SessionExport.Messages != 2 || step.SessionExport.HTMLBytes == 0 {
t.Fatalf("export evidence wrong: %+v", step.SessionExport)
}
if _, ok := artifactNamed(step.Artifacts, stage.SessionMarkdownFile); ok {
t.Fatalf("legacy session.md must not be produced: %+v", step.Artifacts)
}
artifact, ok := artifactNamed(step.Artifacts, "session.html")
if !ok {
t.Fatalf("session.html not in the artifact listing: %+v", step.Artifacts)
}
wantURL := fmt.Sprintf("/artifacts/%d/1/session.html", runID)
if artifact.URL != wantURL || artifact.SizeBytes == 0 {
t.Fatalf("session.html listing wrong: %+v", artifact)
}
srv := httptest.NewServer(handler)
defer srv.Close()
resp, err := http.Get(srv.URL + wantURL)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusOK || len(body) == 0 {
t.Fatalf("session.html served %d (%d bytes)", resp.StatusCode, len(body))
}
if contentType := resp.Header.Get("Content-Type"); !strings.HasPrefix(contentType, "text/html") {
t.Fatalf("session.html content type = %q", contentType)
}
if !strings.Contains(string(body), "output here") {
t.Fatal("served html missing tool output")
}
}
// TestRunnerSessionExportFailureTruncationAndUnavailableHarness proves the three
// non-success exports block success without replacing the completed computation.
func TestRunnerSessionExportFailureTruncationAndUnavailableHarness(t *testing.T) {
cases := []struct {
name string
backend string
seam func(stage.SessionExportRequest) (stage.SessionExportResult, error)
wantSrc string
wantDiag string
wantTrunc bool
}{
{
name: "failure",
backend: "v2",
seam: func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
return stage.SessionExportResult{}, errors.New("native session export failed")
},
wantSrc: "native_export",
wantDiag: "native session export failed",
},
{
name: "truncated",
backend: "v2",
seam: func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
return stage.SessionExportResult{Source: "native_export", Truncated: true, Messages: 3}, nil
},
wantSrc: "native_export",
wantTrunc: true,
},
{
name: "unavailable",
backend: "pi",
seam: nil,
wantSrc: "unavailable",
wantDiag: "harness has no native export path",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
handler, store, runID := sessionExportRunner(t, tc.backend, tc.seam)
detail, err := store.GetRun(context.Background(), runID)
if err != nil {
t.Fatal(err)
}
if detail.Status != "waiting" || detail.ExportPendingSequence != 1 || detail.FinishedAt != "" || detail.Output["summary"] != "done" {
t.Fatalf("export gate did not preserve and block computation: %+v", detail)
}
step := detail.Steps[0]
if step.Status != "completed" || step.Outcome != "success" {
t.Fatalf("export changed the stage result: %+v", step)
}
if step.SessionExport == nil || step.SessionExport.Source != tc.wantSrc {
t.Fatalf("export evidence wrong: %+v", step.SessionExport)
}
if tc.wantDiag != "" && !strings.Contains(step.SessionExport.Diagnostic, tc.wantDiag) {
t.Fatalf("diagnostic %q missing %q", step.SessionExport.Diagnostic, tc.wantDiag)
}
if step.SessionExport.Truncated != tc.wantTrunc {
t.Fatalf("truncated = %v, want %v", step.SessionExport.Truncated, tc.wantTrunc)
}
if tc.wantSrc == "unavailable" {
if artifacts, _, _ := handler.runner.scanArtifacts(runID, 1, filepath.Join(handler.runner.artifactsRoot, fmt.Sprint(runID), "1")); len(artifacts) != 0 {
t.Fatalf("unavailable harness wrote files: %+v", artifacts)
}
}
})
}
}