Files
pipelines/internal/server/session_export_repair_test.go
T
alan 22801a9b06 fix(stage): align session export render cap with artifact bound
Six computed Flutter runs stopped at the export handoff gate because the
rendered session.html cap was 2 MiB while their complete sessions (well inside
the 8 MiB source read bound) rendered between 2.25 and 4.28 MiB once html
escaping and the readable projection duplicated native text.

Raise SessionExportFileLimit to 8 MiB, the server's existing per-artifact file
bound, so a complete export is still listed and served. Normal export
verification, versioned repair and the handoff gate keep using the single
shared constant. The source read bound is unchanged, and an over-cap render is
still visibly truncated and recorded partial.

Add focused regressions for a complete export above the old cap, an over-new-cap
file rejected as partial, repair above the old cap leaving original evidence
untouched, the gate accepting the larger repair, and the constant staying inside
the artifact file bound. Update the artifact, handoff-gate and operations docs
and record the diagnosis in docs/notes/session-export-render-cap.md.
2026-10-21 15:26:29 +01:00

214 lines
8.4 KiB
Go

package server
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/cli"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func TestRuntimeSessionExportRepairPreservesOriginalAndUsesRecordedOwner(t *testing.T) {
h, s, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
return stage.SessionExportResult{}, errors.New("export read failed")
})
// The synthetic executor does not own a real agent to settle. Model real
// runtime cleanup explicitly before exercising the settled-only repair gate.
if err := s.ConfirmRecoveredSession(context.Background(), pipeline.SessionOwner{RunID: id, ID: "ses_run"}); err != nil {
t.Fatal(err)
}
original, err := s.GetRun(context.Background(), id)
if err != nil {
t.Fatal(err)
}
before, _ := json.Marshal(original.Steps[0].SessionExport)
if original.Steps[0].SessionExport.Status != "failed" {
t.Fatalf("failure not durable: %+v", original.Steps[0].SessionExport)
}
owner, err := s.RepairSessionOwner(context.Background(), id, 1)
if err != nil {
t.Fatal(err)
}
if owner.ID != "ses_run" || owner.Backend != "v2" || owner.Directory != original.Workspace {
t.Fatalf("owner changed: %+v", owner)
}
public := filepath.Join(h.runner.artifactsRoot, "1", "public")
if err := os.MkdirAll(public, 0700); err != nil {
t.Fatal(err)
}
old := filepath.Join(public, "session.html")
if err := os.WriteFile(old, []byte("historical evidence"), 0600); err != nil {
t.Fatal(err)
}
// First repair also fails: it must remain durable without losing original.
failed, err := h.runner.repairSessionExport(context.Background(), id, 1)
if err != nil {
t.Fatal(err)
}
if len(failed.Steps[0].SessionExportRepairs) != 1 || failed.Steps[0].SessionExportRepairs[0].Status != "failed" {
t.Fatalf("repair failure disappeared: %+v", failed.Steps)
}
// Restore readback availability; this is a fake native export CLI, not a
// model stage, no generation/resumption/definition mutation is performed.
// A full user-artifact inventory must not consume mandatory audit capacity.
remaining := int64(maxArtifactTotalBytes)
for _, file := range original.Steps[0].Artifacts {
remaining -= file.SizeBytes
}
slots := maxArtifactFiles - len(original.Steps[0].Artifacts)
for i := 0; i < slots; i++ {
size := remaining / int64(slots-i)
remaining -= size
if err := s.RecordDeliverable(context.Background(), id, 1, protocol.StageArtifact{Name: fmt.Sprintf("private/capture-%03d.png", i), SizeBytes: size}); err != nil {
t.Fatal(err)
}
}
sessionExportCLI(t)
h.runner.exportSession = nil
repaired, err := h.runner.repairSessionExport(context.Background(), id, 1)
if err != nil {
t.Fatal(err)
}
if repaired.Status != original.Status || len(repaired.Steps[0].SessionExportRepairs) != 2 {
t.Fatalf("repair changed run outcome: %+v", repaired)
}
latest := repaired.Steps[0].SessionExportRepairs[1]
if latest.Status != "complete" || latest.Messages != 2 || latest.SessionID != owner.ID || latest.Backend != owner.Backend || !strings.HasPrefix(latest.HTML, "session-repair-1-") {
t.Fatalf("repair not recorded: %+v", latest)
}
after, _ := json.Marshal(repaired.Steps[0].SessionExport)
if string(before) != string(after) {
t.Fatal("original evidence overwritten")
}
body, _ := os.ReadFile(old)
if string(body) != "historical evidence" {
t.Fatal("historical export overwritten")
}
body, err = os.ReadFile(filepath.Join(h.runner.artifactsRoot, "1", "stages", "01-"+repaired.Steps[0].Stage, latest.HTML))
if err != nil || len(body) == 0 {
t.Fatalf("repair file missing: %v", err)
}
if _, ok := artifactNamed(repaired.Steps[0].Artifacts, latest.HTML); !ok {
t.Fatal("repaired export not discoverable")
}
// A second successful attempt is a new version, never an overwrite.
again, err := h.runner.repairSessionExport(context.Background(), id, 1)
if err != nil {
t.Fatal(err)
}
if again.Steps[0].SessionExportRepairs[2].HTML == latest.HTML {
t.Fatal("repair reused filename")
}
}
// TestRuntimeSessionExportRepairAcceptsAboveTheOldRenderCap proves a versioned
// repair uses the same larger bound as a normal export while leaving the
// original recorded evidence untouched.
func TestRuntimeSessionExportRepairAcceptsAboveTheOldRenderCap(t *testing.T) {
h, s, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
return stage.SessionExportResult{}, errors.New("initial export unavailable")
})
if err := s.ConfirmRecoveredSession(context.Background(), pipeline.SessionOwner{RunID: id, ID: "ses_run"}); err != nil {
t.Fatal(err)
}
original, err := s.GetRun(context.Background(), id)
if err != nil {
t.Fatal(err)
}
before, _ := json.Marshal(original.Steps[0].SessionExport)
size := int64(2<<20) + 4096
h.runner.exportSession = func(_ context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) {
if err := os.MkdirAll(req.ArtifactsDir, 0700); err != nil {
return stage.SessionExportResult{}, err
}
f, err := os.Create(filepath.Join(req.ArtifactsDir, req.FileName))
if err != nil {
return stage.SessionExportResult{}, err
}
if err := f.Truncate(size); err != nil {
f.Close()
return stage.SessionExportResult{}, err
}
if err := f.Close(); err != nil {
return stage.SessionExportResult{}, err
}
return stage.SessionExportResult{Source: "native_export", HTML: req.FileName, HTMLBytes: size, Messages: 2}, nil
}
repaired, err := h.runner.repairSessionExport(context.Background(), id, 1)
if err != nil {
t.Fatal(err)
}
latest := repaired.Steps[0].SessionExportRepairs[0]
if latest.Status != "complete" || latest.HTMLBytes != size || latest.HTML == "" {
t.Fatalf("repair above the old cap was not complete: %+v", latest)
}
after, _ := json.Marshal(repaired.Steps[0].SessionExport)
if string(before) != string(after) {
t.Fatal("repair above the old cap overwrote original evidence")
}
info, err := os.Stat(filepath.Join(h.runner.artifactsRoot, "1", "stages", "01-"+repaired.Steps[0].Stage, latest.HTML))
if err != nil || info.Size() != size {
t.Fatalf("repair file missing or resized: %v %+v", err, info)
}
}
func TestRuntimeRepairRejectsUnrecordedAndActiveVisits(t *testing.T) {
h, _, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
return stage.SessionExportResult{}, errors.New("unavailable")
})
for _, sequence := range []int{0, 2} {
if _, err := h.runner.repairSessionExport(context.Background(), id, sequence); err == nil {
t.Fatalf("invalid visit %d accepted", sequence)
}
}
// The shared fixture now confirms executor cleanup, as the runtime should.
// Explicitly model an in-flight executor for the active-visit repair case.
h.runner.mu.Lock()
h.runner.active[id] = activeRun{cancel: func() {}}
h.runner.mu.Unlock()
if _, err := h.runner.repairSessionExport(context.Background(), id, 1); err == nil {
t.Fatal("active visit accepted for export repair")
}
h.runner.mu.Lock()
delete(h.runner.active, id)
h.runner.mu.Unlock()
}
func TestCLIRepairSessionExportUsesRuntimeProtocol(t *testing.T) {
t.Setenv("PIPELINES_HARNESS_CONFIG", filepath.Join(t.TempDir(), "harnesses.json"))
h, s, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
return stage.SessionExportResult{}, errors.New("fixture readback unavailable")
})
if err := s.ConfirmRecoveredSession(context.Background(), pipeline.SessionOwner{RunID: id, ID: "ses_run"}); err != nil {
t.Fatal(err)
}
sessionExportCLI(t)
h.runner.exportSession = nil
server := httptest.NewServer(h)
defer server.Close()
var out bytes.Buffer
app := cli.App{Out: &out, Err: &out, In: strings.NewReader("")}
err := app.Run(context.Background(), []string{"--url", "ws" + strings.TrimPrefix(server.URL, "http") + "/connect", "repair-session-export", "1", "1", "--json"})
if err != nil {
t.Fatalf("repair command failed: %v %s", err, out.String())
}
var evidence struct {
Status string `json:"status"`
SessionID string `json:"session_id"`
HTML string `json:"html"`
}
if err := json.Unmarshal(out.Bytes(), &evidence); err != nil || evidence.Status != "complete" || evidence.SessionID != "ses_run" || !strings.HasPrefix(evidence.HTML, "session-repair-1-") {
t.Fatalf("wrong repair reply: %+v %v %s", evidence, err, out.String())
}
}